org-element.el 314 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2021 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 'ring)
  53. (require 'backtrace)
  54. (require 'cl-lib)
  55. (require 'ol)
  56. (require 'org)
  57. (require 'org-persist)
  58. (require 'org-compat)
  59. (require 'org-entities)
  60. (require 'org-footnote)
  61. (require 'org-list)
  62. (require 'org-macs)
  63. (require 'org-table)
  64. (declare-function org-at-heading-p "org" (&optional _))
  65. (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
  66. (declare-function org-escape-code-in-string "org-src" (s))
  67. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  68. (declare-function org-macro-extract-arguments "org-macro" (s))
  69. (declare-function org-reduced-level "org" (l))
  70. (declare-function org-unescape-code-in-string "org-src" (s))
  71. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  72. (declare-function outline-next-heading "outline" ())
  73. (declare-function outline-previous-heading "outline" ())
  74. (defvar org-archive-tag)
  75. (defvar org-clock-line-re)
  76. (defvar org-closed-string)
  77. (defvar org-comment-string)
  78. (defvar org-complex-heading-regexp)
  79. (defvar org-dblock-start-re)
  80. (defvar org-deadline-string)
  81. (defvar org-done-keywords)
  82. (defvar org-drawer-regexp)
  83. (defvar org-edit-src-content-indentation)
  84. (defvar org-emph-re)
  85. (defvar org-emphasis-regexp-components)
  86. (defvar org-keyword-time-not-clock-regexp)
  87. (defvar org-match-substring-regexp)
  88. (defvar org-odd-levels-only)
  89. (defvar org-outline-regexp-bol)
  90. (defvar org-planning-line-re)
  91. (defvar org-property-drawer-re)
  92. (defvar org-property-format)
  93. (defvar org-property-re)
  94. (defvar org-scheduled-string)
  95. (defvar org-src-preserve-indentation)
  96. (defvar org-tags-column)
  97. (defvar org-time-stamp-formats)
  98. (defvar org-todo-regexp)
  99. (defvar org-ts-regexp-both)
  100. (defvar org-verbatim-re)
  101. ;;; Definitions And Rules
  102. ;;
  103. ;; Define elements, greater elements and specify recursive objects,
  104. ;; along with the affiliated keywords recognized. Also set up
  105. ;; restrictions on recursive objects combinations.
  106. ;;
  107. ;; `org-element-update-syntax' builds proper syntax regexps according
  108. ;; to current setup.
  109. (defconst org-element-citation-key-re
  110. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  111. "Regexp matching a citation key.
  112. Key is located in match group 1.")
  113. (defconst org-element-citation-prefix-re
  114. (rx "[cite"
  115. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  116. ":"
  117. (zero-or-more (any "\t\n ")))
  118. "Regexp matching a citation prefix.
  119. Style, if any, is located in match group 1.")
  120. (defvar org-element-paragraph-separate nil
  121. "Regexp to separate paragraphs in an Org buffer.
  122. In the case of lines starting with \"#\" and \":\", this regexp
  123. is not sufficient to know if point is at a paragraph ending. See
  124. `org-element-paragraph-parser' for more information.")
  125. (defvar org-element--object-regexp nil
  126. "Regexp possibly matching the beginning of an object.
  127. This regexp allows false positives. Dedicated parser (e.g.,
  128. `org-export-bold-parser') will take care of further filtering.
  129. Radio links are not matched by this regexp, as they are treated
  130. specially in `org-element--object-lex'.")
  131. (defun org-element--set-regexps ()
  132. "Build variable syntax regexps."
  133. (setq org-element-paragraph-separate
  134. (concat "^\\(?:"
  135. ;; Headlines, inlinetasks.
  136. "\\*+ " "\\|"
  137. ;; Footnote definitions.
  138. "\\[fn:[-_[:word:]]+\\]" "\\|"
  139. ;; Diary sexps.
  140. "%%(" "\\|"
  141. "[ \t]*\\(?:"
  142. ;; Empty lines.
  143. "$" "\\|"
  144. ;; Tables (any type).
  145. "|" "\\|"
  146. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  147. ;; Comments, keyword-like or block-like constructs.
  148. ;; Blocks and keywords with dual values need to be
  149. ;; double-checked.
  150. "#\\(?: \\|$\\|\\+\\(?:"
  151. "BEGIN_\\S-+" "\\|"
  152. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  153. "\\|"
  154. ;; Drawers (any type) and fixed-width areas. Drawers
  155. ;; need to be double-checked.
  156. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  157. ;; Horizontal rules.
  158. "-\\{5,\\}[ \t]*$" "\\|"
  159. ;; LaTeX environments.
  160. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  161. ;; Clock lines.
  162. "CLOCK:" "\\|"
  163. ;; Lists.
  164. (let ((term (pcase org-plain-list-ordered-item-terminator
  165. (?\) ")") (?. "\\.") (_ "[.)]")))
  166. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  167. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  168. "\\(?:[ \t]\\|$\\)"))
  169. "\\)\\)")
  170. org-element--object-regexp
  171. (mapconcat #'identity
  172. (let ((link-types (regexp-opt (org-link-types))))
  173. (list
  174. ;; Sub/superscript.
  175. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  176. ;; Bold, code, italic, strike-through, underline
  177. ;; and verbatim.
  178. (concat "[*~=+_/]"
  179. (format "[^%s]"
  180. (nth 2 org-emphasis-regexp-components)))
  181. ;; Plain links.
  182. (concat "\\<" link-types ":")
  183. ;; Objects starting with "[": citations,
  184. ;; footnote reference, statistics cookie,
  185. ;; timestamp (inactive) and regular link.
  186. (format "\\[\\(?:%s\\)"
  187. (mapconcat
  188. #'identity
  189. (list "cite[:/]"
  190. "fn:"
  191. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  192. "\\[")
  193. "\\|"))
  194. ;; Objects starting with "@": export snippets.
  195. "@@"
  196. ;; Objects starting with "{": macro.
  197. "{{{"
  198. ;; Objects starting with "<" : timestamp
  199. ;; (active, diary), target, radio target and
  200. ;; angular links.
  201. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  202. ;; Objects starting with "$": latex fragment.
  203. "\\$"
  204. ;; Objects starting with "\": line break,
  205. ;; entity, latex fragment.
  206. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  207. ;; Objects starting with raw text: inline Babel
  208. ;; source block, inline Babel call.
  209. "\\(?:call\\|src\\)_"))
  210. "\\|")))
  211. (org-element--set-regexps)
  212. (defmacro org-element-with-disabled-cache (&rest body)
  213. "Run BODY without active org-element-cache."
  214. (declare (debug (form body)) (indent 1))
  215. `(cl-letf (((symbol-function #'org-element--cache-active-p) (lambda (&rest _) nil)))
  216. ,@body))
  217. ;;;###autoload
  218. (defun org-element-update-syntax ()
  219. "Update parser internals."
  220. (interactive)
  221. (org-element--set-regexps)
  222. (org-element-cache-reset 'all))
  223. (defconst org-element-all-elements
  224. '(babel-call center-block clock comment comment-block diary-sexp drawer
  225. dynamic-block example-block export-block fixed-width
  226. footnote-definition headline horizontal-rule inlinetask item
  227. keyword latex-environment node-property paragraph plain-list
  228. planning property-drawer quote-block section
  229. special-block src-block table table-row verse-block)
  230. "Complete list of element types.")
  231. (defconst org-element-greater-elements
  232. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  233. item plain-list property-drawer quote-block section
  234. special-block table org-data)
  235. "List of recursive element types aka Greater Elements.")
  236. (defconst org-element-all-objects
  237. '(bold citation citation-reference code entity export-snippet
  238. footnote-reference inline-babel-call inline-src-block italic line-break
  239. latex-fragment link macro radio-target statistics-cookie strike-through
  240. subscript superscript table-cell target timestamp underline verbatim)
  241. "Complete list of object types.")
  242. (defconst org-element-recursive-objects
  243. '(bold citation footnote-reference italic link subscript radio-target
  244. strike-through superscript table-cell underline)
  245. "List of recursive object types.")
  246. (defconst org-element-object-containers
  247. (append org-element-recursive-objects '(paragraph table-row verse-block))
  248. "List of object or element types that can directly contain objects.")
  249. (defconst org-element-affiliated-keywords
  250. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  251. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  252. "List of affiliated keywords as strings.
  253. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  254. are affiliated keywords and need not to be in this list.")
  255. (defconst org-element-keyword-translation-alist
  256. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  257. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  258. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  259. "Alist of usual translations for keywords.
  260. The key is the old name and the value the new one. The property
  261. holding their value will be named after the translated name.")
  262. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  263. "List of affiliated keywords that can occur more than once in an element.
  264. Their value will be consed into a list of strings, which will be
  265. returned as the value of the property.
  266. This list is checked after translations have been applied. See
  267. `org-element-keyword-translation-alist'.
  268. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  269. allow multiple occurrences and need not to be in this list.")
  270. (defconst org-element-parsed-keywords '("CAPTION")
  271. "List of affiliated keywords whose value can be parsed.
  272. Their value will be stored as a secondary string: a list of
  273. strings and objects.
  274. This list is checked after translations have been applied. See
  275. `org-element-keyword-translation-alist'.")
  276. (defconst org-element--parsed-properties-alist
  277. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  278. org-element-parsed-keywords)
  279. "Alist of parsed keywords and associated properties.
  280. This is generated from `org-element-parsed-keywords', which
  281. see.")
  282. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  283. "List of affiliated keywords which can have a secondary value.
  284. In Org syntax, they can be written with optional square brackets
  285. before the colons. For example, RESULTS keyword can be
  286. associated to a hash value with the following:
  287. #+RESULTS[hash-string]: some-source
  288. This list is checked after translations have been applied. See
  289. `org-element-keyword-translation-alist'.")
  290. (defconst org-element--affiliated-re
  291. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  292. (concat
  293. ;; Dual affiliated keywords.
  294. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  295. (regexp-opt org-element-dual-keywords))
  296. "\\|"
  297. ;; Regular affiliated keywords.
  298. (format "\\(?1:%s\\)"
  299. (regexp-opt
  300. (cl-remove-if
  301. (lambda (k) (member k org-element-dual-keywords))
  302. org-element-affiliated-keywords)))
  303. "\\|"
  304. ;; Export attributes.
  305. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  306. "Regexp matching any affiliated keyword.
  307. Keyword name is put in match group 1. Moreover, if keyword
  308. belongs to `org-element-dual-keywords', put the dual value in
  309. match group 2.
  310. Don't modify it, set `org-element-affiliated-keywords' instead.")
  311. (defconst org-element-object-restrictions
  312. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  313. subscript superscript underline verbatim))
  314. (standard-set
  315. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  316. (standard-set-no-line-break (remq 'line-break standard-set)))
  317. `((bold ,@standard-set)
  318. (citation citation-reference)
  319. (citation-reference ,@minimal-set)
  320. (footnote-reference ,@standard-set)
  321. (headline ,@standard-set-no-line-break)
  322. (inlinetask ,@standard-set-no-line-break)
  323. (italic ,@standard-set)
  324. (item ,@standard-set-no-line-break)
  325. (keyword ,@(remq 'footnote-reference standard-set))
  326. ;; Ignore all links in a link description. Also ignore
  327. ;; radio-targets and line breaks.
  328. (link export-snippet inline-babel-call inline-src-block macro
  329. statistics-cookie ,@minimal-set)
  330. (paragraph ,@standard-set)
  331. ;; Remove any variable object from radio target as it would
  332. ;; prevent it from being properly recognized.
  333. (radio-target ,@minimal-set)
  334. (strike-through ,@standard-set)
  335. (subscript ,@standard-set)
  336. (superscript ,@standard-set)
  337. ;; Ignore inline babel call and inline source block as formulas
  338. ;; are possible. Also ignore line breaks and statistics
  339. ;; cookies.
  340. (table-cell citation export-snippet footnote-reference link macro
  341. radio-target target timestamp ,@minimal-set)
  342. (table-row table-cell)
  343. (underline ,@standard-set)
  344. (verse-block ,@standard-set)))
  345. "Alist of objects restrictions.
  346. key is an element or object type containing objects and value is
  347. a list of types that can be contained within an element or object
  348. of such type.
  349. This alist also applies to secondary string. For example, an
  350. `headline' type element doesn't directly contain objects, but
  351. still has an entry since one of its properties (`:title') does.")
  352. (defconst org-element-secondary-value-alist
  353. '((citation :prefix :suffix)
  354. (headline :title)
  355. (inlinetask :title)
  356. (item :tag)
  357. (citation-reference :prefix :suffix))
  358. "Alist between element types and locations of secondary values.")
  359. (defconst org-element--pair-round-table
  360. (let ((table (make-syntax-table)))
  361. (modify-syntax-entry ?\( "()" table)
  362. (modify-syntax-entry ?\) ")(" table)
  363. (dolist (char '(?\{ ?\} ?\[ ?\] ?\< ?\>) table)
  364. (modify-syntax-entry char " " table)))
  365. "Table used internally to pair only round brackets.
  366. Other brackets are treated as spaces.")
  367. (defconst org-element--pair-square-table
  368. (let ((table (make-syntax-table)))
  369. (modify-syntax-entry ?\[ "(]" table)
  370. (modify-syntax-entry ?\] ")[" table)
  371. (dolist (char '(?\{ ?\} ?\( ?\) ?\< ?\>) table)
  372. (modify-syntax-entry char " " table)))
  373. "Table used internally to pair only square brackets.
  374. Other brackets are treated as spaces.")
  375. (defconst org-element--pair-curly-table
  376. (let ((table (make-syntax-table)))
  377. (modify-syntax-entry ?\{ "(}" table)
  378. (modify-syntax-entry ?\} "){" table)
  379. (dolist (char '(?\[ ?\] ?\( ?\) ?\< ?\>) table)
  380. (modify-syntax-entry char " " table)))
  381. "Table used internally to pair only curly brackets.
  382. Other brackets are treated as spaces.")
  383. (defun org-element--parse-paired-brackets (char)
  384. "Parse paired brackets at point.
  385. CHAR is the opening bracket to consider, as a character. Return
  386. contents between brackets, as a string, or nil. Also move point
  387. past the brackets."
  388. (when (eq char (char-after))
  389. (let ((syntax-table (pcase char
  390. (?\{ org-element--pair-curly-table)
  391. (?\[ org-element--pair-square-table)
  392. (?\( org-element--pair-round-table)
  393. (_ nil)))
  394. (pos (point)))
  395. (when syntax-table
  396. (with-syntax-table syntax-table
  397. (let ((end (ignore-errors (scan-lists pos 1 0))))
  398. (when end
  399. (goto-char end)
  400. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  401. ;;; Accessors and Setters
  402. ;;
  403. ;; Provide four accessors: `org-element-type', `org-element-property'
  404. ;; `org-element-contents' and `org-element-restriction'.
  405. ;;
  406. ;; Setter functions allow modification of elements by side effect.
  407. ;; There is `org-element-put-property', `org-element-set-contents'.
  408. ;; These low-level functions are useful to build a parse tree.
  409. ;;
  410. ;; `org-element-adopt-elements', `org-element-set-element',
  411. ;; `org-element-extract-element' and `org-element-insert-before' are
  412. ;; high-level functions useful to modify a parse tree.
  413. ;;
  414. ;; `org-element-secondary-p' is a predicate used to know if a given
  415. ;; object belongs to a secondary string. `org-element-class' tells if
  416. ;; some parsed data is an element or an object, handling pseudo
  417. ;; elements and objects. `org-element-copy' returns an element or
  418. ;; object, stripping its parent property in the process.
  419. (defsubst org-element-type (element)
  420. "Return type of ELEMENT.
  421. The function returns the type of the element or object provided.
  422. It can also return the following special value:
  423. `plain-text' for a string
  424. `org-data' for a complete document
  425. nil in any other case."
  426. (cond
  427. ((not (consp element)) (and (stringp element) 'plain-text))
  428. ((symbolp (car element)) (car element))))
  429. (defsubst org-element-property (property element)
  430. "Extract the value from the PROPERTY of an ELEMENT."
  431. (if (stringp element) (get-text-property 0 property element)
  432. (plist-get (nth 1 element) property)))
  433. (defsubst org-element-contents (element)
  434. "Extract contents from an ELEMENT."
  435. (cond ((not (consp element)) nil)
  436. ((symbolp (car element)) (nthcdr 2 element))
  437. (t element)))
  438. (defsubst org-element-restriction (element)
  439. "Return restriction associated to ELEMENT.
  440. ELEMENT can be an element, an object or a symbol representing an
  441. element or object type."
  442. (cdr (assq (if (symbolp element) element (org-element-type element))
  443. org-element-object-restrictions)))
  444. (defsubst org-element-put-property (element property value)
  445. "In ELEMENT set PROPERTY to VALUE.
  446. Return modified element."
  447. (if (stringp element) (org-add-props element nil property value)
  448. (setcar (cdr element) (plist-put (nth 1 element) property value))
  449. element))
  450. (defsubst org-element-set-contents (element &rest contents)
  451. "Set ELEMENT's contents to CONTENTS.
  452. Return ELEMENT."
  453. (cond ((null element) contents)
  454. ((not (symbolp (car element))) contents)
  455. ((cdr element) (setcdr (cdr element) contents) element)
  456. (t (nconc element contents))))
  457. (defun org-element-secondary-p (object)
  458. "Non-nil when OBJECT directly belongs to a secondary string.
  459. Return value is the property name, as a keyword, or nil."
  460. (let* ((parent (org-element-property :parent object))
  461. (properties (cdr (assq (org-element-type parent)
  462. org-element-secondary-value-alist))))
  463. (catch 'exit
  464. (dolist (p properties)
  465. (and (memq object (org-element-property p parent))
  466. (throw 'exit p))))))
  467. (defsubst org-element-class (datum &optional parent)
  468. "Return class for ELEMENT, as a symbol.
  469. Class is either `element' or `object'. Optional argument PARENT
  470. is the element or object containing DATUM. It defaults to the
  471. value of DATUM `:parent' property."
  472. (let ((type (org-element-type datum))
  473. (parent (or parent (org-element-property :parent datum))))
  474. (cond
  475. ;; Trivial cases.
  476. ((memq type org-element-all-objects) 'object)
  477. ((memq type org-element-all-elements) 'element)
  478. ;; Special cases.
  479. ((eq type 'org-data) 'element)
  480. ((eq type 'plain-text) 'object)
  481. ((not type) 'object)
  482. ;; Pseudo object or elements. Make a guess about its class.
  483. ;; Basically a pseudo object is contained within another object,
  484. ;; a secondary string or a container element.
  485. ((not parent) 'element)
  486. (t
  487. (let ((parent-type (org-element-type parent)))
  488. (cond ((not parent-type) 'object)
  489. ((memq parent-type org-element-object-containers) 'object)
  490. ((org-element-secondary-p datum) 'object)
  491. (t 'element)))))))
  492. (defsubst org-element-adopt-elements (parent &rest children)
  493. "Append elements to the contents of another element.
  494. PARENT is an element or object. CHILDREN can be elements,
  495. objects, or a strings.
  496. The function takes care of setting `:parent' property for CHILD.
  497. Return parent element."
  498. (declare (indent 1))
  499. (if (not children) parent
  500. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  501. ;; string: parent is the list itself.
  502. (dolist (child children)
  503. (org-element-put-property child :parent (or parent children)))
  504. ;; Add CHILDREN at the end of PARENT contents.
  505. (when parent
  506. (apply #'org-element-set-contents
  507. parent
  508. (nconc (org-element-contents parent) children)))
  509. ;; Return modified PARENT element.
  510. (or parent children)))
  511. (defun org-element-extract-element (element)
  512. "Extract ELEMENT from parse tree.
  513. Remove element from the parse tree by side-effect, and return it
  514. with its `:parent' property stripped out."
  515. (let ((parent (org-element-property :parent element))
  516. (secondary (org-element-secondary-p element)))
  517. (if secondary
  518. (org-element-put-property
  519. parent secondary
  520. (delq element (org-element-property secondary parent)))
  521. (apply #'org-element-set-contents
  522. parent
  523. (delq element (org-element-contents parent))))
  524. ;; Return ELEMENT with its :parent removed.
  525. (org-element-put-property element :parent nil)))
  526. (defun org-element-insert-before (element location)
  527. "Insert ELEMENT before LOCATION in parse tree.
  528. LOCATION is an element, object or string within the parse tree.
  529. Parse tree is modified by side effect."
  530. (let* ((parent (org-element-property :parent location))
  531. (property (org-element-secondary-p location))
  532. (siblings (if property (org-element-property property parent)
  533. (org-element-contents parent)))
  534. ;; Special case: LOCATION is the first element of an
  535. ;; independent secondary string (e.g. :title property). Add
  536. ;; ELEMENT in-place.
  537. (specialp (and (not property)
  538. (eq siblings parent)
  539. (eq (car parent) location))))
  540. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  541. (cond (specialp)
  542. ((or (null siblings) (eq (car siblings) location))
  543. (push element siblings))
  544. ((null location) (nconc siblings (list element)))
  545. (t
  546. (let ((index (cl-position location siblings)))
  547. (unless index (error "No location found to insert element"))
  548. (push element (cdr (nthcdr (1- index) siblings))))))
  549. ;; Store SIBLINGS at appropriate place in parse tree.
  550. (cond
  551. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  552. (property (org-element-put-property parent property siblings))
  553. (t (apply #'org-element-set-contents parent siblings)))
  554. ;; Set appropriate :parent property.
  555. (org-element-put-property element :parent parent)))
  556. (defconst org-element--cache-element-properties '(:cached
  557. :org-element--cache-sync-key)
  558. "List of element properties used internally by cache.")
  559. (defun org-element-set-element (old new)
  560. "Replace element or object OLD with element or object NEW.
  561. The function takes care of setting `:parent' property for NEW."
  562. ;; Ensure OLD and NEW have the same parent.
  563. (org-element-put-property new :parent (org-element-property :parent old))
  564. (dolist (p org-element--cache-element-properties)
  565. (when (org-element-property p old)
  566. (org-element-put-property new p (org-element-property p old))))
  567. (if (or (memq (org-element-type old) '(plain-text nil))
  568. (memq (org-element-type new) '(plain-text nil)))
  569. ;; We cannot replace OLD with NEW since one of them is not an
  570. ;; object or element. We take the long path.
  571. (progn (org-element-insert-before new old)
  572. (org-element-extract-element old))
  573. ;; Since OLD is going to be changed into NEW by side-effect, first
  574. ;; make sure that every element or object within NEW has OLD as
  575. ;; parent.
  576. (dolist (blob (org-element-contents new))
  577. (org-element-put-property blob :parent old))
  578. ;; Transfer contents.
  579. (apply #'org-element-set-contents old (org-element-contents new))
  580. ;; Overwrite OLD's properties with NEW's.
  581. (setcar (cdr old) (nth 1 new))
  582. ;; Transfer type.
  583. (setcar old (car new))))
  584. (defun org-element-create (type &optional props &rest children)
  585. "Create a new element of type TYPE.
  586. Optional argument PROPS, when non-nil, is a plist defining the
  587. properties of the element. CHILDREN can be elements, objects or
  588. strings."
  589. (apply #'org-element-adopt-elements (list type props) children))
  590. (defun org-element-copy (datum)
  591. "Return a copy of DATUM.
  592. DATUM is an element, object, string or nil. `:parent' property
  593. is cleared and contents are removed in the process."
  594. (when datum
  595. (let ((type (org-element-type datum)))
  596. (pcase type
  597. (`org-data (list 'org-data nil))
  598. (`plain-text (substring-no-properties datum))
  599. (`nil (copy-sequence datum))
  600. (_
  601. (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
  602. ;; We cannot simply return the copies property list. When
  603. ;; DATUM is i.e. a headline, it's property list (`:title'
  604. ;; in case of headline) can contain parsed objects. The
  605. ;; objects will contain `:parent' property set to the DATUM
  606. ;; iteself. When copied, these inner `:parent' propery
  607. ;; values will contain incorrect object decoupled from
  608. ;; DATUM. Changes to the DATUM copy will not longer be
  609. ;; reflected in the `:parent' properties. So, we need to
  610. ;; reassign inner `:parent' propreties to the DATUM copy
  611. ;; explicitly.
  612. (org-element-map element-copy (cons 'plain-text org-element-all-objects)
  613. (lambda (obj) (when (equal datum (org-element-property :parent obj))
  614. (org-element-put-property obj :parent element-copy))))
  615. element-copy))))))
  616. ;;; Greater elements
  617. ;;
  618. ;; For each greater element type, we define a parser and an
  619. ;; interpreter.
  620. ;;
  621. ;; A parser returns the element or object as the list described above.
  622. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  623. ;; every element containing a secondary string (see
  624. ;; `org-element-secondary-value-alist') will accept an optional
  625. ;; argument to toggle parsing of these secondary strings. Moreover,
  626. ;; `item' parser requires current list's structure as its first
  627. ;; element.
  628. ;;
  629. ;; An interpreter accepts two arguments: the list representation of
  630. ;; the element or object, and its contents. The latter may be nil,
  631. ;; depending on the element or object considered. It returns the
  632. ;; appropriate Org syntax, as a string.
  633. ;;
  634. ;; Parsing functions must follow the naming convention:
  635. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  636. ;; defined in `org-element-greater-elements'.
  637. ;;
  638. ;; Similarly, interpreting functions must follow the naming
  639. ;; convention: org-element-TYPE-interpreter.
  640. ;;
  641. ;; With the exception of `headline' and `item' types, greater elements
  642. ;; cannot contain other greater elements of their own type.
  643. ;;
  644. ;; Beside implementing a parser and an interpreter, adding a new
  645. ;; greater element requires tweaking `org-element--current-element'.
  646. ;; Moreover, the newly defined type must be added to both
  647. ;; `org-element-all-elements' and `org-element-greater-elements'.
  648. ;;;; Center Block
  649. (defun org-element-center-block-parser (limit affiliated)
  650. "Parse a center block.
  651. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  652. the buffer position at the beginning of the first affiliated
  653. keyword and CDR is a plist of affiliated keywords along with
  654. their value.
  655. Return a list whose CAR is `center-block' and CDR is a plist
  656. containing `:begin', `:end', `:contents-begin', `:contents-end',
  657. `:post-blank' and `:post-affiliated' keywords.
  658. Assume point is at the beginning of the block."
  659. (let ((case-fold-search t))
  660. (if (not (save-excursion
  661. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  662. ;; Incomplete block: parse it as a paragraph.
  663. (org-element-paragraph-parser limit affiliated)
  664. (let ((block-end-line (match-beginning 0)))
  665. (let* ((begin (car affiliated))
  666. (post-affiliated (point))
  667. ;; Empty blocks have no contents.
  668. (contents-begin (progn (forward-line)
  669. (and (< (point) block-end-line)
  670. (point))))
  671. (contents-end (and contents-begin block-end-line))
  672. (pos-before-blank (progn (goto-char block-end-line)
  673. (forward-line)
  674. (point)))
  675. (end (save-excursion
  676. (skip-chars-forward " \r\t\n" limit)
  677. (if (eobp) (point) (line-beginning-position)))))
  678. (list 'center-block
  679. (nconc
  680. (list :begin begin
  681. :end end
  682. :contents-begin contents-begin
  683. :contents-end contents-end
  684. :post-blank (count-lines pos-before-blank end)
  685. :post-affiliated post-affiliated)
  686. (cdr affiliated))))))))
  687. (defun org-element-center-block-interpreter (_ contents)
  688. "Interpret a center-block element as Org syntax.
  689. CONTENTS is the contents of the element."
  690. (format "#+begin_center\n%s#+end_center" contents))
  691. ;;;; Drawer
  692. (defun org-element-drawer-parser (limit affiliated)
  693. "Parse a drawer.
  694. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  695. the buffer position at the beginning of the first affiliated
  696. keyword and CDR is a plist of affiliated keywords along with
  697. their value.
  698. Return a list whose CAR is `drawer' and CDR is a plist containing
  699. `:drawer-name', `:begin', `:end', `:contents-begin',
  700. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  701. Assume point is at beginning of drawer."
  702. (let ((case-fold-search t))
  703. (if (not (save-excursion
  704. (goto-char (min limit (line-end-position)))
  705. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  706. ;; Incomplete drawer: parse it as a paragraph.
  707. (org-element-paragraph-parser limit affiliated)
  708. (save-excursion
  709. (let* ((drawer-end-line (match-beginning 0))
  710. (name (progn (looking-at org-drawer-regexp)
  711. (match-string-no-properties 1)))
  712. (begin (car affiliated))
  713. (post-affiliated (point))
  714. ;; Empty drawers have no contents.
  715. (contents-begin (progn (forward-line)
  716. (and (< (point) drawer-end-line)
  717. (point))))
  718. (contents-end (and contents-begin drawer-end-line))
  719. (pos-before-blank (progn (goto-char drawer-end-line)
  720. (forward-line)
  721. (point)))
  722. (end (progn (skip-chars-forward " \r\t\n" limit)
  723. (if (eobp) (point) (line-beginning-position)))))
  724. (list 'drawer
  725. (nconc
  726. (list :begin begin
  727. :end end
  728. :drawer-name name
  729. :contents-begin contents-begin
  730. :contents-end contents-end
  731. :post-blank (count-lines pos-before-blank end)
  732. :post-affiliated post-affiliated)
  733. (cdr affiliated))))))))
  734. (defun org-element-drawer-interpreter (drawer contents)
  735. "Interpret DRAWER element as Org syntax.
  736. CONTENTS is the contents of the element."
  737. (format ":%s:\n%s:END:"
  738. (org-element-property :drawer-name drawer)
  739. contents))
  740. ;;;; Dynamic Block
  741. (defun org-element-dynamic-block-parser (limit affiliated)
  742. "Parse a dynamic block.
  743. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  744. the buffer position at the beginning of the first affiliated
  745. keyword and CDR is a plist of affiliated keywords along with
  746. their value.
  747. Return a list whose CAR is `dynamic-block' and CDR is a plist
  748. containing `:block-name', `:begin', `:end', `:contents-begin',
  749. `:contents-end', `:arguments', `:post-blank' and
  750. `:post-affiliated' keywords.
  751. Assume point is at beginning of dynamic block."
  752. (let ((case-fold-search t))
  753. (if (not (save-excursion
  754. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  755. ;; Incomplete block: parse it as a paragraph.
  756. (org-element-paragraph-parser limit affiliated)
  757. (let ((block-end-line (match-beginning 0)))
  758. (save-excursion
  759. (let* ((name (progn (looking-at org-dblock-start-re)
  760. (match-string-no-properties 1)))
  761. (arguments (match-string-no-properties 3))
  762. (begin (car affiliated))
  763. (post-affiliated (point))
  764. ;; Empty blocks have no contents.
  765. (contents-begin (progn (forward-line)
  766. (and (< (point) block-end-line)
  767. (point))))
  768. (contents-end (and contents-begin block-end-line))
  769. (pos-before-blank (progn (goto-char block-end-line)
  770. (forward-line)
  771. (point)))
  772. (end (progn (skip-chars-forward " \r\t\n" limit)
  773. (if (eobp) (point) (line-beginning-position)))))
  774. (list 'dynamic-block
  775. (nconc
  776. (list :begin begin
  777. :end end
  778. :block-name name
  779. :arguments arguments
  780. :contents-begin contents-begin
  781. :contents-end contents-end
  782. :post-blank (count-lines pos-before-blank end)
  783. :post-affiliated post-affiliated)
  784. (cdr affiliated)))))))))
  785. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  786. "Interpret DYNAMIC-BLOCK element as Org syntax.
  787. CONTENTS is the contents of the element."
  788. (format "#+begin: %s%s\n%s#+end:"
  789. (org-element-property :block-name dynamic-block)
  790. (let ((args (org-element-property :arguments dynamic-block)))
  791. (if args (concat " " args) ""))
  792. contents))
  793. ;;;; Footnote Definition
  794. (defconst org-element--footnote-separator
  795. (concat org-outline-regexp-bol "\\|"
  796. org-footnote-definition-re "\\|"
  797. "^\\([ \t]*\n\\)\\{2,\\}")
  798. "Regexp used as a footnote definition separator.")
  799. (defun org-element-footnote-definition-parser (limit affiliated)
  800. "Parse a footnote definition.
  801. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  802. the buffer position at the beginning of the first affiliated
  803. keyword and CDR is a plist of affiliated keywords along with
  804. their value.
  805. Return a list whose CAR is `footnote-definition' and CDR is
  806. a plist containing `:label', `:begin' `:end', `:contents-begin',
  807. `:contents-end', `:pre-blank',`:post-blank' and
  808. `:post-affiliated' keywords.
  809. Assume point is at the beginning of the footnote definition."
  810. (save-excursion
  811. (let* ((label (progn (looking-at org-footnote-definition-re)
  812. (match-string-no-properties 1)))
  813. (begin (car affiliated))
  814. (post-affiliated (point))
  815. (end
  816. (save-excursion
  817. (end-of-line)
  818. (cond
  819. ((not
  820. (re-search-forward org-element--footnote-separator limit t))
  821. limit)
  822. ((eq ?\[ (char-after (match-beginning 0)))
  823. ;; At a new footnote definition, make sure we end
  824. ;; before any affiliated keyword above.
  825. (forward-line -1)
  826. (while (and (> (point) post-affiliated)
  827. (looking-at-p org-element--affiliated-re))
  828. (forward-line -1))
  829. (line-beginning-position 2))
  830. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  831. (t (skip-chars-forward " \r\t\n" limit)
  832. (if (= limit (point)) limit (line-beginning-position))))))
  833. (pre-blank 0)
  834. (contents-begin
  835. (progn (search-forward "]")
  836. (skip-chars-forward " \r\t\n" end)
  837. (cond ((= (point) end) nil)
  838. ((= (line-beginning-position) post-affiliated) (point))
  839. (t
  840. (setq pre-blank
  841. (count-lines (line-beginning-position) begin))
  842. (line-beginning-position)))))
  843. (contents-end
  844. (progn (goto-char end)
  845. (skip-chars-backward " \r\t\n")
  846. (line-beginning-position 2))))
  847. (list 'footnote-definition
  848. (nconc
  849. (list :label label
  850. :begin begin
  851. :end end
  852. :contents-begin contents-begin
  853. :contents-end (and contents-begin contents-end)
  854. :pre-blank pre-blank
  855. :post-blank (count-lines contents-end end)
  856. :post-affiliated post-affiliated)
  857. (cdr affiliated))))))
  858. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  859. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  860. CONTENTS is the contents of the footnote-definition."
  861. (let ((pre-blank
  862. (min (or (org-element-property :pre-blank footnote-definition)
  863. ;; 0 is specific to paragraphs at the beginning of
  864. ;; the footnote definition, so we use 1 as
  865. ;; a fall-back value, which is more universal.
  866. 1)
  867. ;; Footnote ends after more than two consecutive empty
  868. ;; lines: limit ourselves to 2 newline characters.
  869. 2)))
  870. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  871. (if (= pre-blank 0) (concat " " (org-trim contents))
  872. (concat (make-string pre-blank ?\n) contents)))))
  873. ;;;; Headline
  874. (defun org-element--get-node-properties (&optional at-point-p?)
  875. "Return node properties for headline or property drawer at point.
  876. Upcase property names. It avoids confusion between properties
  877. obtained through property drawer and default properties from the
  878. parser (e.g. `:end' and :END:). Return value is a plist.
  879. When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
  880. parse properties for property drawer at point."
  881. (save-excursion
  882. (unless at-point-p?
  883. (forward-line)
  884. (when (looking-at-p org-planning-line-re) (forward-line)))
  885. (when (looking-at org-property-drawer-re)
  886. (forward-line)
  887. (let ((end (match-end 0)) properties)
  888. (while (< (line-end-position) end)
  889. (looking-at org-property-re)
  890. (let* ((property-name (concat ":" (upcase (match-string 2))))
  891. (property-name-symbol (intern property-name))
  892. (property-value (match-string-no-properties 3)))
  893. (cond
  894. ((and (plist-member properties property-name-symbol)
  895. (string-match-p "+$" property-name))
  896. (let ((val (plist-get properties property-name-symbol)))
  897. (if (listp val)
  898. (setq properties
  899. (plist-put properties
  900. property-name-symbol
  901. (append (plist-get properties property-name-symbol)
  902. (list property-value))))
  903. (plist-put properties property-name-symbol (list val property-value)))))
  904. (t (setq properties (plist-put properties property-name-symbol property-value)))))
  905. (forward-line))
  906. properties))))
  907. (defun org-element--get-time-properties ()
  908. "Return time properties associated to headline at point.
  909. Return value is a plist."
  910. (save-excursion
  911. (when (progn (forward-line) (looking-at org-planning-line-re))
  912. (let ((end (line-end-position)) plist)
  913. (while (re-search-forward org-keyword-time-not-clock-regexp end t)
  914. (goto-char (match-end 1))
  915. (skip-chars-forward " \t")
  916. (let ((keyword (match-string 1))
  917. (time (org-element-timestamp-parser)))
  918. (cond ((equal keyword org-scheduled-string)
  919. (setq plist (plist-put plist :scheduled time)))
  920. ((equal keyword org-deadline-string)
  921. (setq plist (plist-put plist :deadline time)))
  922. (t (setq plist (plist-put plist :closed time))))))
  923. plist))))
  924. (defun org-element-headline-parser (&optional _ raw-secondary-p)
  925. "Parse a headline.
  926. Return a list whose CAR is `headline' and CDR is a plist
  927. containing `:raw-value', `:title', `:begin', `:end',
  928. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  929. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  930. `:deadline', `:closed', `:archivedp', `:commentedp'
  931. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  932. keywords.
  933. The plist also contains any property set in the property drawer,
  934. with its name in upper cases and colons added at the
  935. beginning (e.g., `:CUSTOM_ID').
  936. When RAW-SECONDARY-P is non-nil, headline's title will not be
  937. parsed as a secondary string, but as a plain string instead.
  938. Assume point is at beginning of the headline."
  939. (save-excursion
  940. (let* ((begin (point))
  941. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  942. (skip-chars-forward " \t")))
  943. (todo (and org-todo-regexp
  944. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  945. (progn (goto-char (match-end 0))
  946. (skip-chars-forward " \t")
  947. (match-string 1))))
  948. (todo-type
  949. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  950. (priority (and (looking-at "\\[#.\\][ \t]*")
  951. (progn (goto-char (match-end 0))
  952. (aref (match-string 0) 2))))
  953. (commentedp
  954. (and (let (case-fold-search) (looking-at org-comment-string))
  955. (goto-char (match-end 0))))
  956. (title-start (prog1 (point)
  957. (unless (or todo priority commentedp)
  958. ;; Headline like "* :tag:"
  959. (skip-chars-backward " \t"))))
  960. (tags (when (re-search-forward
  961. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  962. (line-end-position)
  963. 'move)
  964. (goto-char (match-beginning 0))
  965. (org-split-string (match-string 1) ":")))
  966. (title-end (point))
  967. (raw-value (org-trim
  968. (buffer-substring-no-properties title-start title-end)))
  969. (archivedp (member org-archive-tag tags))
  970. (footnote-section-p (and org-footnote-section
  971. (string= org-footnote-section raw-value)))
  972. (standard-props (org-element--get-node-properties))
  973. (time-props (org-element--get-time-properties))
  974. (end (save-excursion
  975. ;; Make sure that `org-end-of-subtree' does not try
  976. ;; to use cache. The headline parser might be
  977. ;; called in the midst of cache processing.
  978. ;; FIXME: We cannot simply bind `org-element-use-cache' here
  979. ;; because apparently some magic related to lexical
  980. ;; scoping prevents `org-element--cache-active-p' call inside
  981. ;; `org-end-of-subtree' to use the overridden value
  982. ;; of `org-element-use-cache'.
  983. (org-element-with-disabled-cache
  984. (org-end-of-subtree t t))))
  985. (contents-begin (save-excursion
  986. (forward-line)
  987. (skip-chars-forward " \r\t\n" end)
  988. (and (/= (point) end) (line-beginning-position))))
  989. (contents-end (and contents-begin
  990. (progn (goto-char end)
  991. (skip-chars-backward " \r\t\n")
  992. (line-beginning-position 2))))
  993. (robust-begin (and contents-begin
  994. (progn (goto-char contents-begin)
  995. (when (looking-at-p org-planning-line-re)
  996. (forward-line))
  997. (when (looking-at org-property-drawer-re)
  998. (goto-char (match-end 0)))
  999. ;; If there is :pre-blank, we
  1000. ;; need to be careful about
  1001. ;; robust beginning.
  1002. (max (if (< (+ 2 contents-begin) contents-end)
  1003. (+ 2 contents-begin)
  1004. 0)
  1005. (point)))))
  1006. (robust-end (and robust-begin
  1007. (when (> (- contents-end 2) robust-begin)
  1008. (- contents-end 2)))))
  1009. (unless robust-end (setq robust-begin nil))
  1010. (let ((headline
  1011. (list 'headline
  1012. (nconc
  1013. (list :raw-value raw-value
  1014. :begin begin
  1015. :end end
  1016. :pre-blank
  1017. (if (not contents-begin) 0
  1018. (1- (count-lines begin contents-begin)))
  1019. :contents-begin contents-begin
  1020. :contents-end contents-end
  1021. :robust-begin robust-begin
  1022. :robust-end robust-end
  1023. :level level
  1024. :priority priority
  1025. :tags tags
  1026. :todo-keyword todo
  1027. :todo-type todo-type
  1028. :post-blank
  1029. (if contents-end
  1030. (count-lines contents-end end)
  1031. (1- (count-lines begin end)))
  1032. :footnote-section-p footnote-section-p
  1033. :archivedp archivedp
  1034. :commentedp commentedp
  1035. :post-affiliated begin)
  1036. time-props
  1037. standard-props))))
  1038. (org-element-put-property
  1039. headline :title
  1040. (if raw-secondary-p raw-value
  1041. (org-element--parse-objects
  1042. (progn (goto-char title-start)
  1043. (skip-chars-forward " \t")
  1044. (point))
  1045. (progn (goto-char title-end)
  1046. (skip-chars-backward " \t")
  1047. (point))
  1048. nil
  1049. (org-element-restriction 'headline)
  1050. headline)))))))
  1051. (defun org-element-headline-interpreter (headline contents)
  1052. "Interpret HEADLINE element as Org syntax.
  1053. CONTENTS is the contents of the element."
  1054. (let* ((level (org-element-property :level headline))
  1055. (todo (org-element-property :todo-keyword headline))
  1056. (priority (org-element-property :priority headline))
  1057. (title (org-element-interpret-data
  1058. (org-element-property :title headline)))
  1059. (tags (let ((tag-list (org-element-property :tags headline)))
  1060. (and tag-list
  1061. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  1062. (commentedp (org-element-property :commentedp headline))
  1063. (pre-blank (or (org-element-property :pre-blank headline) 0))
  1064. (heading
  1065. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  1066. ?*)
  1067. (and todo (concat " " todo))
  1068. (and commentedp (concat " " org-comment-string))
  1069. (and priority (format " [#%c]" priority))
  1070. " "
  1071. (if (and org-footnote-section
  1072. (org-element-property :footnote-section-p headline))
  1073. org-footnote-section
  1074. title))))
  1075. (concat
  1076. heading
  1077. ;; Align tags.
  1078. (when tags
  1079. (cond
  1080. ((zerop org-tags-column) (format " %s" tags))
  1081. ((< org-tags-column 0)
  1082. (concat
  1083. (make-string
  1084. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1085. ?\s)
  1086. tags))
  1087. (t
  1088. (concat
  1089. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1090. tags))))
  1091. (make-string (1+ pre-blank) ?\n)
  1092. contents)))
  1093. ;;;; org-data
  1094. (defun org-element--get-global-node-properties ()
  1095. "Return node properties associated with the whole Org buffer.
  1096. Upcase property names. It avoids confusion between properties
  1097. obtained through property drawer and default properties from the
  1098. parser (e.g. `:end' and :END:). Return value is a plist."
  1099. (org-with-wide-buffer
  1100. (goto-char (point-min))
  1101. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1102. (org-element--get-node-properties t)))
  1103. (defun org-element-org-data-parser (&optional _)
  1104. "Parse org-data."
  1105. (org-with-wide-buffer
  1106. (let* ((begin 1)
  1107. (contents-begin (progn
  1108. (goto-char 1)
  1109. (org-skip-whitespace)
  1110. (beginning-of-line)
  1111. (point)))
  1112. (end (point-max))
  1113. (pos-before-blank (progn (goto-char (point-max))
  1114. (skip-chars-backward " \r\t\n")
  1115. (line-beginning-position 2)))
  1116. (robust-end (when (> (- pos-before-blank 2) contents-begin)
  1117. (- pos-before-blank 2)))
  1118. (robust-begin (when (and robust-end
  1119. (< (+ 2 contents-begin) pos-before-blank))
  1120. (or
  1121. (org-with-wide-buffer
  1122. (goto-char (point-min))
  1123. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1124. (when (looking-at org-property-drawer-re)
  1125. (goto-char (match-end 0))
  1126. (skip-chars-backward " \t")
  1127. (min robust-end (point))))
  1128. (+ 2 contents-begin))))
  1129. (category (cond ((null org-category)
  1130. (when buffer-file-name
  1131. (file-name-sans-extension
  1132. (file-name-nondirectory buffer-file-name))))
  1133. ((symbolp org-category) (symbol-name org-category))
  1134. (t org-category)))
  1135. (category (catch 'buffer-category
  1136. (org-with-point-at end
  1137. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  1138. (org-element-with-disabled-cache
  1139. (let ((element (org-element-at-point-no-context)))
  1140. (when (eq (org-element-type element) 'keyword)
  1141. (throw 'buffer-category
  1142. (org-element-property :value element)))))))
  1143. category))
  1144. (properties (org-element--get-global-node-properties)))
  1145. (unless (plist-get properties :CATEGORY)
  1146. (setq properties (plist-put properties :CATEGORY category)))
  1147. (list 'org-data
  1148. (nconc
  1149. (list :begin begin
  1150. :contents-begin contents-begin
  1151. :contents-end pos-before-blank
  1152. :end end
  1153. :robust-begin robust-begin
  1154. :robust-end robust-end
  1155. :post-blank (count-lines pos-before-blank end)
  1156. :post-affiliated begin
  1157. :path (buffer-file-name)
  1158. :mode 'org-data)
  1159. properties)))))
  1160. (defun org-element-org-data-interpreter (_ contents)
  1161. "Interpret ORG-DATA element as Org syntax.
  1162. CONTENTS is the contents of the element."
  1163. contents)
  1164. ;;;; Inlinetask
  1165. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1166. "Parse an inline task.
  1167. Return a list whose CAR is `inlinetask' and CDR is a plist
  1168. containing `:title', `:begin', `:end', `:pre-blank',
  1169. `:contents-begin' and `:contents-end', `:level', `:priority',
  1170. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1171. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1172. `:post-affiliated' keywords.
  1173. The plist also contains any property set in the property drawer,
  1174. with its name in upper cases and colons added at the
  1175. beginning (e.g., `:CUSTOM_ID').
  1176. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1177. title will not be parsed as a secondary string, but as a plain
  1178. string instead.
  1179. Assume point is at beginning of the inline task."
  1180. (save-excursion
  1181. (let* ((begin (point))
  1182. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1183. (skip-chars-forward " \t")))
  1184. (todo (and org-todo-regexp
  1185. (let (case-fold-search) (looking-at org-todo-regexp))
  1186. (progn (goto-char (match-end 0))
  1187. (skip-chars-forward " \t")
  1188. (match-string 0))))
  1189. (todo-type (and todo
  1190. (if (member todo org-done-keywords) 'done 'todo)))
  1191. (priority (and (looking-at "\\[#.\\][ \t]*")
  1192. (progn (goto-char (match-end 0))
  1193. (aref (match-string 0) 2))))
  1194. (title-start (point))
  1195. (tags (when (re-search-forward
  1196. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1197. (line-end-position)
  1198. 'move)
  1199. (goto-char (match-beginning 0))
  1200. (org-split-string (match-string 1) ":")))
  1201. (title-end (point))
  1202. (raw-value (org-trim
  1203. (buffer-substring-no-properties title-start title-end)))
  1204. (task-end (save-excursion
  1205. (end-of-line)
  1206. (and (re-search-forward org-outline-regexp-bol limit t)
  1207. (looking-at-p "[ \t]*END[ \t]*$")
  1208. (line-beginning-position))))
  1209. (standard-props (and task-end (org-element--get-node-properties)))
  1210. (time-props (and task-end (org-element--get-time-properties)))
  1211. (contents-begin (and task-end
  1212. (< (point) task-end)
  1213. (progn
  1214. (forward-line)
  1215. (skip-chars-forward " \t\n")
  1216. (line-beginning-position))))
  1217. (contents-end (and contents-begin task-end))
  1218. (end (progn (when task-end (goto-char task-end))
  1219. (forward-line)
  1220. (skip-chars-forward " \r\t\n" limit)
  1221. (if (eobp) (point) (line-beginning-position))))
  1222. (inlinetask
  1223. (list 'inlinetask
  1224. (nconc
  1225. (list :raw-value raw-value
  1226. :begin begin
  1227. :end end
  1228. :pre-blank
  1229. (if (not contents-begin) 0
  1230. (1- (count-lines begin contents-begin)))
  1231. :contents-begin contents-begin
  1232. :contents-end contents-end
  1233. :level level
  1234. :priority priority
  1235. :tags tags
  1236. :todo-keyword todo
  1237. :todo-type todo-type
  1238. :post-blank (1- (count-lines (or task-end begin) end))
  1239. :post-affiliated begin)
  1240. time-props
  1241. standard-props))))
  1242. (org-element-put-property
  1243. inlinetask :title
  1244. (if raw-secondary-p raw-value
  1245. (org-element--parse-objects
  1246. (progn (goto-char title-start)
  1247. (skip-chars-forward " \t")
  1248. (point))
  1249. (progn (goto-char title-end)
  1250. (skip-chars-backward " \t")
  1251. (point))
  1252. nil
  1253. (org-element-restriction 'inlinetask)
  1254. inlinetask))))))
  1255. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1256. "Interpret INLINETASK element as Org syntax.
  1257. CONTENTS is the contents of inlinetask."
  1258. (let* ((level (org-element-property :level inlinetask))
  1259. (todo (org-element-property :todo-keyword inlinetask))
  1260. (priority (org-element-property :priority inlinetask))
  1261. (title (org-element-interpret-data
  1262. (org-element-property :title inlinetask)))
  1263. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1264. (and tag-list
  1265. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1266. (task (concat (make-string level ?*)
  1267. (and todo (concat " " todo))
  1268. (and priority (format " [#%c]" priority))
  1269. (and title (concat " " title)))))
  1270. (concat task
  1271. ;; Align tags.
  1272. (when tags
  1273. (cond
  1274. ((zerop org-tags-column) (format " %s" tags))
  1275. ((< org-tags-column 0)
  1276. (concat
  1277. (make-string
  1278. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1279. ?\s)
  1280. tags))
  1281. (t
  1282. (concat
  1283. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1284. tags))))
  1285. ;; Prefer degenerate inlinetasks when there are no
  1286. ;; contents.
  1287. (when contents
  1288. (concat "\n"
  1289. contents
  1290. (make-string level ?*) " end")))))
  1291. ;;;; Item
  1292. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1293. "Parse an item.
  1294. STRUCT is the structure of the plain list.
  1295. Return a list whose CAR is `item' and CDR is a plist containing
  1296. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1297. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1298. `:post-blank' and `:post-affiliated' keywords.
  1299. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1300. any, will not be parsed as a secondary string, but as a plain
  1301. string instead.
  1302. Assume point is at the beginning of the item."
  1303. (save-excursion
  1304. (beginning-of-line)
  1305. (looking-at org-list-full-item-re)
  1306. (let* ((begin (point))
  1307. (bullet (match-string-no-properties 1))
  1308. (checkbox (let ((box (match-string 3)))
  1309. (cond ((equal "[ ]" box) 'off)
  1310. ((equal "[X]" box) 'on)
  1311. ((equal "[-]" box) 'trans))))
  1312. (counter (let ((c (match-string 2)))
  1313. (save-match-data
  1314. (cond
  1315. ((not c) nil)
  1316. ((string-match "[A-Za-z]" c)
  1317. (- (string-to-char (upcase (match-string 0 c)))
  1318. 64))
  1319. ((string-match "[0-9]+" c)
  1320. (string-to-number (match-string 0 c)))))))
  1321. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1322. (if (bolp) (point) (line-beginning-position 2))))
  1323. (pre-blank 0)
  1324. (contents-begin
  1325. (progn
  1326. (goto-char
  1327. ;; Ignore tags in un-ordered lists: they are just
  1328. ;; a part of item's body.
  1329. (if (and (match-beginning 4)
  1330. (save-match-data (string-match "[.)]" bullet)))
  1331. (match-beginning 4)
  1332. (match-end 0)))
  1333. (skip-chars-forward " \r\t\n" end)
  1334. (cond ((= (point) end) nil)
  1335. ;; If first line isn't empty, contents really
  1336. ;; start at the text after item's meta-data.
  1337. ((= (line-beginning-position) begin) (point))
  1338. (t
  1339. (setq pre-blank
  1340. (count-lines (line-beginning-position) begin))
  1341. (line-beginning-position)))))
  1342. (contents-end (and contents-begin
  1343. (progn (goto-char end)
  1344. (skip-chars-backward " \r\t\n")
  1345. (line-beginning-position 2))))
  1346. (item
  1347. (list 'item
  1348. (list :bullet bullet
  1349. :begin begin
  1350. :end end
  1351. :contents-begin contents-begin
  1352. :contents-end contents-end
  1353. :checkbox checkbox
  1354. :counter counter
  1355. :structure struct
  1356. :pre-blank pre-blank
  1357. :post-blank (count-lines (or contents-end begin) end)
  1358. :post-affiliated begin))))
  1359. (org-element-put-property
  1360. item :tag
  1361. (let ((raw (org-list-get-tag begin struct)))
  1362. (when raw
  1363. (if raw-secondary-p raw
  1364. (org-element--parse-objects
  1365. (match-beginning 4) (match-end 4) nil
  1366. (org-element-restriction 'item)
  1367. item))))))))
  1368. (defun org-element-item-interpreter (item contents)
  1369. "Interpret ITEM element as Org syntax.
  1370. CONTENTS is the contents of the element."
  1371. (let ((tag (pcase (org-element-property :tag item)
  1372. (`nil nil)
  1373. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1374. (bullet
  1375. (org-list-bullet-string
  1376. (cond
  1377. ((not (string-match-p "[0-9a-zA-Z]"
  1378. (org-element-property :bullet item))) "- ")
  1379. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1380. (t "1.")))))
  1381. (concat
  1382. bullet
  1383. (pcase (org-element-property :counter item)
  1384. (`nil nil)
  1385. (counter (format "[@%d] " counter)))
  1386. (pcase (org-element-property :checkbox item)
  1387. (`on "[X] ")
  1388. (`off "[ ] ")
  1389. (`trans "[-] ")
  1390. (_ nil))
  1391. tag
  1392. (when contents
  1393. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1394. (pre-blank
  1395. (min (or (org-element-property :pre-blank item)
  1396. ;; 0 is specific to paragraphs at the
  1397. ;; beginning of the item, so we use 1 as
  1398. ;; a fall-back value, which is more universal.
  1399. 1)
  1400. ;; Lists ends after more than two consecutive
  1401. ;; empty lines: limit ourselves to 2 newline
  1402. ;; characters.
  1403. 2))
  1404. (contents (replace-regexp-in-string
  1405. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1406. (if (= pre-blank 0) (org-trim contents)
  1407. (concat (make-string pre-blank ?\n) contents)))))))
  1408. ;;;; Plain List
  1409. (defun org-element--list-struct (limit)
  1410. ;; Return structure of list at point. Internal function. See
  1411. ;; `org-list-struct' for details.
  1412. (let ((case-fold-search t)
  1413. (top-ind limit)
  1414. (item-re (org-item-re))
  1415. (inlinetask-re (and (featurep 'org-inlinetask)
  1416. (boundp 'org-inlinetask-min-level)
  1417. (boundp 'org-inlinetask-max-level)
  1418. (format "^\\*\\{%d,%d\\}+ "
  1419. org-inlinetask-min-level
  1420. org-inlinetask-max-level)))
  1421. items struct)
  1422. (save-excursion
  1423. (catch :exit
  1424. (while t
  1425. (cond
  1426. ;; At limit: end all items.
  1427. ((>= (point) limit)
  1428. (let ((end (progn (skip-chars-backward " \r\t\n")
  1429. (line-beginning-position 2))))
  1430. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1431. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1432. ;; At list end: end all items.
  1433. ((looking-at org-list-end-re)
  1434. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1435. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1436. ;; At a new item: end previous sibling.
  1437. ((looking-at item-re)
  1438. (let ((ind (save-excursion (skip-chars-forward " \t")
  1439. (current-column))))
  1440. (setq top-ind (min top-ind ind))
  1441. (while (and items (<= ind (nth 1 (car items))))
  1442. (let ((item (pop items)))
  1443. (setcar (nthcdr 6 item) (point))
  1444. (push item struct)))
  1445. (push (progn (looking-at org-list-full-item-re)
  1446. (let ((bullet (match-string-no-properties 1)))
  1447. (list (point)
  1448. ind
  1449. bullet
  1450. (match-string-no-properties 2) ; counter
  1451. (match-string-no-properties 3) ; checkbox
  1452. ;; Description tag.
  1453. (and (save-match-data
  1454. (string-match "[-+*]" bullet))
  1455. (match-string-no-properties 4))
  1456. ;; Ending position, unknown so far.
  1457. nil)))
  1458. items))
  1459. (forward-line))
  1460. ;; Skip empty lines.
  1461. ((looking-at "^[ \t]*$") (forward-line))
  1462. ;; Skip inline tasks and blank lines along the way.
  1463. ((and inlinetask-re (looking-at inlinetask-re))
  1464. (forward-line)
  1465. (let ((origin (point)))
  1466. (when (re-search-forward inlinetask-re limit t)
  1467. (if (looking-at-p "END[ \t]*$") (forward-line)
  1468. (goto-char origin)))))
  1469. ;; At some text line. Check if it ends any previous item.
  1470. (t
  1471. (let ((ind (save-excursion
  1472. (skip-chars-forward " \t")
  1473. (current-column)))
  1474. (end (save-excursion
  1475. (skip-chars-backward " \r\t\n")
  1476. (line-beginning-position 2))))
  1477. (while (<= ind (nth 1 (car items)))
  1478. (let ((item (pop items)))
  1479. (setcar (nthcdr 6 item) end)
  1480. (push item struct)
  1481. (unless items
  1482. (throw :exit (sort struct #'car-less-than-car))))))
  1483. ;; Skip blocks (any type) and drawers contents.
  1484. (cond
  1485. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1486. (re-search-forward
  1487. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1488. limit t)))
  1489. ((and (looking-at org-drawer-regexp)
  1490. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1491. (forward-line))))))))
  1492. (defun org-element-plain-list-parser (limit affiliated structure)
  1493. "Parse a plain list.
  1494. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1495. the buffer position at the beginning of the first affiliated
  1496. keyword and CDR is a plist of affiliated keywords along with
  1497. their value. STRUCTURE is the structure of the plain list being
  1498. parsed.
  1499. Return a list whose CAR is `plain-list' and CDR is a plist
  1500. containing `:type', `:begin', `:end', `:contents-begin' and
  1501. `:contents-end', `:structure', `:post-blank' and
  1502. `:post-affiliated' keywords.
  1503. Assume point is at the beginning of the list."
  1504. (save-excursion
  1505. (let* ((struct (or structure (org-element--list-struct limit)))
  1506. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1507. ((nth 5 (assq (point) struct)) 'descriptive)
  1508. (t 'unordered)))
  1509. (contents-begin (point))
  1510. (begin (car affiliated))
  1511. (contents-end (let* ((item (assq contents-begin struct))
  1512. (ind (nth 1 item))
  1513. (pos (nth 6 item)))
  1514. (while (and (setq item (assq pos struct))
  1515. (= (nth 1 item) ind))
  1516. (setq pos (nth 6 item)))
  1517. pos))
  1518. (end (progn (goto-char contents-end)
  1519. (skip-chars-forward " \r\t\n" limit)
  1520. (if (= (point) limit) limit (line-beginning-position)))))
  1521. ;; Return value.
  1522. (list 'plain-list
  1523. (nconc
  1524. (list :type type
  1525. :begin begin
  1526. :end end
  1527. :contents-begin contents-begin
  1528. :contents-end contents-end
  1529. :structure struct
  1530. :post-blank (count-lines contents-end end)
  1531. :post-affiliated contents-begin)
  1532. (cdr affiliated))))))
  1533. (defun org-element-plain-list-interpreter (_ contents)
  1534. "Interpret plain-list element as Org syntax.
  1535. CONTENTS is the contents of the element."
  1536. (with-temp-buffer
  1537. (insert contents)
  1538. (goto-char (point-min))
  1539. (org-list-repair)
  1540. (buffer-string)))
  1541. ;;;; Property Drawer
  1542. (defun org-element-property-drawer-parser (limit)
  1543. "Parse a property drawer.
  1544. LIMIT bounds the search.
  1545. Return a list whose car is `property-drawer' and cdr is a plist
  1546. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1547. `:post-blank' and `:post-affiliated' keywords.
  1548. Assume point is at the beginning of the property drawer."
  1549. (save-excursion
  1550. (let ((case-fold-search t)
  1551. (begin (point))
  1552. (contents-begin (line-beginning-position 2)))
  1553. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1554. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1555. (match-beginning 0)))
  1556. (before-blank (progn (forward-line) (point)))
  1557. (end (progn (skip-chars-forward " \r\t\n" limit)
  1558. (if (eobp) (point) (line-beginning-position)))))
  1559. (list 'property-drawer
  1560. (list :begin begin
  1561. :end end
  1562. :contents-begin (and contents-end contents-begin)
  1563. :contents-end contents-end
  1564. :post-blank (count-lines before-blank end)
  1565. :post-affiliated begin))))))
  1566. (defun org-element-property-drawer-interpreter (_ contents)
  1567. "Interpret property-drawer element as Org syntax.
  1568. CONTENTS is the properties within the drawer."
  1569. (format ":PROPERTIES:\n%s:END:" contents))
  1570. ;;;; Quote Block
  1571. (defun org-element-quote-block-parser (limit affiliated)
  1572. "Parse a quote block.
  1573. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1574. the buffer position at the beginning of the first affiliated
  1575. keyword and CDR is a plist of affiliated keywords along with
  1576. their value.
  1577. Return a list whose CAR is `quote-block' and CDR is a plist
  1578. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1579. `:post-blank' and `:post-affiliated' keywords.
  1580. Assume point is at the beginning of the block."
  1581. (let ((case-fold-search t))
  1582. (if (not (save-excursion
  1583. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1584. ;; Incomplete block: parse it as a paragraph.
  1585. (org-element-paragraph-parser limit affiliated)
  1586. (let ((block-end-line (match-beginning 0)))
  1587. (save-excursion
  1588. (let* ((begin (car affiliated))
  1589. (post-affiliated (point))
  1590. ;; Empty blocks have no contents.
  1591. (contents-begin (progn (forward-line)
  1592. (and (< (point) block-end-line)
  1593. (point))))
  1594. (contents-end (and contents-begin block-end-line))
  1595. (pos-before-blank (progn (goto-char block-end-line)
  1596. (forward-line)
  1597. (point)))
  1598. (end (progn (skip-chars-forward " \r\t\n" limit)
  1599. (if (eobp) (point) (line-beginning-position)))))
  1600. (list 'quote-block
  1601. (nconc
  1602. (list :begin begin
  1603. :end end
  1604. :contents-begin contents-begin
  1605. :contents-end contents-end
  1606. :post-blank (count-lines pos-before-blank end)
  1607. :post-affiliated post-affiliated)
  1608. (cdr affiliated)))))))))
  1609. (defun org-element-quote-block-interpreter (_ contents)
  1610. "Interpret quote-block element as Org syntax.
  1611. CONTENTS is the contents of the element."
  1612. (format "#+begin_quote\n%s#+end_quote" contents))
  1613. ;;;; Section
  1614. (defun org-element-section-parser (_)
  1615. "Parse a section.
  1616. Return a list whose CAR is `section' and CDR is a plist
  1617. containing `:begin', `:end', `:contents-begin', `contents-end',
  1618. `:post-blank' and `:post-affiliated' keywords."
  1619. (save-excursion
  1620. ;; Beginning of section is the beginning of the first non-blank
  1621. ;; line after previous headline.
  1622. (let* ((begin (point))
  1623. (end (progn (org-with-limited-levels (outline-next-heading))
  1624. (point)))
  1625. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1626. (line-beginning-position 2)))
  1627. (robust-end (when (> (- pos-before-blank 2) begin)
  1628. (- pos-before-blank 2)))
  1629. (robust-begin (when robust-end begin))
  1630. )
  1631. (list 'section
  1632. (list :begin begin
  1633. :end end
  1634. :contents-begin begin
  1635. :contents-end pos-before-blank
  1636. :robust-begin robust-begin
  1637. :robust-end robust-end
  1638. :post-blank (count-lines pos-before-blank end)
  1639. :post-affiliated begin)))))
  1640. (defun org-element-section-interpreter (_ contents)
  1641. "Interpret section element as Org syntax.
  1642. CONTENTS is the contents of the element."
  1643. contents)
  1644. ;;;; Special Block
  1645. (defun org-element-special-block-parser (limit affiliated)
  1646. "Parse a special block.
  1647. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1648. the buffer position at the beginning of the first affiliated
  1649. keyword and CDR is a plist of affiliated keywords along with
  1650. their value.
  1651. Return a list whose CAR is `special-block' and CDR is a plist
  1652. containing `:type', `:begin', `:end', `:contents-begin',
  1653. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1654. Assume point is at the beginning of the block."
  1655. (let* ((case-fold-search t)
  1656. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1657. (match-string-no-properties 1))))
  1658. (if (not (save-excursion
  1659. (re-search-forward
  1660. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1661. limit t)))
  1662. ;; Incomplete block: parse it as a paragraph.
  1663. (org-element-paragraph-parser limit affiliated)
  1664. (let ((block-end-line (match-beginning 0)))
  1665. (save-excursion
  1666. (let* ((begin (car affiliated))
  1667. (post-affiliated (point))
  1668. ;; Empty blocks have no contents.
  1669. (contents-begin (progn (forward-line)
  1670. (and (< (point) block-end-line)
  1671. (point))))
  1672. (contents-end (and contents-begin block-end-line))
  1673. (pos-before-blank (progn (goto-char block-end-line)
  1674. (forward-line)
  1675. (point)))
  1676. (end (progn (skip-chars-forward " \r\t\n" limit)
  1677. (if (eobp) (point) (line-beginning-position)))))
  1678. (list 'special-block
  1679. (nconc
  1680. (list :type type
  1681. :begin begin
  1682. :end end
  1683. :contents-begin contents-begin
  1684. :contents-end contents-end
  1685. :post-blank (count-lines pos-before-blank end)
  1686. :post-affiliated post-affiliated)
  1687. (cdr affiliated)))))))))
  1688. (defun org-element-special-block-interpreter (special-block contents)
  1689. "Interpret SPECIAL-BLOCK element as Org syntax.
  1690. CONTENTS is the contents of the element."
  1691. (let ((block-type (org-element-property :type special-block)))
  1692. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1693. ;;; Elements
  1694. ;;
  1695. ;; For each element, a parser and an interpreter are also defined.
  1696. ;; Both follow the same naming convention used for greater elements.
  1697. ;;
  1698. ;; Also, as for greater elements, adding a new element type is done
  1699. ;; through the following steps: implement a parser and an interpreter,
  1700. ;; tweak `org-element--current-element' so that it recognizes the new
  1701. ;; type and add that new type to `org-element-all-elements'.
  1702. ;;;; Babel Call
  1703. (defun org-element-babel-call-parser (limit affiliated)
  1704. "Parse a babel call.
  1705. LIMIT bounds the search. AFFILIATED is a list of which car is
  1706. the buffer position at the beginning of the first affiliated
  1707. keyword and cdr is a plist of affiliated keywords along with
  1708. their value.
  1709. Return a list whose car is `babel-call' and cdr is a plist
  1710. containing `:call', `:inside-header', `:arguments',
  1711. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1712. `:post-affiliated' as keywords."
  1713. (save-excursion
  1714. (let* ((begin (car affiliated))
  1715. (post-affiliated (point))
  1716. (before-blank (line-beginning-position 2))
  1717. (value (progn (search-forward ":" before-blank t)
  1718. (skip-chars-forward " \t")
  1719. (org-trim
  1720. (buffer-substring-no-properties
  1721. (point) (line-end-position)))))
  1722. (call
  1723. (or (org-string-nw-p
  1724. (buffer-substring-no-properties
  1725. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1726. (point))))))
  1727. (inside-header (org-element--parse-paired-brackets ?\[))
  1728. (arguments (org-string-nw-p
  1729. (org-element--parse-paired-brackets ?\()))
  1730. (end-header
  1731. (org-string-nw-p
  1732. (org-trim
  1733. (buffer-substring-no-properties (point) (line-end-position)))))
  1734. (end (progn (forward-line)
  1735. (skip-chars-forward " \r\t\n" limit)
  1736. (if (eobp) (point) (line-beginning-position)))))
  1737. (list 'babel-call
  1738. (nconc
  1739. (list :call call
  1740. :inside-header inside-header
  1741. :arguments arguments
  1742. :end-header end-header
  1743. :begin begin
  1744. :end end
  1745. :value value
  1746. :post-blank (count-lines before-blank end)
  1747. :post-affiliated post-affiliated)
  1748. (cdr affiliated))))))
  1749. (defun org-element-babel-call-interpreter (babel-call _)
  1750. "Interpret BABEL-CALL element as Org syntax."
  1751. (concat "#+call: "
  1752. (org-element-property :call babel-call)
  1753. (let ((h (org-element-property :inside-header babel-call)))
  1754. (and h (format "[%s]" h)))
  1755. (concat "(" (org-element-property :arguments babel-call) ")")
  1756. (let ((h (org-element-property :end-header babel-call)))
  1757. (and h (concat " " h)))))
  1758. ;;;; Clock
  1759. (defun org-element-clock-parser (limit)
  1760. "Parse a clock.
  1761. LIMIT bounds the search.
  1762. Return a list whose CAR is `clock' and CDR is a plist containing
  1763. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1764. `:post-affiliated' as keywords."
  1765. (save-excursion
  1766. (let* ((case-fold-search nil)
  1767. (begin (point))
  1768. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1769. (skip-chars-forward " \t")
  1770. (org-element-timestamp-parser)))
  1771. (duration (and (search-forward " => " (line-end-position) t)
  1772. (progn (skip-chars-forward " \t")
  1773. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1774. (match-string-no-properties 1)))
  1775. (status (if duration 'closed 'running))
  1776. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1777. (skip-chars-forward " \r\t\n" limit)
  1778. (skip-chars-backward " \t")
  1779. (unless (bolp) (end-of-line))
  1780. (count-lines before-blank (point))))
  1781. (end (point)))
  1782. (list 'clock
  1783. (list :status status
  1784. :value value
  1785. :duration duration
  1786. :begin begin
  1787. :end end
  1788. :post-blank post-blank
  1789. :post-affiliated begin)))))
  1790. (defun org-element-clock-interpreter (clock _)
  1791. "Interpret CLOCK element as Org syntax."
  1792. (concat "CLOCK: "
  1793. (org-element-timestamp-interpreter
  1794. (org-element-property :value clock) nil)
  1795. (let ((duration (org-element-property :duration clock)))
  1796. (and duration
  1797. (concat " => "
  1798. (apply 'format
  1799. "%2s:%02s"
  1800. (org-split-string duration ":")))))))
  1801. ;;;; Comment
  1802. (defun org-element-comment-parser (limit)
  1803. "Parse a comment.
  1804. LIMIT bounds the search.
  1805. Return a list whose CAR is `comment' and CDR is a plist
  1806. containing `:begin', `:end', `:value', `:post-blank',
  1807. `:post-affiliated' keywords.
  1808. Assume point is at comment beginning."
  1809. (save-excursion
  1810. (let* ((begin (point))
  1811. (value (prog2 (looking-at "[ \t]*# ?")
  1812. (buffer-substring-no-properties
  1813. (match-end 0) (line-end-position))
  1814. (forward-line)))
  1815. (com-end
  1816. ;; Get comments ending.
  1817. (progn
  1818. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1819. ;; Accumulate lines without leading hash and first
  1820. ;; whitespace.
  1821. (setq value
  1822. (concat value
  1823. "\n"
  1824. (buffer-substring-no-properties
  1825. (match-end 0) (line-end-position))))
  1826. (forward-line))
  1827. (point)))
  1828. (end (progn (goto-char com-end)
  1829. (skip-chars-forward " \r\t\n" limit)
  1830. (if (eobp) (point) (line-beginning-position)))))
  1831. (list 'comment
  1832. (list :begin begin
  1833. :end end
  1834. :value value
  1835. :post-blank (count-lines com-end end)
  1836. :post-affiliated begin)))))
  1837. (defun org-element-comment-interpreter (comment _)
  1838. "Interpret COMMENT element as Org syntax.
  1839. CONTENTS is nil."
  1840. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1841. ;;;; Comment Block
  1842. (defun org-element-comment-block-parser (limit affiliated)
  1843. "Parse an export block.
  1844. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1845. the buffer position at the beginning of the first affiliated
  1846. keyword and CDR is a plist of affiliated keywords along with
  1847. their value.
  1848. Return a list whose CAR is `comment-block' and CDR is a plist
  1849. containing `:begin', `:end', `:value', `:post-blank' and
  1850. `:post-affiliated' keywords.
  1851. Assume point is at comment block beginning."
  1852. (let ((case-fold-search t))
  1853. (if (not (save-excursion
  1854. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1855. ;; Incomplete block: parse it as a paragraph.
  1856. (org-element-paragraph-parser limit affiliated)
  1857. (let ((contents-end (match-beginning 0)))
  1858. (save-excursion
  1859. (let* ((begin (car affiliated))
  1860. (post-affiliated (point))
  1861. (contents-begin (progn (forward-line) (point)))
  1862. (pos-before-blank (progn (goto-char contents-end)
  1863. (forward-line)
  1864. (point)))
  1865. (end (progn (skip-chars-forward " \r\t\n" limit)
  1866. (if (eobp) (point) (line-beginning-position))))
  1867. (value (buffer-substring-no-properties
  1868. contents-begin contents-end)))
  1869. (list 'comment-block
  1870. (nconc
  1871. (list :begin begin
  1872. :end end
  1873. :value value
  1874. :post-blank (count-lines pos-before-blank end)
  1875. :post-affiliated post-affiliated)
  1876. (cdr affiliated)))))))))
  1877. (defun org-element-comment-block-interpreter (comment-block _)
  1878. "Interpret COMMENT-BLOCK element as Org syntax."
  1879. (format "#+begin_comment\n%s#+end_comment"
  1880. (org-element-normalize-string
  1881. (org-remove-indentation
  1882. (org-element-property :value comment-block)))))
  1883. ;;;; Diary Sexp
  1884. (defun org-element-diary-sexp-parser (limit affiliated)
  1885. "Parse a diary sexp.
  1886. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1887. the buffer position at the beginning of the first affiliated
  1888. keyword and CDR is a plist of affiliated keywords along with
  1889. their value.
  1890. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1891. containing `:begin', `:end', `:value', `:post-blank' and
  1892. `:post-affiliated' keywords."
  1893. (save-excursion
  1894. (let ((begin (car affiliated))
  1895. (post-affiliated (point))
  1896. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1897. (match-string-no-properties 1)))
  1898. (pos-before-blank (progn (forward-line) (point)))
  1899. (end (progn (skip-chars-forward " \r\t\n" limit)
  1900. (if (eobp) (point) (line-beginning-position)))))
  1901. (list 'diary-sexp
  1902. (nconc
  1903. (list :value value
  1904. :begin begin
  1905. :end end
  1906. :post-blank (count-lines pos-before-blank end)
  1907. :post-affiliated post-affiliated)
  1908. (cdr affiliated))))))
  1909. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1910. "Interpret DIARY-SEXP as Org syntax."
  1911. (org-element-property :value diary-sexp))
  1912. ;;;; Example Block
  1913. (defun org-element-example-block-parser (limit affiliated)
  1914. "Parse an example block.
  1915. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1916. the buffer position at the beginning of the first affiliated
  1917. keyword and CDR is a plist of affiliated keywords along with
  1918. their value.
  1919. Return a list whose CAR is `example-block' and CDR is a plist
  1920. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1921. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1922. `:value', `:post-blank' and `:post-affiliated' keywords."
  1923. (let ((case-fold-search t))
  1924. (if (not (save-excursion
  1925. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1926. ;; Incomplete block: parse it as a paragraph.
  1927. (org-element-paragraph-parser limit affiliated)
  1928. (let ((contents-end (match-beginning 0)))
  1929. (save-excursion
  1930. (let* ((switches
  1931. (progn
  1932. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1933. (match-string-no-properties 1)))
  1934. ;; Switches analysis.
  1935. (number-lines
  1936. (and switches
  1937. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1938. switches)
  1939. (cons
  1940. (if (equal (match-string 1 switches) "-")
  1941. 'new
  1942. 'continued)
  1943. (if (not (match-end 2)) 0
  1944. ;; Subtract 1 to give number of lines before
  1945. ;; first line.
  1946. (1- (string-to-number (match-string 2 switches)))))))
  1947. (preserve-indent
  1948. (and switches (string-match "-i\\>" switches)))
  1949. ;; Should labels be retained in (or stripped from) example
  1950. ;; blocks?
  1951. (retain-labels
  1952. (or (not switches)
  1953. (not (string-match "-r\\>" switches))
  1954. (and number-lines (string-match "-k\\>" switches))))
  1955. ;; What should code-references use - labels or
  1956. ;; line-numbers?
  1957. (use-labels
  1958. (or (not switches)
  1959. (and retain-labels
  1960. (not (string-match "-k\\>" switches)))))
  1961. (label-fmt
  1962. (and switches
  1963. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1964. (match-string 1 switches)))
  1965. ;; Standard block parsing.
  1966. (begin (car affiliated))
  1967. (post-affiliated (point))
  1968. (contents-begin (line-beginning-position 2))
  1969. (value (org-unescape-code-in-string
  1970. (buffer-substring-no-properties
  1971. contents-begin contents-end)))
  1972. (pos-before-blank (progn (goto-char contents-end)
  1973. (forward-line)
  1974. (point)))
  1975. (end (progn (skip-chars-forward " \r\t\n" limit)
  1976. (if (eobp) (point) (line-beginning-position)))))
  1977. (list 'example-block
  1978. (nconc
  1979. (list :begin begin
  1980. :end end
  1981. :value value
  1982. :switches switches
  1983. :number-lines number-lines
  1984. :preserve-indent preserve-indent
  1985. :retain-labels retain-labels
  1986. :use-labels use-labels
  1987. :label-fmt label-fmt
  1988. :post-blank (count-lines pos-before-blank end)
  1989. :post-affiliated post-affiliated)
  1990. (cdr affiliated)))))))))
  1991. (defun org-element-example-block-interpreter (example-block _)
  1992. "Interpret EXAMPLE-BLOCK element as Org syntax."
  1993. (let ((switches (org-element-property :switches example-block))
  1994. (value
  1995. (let ((val (org-element-property :value example-block)))
  1996. (cond
  1997. ((or org-src-preserve-indentation
  1998. (org-element-property :preserve-indent example-block))
  1999. val)
  2000. ((= 0 org-edit-src-content-indentation)
  2001. (org-remove-indentation val))
  2002. (t
  2003. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2004. (replace-regexp-in-string "^[ \t]*\\S-"
  2005. (concat ind "\\&")
  2006. (org-remove-indentation val))))))))
  2007. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  2008. (org-element-normalize-string (org-escape-code-in-string value))
  2009. "#+end_example")))
  2010. ;;;; Export Block
  2011. (defun org-element-export-block-parser (limit affiliated)
  2012. "Parse an export block.
  2013. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2014. the buffer position at the beginning of the first affiliated
  2015. keyword and CDR is a plist of affiliated keywords along with
  2016. their value.
  2017. Return a list whose CAR is `export-block' and CDR is a plist
  2018. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  2019. `:post-affiliated' keywords.
  2020. Assume point is at export-block beginning."
  2021. (let* ((case-fold-search t))
  2022. (if (not (save-excursion
  2023. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  2024. ;; Incomplete block: parse it as a paragraph.
  2025. (org-element-paragraph-parser limit affiliated)
  2026. (save-excursion
  2027. (let* ((contents-end (match-beginning 0))
  2028. (backend
  2029. (progn
  2030. (looking-at
  2031. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  2032. (match-string-no-properties 1)))
  2033. (begin (car affiliated))
  2034. (post-affiliated (point))
  2035. (contents-begin (progn (forward-line) (point)))
  2036. (pos-before-blank (progn (goto-char contents-end)
  2037. (forward-line)
  2038. (point)))
  2039. (end (progn (skip-chars-forward " \r\t\n" limit)
  2040. (if (eobp) (point) (line-beginning-position))))
  2041. (value (org-unescape-code-in-string
  2042. (buffer-substring-no-properties contents-begin
  2043. contents-end))))
  2044. (list 'export-block
  2045. (nconc
  2046. (list :type (and backend (upcase backend))
  2047. :begin begin
  2048. :end end
  2049. :value value
  2050. :post-blank (count-lines pos-before-blank end)
  2051. :post-affiliated post-affiliated)
  2052. (cdr affiliated))))))))
  2053. (defun org-element-export-block-interpreter (export-block _)
  2054. "Interpret EXPORT-BLOCK element as Org syntax."
  2055. (format "#+begin_export %s\n%s#+end_export"
  2056. (org-element-property :type export-block)
  2057. (org-element-property :value export-block)))
  2058. ;;;; Fixed-width
  2059. (defun org-element-fixed-width-parser (limit affiliated)
  2060. "Parse a fixed-width section.
  2061. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2062. the buffer position at the beginning of the first affiliated
  2063. keyword and CDR is a plist of affiliated keywords along with
  2064. their value.
  2065. Return a list whose CAR is `fixed-width' and CDR is a plist
  2066. containing `:begin', `:end', `:value', `:post-blank' and
  2067. `:post-affiliated' keywords.
  2068. Assume point is at the beginning of the fixed-width area."
  2069. (save-excursion
  2070. (let* ((begin (car affiliated))
  2071. (post-affiliated (point))
  2072. (end-area
  2073. (progn
  2074. (while (and (< (point) limit)
  2075. (looking-at "[ \t]*:\\( \\|$\\)"))
  2076. (forward-line))
  2077. (if (bolp) (line-end-position 0) (point))))
  2078. (end (progn (skip-chars-forward " \r\t\n" limit)
  2079. (if (eobp) (point) (line-beginning-position)))))
  2080. (list 'fixed-width
  2081. (nconc
  2082. (list :begin begin
  2083. :end end
  2084. :value (replace-regexp-in-string
  2085. "^[ \t]*: ?" ""
  2086. (buffer-substring-no-properties post-affiliated
  2087. end-area))
  2088. :post-blank (count-lines end-area end)
  2089. :post-affiliated post-affiliated)
  2090. (cdr affiliated))))))
  2091. (defun org-element-fixed-width-interpreter (fixed-width _)
  2092. "Interpret FIXED-WIDTH element as Org syntax."
  2093. (let ((value (org-element-property :value fixed-width)))
  2094. (and value (replace-regexp-in-string "^" ": " value))))
  2095. ;;;; Horizontal Rule
  2096. (defun org-element-horizontal-rule-parser (limit affiliated)
  2097. "Parse an horizontal rule.
  2098. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2099. the buffer position at the beginning of the first affiliated
  2100. keyword and CDR is a plist of affiliated keywords along with
  2101. their value.
  2102. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  2103. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  2104. keywords."
  2105. (save-excursion
  2106. (let ((begin (car affiliated))
  2107. (post-affiliated (point))
  2108. (post-hr (progn (forward-line) (point)))
  2109. (end (progn (skip-chars-forward " \r\t\n" limit)
  2110. (if (eobp) (point) (line-beginning-position)))))
  2111. (list 'horizontal-rule
  2112. (nconc
  2113. (list :begin begin
  2114. :end end
  2115. :post-blank (count-lines post-hr end)
  2116. :post-affiliated post-affiliated)
  2117. (cdr affiliated))))))
  2118. (defun org-element-horizontal-rule-interpreter (&rest _)
  2119. "Interpret HORIZONTAL-RULE element as Org syntax."
  2120. "-----")
  2121. ;;;; Keyword
  2122. (defun org-element-keyword-parser (limit affiliated)
  2123. "Parse a keyword at point.
  2124. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2125. the buffer position at the beginning of the first affiliated
  2126. keyword and CDR is a plist of affiliated keywords along with
  2127. their value.
  2128. Return a list whose CAR is a normalized `keyword' (uppercase) and
  2129. CDR is a plist containing `:key', `:value', `:begin', `:end',
  2130. `:post-blank' and `:post-affiliated' keywords."
  2131. (save-excursion
  2132. ;; An orphaned affiliated keyword is considered as a regular
  2133. ;; keyword. In this case AFFILIATED is nil, so we take care of
  2134. ;; this corner case.
  2135. (let ((begin (or (car affiliated) (point)))
  2136. (post-affiliated (point))
  2137. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  2138. (upcase (match-string-no-properties 1))))
  2139. (value (org-trim (buffer-substring-no-properties
  2140. (match-end 0) (point-at-eol))))
  2141. (pos-before-blank (progn (forward-line) (point)))
  2142. (end (progn (skip-chars-forward " \r\t\n" limit)
  2143. (if (eobp) (point) (line-beginning-position)))))
  2144. (list 'keyword
  2145. (nconc
  2146. (list :key key
  2147. :value value
  2148. :begin begin
  2149. :end end
  2150. :post-blank (count-lines pos-before-blank end)
  2151. :post-affiliated post-affiliated)
  2152. (cdr affiliated))))))
  2153. (defun org-element-keyword-interpreter (keyword _)
  2154. "Interpret KEYWORD element as Org syntax."
  2155. (format "#+%s: %s"
  2156. (downcase (org-element-property :key keyword))
  2157. (org-element-property :value keyword)))
  2158. ;;;; Latex Environment
  2159. (defconst org-element--latex-begin-environment
  2160. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2161. "Regexp matching the beginning of a LaTeX environment.
  2162. The environment is captured by the first group.
  2163. See also `org-element--latex-end-environment'.")
  2164. (defconst org-element--latex-end-environment
  2165. "\\\\end{%s}[ \t]*$"
  2166. "Format string matching the ending of a LaTeX environment.
  2167. See also `org-element--latex-begin-environment'.")
  2168. (defun org-element-latex-environment-parser (limit affiliated)
  2169. "Parse a LaTeX environment.
  2170. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2171. the buffer position at the beginning of the first affiliated
  2172. keyword and CDR is a plist of affiliated keywords along with
  2173. their value.
  2174. Return a list whose CAR is `latex-environment' and CDR is a plist
  2175. containing `:begin', `:end', `:value', `:post-blank' and
  2176. `:post-affiliated' keywords.
  2177. Assume point is at the beginning of the latex environment."
  2178. (save-excursion
  2179. (let ((case-fold-search t)
  2180. (code-begin (point)))
  2181. (looking-at org-element--latex-begin-environment)
  2182. (if (not (re-search-forward (format org-element--latex-end-environment
  2183. (regexp-quote (match-string 1)))
  2184. limit t))
  2185. ;; Incomplete latex environment: parse it as a paragraph.
  2186. (org-element-paragraph-parser limit affiliated)
  2187. (let* ((code-end (progn (forward-line) (point)))
  2188. (begin (car affiliated))
  2189. (value (buffer-substring-no-properties code-begin code-end))
  2190. (end (progn (skip-chars-forward " \r\t\n" limit)
  2191. (if (eobp) (point) (line-beginning-position)))))
  2192. (list 'latex-environment
  2193. (nconc
  2194. (list :begin begin
  2195. :end end
  2196. :value value
  2197. :post-blank (count-lines code-end end)
  2198. :post-affiliated code-begin)
  2199. (cdr affiliated))))))))
  2200. (defun org-element-latex-environment-interpreter (latex-environment _)
  2201. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2202. (org-element-property :value latex-environment))
  2203. ;;;; Node Property
  2204. (defun org-element-node-property-parser (limit)
  2205. "Parse a node-property at point.
  2206. LIMIT bounds the search.
  2207. Return a list whose CAR is `node-property' and CDR is a plist
  2208. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2209. `:post-affiliated' keywords."
  2210. (looking-at org-property-re)
  2211. (let ((case-fold-search t)
  2212. (begin (point))
  2213. (key (match-string-no-properties 2))
  2214. (value (match-string-no-properties 3))
  2215. (end (save-excursion
  2216. (end-of-line)
  2217. (if (re-search-forward org-property-re limit t)
  2218. (line-beginning-position)
  2219. limit))))
  2220. (list 'node-property
  2221. (list :key key
  2222. :value value
  2223. :begin begin
  2224. :end end
  2225. :post-blank 0
  2226. :post-affiliated begin))))
  2227. (defun org-element-node-property-interpreter (node-property _)
  2228. "Interpret NODE-PROPERTY element as Org syntax."
  2229. (format org-property-format
  2230. (format ":%s:" (org-element-property :key node-property))
  2231. (or (org-element-property :value node-property) "")))
  2232. ;;;; Paragraph
  2233. (defun org-element-paragraph-parser (limit affiliated)
  2234. "Parse a paragraph.
  2235. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2236. the buffer position at the beginning of the first affiliated
  2237. keyword and CDR is a plist of affiliated keywords along with
  2238. their value.
  2239. Return a list whose CAR is `paragraph' and CDR is a plist
  2240. containing `:begin', `:end', `:contents-begin' and
  2241. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2242. Assume point is at the beginning of the paragraph."
  2243. (save-excursion
  2244. (let* ((begin (car affiliated))
  2245. (contents-begin (point))
  2246. (before-blank
  2247. (let ((case-fold-search t))
  2248. (end-of-line)
  2249. ;; A matching `org-element-paragraph-separate' is not
  2250. ;; necessarily the end of the paragraph. In particular,
  2251. ;; drawers, blocks or LaTeX environments opening lines
  2252. ;; must be closed. Moreover keywords with a secondary
  2253. ;; value must belong to "dual keywords".
  2254. (while (not
  2255. (cond
  2256. ((not (and (re-search-forward
  2257. org-element-paragraph-separate limit 'move)
  2258. (progn (beginning-of-line) t))))
  2259. ((looking-at org-drawer-regexp)
  2260. (save-excursion
  2261. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2262. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2263. (save-excursion
  2264. (re-search-forward
  2265. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2266. (regexp-quote (match-string 1)))
  2267. limit t)))
  2268. ((looking-at org-element--latex-begin-environment)
  2269. (save-excursion
  2270. (re-search-forward
  2271. (format org-element--latex-end-environment
  2272. (regexp-quote (match-string 1)))
  2273. limit t)))
  2274. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2275. (member-ignore-case (match-string 1)
  2276. org-element-dual-keywords))
  2277. ;; Everything else is unambiguous.
  2278. (t)))
  2279. (end-of-line))
  2280. (if (= (point) limit) limit
  2281. (goto-char (line-beginning-position)))))
  2282. (contents-end (save-excursion
  2283. (skip-chars-backward " \r\t\n" contents-begin)
  2284. (line-beginning-position 2)))
  2285. (end (progn (skip-chars-forward " \r\t\n" limit)
  2286. (if (eobp) (point) (line-beginning-position)))))
  2287. (list 'paragraph
  2288. (nconc
  2289. (list :begin begin
  2290. :end end
  2291. :contents-begin contents-begin
  2292. :contents-end contents-end
  2293. :post-blank (count-lines before-blank end)
  2294. :post-affiliated contents-begin)
  2295. (cdr affiliated))))))
  2296. (defun org-element-paragraph-interpreter (_ contents)
  2297. "Interpret paragraph element as Org syntax.
  2298. CONTENTS is the contents of the element."
  2299. contents)
  2300. ;;;; Planning
  2301. (defun org-element-planning-parser (limit)
  2302. "Parse a planning.
  2303. LIMIT bounds the search.
  2304. Return a list whose CAR is `planning' and CDR is a plist
  2305. containing `:closed', `:deadline', `:scheduled', `:begin',
  2306. `:end', `:post-blank' and `:post-affiliated' keywords."
  2307. (save-excursion
  2308. (let* ((case-fold-search nil)
  2309. (begin (point))
  2310. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2311. (skip-chars-forward " \r\t\n" limit)
  2312. (skip-chars-backward " \t")
  2313. (unless (bolp) (end-of-line))
  2314. (count-lines before-blank (point))))
  2315. (end (point))
  2316. closed deadline scheduled)
  2317. (goto-char begin)
  2318. (while (re-search-forward org-keyword-time-not-clock-regexp end t)
  2319. (goto-char (match-end 1))
  2320. (skip-chars-forward " \t" end)
  2321. (let ((keyword (match-string 1))
  2322. (time (org-element-timestamp-parser)))
  2323. (cond ((equal keyword org-closed-string) (setq closed time))
  2324. ((equal keyword org-deadline-string) (setq deadline time))
  2325. (t (setq scheduled time)))))
  2326. (list 'planning
  2327. (list :closed closed
  2328. :deadline deadline
  2329. :scheduled scheduled
  2330. :begin begin
  2331. :end end
  2332. :post-blank post-blank
  2333. :post-affiliated begin)))))
  2334. (defun org-element-planning-interpreter (planning _)
  2335. "Interpret PLANNING element as Org syntax."
  2336. (mapconcat
  2337. #'identity
  2338. (delq nil
  2339. (list (let ((deadline (org-element-property :deadline planning)))
  2340. (when deadline
  2341. (concat org-deadline-string " "
  2342. (org-element-timestamp-interpreter deadline nil))))
  2343. (let ((scheduled (org-element-property :scheduled planning)))
  2344. (when scheduled
  2345. (concat org-scheduled-string " "
  2346. (org-element-timestamp-interpreter scheduled nil))))
  2347. (let ((closed (org-element-property :closed planning)))
  2348. (when closed
  2349. (concat org-closed-string " "
  2350. (org-element-timestamp-interpreter closed nil))))))
  2351. " "))
  2352. ;;;; Src Block
  2353. (defun org-element-src-block-parser (limit affiliated)
  2354. "Parse a source block.
  2355. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2356. the buffer position at the beginning of the first affiliated
  2357. keyword and CDR is a plist of affiliated keywords along with
  2358. their value.
  2359. Return a list whose CAR is `src-block' and CDR is a plist
  2360. containing `:language', `:switches', `:parameters', `:begin',
  2361. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2362. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2363. `:post-affiliated' keywords.
  2364. Assume point is at the beginning of the block."
  2365. (let ((case-fold-search t))
  2366. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2367. limit t)))
  2368. ;; Incomplete block: parse it as a paragraph.
  2369. (org-element-paragraph-parser limit affiliated)
  2370. (let ((contents-end (match-beginning 0)))
  2371. (save-excursion
  2372. (let* ((begin (car affiliated))
  2373. (post-affiliated (point))
  2374. ;; Get language as a string.
  2375. (language
  2376. (progn
  2377. (looking-at
  2378. "^[ \t]*#\\+BEGIN_SRC\
  2379. \\(?: +\\(\\S-+\\)\\)?\
  2380. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2381. \\(.*\\)[ \t]*$")
  2382. (match-string-no-properties 1)))
  2383. ;; Get switches.
  2384. (switches (match-string-no-properties 2))
  2385. ;; Get parameters.
  2386. (parameters (match-string-no-properties 3))
  2387. ;; Switches analysis.
  2388. (number-lines
  2389. (and switches
  2390. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2391. switches)
  2392. (cons
  2393. (if (equal (match-string 1 switches) "-")
  2394. 'new
  2395. 'continued)
  2396. (if (not (match-end 2)) 0
  2397. ;; Subtract 1 to give number of lines before
  2398. ;; first line.
  2399. (1- (string-to-number (match-string 2 switches)))))))
  2400. (preserve-indent (and switches
  2401. (string-match "-i\\>" switches)))
  2402. (label-fmt
  2403. (and switches
  2404. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2405. (match-string 1 switches)))
  2406. ;; Should labels be retained in (or stripped from)
  2407. ;; source blocks?
  2408. (retain-labels
  2409. (or (not switches)
  2410. (not (string-match "-r\\>" switches))
  2411. (and number-lines (string-match "-k\\>" switches))))
  2412. ;; What should code-references use - labels or
  2413. ;; line-numbers?
  2414. (use-labels
  2415. (or (not switches)
  2416. (and retain-labels
  2417. (not (string-match "-k\\>" switches)))))
  2418. ;; Retrieve code.
  2419. (value (org-unescape-code-in-string
  2420. (buffer-substring-no-properties
  2421. (line-beginning-position 2) contents-end)))
  2422. (pos-before-blank (progn (goto-char contents-end)
  2423. (forward-line)
  2424. (point)))
  2425. ;; Get position after ending blank lines.
  2426. (end (progn (skip-chars-forward " \r\t\n" limit)
  2427. (if (eobp) (point) (line-beginning-position)))))
  2428. (list 'src-block
  2429. (nconc
  2430. (list :language language
  2431. :switches (and (org-string-nw-p switches)
  2432. (org-trim switches))
  2433. :parameters (and (org-string-nw-p parameters)
  2434. (org-trim parameters))
  2435. :begin begin
  2436. :end end
  2437. :number-lines number-lines
  2438. :preserve-indent preserve-indent
  2439. :retain-labels retain-labels
  2440. :use-labels use-labels
  2441. :label-fmt label-fmt
  2442. :value value
  2443. :post-blank (count-lines pos-before-blank end)
  2444. :post-affiliated post-affiliated)
  2445. (cdr affiliated)))))))))
  2446. (defun org-element-src-block-interpreter (src-block _)
  2447. "Interpret SRC-BLOCK element as Org syntax."
  2448. (let ((lang (org-element-property :language src-block))
  2449. (switches (org-element-property :switches src-block))
  2450. (params (org-element-property :parameters src-block))
  2451. (value
  2452. (let ((val (org-element-property :value src-block)))
  2453. (cond
  2454. ((or org-src-preserve-indentation
  2455. (org-element-property :preserve-indent src-block))
  2456. val)
  2457. ((zerop org-edit-src-content-indentation)
  2458. (org-remove-indentation val))
  2459. (t
  2460. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2461. (replace-regexp-in-string "^[ \t]*\\S-"
  2462. (concat ind "\\&")
  2463. (org-remove-indentation val))))))))
  2464. (format "#+begin_src%s\n%s#+end_src"
  2465. (concat (and lang (concat " " lang))
  2466. (and switches (concat " " switches))
  2467. (and params (concat " " params)))
  2468. (org-element-normalize-string (org-escape-code-in-string value)))))
  2469. ;;;; Table
  2470. (defun org-element-table-parser (limit affiliated)
  2471. "Parse a table at point.
  2472. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2473. the buffer position at the beginning of the first affiliated
  2474. keyword and CDR is a plist of affiliated keywords along with
  2475. their value.
  2476. Return a list whose CAR is `table' and CDR is a plist containing
  2477. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2478. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2479. keywords.
  2480. Assume point is at the beginning of the table."
  2481. (save-excursion
  2482. (let* ((case-fold-search t)
  2483. (table-begin (point))
  2484. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2485. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2486. (if (eq type 'org) "" "+")))
  2487. (begin (car affiliated))
  2488. (table-end
  2489. (if (re-search-forward end-re limit 'move)
  2490. (goto-char (match-beginning 0))
  2491. (point)))
  2492. (tblfm (let (acc)
  2493. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2494. (push (match-string-no-properties 1) acc)
  2495. (forward-line))
  2496. acc))
  2497. (pos-before-blank (point))
  2498. (end (progn (skip-chars-forward " \r\t\n" limit)
  2499. (if (eobp) (point) (line-beginning-position)))))
  2500. (list 'table
  2501. (nconc
  2502. (list :begin begin
  2503. :end end
  2504. :type type
  2505. :tblfm tblfm
  2506. ;; Only `org' tables have contents. `table.el' tables
  2507. ;; use a `:value' property to store raw table as
  2508. ;; a string.
  2509. :contents-begin (and (eq type 'org) table-begin)
  2510. :contents-end (and (eq type 'org) table-end)
  2511. :value (and (eq type 'table.el)
  2512. (buffer-substring-no-properties
  2513. table-begin table-end))
  2514. :post-blank (count-lines pos-before-blank end)
  2515. :post-affiliated table-begin)
  2516. (cdr affiliated))))))
  2517. (defun org-element-table-interpreter (table contents)
  2518. "Interpret TABLE element as Org syntax.
  2519. CONTENTS is a string, if table's type is `org', or nil."
  2520. (if (eq (org-element-property :type table) 'table.el)
  2521. (org-remove-indentation (org-element-property :value table))
  2522. (concat (with-temp-buffer (insert contents)
  2523. (org-table-align)
  2524. (buffer-string))
  2525. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2526. (reverse (org-element-property :tblfm table))
  2527. "\n"))))
  2528. ;;;; Table Row
  2529. (defun org-element-table-row-parser (_)
  2530. "Parse table row at point.
  2531. Return a list whose CAR is `table-row' and CDR is a plist
  2532. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2533. `:type', `:post-blank' and `:post-affiliated' keywords."
  2534. (save-excursion
  2535. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2536. (begin (point))
  2537. ;; A table rule has no contents. In that case, ensure
  2538. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2539. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2540. (contents-end (and (eq type 'standard)
  2541. (progn
  2542. (end-of-line)
  2543. (skip-chars-backward " \t")
  2544. (point))))
  2545. (end (line-beginning-position 2)))
  2546. (list 'table-row
  2547. (list :type type
  2548. :begin begin
  2549. :end end
  2550. :contents-begin contents-begin
  2551. :contents-end contents-end
  2552. :post-blank 0
  2553. :post-affiliated begin)))))
  2554. (defun org-element-table-row-interpreter (table-row contents)
  2555. "Interpret TABLE-ROW element as Org syntax.
  2556. CONTENTS is the contents of the table row."
  2557. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2558. (concat "|" contents)))
  2559. ;;;; Verse Block
  2560. (defun org-element-verse-block-parser (limit affiliated)
  2561. "Parse a verse block.
  2562. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2563. the buffer position at the beginning of the first affiliated
  2564. keyword and CDR is a plist of affiliated keywords along with
  2565. their value.
  2566. Return a list whose CAR is `verse-block' and CDR is a plist
  2567. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2568. `:post-blank' and `:post-affiliated' keywords.
  2569. Assume point is at beginning of the block."
  2570. (let ((case-fold-search t))
  2571. (if (not (save-excursion
  2572. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2573. ;; Incomplete block: parse it as a paragraph.
  2574. (org-element-paragraph-parser limit affiliated)
  2575. (let ((contents-end (match-beginning 0)))
  2576. (save-excursion
  2577. (let* ((begin (car affiliated))
  2578. (post-affiliated (point))
  2579. (contents-begin (progn (forward-line) (point)))
  2580. (pos-before-blank (progn (goto-char contents-end)
  2581. (forward-line)
  2582. (point)))
  2583. (end (progn (skip-chars-forward " \r\t\n" limit)
  2584. (if (eobp) (point) (line-beginning-position)))))
  2585. (list 'verse-block
  2586. (nconc
  2587. (list :begin begin
  2588. :end end
  2589. :contents-begin contents-begin
  2590. :contents-end contents-end
  2591. :post-blank (count-lines pos-before-blank end)
  2592. :post-affiliated post-affiliated)
  2593. (cdr affiliated)))))))))
  2594. (defun org-element-verse-block-interpreter (_ contents)
  2595. "Interpret verse-block element as Org syntax.
  2596. CONTENTS is verse block contents."
  2597. (format "#+begin_verse\n%s#+end_verse" contents))
  2598. ;;; Objects
  2599. ;;
  2600. ;; Unlike to elements, raw text can be found between objects. Hence,
  2601. ;; `org-element--object-lex' is provided to find the next object in
  2602. ;; buffer.
  2603. ;;
  2604. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2605. ;; object types they can contain will be specified in
  2606. ;; `org-element-object-restrictions'.
  2607. ;;
  2608. ;; Creating a new type of object requires to alter
  2609. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2610. ;; new type in `org-element-all-objects', and possibly add
  2611. ;; restrictions in `org-element-object-restrictions'.
  2612. ;;;; Bold
  2613. (defun org-element-bold-parser ()
  2614. "Parse bold object at point, if any.
  2615. When at a bold object, return a list whose car is `bold' and cdr
  2616. is a plist with `:begin', `:end', `:contents-begin' and
  2617. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2618. nil.
  2619. Assume point is at the first star marker."
  2620. (save-excursion
  2621. (unless (bolp) (backward-char 1))
  2622. (when (looking-at org-emph-re)
  2623. (let ((begin (match-beginning 2))
  2624. (contents-begin (match-beginning 4))
  2625. (contents-end (match-end 4))
  2626. (post-blank (progn (goto-char (match-end 2))
  2627. (skip-chars-forward " \t")))
  2628. (end (point)))
  2629. (list 'bold
  2630. (list :begin begin
  2631. :end end
  2632. :contents-begin contents-begin
  2633. :contents-end contents-end
  2634. :post-blank post-blank))))))
  2635. (defun org-element-bold-interpreter (_ contents)
  2636. "Interpret bold object as Org syntax.
  2637. CONTENTS is the contents of the object."
  2638. (format "*%s*" contents))
  2639. ;;;; Citation
  2640. (defun org-element-citation-parser ()
  2641. "Parse citation object at point, if any.
  2642. When at a citation object, return a list whose car is `citation'
  2643. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2644. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2645. keywords. Otherwise, return nil.
  2646. Assume point is at the beginning of the citation."
  2647. (when (looking-at org-element-citation-prefix-re)
  2648. (let* ((begin (point))
  2649. (style (and (match-end 1)
  2650. (match-string-no-properties 1)))
  2651. ;; Ignore blanks between cite type and prefix or key.
  2652. (start (match-end 0))
  2653. (closing (with-syntax-table org-element--pair-square-table
  2654. (ignore-errors (scan-lists begin 1 0)))))
  2655. (save-excursion
  2656. (when (and closing
  2657. (re-search-forward org-element-citation-key-re closing t))
  2658. ;; Find prefix, if any.
  2659. (let ((first-key-end (match-end 0))
  2660. (types (org-element-restriction 'citation-reference))
  2661. (cite
  2662. (list 'citation
  2663. (list :style style
  2664. :begin begin
  2665. :post-blank (progn
  2666. (goto-char closing)
  2667. (skip-chars-forward " \t"))
  2668. :end (point)))))
  2669. ;; `:contents-begin' depends on the presence of
  2670. ;; a non-empty common prefix.
  2671. (goto-char first-key-end)
  2672. (if (not (search-backward ";" start t))
  2673. (org-element-put-property cite :contents-begin start)
  2674. (when (< start (point))
  2675. (org-element-put-property
  2676. cite :prefix
  2677. (org-element--parse-objects start (point) nil types cite)))
  2678. (forward-char)
  2679. (org-element-put-property cite :contents-begin (point)))
  2680. ;; `:contents-end' depends on the presence of a non-empty
  2681. ;; common suffix.
  2682. (goto-char (1- closing))
  2683. (skip-chars-backward " \r\t\n")
  2684. (let ((end (point)))
  2685. (if (or (not (search-backward ";" first-key-end t))
  2686. (re-search-forward org-element-citation-key-re end t))
  2687. (org-element-put-property cite :contents-end end)
  2688. (forward-char)
  2689. (when (< (point) end)
  2690. (org-element-put-property
  2691. cite :suffix
  2692. (org-element--parse-objects (point) end nil types cite)))
  2693. (org-element-put-property cite :contents-end (point))))
  2694. cite))))))
  2695. (defun org-element-citation-interpreter (citation contents)
  2696. "Interpret CITATION object as Org syntax.
  2697. CONTENTS is the contents of the object, as a string."
  2698. (let ((prefix (org-element-property :prefix citation))
  2699. (suffix (org-element-property :suffix citation))
  2700. (style (org-element-property :style citation)))
  2701. (concat "[cite"
  2702. (and style (concat "/" style))
  2703. ":"
  2704. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2705. (if suffix
  2706. (concat contents (org-element-interpret-data suffix))
  2707. ;; Remove spurious semicolon.
  2708. (substring contents nil -1))
  2709. "]")))
  2710. ;;;; Citation Reference
  2711. (defun org-element-citation-reference-parser ()
  2712. "Parse citation reference object at point, if any.
  2713. When at a reference, return a list whose car is
  2714. `citation-reference', and cdr is a plist with `:key',
  2715. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2716. Assume point is at the beginning of the reference."
  2717. (save-excursion
  2718. (let ((begin (point)))
  2719. (when (re-search-forward org-element-citation-key-re nil t)
  2720. (let* ((key (match-string-no-properties 1))
  2721. (key-start (match-beginning 0))
  2722. (key-end (match-end 0))
  2723. (separator (search-forward ";" nil t))
  2724. (end (or separator (point-max)))
  2725. (suffix-end (if separator (1- end) end))
  2726. (types (org-element-restriction 'citation-reference))
  2727. (reference
  2728. (list 'citation-reference
  2729. (list :key key
  2730. :begin begin
  2731. :end end
  2732. :post-blank 0))))
  2733. (when (< begin key-start)
  2734. (org-element-put-property
  2735. reference :prefix
  2736. (org-element--parse-objects begin key-start nil types reference)))
  2737. (when (< key-end suffix-end)
  2738. (org-element-put-property
  2739. reference :suffix
  2740. (org-element--parse-objects key-end suffix-end nil types reference)))
  2741. reference)))))
  2742. (defun org-element-citation-reference-interpreter (citation-reference _)
  2743. "Interpret CITATION-REFERENCE object as Org syntax."
  2744. (concat (org-element-interpret-data
  2745. (org-element-property :prefix citation-reference))
  2746. "@" (org-element-property :key citation-reference)
  2747. (org-element-interpret-data
  2748. (org-element-property :suffix citation-reference))
  2749. ";"))
  2750. ;;;; Code
  2751. (defun org-element-code-parser ()
  2752. "Parse code object at point, if any.
  2753. When at a code object, return a list whose car is `code' and cdr
  2754. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2755. keywords. Otherwise, return nil.
  2756. Assume point is at the first tilde marker."
  2757. (save-excursion
  2758. (unless (bolp) (backward-char 1))
  2759. (when (looking-at org-verbatim-re)
  2760. (let ((begin (match-beginning 2))
  2761. (value (match-string-no-properties 4))
  2762. (post-blank (progn (goto-char (match-end 2))
  2763. (skip-chars-forward " \t")))
  2764. (end (point)))
  2765. (list 'code
  2766. (list :value value
  2767. :begin begin
  2768. :end end
  2769. :post-blank post-blank))))))
  2770. (defun org-element-code-interpreter (code _)
  2771. "Interpret CODE object as Org syntax."
  2772. (format "~%s~" (org-element-property :value code)))
  2773. ;;;; Entity
  2774. (defun org-element-entity-parser ()
  2775. "Parse entity at point, if any.
  2776. When at an entity, return a list whose car is `entity' and cdr
  2777. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2778. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2779. `:post-blank' as keywords. Otherwise, return nil.
  2780. Assume point is at the beginning of the entity."
  2781. (catch 'no-object
  2782. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2783. (save-excursion
  2784. (let* ((value (or (org-entity-get (match-string 1))
  2785. (throw 'no-object nil)))
  2786. (begin (match-beginning 0))
  2787. (bracketsp (string= (match-string 2) "{}"))
  2788. (post-blank (progn (goto-char (match-end 1))
  2789. (when bracketsp (forward-char 2))
  2790. (skip-chars-forward " \t")))
  2791. (end (point)))
  2792. (list 'entity
  2793. (list :name (car value)
  2794. :latex (nth 1 value)
  2795. :latex-math-p (nth 2 value)
  2796. :html (nth 3 value)
  2797. :ascii (nth 4 value)
  2798. :latin1 (nth 5 value)
  2799. :utf-8 (nth 6 value)
  2800. :begin begin
  2801. :end end
  2802. :use-brackets-p bracketsp
  2803. :post-blank post-blank)))))))
  2804. (defun org-element-entity-interpreter (entity _)
  2805. "Interpret ENTITY object as Org syntax."
  2806. (concat "\\"
  2807. (org-element-property :name entity)
  2808. (when (org-element-property :use-brackets-p entity) "{}")))
  2809. ;;;; Export Snippet
  2810. (defun org-element-export-snippet-parser ()
  2811. "Parse export snippet at point.
  2812. When at an export snippet, return a list whose car is
  2813. `export-snippet' and cdr a plist with `:begin', `:end',
  2814. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2815. return nil.
  2816. Assume point is at the beginning of the snippet."
  2817. (save-excursion
  2818. (let (contents-end)
  2819. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2820. (setq contents-end
  2821. (save-match-data (goto-char (match-end 0))
  2822. (re-search-forward "@@" nil t)
  2823. (match-beginning 0))))
  2824. (let* ((begin (match-beginning 0))
  2825. (back-end (match-string-no-properties 1))
  2826. (value (buffer-substring-no-properties
  2827. (match-end 0) contents-end))
  2828. (post-blank (skip-chars-forward " \t"))
  2829. (end (point)))
  2830. (list 'export-snippet
  2831. (list :back-end back-end
  2832. :value value
  2833. :begin begin
  2834. :end end
  2835. :post-blank post-blank)))))))
  2836. (defun org-element-export-snippet-interpreter (export-snippet _)
  2837. "Interpret EXPORT-SNIPPET object as Org syntax."
  2838. (format "@@%s:%s@@"
  2839. (org-element-property :back-end export-snippet)
  2840. (org-element-property :value export-snippet)))
  2841. ;;;; Footnote Reference
  2842. (defun org-element-footnote-reference-parser ()
  2843. "Parse footnote reference at point, if any.
  2844. When at a footnote reference, return a list whose car is
  2845. `footnote-reference' and cdr a plist with `:label', `:type',
  2846. `:begin', `:end', `:contents-begin', `:contents-end' and
  2847. `:post-blank' as keywords. Otherwise, return nil."
  2848. (when (looking-at org-footnote-re)
  2849. (let ((closing (with-syntax-table org-element--pair-square-table
  2850. (ignore-errors (scan-lists (point) 1 0)))))
  2851. (when closing
  2852. (save-excursion
  2853. (let* ((begin (point))
  2854. (label (match-string-no-properties 1))
  2855. (inner-begin (match-end 0))
  2856. (inner-end (1- closing))
  2857. (type (if (match-end 2) 'inline 'standard))
  2858. (post-blank (progn (goto-char closing)
  2859. (skip-chars-forward " \t")))
  2860. (end (point)))
  2861. (list 'footnote-reference
  2862. (list :label label
  2863. :type type
  2864. :begin begin
  2865. :end end
  2866. :contents-begin (and (eq type 'inline) inner-begin)
  2867. :contents-end (and (eq type 'inline) inner-end)
  2868. :post-blank post-blank))))))))
  2869. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2870. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2871. CONTENTS is its definition, when inline, or nil."
  2872. (format "[fn:%s%s]"
  2873. (or (org-element-property :label footnote-reference) "")
  2874. (if contents (concat ":" contents) "")))
  2875. ;;;; Inline Babel Call
  2876. (defun org-element-inline-babel-call-parser ()
  2877. "Parse inline babel call at point, if any.
  2878. When at an inline babel call, return a list whose car is
  2879. `inline-babel-call' and cdr a plist with `:call',
  2880. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2881. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2882. Assume point is at the beginning of the babel call."
  2883. (save-excursion
  2884. (catch :no-object
  2885. (when (let ((case-fold-search nil))
  2886. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2887. (goto-char (match-end 1))
  2888. (let* ((begin (match-beginning 0))
  2889. (call (match-string-no-properties 1))
  2890. (inside-header
  2891. (let ((p (org-element--parse-paired-brackets ?\[)))
  2892. (and (org-string-nw-p p)
  2893. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2894. (arguments (org-string-nw-p
  2895. (or (org-element--parse-paired-brackets ?\()
  2896. ;; Parenthesis are mandatory.
  2897. (throw :no-object nil))))
  2898. (end-header
  2899. (let ((p (org-element--parse-paired-brackets ?\[)))
  2900. (and (org-string-nw-p p)
  2901. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2902. (value (buffer-substring-no-properties begin (point)))
  2903. (post-blank (skip-chars-forward " \t"))
  2904. (end (point)))
  2905. (list 'inline-babel-call
  2906. (list :call call
  2907. :inside-header inside-header
  2908. :arguments arguments
  2909. :end-header end-header
  2910. :begin begin
  2911. :end end
  2912. :value value
  2913. :post-blank post-blank)))))))
  2914. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2915. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2916. (concat "call_"
  2917. (org-element-property :call inline-babel-call)
  2918. (let ((h (org-element-property :inside-header inline-babel-call)))
  2919. (and h (format "[%s]" h)))
  2920. "(" (org-element-property :arguments inline-babel-call) ")"
  2921. (let ((h (org-element-property :end-header inline-babel-call)))
  2922. (and h (format "[%s]" h)))))
  2923. ;;;; Inline Src Block
  2924. (defun org-element-inline-src-block-parser ()
  2925. "Parse inline source block at point, if any.
  2926. When at an inline source block, return a list whose car is
  2927. `inline-src-block' and cdr a plist with `:begin', `:end',
  2928. `:language', `:value', `:parameters' and `:post-blank' as
  2929. keywords. Otherwise, return nil.
  2930. Assume point is at the beginning of the inline source block."
  2931. (save-excursion
  2932. (catch :no-object
  2933. (when (let ((case-fold-search nil))
  2934. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2935. (goto-char (match-end 1))
  2936. (let ((begin (match-beginning 0))
  2937. (language (match-string-no-properties 1))
  2938. (parameters
  2939. (let ((p (org-element--parse-paired-brackets ?\[)))
  2940. (and (org-string-nw-p p)
  2941. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2942. (value (or (org-element--parse-paired-brackets ?\{)
  2943. (throw :no-object nil)))
  2944. (post-blank (skip-chars-forward " \t")))
  2945. (list 'inline-src-block
  2946. (list :language language
  2947. :value value
  2948. :parameters parameters
  2949. :begin begin
  2950. :end (point)
  2951. :post-blank post-blank)))))))
  2952. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2953. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2954. (let ((language (org-element-property :language inline-src-block))
  2955. (arguments (org-element-property :parameters inline-src-block))
  2956. (body (org-element-property :value inline-src-block)))
  2957. (format "src_%s%s{%s}"
  2958. language
  2959. (if arguments (format "[%s]" arguments) "")
  2960. body)))
  2961. ;;;; Italic
  2962. (defun org-element-italic-parser ()
  2963. "Parse italic object at point, if any.
  2964. When at an italic object, return a list whose car is `italic' and
  2965. cdr is a plist with `:begin', `:end', `:contents-begin' and
  2966. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2967. nil.
  2968. Assume point is at the first slash marker."
  2969. (save-excursion
  2970. (unless (bolp) (backward-char 1))
  2971. (when (looking-at org-emph-re)
  2972. (let ((begin (match-beginning 2))
  2973. (contents-begin (match-beginning 4))
  2974. (contents-end (match-end 4))
  2975. (post-blank (progn (goto-char (match-end 2))
  2976. (skip-chars-forward " \t")))
  2977. (end (point)))
  2978. (list 'italic
  2979. (list :begin begin
  2980. :end end
  2981. :contents-begin contents-begin
  2982. :contents-end contents-end
  2983. :post-blank post-blank))))))
  2984. (defun org-element-italic-interpreter (_ contents)
  2985. "Interpret italic object as Org syntax.
  2986. CONTENTS is the contents of the object."
  2987. (format "/%s/" contents))
  2988. ;;;; Latex Fragment
  2989. (defun org-element-latex-fragment-parser ()
  2990. "Parse LaTeX fragment at point, if any.
  2991. When at a LaTeX fragment, return a list whose car is
  2992. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  2993. and `:post-blank' as keywords. Otherwise, return nil.
  2994. Assume point is at the beginning of the LaTeX fragment."
  2995. (catch 'no-object
  2996. (save-excursion
  2997. (let* ((begin (point))
  2998. (after-fragment
  2999. (cond
  3000. ((not (eq ?$ (char-after)))
  3001. (pcase (char-after (1+ (point)))
  3002. (?\( (search-forward "\\)" nil t))
  3003. (?\[ (search-forward "\\]" nil t))
  3004. (_
  3005. ;; Macro.
  3006. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  3007. \\|\\({[^{}\n]*}\\)\\)*")
  3008. (match-end 0)))))
  3009. ((eq ?$ (char-after (1+ (point))))
  3010. (search-forward "$$" nil t 2))
  3011. (t
  3012. (and (not (eq ?$ (char-before)))
  3013. (not (memq (char-after (1+ (point)))
  3014. '(?\s ?\t ?\n ?, ?. ?\;)))
  3015. (search-forward "$" nil t 2)
  3016. (not (memq (char-before (match-beginning 0))
  3017. '(?\s ?\t ?\n ?, ?.)))
  3018. (looking-at-p
  3019. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  3020. (point)))))
  3021. (post-blank
  3022. (if (not after-fragment) (throw 'no-object nil)
  3023. (goto-char after-fragment)
  3024. (skip-chars-forward " \t")))
  3025. (end (point)))
  3026. (list 'latex-fragment
  3027. (list :value (buffer-substring-no-properties begin after-fragment)
  3028. :begin begin
  3029. :end end
  3030. :post-blank post-blank))))))
  3031. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  3032. "Interpret LATEX-FRAGMENT object as Org syntax."
  3033. (org-element-property :value latex-fragment))
  3034. ;;;; Line Break
  3035. (defun org-element-line-break-parser ()
  3036. "Parse line break at point, if any.
  3037. When at a line break, return a list whose car is `line-break',
  3038. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  3039. Otherwise, return nil.
  3040. Assume point is at the beginning of the line break."
  3041. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  3042. (not (eq (char-before) ?\\)))
  3043. (list 'line-break
  3044. (list :begin (point)
  3045. :end (line-beginning-position 2)
  3046. :post-blank 0))))
  3047. (defun org-element-line-break-interpreter (&rest _)
  3048. "Interpret LINE-BREAK object as Org syntax."
  3049. "\\\\\n")
  3050. ;;;; Link
  3051. (defun org-element-link-parser ()
  3052. "Parse link at point, if any.
  3053. When at a link, return a list whose car is `link' and cdr a plist
  3054. with `:type', `:path', `:format', `:raw-link', `:application',
  3055. `:search-option', `:begin', `:end', `:contents-begin',
  3056. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  3057. nil.
  3058. Assume point is at the beginning of the link."
  3059. (catch 'no-object
  3060. (let ((begin (point))
  3061. end contents-begin contents-end link-end post-blank path type format
  3062. raw-link search-option application)
  3063. (cond
  3064. ;; Type 1: Text targeted from a radio target.
  3065. ((and org-target-link-regexp
  3066. (save-excursion (or (bolp) (backward-char))
  3067. (looking-at org-target-link-regexp)))
  3068. (setq type "radio")
  3069. (setq format 'plain)
  3070. (setq link-end (match-end 1))
  3071. (setq path (match-string-no-properties 1))
  3072. (setq contents-begin (match-beginning 1))
  3073. (setq contents-end (match-end 1)))
  3074. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  3075. ((looking-at org-link-bracket-re)
  3076. (setq format 'bracket)
  3077. (setq contents-begin (match-beginning 2))
  3078. (setq contents-end (match-end 2))
  3079. (setq link-end (match-end 0))
  3080. ;; RAW-LINK is the original link. Decode any encoding.
  3081. ;; Expand any abbreviation in it.
  3082. ;;
  3083. ;; Also treat any newline character and associated
  3084. ;; indentation as a single space character. This is not
  3085. ;; compatible with RFC 3986, which requires to ignore
  3086. ;; them altogether. However, doing so would require
  3087. ;; users to encode spaces on the fly when writing links
  3088. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  3089. ;; [[shell:ls *.org]], which defeats Org's focus on
  3090. ;; simplicity.
  3091. (setq raw-link (org-link-expand-abbrev
  3092. (org-link-unescape
  3093. (replace-regexp-in-string
  3094. "[ \t]*\n[ \t]*" " "
  3095. (match-string-no-properties 1)))))
  3096. ;; Determine TYPE of link and set PATH accordingly. According
  3097. ;; to RFC 3986, remove whitespaces from URI in external links.
  3098. ;; In internal ones, treat indentation as a single space.
  3099. (cond
  3100. ;; File type.
  3101. ((or (file-name-absolute-p raw-link)
  3102. (string-match "\\`\\.\\.?/" raw-link))
  3103. (setq type "file")
  3104. (setq path raw-link))
  3105. ;; Explicit type (http, irc, bbdb...).
  3106. ((string-match org-link-types-re raw-link)
  3107. (setq type (match-string 1 raw-link))
  3108. (setq path (substring raw-link (match-end 0))))
  3109. ;; Code-ref type: PATH is the name of the reference.
  3110. ((and (string-match-p "\\`(" raw-link)
  3111. (string-match-p ")\\'" raw-link))
  3112. (setq type "coderef")
  3113. (setq path (substring raw-link 1 -1)))
  3114. ;; Custom-id type: PATH is the name of the custom id.
  3115. ((= (string-to-char raw-link) ?#)
  3116. (setq type "custom-id")
  3117. (setq path (substring raw-link 1)))
  3118. ;; Fuzzy type: Internal link either matches a target, an
  3119. ;; headline name or nothing. PATH is the target or
  3120. ;; headline's name.
  3121. (t
  3122. (setq type "fuzzy")
  3123. (setq path raw-link))))
  3124. ;; Type 3: Plain link, e.g., https://orgmode.org
  3125. ((looking-at org-link-plain-re)
  3126. (setq format 'plain)
  3127. (setq raw-link (match-string-no-properties 0))
  3128. (setq type (match-string-no-properties 1))
  3129. (setq link-end (match-end 0))
  3130. (setq path (match-string-no-properties 2)))
  3131. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  3132. ;; bracket links, follow RFC 3986 and remove any extra
  3133. ;; whitespace in URI.
  3134. ((looking-at org-link-angle-re)
  3135. (setq format 'angle)
  3136. (setq type (match-string-no-properties 1))
  3137. (setq link-end (match-end 0))
  3138. (setq raw-link
  3139. (buffer-substring-no-properties
  3140. (match-beginning 1) (match-end 2)))
  3141. (setq path (replace-regexp-in-string
  3142. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  3143. (t (throw 'no-object nil)))
  3144. ;; In any case, deduce end point after trailing white space from
  3145. ;; LINK-END variable.
  3146. (save-excursion
  3147. (setq post-blank
  3148. (progn (goto-char link-end) (skip-chars-forward " \t")))
  3149. (setq end (point)))
  3150. ;; Special "file"-type link processing. Extract opening
  3151. ;; application and search option, if any. Also normalize URI.
  3152. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  3153. (setq application (match-string 1 type))
  3154. (setq type "file")
  3155. (when (string-match "::\\(.*\\)\\'" path)
  3156. (setq search-option (match-string 1 path))
  3157. (setq path (replace-match "" nil nil path)))
  3158. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3159. ;; Translate link, if `org-link-translation-function' is set.
  3160. (let ((trans (and (functionp org-link-translation-function)
  3161. (funcall org-link-translation-function type path))))
  3162. (when trans
  3163. (setq type (car trans))
  3164. (setq path (cdr trans))))
  3165. (list 'link
  3166. (list :type type
  3167. :path path
  3168. :format format
  3169. :raw-link (or raw-link path)
  3170. :application application
  3171. :search-option search-option
  3172. :begin begin
  3173. :end end
  3174. :contents-begin contents-begin
  3175. :contents-end contents-end
  3176. :post-blank post-blank)))))
  3177. (defun org-element-link-interpreter (link contents)
  3178. "Interpret LINK object as Org syntax.
  3179. CONTENTS is the contents of the object, or nil."
  3180. (let ((type (org-element-property :type link))
  3181. (path (org-element-property :path link)))
  3182. (if (string= type "radio") path
  3183. (let ((fmt (pcase (org-element-property :format link)
  3184. ;; Links with contents and internal links have to
  3185. ;; use bracket syntax. Ignore `:format' in these
  3186. ;; cases. This is also the default syntax when the
  3187. ;; property is not defined, e.g., when the object
  3188. ;; was crafted by the user.
  3189. ((guard contents)
  3190. (format "[[%%s][%s]]"
  3191. ;; Since this is going to be used as
  3192. ;; a format string, escape percent signs
  3193. ;; in description.
  3194. (replace-regexp-in-string "%" "%%" contents)))
  3195. ((or `bracket
  3196. `nil
  3197. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3198. "[[%s]]")
  3199. ;; Otherwise, just obey to `:format'.
  3200. (`angle "<%s>")
  3201. (`plain "%s")
  3202. (f (error "Wrong `:format' value: %s" f)))))
  3203. (format fmt
  3204. (pcase type
  3205. ("coderef" (format "(%s)" path))
  3206. ("custom-id" (concat "#" path))
  3207. ("file"
  3208. (let ((app (org-element-property :application link))
  3209. (opt (org-element-property :search-option link)))
  3210. (concat type (and app (concat "+" app)) ":"
  3211. path
  3212. (and opt (concat "::" opt)))))
  3213. ("fuzzy" path)
  3214. (_ (concat type ":" path))))))))
  3215. ;;;; Macro
  3216. (defun org-element-macro-parser ()
  3217. "Parse macro at point, if any.
  3218. When at a macro, return a list whose car is `macro' and cdr
  3219. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3220. `:post-blank' as keywords. Otherwise, return nil.
  3221. Assume point is at the macro."
  3222. (save-excursion
  3223. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3224. (let ((begin (point))
  3225. (key (downcase (match-string-no-properties 1)))
  3226. (value (match-string-no-properties 0))
  3227. (post-blank (progn (goto-char (match-end 0))
  3228. (skip-chars-forward " \t")))
  3229. (end (point))
  3230. (args (pcase (match-string-no-properties 3)
  3231. (`nil nil)
  3232. (a (org-macro-extract-arguments
  3233. (replace-regexp-in-string
  3234. "[ \t\r\n]+" " " (org-trim a)))))))
  3235. (list 'macro
  3236. (list :key key
  3237. :value value
  3238. :args args
  3239. :begin begin
  3240. :end end
  3241. :post-blank post-blank))))))
  3242. (defun org-element-macro-interpreter (macro _)
  3243. "Interpret MACRO object as Org syntax."
  3244. (format "{{{%s%s}}}"
  3245. (org-element-property :key macro)
  3246. (pcase (org-element-property :args macro)
  3247. (`nil "")
  3248. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3249. ;;;; Radio-target
  3250. (defun org-element-radio-target-parser ()
  3251. "Parse radio target at point, if any.
  3252. When at a radio target, return a list whose car is `radio-target'
  3253. and cdr a plist with `:begin', `:end', `:contents-begin',
  3254. `:contents-end', `:value' and `:post-blank' as keywords.
  3255. Otherwise, return nil.
  3256. Assume point is at the radio target."
  3257. (save-excursion
  3258. (when (looking-at org-radio-target-regexp)
  3259. (let ((begin (point))
  3260. (contents-begin (match-beginning 1))
  3261. (contents-end (match-end 1))
  3262. (value (match-string-no-properties 1))
  3263. (post-blank (progn (goto-char (match-end 0))
  3264. (skip-chars-forward " \t")))
  3265. (end (point)))
  3266. (list 'radio-target
  3267. (list :begin begin
  3268. :end end
  3269. :contents-begin contents-begin
  3270. :contents-end contents-end
  3271. :post-blank post-blank
  3272. :value value))))))
  3273. (defun org-element-radio-target-interpreter (_ contents)
  3274. "Interpret target object as Org syntax.
  3275. CONTENTS is the contents of the object."
  3276. (concat "<<<" contents ">>>"))
  3277. ;;;; Statistics Cookie
  3278. (defun org-element-statistics-cookie-parser ()
  3279. "Parse statistics cookie at point, if any.
  3280. When at a statistics cookie, return a list whose car is
  3281. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3282. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3283. Assume point is at the beginning of the statistics-cookie."
  3284. (save-excursion
  3285. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3286. (let* ((begin (point))
  3287. (value (buffer-substring-no-properties
  3288. (match-beginning 0) (match-end 0)))
  3289. (post-blank (progn (goto-char (match-end 0))
  3290. (skip-chars-forward " \t")))
  3291. (end (point)))
  3292. (list 'statistics-cookie
  3293. (list :begin begin
  3294. :end end
  3295. :value value
  3296. :post-blank post-blank))))))
  3297. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3298. "Interpret STATISTICS-COOKIE object as Org syntax."
  3299. (org-element-property :value statistics-cookie))
  3300. ;;;; Strike-Through
  3301. (defun org-element-strike-through-parser ()
  3302. "Parse strike-through object at point, if any.
  3303. When at a strike-through object, return a list whose car is
  3304. `strike-through' and cdr is a plist with `:begin', `:end',
  3305. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3306. Otherwise, return nil.
  3307. Assume point is at the first plus sign marker."
  3308. (save-excursion
  3309. (unless (bolp) (backward-char 1))
  3310. (when (looking-at org-emph-re)
  3311. (let ((begin (match-beginning 2))
  3312. (contents-begin (match-beginning 4))
  3313. (contents-end (match-end 4))
  3314. (post-blank (progn (goto-char (match-end 2))
  3315. (skip-chars-forward " \t")))
  3316. (end (point)))
  3317. (list 'strike-through
  3318. (list :begin begin
  3319. :end end
  3320. :contents-begin contents-begin
  3321. :contents-end contents-end
  3322. :post-blank post-blank))))))
  3323. (defun org-element-strike-through-interpreter (_ contents)
  3324. "Interpret strike-through object as Org syntax.
  3325. CONTENTS is the contents of the object."
  3326. (format "+%s+" contents))
  3327. ;;;; Subscript
  3328. (defun org-element-subscript-parser ()
  3329. "Parse subscript at point, if any.
  3330. When at a subscript object, return a list whose car is
  3331. `subscript' and cdr a plist with `:begin', `:end',
  3332. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3333. `:post-blank' as keywords. Otherwise, return nil.
  3334. Assume point is at the underscore."
  3335. (save-excursion
  3336. (unless (bolp) (backward-char))
  3337. (when (looking-at org-match-substring-regexp)
  3338. (let ((bracketsp (match-beginning 4))
  3339. (begin (match-beginning 2))
  3340. (contents-begin (or (match-beginning 4)
  3341. (match-beginning 3)))
  3342. (contents-end (or (match-end 4) (match-end 3)))
  3343. (post-blank (progn (goto-char (match-end 0))
  3344. (skip-chars-forward " \t")))
  3345. (end (point)))
  3346. (list 'subscript
  3347. (list :begin begin
  3348. :end end
  3349. :use-brackets-p bracketsp
  3350. :contents-begin contents-begin
  3351. :contents-end contents-end
  3352. :post-blank post-blank))))))
  3353. (defun org-element-subscript-interpreter (subscript contents)
  3354. "Interpret SUBSCRIPT object as Org syntax.
  3355. CONTENTS is the contents of the object."
  3356. (format
  3357. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3358. contents))
  3359. ;;;; Superscript
  3360. (defun org-element-superscript-parser ()
  3361. "Parse superscript at point, if any.
  3362. When at a superscript object, return a list whose car is
  3363. `superscript' and cdr a plist with `:begin', `:end',
  3364. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3365. `:post-blank' as keywords. Otherwise, return nil.
  3366. Assume point is at the caret."
  3367. (save-excursion
  3368. (unless (bolp) (backward-char))
  3369. (when (looking-at org-match-substring-regexp)
  3370. (let ((bracketsp (match-beginning 4))
  3371. (begin (match-beginning 2))
  3372. (contents-begin (or (match-beginning 4)
  3373. (match-beginning 3)))
  3374. (contents-end (or (match-end 4) (match-end 3)))
  3375. (post-blank (progn (goto-char (match-end 0))
  3376. (skip-chars-forward " \t")))
  3377. (end (point)))
  3378. (list 'superscript
  3379. (list :begin begin
  3380. :end end
  3381. :use-brackets-p bracketsp
  3382. :contents-begin contents-begin
  3383. :contents-end contents-end
  3384. :post-blank post-blank))))))
  3385. (defun org-element-superscript-interpreter (superscript contents)
  3386. "Interpret SUPERSCRIPT object as Org syntax.
  3387. CONTENTS is the contents of the object."
  3388. (format
  3389. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3390. contents))
  3391. ;;;; Table Cell
  3392. (defun org-element-table-cell-parser ()
  3393. "Parse table cell at point.
  3394. Return a list whose car is `table-cell' and cdr is a plist
  3395. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3396. and `:post-blank' keywords."
  3397. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3398. (let* ((begin (match-beginning 0))
  3399. (end (match-end 0))
  3400. (contents-begin (match-beginning 1))
  3401. (contents-end (match-end 1)))
  3402. (list 'table-cell
  3403. (list :begin begin
  3404. :end end
  3405. :contents-begin contents-begin
  3406. :contents-end contents-end
  3407. :post-blank 0))))
  3408. (defun org-element-table-cell-interpreter (_ contents)
  3409. "Interpret table-cell element as Org syntax.
  3410. CONTENTS is the contents of the cell, or nil."
  3411. (concat " " contents " |"))
  3412. ;;;; Target
  3413. (defun org-element-target-parser ()
  3414. "Parse target at point, if any.
  3415. When at a target, return a list whose car is `target' and cdr
  3416. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3417. keywords. Otherwise, return nil.
  3418. Assume point is at the target."
  3419. (save-excursion
  3420. (when (looking-at org-target-regexp)
  3421. (let ((begin (point))
  3422. (value (match-string-no-properties 1))
  3423. (post-blank (progn (goto-char (match-end 0))
  3424. (skip-chars-forward " \t")))
  3425. (end (point)))
  3426. (list 'target
  3427. (list :begin begin
  3428. :end end
  3429. :value value
  3430. :post-blank post-blank))))))
  3431. (defun org-element-target-interpreter (target _)
  3432. "Interpret TARGET object as Org syntax."
  3433. (format "<<%s>>" (org-element-property :value target)))
  3434. ;;;; Timestamp
  3435. (defconst org-element--timestamp-regexp
  3436. (concat org-ts-regexp-both
  3437. "\\|"
  3438. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3439. "\\|"
  3440. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3441. "Regexp matching any timestamp type object.")
  3442. (defun org-element-timestamp-parser ()
  3443. "Parse time stamp at point, if any.
  3444. When at a time stamp, return a list whose car is `timestamp', and
  3445. cdr a plist with `:type', `:raw-value', `:year-start',
  3446. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3447. `:year-end', `:month-end', `:day-end', `:hour-end',
  3448. `:minute-end', `:repeater-type', `:repeater-value',
  3449. `:repeater-unit', `:warning-type', `:warning-value',
  3450. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3451. Otherwise, return nil.
  3452. Assume point is at the beginning of the timestamp."
  3453. (when (looking-at-p org-element--timestamp-regexp)
  3454. (save-excursion
  3455. (let* ((begin (point))
  3456. (activep (eq (char-after) ?<))
  3457. (raw-value
  3458. (progn
  3459. (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
  3460. (match-string-no-properties 0)))
  3461. (date-start (match-string-no-properties 1))
  3462. (date-end (match-string 3))
  3463. (diaryp (match-beginning 2))
  3464. (post-blank (progn (goto-char (match-end 0))
  3465. (skip-chars-forward " \t")))
  3466. (end (point))
  3467. (time-range
  3468. (and (not diaryp)
  3469. (string-match
  3470. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3471. date-start)
  3472. (cons (string-to-number (match-string 2 date-start))
  3473. (string-to-number (match-string 3 date-start)))))
  3474. (type (cond (diaryp 'diary)
  3475. ((and activep (or date-end time-range)) 'active-range)
  3476. (activep 'active)
  3477. ((or date-end time-range) 'inactive-range)
  3478. (t 'inactive)))
  3479. (repeater-props
  3480. (and (not diaryp)
  3481. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3482. raw-value)
  3483. (list
  3484. :repeater-type
  3485. (let ((type (match-string 1 raw-value)))
  3486. (cond ((equal "++" type) 'catch-up)
  3487. ((equal ".+" type) 'restart)
  3488. (t 'cumulate)))
  3489. :repeater-value (string-to-number (match-string 2 raw-value))
  3490. :repeater-unit
  3491. (pcase (string-to-char (match-string 3 raw-value))
  3492. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3493. (warning-props
  3494. (and (not diaryp)
  3495. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3496. (list
  3497. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3498. :warning-value (string-to-number (match-string 2 raw-value))
  3499. :warning-unit
  3500. (pcase (string-to-char (match-string 3 raw-value))
  3501. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3502. year-start month-start day-start hour-start minute-start year-end
  3503. month-end day-end hour-end minute-end)
  3504. ;; Parse date-start.
  3505. (unless diaryp
  3506. (let ((date (org-parse-time-string date-start t)))
  3507. (setq year-start (nth 5 date)
  3508. month-start (nth 4 date)
  3509. day-start (nth 3 date)
  3510. hour-start (nth 2 date)
  3511. minute-start (nth 1 date))))
  3512. ;; Compute date-end. It can be provided directly in time-stamp,
  3513. ;; or extracted from time range. Otherwise, it defaults to the
  3514. ;; same values as date-start.
  3515. (unless diaryp
  3516. (let ((date (and date-end (org-parse-time-string date-end t))))
  3517. (setq year-end (or (nth 5 date) year-start)
  3518. month-end (or (nth 4 date) month-start)
  3519. day-end (or (nth 3 date) day-start)
  3520. hour-end (or (nth 2 date) (car time-range) hour-start)
  3521. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3522. (list 'timestamp
  3523. (nconc (list :type type
  3524. :raw-value raw-value
  3525. :year-start year-start
  3526. :month-start month-start
  3527. :day-start day-start
  3528. :hour-start hour-start
  3529. :minute-start minute-start
  3530. :year-end year-end
  3531. :month-end month-end
  3532. :day-end day-end
  3533. :hour-end hour-end
  3534. :minute-end minute-end
  3535. :begin begin
  3536. :end end
  3537. :post-blank post-blank)
  3538. repeater-props
  3539. warning-props))))))
  3540. (defun org-element-timestamp-interpreter (timestamp _)
  3541. "Interpret TIMESTAMP object as Org syntax."
  3542. (let* ((repeat-string
  3543. (concat
  3544. (pcase (org-element-property :repeater-type timestamp)
  3545. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3546. (let ((val (org-element-property :repeater-value timestamp)))
  3547. (and val (number-to-string val)))
  3548. (pcase (org-element-property :repeater-unit timestamp)
  3549. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3550. (warning-string
  3551. (concat
  3552. (pcase (org-element-property :warning-type timestamp)
  3553. (`first "--") (`all "-"))
  3554. (let ((val (org-element-property :warning-value timestamp)))
  3555. (and val (number-to-string val)))
  3556. (pcase (org-element-property :warning-unit timestamp)
  3557. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3558. (build-ts-string
  3559. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3560. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3561. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3562. ;; specify a time range in the timestamp. REPEAT-STRING is
  3563. ;; the repeater string, if any.
  3564. (lambda (time activep &optional with-time-p hour-end minute-end)
  3565. (let ((ts (format-time-string
  3566. (funcall (if with-time-p #'cdr #'car)
  3567. org-time-stamp-formats)
  3568. time)))
  3569. (when (and hour-end minute-end)
  3570. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3571. (setq ts
  3572. (replace-match
  3573. (format "\\&-%02d:%02d" hour-end minute-end)
  3574. nil nil ts)))
  3575. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3576. (dolist (s (list repeat-string warning-string))
  3577. (when (org-string-nw-p s)
  3578. (setq ts (concat (substring ts 0 -1)
  3579. " "
  3580. s
  3581. (substring ts -1)))))
  3582. ;; Return value.
  3583. ts)))
  3584. (type (org-element-property :type timestamp)))
  3585. (pcase type
  3586. ((or `active `inactive)
  3587. (let* ((minute-start (org-element-property :minute-start timestamp))
  3588. (minute-end (org-element-property :minute-end timestamp))
  3589. (hour-start (org-element-property :hour-start timestamp))
  3590. (hour-end (org-element-property :hour-end timestamp))
  3591. (time-range-p (and hour-start hour-end minute-start minute-end
  3592. (or (/= hour-start hour-end)
  3593. (/= minute-start minute-end)))))
  3594. (funcall
  3595. build-ts-string
  3596. (encode-time 0
  3597. (or minute-start 0)
  3598. (or hour-start 0)
  3599. (org-element-property :day-start timestamp)
  3600. (org-element-property :month-start timestamp)
  3601. (org-element-property :year-start timestamp))
  3602. (eq type 'active)
  3603. (and hour-start minute-start)
  3604. (and time-range-p hour-end)
  3605. (and time-range-p minute-end))))
  3606. ((or `active-range `inactive-range)
  3607. (let ((minute-start (org-element-property :minute-start timestamp))
  3608. (minute-end (org-element-property :minute-end timestamp))
  3609. (hour-start (org-element-property :hour-start timestamp))
  3610. (hour-end (org-element-property :hour-end timestamp)))
  3611. (concat
  3612. (funcall
  3613. build-ts-string (encode-time
  3614. 0
  3615. (or minute-start 0)
  3616. (or hour-start 0)
  3617. (org-element-property :day-start timestamp)
  3618. (org-element-property :month-start timestamp)
  3619. (org-element-property :year-start timestamp))
  3620. (eq type 'active-range)
  3621. (and hour-start minute-start))
  3622. "--"
  3623. (funcall build-ts-string
  3624. (encode-time 0
  3625. (or minute-end 0)
  3626. (or hour-end 0)
  3627. (org-element-property :day-end timestamp)
  3628. (org-element-property :month-end timestamp)
  3629. (org-element-property :year-end timestamp))
  3630. (eq type 'active-range)
  3631. (and hour-end minute-end)))))
  3632. (_ (org-element-property :raw-value timestamp)))))
  3633. ;;;; Underline
  3634. (defun org-element-underline-parser ()
  3635. "Parse underline object at point, if any.
  3636. When at an underline object, return a list whose car is
  3637. `underline' and cdr is a plist with `:begin', `:end',
  3638. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3639. Otherwise, return nil.
  3640. Assume point is at the first underscore marker."
  3641. (save-excursion
  3642. (unless (bolp) (backward-char 1))
  3643. (when (looking-at org-emph-re)
  3644. (let ((begin (match-beginning 2))
  3645. (contents-begin (match-beginning 4))
  3646. (contents-end (match-end 4))
  3647. (post-blank (progn (goto-char (match-end 2))
  3648. (skip-chars-forward " \t")))
  3649. (end (point)))
  3650. (list 'underline
  3651. (list :begin begin
  3652. :end end
  3653. :contents-begin contents-begin
  3654. :contents-end contents-end
  3655. :post-blank post-blank))))))
  3656. (defun org-element-underline-interpreter (_ contents)
  3657. "Interpret underline object as Org syntax.
  3658. CONTENTS is the contents of the object."
  3659. (format "_%s_" contents))
  3660. ;;;; Verbatim
  3661. (defun org-element-verbatim-parser ()
  3662. "Parse verbatim object at point, if any.
  3663. When at a verbatim object, return a list whose car is `verbatim'
  3664. and cdr is a plist with `:value', `:begin', `:end' and
  3665. `:post-blank' keywords. Otherwise, return nil.
  3666. Assume point is at the first equal sign marker."
  3667. (save-excursion
  3668. (unless (bolp) (backward-char 1))
  3669. (when (looking-at org-verbatim-re)
  3670. (let ((begin (match-beginning 2))
  3671. (value (match-string-no-properties 4))
  3672. (post-blank (progn (goto-char (match-end 2))
  3673. (skip-chars-forward " \t")))
  3674. (end (point)))
  3675. (list 'verbatim
  3676. (list :value value
  3677. :begin begin
  3678. :end end
  3679. :post-blank post-blank))))))
  3680. (defun org-element-verbatim-interpreter (verbatim _)
  3681. "Interpret VERBATIM object as Org syntax."
  3682. (format "=%s=" (org-element-property :value verbatim)))
  3683. ;;; Parsing Element Starting At Point
  3684. ;;
  3685. ;; `org-element--current-element' is the core function of this section.
  3686. ;; It returns the Lisp representation of the element starting at
  3687. ;; point.
  3688. (defvar org-element--cache-sync-requests); Declared later
  3689. (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
  3690. "Parse the element starting at point.
  3691. Return value is a list like (TYPE PROPS) where TYPE is the type
  3692. of the element and PROPS a plist of properties associated to the
  3693. element.
  3694. Possible types are defined in `org-element-all-elements'.
  3695. LIMIT bounds the search.
  3696. Optional argument GRANULARITY determines the depth of the
  3697. recursion. Allowed values are `headline', `greater-element',
  3698. `element', `object' or nil. When it is broader than `object' (or
  3699. nil), secondary values will not be parsed, since they only
  3700. contain objects.
  3701. Optional argument MODE, when non-nil, can be either
  3702. `first-section', `item', `node-property', `planning',
  3703. `property-drawer', `section', `table-row', or `top-comment'.
  3704. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3705. computed.
  3706. Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
  3707. will also add current element to cache if it is not yet there. Use
  3708. this argument with care, as validity of the element in parse tree is
  3709. not checked.
  3710. This function assumes point is always at the beginning of the
  3711. element it has to parse."
  3712. (let* ((element (and (not (buffer-narrowed-p))
  3713. (org-element--cache-active-p)
  3714. (not org-element--cache-sync-requests)
  3715. (org-element--cache-find (point) t)))
  3716. (element (progn (while (and element
  3717. (not (and (eq (point) (org-element-property :begin element))
  3718. (eq mode (org-element-property :mode element)))))
  3719. (setq element (org-element-property :parent element)))
  3720. element))
  3721. (old-element element)
  3722. (element (when
  3723. (pcase (org-element-property :granularity element)
  3724. (`nil t)
  3725. (`object t)
  3726. (`element (not (memq granularity '(nil object))))
  3727. (`greater-element (not (memq granularity '(nil object element))))
  3728. (`headline (eq granularity 'headline)))
  3729. element)))
  3730. (if element
  3731. element
  3732. (save-excursion
  3733. (let ((case-fold-search t)
  3734. ;; Determine if parsing depth allows for secondary strings
  3735. ;; parsing. It only applies to elements referenced in
  3736. ;; `org-element-secondary-value-alist'.
  3737. (raw-secondary-p (and granularity (not (eq granularity 'object))))
  3738. result)
  3739. (setq
  3740. result
  3741. (cond
  3742. ;; Item.
  3743. ((eq mode 'item)
  3744. (org-element-item-parser limit structure raw-secondary-p))
  3745. ;; Table Row.
  3746. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3747. ;; Node Property.
  3748. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3749. ;; Headline.
  3750. ((org-with-limited-levels (org-at-heading-p))
  3751. (org-element-headline-parser limit raw-secondary-p))
  3752. ;; Sections (must be checked after headline).
  3753. ((eq mode 'section) (org-element-section-parser limit))
  3754. ((eq mode 'first-section)
  3755. (org-element-section-parser
  3756. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3757. limit)))
  3758. ;; Comments.
  3759. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3760. (org-element-comment-parser limit))
  3761. ;; Planning.
  3762. ((and (eq mode 'planning)
  3763. (eq ?* (char-after (line-beginning-position 0)))
  3764. (looking-at org-planning-line-re))
  3765. (org-element-planning-parser limit))
  3766. ;; Property drawer.
  3767. ((and (pcase mode
  3768. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3769. ((or `property-drawer `top-comment)
  3770. (save-excursion
  3771. (beginning-of-line 0)
  3772. (not (looking-at "[[:blank:]]*$"))))
  3773. (_ nil))
  3774. (looking-at org-property-drawer-re))
  3775. (org-element-property-drawer-parser limit))
  3776. ;; When not at bol, point is at the beginning of an item or
  3777. ;; a footnote definition: next item is always a paragraph.
  3778. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3779. ;; Clock.
  3780. ((looking-at org-clock-line-re) (org-element-clock-parser limit))
  3781. ;; Inlinetask.
  3782. ((looking-at "^\\*+ ")
  3783. (org-element-inlinetask-parser limit raw-secondary-p))
  3784. ;; From there, elements can have affiliated keywords.
  3785. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3786. limit (memq granularity '(nil object)))))
  3787. (cond
  3788. ;; Jumping over affiliated keywords put point off-limits.
  3789. ;; Parse them as regular keywords.
  3790. ((and (cdr affiliated) (>= (point) limit))
  3791. (goto-char (car affiliated))
  3792. (org-element-keyword-parser limit nil))
  3793. ;; LaTeX Environment.
  3794. ((looking-at org-element--latex-begin-environment)
  3795. (org-element-latex-environment-parser limit affiliated))
  3796. ;; Drawer.
  3797. ((looking-at org-drawer-regexp)
  3798. (org-element-drawer-parser limit affiliated))
  3799. ;; Fixed Width
  3800. ((looking-at "[ \t]*:\\( \\|$\\)")
  3801. (org-element-fixed-width-parser limit affiliated))
  3802. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3803. ;; Keywords.
  3804. ((looking-at "[ \t]*#\\+")
  3805. (goto-char (match-end 0))
  3806. (cond
  3807. ((looking-at "BEGIN_\\(\\S-+\\)")
  3808. (beginning-of-line)
  3809. (funcall (pcase (upcase (match-string 1))
  3810. ("CENTER" #'org-element-center-block-parser)
  3811. ("COMMENT" #'org-element-comment-block-parser)
  3812. ("EXAMPLE" #'org-element-example-block-parser)
  3813. ("EXPORT" #'org-element-export-block-parser)
  3814. ("QUOTE" #'org-element-quote-block-parser)
  3815. ("SRC" #'org-element-src-block-parser)
  3816. ("VERSE" #'org-element-verse-block-parser)
  3817. (_ #'org-element-special-block-parser))
  3818. limit
  3819. affiliated))
  3820. ((looking-at "CALL:")
  3821. (beginning-of-line)
  3822. (org-element-babel-call-parser limit affiliated))
  3823. ((looking-at "BEGIN:? ")
  3824. (beginning-of-line)
  3825. (org-element-dynamic-block-parser limit affiliated))
  3826. ((looking-at "\\S-+:")
  3827. (beginning-of-line)
  3828. (org-element-keyword-parser limit affiliated))
  3829. (t
  3830. (beginning-of-line)
  3831. (org-element-paragraph-parser limit affiliated))))
  3832. ;; Footnote Definition.
  3833. ((looking-at org-footnote-definition-re)
  3834. (org-element-footnote-definition-parser limit affiliated))
  3835. ;; Horizontal Rule.
  3836. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3837. (org-element-horizontal-rule-parser limit affiliated))
  3838. ;; Diary Sexp.
  3839. ((looking-at "%%(")
  3840. (org-element-diary-sexp-parser limit affiliated))
  3841. ;; Table.
  3842. ((or (looking-at "[ \t]*|")
  3843. ;; There is no strict definition of a table.el
  3844. ;; table. Try to prevent false positive while being
  3845. ;; quick.
  3846. (let ((rule-regexp
  3847. (rx (zero-or-more (any " \t"))
  3848. "+"
  3849. (one-or-more (one-or-more "-") "+")
  3850. (zero-or-more (any " \t"))
  3851. eol))
  3852. (non-table.el-line
  3853. (rx bol
  3854. (zero-or-more (any " \t"))
  3855. (or eol (not (any "+| \t")))))
  3856. (next (line-beginning-position 2)))
  3857. ;; Start with a full rule.
  3858. (and
  3859. (looking-at rule-regexp)
  3860. (< next limit) ;no room for a table.el table
  3861. (save-excursion
  3862. (end-of-line)
  3863. (cond
  3864. ;; Must end with a full rule.
  3865. ((not (re-search-forward non-table.el-line limit 'move))
  3866. (if (bolp) (forward-line -1) (beginning-of-line))
  3867. (looking-at rule-regexp))
  3868. ;; Ignore pseudo-tables with a single
  3869. ;; rule.
  3870. ((= next (line-beginning-position))
  3871. nil)
  3872. ;; Must end with a full rule.
  3873. (t
  3874. (forward-line -1)
  3875. (looking-at rule-regexp)))))))
  3876. (org-element-table-parser limit affiliated))
  3877. ;; List.
  3878. ((looking-at (org-item-re))
  3879. (org-element-plain-list-parser
  3880. limit affiliated
  3881. (or structure (org-element--list-struct limit))))
  3882. ;; Default element: Paragraph.
  3883. (t (org-element-paragraph-parser limit affiliated)))))))
  3884. (when result
  3885. (org-element-put-property result :mode mode)
  3886. (org-element-put-property result :granularity granularity))
  3887. (when (and (not (buffer-narrowed-p))
  3888. (org-element--cache-active-p)
  3889. (not org-element--cache-sync-requests)
  3890. add-to-cache)
  3891. (if (not old-element)
  3892. (setq result (org-element--cache-put result))
  3893. (org-element-set-element old-element result)
  3894. (setq result old-element)))
  3895. result)))))
  3896. ;; Most elements can have affiliated keywords. When looking for an
  3897. ;; element beginning, we want to move before them, as they belong to
  3898. ;; that element, and, in the meantime, collect information they give
  3899. ;; into appropriate properties. Hence the following function.
  3900. (defun org-element--collect-affiliated-keywords (limit parse)
  3901. "Collect affiliated keywords from point down to LIMIT.
  3902. Return a list whose CAR is the position at the first of them and
  3903. CDR a plist of keywords and values and move point to the
  3904. beginning of the first line after them.
  3905. As a special case, if element doesn't start at the beginning of
  3906. the line (e.g., a paragraph starting an item), CAR is current
  3907. position of point and CDR is nil.
  3908. When PARSE is non-nil, values from keywords belonging to
  3909. `org-element-parsed-keywords' are parsed as secondary strings."
  3910. (if (not (bolp)) (list (point))
  3911. (let ((case-fold-search t)
  3912. (origin (point))
  3913. ;; RESTRICT is the list of objects allowed in parsed
  3914. ;; keywords value. If PARSE is nil, no object is allowed.
  3915. (restrict (and parse (org-element-restriction 'keyword)))
  3916. output)
  3917. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3918. (let* ((raw-kwd (upcase (match-string 1)))
  3919. ;; Apply translation to RAW-KWD. From there, KWD is
  3920. ;; the official keyword.
  3921. (kwd (or (cdr (assoc raw-kwd
  3922. org-element-keyword-translation-alist))
  3923. raw-kwd))
  3924. ;; PARSED? is non-nil when keyword should have its
  3925. ;; value parsed.
  3926. (parsed? (member kwd org-element-parsed-keywords))
  3927. ;; Find main value for any keyword.
  3928. (value
  3929. (let ((beg (match-end 0))
  3930. (end (save-excursion
  3931. (end-of-line)
  3932. (skip-chars-backward " \t")
  3933. (point))))
  3934. (if parsed?
  3935. (save-match-data
  3936. (org-element--parse-objects beg end nil restrict))
  3937. (org-trim (buffer-substring-no-properties beg end)))))
  3938. ;; If KWD is a dual keyword, find its secondary value.
  3939. ;; Maybe parse it.
  3940. (dual? (member kwd org-element-dual-keywords))
  3941. (dual-value
  3942. (and dual?
  3943. (let ((sec (match-string-no-properties 2)))
  3944. (cond
  3945. ((and sec parsed?)
  3946. (save-match-data
  3947. (org-element--parse-objects
  3948. (match-beginning 2) (match-end 2) nil restrict)))
  3949. (sec sec)))))
  3950. ;; Attribute a property name to KWD.
  3951. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3952. ;; Now set final shape for VALUE.
  3953. (when dual?
  3954. (setq value (and (or value dual-value) (cons value dual-value))))
  3955. (when (or (member kwd org-element-multiple-keywords)
  3956. ;; Attributes can always appear on multiple lines.
  3957. (string-match "^ATTR_" kwd))
  3958. (setq value (cons value (plist-get output kwd-sym))))
  3959. ;; Eventually store the new value in OUTPUT.
  3960. (setq output (plist-put output kwd-sym value))
  3961. ;; Move to next keyword.
  3962. (forward-line)))
  3963. ;; If affiliated keywords are orphaned: move back to first one.
  3964. ;; They will be parsed as a paragraph.
  3965. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3966. ;; Return value.
  3967. (cons origin output))))
  3968. ;;; The Org Parser
  3969. ;;
  3970. ;; The two major functions here are `org-element-parse-buffer', which
  3971. ;; parses Org syntax inside the current buffer, taking into account
  3972. ;; region, narrowing, or even visibility if specified, and
  3973. ;; `org-element-parse-secondary-string', which parses objects within
  3974. ;; a given string.
  3975. ;;
  3976. ;; The (almost) almighty `org-element-map' allows applying a function
  3977. ;; on elements or objects matching some type, and accumulating the
  3978. ;; resulting values. In an export situation, it also skips unneeded
  3979. ;; parts of the parse tree.
  3980. (defun org-element-parse-buffer (&optional granularity visible-only)
  3981. "Recursively parse the buffer and return structure.
  3982. If narrowing is in effect, only parse the visible part of the
  3983. buffer.
  3984. Optional argument GRANULARITY determines the depth of the
  3985. recursion. It can be set to the following symbols:
  3986. `headline' Only parse headlines.
  3987. `greater-element' Don't recurse into greater elements except
  3988. headlines and sections. Thus, elements
  3989. parsed are the top-level ones.
  3990. `element' Parse everything but objects and plain text.
  3991. `object' Parse the complete buffer (default).
  3992. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3993. elements.
  3994. An element or object is represented as a list with the
  3995. pattern (TYPE PROPERTIES CONTENTS), where :
  3996. TYPE is a symbol describing the element or object. See
  3997. `org-element-all-elements' and `org-element-all-objects' for an
  3998. exhaustive list of such symbols. One can retrieve it with
  3999. `org-element-type' function.
  4000. PROPERTIES is the list of attributes attached to the element or
  4001. object, as a plist. Although most of them are specific to the
  4002. element or object type, all types share `:begin', `:end',
  4003. `:post-blank' and `:parent' properties, which respectively
  4004. refer to buffer position where the element or object starts,
  4005. ends, the number of white spaces or blank lines after it, and
  4006. the element or object containing it. Properties values can be
  4007. obtained by using `org-element-property' function.
  4008. CONTENTS is a list of elements, objects or raw strings
  4009. contained in the current element or object, when applicable.
  4010. One can access them with `org-element-contents' function.
  4011. The Org buffer has `org-data' as type and nil as properties.
  4012. `org-element-map' function can be used to find specific elements
  4013. or objects within the parse tree.
  4014. This function assumes that current major mode is `org-mode'."
  4015. (save-excursion
  4016. (goto-char (point-min))
  4017. (let ((org-data (org-element-org-data-parser)))
  4018. (org-skip-whitespace)
  4019. (org-element--parse-elements
  4020. (point-at-bol) (point-max)
  4021. ;; Start in `first-section' mode so text before the first
  4022. ;; headline belongs to a section.
  4023. 'first-section nil granularity visible-only org-data))))
  4024. (defun org-element-parse-secondary-string (string restriction &optional parent)
  4025. "Recursively parse objects in STRING and return structure.
  4026. RESTRICTION is a symbol limiting the object types that will be
  4027. looked after.
  4028. Optional argument PARENT, when non-nil, is the element or object
  4029. containing the secondary string. It is used to set correctly
  4030. `:parent' property within the string.
  4031. If STRING is the empty string or nil, return nil."
  4032. (cond
  4033. ((not string) nil)
  4034. ((equal string "") nil)
  4035. (t (let ((local-variables (buffer-local-variables)))
  4036. (with-temp-buffer
  4037. (dolist (v local-variables)
  4038. (ignore-errors
  4039. (if (symbolp v) (makunbound v)
  4040. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  4041. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  4042. (set (make-local-variable (car v)) (cdr v))))))
  4043. ;; Transferring local variables may put the temporary buffer
  4044. ;; into a read-only state. Make sure we can insert STRING.
  4045. (let ((inhibit-read-only t)) (insert string))
  4046. ;; Prevent "Buffer *temp* modified; kill anyway?".
  4047. (restore-buffer-modified-p nil)
  4048. (org-element--parse-objects
  4049. (point-min) (point-max) nil restriction parent))))))
  4050. (defun org-element-map
  4051. (data types fun &optional info first-match no-recursion with-affiliated)
  4052. "Map a function on selected elements or objects.
  4053. DATA is a parse tree, an element, an object, a string, or a list
  4054. of such constructs. TYPES is a symbol or list of symbols of
  4055. elements or objects types (see `org-element-all-elements' and
  4056. `org-element-all-objects' for a complete list of types). FUN is
  4057. the function called on the matching element or object. It has to
  4058. accept one argument: the element or object itself.
  4059. When optional argument INFO is non-nil, it should be a plist
  4060. holding export options. In that case, parts of the parse tree
  4061. not exportable according to that property list will be skipped.
  4062. When optional argument FIRST-MATCH is non-nil, stop at the first
  4063. match for which FUN doesn't return nil, and return that value.
  4064. Optional argument NO-RECURSION is a symbol or a list of symbols
  4065. representing elements or objects types. `org-element-map' won't
  4066. enter any recursive element or object whose type belongs to that
  4067. list. Though, FUN can still be applied on them.
  4068. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  4069. apply to matching objects within parsed affiliated keywords (see
  4070. `org-element-parsed-keywords').
  4071. Nil values returned from FUN do not appear in the results.
  4072. Examples:
  4073. ---------
  4074. Assuming TREE is a variable containing an Org buffer parse tree,
  4075. the following example will return a flat list of all `src-block'
  4076. and `example-block' elements in it:
  4077. (org-element-map tree \\='(example-block src-block) #\\='identity)
  4078. The following snippet will find the first headline with a level
  4079. of 1 and a \"phone\" tag, and will return its beginning position:
  4080. (org-element-map tree \\='headline
  4081. (lambda (hl)
  4082. (and (= (org-element-property :level hl) 1)
  4083. (member \"phone\" (org-element-property :tags hl))
  4084. (org-element-property :begin hl)))
  4085. nil t)
  4086. The next example will return a flat list of all `plain-list' type
  4087. elements in TREE that are not a sub-list themselves:
  4088. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  4089. Eventually, this example will return a flat list of all `bold'
  4090. type objects containing a `latex-snippet' type object, even
  4091. looking into captions:
  4092. (org-element-map tree \\='bold
  4093. (lambda (b)
  4094. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  4095. nil nil nil t)"
  4096. (declare (indent 2))
  4097. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  4098. (let* ((types (if (listp types) types (list types)))
  4099. (no-recursion (if (listp no-recursion) no-recursion
  4100. (list no-recursion)))
  4101. ;; Recursion depth is determined by --CATEGORY.
  4102. (--category
  4103. (catch :--found
  4104. (let ((category 'greater-elements)
  4105. (all-objects (cons 'plain-text org-element-all-objects)))
  4106. (dolist (type types category)
  4107. (cond ((memq type all-objects)
  4108. ;; If one object is found, the function has
  4109. ;; to recurse into every object.
  4110. (throw :--found 'objects))
  4111. ((not (memq type org-element-greater-elements))
  4112. ;; If one regular element is found, the
  4113. ;; function has to recurse, at least, into
  4114. ;; every element it encounters.
  4115. (and (not (eq category 'elements))
  4116. (setq category 'elements))))))))
  4117. --acc)
  4118. (letrec ((--walk-tree
  4119. (lambda (--data)
  4120. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  4121. ;; holding contextual information.
  4122. (let ((--type (org-element-type --data)))
  4123. (cond
  4124. ((not --data))
  4125. ;; Ignored element in an export context.
  4126. ((and info (memq --data (plist-get info :ignore-list))))
  4127. ;; List of elements or objects.
  4128. ((not --type) (mapc --walk-tree --data))
  4129. ;; Unconditionally enter parse trees.
  4130. ((eq --type 'org-data)
  4131. (mapc --walk-tree (org-element-contents --data)))
  4132. (t
  4133. ;; Check if TYPE is matching among TYPES. If so,
  4134. ;; apply FUN to --DATA and accumulate return value
  4135. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  4136. (when (memq --type types)
  4137. (let ((result (funcall fun --data)))
  4138. (cond ((not result))
  4139. (first-match (throw :--map-first-match result))
  4140. (t (push result --acc)))))
  4141. ;; If --DATA has a secondary string that can contain
  4142. ;; objects with their type among TYPES, look inside.
  4143. (when (and (eq --category 'objects) (not (stringp --data)))
  4144. (dolist (p (cdr (assq --type
  4145. org-element-secondary-value-alist)))
  4146. (funcall --walk-tree (org-element-property p --data))))
  4147. ;; If --DATA has any parsed affiliated keywords and
  4148. ;; WITH-AFFILIATED is non-nil, look for objects in
  4149. ;; them.
  4150. (when (and with-affiliated
  4151. (eq --category 'objects)
  4152. (eq (org-element-class --data) 'element))
  4153. (dolist (kwd-pair org-element--parsed-properties-alist)
  4154. (let ((kwd (car kwd-pair))
  4155. (value (org-element-property (cdr kwd-pair) --data)))
  4156. ;; Pay attention to the type of parsed
  4157. ;; keyword. In particular, preserve order for
  4158. ;; multiple keywords.
  4159. (cond
  4160. ((not value))
  4161. ((member kwd org-element-dual-keywords)
  4162. (if (member kwd org-element-multiple-keywords)
  4163. (dolist (line (reverse value))
  4164. (funcall --walk-tree (cdr line))
  4165. (funcall --walk-tree (car line)))
  4166. (funcall --walk-tree (cdr value))
  4167. (funcall --walk-tree (car value))))
  4168. ((member kwd org-element-multiple-keywords)
  4169. (mapc --walk-tree (reverse value)))
  4170. (t (funcall --walk-tree value))))))
  4171. ;; Determine if a recursion into --DATA is possible.
  4172. (cond
  4173. ;; --TYPE is explicitly removed from recursion.
  4174. ((memq --type no-recursion))
  4175. ;; --DATA has no contents.
  4176. ((not (org-element-contents --data)))
  4177. ;; Looking for greater elements but --DATA is
  4178. ;; simply an element or an object.
  4179. ((and (eq --category 'greater-elements)
  4180. (not (memq --type org-element-greater-elements))))
  4181. ;; Looking for elements but --DATA is an object.
  4182. ((and (eq --category 'elements)
  4183. (eq (org-element-class --data) 'object)))
  4184. ;; In any other case, map contents.
  4185. (t (mapc --walk-tree (org-element-contents --data))))))))))
  4186. (catch :--map-first-match
  4187. (funcall --walk-tree data)
  4188. ;; Return value in a proper order.
  4189. (nreverse --acc)))))
  4190. ;; The following functions are internal parts of the parser.
  4191. ;;
  4192. ;; The first one, `org-element--parse-elements' acts at the element's
  4193. ;; level.
  4194. ;;
  4195. ;; The second one, `org-element--parse-objects' applies on all objects
  4196. ;; of a paragraph or a secondary string. It calls
  4197. ;; `org-element--object-lex' to find the next object in the current
  4198. ;; container.
  4199. (defsubst org-element--next-mode (mode type parent?)
  4200. "Return next mode according to current one.
  4201. MODE is a symbol representing the expectation about the next
  4202. element or object. Meaningful values are `first-section',
  4203. `item', `node-property', `planning', `property-drawer',
  4204. `section', `table-row', `top-comment', and nil.
  4205. TYPE is the type of the current element or object.
  4206. If PARENT? is non-nil, assume the next element or object will be
  4207. located inside the current one."
  4208. (if parent?
  4209. (pcase type
  4210. (`headline 'section)
  4211. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4212. ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
  4213. ((and (guard (not mode)) `org-data) 'first-section)
  4214. (`inlinetask 'planning)
  4215. (`plain-list 'item)
  4216. (`property-drawer 'node-property)
  4217. (`section 'planning)
  4218. (`table 'table-row))
  4219. (pcase mode
  4220. (`item 'item)
  4221. (`node-property 'node-property)
  4222. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4223. (`table-row 'table-row)
  4224. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4225. (defun org-element--parse-elements
  4226. (beg end mode structure granularity visible-only acc)
  4227. "Parse elements between BEG and END positions.
  4228. MODE prioritizes some elements over the others. It can be set to
  4229. `first-section', `item', `node-property', `planning',
  4230. `property-drawer', `section', `table-row', `top-comment', or nil.
  4231. When value is `item', STRUCTURE will be used as the current list
  4232. structure.
  4233. GRANULARITY determines the depth of the recursion. See
  4234. `org-element-parse-buffer' for more information.
  4235. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4236. elements.
  4237. Elements are accumulated into ACC."
  4238. (save-excursion
  4239. (goto-char beg)
  4240. ;; When parsing only headlines, skip any text before first one.
  4241. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4242. (org-with-limited-levels (outline-next-heading)))
  4243. (let (elements)
  4244. (while (< (point) end)
  4245. ;; Visible only: skip invisible parts due to folding.
  4246. (if (and visible-only (org-invisible-p nil t))
  4247. (progn
  4248. (goto-char (org-find-visible))
  4249. (when (and (eolp) (not (eobp))) (forward-char)))
  4250. ;; Find current element's type and parse it accordingly to
  4251. ;; its category.
  4252. (let* ((element (org-element-copy
  4253. ;; `org-element--current-element' may return cached
  4254. ;; elements. Below code reassigns
  4255. ;; `:parent' property of the element and
  4256. ;; may interfere with cache
  4257. ;; synchronisation if parent element is not
  4258. ;; yet in cache. Moreover, the returned
  4259. ;; structure may be altered by caller code
  4260. ;; arbitrarily. Hence, we return a copy of
  4261. ;; the potentially cached element to make
  4262. ;; potential modifications safe for element
  4263. ;; cache.
  4264. (org-element--current-element
  4265. end granularity mode structure)))
  4266. (type (org-element-type element))
  4267. (cbeg (org-element-property :contents-begin element)))
  4268. (goto-char (org-element-property :end element))
  4269. ;; Fill ELEMENT contents by side-effect.
  4270. (cond
  4271. ;; If element has no contents, don't modify it.
  4272. ((not cbeg))
  4273. ;; Greater element: parse it between `contents-begin' and
  4274. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4275. ;; or ELEMENT is a headline, in which case going inside
  4276. ;; is mandatory, in order to get sub-level headings.
  4277. ((and (memq type org-element-greater-elements)
  4278. (or (memq granularity '(element object nil))
  4279. (and (eq granularity 'greater-element)
  4280. (eq type 'section))
  4281. (eq type 'headline)))
  4282. (org-element--parse-elements
  4283. cbeg (org-element-property :contents-end element)
  4284. ;; Possibly switch to a special mode.
  4285. (org-element--next-mode mode type t)
  4286. (and (memq type '(item plain-list))
  4287. (org-element-property :structure element))
  4288. granularity visible-only element))
  4289. ;; ELEMENT has contents. Parse objects inside, if
  4290. ;; GRANULARITY allows it.
  4291. ((memq granularity '(object nil))
  4292. (org-element--parse-objects
  4293. cbeg (org-element-property :contents-end element) element
  4294. (org-element-restriction type))))
  4295. (push (org-element-put-property element :parent acc) elements)
  4296. ;; Update mode.
  4297. (setq mode (org-element--next-mode mode type nil)))))
  4298. ;; Return result.
  4299. (org-element-put-property acc :granularity granularity)
  4300. (apply #'org-element-set-contents acc (nreverse elements)))))
  4301. (defun org-element--object-lex (restriction)
  4302. "Return next object in current buffer or nil.
  4303. RESTRICTION is a list of object types, as symbols, that should be
  4304. looked after. This function assumes that the buffer is narrowed
  4305. to an appropriate container (e.g., a paragraph)."
  4306. (cond
  4307. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4308. ((memq 'citation-reference restriction)
  4309. (org-element-citation-reference-parser))
  4310. (t
  4311. (let* ((start (point))
  4312. (limit
  4313. ;; Object regexp sometimes needs to have a peek at
  4314. ;; a character ahead. Therefore, when there is a hard
  4315. ;; limit, make it one more than the true beginning of the
  4316. ;; radio target.
  4317. (save-excursion
  4318. (cond ((not org-target-link-regexp) nil)
  4319. ((not (memq 'link restriction)) nil)
  4320. ((progn
  4321. (unless (bolp) (forward-char -1))
  4322. (not (re-search-forward org-target-link-regexp nil t)))
  4323. nil)
  4324. ;; Since we moved backward, we do not want to
  4325. ;; match again an hypothetical 1-character long
  4326. ;; radio link before us. Realizing that this can
  4327. ;; only happen if such a radio link starts at
  4328. ;; beginning of line, we prevent this here.
  4329. ((and (= start (1+ (line-beginning-position)))
  4330. (= start (match-end 1)))
  4331. (and (re-search-forward org-target-link-regexp nil t)
  4332. (1+ (match-beginning 1))))
  4333. (t (1+ (match-beginning 1))))))
  4334. found)
  4335. (save-excursion
  4336. (while (and (not found)
  4337. (re-search-forward org-element--object-regexp limit 'move))
  4338. (goto-char (match-beginning 0))
  4339. (let ((result (match-string 0)))
  4340. (setq found
  4341. (cond
  4342. ((string-prefix-p "call_" result t)
  4343. (and (memq 'inline-babel-call restriction)
  4344. (org-element-inline-babel-call-parser)))
  4345. ((string-prefix-p "src_" result t)
  4346. (and (memq 'inline-src-block restriction)
  4347. (org-element-inline-src-block-parser)))
  4348. (t
  4349. (pcase (char-after)
  4350. (?^ (and (memq 'superscript restriction)
  4351. (org-element-superscript-parser)))
  4352. (?_ (or (and (memq 'subscript restriction)
  4353. (org-element-subscript-parser))
  4354. (and (memq 'underline restriction)
  4355. (org-element-underline-parser))))
  4356. (?* (and (memq 'bold restriction)
  4357. (org-element-bold-parser)))
  4358. (?/ (and (memq 'italic restriction)
  4359. (org-element-italic-parser)))
  4360. (?~ (and (memq 'code restriction)
  4361. (org-element-code-parser)))
  4362. (?= (and (memq 'verbatim restriction)
  4363. (org-element-verbatim-parser)))
  4364. (?+ (and (memq 'strike-through restriction)
  4365. (org-element-strike-through-parser)))
  4366. (?@ (and (memq 'export-snippet restriction)
  4367. (org-element-export-snippet-parser)))
  4368. (?{ (and (memq 'macro restriction)
  4369. (org-element-macro-parser)))
  4370. (?$ (and (memq 'latex-fragment restriction)
  4371. (org-element-latex-fragment-parser)))
  4372. (?<
  4373. (if (eq (aref result 1) ?<)
  4374. (or (and (memq 'radio-target restriction)
  4375. (org-element-radio-target-parser))
  4376. (and (memq 'target restriction)
  4377. (org-element-target-parser)))
  4378. (or (and (memq 'timestamp restriction)
  4379. (org-element-timestamp-parser))
  4380. (and (memq 'link restriction)
  4381. (org-element-link-parser)))))
  4382. (?\\
  4383. (if (eq (aref result 1) ?\\)
  4384. (and (memq 'line-break restriction)
  4385. (org-element-line-break-parser))
  4386. (or (and (memq 'entity restriction)
  4387. (org-element-entity-parser))
  4388. (and (memq 'latex-fragment restriction)
  4389. (org-element-latex-fragment-parser)))))
  4390. (?\[
  4391. (pcase (aref result 1)
  4392. ((and ?\[
  4393. (guard (memq 'link restriction)))
  4394. (org-element-link-parser))
  4395. ((and ?f
  4396. (guard (memq 'footnote-reference restriction)))
  4397. (org-element-footnote-reference-parser))
  4398. ((and ?c
  4399. (guard (memq 'citation restriction)))
  4400. (org-element-citation-parser))
  4401. ((and (or ?% ?/)
  4402. (guard (memq 'statistics-cookie restriction)))
  4403. (org-element-statistics-cookie-parser))
  4404. (_
  4405. (or (and (memq 'timestamp restriction)
  4406. (org-element-timestamp-parser))
  4407. (and (memq 'statistics-cookie restriction)
  4408. (org-element-statistics-cookie-parser))))))
  4409. ;; This is probably a plain link.
  4410. (_ (and (memq 'link restriction)
  4411. (org-element-link-parser)))))))
  4412. (or (eobp) (forward-char))))
  4413. (cond (found)
  4414. (limit (forward-char -1)
  4415. (org-element-link-parser)) ;radio link
  4416. (t nil)))))))
  4417. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4418. "Parse objects between BEG and END and return recursive structure.
  4419. Objects are accumulated in ACC. RESTRICTION is a list of object
  4420. successors which are allowed in the current object.
  4421. ACC becomes the parent for all parsed objects. However, if ACC
  4422. is nil (i.e., a secondary string is being parsed) and optional
  4423. argument PARENT is non-nil, use it as the parent for all objects.
  4424. Eventually, if both ACC and PARENT are nil, the common parent is
  4425. the list of objects itself."
  4426. (save-excursion
  4427. (save-restriction
  4428. (narrow-to-region beg end)
  4429. (goto-char (point-min))
  4430. (let (next-object contents)
  4431. (while (and (not (eobp))
  4432. (setq next-object (org-element--object-lex restriction)))
  4433. ;; Text before any object.
  4434. (let ((obj-beg (org-element-property :begin next-object)))
  4435. (unless (= (point) obj-beg)
  4436. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4437. (push (if acc (org-element-put-property text :parent acc) text)
  4438. contents))))
  4439. ;; Object...
  4440. (let ((obj-end (org-element-property :end next-object))
  4441. (cont-beg (org-element-property :contents-begin next-object)))
  4442. (when acc (org-element-put-property next-object :parent acc))
  4443. (push (if cont-beg
  4444. ;; Fill contents of NEXT-OBJECT if possible.
  4445. (org-element--parse-objects
  4446. cont-beg
  4447. (org-element-property :contents-end next-object)
  4448. next-object
  4449. (org-element-restriction next-object))
  4450. next-object)
  4451. contents)
  4452. (goto-char obj-end)))
  4453. ;; Text after last object.
  4454. (unless (eobp)
  4455. (let ((text (buffer-substring-no-properties (point) end)))
  4456. (push (if acc (org-element-put-property text :parent acc) text)
  4457. contents)))
  4458. ;; Result. Set appropriate parent.
  4459. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4460. (let* ((contents (nreverse contents))
  4461. (parent (or parent contents)))
  4462. (dolist (datum contents contents)
  4463. (org-element-put-property datum :parent parent))))))))
  4464. ;;; Towards A Bijective Process
  4465. ;;
  4466. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4467. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4468. ;; interpreted and expanded into a string with canonical Org syntax.
  4469. ;; Hence `org-element-interpret-data'.
  4470. ;;
  4471. ;; The function relies internally on
  4472. ;; `org-element--interpret-affiliated-keywords'.
  4473. ;;;###autoload
  4474. (defun org-element-interpret-data (data)
  4475. "Interpret DATA as Org syntax.
  4476. DATA is a parse tree, an element, an object or a secondary string
  4477. to interpret. Return Org syntax as a string."
  4478. (letrec ((fun
  4479. (lambda (data parent)
  4480. (let* ((type (org-element-type data))
  4481. ;; Find interpreter for current object or
  4482. ;; element. If it doesn't exist (e.g. this is
  4483. ;; a pseudo object or element), return contents,
  4484. ;; if any.
  4485. (interpret
  4486. (let ((fun (intern
  4487. (format "org-element-%s-interpreter" type))))
  4488. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4489. (results
  4490. (cond
  4491. ;; Secondary string.
  4492. ((not type)
  4493. (mapconcat (lambda (obj) (funcall fun obj parent))
  4494. data
  4495. ""))
  4496. ;; Full Org document.
  4497. ((eq type 'org-data)
  4498. (mapconcat (lambda (obj) (funcall fun obj parent))
  4499. (org-element-contents data)
  4500. ""))
  4501. ;; Plain text: return it.
  4502. ((stringp data) data)
  4503. ;; Element or object without contents.
  4504. ((not (org-element-contents data))
  4505. (funcall interpret data nil))
  4506. ;; Element or object with contents.
  4507. (t
  4508. (funcall
  4509. interpret
  4510. data
  4511. ;; Recursively interpret contents.
  4512. (mapconcat
  4513. (lambda (datum) (funcall fun datum data))
  4514. (org-element-contents
  4515. (if (not (memq type '(paragraph verse-block)))
  4516. data
  4517. ;; Fix indentation of elements containing
  4518. ;; objects. We ignore `table-row'
  4519. ;; elements as they are one line long
  4520. ;; anyway.
  4521. (org-element-normalize-contents
  4522. data
  4523. ;; When normalizing first paragraph of
  4524. ;; an item or a footnote-definition,
  4525. ;; ignore first line's indentation.
  4526. (and (eq type 'paragraph)
  4527. (memq (org-element-type parent)
  4528. '(footnote-definition item))
  4529. (eq data (car (org-element-contents parent)))
  4530. (eq (org-element-property :pre-blank parent)
  4531. 0)))))
  4532. ""))))))
  4533. (if (memq type '(org-data nil)) results
  4534. ;; Build white spaces. If no `:post-blank' property
  4535. ;; is specified, assume its value is 0.
  4536. (let ((blank (or (org-element-property :post-blank data) 0)))
  4537. (if (eq (org-element-class data parent) 'object)
  4538. (concat results (make-string blank ?\s))
  4539. (concat (org-element--interpret-affiliated-keywords data)
  4540. (org-element-normalize-string results)
  4541. (make-string blank ?\n)))))))))
  4542. (funcall fun data nil)))
  4543. (defun org-element--interpret-affiliated-keywords (element)
  4544. "Return ELEMENT's affiliated keywords as Org syntax.
  4545. If there is no affiliated keyword, return the empty string."
  4546. (let ((keyword-to-org
  4547. (lambda (key value)
  4548. (let (dual)
  4549. (when (member key org-element-dual-keywords)
  4550. (setq dual (cdr value) value (car value)))
  4551. (concat "#+" (downcase key)
  4552. (and dual
  4553. (format "[%s]" (org-element-interpret-data dual)))
  4554. ": "
  4555. (if (member key org-element-parsed-keywords)
  4556. (org-element-interpret-data value)
  4557. value)
  4558. "\n")))))
  4559. (mapconcat
  4560. (lambda (prop)
  4561. (let ((value (org-element-property prop element))
  4562. (keyword (upcase (substring (symbol-name prop) 1))))
  4563. (when value
  4564. (if (or (member keyword org-element-multiple-keywords)
  4565. ;; All attribute keywords can have multiple lines.
  4566. (string-match "^ATTR_" keyword))
  4567. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4568. (reverse value)
  4569. "")
  4570. (funcall keyword-to-org keyword value)))))
  4571. ;; List all ELEMENT's properties matching an attribute line or an
  4572. ;; affiliated keyword, but ignore translated keywords since they
  4573. ;; cannot belong to the property list.
  4574. (cl-loop for prop in (nth 1 element) by 'cddr
  4575. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4576. (or (string-match "^ATTR_" keyword)
  4577. (and
  4578. (member keyword org-element-affiliated-keywords)
  4579. (not (assoc keyword
  4580. org-element-keyword-translation-alist)))))
  4581. collect prop)
  4582. "")))
  4583. ;; Because interpretation of the parse tree must return the same
  4584. ;; number of blank lines between elements and the same number of white
  4585. ;; space after objects, some special care must be given to white
  4586. ;; spaces.
  4587. ;;
  4588. ;; The first function, `org-element-normalize-string', ensures any
  4589. ;; string different from the empty string will end with a single
  4590. ;; newline character.
  4591. ;;
  4592. ;; The second function, `org-element-normalize-contents', removes
  4593. ;; global indentation from the contents of the current element.
  4594. (defun org-element-normalize-string (s)
  4595. "Ensure string S ends with a single newline character.
  4596. If S isn't a string return it unchanged. If S is the empty
  4597. string, return it. Otherwise, return a new string with a single
  4598. newline character at its end."
  4599. (cond
  4600. ((not (stringp s)) s)
  4601. ((string= "" s) "")
  4602. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4603. (replace-match "\n" nil nil s)))))
  4604. (defun org-element-normalize-contents (element &optional ignore-first)
  4605. "Normalize plain text in ELEMENT's contents.
  4606. ELEMENT must only contain plain text and objects.
  4607. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4608. indentation to compute maximal common indentation.
  4609. Return the normalized element that is element with global
  4610. indentation removed from its contents."
  4611. (letrec ((find-min-ind
  4612. ;; Return minimal common indentation within BLOB. This is
  4613. ;; done by walking recursively BLOB and updating MIN-IND
  4614. ;; along the way. FIRST-FLAG is non-nil when the next
  4615. ;; object is expected to be a string that doesn't start
  4616. ;; with a newline character. It happens for strings at
  4617. ;; the beginnings of the contents or right after a line
  4618. ;; break.
  4619. (lambda (blob first-flag min-ind)
  4620. (dolist (datum (org-element-contents blob) min-ind)
  4621. (when first-flag
  4622. (setq first-flag nil)
  4623. (cond
  4624. ;; Objects cannot start with spaces: in this
  4625. ;; case, indentation is 0.
  4626. ((not (stringp datum)) (throw :zero 0))
  4627. ((not (string-match
  4628. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4629. (throw :zero 0))
  4630. ((equal (match-string 2 datum) "\n")
  4631. (put-text-property
  4632. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4633. (t
  4634. (let ((i (string-width (match-string 1 datum))))
  4635. (put-text-property
  4636. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4637. (setq min-ind (min i min-ind))))))
  4638. (cond
  4639. ((stringp datum)
  4640. (let ((s 0))
  4641. (while (string-match
  4642. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4643. (setq s (match-end 1))
  4644. (cond
  4645. ((equal (match-string 1 datum) "")
  4646. (unless (member (match-string 2 datum) '("" "\n"))
  4647. (throw :zero 0)))
  4648. ((equal (match-string 2 datum) "\n")
  4649. (put-text-property (match-beginning 1) (match-end 1)
  4650. 'org-ind 'empty datum))
  4651. (t
  4652. (let ((i (string-width (match-string 1 datum))))
  4653. (put-text-property (match-beginning 1) (match-end 1)
  4654. 'org-ind i datum)
  4655. (setq min-ind (min i min-ind))))))))
  4656. ((eq (org-element-type datum) 'line-break)
  4657. (setq first-flag t))
  4658. ((memq (org-element-type datum) org-element-recursive-objects)
  4659. (setq min-ind
  4660. (funcall find-min-ind datum first-flag min-ind)))))))
  4661. (min-ind
  4662. (catch :zero
  4663. (funcall find-min-ind
  4664. element (not ignore-first) most-positive-fixnum))))
  4665. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4666. ;; Build ELEMENT back, replacing each string with the same
  4667. ;; string minus common indentation.
  4668. (letrec ((build
  4669. (lambda (datum)
  4670. ;; Return DATUM with all its strings indentation
  4671. ;; shortened from MIN-IND white spaces.
  4672. (setcdr
  4673. (cdr datum)
  4674. (mapcar
  4675. (lambda (object)
  4676. (cond
  4677. ((stringp object)
  4678. (with-temp-buffer
  4679. (insert object)
  4680. (let ((s (point-min)))
  4681. (while (setq s (text-property-not-all
  4682. s (point-max) 'org-ind nil))
  4683. (goto-char s)
  4684. (let ((i (get-text-property s 'org-ind)))
  4685. (delete-region s (progn
  4686. (skip-chars-forward " \t")
  4687. (point)))
  4688. (when (integerp i) (indent-to (- i min-ind))))))
  4689. (buffer-string)))
  4690. ((memq (org-element-type object)
  4691. org-element-recursive-objects)
  4692. (funcall build object))
  4693. (t object)))
  4694. (org-element-contents datum)))
  4695. datum)))
  4696. (funcall build element)))))
  4697. ;;; Cache
  4698. ;;
  4699. ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
  4700. ;; fast mapping across Org elements in `org-element-cache-map', which see.
  4701. ;;
  4702. ;; When cache is enabled, the elements returned by `org-element-at-point' and
  4703. ;; `org-element-context' are returned by reference. Altering these elements will
  4704. ;; also alter their cache representation. The same is true for
  4705. ;; elements passed to mapping function in `org-element-cache-map'.
  4706. ;;
  4707. ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
  4708. ;; `org-element-cache-map'.
  4709. ;;
  4710. ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
  4711. ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
  4712. ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
  4713. ;;
  4714. ;; Internally, parsed elements are stored in an AVL tree,
  4715. ;; `org-element--cache'. This tree is updated lazily: whenever
  4716. ;; a change happens to the buffer, a synchronization request is
  4717. ;; registered in `org-element--cache-sync-requests' (see
  4718. ;; `org-element--cache-submit-request'). During idle time, requests
  4719. ;; are processed by `org-element--cache-sync'. Synchronization also
  4720. ;; happens when an element is required from the cache. In this case,
  4721. ;; the process stops as soon as the needed element is up-to-date.
  4722. ;;
  4723. ;; A synchronization request can only apply on a synchronized part of
  4724. ;; the cache. Therefore, the cache is updated at least to the
  4725. ;; location where the new request applies. Thus, requests are ordered
  4726. ;; from left to right and all elements starting before the first
  4727. ;; request are correct. This property is used by functions like
  4728. ;; `org-element--cache-find' to retrieve elements in the part of the
  4729. ;; cache that can be trusted.
  4730. ;;
  4731. ;; A request applies to every element, starting from its original
  4732. ;; location (or key, see below). When a request is processed, it
  4733. ;; moves forward and may collide the next one. In this case, both
  4734. ;; requests are merged into a new one that starts from that element.
  4735. ;; As a consequence, the whole synchronization complexity does not
  4736. ;; depend on the number of pending requests, but on the number of
  4737. ;; elements the very first request will be applied on.
  4738. ;;
  4739. ;; Elements cannot be accessed through their beginning position, which
  4740. ;; may or may not be up-to-date. Instead, each element in the tree is
  4741. ;; associated to a key, obtained with `org-element--cache-key'. This
  4742. ;; mechanism is robust enough to preserve total order among elements
  4743. ;; even when the tree is only partially synchronized.
  4744. ;;
  4745. ;; The cache code debuggin is fairly complex because cache request
  4746. ;; state is often hard to reproduce. An extensive diagnostics
  4747. ;; functionality is built into the cache code to assist hunting bugs.
  4748. ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
  4749. ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
  4750. ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
  4751. ;; `org-element--cache-map-statistics-threshold'.
  4752. (defvar org-element-use-cache t
  4753. "Non-nil when Org parser should cache its results.")
  4754. (defvar org-element-cache-persistent t
  4755. "Non-nil when cache should persist between Emacs sessions.")
  4756. (defvar org-element-cache-sync-idle-time 0.6
  4757. "Length, in seconds, of idle time before syncing cache.")
  4758. (defvar org-element-cache-sync-duration 0.04
  4759. "Maximum duration, as a time value, for a cache synchronization.
  4760. If the synchronization is not over after this delay, the process
  4761. pauses and resumes after `org-element-cache-sync-break'
  4762. seconds.")
  4763. (defvar org-element-cache-sync-break 0.3
  4764. "Duration, as a time value, of the pause between synchronizations.
  4765. See `org-element-cache-sync-duration' for more information.")
  4766. (defvar org-element--cache-self-verify t
  4767. "Activate extra consistency checks for the cache.
  4768. This may cause serious performance degradation depending on the value
  4769. of `org-element--cache-self-verify-frequency'.
  4770. When set to symbol `backtrace', record and display backtrace log if
  4771. any inconsistency is detected.")
  4772. (defvar org-element--cache-self-verify-frequency 0.03
  4773. "Frequency of cache element verification.
  4774. This number is a probability to check an element requested from cache
  4775. to be correct. Setting this to a value less than 0.0001 is useless.")
  4776. (defvar org-element--cache-diagnostics nil
  4777. "Print detailed diagnostics of cache processing.")
  4778. (defvar org-element--cache-map-statistics nil
  4779. "Print statistics for `org-element-cache-map'.")
  4780. (defvar org-element--cache-map-statistics-threshold 0.1
  4781. "Time threshold in seconds to log statistics for `org-element-cache-map'.")
  4782. (defvar org-element--cache-diagnostics-level 2
  4783. "Detail level of the diagnostics.")
  4784. (defvar-local org-element--cache-diagnostics-ring nil
  4785. "Ring containing last `org-element--cache-diagnostics-ring-size'
  4786. cache process log entries.")
  4787. (defvar org-element--cache-diagnostics-ring-size 5000
  4788. "Size of `org-element--cache-diagnostics-ring'.")
  4789. ;;;; Data Structure
  4790. (defvar-local org-element--cache nil
  4791. "AVL tree used to cache elements.
  4792. Each node of the tree contains an element. Comparison is done
  4793. with `org-element--cache-compare'. This cache is used in
  4794. `org-element-at-point'.")
  4795. (defvar-local org-element--headline-cache nil
  4796. "AVL tree used to cache headline and inlinetask elements.
  4797. Each node of the tree contains an element. Comparison is done
  4798. with `org-element--cache-compare'. This cache is used in
  4799. `org-element-cache-map'.")
  4800. (defvar-local org-element--cache-size 0
  4801. "Size of the `org-element--cache'.
  4802. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4803. (defvar-local org-element--headline-cache-size 0
  4804. "Size of the `org-element--headline-cache'.
  4805. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4806. (defvar-local org-element--cache-sync-requests nil
  4807. "List of pending synchronization requests.
  4808. A request is a vector with the following pattern:
  4809. [NEXT BEG END OFFSET PARENT PHASE]
  4810. Processing a synchronization request consists of three phases:
  4811. 0. Delete modified elements,
  4812. 1. Fill missing area in cache,
  4813. 2. Shift positions and re-parent elements after the changes.
  4814. During phase 0, NEXT is the key of the first element to be
  4815. removed, BEG and END is buffer position delimiting the
  4816. modifications. Elements starting between them (inclusive) are
  4817. removed. So are elements whose parent is removed. PARENT, when
  4818. non-nil, is the common parent of all the elements between BEG and END.
  4819. It is guaranteed that only a single phase 0 request exists at any
  4820. moment of time. If it does, it must be the first request in the list.
  4821. During phase 1, NEXT is the key of the next known element in
  4822. cache and BEG its beginning position. Parse buffer between that
  4823. element and the one before it in order to determine the parent of
  4824. the next element. Set PARENT to the element containing NEXT.
  4825. During phase 2, NEXT is the key of the next element to shift in
  4826. the parse tree. All elements starting from this one have their
  4827. properties relative to buffer positions shifted by integer
  4828. OFFSET and, if they belong to element PARENT, are adopted by it.
  4829. PHASE specifies the phase number, as an integer.
  4830. For any synchronisation request, all the later requests in the cache
  4831. must not start at or before END. See `org-element--cache-submit-request'.")
  4832. (defvar-local org-element--cache-sync-timer nil
  4833. "Timer used for cache synchronization.")
  4834. (defvar-local org-element--cache-sync-keys-value nil
  4835. "Id value used to identify keys during synchronisation.
  4836. See `org-element--cache-key' for more information.")
  4837. (defvar-local org-element--cache-change-tic nil
  4838. "Last `buffer-chars-modified-tick' for registered changes.")
  4839. (defvar org-element--cache-non-modifying-commands '(org-agenda
  4840. org-agenda-redo
  4841. org-sparse-tree
  4842. org-occur
  4843. org-columns
  4844. org-columns-redo
  4845. org-columns-new
  4846. org-columns-delete
  4847. org-columns-compute
  4848. org-columns-insert-dblock
  4849. org-agenda-columns
  4850. org-ctrl-c-ctrl-c)
  4851. "List of commands that are not expected to change the cache state.
  4852. This variable is used to determine when re-parsing buffer is not going
  4853. to slow down the command.
  4854. If the commends end up modifying the cache, the worst case scenario is
  4855. performance drop. So, advicing these commands is safe. Yet, it is
  4856. better to remove the commands adviced in such way from this list.")
  4857. (defmacro org-element--request-key (request)
  4858. "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
  4859. `(aref ,request 0))
  4860. (defmacro org-element--request-beg (request)
  4861. "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
  4862. `(aref ,request 1))
  4863. (defmacro org-element--request-end (request)
  4864. "Get END part of a `org-element--cache-sync-requests' REQUEST."
  4865. `(aref ,request 2))
  4866. (defmacro org-element--request-offset (request)
  4867. "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
  4868. `(aref ,request 3))
  4869. (defmacro org-element--request-parent (request)
  4870. "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
  4871. `(aref ,request 4))
  4872. (defmacro org-element--request-phase (request)
  4873. "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
  4874. `(aref ,request 5))
  4875. (defmacro org-element--format-element (element)
  4876. "Format ELEMENT for printing in diagnostics."
  4877. `(let ((print-length 50)
  4878. (print-level 5))
  4879. (prin1-to-string ,element)))
  4880. (defmacro org-element--cache-log-message (format-string &rest args)
  4881. "Add a new log message for org-element-cache."
  4882. `(when (or org-element--cache-diagnostics
  4883. (eq org-element--cache-self-verify 'backtrace))
  4884. (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
  4885. (buffer-name (current-buffer)))
  4886. ,format-string))
  4887. (format-string (funcall #'format format-string ,@args)))
  4888. (if org-element--cache-diagnostics
  4889. (warn "%s" format-string)
  4890. (unless org-element--cache-diagnostics-ring
  4891. (setq org-element--cache-diagnostics-ring
  4892. (make-ring org-element--cache-diagnostics-ring-size)))
  4893. (ring-insert org-element--cache-diagnostics-ring format-string)))))
  4894. (defmacro org-element--cache-warn (format-string &rest args)
  4895. "Raise warning for org-element-cache."
  4896. `(let* ((format-string (funcall #'format ,format-string ,@args))
  4897. (format-string
  4898. (if (or (not org-element--cache-diagnostics-ring)
  4899. (not (eq 'backtrace org-element--cache-self-verify)))
  4900. format-string
  4901. (prog1
  4902. (concat (format "Warning(%s): "
  4903. (buffer-name (current-buffer)))
  4904. format-string
  4905. "\nBacktrace:\n "
  4906. (mapconcat #'identity
  4907. (ring-elements org-element--cache-diagnostics-ring)
  4908. "\n "))
  4909. (setq org-element--cache-diagnostics-ring nil)))))
  4910. (if (and (boundp 'org-batch-test) org-batch-test)
  4911. (error "%s" (concat "org-element--cache: " format-string))
  4912. (warn "%s" (concat "org-element--cache: " format-string)))))
  4913. (defsubst org-element--cache-key (element)
  4914. "Return a unique key for ELEMENT in cache tree.
  4915. Keys are used to keep a total order among elements in the cache.
  4916. Comparison is done with `org-element--cache-key-less-p'.
  4917. When no synchronization is taking place, a key is simply the
  4918. beginning position of the element, or that position plus one in
  4919. the case of an first item (respectively row) in
  4920. a list (respectively a table). They key of a section is its beginning
  4921. position minus one.
  4922. During a synchronization, the key is the one the element had when
  4923. the cache was synchronized for the last time. Elements added to
  4924. cache during the synchronization get a new key generated with
  4925. `org-element--cache-generate-key'.
  4926. Such keys are stored inside the element property
  4927. `:org-element--cache-sync-key'. The property is a cons containing
  4928. current `org-element--cache-sync-keys-value' and the element key."
  4929. (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
  4930. (cdr (org-element-property :org-element--cache-sync-key element)))
  4931. (let* ((begin (org-element-property :begin element))
  4932. ;; Increase beginning position of items (respectively
  4933. ;; table rows) by one, so the first item can get
  4934. ;; a different key from its parent list (respectively
  4935. ;; table).
  4936. (key (if (memq (org-element-type element) '(item table-row))
  4937. (1+ begin)
  4938. ;; Decrease beginning position of sections by one,
  4939. ;; so that the first element of the section get
  4940. ;; different key from the parent section.
  4941. (if (eq (org-element-type element) 'section)
  4942. (1- begin)
  4943. (if (eq (org-element-type element) 'org-data)
  4944. (- begin 2)
  4945. begin)))))
  4946. (when org-element--cache-sync-requests
  4947. (org-element-put-property element
  4948. :org-element--cache-sync-key
  4949. (cons org-element--cache-sync-keys-value key)))
  4950. key)))
  4951. (defun org-element--cache-generate-key (lower upper)
  4952. "Generate a key between LOWER and UPPER.
  4953. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4954. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4955. a unique key, as an integer or a list of integers, according to
  4956. the following rules:
  4957. - LOWER and UPPER are compared level-wise until values differ.
  4958. - If, at a given level, LOWER and UPPER differ from more than
  4959. 2, the new key shares all the levels above with LOWER and
  4960. gets a new level. Its value is the mean between LOWER and
  4961. UPPER:
  4962. (1 2) + (1 4) --> (1 3)
  4963. - If LOWER has no value to compare with, it is assumed that its
  4964. value is `most-negative-fixnum'. E.g.,
  4965. (1 1) + (1 1 2)
  4966. is equivalent to
  4967. (1 1 m) + (1 1 2)
  4968. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4969. short of levels, the current value is `most-positive-fixnum'.
  4970. - If they differ from only one, the new key inherits from
  4971. current LOWER level and fork it at the next level. E.g.,
  4972. (2 1) + (3 3)
  4973. is equivalent to
  4974. (2 1) + (2 M)
  4975. where M is `most-positive-fixnum'.
  4976. - If the key is only one level long, it is returned as an
  4977. integer:
  4978. (1 2) + (3 2) --> 2
  4979. When they are not equals, the function assumes that LOWER is
  4980. lesser than UPPER, per `org-element--cache-key-less-p'."
  4981. (if (equal lower upper) lower
  4982. (let ((lower (if (integerp lower) (list lower) lower))
  4983. (upper (if (integerp upper) (list upper) upper))
  4984. skip-upper key)
  4985. (catch 'exit
  4986. (while t
  4987. (let ((min (or (car lower) most-negative-fixnum))
  4988. (max (cond (skip-upper most-positive-fixnum)
  4989. ((car upper))
  4990. (t most-positive-fixnum))))
  4991. (if (< (1+ min) max)
  4992. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  4993. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  4994. (when (and (< min max) (not skip-upper))
  4995. ;; When at a given level, LOWER and UPPER differ from
  4996. ;; 1, ignore UPPER altogether. Instead create a key
  4997. ;; between LOWER and the greatest key with the same
  4998. ;; prefix as LOWER so far.
  4999. (setq skip-upper t))
  5000. (push min key)
  5001. (setq lower (cdr lower) upper (cdr upper)))))))))
  5002. (defsubst org-element--cache-key-less-p (a b)
  5003. "Non-nil if key A is less than key B.
  5004. A and B are either integers or lists of integers, as returned by
  5005. `org-element--cache-key'."
  5006. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  5007. (if (integerp b) (< (car a) b)
  5008. (catch 'exit
  5009. (while (and a b)
  5010. (cond ((car-less-than-car a b) (throw 'exit t))
  5011. ((car-less-than-car b a) (throw 'exit nil))
  5012. (t (setq a (cdr a) b (cdr b)))))
  5013. ;; If A is empty, either keys are equal (B is also empty) and
  5014. ;; we return nil, or A is lesser than B (B is longer) and we
  5015. ;; return a non-nil value.
  5016. ;;
  5017. ;; If A is not empty, B is necessarily empty and A is greater
  5018. ;; than B (A is longer). Therefore, return nil.
  5019. (and (null a) b)))))
  5020. (defun org-element--cache-compare (a b)
  5021. "Non-nil when element A is located before element B."
  5022. (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
  5023. (defsubst org-element--cache-root ()
  5024. "Return root value in `org-element--cache' .
  5025. This function assumes `org-element--cache' is a valid AVL tree."
  5026. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  5027. (defsubst org-element--headline-cache-root ()
  5028. "Return root value in `org-element--headline-cache' .
  5029. This function assumes `org-element--headline-cache' is a valid AVL tree."
  5030. (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
  5031. ;;;; Tools
  5032. (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
  5033. "Non-nil when cache is active in current buffer."
  5034. (and org-element-use-cache
  5035. org-element--cache
  5036. (derived-mode-p 'org-mode)
  5037. (or called-from-cache-change-func-p
  5038. (and
  5039. ;; org-num-mode calls some Org structure analysis functions
  5040. ;; that can trigger cache update in the middle of changes. See
  5041. ;; `org-num--verify' calling `org-num--skip-value' calling
  5042. ;; `org-entry-get' that uses cache.
  5043. ;; Forcefully disable cache when called from inside a
  5044. ;; modification hook, where `inhibit-modification-hooks' is set
  5045. ;; to t.
  5046. (not inhibit-modification-hooks)
  5047. ;; `combine-change-calls' sets `after-change-functions' to
  5048. ;; nil. We need not to use cache inside
  5049. ;; `combine-change-calls' because the buffer is potentially
  5050. ;; changed without notice (the change will be registered
  5051. ;; after exiting the `combine-change-calls' body though).
  5052. (memq #'org-element--cache-after-change after-change-functions))
  5053. (eq org-element--cache-change-tic (buffer-chars-modified-tick)))))
  5054. (defun org-element--cache-find (pos &optional side)
  5055. "Find element in cache starting at POS or before.
  5056. POS refers to a buffer position.
  5057. When optional argument SIDE is non-nil, the function checks for
  5058. elements starting at or past POS instead. If SIDE is `both', the
  5059. function returns a cons cell where car is the first element
  5060. starting at or before POS and cdr the first element starting
  5061. after POS.
  5062. The function can only find elements in the synchronized part of
  5063. the cache."
  5064. (with-current-buffer (or (buffer-base-buffer) (current-buffer))
  5065. (let ((limit (and org-element--cache-sync-requests
  5066. (org-element--request-key (car org-element--cache-sync-requests))))
  5067. (node (org-element--cache-root))
  5068. lower upper)
  5069. (while node
  5070. (let* ((element (avl-tree--node-data node))
  5071. (begin (org-element-property :begin element)))
  5072. (cond
  5073. ((and limit
  5074. (not (org-element--cache-key-less-p
  5075. (org-element--cache-key element) limit)))
  5076. (setq node (avl-tree--node-left node)))
  5077. ((> begin pos)
  5078. (setq upper element
  5079. node (avl-tree--node-left node)))
  5080. ((or (< begin pos)
  5081. ;; If the element is section or org-data, we also need
  5082. ;; to check the following element.
  5083. (memq (org-element-type element) '(section org-data)))
  5084. (setq lower element
  5085. node (avl-tree--node-right node)))
  5086. ;; We found an element in cache starting at POS. If `side'
  5087. ;; is `both' we also want the next one in order to generate
  5088. ;; a key in-between.
  5089. ;;
  5090. ;; If the element is the first row or item in a table or
  5091. ;; a plain list, we always return the table or the plain
  5092. ;; list.
  5093. ;;
  5094. ;; In any other case, we return the element found.
  5095. ((eq side 'both)
  5096. (setq lower element)
  5097. (setq node (avl-tree--node-right node)))
  5098. ((and (memq (org-element-type element) '(item table-row))
  5099. (let ((parent (org-element-property :parent element)))
  5100. (and (= (org-element-property :begin element)
  5101. (org-element-property :contents-begin parent))
  5102. (setq node nil
  5103. lower parent
  5104. upper parent)))))
  5105. (t
  5106. (setq node nil
  5107. lower element
  5108. upper element)))))
  5109. (pcase side
  5110. (`both (cons lower upper))
  5111. (`nil lower)
  5112. (_ upper)))))
  5113. (defun org-element--cache-put (element)
  5114. "Store ELEMENT in current buffer's cache, if allowed."
  5115. (when (org-element--cache-active-p)
  5116. (when org-element--cache-sync-requests
  5117. ;; During synchronization, first build an appropriate key for
  5118. ;; the new element so `avl-tree-enter' can insert it at the
  5119. ;; right spot in the cache.
  5120. (let* ((keys (org-element--cache-find
  5121. (org-element-property :begin element) 'both))
  5122. (new-key (org-element--cache-generate-key
  5123. (and (car keys) (org-element--cache-key (car keys)))
  5124. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  5125. (org-element--cache-sync-requests
  5126. (org-element--request-key (car org-element--cache-sync-requests)))))))
  5127. (org-element-put-property element
  5128. :org-element--cache-sync-key
  5129. (cons org-element--cache-sync-keys-value new-key))))
  5130. (when (>= org-element--cache-diagnostics-level 2)
  5131. (org-element--cache-log-message "Added new element with %S key: %S"
  5132. (org-element-property :org-element--cache-sync-key element)
  5133. (org-element--format-element element)))
  5134. (org-element-put-property element :cached t)
  5135. (when (memq (org-element-type element) '(headline inlinetask))
  5136. (cl-incf org-element--headline-cache-size)
  5137. (avl-tree-enter org-element--headline-cache element))
  5138. (cl-incf org-element--cache-size)
  5139. (avl-tree-enter org-element--cache element)))
  5140. (defsubst org-element--cache-remove (element)
  5141. "Remove ELEMENT from cache.
  5142. Assume ELEMENT belongs to cache and that a cache is active."
  5143. (org-element-put-property element :cached nil)
  5144. (cl-decf org-element--cache-size)
  5145. ;; Invalidate contents of parent.
  5146. (when (and (org-element-property :parent element)
  5147. (org-element-contents (org-element-property :parent element)))
  5148. (org-element-set-contents (org-element-property :parent element) nil))
  5149. (when (memq (org-element-type element) '(headline inlinetask))
  5150. (cl-decf org-element--headline-cache-size)
  5151. (avl-tree-delete org-element--headline-cache element))
  5152. (or (avl-tree-delete org-element--cache element)
  5153. (progn
  5154. ;; This should not happen, but if it is, would be better to know
  5155. ;; where it happens.
  5156. (org-element--cache-warn "Failed to delete %S element in %S at %S. The element cache key was %S.
  5157. If this warning appears regularly, please report it to Org mode mailing list (M-x org-submit-bug-report)."
  5158. (org-element-type element)
  5159. (current-buffer)
  5160. (org-element-property :begin element)
  5161. (org-element-property :org-element--cache-sync-key element))
  5162. (org-element-cache-reset)
  5163. (throw 'quit nil))))
  5164. ;;;; Synchronization
  5165. (defsubst org-element--cache-set-timer (buffer)
  5166. "Set idle timer for cache synchronization in BUFFER."
  5167. (when org-element--cache-sync-timer
  5168. (cancel-timer org-element--cache-sync-timer))
  5169. (setq org-element--cache-sync-timer
  5170. (run-with-idle-timer
  5171. (let ((idle (current-idle-time)))
  5172. (if idle (time-add idle org-element-cache-sync-break)
  5173. org-element-cache-sync-idle-time))
  5174. nil
  5175. #'org-element--cache-sync
  5176. buffer)))
  5177. (defsubst org-element--cache-interrupt-p (time-limit)
  5178. "Non-nil when synchronization process should be interrupted.
  5179. TIME-LIMIT is a time value or nil."
  5180. (and time-limit
  5181. (or (input-pending-p)
  5182. (time-less-p time-limit nil))))
  5183. (defsubst org-element--cache-shift-positions (element offset &optional props)
  5184. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  5185. Properties containing buffer positions are `:begin', `:end',
  5186. `:contents-begin', `:contents-end' and `:structure'. When
  5187. optional argument PROPS is a list of keywords, only shift
  5188. properties provided in that list.
  5189. Properties are modified by side-effect."
  5190. (let ((properties (nth 1 element)))
  5191. ;; Shift `:structure' property for the first plain list only: it
  5192. ;; is the only one that really matters and it prevents from
  5193. ;; shifting it more than once.
  5194. (when (and (or (not props) (memq :structure props))
  5195. (eq (org-element-type element) 'plain-list)
  5196. (not (eq (org-element-type (plist-get properties :parent)) 'item)))
  5197. (dolist (item (plist-get properties :structure))
  5198. (cl-incf (car item) offset)
  5199. (cl-incf (nth 6 item) offset)))
  5200. (dolist (key '( :begin :contents-begin :contents-end :end
  5201. :post-affiliated :robust-begin :robust-end))
  5202. (let ((value (and (or (not props) (memq key props))
  5203. (plist-get properties key))))
  5204. (and value (plist-put properties key (+ offset value)))))))
  5205. (defvar org-element--cache-interrupt-C-g t
  5206. "When non-nil, allow the user to abort `org-element--cache-sync'.
  5207. The execution is aborted upon pressing `\\[keyboard-quit]'
  5208. `org-element--cache-interrupt-C-g-max-count' times.")
  5209. (defvar org-element--cache-interrupt-C-g-max-count 5
  5210. "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
  5211. See `org-element--cache-interrupt-C-g'.")
  5212. (defvar org-element--cache-interrupt-C-g-count 0
  5213. "Current number of `org-element--cache-sync' calls.
  5214. See `org-element--cache-interrupt-C-g'.")
  5215. (defun org-element--cache-sync (buffer &optional threshold future-change)
  5216. "Synchronize cache with recent modification in BUFFER.
  5217. When optional argument THRESHOLD is non-nil, do the
  5218. synchronization for all elements starting before or at threshold,
  5219. then exit. Otherwise, synchronize cache for as long as
  5220. `org-element-cache-sync-duration' or until Emacs leaves idle
  5221. state.
  5222. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  5223. not registered yet in the cache are going to happen. It is used
  5224. in `org-element--cache-submit-request', where cache is partially
  5225. updated before current modification are actually submitted."
  5226. (when (buffer-live-p buffer)
  5227. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  5228. ;; Check if the buffer have been changed outside visibility of
  5229. ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
  5230. (if (/= org-element--cache-change-tic
  5231. (buffer-chars-modified-tick))
  5232. (progn
  5233. (org-element--cache-warn "Unregistered buffer modifications detected. Resetting.
  5234. If this warning appears regularly, please report it to Org mode mailing list (M-x org-submit-bug-report).
  5235. The buffer is: %s\n Current command: %S\n Backtrace:\n%S"
  5236. (buffer-name (current-buffer))
  5237. this-command
  5238. (backtrace-to-string (backtrace-get-frames 'backtrace)))
  5239. (org-element-cache-reset))
  5240. (let ((inhibit-quit t) request next)
  5241. (setq org-element--cache-interrupt-C-g-count 0)
  5242. (when org-element--cache-sync-timer
  5243. (cancel-timer org-element--cache-sync-timer))
  5244. (let ((time-limit (time-add nil org-element-cache-sync-duration)))
  5245. (catch 'org-element--cache-interrupt
  5246. (when org-element--cache-sync-requests
  5247. (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
  5248. (while org-element--cache-sync-requests
  5249. (setq request (car org-element--cache-sync-requests)
  5250. next (nth 1 org-element--cache-sync-requests))
  5251. (org-element--cache-process-request
  5252. request
  5253. (when next (org-element--request-key next))
  5254. threshold
  5255. (unless threshold time-limit)
  5256. future-change)
  5257. ;; Re-assign current and next requests. It could have
  5258. ;; been altered during phase 1.
  5259. (setq request (car org-element--cache-sync-requests)
  5260. next (nth 1 org-element--cache-sync-requests))
  5261. ;; Request processed. Merge current and next offsets and
  5262. ;; transfer ending position.
  5263. (when next
  5264. ;; The following requests can only be either phase 1
  5265. ;; or phase 2 requests. We need to let them know
  5266. ;; that additional shifting happened ahead of them.
  5267. (cl-incf (org-element--request-offset next) (org-element--request-offset request))
  5268. (org-element--cache-log-message "Updating next request offset to %d: %s"
  5269. (org-element--request-offset next)
  5270. (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
  5271. ;; FIXME: END part of the request only matters for
  5272. ;; phase 0 requests. However, the only possible
  5273. ;; phase 0 request must be the first request in the
  5274. ;; list all the time. END position should be
  5275. ;; unused.
  5276. (setf (org-element--request-end next) (org-element--request-end request)))
  5277. (setq org-element--cache-sync-requests
  5278. (cdr org-element--cache-sync-requests)))))
  5279. ;; If more requests are awaiting, set idle timer accordingly.
  5280. ;; Otherwise, reset keys.
  5281. (if org-element--cache-sync-requests
  5282. (org-element--cache-set-timer buffer)
  5283. (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value))))))))
  5284. (defun org-element--cache-process-request
  5285. (request next-request-key threshold time-limit future-change)
  5286. "Process synchronization REQUEST for all entries before NEXT.
  5287. REQUEST is a vector, built by `org-element--cache-submit-request'.
  5288. NEXT-REQUEST-KEY is a cache key of the next request, as returned by
  5289. `org-element--cache-key'.
  5290. When non-nil, THRESHOLD is a buffer position. Synchronization
  5291. stops as soon as a shifted element begins after it.
  5292. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  5293. after this time or when Emacs exits idle state.
  5294. When non-nil, FUTURE-CHANGE is a buffer position where changes
  5295. not registered yet in the cache are going to happen. See
  5296. `org-element--cache-submit-request' for more information.
  5297. Throw `org-element--cache-interrupt' if the process stops before
  5298. completing the request."
  5299. (org-element--cache-log-message "org-element-cache: Processing request %s up to %S-%S, next: %S"
  5300. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5301. future-change
  5302. threshold
  5303. next-request-key)
  5304. (catch 'quit
  5305. (when (= (org-element--request-phase request) 0)
  5306. ;; Phase 0.
  5307. ;;
  5308. ;; Delete all elements starting after beginning of the element
  5309. ;; with request key NEXT, but not after buffer position END.
  5310. ;;
  5311. ;; At each iteration, we start again at tree root since
  5312. ;; a deletion modifies structure of the balanced tree.
  5313. (org-element--cache-log-message "Phase 0")
  5314. (catch 'end-phase
  5315. (let ((deletion-count 0))
  5316. (while t
  5317. (when (org-element--cache-interrupt-p time-limit)
  5318. (org-element--cache-log-message "Interrupt: time limit")
  5319. (throw 'org-element--cache-interrupt nil))
  5320. (let ((request-key (org-element--request-key request))
  5321. (end (org-element--request-end request))
  5322. (node (org-element--cache-root))
  5323. data data-key)
  5324. ;; Find first element in cache with key REQUEST-KEY or
  5325. ;; after it.
  5326. (while node
  5327. (let* ((element (avl-tree--node-data node))
  5328. (key (org-element--cache-key element)))
  5329. (cond
  5330. ((org-element--cache-key-less-p key request-key)
  5331. (setq node (avl-tree--node-right node)))
  5332. ((org-element--cache-key-less-p request-key key)
  5333. (setq data element
  5334. data-key key
  5335. node (avl-tree--node-left node)))
  5336. (t (setq data element
  5337. data-key key
  5338. node nil)))))
  5339. (if data
  5340. ;; We found first element in cache starting at or
  5341. ;; after REQUEST-KEY.
  5342. (let ((pos (org-element-property :begin data)))
  5343. ;; FIXME: Maybe simply (< pos end)?
  5344. (if (<= pos end)
  5345. (progn
  5346. (org-element--cache-log-message "removing %S::%S"
  5347. (org-element-property :org-element--cache-sync-key data)
  5348. (org-element--format-element data))
  5349. (cl-incf deletion-count)
  5350. (org-element--cache-remove data)
  5351. (when (and (> (log org-element--cache-size 2) 10)
  5352. (> deletion-count
  5353. (/ org-element--cache-size (log org-element--cache-size 2))))
  5354. (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
  5355. deletion-count
  5356. org-element--cache-size
  5357. (log org-element--cache-size 2))
  5358. (org-element-cache-reset)
  5359. (throw 'quit t)))
  5360. ;; Done deleting everthing starting before END.
  5361. ;; DATA-KEY is the first known element after END.
  5362. ;; Move on to phase 1.
  5363. (org-element--cache-log-message "found element after %d: %S::%S"
  5364. end
  5365. (org-element-property :org-element--cache-sync-key data)
  5366. (org-element--format-element data))
  5367. (setf (org-element--request-key request) data-key)
  5368. (setf (org-element--request-beg request) pos)
  5369. (setf (org-element--request-phase request) 1)
  5370. (throw 'end-phase nil)))
  5371. ;; No element starting after modifications left in
  5372. ;; cache: further processing is futile.
  5373. (org-element--cache-log-message "Phase 0 deleted all elements in cache after %S!"
  5374. request-key)
  5375. (throw 'quit t)))))))
  5376. (when (= (org-element--request-phase request) 1)
  5377. ;; Phase 1.
  5378. ;;
  5379. ;; Phase 0 left a hole in the cache. Some elements after it
  5380. ;; could have parents within. For example, in the following
  5381. ;; buffer:
  5382. ;;
  5383. ;; - item
  5384. ;;
  5385. ;;
  5386. ;; Paragraph1
  5387. ;;
  5388. ;; Paragraph2
  5389. ;;
  5390. ;; if we remove a blank line between "item" and "Paragraph1",
  5391. ;; everything down to "Paragraph2" is removed from cache. But
  5392. ;; the paragraph now belongs to the list, and its `:parent'
  5393. ;; property no longer is accurate.
  5394. ;;
  5395. ;; Therefore we need to parse again elements in the hole, or at
  5396. ;; least in its last section, so that we can re-parent
  5397. ;; subsequent elements, during phase 2.
  5398. ;;
  5399. ;; Note that we only need to get the parent from the first
  5400. ;; element in cache after the hole.
  5401. ;;
  5402. ;; When next key is lesser or equal to the current one, current
  5403. ;; request is inside a to-be-shifted part of the cache. It is
  5404. ;; fine because the order of elements will not be altered by
  5405. ;; shifting. However, we cannot know the real position of the
  5406. ;; unshifted NEXT element in the current request. So, we need
  5407. ;; to sort the request list according to keys and re-start
  5408. ;; processing from the new leftmost request.
  5409. (org-element--cache-log-message "Phase 1")
  5410. (let ((key (org-element--request-key request)))
  5411. (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
  5412. ;; In theory, the only case when requests are not
  5413. ;; ordered is when key of the next request is either the
  5414. ;; same with current key or it is a key for a removed
  5415. ;; element. Either way, we can simply merge the two
  5416. ;; requests.
  5417. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5418. (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
  5419. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5420. (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
  5421. (setf (org-element--request-key next-request) key)
  5422. (setf (org-element--request-beg next-request) (org-element--request-beg request))
  5423. (setf (org-element--request-phase next-request) 1)
  5424. (throw 'quit t))))
  5425. ;; Next element will start at its beginning position plus
  5426. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  5427. ;; contains the real beginning position of the first element to
  5428. ;; shift and re-parent.
  5429. (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request))))
  5430. (cond ((and threshold (> limit threshold))
  5431. (org-element--cache-log-message "Interrupt: position %d after threshold %d" limit threshold)
  5432. (throw 'org-element--cache-interrupt nil))
  5433. ((and future-change (>= limit future-change))
  5434. ;; Changes happened around this element and they will
  5435. ;; trigger another phase 1 request. Skip re-parenting
  5436. ;; and simply proceed with shifting (phase 2) to make
  5437. ;; sure that followup phase 0 request for the recent
  5438. ;; changes can operate on the correctly shifted cache.
  5439. (org-element--cache-log-message "position %d after future change %d" limit future-change)
  5440. (setf (org-element--request-parent request) nil)
  5441. (setf (org-element--request-phase request) 2))
  5442. (t
  5443. ;; No relevant changes happened after submitting this
  5444. ;; request. We are safe to look at the actual Org
  5445. ;; buffer and calculate the new parent.
  5446. (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
  5447. (org-element--cache-log-message "New parent at %d: %S::%S"
  5448. limit
  5449. (org-element-property :org-element--cache-sync-key parent)
  5450. (org-element--format-element parent))
  5451. (setf (org-element--request-parent request) parent)
  5452. (setf (org-element--request-phase request) 2))))))
  5453. ;; Phase 2.
  5454. ;;
  5455. ;; Shift all elements starting from key START, but before NEXT, by
  5456. ;; OFFSET, and re-parent them when appropriate.
  5457. ;;
  5458. ;; Elements are modified by side-effect so the tree structure
  5459. ;; remains intact.
  5460. ;;
  5461. ;; Once THRESHOLD, if any, is reached, or once there is an input
  5462. ;; pending, exit. Before leaving, the current synchronization
  5463. ;; request is updated.
  5464. (org-element--cache-log-message "Phase 2")
  5465. (let ((start (org-element--request-key request))
  5466. (offset (org-element--request-offset request))
  5467. (parent (org-element--request-parent request))
  5468. (node (org-element--cache-root))
  5469. (stack (list nil))
  5470. (leftp t)
  5471. exit-flag continue-flag)
  5472. ;; No re-parenting nor shifting planned: request is over.
  5473. (when (and (not parent) (zerop offset))
  5474. (org-element--cache-log-message "Empty offset. Request completed.")
  5475. (throw 'quit t))
  5476. (while node
  5477. (let* ((data (avl-tree--node-data node))
  5478. (key (org-element--cache-key data)))
  5479. ;; Traverse the cache tree. Ignore all the elements before
  5480. ;; START. Note that `avl-tree-stack' would not bypass the
  5481. ;; elements before START and thus would have beeen less
  5482. ;; efficient.
  5483. (if (and leftp (avl-tree--node-left node)
  5484. (not (org-element--cache-key-less-p key start)))
  5485. (progn (push node stack)
  5486. (setq node (avl-tree--node-left node)))
  5487. ;; Shift and re-parent when current node starts at or
  5488. ;; after START, but before NEXT.
  5489. (unless (org-element--cache-key-less-p key start)
  5490. ;; We reached NEXT. Request is complete.
  5491. (when (and next-request-key
  5492. (not (org-element--cache-key-less-p key next-request-key)))
  5493. (org-element--cache-log-message "Reached next request.")
  5494. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5495. (unless (and (org-element-property :cached (org-element--request-parent next-request))
  5496. (org-element-property :begin (org-element--request-parent next-request))
  5497. (> (org-element-property :begin (org-element--request-parent next-request))
  5498. (org-element-property :begin parent)))
  5499. (setf (org-element--request-parent next-request) parent)))
  5500. (throw 'quit t))
  5501. ;; Handle interruption request. Update current request.
  5502. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  5503. (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
  5504. (setf (org-element--request-key request) key)
  5505. (setf (org-element--request-parent request) parent)
  5506. (throw 'org-element--cache-interrupt nil))
  5507. ;; Shift element.
  5508. (unless (zerop offset)
  5509. (when (>= org-element--cache-diagnostics-level 3)
  5510. (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
  5511. offset
  5512. (org-element-property :org-element--cache-sync-key data)
  5513. (org-element--format-element data)))
  5514. (org-element--cache-shift-positions data offset))
  5515. (let ((begin (org-element-property :begin data)))
  5516. ;; Update PARENT and re-parent DATA, only when
  5517. ;; necessary. Propagate new structures for lists.
  5518. (while (and parent
  5519. (<= (org-element-property :end parent) begin))
  5520. (setq parent (org-element-property :parent parent)))
  5521. (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
  5522. ;; Consider scenario when DATA lays within
  5523. ;; sensitive lines of PARENT that was found
  5524. ;; during phase 2. For example:
  5525. ;;
  5526. ;; #+ begin_quote
  5527. ;; Paragraph
  5528. ;; #+end_quote
  5529. ;;
  5530. ;; In the above source block, remove space in
  5531. ;; the first line will trigger re-parenting of
  5532. ;; the paragraph and "#+end_quote" that is also
  5533. ;; considered paragraph before the modification.
  5534. ;; However, the paragraph element stored in
  5535. ;; cache must be deleted instead.
  5536. ((and parent
  5537. (or (not (memq (org-element-type parent) org-element-greater-elements))
  5538. (and (org-element-property :contents-begin parent)
  5539. (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
  5540. (and (org-element-property :contents-end parent)
  5541. (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
  5542. (> (org-element-property :end data) (org-element-property :end parent))
  5543. (and (org-element-property :contents-end data)
  5544. (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
  5545. (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
  5546. (org-element-property :org-element--cache-sync-key data)
  5547. (org-element--format-element data))
  5548. (org-element--cache-remove data)
  5549. ;; We altered the tree structure. The tree
  5550. ;; traversal needs to be restarted.
  5551. (setf (org-element--request-key request) key)
  5552. (setf (org-element--request-parent request) parent)
  5553. ;; Restart tree traversal.
  5554. (setq node (org-element--cache-root)
  5555. stack (list nil)
  5556. leftp t
  5557. begin -1
  5558. continue-flag t))
  5559. ((and parent
  5560. (not (eq parent data))
  5561. (let ((p (org-element-property :parent data)))
  5562. (or (not p)
  5563. (< (org-element-property :begin p)
  5564. (org-element-property :begin parent))
  5565. (unless (eq p parent)
  5566. (not (org-element-property :cached p))
  5567. ;; (not (avl-tree-member-p org-element--cache p))
  5568. ))))
  5569. (org-element--cache-log-message "Updating parent in %S\n Old parent: %S\n New parent: %S"
  5570. (org-element--format-element data)
  5571. (org-element--format-element (org-element-property :parent data))
  5572. (org-element--format-element parent))
  5573. (when (and (eq 'org-data (org-element-type parent))
  5574. (not (eq 'headline (org-element-type data))))
  5575. ;; FIXME: This check is here to see whether
  5576. ;; such error happens within
  5577. ;; `org-element--cache-process-request' or somewhere
  5578. ;; else.
  5579. (org-element--cache-warn "Added org-data parent to non-headline element: %S\nIf this warning appears regularly, please report it to Org mode mailing list (M-x org-submit-bug-report)." data)
  5580. (org-element-cache-reset)
  5581. (throw 'quit t))
  5582. (org-element-put-property data :parent parent)
  5583. (let ((s (org-element-property :structure parent)))
  5584. (when (and s (org-element-property :structure data))
  5585. (org-element-put-property data :structure s)))))
  5586. ;; Cache is up-to-date past THRESHOLD. Request
  5587. ;; interruption.
  5588. (when (and threshold (> begin threshold))
  5589. (org-element--cache-log-message "Reached threshold %d: %S"
  5590. threshold
  5591. (org-element--format-element data))
  5592. (setq exit-flag t))))
  5593. (if continue-flag
  5594. (setq continue-flag nil)
  5595. (setq node (if (setq leftp (avl-tree--node-right node))
  5596. (avl-tree--node-right node)
  5597. (pop stack)))))))
  5598. ;; We reached end of tree: synchronization complete.
  5599. t))
  5600. (org-element--cache-log-message "org-element-cache: Finished process. The cache size is %d. The remaining sync requests: %S"
  5601. org-element--cache-size
  5602. (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests))))
  5603. (defsubst org-element--open-end-p (element)
  5604. "Check if ELEMENT in current buffer contains extra blank lines after
  5605. it and does not have closing term.
  5606. Examples of such elements are: section, headline, org-data,
  5607. and footnote-definition."
  5608. (and (org-element-property :contents-end element)
  5609. (= (org-element-property :contents-end element)
  5610. (save-excursion
  5611. (goto-char (org-element-property :end element))
  5612. (skip-chars-backward " \r\n\t")
  5613. (line-beginning-position 2)))))
  5614. (defun org-element--parse-to (pos &optional syncp time-limit)
  5615. "Parse elements in current section, down to POS.
  5616. Start parsing from the closest between the last known element in
  5617. cache or headline above. Return the smallest element containing
  5618. POS.
  5619. When optional argument SYNCP is non-nil, return the parent of the
  5620. element containing POS instead. In that case, it is also
  5621. possible to provide TIME-LIMIT, which is a time value specifying
  5622. when the parsing should stop. The function throws
  5623. `org-element--cache-interrupt' if the process stopped before finding
  5624. the expected result."
  5625. (catch 'exit
  5626. (save-match-data
  5627. (org-with-wide-buffer
  5628. (goto-char pos)
  5629. (save-excursion
  5630. (end-of-line)
  5631. (skip-chars-backward " \r\t\n")
  5632. ;; Within blank lines at the beginning of buffer, return nil.
  5633. (when (bobp) (throw 'exit nil)))
  5634. (let* ((cached (and (org-element--cache-active-p)
  5635. (org-element--cache-find pos nil)))
  5636. (mode (org-element-property :mode cached))
  5637. element next)
  5638. (cond
  5639. ;; Nothing in cache before point: start parsing from first
  5640. ;; element in buffer down to POS or from the beginning of the
  5641. ;; file.
  5642. ((and (not cached) (org-element--cache-active-p))
  5643. (setq element (org-element-org-data-parser))
  5644. (unless (org-element-property :begin element)
  5645. (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
  5646. (org-element--cache-log-message "Nothing in cache. Adding org-data: %S"
  5647. (org-element--format-element element))
  5648. (org-element--cache-put element)
  5649. (goto-char (org-element-property :contents-begin element))
  5650. (setq mode 'org-data))
  5651. ;; Nothing in cache before point because cache is not active.
  5652. ;; Parse from previous heading to avoid re-parsing the whole
  5653. ;; buffer above. This comes at the cost of not calculating
  5654. ;; `:parent' property for headings.
  5655. ((not cached)
  5656. (if (org-with-limited-levels (outline-previous-heading))
  5657. (progn
  5658. (setq element (org-element-headline-parser nil 'fast))
  5659. (setq mode 'planning)
  5660. (forward-line))
  5661. (setq mode 'top-comment))
  5662. (org-skip-whitespace)
  5663. (beginning-of-line))
  5664. ;; Check if CACHED or any of its ancestors contain point.
  5665. ;;
  5666. ;; If there is such an element, we inspect it in order to know
  5667. ;; if we return it or if we need to parse its contents.
  5668. ;; Otherwise, we just start parsing from location, which is
  5669. ;; right after the top-most element containing CACHED but
  5670. ;; still before POS.
  5671. ;;
  5672. ;; As a special case, if POS is at the end of the buffer, we
  5673. ;; want to return the innermost element ending there.
  5674. ;;
  5675. ;; Also, if we find an ancestor and discover that we need to
  5676. ;; parse its contents, make sure we don't start from
  5677. ;; `:contents-begin', as we would otherwise go past CACHED
  5678. ;; again. Instead, in that situation, we will resume parsing
  5679. ;; from NEXT, which is located after CACHED or its higher
  5680. ;; ancestor not containing point.
  5681. (t
  5682. (let ((up cached)
  5683. (pos (if (= (point-max) pos) (1- pos) pos)))
  5684. (while (and up (<= (org-element-property :end up) pos))
  5685. (goto-char (org-element-property :end up))
  5686. (setq element up
  5687. mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
  5688. up (org-element-property :parent up)
  5689. next (point)))
  5690. (when up (setq element up)))))
  5691. ;; Parse successively each element until we reach POS.
  5692. (let ((end (or (org-element-property :end element) (point-max)))
  5693. (parent (org-element-property :parent element)))
  5694. (while t
  5695. (when (org-element--cache-interrupt-p time-limit)
  5696. (throw 'org-element--cache-interrupt nil))
  5697. (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
  5698. (when quit-flag
  5699. (cl-incf org-element--cache-interrupt-C-g-count)
  5700. (setq quit-flag nil))
  5701. (when (>= org-element--cache-interrupt-C-g-count
  5702. org-element--cache-interrupt-C-g-max-count)
  5703. (setq quit-flag t)
  5704. (setq org-element--cache-interrupt-C-g-count 0)
  5705. (org-element-cache-reset)
  5706. (error "org-element: Parsing aborted by user. Cache has been cleared.
  5707. If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
  5708. (message (substitute-command-keys
  5709. "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
  5710. (- org-element--cache-interrupt-C-g-max-count
  5711. org-element--cache-interrupt-C-g-count)))
  5712. (unless element
  5713. ;; Do not try to parse within blank at EOB.
  5714. (unless (save-excursion
  5715. (org-skip-whitespace)
  5716. (eobp))
  5717. (setq element (org-element--current-element
  5718. end 'element mode
  5719. (org-element-property :structure parent))))
  5720. ;; Make sure that we return referenced element in cache
  5721. ;; that can be altered directly.
  5722. (if element
  5723. (setq element (or (org-element--cache-put element) element))
  5724. ;; Nothing to parse (i.e. empty file).
  5725. (throw 'exit parent))
  5726. (org-element-put-property element :parent parent))
  5727. (let ((elem-end (org-element-property :end element))
  5728. (type (org-element-type element)))
  5729. (cond
  5730. ;; Skip any element ending before point. Also skip
  5731. ;; element ending at point (unless it is also the end of
  5732. ;; buffer) since we're sure that another element begins
  5733. ;; after it.
  5734. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5735. ;; Avoid parsing headline siblings above.
  5736. (goto-char elem-end)
  5737. (when (eq type 'headline)
  5738. (save-match-data
  5739. (unless (when (and (/= 1 (org-element-property :level element))
  5740. (re-search-forward
  5741. (rx-to-string
  5742. `(and bol (repeat 1 ,(1- (org-element-property :level element)) "*") " "))
  5743. pos t))
  5744. (beginning-of-line)
  5745. t)
  5746. ;; There are headings with lower level than
  5747. ;; ELEMENT between ELEM-END and POS. Siblings
  5748. ;; may exist though. Parse starting from the
  5749. ;; last sibling or from ELEM-END if there are
  5750. ;; no other siblings.
  5751. (goto-char pos)
  5752. (re-search-backward
  5753. (rx-to-string
  5754. `(and bol (repeat ,(org-element-property :level element) "*") " "))
  5755. elem-end t))))
  5756. (setq mode (org-element--next-mode mode type nil)))
  5757. ;; A non-greater element contains point: return it.
  5758. ((not (memq type org-element-greater-elements))
  5759. (throw 'exit (if syncp parent element)))
  5760. ;; Otherwise, we have to decide if ELEMENT really
  5761. ;; contains POS. In that case we start parsing from
  5762. ;; contents' beginning.
  5763. ;;
  5764. ;; If POS is at contents' beginning but it is also at
  5765. ;; the beginning of the first item in a list or a table.
  5766. ;; In that case, we need to create an anchor for that
  5767. ;; list or table, so return it.
  5768. ;;
  5769. ;; Also, if POS is at the end of the buffer, no element
  5770. ;; can start after it, but more than one may end there.
  5771. ;; Arbitrarily, we choose to return the innermost of
  5772. ;; such elements.
  5773. ((let ((cbeg (org-element-property :contents-begin element))
  5774. (cend (org-element-property :contents-end element)))
  5775. (when (and cbeg cend
  5776. (or (< cbeg pos)
  5777. (and (= cbeg pos)
  5778. (not (memq type '(plain-list table)))))
  5779. (or (> cend pos)
  5780. ;; When we are at cend or within blank
  5781. ;; lines after, it is a special case:
  5782. ;; 1. At the end of buffer we return
  5783. ;; the innermost element.
  5784. ;; 2. At cend of element with return
  5785. ;; that element.
  5786. ;; 3. At the end of element, we would
  5787. ;; return in the earlier cond form.
  5788. ;; 4. Within blank lines after cend,
  5789. ;; when element does not have a
  5790. ;; closing keyword, we return that
  5791. ;; outermost element, unless the
  5792. ;; outermost element is a non-empty
  5793. ;; headline. In the latter case, we
  5794. ;; return the outermost element inside
  5795. ;; the headline section.
  5796. (and (org-element--open-end-p element)
  5797. (or (= (org-element-property :end element) (point-max))
  5798. (and (>= pos (org-element-property :contents-end element))
  5799. (memq (org-element-type element) '(org-data section headline)))))))
  5800. (goto-char (or next cbeg))
  5801. (setq mode (if next mode (org-element--next-mode mode type t))
  5802. next nil
  5803. parent element
  5804. end (if (org-element--open-end-p element)
  5805. (org-element-property :end element)
  5806. (org-element-property :contents-end element))))))
  5807. ;; Otherwise, return ELEMENT as it is the smallest
  5808. ;; element containing POS.
  5809. (t (throw 'exit (if syncp parent element)))))
  5810. (setq element nil))))))))
  5811. ;;;; Staging Buffer Changes
  5812. (defconst org-element--cache-sensitive-re
  5813. (concat
  5814. "^\\*+ " "\\|"
  5815. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5816. "^[ \t]*\\(?:"
  5817. "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
  5818. org-list-full-item-re "\\|"
  5819. ":\\(?: \\|$\\)" "\\|"
  5820. "\\\\begin{[A-Za-z0-9*]+}" "\\|"
  5821. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  5822. "\\)")
  5823. "Regexp matching a sensitive line, structure wise.
  5824. A sensitive line is a headline, inlinetask, block, drawer, or
  5825. latex-environment boundary. When such a line is modified,
  5826. structure changes in the document may propagate in the whole
  5827. section, possibly making cache invalid.")
  5828. (defvar org-element--cache-change-warning nil
  5829. "Non-nil when a sensitive line is about to be changed.
  5830. It is a symbol among nil, t, or a number representing smallest level of
  5831. modified headline. The level considers headline levels both before
  5832. and after the modification.")
  5833. (defun org-element--cache-before-change (beg end)
  5834. "Detect modifications in sensitive parts of Org buffer.
  5835. BEG and END are the beginning and end of the range of changed
  5836. text. See `before-change-functions' for more information.
  5837. The function returns the new value of `org-element--cache-change-warning'."
  5838. (when (org-element--cache-active-p t)
  5839. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  5840. (current-buffer))
  5841. (org-with-wide-buffer
  5842. (setq org-element--cache-change-tic (buffer-chars-modified-tick))
  5843. (goto-char beg)
  5844. (beginning-of-line)
  5845. (let ((bottom (save-excursion (goto-char end) (line-end-position))))
  5846. (prog1
  5847. (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
  5848. (org-element--cache-change-warning-after))
  5849. (setq org-element--cache-change-warning-after
  5850. (save-match-data
  5851. (let ((case-fold-search t))
  5852. (when (re-search-forward
  5853. org-element--cache-sensitive-re bottom t)
  5854. (goto-char beg)
  5855. (beginning-of-line)
  5856. (let (min-level)
  5857. (cl-loop while (re-search-forward
  5858. (rx-to-string
  5859. (if min-level
  5860. `(and bol (repeat 1 ,(1- min-level) "*") " ")
  5861. `(and bol (+ "*") " ")))
  5862. bottom t)
  5863. do (setq min-level (1- (length (match-string 0))))
  5864. until (= min-level 1))
  5865. (goto-char beg)
  5866. (beginning-of-line)
  5867. (or min-level
  5868. (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
  5869. 'org-data)
  5870. t))))))
  5871. (setq org-element--cache-change-warning
  5872. (cond
  5873. ((and (numberp org-element--cache-change-warning-before)
  5874. (numberp org-element--cache-change-warning-after))
  5875. (min org-element--cache-change-warning-after
  5876. org-element--cache-change-warning-before))
  5877. ((numberp org-element--cache-change-warning-before)
  5878. org-element--cache-change-warning-before)
  5879. ((numberp org-element--cache-change-warning-after)
  5880. org-element--cache-change-warning-after)
  5881. (t (or org-element--cache-change-warning-after
  5882. org-element--cache-change-warning-before)))))
  5883. (org-element--cache-log-message "%S is about to modify text: warning %S"
  5884. this-command
  5885. org-element--cache-change-warning)))))))
  5886. (defun org-element--cache-after-change (beg end pre)
  5887. "Update buffer modifications for current buffer.
  5888. BEG and END are the beginning and end of the range of changed
  5889. text, and the length in bytes of the pre-change text replaced by
  5890. that range. See `after-change-functions' for more information."
  5891. (when (org-element--cache-active-p t)
  5892. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  5893. (current-buffer))
  5894. (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
  5895. (org-element--cache-log-message "After change")
  5896. (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
  5897. ;; Store synchronization request.
  5898. (let ((offset (- end beg pre)))
  5899. (save-match-data
  5900. (org-element--cache-submit-request beg (- end offset) offset)))
  5901. ;; Activate a timer to process the request during idle time.
  5902. (org-element--cache-set-timer (current-buffer))))))
  5903. (defun org-element--cache-for-removal (beg end offset)
  5904. "Return first element to remove from cache.
  5905. BEG and END are buffer positions delimiting buffer modifications.
  5906. OFFSET is the size of the changes.
  5907. Returned element is usually the first element in cache containing
  5908. any position between BEG and END. As an exception, greater
  5909. elements around the changes that are robust to contents
  5910. modifications are preserved and updated according to the
  5911. changes. In the latter case, the returned element is the outermost
  5912. non-robust element affected by the changes. Note that the returned
  5913. element may end before END position in which case some cached element
  5914. starting after the returned may still be affected by the changes.
  5915. Also, when there are no elements in cache before BEG, return first
  5916. known element in cache (it may start after END)."
  5917. (let* ((elements (org-element--cache-find (1- beg) 'both))
  5918. (before (car elements))
  5919. (after (cdr elements)))
  5920. (if (not before) after
  5921. (let ((up before)
  5922. (robust-flag t))
  5923. (while up
  5924. (if (let ((type (org-element-type up)))
  5925. (or (and (memq type '( center-block dynamic-block
  5926. quote-block special-block))
  5927. ;; Sensitive change. This is
  5928. ;; unconditionally non-robust change.
  5929. (not org-element--cache-change-warning)
  5930. (let ((cbeg (org-element-property :contents-begin up))
  5931. (cend (org-element-property :contents-end up)))
  5932. (and cbeg
  5933. (<= cbeg beg)
  5934. (or (> cend end)
  5935. (and (= cend end)
  5936. (= (+ end offset) (point-max)))))))
  5937. (and (memq type '(headline section org-data))
  5938. (let ((rbeg (org-element-property :robust-begin up))
  5939. (rend (org-element-property :robust-end up)))
  5940. (and rbeg rend
  5941. (<= rbeg beg)
  5942. (or (> rend end)
  5943. (and (= rend end)
  5944. (= (+ end offset) (point-max))))))
  5945. (pcase type
  5946. ;; Sensitive change in section. Need to
  5947. ;; re-parse.
  5948. (`section (not org-element--cache-change-warning))
  5949. ;; Headline might be inserted. This is non-robust
  5950. ;; change when `up' is a `headline' or `section'
  5951. ;; with `>' level compared to the inserted headline.
  5952. ;;
  5953. ;; Also, planning info/property drawer
  5954. ;; could have been inserted. It is not
  5955. ;; robust change then.
  5956. (`headline
  5957. (and
  5958. (or (not (numberp org-element--cache-change-warning))
  5959. (> org-element--cache-change-warning
  5960. (org-element-property :level up)))
  5961. (org-with-point-at (org-element-property :contents-begin up)
  5962. (unless
  5963. (save-match-data
  5964. (when (looking-at-p org-planning-line-re)
  5965. (forward-line))
  5966. (when (looking-at org-property-drawer-re)
  5967. (< beg (match-end 0))))
  5968. 'robust))))
  5969. (`org-data (not (eq org-element--cache-change-warning 'org-data)))
  5970. (_ 'robust)))))
  5971. ;; UP is a robust greater element containing changes.
  5972. ;; We only need to extend its ending boundaries.
  5973. (progn
  5974. (org-element--cache-shift-positions
  5975. up offset
  5976. (if (and (org-element-property :robust-begin up)
  5977. (org-element-property :robust-end up))
  5978. '(:contents-end :end :robust-end)
  5979. '(:contents-end :end)))
  5980. (org-element--cache-log-message "Shifting end positions of robust parent: %S"
  5981. (org-element--format-element up)))
  5982. (unless (or
  5983. ;; UP is non-robust. Yet, if UP is headline, flagging
  5984. ;; everything inside for removal may be to
  5985. ;; costly. Instead, we should better re-parse only the
  5986. ;; headline itself when possible. If a headline is still
  5987. ;; starting from old :begin position, we do not care that
  5988. ;; its boundaries could have extended to shrinked - we
  5989. ;; will re-parent and shift them anyway.
  5990. (and (eq 'headline (org-element-type up))
  5991. ;; The change is not inside headline. Not
  5992. ;; updating here.
  5993. (not (<= beg (org-element-property :begin up)))
  5994. (not (>= end (org-element-property :end up)))
  5995. (let ((current (org-with-point-at (org-element-property :begin up)
  5996. (org-element-with-disabled-cache
  5997. (org-element--current-element (point-max))))))
  5998. (when (eq 'headline (org-element-type current))
  5999. (org-element--cache-log-message "Found non-robust headline that can be updated individually: %S"
  6000. (org-element--format-element current))
  6001. (org-element-set-element up current)
  6002. t)))
  6003. ;; If UP is org-data, the situation is similar to
  6004. ;; headline case. We just need to re-parse the
  6005. ;; org-data itself.
  6006. (when (eq 'org-data (org-element-type up))
  6007. (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
  6008. (org-element--cache-log-message "Found non-robust change invalidating org-data. Re-parsing: %S"
  6009. (org-element--format-element up))
  6010. t))
  6011. (org-element--cache-log-message "Found non-robust element: %S"
  6012. (org-element--format-element up))
  6013. (setq before up)
  6014. (when robust-flag (setq robust-flag nil))))
  6015. (unless (or (org-element-property :parent up)
  6016. (eq 'org-data (org-element-type up)))
  6017. (org-element--cache-warn "Got element without parent. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" up))
  6018. (setq up (org-element-property :parent up)))
  6019. ;; We're at top level element containing ELEMENT: if it's
  6020. ;; altered by buffer modifications, it is first element in
  6021. ;; cache to be removed. Otherwise, that first element is the
  6022. ;; following one.
  6023. ;;
  6024. ;; As a special case, do not remove BEFORE if it is a robust
  6025. ;; container for current changes.
  6026. (if (or (< (org-element-property :end before) beg) robust-flag) after
  6027. before)))))
  6028. (defun org-element--cache-submit-request (beg end offset)
  6029. "Submit a new cache synchronization request for current buffer.
  6030. BEG and END are buffer positions delimiting the minimal area
  6031. where cache data should be removed. OFFSET is the size of the
  6032. change, as an integer."
  6033. (org-element--cache-log-message "Submitting new synchronization request for [%S..%S]𝝙%S"
  6034. beg end offset)
  6035. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6036. (current-buffer))
  6037. (let ((next (car org-element--cache-sync-requests))
  6038. delete-to delete-from)
  6039. (if (and next
  6040. ;; First existing sync request is in phase 0.
  6041. (= 0 (org-element--request-phase next))
  6042. ;; Current changes intersect with the first sync request.
  6043. (> (setq delete-to (+ (org-element--request-end next)
  6044. (org-element--request-offset next)))
  6045. end)
  6046. (<= (setq delete-from (org-element--request-beg next))
  6047. end))
  6048. ;; Current changes can be merged with first sync request: we
  6049. ;; can save a partial cache synchronization.
  6050. (progn
  6051. (org-element--cache-log-message "Found another phase 0 request intersecting with current")
  6052. ;; Update OFFSET of the existing request.
  6053. (cl-incf (org-element--request-offset next) offset)
  6054. ;; If last change happened within area to be removed, extend
  6055. ;; boundaries of robust parents, if any. Otherwise, find
  6056. ;; first element to remove and update request accordingly.
  6057. (if (> beg delete-from)
  6058. ;; The current modification is completely inside NEXT.
  6059. ;; We already added the current OFFSET to the NEXT
  6060. ;; request. However, the robust elements around
  6061. ;; modifications also need to be shifted. Moreover, the
  6062. ;; new modification may also have non-nil
  6063. ;; `org-element--cache-change-warning'. In the latter case, we
  6064. ;; also need to update the request.
  6065. (let ((first (org-element--cache-for-removal beg end offset) ; Shift as needed.
  6066. ))
  6067. (org-element--cache-log-message "Current request is inside next. Candidate parent: %S"
  6068. (org-element--format-element first))
  6069. (when
  6070. ;; Non-robust element is now before NEXT. Need to
  6071. ;; update.
  6072. (and first
  6073. (org-element--cache-key-less-p (org-element--cache-key first)
  6074. (org-element--request-key next)))
  6075. (org-element--cache-log-message "Current request is inside next. New parent: %S"
  6076. (org-element--format-element first))
  6077. (setf (org-element--request-key next) (org-element--cache-key first))
  6078. (setf (org-element--request-beg next) (org-element-property :begin first))
  6079. (setf (org-element--request-end next) (max (org-element-property :end first)
  6080. (org-element--request-end next)))
  6081. (setf (org-element--request-parent next) (org-element-property :parent first))))
  6082. ;; The current and NEXT modifications are intersecting
  6083. ;; with current modification starting before NEXT and NEXT
  6084. ;; ending after current. We need to update the common
  6085. ;; non-robust parent for the new extended modification
  6086. ;; region.
  6087. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  6088. (org-element--cache-log-message "Current request intersects with next. Candidate parent: %S"
  6089. (org-element--format-element first))
  6090. (when (and first
  6091. (org-element--cache-key-less-p (org-element--cache-key first)
  6092. (org-element--request-key next)))
  6093. (org-element--cache-log-message "Current request intersects with next. Updating. New parent: %S"
  6094. (org-element--format-element first))
  6095. (setf (org-element--request-key next) (org-element--cache-key first))
  6096. (setf (org-element--request-beg next) (org-element-property :begin first))
  6097. (setf (org-element--request-end next) (max (org-element-property :end first)
  6098. (org-element--request-end next)))
  6099. (setf (org-element--request-parent next) (org-element-property :parent first))))))
  6100. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  6101. ;; if any, is no longer a 0-phase request, thus ensuring that
  6102. ;; phases are properly ordered. We need to provide OFFSET as
  6103. ;; optional parameter since current modifications are not known
  6104. ;; yet to the otherwise correct part of the cache (i.e, before
  6105. ;; the first request).
  6106. (org-element--cache-log-message "Adding new phase 0 request")
  6107. (when next (org-element--cache-sync (current-buffer) end beg))
  6108. (let ((first (org-element--cache-for-removal beg end offset)))
  6109. (if first
  6110. (push (let ((first-beg (org-element-property :begin first))
  6111. (key (org-element--cache-key first)))
  6112. (cond
  6113. ;; When changes happen before the first known
  6114. ;; element, re-parent and shift the rest of the
  6115. ;; cache.
  6116. ((> first-beg end)
  6117. (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
  6118. (vector key first-beg nil offset nil 1))
  6119. ;; Otherwise, we find the first non robust
  6120. ;; element containing END. All elements between
  6121. ;; FIRST and this one are to be removed.
  6122. ;;
  6123. ;; The current modification is completely inside
  6124. ;; FIRST. Clear and update cached elements in
  6125. ;; region containing FIRST.
  6126. ((let ((first-end (org-element-property :end first)))
  6127. (when (> first-end end)
  6128. (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
  6129. (vector key first-beg first-end offset (org-element-property :parent first) 0))))
  6130. (t
  6131. ;; Now, FIRST is the first element after BEG or
  6132. ;; non-robust element containing BEG. However,
  6133. ;; FIRST ends before END and there might be
  6134. ;; another ELEMENT before END that spans beyond
  6135. ;; END. If there is such element, we need to
  6136. ;; extend the region down to end of the common
  6137. ;; parent of FIRST and everything inside
  6138. ;; BEG..END.
  6139. (let* ((element (org-element--cache-find end))
  6140. (element-end (org-element-property :end element))
  6141. (up element))
  6142. (while (and (not (eq up first))
  6143. (setq up (org-element-property :parent up))
  6144. (>= (org-element-property :begin up) first-beg))
  6145. ;; Note that UP might have been already
  6146. ;; shifted if it is a robust element. After
  6147. ;; deletion, it can put it's end before yet
  6148. ;; unprocessed ELEMENT.
  6149. (setq element-end (max (org-element-property :end up) element-end)
  6150. element up))
  6151. ;; Extend region to remove elements between
  6152. ;; beginning of first and the end of outermost
  6153. ;; element starting before END but after
  6154. ;; beginning of first.
  6155. ;; of the FIRST.
  6156. (org-element--cache-log-message "Extending to all elements between:\n 1: %S\n 2: %S"
  6157. (org-element--format-element first)
  6158. (org-element--format-element element))
  6159. (vector key first-beg element-end offset up 0)))))
  6160. org-element--cache-sync-requests)
  6161. ;; No element to remove. No need to re-parent either.
  6162. ;; Simply shift additional elements, if any, by OFFSET.
  6163. (if org-element--cache-sync-requests
  6164. (progn
  6165. (org-element--cache-log-message "Nothing to remove. Updating offset of the next request by 𝝙%d: %S"
  6166. offset
  6167. (let ((print-level 3))
  6168. (car org-element--cache-sync-requests)))
  6169. (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
  6170. offset))
  6171. (org-element--cache-log-message "Nothing to remove. No elements in cache after %d. Terminating."
  6172. end))))))
  6173. (setq org-element--cache-change-warning nil)))
  6174. (defun org-element--cache-verify-element (element)
  6175. "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
  6176. Return non-nil when verification failed."
  6177. ;; Verify correct parent for the element.
  6178. (let ((org-element--cache-self-verify (or org-element--cache-self-verify
  6179. (and (boundp 'org-batch-test) org-batch-test)))
  6180. (org-element--cache-self-verify-frequency (if (and (boundp 'org-batch-test) org-batch-test)
  6181. 1
  6182. org-element--cache-self-verify-frequency)))
  6183. (when (and org-element--cache-self-verify
  6184. (org-element--cache-active-p)
  6185. (derived-mode-p 'org-mode)
  6186. (org-element-property :parent element)
  6187. (eq 'headline (org-element-type element))
  6188. ;; Avoid too much slowdown
  6189. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6190. (org-with-point-at (org-element-property :begin element)
  6191. (org-element-with-disabled-cache (org-up-heading-or-point-min))
  6192. (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
  6193. (eq (point) (point-min)))
  6194. (org-element--cache-warn "Cached element has wrong parent in %s. Resetting.
  6195. If this warning appears regularly, please report it to Org mode mailing list (M-x org-submit-bug-report).
  6196. The element is: %S\n The parent is: %S\n The real parent is: %S"
  6197. (buffer-name (current-buffer))
  6198. (org-element--format-element element)
  6199. (org-element--format-element (org-element-property :parent element))
  6200. (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
  6201. (org-element-cache-reset))
  6202. (org-element--cache-verify-element (org-element-property :parent element))))
  6203. ;; Verify the element itself.
  6204. (when (and org-element--cache-self-verify
  6205. (org-element--cache-active-p)
  6206. element
  6207. (not (memq (org-element-type element) '(section org-data)))
  6208. ;; Avoid too much slowdown
  6209. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6210. (let ((real-element (let (org-element-use-cache)
  6211. (org-element--parse-to
  6212. (if (memq (org-element-type element) '(table-row item))
  6213. (1+ (org-element-property :begin element))
  6214. (org-element-property :begin element))))))
  6215. (unless (and (eq (org-element-type real-element) (org-element-type element))
  6216. (eq (org-element-property :begin real-element) (org-element-property :begin element))
  6217. (eq (org-element-property :end real-element) (org-element-property :end element))
  6218. (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
  6219. (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
  6220. (or (not (org-element-property :ID real-element))
  6221. (string= (org-element-property :ID real-element) (org-element-property :ID element))))
  6222. (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
  6223. If this warning appears regularly, please report it to Org mode mailing list (M-x org-submit-bug-report).
  6224. The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
  6225. this-command
  6226. (buffer-name (current-buffer))
  6227. (if (/= org-element--cache-change-tic
  6228. (buffer-chars-modified-tick))
  6229. "no" "yes")
  6230. (org-element--format-element element)
  6231. (org-element--format-element real-element)
  6232. (org-element--cache-find (1- (org-element-property :begin real-element)))
  6233. (car (org-element--cache-find (org-element-property :begin real-element) 'both))
  6234. (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
  6235. (org-element-cache-reset))))))
  6236. ;;; Cache persistance
  6237. (defun org-element--cache-persist-before-write (var &optional buffer)
  6238. "Sync cache before saving."
  6239. (when (and org-element-use-cache
  6240. buffer
  6241. org-element-cache-persistent
  6242. (eq var 'org-element--cache)
  6243. (derived-mode-p 'org-mode)
  6244. org-element--cache)
  6245. (with-current-buffer buffer
  6246. ;; Cleanup cache request keys to avoid collisions during next
  6247. ;; Emacs session.
  6248. (avl-tree-mapc
  6249. (lambda (el)
  6250. (org-element-put-property el :org-element--cache-sync-key nil))
  6251. org-element--cache)
  6252. (org-with-wide-buffer
  6253. (org-element-at-point (point-max))))
  6254. nil))
  6255. (defun org-element--cache-persist-before-read (var &optional buffer)
  6256. "Avoid reading cache before Org mode is loaded."
  6257. (when (memq var '(org-element--cache org-element--headline-cache))
  6258. (if (not buffer) 'forbid
  6259. (with-current-buffer buffer
  6260. (unless (and org-element-use-cache
  6261. org-element-cache-persistent
  6262. (derived-mode-p 'org-mode))
  6263. 'forbid)))))
  6264. (defun org-element--cache-persist-after-read (var &optional buffer)
  6265. "Setup restored cache."
  6266. (with-current-buffer buffer
  6267. (when (and org-element-use-cache org-element-cache-persistent)
  6268. (when (and (eq var 'org-element--cache) org-element--cache)
  6269. (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
  6270. (when (and (eq var 'org-element--headline-cache) org-element--headline-cache)
  6271. (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache))))))
  6272. (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
  6273. (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
  6274. (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
  6275. ;;;; Public Functions
  6276. ;;;###autoload
  6277. (defun org-element-cache-reset (&optional all)
  6278. "Reset cache in current buffer.
  6279. When optional argument ALL is non-nil, reset cache in all Org
  6280. buffers."
  6281. (interactive "P")
  6282. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  6283. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  6284. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  6285. (when (not org-element-cache-persistent)
  6286. (org-persist-unregister 'org-element--headline-cache (current-buffer))
  6287. (org-persist-unregister 'org-element--cache (current-buffer)))
  6288. (when org-element-cache-persistent
  6289. (org-persist-register 'org-element--cache (current-buffer))
  6290. (org-persist-register 'org-element--headline-cache
  6291. (current-buffer)
  6292. :inherit 'org-element--cache))
  6293. (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
  6294. (setq-local org-element--cache-gapless nil)
  6295. (setq-local org-element--cache
  6296. (avl-tree-create #'org-element--cache-compare))
  6297. (setq-local org-element--headline-cache
  6298. (avl-tree-create #'org-element--cache-compare))
  6299. (setq-local org-element--cache-size 0)
  6300. (setq-local org-element--headline-cache-size 0)
  6301. (setq-local org-element--cache-sync-keys-value 0)
  6302. (setq-local org-element--cache-change-warning nil)
  6303. (setq-local org-element--cache-sync-requests nil)
  6304. (setq-local org-element--cache-sync-timer nil)
  6305. (add-hook 'before-change-functions
  6306. #'org-element--cache-before-change nil t)
  6307. (add-hook 'after-change-functions
  6308. #'org-element--cache-after-change nil t)))))
  6309. ;;;###autoload
  6310. (defun org-element-cache-refresh (pos)
  6311. "Refresh cache at position POS."
  6312. (when (org-element--cache-active-p)
  6313. (org-element--cache-sync (current-buffer) pos)
  6314. (org-element--cache-submit-request pos pos 0)
  6315. (org-element--cache-set-timer (current-buffer))))
  6316. (defvar warning-minimum-log-level) ; Defined in warning.el
  6317. (defvar-local org-element--cache-gapless nil
  6318. "An alist containing (granularity . `org-element--cache-change-tic') elements.
  6319. Each element indicates the latest `org-element--cache-change-tic' when
  6320. change did not contain gaps.")
  6321. (defvar org-element-cache-map--recurse nil)
  6322. ;;;###autoload
  6323. (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
  6324. next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
  6325. narrow)
  6326. "Map all elements in current buffer with FUNC according to
  6327. GRANULARITY. Collect non-nil return values into result list.
  6328. If some elements are not yet in cache, they will be added.
  6329. GRANULARITY can be `headline', `headline+inlinetask'
  6330. `greater-element', or `element'. The default is
  6331. `headline+inlinetask'. `object' granularity is not supported.
  6332. ELEMENTS is a list of elements to be mapped over.
  6333. NEXT-RE is a regexp used to search next candidate match when FUNC
  6334. returns non-nil and to search the first candidate match. FAIL-RE is a
  6335. regexp used to search next candidate match when FUNC returns nil. The
  6336. mapping will continue starting from headline at the RE match.
  6337. FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
  6338. mapped elements to elements starting at of after FROM-POS but before
  6339. TO-POS.
  6340. AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
  6341. after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
  6342. map all the elements starting from first element inside section, but
  6343. not including the section).
  6344. LIMIT-COUNT limits mapping to that many first matches where FUNC
  6345. returns non-nil.
  6346. NARROW controls whether current buffer narrowing should be preserved.
  6347. This function is a subset of what `org-element-map' does, but much
  6348. more performant. Cached elements are supplied as the single argument
  6349. of FUNC. Changes to elements made in FUNC will also alter the cache."
  6350. (unless (org-element--cache-active-p)
  6351. (error "Cache must be active."))
  6352. (unless (memq granularity '( headline headline+inlinetask
  6353. greater-element element))
  6354. (error "Unsupported granularity: %S" granularity))
  6355. ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
  6356. ;; process.
  6357. (unless (markerp to-pos)
  6358. (let ((mk (make-marker)))
  6359. (set-marker mk to-pos)
  6360. (setq to-pos mk)))
  6361. ;; Make sure that garbage collector does not stand on the way to
  6362. ;; maximum performance.
  6363. (let ((gc-cons-threshold #x40000000))
  6364. (save-excursion
  6365. (save-restriction
  6366. (unless narrow (widen))
  6367. ;; Synchronise cache up to the end of mapped region.
  6368. (org-element-at-point to-pos)
  6369. (cl-macrolet ((cache-root
  6370. ;; Use the most optimal version of cache available.
  6371. () `(if (memq granularity '(headline headline+inlinetask))
  6372. (org-element--headline-cache-root)
  6373. (org-element--cache-root)))
  6374. (cache-size
  6375. ;; Use the most optimal version of cache available.
  6376. () `(if (memq granularity '(headline headline+inlinetask))
  6377. org-element--headline-cache-size
  6378. org-element--cache-size))
  6379. (cache-walk-restart
  6380. ;; Restart tree traversal after AVL tree re-balance.
  6381. () `(when node
  6382. (org-element-at-point (point-max))
  6383. (setq node (cache-root)
  6384. stack (list nil)
  6385. leftp t
  6386. continue-flag t)))
  6387. (cache-walk-abort
  6388. ;; Abort tree traversal.
  6389. () `(setq continue-flag t
  6390. node nil))
  6391. (element-match-at-point
  6392. ;; Returning the first element to match around point.
  6393. ;; For example, if point is inside headline and
  6394. ;; granularity is restricted to headlines only, skip
  6395. ;; over all the child elements inside the headline
  6396. ;; and return the first parent headline.
  6397. ;; When we are inside a cache gap, calling
  6398. ;; `org-element-at-point' also fills the cache gap down to
  6399. ;; point.
  6400. () `(progn
  6401. ;; Parsing is one of the performance
  6402. ;; bottlenecks. Make sure to optimise it as
  6403. ;; much as possible.
  6404. ;;
  6405. ;; Avoid extra staff like timer cancels et al
  6406. ;; and only call `org-element--cache-sync-requests' when
  6407. ;; there are pending requests.
  6408. (when org-element--cache-sync-requests
  6409. (org-element--cache-sync (current-buffer)))
  6410. ;; Call `org-element--parse-to' directly avoiding any
  6411. ;; kind of `org-element-at-point' overheads.
  6412. (if restrict-elements
  6413. ;; Search directly instead of calling
  6414. ;; `org-element-lineage' to avoid funcall overheads
  6415. ;; and making sure that we do not go all
  6416. ;; the way to `org-data' as `org-element-lineage'
  6417. ;; does.
  6418. (let ((el (org-element--parse-to (point))))
  6419. (while (and el (not (memq (org-element-type el) restrict-elements)))
  6420. (setq el (org-element-property :parent el)))
  6421. el)
  6422. (org-element--parse-to (point)))))
  6423. ;; Starting from (point), search RE and move START to
  6424. ;; the next valid element to be matched according to
  6425. ;; restriction. Abort cache walk if no next element
  6426. ;; can be found. When RE is nil, just find element at
  6427. ;; point.
  6428. (move-start-to-next-match
  6429. (re) `(save-match-data
  6430. (if (or (not ,re) (re-search-forward (or (car-safe ,re) ,re) nil 'move))
  6431. (unless (or (< (point) (or start -1))
  6432. (and data
  6433. (< (point) (org-element-property :begin data))))
  6434. (if (cdr-safe ,re)
  6435. ;; Avoid parsing when we are 100%
  6436. ;; sure that regexp is good enough
  6437. ;; to find new START.
  6438. (setq start (match-beginning 0))
  6439. (setq start (max (or start -1)
  6440. (or (org-element-property :begin data) -1)
  6441. (org-element-property :begin (element-match-at-point)))))
  6442. (when (>= start to-pos) (cache-walk-abort)))
  6443. (cache-walk-abort))))
  6444. ;; Find expected begin position of an element after
  6445. ;; DATA.
  6446. (next-element-start
  6447. (data) `(let (next-start)
  6448. (if (memq granularity '(headline headline+inlinetask))
  6449. (setq next-start (or (when (memq (org-element-type data) '(headline org-data))
  6450. (org-element-property :contents-begin data))
  6451. (org-element-property :end data)))
  6452. (setq next-start (or (when (memq (org-element-type data) org-element-greater-elements)
  6453. (org-element-property :contents-begin data))
  6454. (org-element-property :end data))))
  6455. ;; DATA end may be the last element inside
  6456. ;; i.e. source block. Skip up to the end
  6457. ;; of parent in such case.
  6458. (let ((parent data))
  6459. (catch :exit
  6460. (when (eq next-start (org-element-property :contents-end parent))
  6461. (setq next-start (org-element-property :end parent)))
  6462. (while (setq parent (org-element-property :parent parent))
  6463. (if (eq next-start (org-element-property :contents-end parent))
  6464. (setq next-start (org-element-property :end parent))
  6465. (throw :exit t)))))
  6466. next-start))
  6467. ;; Check if cache does not have gaps.
  6468. (cache-gapless-p
  6469. () `(eq org-element--cache-change-tic
  6470. (alist-get granularity org-element--cache-gapless))))
  6471. ;; The core algorithm is simple walk along binary tree. However,
  6472. ;; instead of checking all the tree elements from first to last
  6473. ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
  6474. ;; the elements before FROM-POS efficiently: O(logN) instead of
  6475. ;; O(Nbefore).
  6476. ;;
  6477. ;; Later, we may also not check every single element in the
  6478. ;; binary tree after FROM-POS. Instead, we can find position of
  6479. ;; next candidate elements by means of regexp search and skip the
  6480. ;; binary tree branches that are before the next candidate:
  6481. ;; again, O(logN) instead of O(Nbetween).
  6482. ;;
  6483. ;; Some elements might not yet be in the tree. So, we also parse
  6484. ;; the empty gaps in cache as needed making sure that we do not
  6485. ;; miss anything.
  6486. (let* (;; START is always beginning of an element. When there is
  6487. ;; no element in cache at START, we are inside cache gap
  6488. ;; and need to fill it.
  6489. (start (and from-pos
  6490. (progn
  6491. (goto-char from-pos)
  6492. (org-element-property :begin (element-match-at-point)))))
  6493. ;; Some elements may start at the same position, so we
  6494. ;; also keep track of the last processed element and make
  6495. ;; sure that we do not try to search it again.
  6496. (prev after-element)
  6497. (node (cache-root))
  6498. data
  6499. (stack (list nil))
  6500. (leftp t)
  6501. result
  6502. ;; Whether previous element matched FUNC (FUNC
  6503. ;; returned non-nil).
  6504. (last-match t)
  6505. continue-flag
  6506. ;; Byte-compile FUNC making sure that it is as performant
  6507. ;; as it could be.
  6508. (func (if (or (byte-code-function-p func)
  6509. (and (symbolp func)
  6510. (subrp (symbol-function func)))
  6511. (and (symbolp func)
  6512. (fboundp 'native-comp-available-p)
  6513. (native-comp-available-p)
  6514. (fboundp 'subr-native-elisp-p)
  6515. (subr-native-elisp-p (symbol-function func)))
  6516. ;; FIXME: Working around bug
  6517. ;; https://list.orgmode.org/87tuha62rq.fsf@localhost/T/#t
  6518. ;; Byte-compilation in
  6519. ;; `org-agenda-get-scheduled' call
  6520. ;; somehow alters the FUNC result in
  6521. ;; Emacs 26 and 27, but not in Emacs
  6522. ;; >=28.
  6523. (version< emacs-version "29"))
  6524. func
  6525. (let ((warning-minimum-log-level :error)
  6526. (inhibit-message t))
  6527. (condition-case nil
  6528. (if (and (fboundp 'native-comp-available-p)
  6529. (fboundp 'native-compile)
  6530. (native-comp-available-p))
  6531. ;; Use native compilation to even better
  6532. ;; performance.
  6533. (native-compile func)
  6534. (byte-compile func))
  6535. (error func)))))
  6536. ;; Generic regexp to search next potential match. If it
  6537. ;; is a cons of (regexp . 'match-beg), we are 100% sure
  6538. ;; that the match beginning is the existing element
  6539. ;; beginning.
  6540. (next-element-re (pcase granularity
  6541. ((or `headline
  6542. (guard (eq '(headline)
  6543. restrict-elements)))
  6544. (cons
  6545. (org-with-limited-levels
  6546. org-outline-regexp-bol)
  6547. 'match-beg))
  6548. (`headline+inlinetask
  6549. (cons
  6550. (if (eq '(inlinetask) restrict-elements)
  6551. (org-inlinetask-outline-regexp)
  6552. org-outline-regexp-bol)
  6553. 'match-beg))
  6554. ;; TODO: May add other commonly
  6555. ;; searched elements as needed.
  6556. (_)))
  6557. ;; Make sure that we are not checking the same regexp twice.
  6558. (next-re (unless (and next-re
  6559. (string= next-re
  6560. (or (car-safe next-element-re)
  6561. next-element-re)))
  6562. next-re))
  6563. (fail-re (unless (and fail-re
  6564. (string= fail-re
  6565. (or (car-safe next-element-re)
  6566. next-element-re)))
  6567. fail-re))
  6568. (restrict-elements (or restrict-elements
  6569. (pcase granularity
  6570. (`headline
  6571. '(headline))
  6572. (`headline+inlinetask
  6573. '(headline inlinetask))
  6574. (`greater-element
  6575. org-element-greater-elements)
  6576. (_ nil))))
  6577. ;; Statistics
  6578. (time (float-time))
  6579. (predicate-time 0)
  6580. (count-predicate-calls-match 0)
  6581. (count-predicate-calls-fail 0))
  6582. ;; Skip to first element within region.
  6583. (goto-char (or start (point-min)))
  6584. (move-start-to-next-match next-element-re)
  6585. (unless (and start (>= start to-pos))
  6586. ;; Pre-process cache filling all the gaps.
  6587. (unless (or org-element-cache-map--recurse
  6588. (cache-gapless-p)
  6589. ;; Pre-processing all the elements in large
  6590. ;; buffers when NEXT-RE/FAIL-RE are provided
  6591. ;; may be much slower compared to using
  6592. ;; regexp.
  6593. (and (eq granularity 'element)
  6594. (or next-re fail-re)))
  6595. (let ((org-element-cache-map--recurse t))
  6596. (org-element-cache-map
  6597. #'ignore
  6598. :granularity granularity)
  6599. ;; Re-assign the cache root after filling the cache
  6600. ;; gaps.
  6601. (setq node (cache-root)))
  6602. (setf (alist-get granularity org-element--cache-gapless)
  6603. org-element--cache-change-tic))
  6604. (while node
  6605. (setq data (avl-tree--node-data node))
  6606. (if (and leftp (avl-tree--node-left node) ; Left branch.
  6607. ;; Do not move to left branch when we are before
  6608. ;; PREV.
  6609. (or (not prev)
  6610. (not (org-element--cache-key-less-p
  6611. (org-element--cache-key data)
  6612. (org-element--cache-key prev))))
  6613. ;; ... or when we are before START.
  6614. (or (not start)
  6615. (not (> start (org-element-property :begin data)))))
  6616. (progn (push node stack)
  6617. (setq node (avl-tree--node-left node)))
  6618. ;; The whole tree left to DATA is before START and
  6619. ;; PREV. DATA may still be before START (i.e. when
  6620. ;; DATA is the root or when START moved), at START, or
  6621. ;; after START.
  6622. ;;
  6623. ;; If DATA is before start, skip it over and move to
  6624. ;; subsequent elements.
  6625. ;; If DATA is at start, run FUNC if necessary and
  6626. ;; update START according and NEXT-RE, FAIL-RE,
  6627. ;; NEXT-ELEMENT-RE.
  6628. ;; If DATA is after start, we have found a cache gap
  6629. ;; and need to fill it.
  6630. (unless (or (and start (< (org-element-property :begin data) start))
  6631. (and prev (not (org-element--cache-key-less-p
  6632. (org-element--cache-key prev)
  6633. (org-element--cache-key data)))))
  6634. ;; DATA is at of after START and PREV.
  6635. (if (or (not start) (= (org-element-property :begin data) start))
  6636. ;; DATA is at START. Match it.
  6637. ;; In the process, we may alter the buffer,
  6638. ;; so also keep track of the cache state.
  6639. (let ((modified-tic org-element--cache-change-tic)
  6640. (cache-size (cache-size)))
  6641. ;; When NEXT-RE/FAIL-RE is provided, skip to
  6642. ;; next regexp match after :begin of the current
  6643. ;; element.
  6644. (when (if last-match next-re fail-re)
  6645. (goto-char (org-element-property :begin data))
  6646. (move-start-to-next-match
  6647. (if last-match next-re fail-re)))
  6648. (when (and (or (not start) (eq (org-element-property :begin data) start))
  6649. (< (org-element-property :begin data) to-pos))
  6650. ;; Calculate where next possible element
  6651. ;; starts and update START if needed.
  6652. (setq start (next-element-start data))
  6653. (goto-char start)
  6654. ;; Move START further if possible.
  6655. (when (and next-element-re
  6656. ;; Do not move if we know for
  6657. ;; sure that cache does not
  6658. ;; contain gaps. Regexp
  6659. ;; searches are not cheap.
  6660. (not (cache-gapless-p)))
  6661. (move-start-to-next-match next-element-re)
  6662. ;; Make sure that point is at START
  6663. ;; before running FUNC.
  6664. (goto-char start))
  6665. ;; Try FUNC if DATA matches all the
  6666. ;; restrictions. Calculate new START.
  6667. (when (or (not restrict-elements)
  6668. (memq (org-element-type data) restrict-elements))
  6669. ;; DATA matches restriction. FUNC may
  6670. ;;
  6671. ;; Call FUNC. FUNC may move point.
  6672. (if org-element--cache-map-statistics
  6673. (let ((before-time (float-time)))
  6674. (push (funcall func data) result)
  6675. (cl-incf predicate-time
  6676. (- (float-time)
  6677. before-time))
  6678. (if (car result)
  6679. (cl-incf count-predicate-calls-match)
  6680. (cl-incf count-predicate-calls-fail)))
  6681. (push (funcall func data) result)
  6682. (when (car result) (cl-incf count-predicate-calls-match)))
  6683. ;; Set `last-match'.
  6684. (setq last-match (car result))
  6685. ;; If FUNC moved point forward, update
  6686. ;; START.
  6687. (when (> (point) start)
  6688. (move-start-to-next-match nil))
  6689. ;; Drop nil.
  6690. (unless (car result) (pop result)))
  6691. ;; If FUNC did not move the point and we
  6692. ;; know for sure that cache does not contain
  6693. ;; gaps, do not try to calculate START in
  6694. ;; advance but simply loop to the next cache
  6695. ;; element.
  6696. (when (and (cache-gapless-p)
  6697. (eq (next-element-start data)
  6698. start))
  6699. (setq start nil))
  6700. ;; Check if the buffer has been modified.
  6701. (unless (and (eq modified-tic org-element--cache-change-tic)
  6702. (eq cache-size (cache-size)))
  6703. ;; START may no longer be valid, update
  6704. ;; it to beginning of real element.
  6705. (goto-char start)
  6706. ;; Upon modification, START may lay
  6707. ;; inside an element. We want to move
  6708. ;; it to real beginning then despite
  6709. ;; START being larger.
  6710. (setq start -1)
  6711. (move-start-to-next-match nil)
  6712. ;; The new element may now start before
  6713. ;; or at already processed position.
  6714. ;; Make sure that we continue from an
  6715. ;; element past already processed
  6716. ;; place.
  6717. (when (<= start (org-element-property :begin data))
  6718. (goto-char start)
  6719. (goto-char (next-element-start (element-match-at-point)))
  6720. (move-start-to-next-match next-element-re))
  6721. (org-element-at-point to-pos)
  6722. (cache-walk-restart))
  6723. ;; Reached LIMIT-COUNT. Abort.
  6724. (when (and limit-count
  6725. (>= count-predicate-calls-match
  6726. limit-count))
  6727. (cache-walk-abort))
  6728. (if (org-element-property :cached data)
  6729. (setq prev data)
  6730. (setq prev nil))))
  6731. ;; DATA is after START. Fill the gap.
  6732. (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
  6733. ;; Tables and lists are special, we need a
  6734. ;; trickery to make items/rows be populated
  6735. ;; into cache.
  6736. (org-element--parse-to (1+ start)))
  6737. ;; Restart tree traversal as AVL tree is
  6738. ;; re-balanced upon adding elements. We can no
  6739. ;; longer trust STACK.
  6740. (cache-walk-restart)))
  6741. ;; Second, move to the right branch of the tree or skip
  6742. ;; it alltogether.
  6743. (if continue-flag
  6744. (setq continue-flag nil)
  6745. (setq node (if (and (car stack)
  6746. ;; If START advanced beyond stack parent, skip the right branch.
  6747. (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
  6748. (and prev (org-element--cache-key-less-p
  6749. (org-element--cache-key (avl-tree--node-data (car stack)))
  6750. (org-element--cache-key prev)))))
  6751. (progn
  6752. (setq leftp nil)
  6753. (pop stack))
  6754. ;; Otherwise, move ahead into the right
  6755. ;; branch when it exists.
  6756. (if (setq leftp (avl-tree--node-right node))
  6757. (avl-tree--node-right node)
  6758. (pop stack))))))))
  6759. (when (and org-element--cache-map-statistics
  6760. (or (not org-element--cache-map-statistics-threshold)
  6761. (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
  6762. (message "Mapped over elements in %S. %d/%d predicate matches. Total time: %f sec. Time running predicates: %f sec (%f sec avg)
  6763. Calling parameters: :granularity %S :restrict-elements %S :next-re %S :fail-re %S :from-pos %S :to-pos %S :limit-count %S :after-element %S"
  6764. (current-buffer)
  6765. count-predicate-calls-match
  6766. (+ count-predicate-calls-match
  6767. count-predicate-calls-fail)
  6768. (- (float-time) time)
  6769. predicate-time
  6770. (if (zerop (+ count-predicate-calls-match
  6771. count-predicate-calls-fail))
  6772. 0
  6773. (/ predicate-time (+ count-predicate-calls-match
  6774. count-predicate-calls-fail)))
  6775. granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
  6776. ;; Return result.
  6777. (nreverse result)))))))
  6778. ;;; The Toolbox
  6779. ;;
  6780. ;; The first move is to implement a way to obtain the smallest element
  6781. ;; containing point. This is the job of `org-element-at-point'. It
  6782. ;; basically jumps back to the beginning of section containing point
  6783. ;; and proceed, one element after the other, with
  6784. ;; `org-element--current-element' until the container is found. Note:
  6785. ;; When using `org-element-at-point', secondary values are never
  6786. ;; parsed since the function focuses on elements, not on objects.
  6787. ;;
  6788. ;; At a deeper level, `org-element-context' lists all elements and
  6789. ;; objects containing point.
  6790. ;;
  6791. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  6792. ;; internally by navigation and manipulation tools.
  6793. ;;;###autoload
  6794. (defun org-element-at-point (&optional pom cached-only)
  6795. "Determine closest element around point or POM.
  6796. Only check cached element when CACHED-ONLY is non-nil and return nil
  6797. unconditionally when element at POM is not in cache.
  6798. Return value is a list like (TYPE PROPS) where TYPE is the type
  6799. of the element and PROPS a plist of properties associated to the
  6800. element.
  6801. Possible types are defined in `org-element-all-elements'.
  6802. Properties depend on element or object type, but always include
  6803. `:begin', `:end', and `:post-blank' properties.
  6804. As a special case, if point is at the very beginning of the first
  6805. item in a list or sub-list, returned element will be that list
  6806. instead of the item. Likewise, if point is at the beginning of
  6807. the first row of a table, returned element will be the table
  6808. instead of the first row.
  6809. When point is at the end of the buffer, return the innermost
  6810. element ending there."
  6811. (setq pom (or pom (point)))
  6812. ;; Allow re-parsing when the command can benefit from it.
  6813. (when (and cached-only
  6814. (memq this-command org-element--cache-non-modifying-commands))
  6815. (setq cached-only nil))
  6816. (let (element)
  6817. (when (org-element--cache-active-p)
  6818. (if (not org-element--cache) (org-element-cache-reset)
  6819. (unless cached-only (org-element--cache-sync (current-buffer) pom))))
  6820. (setq element (if cached-only
  6821. (and (org-element--cache-active-p)
  6822. (or (not org-element--cache-sync-requests)
  6823. (org-element--cache-key-less-p pom (org-element--request-key (car org-element--cache-sync-requests))))
  6824. (org-element--cache-find pom))
  6825. (condition-case err
  6826. (org-element--parse-to pom)
  6827. (error
  6828. (org-element--cache-warn "Cache corruption detected in %s. Resetting.\n The error was: %S\n Backtrace:\n%S\n Please report this to Org mode mailing list (M-x org-submit-bug-report)."
  6829. (buffer-name (current-buffer))
  6830. err
  6831. (backtrace-to-string (backtrace-get-frames 'backtrace)))
  6832. (org-element-cache-reset)
  6833. (org-element--parse-to pom)))))
  6834. (when (and (org-element--cache-active-p)
  6835. element
  6836. (org-element--cache-verify-element element))
  6837. (setq element (org-element--parse-to pom)))
  6838. (unless (eq 'org-data (org-element-type element))
  6839. (unless (and cached-only
  6840. (not (and element
  6841. (or (= pom (org-element-property :begin element))
  6842. (and (not (memq (org-element-type element) org-element-greater-elements))
  6843. (>= pom (org-element-property :begin element))
  6844. (< pom (org-element-property :end element)))
  6845. (and (org-element-property :contents-begin element)
  6846. (>= pom (org-element-property :begin element))
  6847. (< pom (org-element-property :contents-begin element)))
  6848. (and (org-element-property :contents-end element)
  6849. (< pom (org-element-property :end element))
  6850. (>= pom (org-element-property :contents-end element)))
  6851. (and (not (org-element-property :contents-end element))
  6852. (>= pom (org-element-property :begin element))
  6853. (< pom (org-element-property :end element)))))))
  6854. (if (not (eq (org-element-type element) 'section))
  6855. element
  6856. (org-element-at-point (1+ pom) cached-only))))))
  6857. ;;;###autoload
  6858. (defsubst org-element-at-point-no-context (&optional pom)
  6859. "Quickly find element at point or POM.
  6860. It is a faster version of `org-element-at-point' that is not
  6861. guaranteed to return correct `:parent' properties even when cache is
  6862. enabled."
  6863. (or (org-element-at-point pom 'cached-only)
  6864. (let (org-element-use-cache) (org-element-at-point pom))))
  6865. ;;;###autoload
  6866. (defun org-element-context (&optional element)
  6867. "Return smallest element or object around point.
  6868. Return value is a list like (TYPE PROPS) where TYPE is the type
  6869. of the element or object and PROPS a plist of properties
  6870. associated to it.
  6871. Possible types are defined in `org-element-all-elements' and
  6872. `org-element-all-objects'. Properties depend on element or
  6873. object type, but always include `:begin', `:end', `:parent' and
  6874. `:post-blank'.
  6875. As a special case, if point is right after an object and not at
  6876. the beginning of any other object, return that object.
  6877. Optional argument ELEMENT, when non-nil, is the closest element
  6878. containing point, as returned by `org-element-at-point'.
  6879. Providing it allows for quicker computation."
  6880. (catch 'objects-forbidden
  6881. (org-with-wide-buffer
  6882. (let* ((pos (point))
  6883. (element (or element (org-element-at-point-no-context)))
  6884. (type (org-element-type element))
  6885. (post (org-element-property :post-affiliated element)))
  6886. ;; If point is inside an element containing objects or
  6887. ;; a secondary string, narrow buffer to the container and
  6888. ;; proceed with parsing. Otherwise, return ELEMENT.
  6889. (cond
  6890. ;; At a parsed affiliated keyword, check if we're inside main
  6891. ;; or dual value.
  6892. ((and post (< pos post))
  6893. (beginning-of-line)
  6894. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  6895. (cond
  6896. ((not (member-ignore-case (match-string 1)
  6897. org-element-parsed-keywords))
  6898. (throw 'objects-forbidden element))
  6899. ((< (match-end 0) pos)
  6900. (narrow-to-region (match-end 0) (line-end-position)))
  6901. ((and (match-beginning 2)
  6902. (>= pos (match-beginning 2))
  6903. (< pos (match-end 2)))
  6904. (narrow-to-region (match-beginning 2) (match-end 2)))
  6905. (t (throw 'objects-forbidden element)))
  6906. ;; Also change type to retrieve correct restrictions.
  6907. (setq type 'keyword))
  6908. ;; At an item, objects can only be located within tag, if any.
  6909. ((eq type 'item)
  6910. (let ((tag (org-element-property :tag element)))
  6911. (if (or (not tag) (/= (line-beginning-position) post))
  6912. (throw 'objects-forbidden element)
  6913. (beginning-of-line)
  6914. (search-forward tag (line-end-position))
  6915. (goto-char (match-beginning 0))
  6916. (if (and (>= pos (point)) (< pos (match-end 0)))
  6917. (narrow-to-region (point) (match-end 0))
  6918. (throw 'objects-forbidden element)))))
  6919. ;; At an headline or inlinetask, objects are in title.
  6920. ((memq type '(headline inlinetask))
  6921. (let ((case-fold-search nil))
  6922. (goto-char (org-element-property :begin element))
  6923. (looking-at org-complex-heading-regexp)
  6924. (let ((end (match-end 4)))
  6925. (if (not end) (throw 'objects-forbidden element)
  6926. (goto-char (match-beginning 4))
  6927. (when (looking-at org-comment-string)
  6928. (goto-char (match-end 0)))
  6929. (if (>= (point) end) (throw 'objects-forbidden element)
  6930. (narrow-to-region (point) end))))))
  6931. ;; At a paragraph, a table-row or a verse block, objects are
  6932. ;; located within their contents.
  6933. ((memq type '(paragraph table-row verse-block))
  6934. (let ((cbeg (org-element-property :contents-begin element))
  6935. (cend (org-element-property :contents-end element)))
  6936. ;; CBEG is nil for table rules.
  6937. (if (and cbeg cend (>= pos cbeg)
  6938. (or (< pos cend) (and (= pos cend) (eobp))))
  6939. (narrow-to-region cbeg cend)
  6940. (throw 'objects-forbidden element))))
  6941. (t (throw 'objects-forbidden element)))
  6942. (goto-char (point-min))
  6943. (let ((restriction (org-element-restriction type))
  6944. (parent element)
  6945. last)
  6946. (catch 'exit
  6947. (while t
  6948. (let ((next (org-element--object-lex restriction)))
  6949. (when next (org-element-put-property next :parent parent))
  6950. ;; Process NEXT, if any, in order to know if we need to
  6951. ;; skip it, return it or move into it.
  6952. (if (or (not next) (> (org-element-property :begin next) pos))
  6953. (throw 'exit (or last parent))
  6954. (let ((end (org-element-property :end next))
  6955. (cbeg (org-element-property :contents-begin next))
  6956. (cend (org-element-property :contents-end next)))
  6957. (cond
  6958. ;; Skip objects ending before point. Also skip
  6959. ;; objects ending at point unless it is also the
  6960. ;; end of buffer, since we want to return the
  6961. ;; innermost object.
  6962. ((and (<= end pos) (/= (point-max) end))
  6963. (goto-char end)
  6964. ;; For convenience, when object ends at POS,
  6965. ;; without any space, store it in LAST, as we
  6966. ;; will return it if no object starts here.
  6967. (when (and (= end pos)
  6968. (not (memq (char-before) '(?\s ?\t))))
  6969. (setq last next)))
  6970. ;; If POS is within a container object, move into
  6971. ;; that object.
  6972. ((and cbeg cend
  6973. (>= pos cbeg)
  6974. (or (< pos cend)
  6975. ;; At contents' end, if there is no
  6976. ;; space before point, also move into
  6977. ;; object, for consistency with
  6978. ;; convenience feature above.
  6979. (and (= pos cend)
  6980. (or (= (point-max) pos)
  6981. (not (memq (char-before pos)
  6982. '(?\s ?\t)))))))
  6983. (goto-char cbeg)
  6984. (narrow-to-region (point) cend)
  6985. (setq parent next)
  6986. (setq restriction (org-element-restriction next)))
  6987. ;; Otherwise, return NEXT.
  6988. (t (throw 'exit next)))))))))))))
  6989. (defun org-element-lineage (datum &optional types with-self)
  6990. "List all ancestors of a given element or object.
  6991. DATUM is an object or element.
  6992. Return ancestors from the closest to the farthest. When optional
  6993. argument TYPES is a list of symbols, return the first element or
  6994. object in the lineage whose type belongs to that list instead.
  6995. When optional argument WITH-SELF is non-nil, lineage includes
  6996. DATUM itself as the first element, and TYPES, if provided, also
  6997. apply to it.
  6998. When DATUM is obtained through `org-element-context' or
  6999. `org-element-at-point', only ancestors from its section can be
  7000. found. There is no such limitation when DATUM belongs to a full
  7001. parse tree."
  7002. (let ((up (if with-self datum (org-element-property :parent datum)))
  7003. ancestors)
  7004. (while (and up (not (memq (org-element-type up) types)))
  7005. (unless types (push up ancestors))
  7006. (setq up (org-element-property :parent up)))
  7007. (if types up (nreverse ancestors))))
  7008. (defun org-element-nested-p (elem-A elem-B)
  7009. "Non-nil when elements ELEM-A and ELEM-B are nested."
  7010. (let ((beg-A (org-element-property :begin elem-A))
  7011. (beg-B (org-element-property :begin elem-B))
  7012. (end-A (org-element-property :end elem-A))
  7013. (end-B (org-element-property :end elem-B)))
  7014. (or (and (>= beg-A beg-B) (<= end-A end-B))
  7015. (and (>= beg-B beg-A) (<= end-B end-A)))))
  7016. (defun org-element-swap-A-B (elem-A elem-B)
  7017. "Swap elements ELEM-A and ELEM-B.
  7018. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7019. end of ELEM-A."
  7020. (goto-char (org-element-property :begin elem-A))
  7021. ;; There are two special cases when an element doesn't start at bol:
  7022. ;; the first paragraph in an item or in a footnote definition.
  7023. (let ((specialp (not (bolp))))
  7024. ;; Only a paragraph without any affiliated keyword can be moved at
  7025. ;; ELEM-A position in such a situation. Note that the case of
  7026. ;; a footnote definition is impossible: it cannot contain two
  7027. ;; paragraphs in a row because it cannot contain a blank line.
  7028. (when (and specialp
  7029. (or (not (eq (org-element-type elem-B) 'paragraph))
  7030. (/= (org-element-property :begin elem-B)
  7031. (org-element-property :contents-begin elem-B))))
  7032. (error "Cannot swap elements"))
  7033. ;; In a special situation, ELEM-A will have no indentation. We'll
  7034. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7035. (let* ((ind-B (when specialp
  7036. (goto-char (org-element-property :begin elem-B))
  7037. (current-indentation)))
  7038. (beg-A (org-element-property :begin elem-A))
  7039. (end-A (save-excursion
  7040. (goto-char (org-element-property :end elem-A))
  7041. (skip-chars-backward " \r\t\n")
  7042. (point-at-eol)))
  7043. (beg-B (org-element-property :begin elem-B))
  7044. (end-B (save-excursion
  7045. (goto-char (org-element-property :end elem-B))
  7046. (skip-chars-backward " \r\t\n")
  7047. (point-at-eol)))
  7048. ;; Store inner overlays responsible for visibility status.
  7049. ;; We also need to store their boundaries as they will be
  7050. ;; removed from buffer.
  7051. (overlays
  7052. (cons
  7053. (delq nil
  7054. (mapcar (lambda (o)
  7055. (and (>= (overlay-start o) beg-A)
  7056. (<= (overlay-end o) end-A)
  7057. (list o (overlay-start o) (overlay-end o))))
  7058. (overlays-in beg-A end-A)))
  7059. (delq nil
  7060. (mapcar (lambda (o)
  7061. (and (>= (overlay-start o) beg-B)
  7062. (<= (overlay-end o) end-B)
  7063. (list o (overlay-start o) (overlay-end o))))
  7064. (overlays-in beg-B end-B)))))
  7065. ;; Get contents.
  7066. (body-A (buffer-substring beg-A end-A))
  7067. (body-B (delete-and-extract-region beg-B end-B)))
  7068. (goto-char beg-B)
  7069. (when specialp
  7070. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7071. (indent-to-column ind-B))
  7072. (insert body-A)
  7073. ;; Restore ex ELEM-A overlays.
  7074. (let ((offset (- beg-B beg-A)))
  7075. (dolist (o (car overlays))
  7076. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  7077. (goto-char beg-A)
  7078. (delete-region beg-A end-A)
  7079. (insert body-B)
  7080. ;; Restore ex ELEM-B overlays.
  7081. (dolist (o (cdr overlays))
  7082. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  7083. (goto-char (org-element-property :end elem-B)))))
  7084. (provide 'org-element)
  7085. ;; Local variables:
  7086. ;; generated-autoload-file: "org-loaddefs.el"
  7087. ;; End:
  7088. ;;; org-element.el ends here