org-element.el 332 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
  19. ;; Org syntax.
  20. ;;
  21. ;; Lisp-wise, a syntax object can be represented as a list.
  22. ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
  23. ;; TYPE is a symbol describing the object.
  24. ;; PROPERTIES is the property list attached to it. See docstring of
  25. ;; appropriate parsing function to get an exhaustive list.
  26. ;; CONTENTS is a list of syntax objects or raw strings contained
  27. ;; in the current object, when applicable.
  28. ;;
  29. ;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
  30. ;;
  31. ;; The first part of this file defines constants for the Org syntax,
  32. ;; while the second one provide accessors and setters functions.
  33. ;;
  34. ;; The next part implements a parser and an interpreter for each
  35. ;; element and object type in Org syntax.
  36. ;;
  37. ;; The following part creates a fully recursive buffer parser. It
  38. ;; also provides a tool to map a function to elements or objects
  39. ;; matching some criteria in the parse tree. Functions of interest
  40. ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
  41. ;; extent, `org-element-parse-secondary-string'.
  42. ;;
  43. ;; The penultimate part is the cradle of an interpreter for the
  44. ;; obtained parse tree: `org-element-interpret-data'.
  45. ;;
  46. ;; The library ends by furnishing `org-element-at-point' function, and
  47. ;; a way to give information about document structure around point
  48. ;; with `org-element-context'. A cache mechanism is also provided for
  49. ;; these functions.
  50. ;;; Code:
  51. (require 'avl-tree)
  52. (require 'ring)
  53. (require 'cl-lib)
  54. (require 'ol)
  55. (require 'org)
  56. (require 'org-persist)
  57. (require 'org-compat)
  58. (require 'org-entities)
  59. (require 'org-footnote)
  60. (require 'org-list)
  61. (require 'org-macs)
  62. (require 'org-table)
  63. (require 'org-fold-core)
  64. (declare-function org-at-heading-p "org" (&optional _))
  65. (declare-function org-escape-code-in-string "org-src" (s))
  66. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  67. (declare-function org-macro-extract-arguments "org-macro" (s))
  68. (declare-function org-reduced-level "org" (l))
  69. (declare-function org-unescape-code-in-string "org-src" (s))
  70. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  71. (declare-function outline-next-heading "outline" ())
  72. (declare-function outline-previous-heading "outline" ())
  73. (defvar org-complex-heading-regexp)
  74. (defvar org-done-keywords)
  75. (defvar org-edit-src-content-indentation)
  76. (defvar org-match-substring-regexp)
  77. (defvar org-odd-levels-only)
  78. (defvar org-property-drawer-re)
  79. (defvar org-property-format)
  80. (defvar org-property-re)
  81. (defvar org-src-preserve-indentation)
  82. (defvar org-tags-column)
  83. (defvar org-time-stamp-formats)
  84. (defvar org-todo-regexp)
  85. (defvar org-ts-regexp-both)
  86. ;;; Definitions And Rules
  87. ;;
  88. ;; Define elements, greater elements and specify recursive objects,
  89. ;; along with the affiliated keywords recognized. Also set up
  90. ;; restrictions on recursive objects combinations.
  91. ;;
  92. ;; `org-element-update-syntax' builds proper syntax regexps according
  93. ;; to current setup.
  94. (defconst org-element-archive-tag "ARCHIVE"
  95. "Tag marking a substree as archived.")
  96. (defconst org-element-citation-key-re
  97. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  98. "Regexp matching a citation key.
  99. Key is located in match group 1.")
  100. (defconst org-element-citation-prefix-re
  101. (rx "[cite"
  102. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  103. ":"
  104. (zero-or-more (any "\t\n ")))
  105. "Regexp matching a citation prefix.
  106. Style, if any, is located in match group 1.")
  107. (defconst org-element-clock-line-re
  108. (rx line-start (0+ (or ?\t ?\s)) "CLOCK:")
  109. "Regexp matching a clock line.")
  110. (defconst org-element-comment-string "COMMENT"
  111. "String marker for commented headlines.")
  112. (defconst org-element-closed-keyword "CLOSED:"
  113. "Keyword used to close TODO entries.")
  114. (defconst org-element-deadline-keyword "DEADLINE:"
  115. "Keyword used to mark deadline entries.")
  116. (defconst org-element-scheduled-keyword "SCHEDULED:"
  117. "Keyword used to mark scheduled entries.")
  118. (defconst org-element-planning-keywords-re
  119. (regexp-opt (list org-element-closed-keyword
  120. org-element-deadline-keyword
  121. org-element-scheduled-keyword))
  122. "Regexp matching any planning line keyword.")
  123. (defconst org-element-planning-line-re
  124. (rx-to-string
  125. `(seq line-start (0+ (any ?\s ?\t))
  126. (group (regexp ,org-element-planning-keywords-re))))
  127. "Regexp matching a planning line.")
  128. (defconst org-element-drawer-re
  129. (rx line-start (0+ (any ?\s ?\t))
  130. ":" (group (1+ (any ?- ?_ word))) ":"
  131. (0+ (any ?\s ?\t)) line-end)
  132. "Regexp matching opening or closing line of a drawer.
  133. Drawer's name is located in match group 1.")
  134. (defconst org-element-dynamic-block-open-re
  135. (rx line-start (0+ (any ?\s ?\t))
  136. "#+BEGIN:" (0+ (any ?\s ?\t))
  137. (group (1+ word))
  138. (opt
  139. (1+ (any ?\s ?\t))
  140. (group (1+ nonl))))
  141. "Regexp matching the opening line of a dynamic block.
  142. Dynamic block's name is located in match group 1.
  143. Parameters are in match group 2.")
  144. (defconst org-element-headline-re
  145. (rx line-start (1+ "*") " ")
  146. "Regexp matching a headline.")
  147. (defvar org-element-paragraph-separate nil
  148. "Regexp to separate paragraphs in an Org buffer.
  149. In the case of lines starting with \"#\" and \":\", this regexp
  150. is not sufficient to know if point is at a paragraph ending. See
  151. `org-element-paragraph-parser' for more information.")
  152. (defvar org-element--object-regexp nil
  153. "Regexp possibly matching the beginning of an object.
  154. This regexp allows false positives. Dedicated parser (e.g.,
  155. `org-export-bold-parser') will take care of further filtering.
  156. Radio links are not matched by this regexp, as they are treated
  157. specially in `org-element--object-lex'.")
  158. (defun org-element--set-regexps ()
  159. "Build variable syntax regexps."
  160. (setq org-element-paragraph-separate
  161. (concat "^\\(?:"
  162. ;; Headlines, inlinetasks.
  163. "\\*+ " "\\|"
  164. ;; Footnote definitions.
  165. "\\[fn:[-_[:word:]]+\\]" "\\|"
  166. ;; Diary sexps.
  167. "%%(" "\\|"
  168. "[ \t]*\\(?:"
  169. ;; Empty lines.
  170. "$" "\\|"
  171. ;; Tables (any type).
  172. "|" "\\|"
  173. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  174. ;; Comments, keyword-like or block-like constructs.
  175. ;; Blocks and keywords with dual values need to be
  176. ;; double-checked.
  177. "#\\(?: \\|$\\|\\+\\(?:"
  178. "BEGIN_\\S-+" "\\|"
  179. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  180. "\\|"
  181. ;; Drawers (any type) and fixed-width areas. Drawers
  182. ;; need to be double-checked.
  183. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  184. ;; Horizontal rules.
  185. "-\\{5,\\}[ \t]*$" "\\|"
  186. ;; LaTeX environments.
  187. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  188. ;; Clock lines.
  189. "CLOCK:" "\\|"
  190. ;; Lists.
  191. (let ((term (pcase org-plain-list-ordered-item-terminator
  192. (?\) ")") (?. "\\.") (_ "[.)]")))
  193. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  194. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  195. "\\(?:[ \t]\\|$\\)"))
  196. "\\)\\)")
  197. org-element--object-regexp
  198. (mapconcat #'identity
  199. (let ((link-types (regexp-opt (org-link-types))))
  200. (list
  201. ;; Sub/superscript.
  202. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  203. ;; Bold, code, italic, strike-through, underline
  204. ;; and verbatim.
  205. (rx (or "*" "~" "=" "+" "_" "/") (not space))
  206. ;; Plain links.
  207. (concat "\\<" link-types ":")
  208. ;; Objects starting with "[": citations,
  209. ;; footnote reference, statistics cookie,
  210. ;; timestamp (inactive) and regular link.
  211. (format "\\[\\(?:%s\\)"
  212. (mapconcat
  213. #'identity
  214. (list "cite[:/]"
  215. "fn:"
  216. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  217. "\\[")
  218. "\\|"))
  219. ;; Objects starting with "@": export snippets.
  220. "@@"
  221. ;; Objects starting with "{": macro.
  222. "{{{"
  223. ;; Objects starting with "<" : timestamp
  224. ;; (active, diary), target, radio target and
  225. ;; angular links.
  226. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  227. ;; Objects starting with "$": latex fragment.
  228. "\\$"
  229. ;; Objects starting with "\": line break,
  230. ;; entity, latex fragment.
  231. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  232. ;; Objects starting with raw text: inline Babel
  233. ;; source block, inline Babel call.
  234. "\\(?:call\\|src\\)_"))
  235. "\\|")))
  236. (org-element--set-regexps)
  237. ;;;###autoload
  238. (defun org-element-update-syntax ()
  239. "Update parser internals."
  240. (interactive)
  241. (org-element--set-regexps)
  242. (org-element-cache-reset 'all))
  243. (defconst org-element-all-elements
  244. '(babel-call center-block clock comment comment-block diary-sexp drawer
  245. dynamic-block example-block export-block fixed-width
  246. footnote-definition headline horizontal-rule inlinetask item
  247. keyword latex-environment node-property paragraph plain-list
  248. planning property-drawer quote-block section
  249. special-block src-block table table-row verse-block)
  250. "Complete list of element types.")
  251. (defconst org-element-greater-elements
  252. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  253. item plain-list property-drawer quote-block section
  254. special-block table org-data)
  255. "List of recursive element types aka Greater Elements.")
  256. (defconst org-element-all-objects
  257. '(bold citation citation-reference code entity export-snippet
  258. footnote-reference inline-babel-call inline-src-block italic line-break
  259. latex-fragment link macro radio-target statistics-cookie strike-through
  260. subscript superscript table-cell target timestamp underline verbatim)
  261. "Complete list of object types.")
  262. (defconst org-element-recursive-objects
  263. '(bold citation footnote-reference italic link subscript radio-target
  264. strike-through superscript table-cell underline)
  265. "List of recursive object types.")
  266. (defconst org-element-object-containers
  267. (append org-element-recursive-objects '(paragraph table-row verse-block))
  268. "List of object or element types that can directly contain objects.")
  269. (defconst org-element-affiliated-keywords
  270. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  271. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  272. "List of affiliated keywords as strings.
  273. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  274. are affiliated keywords and need not to be in this list.")
  275. (defconst org-element-keyword-translation-alist
  276. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  277. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  278. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  279. "Alist of usual translations for keywords.
  280. The key is the old name and the value the new one. The property
  281. holding their value will be named after the translated name.")
  282. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  283. "List of affiliated keywords that can occur more than once in an element.
  284. Their value will be consed into a list of strings, which will be
  285. returned as the value of the property.
  286. This list is checked after translations have been applied. See
  287. `org-element-keyword-translation-alist'.
  288. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  289. allow multiple occurrences and need not to be in this list.")
  290. (defconst org-element-parsed-keywords '("CAPTION")
  291. "List of affiliated keywords whose value can be parsed.
  292. Their value will be stored as a secondary string: a list of
  293. strings and objects.
  294. This list is checked after translations have been applied. See
  295. `org-element-keyword-translation-alist'.")
  296. (defconst org-element--parsed-properties-alist
  297. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  298. org-element-parsed-keywords)
  299. "Alist of parsed keywords and associated properties.
  300. This is generated from `org-element-parsed-keywords', which
  301. see.")
  302. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  303. "List of affiliated keywords which can have a secondary value.
  304. In Org syntax, they can be written with optional square brackets
  305. before the colons. For example, RESULTS keyword can be
  306. associated to a hash value with the following:
  307. #+RESULTS[hash-string]: some-source
  308. This list is checked after translations have been applied. See
  309. `org-element-keyword-translation-alist'.")
  310. (defconst org-element--affiliated-re
  311. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  312. (concat
  313. ;; Dual affiliated keywords.
  314. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  315. (regexp-opt org-element-dual-keywords))
  316. "\\|"
  317. ;; Regular affiliated keywords.
  318. (format "\\(?1:%s\\)"
  319. (regexp-opt
  320. (cl-remove-if
  321. (lambda (k) (member k org-element-dual-keywords))
  322. org-element-affiliated-keywords)))
  323. "\\|"
  324. ;; Export attributes.
  325. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  326. "Regexp matching any affiliated keyword.
  327. Keyword name is put in match group 1. Moreover, if keyword
  328. belongs to `org-element-dual-keywords', put the dual value in
  329. match group 2.
  330. Don't modify it, set `org-element-affiliated-keywords' instead.")
  331. (defconst org-element-object-restrictions
  332. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  333. subscript superscript underline verbatim))
  334. (standard-set
  335. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  336. (standard-set-no-line-break (remq 'line-break standard-set)))
  337. `((bold ,@standard-set)
  338. (citation citation-reference)
  339. (citation-reference ,@minimal-set)
  340. (footnote-reference ,@standard-set)
  341. (headline ,@standard-set-no-line-break)
  342. (inlinetask ,@standard-set-no-line-break)
  343. (italic ,@standard-set)
  344. (item ,@standard-set-no-line-break)
  345. (keyword ,@(remq 'footnote-reference standard-set))
  346. ;; Ignore all links in a link description. Also ignore
  347. ;; radio-targets and line breaks.
  348. (link export-snippet inline-babel-call inline-src-block macro
  349. statistics-cookie ,@minimal-set)
  350. (paragraph ,@standard-set)
  351. ;; Remove any variable object from radio target as it would
  352. ;; prevent it from being properly recognized.
  353. (radio-target ,@minimal-set)
  354. (strike-through ,@standard-set)
  355. (subscript ,@standard-set)
  356. (superscript ,@standard-set)
  357. ;; Ignore inline babel call and inline source block as formulas
  358. ;; are possible. Also ignore line breaks and statistics
  359. ;; cookies.
  360. (table-cell citation export-snippet footnote-reference link macro
  361. radio-target target timestamp ,@minimal-set)
  362. (table-row table-cell)
  363. (underline ,@standard-set)
  364. (verse-block ,@standard-set)))
  365. "Alist of objects restrictions.
  366. key is an element or object type containing objects and value is
  367. a list of types that can be contained within an element or object
  368. of such type.
  369. This alist also applies to secondary string. For example, an
  370. `headline' type element doesn't directly contain objects, but
  371. still has an entry since one of its properties (`:title') does.")
  372. (defconst org-element-secondary-value-alist
  373. '((citation :prefix :suffix)
  374. (headline :title)
  375. (inlinetask :title)
  376. (item :tag)
  377. (citation-reference :prefix :suffix))
  378. "Alist between element types and locations of secondary values.")
  379. (defconst org-element--pair-round-table
  380. (let ((table (make-char-table 'syntax-table '(2))))
  381. (modify-syntax-entry ?\( "()" table)
  382. (modify-syntax-entry ?\) ")(" table)
  383. table)
  384. "Table used internally to pair only round brackets.")
  385. (defconst org-element--pair-square-table
  386. (let ((table (make-char-table 'syntax-table '(2))))
  387. (modify-syntax-entry ?\[ "(]" table)
  388. (modify-syntax-entry ?\] ")[" table)
  389. table)
  390. "Table used internally to pair only square brackets.")
  391. (defconst org-element--pair-curly-table
  392. (let ((table (make-char-table 'syntax-table '(2))))
  393. (modify-syntax-entry ?\{ "(}" table)
  394. (modify-syntax-entry ?\} "){" table)
  395. table)
  396. "Table used internally to pair only curly brackets.")
  397. (defun org-element--parse-paired-brackets (char)
  398. "Parse paired brackets at point.
  399. CHAR is the opening bracket to consider, as a character. Return
  400. contents between brackets, as a string, or nil. Also move point
  401. past the brackets."
  402. (when (eq char (char-after))
  403. (let ((syntax-table (pcase char
  404. (?\{ org-element--pair-curly-table)
  405. (?\[ org-element--pair-square-table)
  406. (?\( org-element--pair-round-table)
  407. (_ nil)))
  408. (pos (point)))
  409. (when syntax-table
  410. (with-syntax-table syntax-table
  411. (let ((end (ignore-errors (scan-lists pos 1 0))))
  412. (when end
  413. (goto-char end)
  414. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  415. ;;; Accessors and Setters
  416. ;;
  417. ;; Provide four accessors: `org-element-type', `org-element-property'
  418. ;; `org-element-contents' and `org-element-restriction'.
  419. ;;
  420. ;; Setter functions allow modification of elements by side effect.
  421. ;; There is `org-element-put-property', `org-element-set-contents'.
  422. ;; These low-level functions are useful to build a parse tree.
  423. ;;
  424. ;; `org-element-adopt-elements', `org-element-set-element',
  425. ;; `org-element-extract-element' and `org-element-insert-before' are
  426. ;; high-level functions useful to modify a parse tree.
  427. ;;
  428. ;; `org-element-secondary-p' is a predicate used to know if a given
  429. ;; object belongs to a secondary string. `org-element-class' tells if
  430. ;; some parsed data is an element or an object, handling pseudo
  431. ;; elements and objects. `org-element-copy' returns an element or
  432. ;; object, stripping its parent property in the process.
  433. (defsubst org-element-type (element)
  434. "Return type of ELEMENT.
  435. The function returns the type of the element or object provided.
  436. It can also return the following special value:
  437. `plain-text' for a string
  438. `org-data' for a complete document
  439. nil in any other case."
  440. (cond
  441. ((not (consp element)) (and (stringp element) 'plain-text))
  442. ((symbolp (car element)) (car element))))
  443. (defsubst org-element-property (property element)
  444. "Extract the value from the PROPERTY of an ELEMENT."
  445. (if (stringp element) (get-text-property 0 property element)
  446. (plist-get (nth 1 element) property)))
  447. (defsubst org-element-contents (element)
  448. "Extract contents from an ELEMENT."
  449. (cond ((not (consp element)) nil)
  450. ((symbolp (car element)) (nthcdr 2 element))
  451. (t element)))
  452. (defsubst org-element-restriction (element)
  453. "Return restriction associated to ELEMENT.
  454. ELEMENT can be an element, an object or a symbol representing an
  455. element or object type."
  456. (cdr (assq (if (symbolp element) element (org-element-type element))
  457. org-element-object-restrictions)))
  458. (defsubst org-element-put-property (element property value)
  459. "In ELEMENT set PROPERTY to VALUE.
  460. Return modified element."
  461. (if (stringp element) (org-add-props element nil property value)
  462. (setcar (cdr element) (plist-put (nth 1 element) property value))
  463. element))
  464. (defsubst org-element-set-contents (element &rest contents)
  465. "Set ELEMENT's contents to CONTENTS.
  466. Return ELEMENT."
  467. (cond ((null element) contents)
  468. ((not (symbolp (car element))) contents)
  469. ((cdr element) (setcdr (cdr element) contents) element)
  470. (t (nconc element contents))))
  471. (defun org-element-secondary-p (object)
  472. "Non-nil when OBJECT directly belongs to a secondary string.
  473. Return value is the property name, as a keyword, or nil."
  474. (let* ((parent (org-element-property :parent object))
  475. (properties (cdr (assq (org-element-type parent)
  476. org-element-secondary-value-alist))))
  477. (catch 'exit
  478. (dolist (p properties)
  479. (and (memq object (org-element-property p parent))
  480. (throw 'exit p))))))
  481. (defsubst org-element-class (datum &optional parent)
  482. "Return class for ELEMENT, as a symbol.
  483. Class is either `element' or `object'. Optional argument PARENT
  484. is the element or object containing DATUM. It defaults to the
  485. value of DATUM `:parent' property."
  486. (let ((type (org-element-type datum))
  487. (parent (or parent (org-element-property :parent datum))))
  488. (cond
  489. ;; Trivial cases.
  490. ((memq type org-element-all-objects) 'object)
  491. ((memq type org-element-all-elements) 'element)
  492. ;; Special cases.
  493. ((eq type 'org-data) 'element)
  494. ((eq type 'plain-text) 'object)
  495. ((not type) 'object)
  496. ;; Pseudo object or elements. Make a guess about its class.
  497. ;; Basically a pseudo object is contained within another object,
  498. ;; a secondary string or a container element.
  499. ((not parent) 'element)
  500. (t
  501. (let ((parent-type (org-element-type parent)))
  502. (cond ((not parent-type) 'object)
  503. ((memq parent-type org-element-object-containers) 'object)
  504. ((org-element-secondary-p datum) 'object)
  505. (t 'element)))))))
  506. (defsubst org-element-adopt-elements (parent &rest children)
  507. "Append elements to the contents of another element.
  508. PARENT is an element or object. CHILDREN can be elements,
  509. objects, or a strings.
  510. The function takes care of setting `:parent' property for CHILD.
  511. Return parent element."
  512. (declare (indent 1))
  513. (if (not children) parent
  514. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  515. ;; string: parent is the list itself.
  516. (dolist (child children)
  517. (org-element-put-property child :parent (or parent children)))
  518. ;; Add CHILDREN at the end of PARENT contents.
  519. (when parent
  520. (apply #'org-element-set-contents
  521. parent
  522. (nconc (org-element-contents parent) children)))
  523. ;; Return modified PARENT element.
  524. (or parent children)))
  525. (defun org-element-extract-element (element)
  526. "Extract ELEMENT from parse tree.
  527. Remove element from the parse tree by side-effect, and return it
  528. with its `:parent' property stripped out."
  529. (let ((parent (org-element-property :parent element))
  530. (secondary (org-element-secondary-p element)))
  531. (if secondary
  532. (org-element-put-property
  533. parent secondary
  534. (delq element (org-element-property secondary parent)))
  535. (apply #'org-element-set-contents
  536. parent
  537. (delq element (org-element-contents parent))))
  538. ;; Return ELEMENT with its :parent removed.
  539. (org-element-put-property element :parent nil)))
  540. (defun org-element-insert-before (element location)
  541. "Insert ELEMENT before LOCATION in parse tree.
  542. LOCATION is an element, object or string within the parse tree.
  543. Parse tree is modified by side effect."
  544. (let* ((parent (org-element-property :parent location))
  545. (property (org-element-secondary-p location))
  546. (siblings (if property (org-element-property property parent)
  547. (org-element-contents parent)))
  548. ;; Special case: LOCATION is the first element of an
  549. ;; independent secondary string (e.g. :title property). Add
  550. ;; ELEMENT in-place.
  551. (specialp (and (not property)
  552. (eq siblings parent)
  553. (eq (car parent) location))))
  554. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  555. (cond (specialp)
  556. ((or (null siblings) (eq (car siblings) location))
  557. (push element siblings))
  558. ((null location) (nconc siblings (list element)))
  559. (t
  560. (let ((index (cl-position location siblings)))
  561. (unless index (error "No location found to insert element"))
  562. (push element (cdr (nthcdr (1- index) siblings))))))
  563. ;; Store SIBLINGS at appropriate place in parse tree.
  564. (cond
  565. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  566. (property (org-element-put-property parent property siblings))
  567. (t (apply #'org-element-set-contents parent siblings)))
  568. ;; Set appropriate :parent property.
  569. (org-element-put-property element :parent parent)))
  570. (defconst org-element--cache-element-properties
  571. '(:cached
  572. :org-element--cache-sync-key)
  573. "List of element properties used internally by cache.")
  574. (defun org-element-set-element (old new)
  575. "Replace element or object OLD with element or object NEW.
  576. The function takes care of setting `:parent' property for NEW."
  577. ;; Ensure OLD and NEW have the same parent.
  578. (org-element-put-property new :parent (org-element-property :parent old))
  579. (dolist (p org-element--cache-element-properties)
  580. (when (org-element-property p old)
  581. (org-element-put-property new p (org-element-property p old))))
  582. (if (or (memq (org-element-type old) '(plain-text nil))
  583. (memq (org-element-type new) '(plain-text nil)))
  584. ;; We cannot replace OLD with NEW since one of them is not an
  585. ;; object or element. We take the long path.
  586. (progn (org-element-insert-before new old)
  587. (org-element-extract-element old))
  588. ;; Since OLD is going to be changed into NEW by side-effect, first
  589. ;; make sure that every element or object within NEW has OLD as
  590. ;; parent.
  591. (dolist (blob (org-element-contents new))
  592. (org-element-put-property blob :parent old))
  593. ;; Transfer contents.
  594. (apply #'org-element-set-contents old (org-element-contents new))
  595. ;; Overwrite OLD's properties with NEW's.
  596. (setcar (cdr old) (nth 1 new))
  597. ;; Transfer type.
  598. (setcar old (car new))))
  599. (defun org-element-create (type &optional props &rest children)
  600. "Create a new element of type TYPE.
  601. Optional argument PROPS, when non-nil, is a plist defining the
  602. properties of the element. CHILDREN can be elements, objects or
  603. strings."
  604. (apply #'org-element-adopt-elements (list type props) children))
  605. (defun org-element-copy (datum)
  606. "Return a copy of DATUM.
  607. DATUM is an element, object, string or nil. `:parent' property
  608. is cleared and contents are removed in the process."
  609. (when datum
  610. (let ((type (org-element-type datum)))
  611. (pcase type
  612. (`org-data (list 'org-data nil))
  613. (`plain-text (substring-no-properties datum))
  614. (`nil (copy-sequence datum))
  615. (_
  616. (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
  617. ;; We cannot simply return the copies property list. When
  618. ;; DATUM is i.e. a headline, it's property list (`:title'
  619. ;; in case of headline) can contain parsed objects. The
  620. ;; objects will contain `:parent' property set to the DATUM
  621. ;; itself. When copied, these inner `:parent' propery
  622. ;; values will contain incorrect object decoupled from
  623. ;; DATUM. Changes to the DATUM copy will not longer be
  624. ;; reflected in the `:parent' properties. So, we need to
  625. ;; reassign inner `:parent' propreties to the DATUM copy
  626. ;; explicitly.
  627. (org-element-map element-copy (cons 'plain-text org-element-all-objects)
  628. (lambda (obj) (when (equal datum (org-element-property :parent obj))
  629. (org-element-put-property obj :parent element-copy))))
  630. element-copy))))))
  631. ;;; Greater elements
  632. ;;
  633. ;; For each greater element type, we define a parser and an
  634. ;; interpreter.
  635. ;;
  636. ;; A parser returns the element or object as the list described above.
  637. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  638. ;; every element containing a secondary string (see
  639. ;; `org-element-secondary-value-alist') will accept an optional
  640. ;; argument to toggle parsing of these secondary strings. Moreover,
  641. ;; `item' parser requires current list's structure as its first
  642. ;; element.
  643. ;;
  644. ;; An interpreter accepts two arguments: the list representation of
  645. ;; the element or object, and its contents. The latter may be nil,
  646. ;; depending on the element or object considered. It returns the
  647. ;; appropriate Org syntax, as a string.
  648. ;;
  649. ;; Parsing functions must follow the naming convention:
  650. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  651. ;; defined in `org-element-greater-elements'.
  652. ;;
  653. ;; Similarly, interpreting functions must follow the naming
  654. ;; convention: org-element-TYPE-interpreter.
  655. ;;
  656. ;; With the exception of `headline' and `item' types, greater elements
  657. ;; cannot contain other greater elements of their own type.
  658. ;;
  659. ;; Beside implementing a parser and an interpreter, adding a new
  660. ;; greater element requires tweaking `org-element--current-element'.
  661. ;; Moreover, the newly defined type must be added to both
  662. ;; `org-element-all-elements' and `org-element-greater-elements'.
  663. ;;;; Center Block
  664. (defun org-element-center-block-parser (limit affiliated)
  665. "Parse a center block.
  666. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  667. the buffer position at the beginning of the first affiliated
  668. keyword and CDR is a plist of affiliated keywords along with
  669. their value.
  670. Return a list whose CAR is `center-block' and CDR is a plist
  671. containing `:begin', `:end', `:contents-begin', `:contents-end',
  672. `:post-blank' and `:post-affiliated' keywords.
  673. Assume point is at the beginning of the block."
  674. (let ((case-fold-search t))
  675. (if (not (save-excursion
  676. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  677. ;; Incomplete block: parse it as a paragraph.
  678. (org-element-paragraph-parser limit affiliated)
  679. (let ((block-end-line (match-beginning 0)))
  680. (let* ((begin (car affiliated))
  681. (post-affiliated (point))
  682. ;; Empty blocks have no contents.
  683. (contents-begin (progn (forward-line)
  684. (and (< (point) block-end-line)
  685. (point))))
  686. (contents-end (and contents-begin block-end-line))
  687. (pos-before-blank (progn (goto-char block-end-line)
  688. (forward-line)
  689. (point)))
  690. (end (save-excursion
  691. (skip-chars-forward " \r\t\n" limit)
  692. (if (eobp) (point) (line-beginning-position)))))
  693. (list 'center-block
  694. (nconc
  695. (list :begin begin
  696. :end end
  697. :contents-begin contents-begin
  698. :contents-end contents-end
  699. :post-blank (count-lines pos-before-blank end)
  700. :post-affiliated post-affiliated)
  701. (cdr affiliated))))))))
  702. (defun org-element-center-block-interpreter (_ contents)
  703. "Interpret a center-block element as Org syntax.
  704. CONTENTS is the contents of the element."
  705. (format "#+begin_center\n%s#+end_center" contents))
  706. ;;;; Drawer
  707. (defun org-element-drawer-parser (limit affiliated)
  708. "Parse a drawer.
  709. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  710. the buffer position at the beginning of the first affiliated
  711. keyword and CDR is a plist of affiliated keywords along with
  712. their value.
  713. Return a list whose CAR is `drawer' and CDR is a plist containing
  714. `:drawer-name', `:begin', `:end', `:contents-begin',
  715. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  716. Assume point is at beginning of drawer."
  717. (let ((case-fold-search t))
  718. (if (not (save-excursion
  719. (goto-char (min limit (line-end-position)))
  720. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  721. ;; Incomplete drawer: parse it as a paragraph.
  722. (org-element-paragraph-parser limit affiliated)
  723. (save-excursion
  724. (let* ((drawer-end-line (match-beginning 0))
  725. (name
  726. (progn
  727. (looking-at org-element-drawer-re)
  728. (match-string-no-properties 1)))
  729. (begin (car affiliated))
  730. (post-affiliated (point))
  731. ;; Empty drawers have no contents.
  732. (contents-begin (progn (forward-line)
  733. (and (< (point) drawer-end-line)
  734. (point))))
  735. (contents-end (and contents-begin drawer-end-line))
  736. (pos-before-blank (progn (goto-char drawer-end-line)
  737. (forward-line)
  738. (point)))
  739. (end (progn (skip-chars-forward " \r\t\n" limit)
  740. (if (eobp) (point) (line-beginning-position)))))
  741. (list 'drawer
  742. (nconc
  743. (list :begin begin
  744. :end end
  745. :drawer-name name
  746. :contents-begin contents-begin
  747. :contents-end contents-end
  748. :post-blank (count-lines pos-before-blank end)
  749. :post-affiliated post-affiliated)
  750. (cdr affiliated))))))))
  751. (defun org-element-drawer-interpreter (drawer contents)
  752. "Interpret DRAWER element as Org syntax.
  753. CONTENTS is the contents of the element."
  754. (format ":%s:\n%s:END:"
  755. (org-element-property :drawer-name drawer)
  756. contents))
  757. ;;;; Dynamic Block
  758. (defun org-element-dynamic-block-parser (limit affiliated)
  759. "Parse a dynamic block.
  760. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  761. the buffer position at the beginning of the first affiliated
  762. keyword and CDR is a plist of affiliated keywords along with
  763. their value.
  764. Return a list whose CAR is `dynamic-block' and CDR is a plist
  765. containing `:block-name', `:begin', `:end', `:contents-begin',
  766. `:contents-end', `:arguments', `:post-blank' and
  767. `:post-affiliated' keywords.
  768. Assume point is at beginning of dynamic block."
  769. (let ((case-fold-search t))
  770. (if (not (save-excursion
  771. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  772. ;; Incomplete block: parse it as a paragraph.
  773. (org-element-paragraph-parser limit affiliated)
  774. (let ((block-end-line (match-beginning 0)))
  775. (save-excursion
  776. (let* ((name (progn
  777. (looking-at org-element-dynamic-block-open-re)
  778. (match-string-no-properties 1)))
  779. (arguments (match-string-no-properties 2))
  780. (begin (car affiliated))
  781. (post-affiliated (point))
  782. ;; Empty blocks have no contents.
  783. (contents-begin (progn (forward-line)
  784. (and (< (point) block-end-line)
  785. (point))))
  786. (contents-end (and contents-begin block-end-line))
  787. (pos-before-blank (progn (goto-char block-end-line)
  788. (forward-line)
  789. (point)))
  790. (end (progn (skip-chars-forward " \r\t\n" limit)
  791. (if (eobp) (point) (line-beginning-position)))))
  792. (list 'dynamic-block
  793. (nconc
  794. (list :begin begin
  795. :end end
  796. :block-name name
  797. :arguments arguments
  798. :contents-begin contents-begin
  799. :contents-end contents-end
  800. :post-blank (count-lines pos-before-blank end)
  801. :post-affiliated post-affiliated)
  802. (cdr affiliated)))))))))
  803. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  804. "Interpret DYNAMIC-BLOCK element as Org syntax.
  805. CONTENTS is the contents of the element."
  806. (format "#+begin: %s%s\n%s#+end:"
  807. (org-element-property :block-name dynamic-block)
  808. (let ((args (org-element-property :arguments dynamic-block)))
  809. (if args (concat " " args) ""))
  810. contents))
  811. ;;;; Footnote Definition
  812. (defconst org-element--footnote-separator
  813. (concat org-element-headline-re "\\|"
  814. org-footnote-definition-re "\\|"
  815. "^\\([ \t]*\n\\)\\{2,\\}")
  816. "Regexp used as a footnote definition separator.")
  817. (defun org-element-footnote-definition-parser (limit affiliated)
  818. "Parse a footnote definition.
  819. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  820. the buffer position at the beginning of the first affiliated
  821. keyword and CDR is a plist of affiliated keywords along with
  822. their value.
  823. Return a list whose CAR is `footnote-definition' and CDR is
  824. a plist containing `:label', `:begin' `:end', `:contents-begin',
  825. `:contents-end', `:pre-blank',`:post-blank' and
  826. `:post-affiliated' keywords.
  827. Assume point is at the beginning of the footnote definition."
  828. (save-excursion
  829. (let* ((label (progn (looking-at org-footnote-definition-re)
  830. (match-string-no-properties 1)))
  831. (begin (car affiliated))
  832. (post-affiliated (point))
  833. (end
  834. (save-excursion
  835. (end-of-line)
  836. (cond
  837. ((not
  838. (re-search-forward org-element--footnote-separator limit t))
  839. limit)
  840. ((eq ?\[ (char-after (match-beginning 0)))
  841. ;; At a new footnote definition, make sure we end
  842. ;; before any affiliated keyword above.
  843. (forward-line -1)
  844. (while (and (> (point) post-affiliated)
  845. (looking-at-p org-element--affiliated-re))
  846. (forward-line -1))
  847. (line-beginning-position 2))
  848. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  849. (t (skip-chars-forward " \r\t\n" limit)
  850. (if (= limit (point)) limit (line-beginning-position))))))
  851. (pre-blank 0)
  852. (contents-begin
  853. (progn (search-forward "]")
  854. (skip-chars-forward " \r\t\n" end)
  855. (cond ((= (point) end) nil)
  856. ((= (line-beginning-position) post-affiliated) (point))
  857. (t
  858. (setq pre-blank
  859. (count-lines (line-beginning-position) begin))
  860. (line-beginning-position)))))
  861. (contents-end
  862. (progn (goto-char end)
  863. (skip-chars-backward " \r\t\n")
  864. (line-beginning-position 2))))
  865. (list 'footnote-definition
  866. (nconc
  867. (list :label label
  868. :begin begin
  869. :end end
  870. :contents-begin contents-begin
  871. :contents-end (and contents-begin contents-end)
  872. :pre-blank pre-blank
  873. :post-blank (count-lines contents-end end)
  874. :post-affiliated post-affiliated)
  875. (cdr affiliated))))))
  876. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  877. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  878. CONTENTS is the contents of the footnote-definition."
  879. (let ((pre-blank
  880. (min (or (org-element-property :pre-blank footnote-definition)
  881. ;; 0 is specific to paragraphs at the beginning of
  882. ;; the footnote definition, so we use 1 as
  883. ;; a fall-back value, which is more universal.
  884. 1)
  885. ;; Footnote ends after more than two consecutive empty
  886. ;; lines: limit ourselves to 2 newline characters.
  887. 2)))
  888. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  889. (if (= pre-blank 0) (concat " " (org-trim contents))
  890. (concat (make-string pre-blank ?\n) contents)))))
  891. ;;;; Headline
  892. (defun org-element--get-node-properties (&optional at-point-p?)
  893. "Return node properties for headline or property drawer at point.
  894. Upcase property names. It avoids confusion between properties
  895. obtained through property drawer and default properties from the
  896. parser (e.g. `:end' and :END:). Return value is a plist.
  897. When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
  898. parse properties for property drawer at point."
  899. (save-excursion
  900. (unless at-point-p?
  901. (forward-line)
  902. (when (looking-at-p org-element-planning-line-re) (forward-line)))
  903. (when (looking-at org-property-drawer-re)
  904. (forward-line)
  905. (let ((end (match-end 0)) properties)
  906. (while (< (line-end-position) end)
  907. (looking-at org-property-re)
  908. (let* ((property-name (concat ":" (upcase (match-string 2))))
  909. (property-name-symbol (intern property-name))
  910. (property-value (match-string-no-properties 3)))
  911. (cond
  912. ((and (plist-member properties property-name-symbol)
  913. (string-match-p "+$" property-name))
  914. (let ((val (plist-get properties property-name-symbol)))
  915. (if (listp val)
  916. (setq properties
  917. (plist-put properties
  918. property-name-symbol
  919. (append (plist-get properties property-name-symbol)
  920. (list property-value))))
  921. (plist-put properties property-name-symbol (list val property-value)))))
  922. (t (setq properties (plist-put properties property-name-symbol property-value)))))
  923. (forward-line))
  924. properties))))
  925. (defun org-element--get-time-properties ()
  926. "Return time properties associated to headline at point.
  927. Return value is a plist."
  928. (save-excursion
  929. (when (progn (forward-line) (looking-at org-element-planning-line-re))
  930. (let ((end (line-end-position))
  931. plist)
  932. (while (re-search-forward org-element-planning-keywords-re end t)
  933. (skip-chars-forward " \t")
  934. (let ((keyword (match-string 0))
  935. (time (org-element-timestamp-parser)))
  936. (cond ((equal keyword org-element-scheduled-keyword)
  937. (setq plist (plist-put plist :scheduled time)))
  938. ((equal keyword org-element-deadline-keyword)
  939. (setq plist (plist-put plist :deadline time)))
  940. (t (setq plist (plist-put plist :closed time))))))
  941. plist))))
  942. (defun org-element-headline-parser (&optional _ raw-secondary-p)
  943. "Parse a headline.
  944. Return a list whose CAR is `headline' and CDR is a plist
  945. containing `:raw-value', `:title', `:begin', `:end',
  946. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  947. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  948. `:deadline', `:closed', `:archivedp', `:commentedp'
  949. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  950. keywords.
  951. The plist also contains any property set in the property drawer,
  952. with its name in upper cases and colons added at the
  953. beginning (e.g., `:CUSTOM_ID').
  954. When RAW-SECONDARY-P is non-nil, headline's title will not be
  955. parsed as a secondary string, but as a plain string instead.
  956. Assume point is at beginning of the headline."
  957. (save-excursion
  958. (let* ((begin (point))
  959. (true-level (prog1 (skip-chars-forward "*")
  960. (skip-chars-forward " \t")))
  961. (level (org-reduced-level true-level))
  962. (todo (and org-todo-regexp
  963. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  964. (progn (goto-char (match-end 0))
  965. (skip-chars-forward " \t")
  966. (match-string 1))))
  967. (todo-type
  968. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  969. (priority (and (looking-at "\\[#.\\][ \t]*")
  970. (progn (goto-char (match-end 0))
  971. (aref (match-string 0) 2))))
  972. (commentedp
  973. (and (let ((case-fold-search nil))
  974. (looking-at org-element-comment-string))
  975. (goto-char (match-end 0))
  976. (when (looking-at-p "\\(?:[ \t]\\|$\\)")
  977. (point))))
  978. (title-start (prog1 (point)
  979. (unless (or todo priority commentedp)
  980. ;; Headline like "* :tag:"
  981. (skip-chars-backward " \t"))))
  982. (tags (when (re-search-forward
  983. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  984. (line-end-position)
  985. 'move)
  986. (goto-char (match-beginning 0))
  987. (org-split-string (match-string 1) ":")))
  988. (title-end (point))
  989. (raw-value (org-trim
  990. (buffer-substring-no-properties title-start title-end)))
  991. (archivedp (member org-element-archive-tag tags))
  992. (footnote-section-p (and org-footnote-section
  993. (string= org-footnote-section raw-value)))
  994. (standard-props (org-element--get-node-properties))
  995. (time-props (org-element--get-time-properties))
  996. (end
  997. (save-excursion
  998. (let ((re (rx-to-string
  999. `(seq line-start (** 1 ,true-level "*") " "))))
  1000. (if (re-search-forward re nil t)
  1001. (line-beginning-position)
  1002. (point-max)))))
  1003. (contents-begin (save-excursion
  1004. (forward-line)
  1005. (skip-chars-forward " \r\t\n" end)
  1006. (and (/= (point) end) (line-beginning-position))))
  1007. (contents-end (and contents-begin
  1008. (progn (goto-char end)
  1009. (skip-chars-backward " \r\t\n")
  1010. (line-beginning-position 2))))
  1011. (robust-begin (and contents-begin
  1012. (progn (goto-char contents-begin)
  1013. (when (looking-at-p org-element-planning-line-re)
  1014. (forward-line))
  1015. (when (looking-at org-property-drawer-re)
  1016. (goto-char (match-end 0)))
  1017. ;; If there is :pre-blank, we
  1018. ;; need to be careful about
  1019. ;; robust beginning.
  1020. (max (if (< (+ 2 contents-begin) contents-end)
  1021. (+ 2 contents-begin)
  1022. 0)
  1023. (point)))))
  1024. (robust-end (and robust-begin
  1025. (when (> (- contents-end 2) robust-begin)
  1026. (- contents-end 2)))))
  1027. (unless robust-end (setq robust-begin nil))
  1028. (let ((headline
  1029. (list 'headline
  1030. (nconc
  1031. (list :raw-value raw-value
  1032. :begin begin
  1033. :end end
  1034. :pre-blank
  1035. (if (not contents-begin) 0
  1036. (1- (count-lines begin contents-begin)))
  1037. :contents-begin contents-begin
  1038. :contents-end contents-end
  1039. :robust-begin robust-begin
  1040. :robust-end robust-end
  1041. :level level
  1042. :priority priority
  1043. :tags tags
  1044. :todo-keyword todo
  1045. :todo-type todo-type
  1046. :post-blank
  1047. (if contents-end
  1048. (count-lines contents-end end)
  1049. (1- (count-lines begin end)))
  1050. :footnote-section-p footnote-section-p
  1051. :archivedp archivedp
  1052. :commentedp commentedp
  1053. :post-affiliated begin)
  1054. time-props
  1055. standard-props))))
  1056. (org-element-put-property
  1057. headline :title
  1058. (if raw-secondary-p raw-value
  1059. (org-element--parse-objects
  1060. (progn (goto-char title-start)
  1061. (skip-chars-forward " \t")
  1062. (point))
  1063. (progn (goto-char title-end)
  1064. (skip-chars-backward " \t")
  1065. (point))
  1066. nil
  1067. (org-element-restriction 'headline)
  1068. headline)))))))
  1069. (defun org-element-headline-interpreter (headline contents)
  1070. "Interpret HEADLINE element as Org syntax.
  1071. CONTENTS is the contents of the element."
  1072. (let* ((level (org-element-property :level headline))
  1073. (todo (org-element-property :todo-keyword headline))
  1074. (priority (org-element-property :priority headline))
  1075. (title (org-element-interpret-data
  1076. (org-element-property :title headline)))
  1077. (tags (let ((tag-list (org-element-property :tags headline)))
  1078. (and tag-list
  1079. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  1080. (commentedp (org-element-property :commentedp headline))
  1081. (pre-blank (or (org-element-property :pre-blank headline) 0))
  1082. (heading
  1083. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  1084. ?*)
  1085. (and todo (concat " " todo))
  1086. (and commentedp (concat " " org-element-comment-string))
  1087. (and priority (format " [#%c]" priority))
  1088. " "
  1089. (if (and org-footnote-section
  1090. (org-element-property :footnote-section-p headline))
  1091. org-footnote-section
  1092. title))))
  1093. (concat
  1094. heading
  1095. ;; Align tags.
  1096. (when tags
  1097. (cond
  1098. ((zerop org-tags-column) (format " %s" tags))
  1099. ((< org-tags-column 0)
  1100. (concat
  1101. (make-string
  1102. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1103. ?\s)
  1104. tags))
  1105. (t
  1106. (concat
  1107. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1108. tags))))
  1109. (make-string (1+ pre-blank) ?\n)
  1110. contents)))
  1111. ;;;; org-data
  1112. (defun org-element--get-global-node-properties ()
  1113. "Return node properties associated with the whole Org buffer.
  1114. Upcase property names. It avoids confusion between properties
  1115. obtained through property drawer and default properties from the
  1116. parser (e.g. `:end' and :END:). Return value is a plist."
  1117. (org-with-wide-buffer
  1118. (goto-char (point-min))
  1119. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1120. (org-element--get-node-properties t)))
  1121. (defvar org-element-org-data-parser--recurse nil)
  1122. (defun org-element-org-data-parser (&optional _)
  1123. "Parse org-data."
  1124. (org-with-wide-buffer
  1125. (let* ((begin 1)
  1126. (contents-begin (progn
  1127. (goto-char 1)
  1128. (org-skip-whitespace)
  1129. (beginning-of-line)
  1130. (point)))
  1131. (end (point-max))
  1132. (pos-before-blank (progn (goto-char (point-max))
  1133. (skip-chars-backward " \r\t\n")
  1134. (line-beginning-position 2)))
  1135. (robust-end (when (> (- pos-before-blank 2) contents-begin)
  1136. (- pos-before-blank 2)))
  1137. (robust-begin (when (and robust-end
  1138. (< (+ 2 contents-begin) pos-before-blank))
  1139. (or
  1140. (org-with-wide-buffer
  1141. (goto-char (point-min))
  1142. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1143. (when (looking-at org-property-drawer-re)
  1144. (goto-char (match-end 0))
  1145. (skip-chars-backward " \t")
  1146. (min robust-end (point))))
  1147. (+ 2 contents-begin))))
  1148. (category (cond ((null org-category)
  1149. (when (with-current-buffer
  1150. (or (buffer-base-buffer)
  1151. (current-buffer))
  1152. buffer-file-name)
  1153. (file-name-sans-extension
  1154. (file-name-nondirectory
  1155. (with-current-buffer
  1156. (or (buffer-base-buffer)
  1157. (current-buffer))
  1158. buffer-file-name)))))
  1159. ((symbolp org-category) (symbol-name org-category))
  1160. (t org-category)))
  1161. (category (catch 'buffer-category
  1162. (unless org-element-org-data-parser--recurse
  1163. (org-with-point-at end
  1164. ;; Avoid recursive calls from
  1165. ;; `org-element-at-point-no-context'.
  1166. (let ((org-element-org-data-parser--recurse t))
  1167. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  1168. (org-element-with-disabled-cache
  1169. (let ((element (org-element-at-point-no-context)))
  1170. (when (eq (org-element-type element) 'keyword)
  1171. (throw 'buffer-category
  1172. (org-element-property :value element)))))))))
  1173. category))
  1174. (properties (org-element--get-global-node-properties)))
  1175. (unless (plist-get properties :CATEGORY)
  1176. (setq properties (plist-put properties :CATEGORY category)))
  1177. (list 'org-data
  1178. (nconc
  1179. (list :begin begin
  1180. :contents-begin contents-begin
  1181. :contents-end pos-before-blank
  1182. :end end
  1183. :robust-begin robust-begin
  1184. :robust-end robust-end
  1185. :post-blank (count-lines pos-before-blank end)
  1186. :post-affiliated begin
  1187. :path (buffer-file-name)
  1188. :mode 'org-data)
  1189. properties)))))
  1190. (defun org-element-org-data-interpreter (_ contents)
  1191. "Interpret ORG-DATA element as Org syntax.
  1192. CONTENTS is the contents of the element."
  1193. contents)
  1194. ;;;; Inlinetask
  1195. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1196. "Parse an inline task.
  1197. Return a list whose CAR is `inlinetask' and CDR is a plist
  1198. containing `:title', `:begin', `:end', `:pre-blank',
  1199. `:contents-begin' and `:contents-end', `:level', `:priority',
  1200. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1201. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1202. `:post-affiliated' keywords.
  1203. The plist also contains any property set in the property drawer,
  1204. with its name in upper cases and colons added at the
  1205. beginning (e.g., `:CUSTOM_ID').
  1206. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1207. title will not be parsed as a secondary string, but as a plain
  1208. string instead.
  1209. Assume point is at beginning of the inline task."
  1210. (save-excursion
  1211. (let* ((begin (point))
  1212. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1213. (skip-chars-forward " \t")))
  1214. (todo (and org-todo-regexp
  1215. (let (case-fold-search) (looking-at org-todo-regexp))
  1216. (progn (goto-char (match-end 0))
  1217. (skip-chars-forward " \t")
  1218. (match-string 0))))
  1219. (todo-type (and todo
  1220. (if (member todo org-done-keywords) 'done 'todo)))
  1221. (priority (and (looking-at "\\[#.\\][ \t]*")
  1222. (progn (goto-char (match-end 0))
  1223. (aref (match-string 0) 2))))
  1224. (title-start (point))
  1225. (tags (when (re-search-forward
  1226. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1227. (line-end-position)
  1228. 'move)
  1229. (goto-char (match-beginning 0))
  1230. (org-split-string (match-string 1) ":")))
  1231. (title-end (point))
  1232. (raw-value (org-trim
  1233. (buffer-substring-no-properties title-start title-end)))
  1234. (task-end (save-excursion
  1235. (end-of-line)
  1236. (and (re-search-forward org-element-headline-re limit t)
  1237. (looking-at-p "[ \t]*END[ \t]*$")
  1238. (line-beginning-position))))
  1239. (standard-props (and task-end (org-element--get-node-properties)))
  1240. (time-props (and task-end (org-element--get-time-properties)))
  1241. (contents-begin (and task-end
  1242. (< (point) task-end)
  1243. (progn
  1244. (forward-line)
  1245. (skip-chars-forward " \t\n")
  1246. (line-beginning-position))))
  1247. (contents-end (and contents-begin task-end))
  1248. (end (progn (when task-end (goto-char task-end))
  1249. (forward-line)
  1250. (skip-chars-forward " \r\t\n" limit)
  1251. (if (eobp) (point) (line-beginning-position))))
  1252. (inlinetask
  1253. (list 'inlinetask
  1254. (nconc
  1255. (list :raw-value raw-value
  1256. :begin begin
  1257. :end end
  1258. :pre-blank
  1259. (if (not contents-begin) 0
  1260. (1- (count-lines begin contents-begin)))
  1261. :contents-begin contents-begin
  1262. :contents-end contents-end
  1263. :level level
  1264. :priority priority
  1265. :tags tags
  1266. :todo-keyword todo
  1267. :todo-type todo-type
  1268. :post-blank (1- (count-lines (or task-end begin) end))
  1269. :post-affiliated begin)
  1270. time-props
  1271. standard-props))))
  1272. (org-element-put-property
  1273. inlinetask :title
  1274. (if raw-secondary-p raw-value
  1275. (org-element--parse-objects
  1276. (progn (goto-char title-start)
  1277. (skip-chars-forward " \t")
  1278. (point))
  1279. (progn (goto-char title-end)
  1280. (skip-chars-backward " \t")
  1281. (point))
  1282. nil
  1283. (org-element-restriction 'inlinetask)
  1284. inlinetask))))))
  1285. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1286. "Interpret INLINETASK element as Org syntax.
  1287. CONTENTS is the contents of inlinetask."
  1288. (let* ((level (org-element-property :level inlinetask))
  1289. (todo (org-element-property :todo-keyword inlinetask))
  1290. (priority (org-element-property :priority inlinetask))
  1291. (title (org-element-interpret-data
  1292. (org-element-property :title inlinetask)))
  1293. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1294. (and tag-list
  1295. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1296. (task (concat (make-string level ?*)
  1297. (and todo (concat " " todo))
  1298. (and priority (format " [#%c]" priority))
  1299. (and title (concat " " title)))))
  1300. (concat task
  1301. ;; Align tags.
  1302. (when tags
  1303. (cond
  1304. ((zerop org-tags-column) (format " %s" tags))
  1305. ((< org-tags-column 0)
  1306. (concat
  1307. (make-string
  1308. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1309. ?\s)
  1310. tags))
  1311. (t
  1312. (concat
  1313. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1314. tags))))
  1315. ;; Prefer degenerate inlinetasks when there are no
  1316. ;; contents.
  1317. (when contents
  1318. (concat "\n"
  1319. contents
  1320. (make-string level ?*) " end")))))
  1321. ;;;; Item
  1322. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1323. "Parse an item.
  1324. STRUCT is the structure of the plain list.
  1325. Return a list whose CAR is `item' and CDR is a plist containing
  1326. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1327. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1328. `:post-blank' and `:post-affiliated' keywords.
  1329. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1330. any, will not be parsed as a secondary string, but as a plain
  1331. string instead.
  1332. Assume point is at the beginning of the item."
  1333. (save-excursion
  1334. (beginning-of-line)
  1335. (looking-at org-list-full-item-re)
  1336. (let* ((begin (point))
  1337. (bullet (match-string-no-properties 1))
  1338. (checkbox (let ((box (match-string 3)))
  1339. (cond ((equal "[ ]" box) 'off)
  1340. ((equal "[X]" box) 'on)
  1341. ((equal "[-]" box) 'trans))))
  1342. (counter (let ((c (match-string 2)))
  1343. (save-match-data
  1344. (cond
  1345. ((not c) nil)
  1346. ((string-match "[A-Za-z]" c)
  1347. (- (string-to-char (upcase (match-string 0 c)))
  1348. 64))
  1349. ((string-match "[0-9]+" c)
  1350. (string-to-number (match-string 0 c)))))))
  1351. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1352. (if (bolp) (point) (line-beginning-position 2))))
  1353. (pre-blank 0)
  1354. (contents-begin
  1355. (progn
  1356. (goto-char
  1357. ;; Ignore tags in un-ordered lists: they are just
  1358. ;; a part of item's body.
  1359. (if (and (match-beginning 4)
  1360. (save-match-data (string-match "[.)]" bullet)))
  1361. (match-beginning 4)
  1362. (match-end 0)))
  1363. (skip-chars-forward " \r\t\n" end)
  1364. (cond ((= (point) end) nil)
  1365. ;; If first line isn't empty, contents really
  1366. ;; start at the text after item's meta-data.
  1367. ((= (line-beginning-position) begin) (point))
  1368. (t
  1369. (setq pre-blank
  1370. (count-lines (line-beginning-position) begin))
  1371. (line-beginning-position)))))
  1372. (contents-end (and contents-begin
  1373. (progn (goto-char end)
  1374. (skip-chars-backward " \r\t\n")
  1375. (line-beginning-position 2))))
  1376. (item
  1377. (list 'item
  1378. (list :bullet bullet
  1379. :begin begin
  1380. :end end
  1381. :contents-begin contents-begin
  1382. :contents-end contents-end
  1383. :checkbox checkbox
  1384. :counter counter
  1385. :structure struct
  1386. :pre-blank pre-blank
  1387. :post-blank (count-lines (or contents-end begin) end)
  1388. :post-affiliated begin))))
  1389. (org-element-put-property
  1390. item :tag
  1391. (let ((raw (org-list-get-tag begin struct)))
  1392. (when raw
  1393. (if raw-secondary-p raw
  1394. (org-element--parse-objects
  1395. (match-beginning 4) (match-end 4) nil
  1396. (org-element-restriction 'item)
  1397. item))))))))
  1398. (defun org-element-item-interpreter (item contents)
  1399. "Interpret ITEM element as Org syntax.
  1400. CONTENTS is the contents of the element."
  1401. (let ((tag (pcase (org-element-property :tag item)
  1402. (`nil nil)
  1403. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1404. (bullet
  1405. (org-list-bullet-string
  1406. (cond
  1407. ((not (string-match-p "[0-9a-zA-Z]"
  1408. (org-element-property :bullet item))) "- ")
  1409. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1410. (t "1.")))))
  1411. (concat
  1412. bullet
  1413. (pcase (org-element-property :counter item)
  1414. (`nil nil)
  1415. (counter (format "[@%d] " counter)))
  1416. (pcase (org-element-property :checkbox item)
  1417. (`on "[X] ")
  1418. (`off "[ ] ")
  1419. (`trans "[-] ")
  1420. (_ nil))
  1421. tag
  1422. (when contents
  1423. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1424. (pre-blank
  1425. (min (or (org-element-property :pre-blank item)
  1426. ;; 0 is specific to paragraphs at the
  1427. ;; beginning of the item, so we use 1 as
  1428. ;; a fall-back value, which is more universal.
  1429. 1)
  1430. ;; Lists ends after more than two consecutive
  1431. ;; empty lines: limit ourselves to 2 newline
  1432. ;; characters.
  1433. 2))
  1434. (contents (replace-regexp-in-string
  1435. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1436. (if (= pre-blank 0) (org-trim contents)
  1437. (concat (make-string pre-blank ?\n) contents)))))))
  1438. ;;;; Plain List
  1439. (defun org-element--list-struct (limit)
  1440. ;; Return structure of list at point. Internal function. See
  1441. ;; `org-list-struct' for details.
  1442. (let ((case-fold-search t)
  1443. (top-ind limit)
  1444. (item-re (org-item-re))
  1445. (inlinetask-re (and (featurep 'org-inlinetask)
  1446. (boundp 'org-inlinetask-min-level)
  1447. (boundp 'org-inlinetask-max-level)
  1448. (format "^\\*\\{%d,%d\\}+ "
  1449. org-inlinetask-min-level
  1450. org-inlinetask-max-level)))
  1451. items struct)
  1452. (save-excursion
  1453. (catch :exit
  1454. (while t
  1455. (cond
  1456. ;; At limit: end all items.
  1457. ((>= (point) limit)
  1458. (let ((end (progn (skip-chars-backward " \r\t\n")
  1459. (line-beginning-position 2))))
  1460. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1461. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1462. ;; At list end: end all items.
  1463. ((looking-at org-list-end-re)
  1464. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1465. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1466. ;; At a new item: end previous sibling.
  1467. ((looking-at item-re)
  1468. (let ((ind (save-excursion (skip-chars-forward " \t")
  1469. (current-column))))
  1470. (setq top-ind (min top-ind ind))
  1471. (while (and items (<= ind (nth 1 (car items))))
  1472. (let ((item (pop items)))
  1473. (setcar (nthcdr 6 item) (point))
  1474. (push item struct)))
  1475. (push (progn (looking-at org-list-full-item-re)
  1476. (let ((bullet (match-string-no-properties 1)))
  1477. (list (point)
  1478. ind
  1479. bullet
  1480. (match-string-no-properties 2) ; counter
  1481. (match-string-no-properties 3) ; checkbox
  1482. ;; Description tag.
  1483. (and (save-match-data
  1484. (string-match "[-+*]" bullet))
  1485. (match-string-no-properties 4))
  1486. ;; Ending position, unknown so far.
  1487. nil)))
  1488. items))
  1489. (forward-line))
  1490. ;; Skip empty lines.
  1491. ((looking-at "^[ \t]*$") (forward-line))
  1492. ;; Skip inline tasks and blank lines along the way.
  1493. ((and inlinetask-re (looking-at inlinetask-re))
  1494. (forward-line)
  1495. (let ((origin (point)))
  1496. (when (re-search-forward inlinetask-re limit t)
  1497. (if (looking-at-p "END[ \t]*$") (forward-line)
  1498. (goto-char origin)))))
  1499. ;; At some text line. Check if it ends any previous item.
  1500. (t
  1501. (let ((ind (save-excursion
  1502. (skip-chars-forward " \t")
  1503. (current-column)))
  1504. (end (save-excursion
  1505. (skip-chars-backward " \r\t\n")
  1506. (line-beginning-position 2))))
  1507. (while (<= ind (nth 1 (car items)))
  1508. (let ((item (pop items)))
  1509. (setcar (nthcdr 6 item) end)
  1510. (push item struct)
  1511. (unless items
  1512. (throw :exit (sort struct #'car-less-than-car))))))
  1513. ;; Skip blocks (any type) and drawers contents.
  1514. (cond
  1515. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1516. (re-search-forward
  1517. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1518. limit t)))
  1519. ((and (looking-at org-element-drawer-re)
  1520. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1521. (forward-line))))))))
  1522. (defun org-element-plain-list-parser (limit affiliated structure)
  1523. "Parse a plain list.
  1524. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1525. the buffer position at the beginning of the first affiliated
  1526. keyword and CDR is a plist of affiliated keywords along with
  1527. their value. STRUCTURE is the structure of the plain list being
  1528. parsed.
  1529. Return a list whose CAR is `plain-list' and CDR is a plist
  1530. containing `:type', `:begin', `:end', `:contents-begin' and
  1531. `:contents-end', `:structure', `:post-blank' and
  1532. `:post-affiliated' keywords.
  1533. Assume point is at the beginning of the list."
  1534. (save-excursion
  1535. (let* ((struct (or structure (org-element--list-struct limit)))
  1536. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1537. ((nth 5 (assq (point) struct)) 'descriptive)
  1538. (t 'unordered)))
  1539. (contents-begin (point))
  1540. (begin (car affiliated))
  1541. (contents-end (let* ((item (assq contents-begin struct))
  1542. (ind (nth 1 item))
  1543. (pos (nth 6 item)))
  1544. (while (and (setq item (assq pos struct))
  1545. (= (nth 1 item) ind))
  1546. (setq pos (nth 6 item)))
  1547. pos))
  1548. (end (progn (goto-char contents-end)
  1549. (skip-chars-forward " \r\t\n" limit)
  1550. (if (= (point) limit) limit (line-beginning-position)))))
  1551. ;; Return value.
  1552. (list 'plain-list
  1553. (nconc
  1554. (list :type type
  1555. :begin begin
  1556. :end end
  1557. :contents-begin contents-begin
  1558. :contents-end contents-end
  1559. :structure struct
  1560. :post-blank (count-lines contents-end end)
  1561. :post-affiliated contents-begin)
  1562. (cdr affiliated))))))
  1563. (defun org-element-plain-list-interpreter (_ contents)
  1564. "Interpret plain-list element as Org syntax.
  1565. CONTENTS is the contents of the element."
  1566. (with-temp-buffer
  1567. (insert contents)
  1568. (goto-char (point-min))
  1569. (org-list-repair)
  1570. (buffer-string)))
  1571. ;;;; Property Drawer
  1572. (defun org-element-property-drawer-parser (limit)
  1573. "Parse a property drawer.
  1574. LIMIT bounds the search.
  1575. Return a list whose car is `property-drawer' and cdr is a plist
  1576. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1577. `:post-blank' and `:post-affiliated' keywords.
  1578. Assume point is at the beginning of the property drawer."
  1579. (save-excursion
  1580. (let ((case-fold-search t)
  1581. (begin (point))
  1582. (contents-begin (line-beginning-position 2)))
  1583. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1584. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1585. (match-beginning 0)))
  1586. (before-blank (progn (forward-line) (point)))
  1587. (end (progn (skip-chars-forward " \r\t\n" limit)
  1588. (if (eobp) (point) (line-beginning-position)))))
  1589. (list 'property-drawer
  1590. (list :begin begin
  1591. :end end
  1592. :contents-begin (and contents-end contents-begin)
  1593. :contents-end contents-end
  1594. :post-blank (count-lines before-blank end)
  1595. :post-affiliated begin))))))
  1596. (defun org-element-property-drawer-interpreter (_ contents)
  1597. "Interpret property-drawer element as Org syntax.
  1598. CONTENTS is the properties within the drawer."
  1599. (format ":PROPERTIES:\n%s:END:" contents))
  1600. ;;;; Quote Block
  1601. (defun org-element-quote-block-parser (limit affiliated)
  1602. "Parse a quote block.
  1603. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1604. the buffer position at the beginning of the first affiliated
  1605. keyword and CDR is a plist of affiliated keywords along with
  1606. their value.
  1607. Return a list whose CAR is `quote-block' and CDR is a plist
  1608. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1609. `:post-blank' and `:post-affiliated' keywords.
  1610. Assume point is at the beginning of the block."
  1611. (let ((case-fold-search t))
  1612. (if (not (save-excursion
  1613. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1614. ;; Incomplete block: parse it as a paragraph.
  1615. (org-element-paragraph-parser limit affiliated)
  1616. (let ((block-end-line (match-beginning 0)))
  1617. (save-excursion
  1618. (let* ((begin (car affiliated))
  1619. (post-affiliated (point))
  1620. ;; Empty blocks have no contents.
  1621. (contents-begin (progn (forward-line)
  1622. (and (< (point) block-end-line)
  1623. (point))))
  1624. (contents-end (and contents-begin block-end-line))
  1625. (pos-before-blank (progn (goto-char block-end-line)
  1626. (forward-line)
  1627. (point)))
  1628. (end (progn (skip-chars-forward " \r\t\n" limit)
  1629. (if (eobp) (point) (line-beginning-position)))))
  1630. (list 'quote-block
  1631. (nconc
  1632. (list :begin begin
  1633. :end end
  1634. :contents-begin contents-begin
  1635. :contents-end contents-end
  1636. :post-blank (count-lines pos-before-blank end)
  1637. :post-affiliated post-affiliated)
  1638. (cdr affiliated)))))))))
  1639. (defun org-element-quote-block-interpreter (_ contents)
  1640. "Interpret quote-block element as Org syntax.
  1641. CONTENTS is the contents of the element."
  1642. (format "#+begin_quote\n%s#+end_quote" contents))
  1643. ;;;; Section
  1644. (defun org-element-section-parser (_)
  1645. "Parse a section.
  1646. Return a list whose CAR is `section' and CDR is a plist
  1647. containing `:begin', `:end', `:contents-begin', `contents-end',
  1648. `:post-blank' and `:post-affiliated' keywords."
  1649. (save-excursion
  1650. ;; Beginning of section is the beginning of the first non-blank
  1651. ;; line after previous headline.
  1652. (let* ((begin (point))
  1653. (end (progn (org-with-limited-levels (outline-next-heading))
  1654. (point)))
  1655. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1656. (line-beginning-position 2)))
  1657. (robust-end (when (> (- pos-before-blank 2) begin)
  1658. (- pos-before-blank 2)))
  1659. (robust-begin (when robust-end begin))
  1660. )
  1661. (list 'section
  1662. (list :begin begin
  1663. :end end
  1664. :contents-begin begin
  1665. :contents-end pos-before-blank
  1666. :robust-begin robust-begin
  1667. :robust-end robust-end
  1668. :post-blank (count-lines pos-before-blank end)
  1669. :post-affiliated begin)))))
  1670. (defun org-element-section-interpreter (_ contents)
  1671. "Interpret section element as Org syntax.
  1672. CONTENTS is the contents of the element."
  1673. contents)
  1674. ;;;; Special Block
  1675. (defun org-element-special-block-parser (limit affiliated)
  1676. "Parse a special block.
  1677. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1678. the buffer position at the beginning of the first affiliated
  1679. keyword and CDR is a plist of affiliated keywords along with
  1680. their value.
  1681. Return a list whose CAR is `special-block' and CDR is a plist
  1682. containing `:type', `:begin', `:end', `:contents-begin',
  1683. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1684. Assume point is at the beginning of the block."
  1685. (let* ((case-fold-search t)
  1686. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1687. (match-string-no-properties 1))))
  1688. (if (not (save-excursion
  1689. (re-search-forward
  1690. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1691. limit t)))
  1692. ;; Incomplete block: parse it as a paragraph.
  1693. (org-element-paragraph-parser limit affiliated)
  1694. (let ((block-end-line (match-beginning 0)))
  1695. (save-excursion
  1696. (let* ((begin (car affiliated))
  1697. (post-affiliated (point))
  1698. ;; Empty blocks have no contents.
  1699. (contents-begin (progn (forward-line)
  1700. (and (< (point) block-end-line)
  1701. (point))))
  1702. (contents-end (and contents-begin block-end-line))
  1703. (pos-before-blank (progn (goto-char block-end-line)
  1704. (forward-line)
  1705. (point)))
  1706. (end (progn (skip-chars-forward " \r\t\n" limit)
  1707. (if (eobp) (point) (line-beginning-position)))))
  1708. (list 'special-block
  1709. (nconc
  1710. (list :type type
  1711. :begin begin
  1712. :end end
  1713. :contents-begin contents-begin
  1714. :contents-end contents-end
  1715. :post-blank (count-lines pos-before-blank end)
  1716. :post-affiliated post-affiliated)
  1717. (cdr affiliated)))))))))
  1718. (defun org-element-special-block-interpreter (special-block contents)
  1719. "Interpret SPECIAL-BLOCK element as Org syntax.
  1720. CONTENTS is the contents of the element."
  1721. (let ((block-type (org-element-property :type special-block)))
  1722. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1723. ;;; Elements
  1724. ;;
  1725. ;; For each element, a parser and an interpreter are also defined.
  1726. ;; Both follow the same naming convention used for greater elements.
  1727. ;;
  1728. ;; Also, as for greater elements, adding a new element type is done
  1729. ;; through the following steps: implement a parser and an interpreter,
  1730. ;; tweak `org-element--current-element' so that it recognizes the new
  1731. ;; type and add that new type to `org-element-all-elements'.
  1732. ;;;; Babel Call
  1733. (defun org-element-babel-call-parser (limit affiliated)
  1734. "Parse a babel call.
  1735. LIMIT bounds the search. AFFILIATED is a list of which car is
  1736. the buffer position at the beginning of the first affiliated
  1737. keyword and cdr is a plist of affiliated keywords along with
  1738. their value.
  1739. Return a list whose car is `babel-call' and cdr is a plist
  1740. containing `:call', `:inside-header', `:arguments',
  1741. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1742. `:post-affiliated' as keywords."
  1743. (save-excursion
  1744. (let* ((begin (car affiliated))
  1745. (post-affiliated (point))
  1746. (before-blank (line-beginning-position 2))
  1747. (value (progn (search-forward ":" before-blank t)
  1748. (skip-chars-forward " \t")
  1749. (org-trim
  1750. (buffer-substring-no-properties
  1751. (point) (line-end-position)))))
  1752. (call
  1753. (or (org-string-nw-p
  1754. (buffer-substring-no-properties
  1755. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1756. (point))))))
  1757. (inside-header (org-element--parse-paired-brackets ?\[))
  1758. (arguments (org-string-nw-p
  1759. (org-element--parse-paired-brackets ?\()))
  1760. (end-header
  1761. (org-string-nw-p
  1762. (org-trim
  1763. (buffer-substring-no-properties (point) (line-end-position)))))
  1764. (end (progn (forward-line)
  1765. (skip-chars-forward " \r\t\n" limit)
  1766. (if (eobp) (point) (line-beginning-position)))))
  1767. (list 'babel-call
  1768. (nconc
  1769. (list :call call
  1770. :inside-header inside-header
  1771. :arguments arguments
  1772. :end-header end-header
  1773. :begin begin
  1774. :end end
  1775. :value value
  1776. :post-blank (count-lines before-blank end)
  1777. :post-affiliated post-affiliated)
  1778. (cdr affiliated))))))
  1779. (defun org-element-babel-call-interpreter (babel-call _)
  1780. "Interpret BABEL-CALL element as Org syntax."
  1781. (concat "#+call: "
  1782. (org-element-property :call babel-call)
  1783. (let ((h (org-element-property :inside-header babel-call)))
  1784. (and h (format "[%s]" h)))
  1785. (concat "(" (org-element-property :arguments babel-call) ")")
  1786. (let ((h (org-element-property :end-header babel-call)))
  1787. (and h (concat " " h)))))
  1788. ;;;; Clock
  1789. (defun org-element-clock-parser (limit)
  1790. "Parse a clock.
  1791. LIMIT bounds the search.
  1792. Return a list whose CAR is `clock' and CDR is a plist containing
  1793. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1794. `:post-affiliated' as keywords."
  1795. (save-excursion
  1796. (let* ((case-fold-search nil)
  1797. (begin (point))
  1798. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1799. (skip-chars-forward " \t")
  1800. (org-element-timestamp-parser)))
  1801. (duration (and (search-forward " => " (line-end-position) t)
  1802. (progn (skip-chars-forward " \t")
  1803. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1804. (match-string-no-properties 1)))
  1805. (status (if duration 'closed 'running))
  1806. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1807. (skip-chars-forward " \r\t\n" limit)
  1808. (skip-chars-backward " \t")
  1809. (unless (bolp) (end-of-line))
  1810. (count-lines before-blank (point))))
  1811. (end (point)))
  1812. (list 'clock
  1813. (list :status status
  1814. :value value
  1815. :duration duration
  1816. :begin begin
  1817. :end end
  1818. :post-blank post-blank
  1819. :post-affiliated begin)))))
  1820. (defun org-element-clock-interpreter (clock _)
  1821. "Interpret CLOCK element as Org syntax."
  1822. (concat "CLOCK: "
  1823. (org-element-timestamp-interpreter
  1824. (org-element-property :value clock) nil)
  1825. (let ((duration (org-element-property :duration clock)))
  1826. (and duration
  1827. (concat " => "
  1828. (apply 'format
  1829. "%2s:%02s"
  1830. (org-split-string duration ":")))))))
  1831. ;;;; Comment
  1832. (defun org-element-comment-parser (limit)
  1833. "Parse a comment.
  1834. LIMIT bounds the search.
  1835. Return a list whose CAR is `comment' and CDR is a plist
  1836. containing `:begin', `:end', `:value', `:post-blank',
  1837. `:post-affiliated' keywords.
  1838. Assume point is at comment beginning."
  1839. (save-excursion
  1840. (let* ((begin (point))
  1841. (value (prog2 (looking-at "[ \t]*# ?")
  1842. (buffer-substring-no-properties
  1843. (match-end 0) (line-end-position))
  1844. (forward-line)))
  1845. (com-end
  1846. ;; Get comments ending.
  1847. (progn
  1848. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1849. ;; Accumulate lines without leading hash and first
  1850. ;; whitespace.
  1851. (setq value
  1852. (concat value
  1853. "\n"
  1854. (buffer-substring-no-properties
  1855. (match-end 0) (line-end-position))))
  1856. (forward-line))
  1857. (point)))
  1858. (end (progn (goto-char com-end)
  1859. (skip-chars-forward " \r\t\n" limit)
  1860. (if (eobp) (point) (line-beginning-position)))))
  1861. (list 'comment
  1862. (list :begin begin
  1863. :end end
  1864. :value value
  1865. :post-blank (count-lines com-end end)
  1866. :post-affiliated begin)))))
  1867. (defun org-element-comment-interpreter (comment _)
  1868. "Interpret COMMENT element as Org syntax.
  1869. CONTENTS is nil."
  1870. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1871. ;;;; Comment Block
  1872. (defun org-element-comment-block-parser (limit affiliated)
  1873. "Parse an export block.
  1874. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1875. the buffer position at the beginning of the first affiliated
  1876. keyword and CDR is a plist of affiliated keywords along with
  1877. their value.
  1878. Return a list whose CAR is `comment-block' and CDR is a plist
  1879. containing `:begin', `:end', `:value', `:post-blank' and
  1880. `:post-affiliated' keywords.
  1881. Assume point is at comment block beginning."
  1882. (let ((case-fold-search t))
  1883. (if (not (save-excursion
  1884. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1885. ;; Incomplete block: parse it as a paragraph.
  1886. (org-element-paragraph-parser limit affiliated)
  1887. (let ((contents-end (match-beginning 0)))
  1888. (save-excursion
  1889. (let* ((begin (car affiliated))
  1890. (post-affiliated (point))
  1891. (contents-begin (progn (forward-line) (point)))
  1892. (pos-before-blank (progn (goto-char contents-end)
  1893. (forward-line)
  1894. (point)))
  1895. (end (progn (skip-chars-forward " \r\t\n" limit)
  1896. (if (eobp) (point) (line-beginning-position))))
  1897. (value (buffer-substring-no-properties
  1898. contents-begin contents-end)))
  1899. (list 'comment-block
  1900. (nconc
  1901. (list :begin begin
  1902. :end end
  1903. :value value
  1904. :post-blank (count-lines pos-before-blank end)
  1905. :post-affiliated post-affiliated)
  1906. (cdr affiliated)))))))))
  1907. (defun org-element-comment-block-interpreter (comment-block _)
  1908. "Interpret COMMENT-BLOCK element as Org syntax."
  1909. (format "#+begin_comment\n%s#+end_comment"
  1910. (org-element-normalize-string
  1911. (org-remove-indentation
  1912. (org-element-property :value comment-block)))))
  1913. ;;;; Diary Sexp
  1914. (defun org-element-diary-sexp-parser (limit affiliated)
  1915. "Parse a diary sexp.
  1916. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1917. the buffer position at the beginning of the first affiliated
  1918. keyword and CDR is a plist of affiliated keywords along with
  1919. their value.
  1920. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1921. containing `:begin', `:end', `:value', `:post-blank' and
  1922. `:post-affiliated' keywords."
  1923. (save-excursion
  1924. (let ((begin (car affiliated))
  1925. (post-affiliated (point))
  1926. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1927. (match-string-no-properties 1)))
  1928. (pos-before-blank (progn (forward-line) (point)))
  1929. (end (progn (skip-chars-forward " \r\t\n" limit)
  1930. (if (eobp) (point) (line-beginning-position)))))
  1931. (list 'diary-sexp
  1932. (nconc
  1933. (list :value value
  1934. :begin begin
  1935. :end end
  1936. :post-blank (count-lines pos-before-blank end)
  1937. :post-affiliated post-affiliated)
  1938. (cdr affiliated))))))
  1939. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1940. "Interpret DIARY-SEXP as Org syntax."
  1941. (org-element-property :value diary-sexp))
  1942. ;;;; Example Block
  1943. (defun org-element-example-block-parser (limit affiliated)
  1944. "Parse an example block.
  1945. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1946. the buffer position at the beginning of the first affiliated
  1947. keyword and CDR is a plist of affiliated keywords along with
  1948. their value.
  1949. Return a list whose CAR is `example-block' and CDR is a plist
  1950. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1951. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1952. `:value', `:post-blank' and `:post-affiliated' keywords."
  1953. (let ((case-fold-search t))
  1954. (if (not (save-excursion
  1955. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1956. ;; Incomplete block: parse it as a paragraph.
  1957. (org-element-paragraph-parser limit affiliated)
  1958. (let ((contents-end (match-beginning 0)))
  1959. (save-excursion
  1960. (let* ((switches
  1961. (progn
  1962. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1963. (match-string-no-properties 1)))
  1964. ;; Switches analysis.
  1965. (number-lines
  1966. (and switches
  1967. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1968. switches)
  1969. (cons
  1970. (if (equal (match-string 1 switches) "-")
  1971. 'new
  1972. 'continued)
  1973. (if (not (match-end 2)) 0
  1974. ;; Subtract 1 to give number of lines before
  1975. ;; first line.
  1976. (1- (string-to-number (match-string 2 switches)))))))
  1977. (preserve-indent
  1978. (and switches (string-match "-i\\>" switches)))
  1979. ;; Should labels be retained in (or stripped from) example
  1980. ;; blocks?
  1981. (retain-labels
  1982. (or (not switches)
  1983. (not (string-match "-r\\>" switches))
  1984. (and number-lines (string-match "-k\\>" switches))))
  1985. ;; What should code-references use - labels or
  1986. ;; line-numbers?
  1987. (use-labels
  1988. (or (not switches)
  1989. (and retain-labels
  1990. (not (string-match "-k\\>" switches)))))
  1991. (label-fmt
  1992. (and switches
  1993. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1994. (match-string 1 switches)))
  1995. ;; Standard block parsing.
  1996. (begin (car affiliated))
  1997. (post-affiliated (point))
  1998. (contents-begin (line-beginning-position 2))
  1999. (value (org-unescape-code-in-string
  2000. (buffer-substring-no-properties
  2001. contents-begin contents-end)))
  2002. (pos-before-blank (progn (goto-char contents-end)
  2003. (forward-line)
  2004. (point)))
  2005. (end (progn (skip-chars-forward " \r\t\n" limit)
  2006. (if (eobp) (point) (line-beginning-position)))))
  2007. (list 'example-block
  2008. (nconc
  2009. (list :begin begin
  2010. :end end
  2011. :value value
  2012. :switches switches
  2013. :number-lines number-lines
  2014. :preserve-indent preserve-indent
  2015. :retain-labels retain-labels
  2016. :use-labels use-labels
  2017. :label-fmt label-fmt
  2018. :post-blank (count-lines pos-before-blank end)
  2019. :post-affiliated post-affiliated)
  2020. (cdr affiliated)))))))))
  2021. (defun org-element-example-block-interpreter (example-block _)
  2022. "Interpret EXAMPLE-BLOCK element as Org syntax."
  2023. (let ((switches (org-element-property :switches example-block))
  2024. (value
  2025. (let ((val (org-element-property :value example-block)))
  2026. (cond
  2027. ((or org-src-preserve-indentation
  2028. (org-element-property :preserve-indent example-block))
  2029. val)
  2030. ((= 0 org-edit-src-content-indentation)
  2031. (org-remove-indentation val))
  2032. (t
  2033. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2034. (replace-regexp-in-string "^[ \t]*\\S-"
  2035. (concat ind "\\&")
  2036. (org-remove-indentation val))))))))
  2037. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  2038. (org-element-normalize-string (org-escape-code-in-string value))
  2039. "#+end_example")))
  2040. ;;;; Export Block
  2041. (defun org-element-export-block-parser (limit affiliated)
  2042. "Parse an export block.
  2043. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2044. the buffer position at the beginning of the first affiliated
  2045. keyword and CDR is a plist of affiliated keywords along with
  2046. their value.
  2047. Return a list whose CAR is `export-block' and CDR is a plist
  2048. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  2049. `:post-affiliated' keywords.
  2050. Assume point is at export-block beginning."
  2051. (let* ((case-fold-search t))
  2052. (if (not (save-excursion
  2053. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  2054. ;; Incomplete block: parse it as a paragraph.
  2055. (org-element-paragraph-parser limit affiliated)
  2056. (save-excursion
  2057. (let* ((contents-end (match-beginning 0))
  2058. (backend
  2059. (progn
  2060. (looking-at
  2061. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  2062. (match-string-no-properties 1)))
  2063. (begin (car affiliated))
  2064. (post-affiliated (point))
  2065. (contents-begin (progn (forward-line) (point)))
  2066. (pos-before-blank (progn (goto-char contents-end)
  2067. (forward-line)
  2068. (point)))
  2069. (end (progn (skip-chars-forward " \r\t\n" limit)
  2070. (if (eobp) (point) (line-beginning-position))))
  2071. (value (org-unescape-code-in-string
  2072. (buffer-substring-no-properties contents-begin
  2073. contents-end))))
  2074. (list 'export-block
  2075. (nconc
  2076. (list :type (and backend (upcase backend))
  2077. :begin begin
  2078. :end end
  2079. :value value
  2080. :post-blank (count-lines pos-before-blank end)
  2081. :post-affiliated post-affiliated)
  2082. (cdr affiliated))))))))
  2083. (defun org-element-export-block-interpreter (export-block _)
  2084. "Interpret EXPORT-BLOCK element as Org syntax."
  2085. (format "#+begin_export %s\n%s#+end_export"
  2086. (org-element-property :type export-block)
  2087. (org-element-property :value export-block)))
  2088. ;;;; Fixed-width
  2089. (defun org-element-fixed-width-parser (limit affiliated)
  2090. "Parse a fixed-width section.
  2091. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2092. the buffer position at the beginning of the first affiliated
  2093. keyword and CDR is a plist of affiliated keywords along with
  2094. their value.
  2095. Return a list whose CAR is `fixed-width' and CDR is a plist
  2096. containing `:begin', `:end', `:value', `:post-blank' and
  2097. `:post-affiliated' keywords.
  2098. Assume point is at the beginning of the fixed-width area."
  2099. (save-excursion
  2100. (let* ((begin (car affiliated))
  2101. (post-affiliated (point))
  2102. (end-area
  2103. (progn
  2104. (while (and (< (point) limit)
  2105. (looking-at "[ \t]*:\\( \\|$\\)"))
  2106. (forward-line))
  2107. (if (bolp) (line-end-position 0) (point))))
  2108. (end (progn (skip-chars-forward " \r\t\n" limit)
  2109. (if (eobp) (point) (line-beginning-position)))))
  2110. (list 'fixed-width
  2111. (nconc
  2112. (list :begin begin
  2113. :end end
  2114. :value (replace-regexp-in-string
  2115. "^[ \t]*: ?" ""
  2116. (buffer-substring-no-properties post-affiliated
  2117. end-area))
  2118. :post-blank (count-lines end-area end)
  2119. :post-affiliated post-affiliated)
  2120. (cdr affiliated))))))
  2121. (defun org-element-fixed-width-interpreter (fixed-width _)
  2122. "Interpret FIXED-WIDTH element as Org syntax."
  2123. (let ((value (org-element-property :value fixed-width)))
  2124. (and value (replace-regexp-in-string "^" ": " value))))
  2125. ;;;; Horizontal Rule
  2126. (defun org-element-horizontal-rule-parser (limit affiliated)
  2127. "Parse an horizontal rule.
  2128. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2129. the buffer position at the beginning of the first affiliated
  2130. keyword and CDR is a plist of affiliated keywords along with
  2131. their value.
  2132. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  2133. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  2134. keywords."
  2135. (save-excursion
  2136. (let ((begin (car affiliated))
  2137. (post-affiliated (point))
  2138. (post-hr (progn (forward-line) (point)))
  2139. (end (progn (skip-chars-forward " \r\t\n" limit)
  2140. (if (eobp) (point) (line-beginning-position)))))
  2141. (list 'horizontal-rule
  2142. (nconc
  2143. (list :begin begin
  2144. :end end
  2145. :post-blank (count-lines post-hr end)
  2146. :post-affiliated post-affiliated)
  2147. (cdr affiliated))))))
  2148. (defun org-element-horizontal-rule-interpreter (&rest _)
  2149. "Interpret HORIZONTAL-RULE element as Org syntax."
  2150. "-----")
  2151. ;;;; Keyword
  2152. (defun org-element-keyword-parser (limit affiliated)
  2153. "Parse a keyword at point.
  2154. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2155. the buffer position at the beginning of the first affiliated
  2156. keyword and CDR is a plist of affiliated keywords along with
  2157. their value.
  2158. Return a list whose CAR is a normalized `keyword' (uppercase) and
  2159. CDR is a plist containing `:key', `:value', `:begin', `:end',
  2160. `:post-blank' and `:post-affiliated' keywords."
  2161. (save-excursion
  2162. ;; An orphaned affiliated keyword is considered as a regular
  2163. ;; keyword. In this case AFFILIATED is nil, so we take care of
  2164. ;; this corner case.
  2165. (let ((begin (or (car affiliated) (point)))
  2166. (post-affiliated (point))
  2167. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  2168. (upcase (match-string-no-properties 1))))
  2169. (value (org-trim (buffer-substring-no-properties
  2170. (match-end 0) (point-at-eol))))
  2171. (pos-before-blank (progn (forward-line) (point)))
  2172. (end (progn (skip-chars-forward " \r\t\n" limit)
  2173. (if (eobp) (point) (line-beginning-position)))))
  2174. (list 'keyword
  2175. (nconc
  2176. (list :key key
  2177. :value value
  2178. :begin begin
  2179. :end end
  2180. :post-blank (count-lines pos-before-blank end)
  2181. :post-affiliated post-affiliated)
  2182. (cdr affiliated))))))
  2183. (defun org-element-keyword-interpreter (keyword _)
  2184. "Interpret KEYWORD element as Org syntax."
  2185. (format "#+%s: %s"
  2186. (downcase (org-element-property :key keyword))
  2187. (org-element-property :value keyword)))
  2188. ;;;; Latex Environment
  2189. (defconst org-element--latex-begin-environment
  2190. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2191. "Regexp matching the beginning of a LaTeX environment.
  2192. The environment is captured by the first group.
  2193. See also `org-element--latex-end-environment'.")
  2194. (defconst org-element--latex-end-environment
  2195. "\\\\end{%s}[ \t]*$"
  2196. "Format string matching the ending of a LaTeX environment.
  2197. See also `org-element--latex-begin-environment'.")
  2198. (defun org-element-latex-environment-parser (limit affiliated)
  2199. "Parse a LaTeX environment.
  2200. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2201. the buffer position at the beginning of the first affiliated
  2202. keyword and CDR is a plist of affiliated keywords along with
  2203. their value.
  2204. Return a list whose CAR is `latex-environment' and CDR is a plist
  2205. containing `:begin', `:end', `:value', `:post-blank' and
  2206. `:post-affiliated' keywords.
  2207. Assume point is at the beginning of the latex environment."
  2208. (save-excursion
  2209. (let ((case-fold-search t)
  2210. (code-begin (point)))
  2211. (looking-at org-element--latex-begin-environment)
  2212. (if (not (re-search-forward (format org-element--latex-end-environment
  2213. (regexp-quote (match-string 1)))
  2214. limit t))
  2215. ;; Incomplete latex environment: parse it as a paragraph.
  2216. (org-element-paragraph-parser limit affiliated)
  2217. (let* ((code-end (progn (forward-line) (point)))
  2218. (begin (car affiliated))
  2219. (value (buffer-substring-no-properties code-begin code-end))
  2220. (end (progn (skip-chars-forward " \r\t\n" limit)
  2221. (if (eobp) (point) (line-beginning-position)))))
  2222. (list 'latex-environment
  2223. (nconc
  2224. (list :begin begin
  2225. :end end
  2226. :value value
  2227. :post-blank (count-lines code-end end)
  2228. :post-affiliated code-begin)
  2229. (cdr affiliated))))))))
  2230. (defun org-element-latex-environment-interpreter (latex-environment _)
  2231. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2232. (org-element-property :value latex-environment))
  2233. ;;;; Node Property
  2234. (defun org-element-node-property-parser (limit)
  2235. "Parse a node-property at point.
  2236. LIMIT bounds the search.
  2237. Return a list whose CAR is `node-property' and CDR is a plist
  2238. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2239. `:post-affiliated' keywords."
  2240. (looking-at org-property-re)
  2241. (let ((case-fold-search t)
  2242. (begin (point))
  2243. (key (match-string-no-properties 2))
  2244. (value (match-string-no-properties 3))
  2245. (end (save-excursion
  2246. (end-of-line)
  2247. (if (re-search-forward org-property-re limit t)
  2248. (line-beginning-position)
  2249. limit))))
  2250. (list 'node-property
  2251. (list :key key
  2252. :value value
  2253. :begin begin
  2254. :end end
  2255. :post-blank 0
  2256. :post-affiliated begin))))
  2257. (defun org-element-node-property-interpreter (node-property _)
  2258. "Interpret NODE-PROPERTY element as Org syntax."
  2259. (format org-property-format
  2260. (format ":%s:" (org-element-property :key node-property))
  2261. (or (org-element-property :value node-property) "")))
  2262. ;;;; Paragraph
  2263. (defun org-element-paragraph-parser (limit affiliated)
  2264. "Parse a paragraph.
  2265. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2266. the buffer position at the beginning of the first affiliated
  2267. keyword and CDR is a plist of affiliated keywords along with
  2268. their value.
  2269. Return a list whose CAR is `paragraph' and CDR is a plist
  2270. containing `:begin', `:end', `:contents-begin' and
  2271. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2272. Assume point is at the beginning of the paragraph."
  2273. (save-excursion
  2274. (let* ((begin (car affiliated))
  2275. (contents-begin (point))
  2276. (before-blank
  2277. (let ((case-fold-search t))
  2278. (end-of-line)
  2279. ;; A matching `org-element-paragraph-separate' is not
  2280. ;; necessarily the end of the paragraph. In particular,
  2281. ;; drawers, blocks or LaTeX environments opening lines
  2282. ;; must be closed. Moreover keywords with a secondary
  2283. ;; value must belong to "dual keywords".
  2284. (while (not
  2285. (cond
  2286. ((not (and (re-search-forward
  2287. org-element-paragraph-separate limit 'move)
  2288. (progn (beginning-of-line) t))))
  2289. ((looking-at org-element-drawer-re)
  2290. (save-excursion
  2291. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2292. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2293. (save-excursion
  2294. (re-search-forward
  2295. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2296. (regexp-quote (match-string 1)))
  2297. limit t)))
  2298. ((looking-at org-element--latex-begin-environment)
  2299. (save-excursion
  2300. (re-search-forward
  2301. (format org-element--latex-end-environment
  2302. (regexp-quote (match-string 1)))
  2303. limit t)))
  2304. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2305. (member-ignore-case (match-string 1)
  2306. org-element-dual-keywords))
  2307. ;; Everything else is unambiguous.
  2308. (t)))
  2309. (end-of-line))
  2310. (if (= (point) limit) limit
  2311. (goto-char (line-beginning-position)))))
  2312. (contents-end (save-excursion
  2313. (skip-chars-backward " \r\t\n" contents-begin)
  2314. (line-beginning-position 2)))
  2315. (end (progn (skip-chars-forward " \r\t\n" limit)
  2316. (if (eobp) (point) (line-beginning-position)))))
  2317. (list 'paragraph
  2318. (nconc
  2319. (list :begin begin
  2320. :end end
  2321. :contents-begin contents-begin
  2322. :contents-end contents-end
  2323. :post-blank (count-lines before-blank end)
  2324. :post-affiliated contents-begin)
  2325. (cdr affiliated))))))
  2326. (defun org-element-paragraph-interpreter (_ contents)
  2327. "Interpret paragraph element as Org syntax.
  2328. CONTENTS is the contents of the element."
  2329. contents)
  2330. ;;;; Planning
  2331. (defun org-element-planning-parser (limit)
  2332. "Parse a planning.
  2333. LIMIT bounds the search.
  2334. Return a list whose CAR is `planning' and CDR is a plist
  2335. containing `:closed', `:deadline', `:scheduled', `:begin',
  2336. `:end', `:post-blank' and `:post-affiliated' keywords."
  2337. (save-excursion
  2338. (let* ((case-fold-search nil)
  2339. (begin (point))
  2340. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2341. (skip-chars-forward " \r\t\n" limit)
  2342. (skip-chars-backward " \t")
  2343. (unless (bolp) (end-of-line))
  2344. (count-lines before-blank (point))))
  2345. (end (point))
  2346. closed deadline scheduled)
  2347. (goto-char begin)
  2348. (while (re-search-forward org-element-planning-keywords-re end t)
  2349. (skip-chars-forward " \t" end)
  2350. (let ((keyword (match-string 0))
  2351. (time (org-element-timestamp-parser)))
  2352. (cond
  2353. ((equal keyword org-element-closed-keyword) (setq closed time))
  2354. ((equal keyword org-element-deadline-keyword) (setq deadline time))
  2355. (t (setq scheduled time)))))
  2356. (list 'planning
  2357. (list :closed closed
  2358. :deadline deadline
  2359. :scheduled scheduled
  2360. :begin begin
  2361. :end end
  2362. :post-blank post-blank
  2363. :post-affiliated begin)))))
  2364. (defun org-element-planning-interpreter (planning _)
  2365. "Interpret PLANNING element as Org syntax."
  2366. (mapconcat
  2367. #'identity
  2368. (delq nil
  2369. (list (let ((deadline (org-element-property :deadline planning)))
  2370. (when deadline
  2371. (concat org-element-deadline-keyword " "
  2372. (org-element-timestamp-interpreter deadline nil))))
  2373. (let ((scheduled (org-element-property :scheduled planning)))
  2374. (when scheduled
  2375. (concat org-element-scheduled-keyword " "
  2376. (org-element-timestamp-interpreter scheduled nil))))
  2377. (let ((closed (org-element-property :closed planning)))
  2378. (when closed
  2379. (concat org-element-closed-keyword " "
  2380. (org-element-timestamp-interpreter closed nil))))))
  2381. " "))
  2382. ;;;; Src Block
  2383. (defun org-element-src-block-parser (limit affiliated)
  2384. "Parse a source block.
  2385. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2386. the buffer position at the beginning of the first affiliated
  2387. keyword and CDR is a plist of affiliated keywords along with
  2388. their value.
  2389. Return a list whose CAR is `src-block' and CDR is a plist
  2390. containing `:language', `:switches', `:parameters', `:begin',
  2391. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2392. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2393. `:post-affiliated' keywords.
  2394. Assume point is at the beginning of the block."
  2395. (let ((case-fold-search t))
  2396. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2397. limit t)))
  2398. ;; Incomplete block: parse it as a paragraph.
  2399. (org-element-paragraph-parser limit affiliated)
  2400. (let ((contents-end (match-beginning 0)))
  2401. (save-excursion
  2402. (let* ((begin (car affiliated))
  2403. (post-affiliated (point))
  2404. ;; Get language as a string.
  2405. (language
  2406. (progn
  2407. (looking-at
  2408. "^[ \t]*#\\+BEGIN_SRC\
  2409. \\(?: +\\(\\S-+\\)\\)?\
  2410. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2411. \\(.*\\)[ \t]*$")
  2412. (match-string-no-properties 1)))
  2413. ;; Get switches.
  2414. (switches (match-string-no-properties 2))
  2415. ;; Get parameters.
  2416. (parameters (match-string-no-properties 3))
  2417. ;; Switches analysis.
  2418. (number-lines
  2419. (and switches
  2420. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2421. switches)
  2422. (cons
  2423. (if (equal (match-string 1 switches) "-")
  2424. 'new
  2425. 'continued)
  2426. (if (not (match-end 2)) 0
  2427. ;; Subtract 1 to give number of lines before
  2428. ;; first line.
  2429. (1- (string-to-number (match-string 2 switches)))))))
  2430. (preserve-indent (and switches
  2431. (string-match "-i\\>" switches)))
  2432. (label-fmt
  2433. (and switches
  2434. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2435. (match-string 1 switches)))
  2436. ;; Should labels be retained in (or stripped from)
  2437. ;; source blocks?
  2438. (retain-labels
  2439. (or (not switches)
  2440. (not (string-match "-r\\>" switches))
  2441. (and number-lines (string-match "-k\\>" switches))))
  2442. ;; What should code-references use - labels or
  2443. ;; line-numbers?
  2444. (use-labels
  2445. (or (not switches)
  2446. (and retain-labels
  2447. (not (string-match "-k\\>" switches)))))
  2448. ;; Retrieve code.
  2449. (value (org-unescape-code-in-string
  2450. (buffer-substring-no-properties
  2451. (line-beginning-position 2) contents-end)))
  2452. (pos-before-blank (progn (goto-char contents-end)
  2453. (forward-line)
  2454. (point)))
  2455. ;; Get position after ending blank lines.
  2456. (end (progn (skip-chars-forward " \r\t\n" limit)
  2457. (if (eobp) (point) (line-beginning-position)))))
  2458. (list 'src-block
  2459. (nconc
  2460. (list :language language
  2461. :switches (and (org-string-nw-p switches)
  2462. (org-trim switches))
  2463. :parameters (and (org-string-nw-p parameters)
  2464. (org-trim parameters))
  2465. :begin begin
  2466. :end end
  2467. :number-lines number-lines
  2468. :preserve-indent preserve-indent
  2469. :retain-labels retain-labels
  2470. :use-labels use-labels
  2471. :label-fmt label-fmt
  2472. :value value
  2473. :post-blank (count-lines pos-before-blank end)
  2474. :post-affiliated post-affiliated)
  2475. (cdr affiliated)))))))))
  2476. (defun org-element-src-block-interpreter (src-block _)
  2477. "Interpret SRC-BLOCK element as Org syntax."
  2478. (let ((lang (org-element-property :language src-block))
  2479. (switches (org-element-property :switches src-block))
  2480. (params (org-element-property :parameters src-block))
  2481. (value
  2482. (let ((val (org-element-property :value src-block)))
  2483. (cond
  2484. ((or org-src-preserve-indentation
  2485. (org-element-property :preserve-indent src-block))
  2486. val)
  2487. ((zerop org-edit-src-content-indentation)
  2488. (org-remove-indentation val))
  2489. (t
  2490. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2491. (replace-regexp-in-string "^[ \t]*\\S-"
  2492. (concat ind "\\&")
  2493. (org-remove-indentation val))))))))
  2494. (format "#+begin_src%s\n%s#+end_src"
  2495. (concat (and lang (concat " " lang))
  2496. (and switches (concat " " switches))
  2497. (and params (concat " " params)))
  2498. (org-element-normalize-string (org-escape-code-in-string value)))))
  2499. ;;;; Table
  2500. (defun org-element-table-parser (limit affiliated)
  2501. "Parse a table at point.
  2502. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2503. the buffer position at the beginning of the first affiliated
  2504. keyword and CDR is a plist of affiliated keywords along with
  2505. their value.
  2506. Return a list whose CAR is `table' and CDR is a plist containing
  2507. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2508. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2509. keywords.
  2510. Assume point is at the beginning of the table."
  2511. (save-excursion
  2512. (let* ((case-fold-search t)
  2513. (table-begin (point))
  2514. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2515. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2516. (if (eq type 'org) "" "+")))
  2517. (begin (car affiliated))
  2518. (table-end
  2519. (if (re-search-forward end-re limit 'move)
  2520. (goto-char (match-beginning 0))
  2521. (point)))
  2522. (tblfm (let (acc)
  2523. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2524. (push (match-string-no-properties 1) acc)
  2525. (forward-line))
  2526. acc))
  2527. (pos-before-blank (point))
  2528. (end (progn (skip-chars-forward " \r\t\n" limit)
  2529. (if (eobp) (point) (line-beginning-position)))))
  2530. (list 'table
  2531. (nconc
  2532. (list :begin begin
  2533. :end end
  2534. :type type
  2535. :tblfm tblfm
  2536. ;; Only `org' tables have contents. `table.el' tables
  2537. ;; use a `:value' property to store raw table as
  2538. ;; a string.
  2539. :contents-begin (and (eq type 'org) table-begin)
  2540. :contents-end (and (eq type 'org) table-end)
  2541. :value (and (eq type 'table.el)
  2542. (buffer-substring-no-properties
  2543. table-begin table-end))
  2544. :post-blank (count-lines pos-before-blank end)
  2545. :post-affiliated table-begin)
  2546. (cdr affiliated))))))
  2547. (defun org-element-table-interpreter (table contents)
  2548. "Interpret TABLE element as Org syntax.
  2549. CONTENTS is a string, if table's type is `org', or nil."
  2550. (if (eq (org-element-property :type table) 'table.el)
  2551. (org-remove-indentation (org-element-property :value table))
  2552. (concat (with-temp-buffer (insert contents)
  2553. (org-table-align)
  2554. (buffer-string))
  2555. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2556. (reverse (org-element-property :tblfm table))
  2557. "\n"))))
  2558. ;;;; Table Row
  2559. (defun org-element-table-row-parser (_)
  2560. "Parse table row at point.
  2561. Return a list whose CAR is `table-row' and CDR is a plist
  2562. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2563. `:type', `:post-blank' and `:post-affiliated' keywords."
  2564. (save-excursion
  2565. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2566. (begin (point))
  2567. ;; A table rule has no contents. In that case, ensure
  2568. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2569. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2570. (contents-end (and (eq type 'standard)
  2571. (progn
  2572. (end-of-line)
  2573. (skip-chars-backward " \t")
  2574. (point))))
  2575. (end (line-beginning-position 2)))
  2576. (list 'table-row
  2577. (list :type type
  2578. :begin begin
  2579. :end end
  2580. :contents-begin contents-begin
  2581. :contents-end contents-end
  2582. :post-blank 0
  2583. :post-affiliated begin)))))
  2584. (defun org-element-table-row-interpreter (table-row contents)
  2585. "Interpret TABLE-ROW element as Org syntax.
  2586. CONTENTS is the contents of the table row."
  2587. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2588. (concat "|" contents)))
  2589. ;;;; Verse Block
  2590. (defun org-element-verse-block-parser (limit affiliated)
  2591. "Parse a verse block.
  2592. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2593. the buffer position at the beginning of the first affiliated
  2594. keyword and CDR is a plist of affiliated keywords along with
  2595. their value.
  2596. Return a list whose CAR is `verse-block' and CDR is a plist
  2597. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2598. `:post-blank' and `:post-affiliated' keywords.
  2599. Assume point is at beginning of the block."
  2600. (let ((case-fold-search t))
  2601. (if (not (save-excursion
  2602. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2603. ;; Incomplete block: parse it as a paragraph.
  2604. (org-element-paragraph-parser limit affiliated)
  2605. (let ((contents-end (match-beginning 0)))
  2606. (save-excursion
  2607. (let* ((begin (car affiliated))
  2608. (post-affiliated (point))
  2609. (contents-begin (progn (forward-line) (point)))
  2610. (pos-before-blank (progn (goto-char contents-end)
  2611. (forward-line)
  2612. (point)))
  2613. (end (progn (skip-chars-forward " \r\t\n" limit)
  2614. (if (eobp) (point) (line-beginning-position)))))
  2615. (list 'verse-block
  2616. (nconc
  2617. (list :begin begin
  2618. :end end
  2619. :contents-begin contents-begin
  2620. :contents-end contents-end
  2621. :post-blank (count-lines pos-before-blank end)
  2622. :post-affiliated post-affiliated)
  2623. (cdr affiliated)))))))))
  2624. (defun org-element-verse-block-interpreter (_ contents)
  2625. "Interpret verse-block element as Org syntax.
  2626. CONTENTS is verse block contents."
  2627. (format "#+begin_verse\n%s#+end_verse" contents))
  2628. ;;; Objects
  2629. ;;
  2630. ;; Unlike to elements, raw text can be found between objects. Hence,
  2631. ;; `org-element--object-lex' is provided to find the next object in
  2632. ;; buffer.
  2633. ;;
  2634. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2635. ;; object types they can contain will be specified in
  2636. ;; `org-element-object-restrictions'.
  2637. ;;
  2638. ;; Creating a new type of object requires to alter
  2639. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2640. ;; new type in `org-element-all-objects', and possibly add
  2641. ;; restrictions in `org-element-object-restrictions'.
  2642. ;;;; Bold
  2643. (defun org-element--parse-generic-emphasis (mark type)
  2644. "Parse emphasis object at point, if any.
  2645. MARK is the delimiter string used. TYPE is a symbol among
  2646. ‘bold’, ‘code’, ‘italic’, ‘strike-through’, ‘underline’, and
  2647. ‘verbatim’.
  2648. Assume point is at first MARK."
  2649. (save-excursion
  2650. (let ((origin (point)))
  2651. (unless (bolp) (forward-char -1))
  2652. (let ((opening-re
  2653. (rx-to-string
  2654. `(seq (or line-start (any space ?- ?\( ?' ?\" ?\{))
  2655. ,mark
  2656. (not space)))))
  2657. (when (looking-at opening-re)
  2658. (goto-char (1+ origin))
  2659. (let ((closing-re
  2660. (rx-to-string
  2661. `(seq
  2662. (not space)
  2663. (group ,mark)
  2664. (or (any space ?- ?. ?, ?\; ?: ?! ?? ?' ?\" ?\) ?\} ?\\ ?\[)
  2665. line-end)))))
  2666. (when (re-search-forward closing-re nil t)
  2667. (let ((closing (match-end 1)))
  2668. (goto-char closing)
  2669. (let* ((post-blank (skip-chars-forward " \t"))
  2670. (contents-begin (1+ origin))
  2671. (contents-end (1- closing)))
  2672. (list type
  2673. (append
  2674. (list :begin origin
  2675. :end (point)
  2676. :post-blank post-blank)
  2677. (if (memq type '(code verbatim))
  2678. (list :value
  2679. (and (memq type '(code verbatim))
  2680. (buffer-substring
  2681. contents-begin contents-end)))
  2682. (list :contents-begin contents-begin
  2683. :contents-end contents-end)))))))))))))
  2684. (defun org-element-bold-parser ()
  2685. "Parse bold object at point, if any.
  2686. When at a bold object, return a list whose car is `bold' and cdr
  2687. is a plist with `:begin', `:end', `:contents-begin' and
  2688. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2689. nil.
  2690. Assume point is at the first star marker."
  2691. (org-element--parse-generic-emphasis "*" 'bold))
  2692. (defun org-element-bold-interpreter (_ contents)
  2693. "Interpret bold object as Org syntax.
  2694. CONTENTS is the contents of the object."
  2695. (format "*%s*" contents))
  2696. ;;;; Citation
  2697. (defun org-element-citation-parser ()
  2698. "Parse citation object at point, if any.
  2699. When at a citation object, return a list whose car is `citation'
  2700. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2701. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2702. keywords. Otherwise, return nil.
  2703. Assume point is at the beginning of the citation."
  2704. (when (looking-at org-element-citation-prefix-re)
  2705. (let* ((begin (point))
  2706. (style (and (match-end 1)
  2707. (match-string-no-properties 1)))
  2708. ;; Ignore blanks between cite type and prefix or key.
  2709. (start (match-end 0))
  2710. (closing (with-syntax-table org-element--pair-square-table
  2711. (ignore-errors (scan-lists begin 1 0)))))
  2712. (save-excursion
  2713. (when (and closing
  2714. (re-search-forward org-element-citation-key-re closing t))
  2715. ;; Find prefix, if any.
  2716. (let ((first-key-end (match-end 0))
  2717. (types (org-element-restriction 'citation-reference))
  2718. (cite
  2719. (list 'citation
  2720. (list :style style
  2721. :begin begin
  2722. :post-blank (progn
  2723. (goto-char closing)
  2724. (skip-chars-forward " \t"))
  2725. :end (point)))))
  2726. ;; `:contents-begin' depends on the presence of
  2727. ;; a non-empty common prefix.
  2728. (goto-char first-key-end)
  2729. (if (not (search-backward ";" start t))
  2730. (org-element-put-property cite :contents-begin start)
  2731. (when (< start (point))
  2732. (org-element-put-property
  2733. cite :prefix
  2734. (org-element--parse-objects start (point) nil types cite)))
  2735. (forward-char)
  2736. (org-element-put-property cite :contents-begin (point)))
  2737. ;; `:contents-end' depends on the presence of a non-empty
  2738. ;; common suffix.
  2739. (goto-char (1- closing))
  2740. (skip-chars-backward " \r\t\n")
  2741. (let ((end (point)))
  2742. (if (or (not (search-backward ";" first-key-end t))
  2743. (re-search-forward org-element-citation-key-re end t))
  2744. (org-element-put-property cite :contents-end end)
  2745. (forward-char)
  2746. (when (< (point) end)
  2747. (org-element-put-property
  2748. cite :suffix
  2749. (org-element--parse-objects (point) end nil types cite)))
  2750. (org-element-put-property cite :contents-end (point))))
  2751. cite))))))
  2752. (defun org-element-citation-interpreter (citation contents)
  2753. "Interpret CITATION object as Org syntax.
  2754. CONTENTS is the contents of the object, as a string."
  2755. (let ((prefix (org-element-property :prefix citation))
  2756. (suffix (org-element-property :suffix citation))
  2757. (style (org-element-property :style citation)))
  2758. (concat "[cite"
  2759. (and style (concat "/" style))
  2760. ":"
  2761. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2762. (if suffix
  2763. (concat contents (org-element-interpret-data suffix))
  2764. ;; Remove spurious semicolon.
  2765. (substring contents nil -1))
  2766. "]")))
  2767. ;;;; Citation Reference
  2768. (defun org-element-citation-reference-parser ()
  2769. "Parse citation reference object at point, if any.
  2770. When at a reference, return a list whose car is
  2771. `citation-reference', and cdr is a plist with `:key',
  2772. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2773. Assume point is at the beginning of the reference."
  2774. (save-excursion
  2775. (let ((begin (point)))
  2776. (when (re-search-forward org-element-citation-key-re nil t)
  2777. (let* ((key (match-string-no-properties 1))
  2778. (key-start (match-beginning 0))
  2779. (key-end (match-end 0))
  2780. (separator (search-forward ";" nil t))
  2781. (end (or separator (point-max)))
  2782. (suffix-end (if separator (1- end) end))
  2783. (types (org-element-restriction 'citation-reference))
  2784. (reference
  2785. (list 'citation-reference
  2786. (list :key key
  2787. :begin begin
  2788. :end end
  2789. :post-blank 0))))
  2790. (when (< begin key-start)
  2791. (org-element-put-property
  2792. reference :prefix
  2793. (org-element--parse-objects begin key-start nil types reference)))
  2794. (when (< key-end suffix-end)
  2795. (org-element-put-property
  2796. reference :suffix
  2797. (org-element--parse-objects key-end suffix-end nil types reference)))
  2798. reference)))))
  2799. (defun org-element-citation-reference-interpreter (citation-reference _)
  2800. "Interpret CITATION-REFERENCE object as Org syntax."
  2801. (concat (org-element-interpret-data
  2802. (org-element-property :prefix citation-reference))
  2803. "@" (org-element-property :key citation-reference)
  2804. (org-element-interpret-data
  2805. (org-element-property :suffix citation-reference))
  2806. ";"))
  2807. ;;;; Code
  2808. (defun org-element-code-parser ()
  2809. "Parse code object at point, if any.
  2810. When at a code object, return a list whose car is `code' and cdr
  2811. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2812. keywords. Otherwise, return nil.
  2813. Assume point is at the first tilde marker."
  2814. (org-element--parse-generic-emphasis "~" 'code))
  2815. (defun org-element-code-interpreter (code _)
  2816. "Interpret CODE object as Org syntax."
  2817. (format "~%s~" (org-element-property :value code)))
  2818. ;;;; Entity
  2819. (defun org-element-entity-parser ()
  2820. "Parse entity at point, if any.
  2821. When at an entity, return a list whose car is `entity' and cdr
  2822. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2823. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2824. `:post-blank' as keywords. Otherwise, return nil.
  2825. Assume point is at the beginning of the entity."
  2826. (catch 'no-object
  2827. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2828. (save-excursion
  2829. (let* ((value (or (org-entity-get (match-string 1))
  2830. (throw 'no-object nil)))
  2831. (begin (match-beginning 0))
  2832. (bracketsp (string= (match-string 2) "{}"))
  2833. (post-blank (progn (goto-char (match-end 1))
  2834. (when bracketsp (forward-char 2))
  2835. (skip-chars-forward " \t")))
  2836. (end (point)))
  2837. (list 'entity
  2838. (list :name (car value)
  2839. :latex (nth 1 value)
  2840. :latex-math-p (nth 2 value)
  2841. :html (nth 3 value)
  2842. :ascii (nth 4 value)
  2843. :latin1 (nth 5 value)
  2844. :utf-8 (nth 6 value)
  2845. :begin begin
  2846. :end end
  2847. :use-brackets-p bracketsp
  2848. :post-blank post-blank)))))))
  2849. (defun org-element-entity-interpreter (entity _)
  2850. "Interpret ENTITY object as Org syntax."
  2851. (concat "\\"
  2852. (org-element-property :name entity)
  2853. (when (org-element-property :use-brackets-p entity) "{}")))
  2854. ;;;; Export Snippet
  2855. (defun org-element-export-snippet-parser ()
  2856. "Parse export snippet at point.
  2857. When at an export snippet, return a list whose car is
  2858. `export-snippet' and cdr a plist with `:begin', `:end',
  2859. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2860. return nil.
  2861. Assume point is at the beginning of the snippet."
  2862. (save-excursion
  2863. (let (contents-end)
  2864. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2865. (setq contents-end
  2866. (save-match-data (goto-char (match-end 0))
  2867. (when
  2868. (re-search-forward "@@" nil t)
  2869. (match-beginning 0)))))
  2870. (let* ((begin (match-beginning 0))
  2871. (back-end (match-string-no-properties 1))
  2872. (value (buffer-substring-no-properties
  2873. (match-end 0) contents-end))
  2874. (post-blank (skip-chars-forward " \t"))
  2875. (end (point)))
  2876. (list 'export-snippet
  2877. (list :back-end back-end
  2878. :value value
  2879. :begin begin
  2880. :end end
  2881. :post-blank post-blank)))))))
  2882. (defun org-element-export-snippet-interpreter (export-snippet _)
  2883. "Interpret EXPORT-SNIPPET object as Org syntax."
  2884. (format "@@%s:%s@@"
  2885. (org-element-property :back-end export-snippet)
  2886. (org-element-property :value export-snippet)))
  2887. ;;;; Footnote Reference
  2888. (defun org-element-footnote-reference-parser ()
  2889. "Parse footnote reference at point, if any.
  2890. When at a footnote reference, return a list whose car is
  2891. `footnote-reference' and cdr a plist with `:label', `:type',
  2892. `:begin', `:end', `:contents-begin', `:contents-end' and
  2893. `:post-blank' as keywords. Otherwise, return nil."
  2894. (when (looking-at org-footnote-re)
  2895. (let ((closing (with-syntax-table org-element--pair-square-table
  2896. (ignore-errors (scan-lists (point) 1 0)))))
  2897. (when closing
  2898. (save-excursion
  2899. (let* ((begin (point))
  2900. (label (match-string-no-properties 1))
  2901. (inner-begin (match-end 0))
  2902. (inner-end (1- closing))
  2903. (type (if (match-end 2) 'inline 'standard))
  2904. (post-blank (progn (goto-char closing)
  2905. (skip-chars-forward " \t")))
  2906. (end (point)))
  2907. (list 'footnote-reference
  2908. (list :label label
  2909. :type type
  2910. :begin begin
  2911. :end end
  2912. :contents-begin (and (eq type 'inline) inner-begin)
  2913. :contents-end (and (eq type 'inline) inner-end)
  2914. :post-blank post-blank))))))))
  2915. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2916. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2917. CONTENTS is its definition, when inline, or nil."
  2918. (format "[fn:%s%s]"
  2919. (or (org-element-property :label footnote-reference) "")
  2920. (if contents (concat ":" contents) "")))
  2921. ;;;; Inline Babel Call
  2922. (defun org-element-inline-babel-call-parser ()
  2923. "Parse inline babel call at point, if any.
  2924. When at an inline babel call, return a list whose car is
  2925. `inline-babel-call' and cdr a plist with `:call',
  2926. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2927. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2928. Assume point is at the beginning of the babel call."
  2929. (save-excursion
  2930. (catch :no-object
  2931. (when (let ((case-fold-search nil))
  2932. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2933. (goto-char (match-end 1))
  2934. (let* ((begin (match-beginning 0))
  2935. (call (match-string-no-properties 1))
  2936. (inside-header
  2937. (let ((p (org-element--parse-paired-brackets ?\[)))
  2938. (and (org-string-nw-p p)
  2939. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2940. (arguments (org-string-nw-p
  2941. (or (org-element--parse-paired-brackets ?\()
  2942. ;; Parenthesis are mandatory.
  2943. (throw :no-object nil))))
  2944. (end-header
  2945. (let ((p (org-element--parse-paired-brackets ?\[)))
  2946. (and (org-string-nw-p p)
  2947. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2948. (value (buffer-substring-no-properties begin (point)))
  2949. (post-blank (skip-chars-forward " \t"))
  2950. (end (point)))
  2951. (list 'inline-babel-call
  2952. (list :call call
  2953. :inside-header inside-header
  2954. :arguments arguments
  2955. :end-header end-header
  2956. :begin begin
  2957. :end end
  2958. :value value
  2959. :post-blank post-blank)))))))
  2960. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2961. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2962. (concat "call_"
  2963. (org-element-property :call inline-babel-call)
  2964. (let ((h (org-element-property :inside-header inline-babel-call)))
  2965. (and h (format "[%s]" h)))
  2966. "(" (org-element-property :arguments inline-babel-call) ")"
  2967. (let ((h (org-element-property :end-header inline-babel-call)))
  2968. (and h (format "[%s]" h)))))
  2969. ;;;; Inline Src Block
  2970. (defun org-element-inline-src-block-parser ()
  2971. "Parse inline source block at point, if any.
  2972. When at an inline source block, return a list whose car is
  2973. `inline-src-block' and cdr a plist with `:begin', `:end',
  2974. `:language', `:value', `:parameters' and `:post-blank' as
  2975. keywords. Otherwise, return nil.
  2976. Assume point is at the beginning of the inline source block."
  2977. (save-excursion
  2978. (catch :no-object
  2979. (when (let ((case-fold-search nil))
  2980. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2981. (goto-char (match-end 1))
  2982. (let ((begin (match-beginning 0))
  2983. (language (match-string-no-properties 1))
  2984. (parameters
  2985. (let ((p (org-element--parse-paired-brackets ?\[)))
  2986. (and (org-string-nw-p p)
  2987. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2988. (value (or (org-element--parse-paired-brackets ?\{)
  2989. (throw :no-object nil)))
  2990. (post-blank (skip-chars-forward " \t")))
  2991. (list 'inline-src-block
  2992. (list :language language
  2993. :value value
  2994. :parameters parameters
  2995. :begin begin
  2996. :end (point)
  2997. :post-blank post-blank)))))))
  2998. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2999. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  3000. (let ((language (org-element-property :language inline-src-block))
  3001. (arguments (org-element-property :parameters inline-src-block))
  3002. (body (org-element-property :value inline-src-block)))
  3003. (format "src_%s%s{%s}"
  3004. language
  3005. (if arguments (format "[%s]" arguments) "")
  3006. body)))
  3007. ;;;; Italic
  3008. (defun org-element-italic-parser ()
  3009. "Parse italic object at point, if any.
  3010. When at an italic object, return a list whose car is `italic' and
  3011. cdr is a plist with `:begin', `:end', `:contents-begin' and
  3012. `:contents-end' and `:post-blank' keywords. Otherwise, return
  3013. nil.
  3014. Assume point is at the first slash marker."
  3015. (org-element--parse-generic-emphasis "/" 'italic))
  3016. (defun org-element-italic-interpreter (_ contents)
  3017. "Interpret italic object as Org syntax.
  3018. CONTENTS is the contents of the object."
  3019. (format "/%s/" contents))
  3020. ;;;; Latex Fragment
  3021. (defun org-element-latex-fragment-parser ()
  3022. "Parse LaTeX fragment at point, if any.
  3023. When at a LaTeX fragment, return a list whose car is
  3024. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  3025. and `:post-blank' as keywords. Otherwise, return nil.
  3026. Assume point is at the beginning of the LaTeX fragment."
  3027. (catch 'no-object
  3028. (save-excursion
  3029. (let* ((begin (point))
  3030. (after-fragment
  3031. (cond
  3032. ((not (eq ?$ (char-after)))
  3033. (pcase (char-after (1+ (point)))
  3034. (?\( (search-forward "\\)" nil t))
  3035. (?\[ (search-forward "\\]" nil t))
  3036. (_
  3037. ;; Macro.
  3038. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  3039. \\|\\({[^{}\n]*}\\)\\)*")
  3040. (match-end 0)))))
  3041. ((eq ?$ (char-after (1+ (point))))
  3042. (search-forward "$$" nil t 2))
  3043. (t
  3044. (and (not (eq ?$ (char-before)))
  3045. (not (memq (char-after (1+ (point)))
  3046. '(?\s ?\t ?\n ?, ?. ?\;)))
  3047. (search-forward "$" nil t 2)
  3048. (not (memq (char-before (match-beginning 0))
  3049. '(?\s ?\t ?\n ?, ?.)))
  3050. (looking-at-p
  3051. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  3052. (point)))))
  3053. (post-blank
  3054. (if (not after-fragment) (throw 'no-object nil)
  3055. (goto-char after-fragment)
  3056. (skip-chars-forward " \t")))
  3057. (end (point)))
  3058. (list 'latex-fragment
  3059. (list :value (buffer-substring-no-properties begin after-fragment)
  3060. :begin begin
  3061. :end end
  3062. :post-blank post-blank))))))
  3063. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  3064. "Interpret LATEX-FRAGMENT object as Org syntax."
  3065. (org-element-property :value latex-fragment))
  3066. ;;;; Line Break
  3067. (defun org-element-line-break-parser ()
  3068. "Parse line break at point, if any.
  3069. When at a line break, return a list whose car is `line-break',
  3070. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  3071. Otherwise, return nil.
  3072. Assume point is at the beginning of the line break."
  3073. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  3074. (not (eq (char-before) ?\\)))
  3075. (list 'line-break
  3076. (list :begin (point)
  3077. :end (line-beginning-position 2)
  3078. :post-blank 0))))
  3079. (defun org-element-line-break-interpreter (&rest _)
  3080. "Interpret LINE-BREAK object as Org syntax."
  3081. "\\\\\n")
  3082. ;;;; Link
  3083. (defun org-element-link-parser ()
  3084. "Parse link at point, if any.
  3085. When at a link, return a list whose car is `link' and cdr a plist
  3086. with `:type', `:path', `:format', `:raw-link', `:application',
  3087. `:search-option', `:begin', `:end', `:contents-begin',
  3088. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  3089. nil.
  3090. Assume point is at the beginning of the link."
  3091. (catch 'no-object
  3092. (let ((begin (point))
  3093. end contents-begin contents-end link-end post-blank path type format
  3094. raw-link search-option application)
  3095. (cond
  3096. ;; Type 1: Text targeted from a radio target.
  3097. ((and org-target-link-regexp
  3098. (save-excursion (or (bolp) (backward-char))
  3099. (looking-at org-target-link-regexp)))
  3100. (setq type "radio")
  3101. (setq format 'plain)
  3102. (setq link-end (match-end 1))
  3103. (setq path (match-string-no-properties 1))
  3104. (setq contents-begin (match-beginning 1))
  3105. (setq contents-end (match-end 1)))
  3106. ;; Type 2: Standard link, i.e. [[https://orgmode.org][website]]
  3107. ((looking-at org-link-bracket-re)
  3108. (setq format 'bracket)
  3109. (setq contents-begin (match-beginning 2))
  3110. (setq contents-end (match-end 2))
  3111. (setq link-end (match-end 0))
  3112. ;; RAW-LINK is the original link. Decode any encoding.
  3113. ;; Expand any abbreviation in it.
  3114. ;;
  3115. ;; Also treat any newline character and associated
  3116. ;; indentation as a single space character. This is not
  3117. ;; compatible with RFC 3986, which requires to ignore
  3118. ;; them altogether. However, doing so would require
  3119. ;; users to encode spaces on the fly when writing links
  3120. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  3121. ;; [[shell:ls *.org]], which defeats Org's focus on
  3122. ;; simplicity.
  3123. (setq raw-link (org-link-expand-abbrev
  3124. (org-link-unescape
  3125. (replace-regexp-in-string
  3126. "[ \t]*\n[ \t]*" " "
  3127. (match-string-no-properties 1)))))
  3128. ;; Determine TYPE of link and set PATH accordingly. According
  3129. ;; to RFC 3986, remove whitespaces from URI in external links.
  3130. ;; In internal ones, treat indentation as a single space.
  3131. (cond
  3132. ;; File type.
  3133. ((or (file-name-absolute-p raw-link)
  3134. (string-match "\\`\\.\\.?/" raw-link))
  3135. (setq type "file")
  3136. (setq path raw-link))
  3137. ;; Explicit type (http, irc, bbdb...).
  3138. ((string-match org-link-types-re raw-link)
  3139. (setq type (match-string 1 raw-link))
  3140. (setq path (substring raw-link (match-end 0))))
  3141. ;; Code-ref type: PATH is the name of the reference.
  3142. ((and (string-match-p "\\`(" raw-link)
  3143. (string-match-p ")\\'" raw-link))
  3144. (setq type "coderef")
  3145. (setq path (substring raw-link 1 -1)))
  3146. ;; Custom-id type: PATH is the name of the custom id.
  3147. ((= (string-to-char raw-link) ?#)
  3148. (setq type "custom-id")
  3149. (setq path (substring raw-link 1)))
  3150. ;; Fuzzy type: Internal link either matches a target, an
  3151. ;; headline name or nothing. PATH is the target or
  3152. ;; headline's name.
  3153. (t
  3154. (setq type "fuzzy")
  3155. (setq path raw-link))))
  3156. ;; Type 3: Plain link, e.g., https://orgmode.org
  3157. ((looking-at org-link-plain-re)
  3158. (setq format 'plain)
  3159. (setq raw-link (match-string-no-properties 0))
  3160. (setq type (match-string-no-properties 1))
  3161. (setq link-end (match-end 0))
  3162. (setq path (match-string-no-properties 2)))
  3163. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  3164. ;; bracket links, follow RFC 3986 and remove any extra
  3165. ;; whitespace in URI.
  3166. ((looking-at org-link-angle-re)
  3167. (setq format 'angle)
  3168. (setq type (match-string-no-properties 1))
  3169. (setq link-end (match-end 0))
  3170. (setq raw-link
  3171. (buffer-substring-no-properties
  3172. (match-beginning 1) (match-end 2)))
  3173. (setq path (replace-regexp-in-string
  3174. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  3175. (t (throw 'no-object nil)))
  3176. ;; In any case, deduce end point after trailing white space from
  3177. ;; LINK-END variable.
  3178. (save-excursion
  3179. (setq post-blank
  3180. (progn (goto-char link-end) (skip-chars-forward " \t")))
  3181. (setq end (point)))
  3182. ;; Special "file"-type link processing. Extract opening
  3183. ;; application and search option, if any. Also normalize URI.
  3184. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  3185. (setq application (match-string 1 type))
  3186. (setq type "file")
  3187. (when (string-match "::\\(.*\\)\\'" path)
  3188. (setq search-option (match-string 1 path))
  3189. (setq path (replace-match "" nil nil path)))
  3190. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3191. ;; Translate link, if `org-link-translation-function' is set.
  3192. (let ((trans (and (functionp org-link-translation-function)
  3193. (funcall org-link-translation-function type path))))
  3194. (when trans
  3195. (setq type (car trans))
  3196. (setq path (cdr trans))))
  3197. (list 'link
  3198. (list :type type
  3199. :path path
  3200. :format format
  3201. :raw-link (or raw-link path)
  3202. :application application
  3203. :search-option search-option
  3204. :begin begin
  3205. :end end
  3206. :contents-begin contents-begin
  3207. :contents-end contents-end
  3208. :post-blank post-blank)))))
  3209. (defun org-element-link-interpreter (link contents)
  3210. "Interpret LINK object as Org syntax.
  3211. CONTENTS is the contents of the object, or nil."
  3212. (let ((type (org-element-property :type link))
  3213. (path (org-element-property :path link)))
  3214. (if (string= type "radio") path
  3215. (let ((fmt (pcase (org-element-property :format link)
  3216. ;; Links with contents and internal links have to
  3217. ;; use bracket syntax. Ignore `:format' in these
  3218. ;; cases. This is also the default syntax when the
  3219. ;; property is not defined, e.g., when the object
  3220. ;; was crafted by the user.
  3221. ((guard contents)
  3222. (format "[[%%s][%s]]"
  3223. ;; Since this is going to be used as
  3224. ;; a format string, escape percent signs
  3225. ;; in description.
  3226. (replace-regexp-in-string "%" "%%" contents)))
  3227. ((or `bracket
  3228. `nil
  3229. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3230. "[[%s]]")
  3231. ;; Otherwise, just obey to `:format'.
  3232. (`angle "<%s>")
  3233. (`plain "%s")
  3234. (f (error "Wrong `:format' value: %s" f)))))
  3235. (format fmt
  3236. (pcase type
  3237. ("coderef" (format "(%s)" path))
  3238. ("custom-id" (concat "#" path))
  3239. ("file"
  3240. (let ((app (org-element-property :application link))
  3241. (opt (org-element-property :search-option link)))
  3242. (concat type (and app (concat "+" app)) ":"
  3243. path
  3244. (and opt (concat "::" opt)))))
  3245. ("fuzzy" path)
  3246. (_ (concat type ":" path))))))))
  3247. ;;;; Macro
  3248. (defun org-element-macro-parser ()
  3249. "Parse macro at point, if any.
  3250. When at a macro, return a list whose car is `macro' and cdr
  3251. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3252. `:post-blank' as keywords. Otherwise, return nil.
  3253. Assume point is at the macro."
  3254. (save-excursion
  3255. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3256. (let ((begin (point))
  3257. (key (downcase (match-string-no-properties 1)))
  3258. (value (match-string-no-properties 0))
  3259. (post-blank (progn (goto-char (match-end 0))
  3260. (skip-chars-forward " \t")))
  3261. (end (point))
  3262. (args (pcase (match-string-no-properties 3)
  3263. (`nil nil)
  3264. (a (org-macro-extract-arguments
  3265. (replace-regexp-in-string
  3266. "[ \t\r\n]+" " " (org-trim a)))))))
  3267. (list 'macro
  3268. (list :key key
  3269. :value value
  3270. :args args
  3271. :begin begin
  3272. :end end
  3273. :post-blank post-blank))))))
  3274. (defun org-element-macro-interpreter (macro _)
  3275. "Interpret MACRO object as Org syntax."
  3276. (format "{{{%s%s}}}"
  3277. (org-element-property :key macro)
  3278. (pcase (org-element-property :args macro)
  3279. (`nil "")
  3280. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3281. ;;;; Radio-target
  3282. (defun org-element-radio-target-parser ()
  3283. "Parse radio target at point, if any.
  3284. When at a radio target, return a list whose car is `radio-target'
  3285. and cdr a plist with `:begin', `:end', `:contents-begin',
  3286. `:contents-end', `:value' and `:post-blank' as keywords.
  3287. Otherwise, return nil.
  3288. Assume point is at the radio target."
  3289. (save-excursion
  3290. (when (looking-at org-radio-target-regexp)
  3291. (let ((begin (point))
  3292. (contents-begin (match-beginning 1))
  3293. (contents-end (match-end 1))
  3294. (value (match-string-no-properties 1))
  3295. (post-blank (progn (goto-char (match-end 0))
  3296. (skip-chars-forward " \t")))
  3297. (end (point)))
  3298. (list 'radio-target
  3299. (list :begin begin
  3300. :end end
  3301. :contents-begin contents-begin
  3302. :contents-end contents-end
  3303. :post-blank post-blank
  3304. :value value))))))
  3305. (defun org-element-radio-target-interpreter (_ contents)
  3306. "Interpret target object as Org syntax.
  3307. CONTENTS is the contents of the object."
  3308. (concat "<<<" contents ">>>"))
  3309. ;;;; Statistics Cookie
  3310. (defun org-element-statistics-cookie-parser ()
  3311. "Parse statistics cookie at point, if any.
  3312. When at a statistics cookie, return a list whose car is
  3313. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3314. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3315. Assume point is at the beginning of the statistics-cookie."
  3316. (save-excursion
  3317. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3318. (let* ((begin (point))
  3319. (value (buffer-substring-no-properties
  3320. (match-beginning 0) (match-end 0)))
  3321. (post-blank (progn (goto-char (match-end 0))
  3322. (skip-chars-forward " \t")))
  3323. (end (point)))
  3324. (list 'statistics-cookie
  3325. (list :begin begin
  3326. :end end
  3327. :value value
  3328. :post-blank post-blank))))))
  3329. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3330. "Interpret STATISTICS-COOKIE object as Org syntax."
  3331. (org-element-property :value statistics-cookie))
  3332. ;;;; Strike-Through
  3333. (defun org-element-strike-through-parser ()
  3334. "Parse strike-through object at point, if any.
  3335. When at a strike-through object, return a list whose car is
  3336. `strike-through' and cdr is a plist with `:begin', `:end',
  3337. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3338. Otherwise, return nil.
  3339. Assume point is at the first plus sign marker."
  3340. (org-element--parse-generic-emphasis "+" 'strike-through))
  3341. (defun org-element-strike-through-interpreter (_ contents)
  3342. "Interpret strike-through object as Org syntax.
  3343. CONTENTS is the contents of the object."
  3344. (format "+%s+" contents))
  3345. ;;;; Subscript
  3346. (defun org-element-subscript-parser ()
  3347. "Parse subscript at point, if any.
  3348. When at a subscript object, return a list whose car is
  3349. `subscript' and cdr a plist with `:begin', `:end',
  3350. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3351. `:post-blank' as keywords. Otherwise, return nil.
  3352. Assume point is at the underscore."
  3353. (save-excursion
  3354. (unless (bolp) (backward-char))
  3355. (when (looking-at org-match-substring-regexp)
  3356. (let ((bracketsp (match-beginning 4))
  3357. (begin (match-beginning 2))
  3358. (contents-begin (or (match-beginning 4)
  3359. (match-beginning 3)))
  3360. (contents-end (or (match-end 4) (match-end 3)))
  3361. (post-blank (progn (goto-char (match-end 0))
  3362. (skip-chars-forward " \t")))
  3363. (end (point)))
  3364. (list 'subscript
  3365. (list :begin begin
  3366. :end end
  3367. :use-brackets-p bracketsp
  3368. :contents-begin contents-begin
  3369. :contents-end contents-end
  3370. :post-blank post-blank))))))
  3371. (defun org-element-subscript-interpreter (subscript contents)
  3372. "Interpret SUBSCRIPT object as Org syntax.
  3373. CONTENTS is the contents of the object."
  3374. (format
  3375. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3376. contents))
  3377. ;;;; Superscript
  3378. (defun org-element-superscript-parser ()
  3379. "Parse superscript at point, if any.
  3380. When at a superscript object, return a list whose car is
  3381. `superscript' and cdr a plist with `:begin', `:end',
  3382. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3383. `:post-blank' as keywords. Otherwise, return nil.
  3384. Assume point is at the caret."
  3385. (save-excursion
  3386. (unless (bolp) (backward-char))
  3387. (when (looking-at org-match-substring-regexp)
  3388. (let ((bracketsp (match-beginning 4))
  3389. (begin (match-beginning 2))
  3390. (contents-begin (or (match-beginning 4)
  3391. (match-beginning 3)))
  3392. (contents-end (or (match-end 4) (match-end 3)))
  3393. (post-blank (progn (goto-char (match-end 0))
  3394. (skip-chars-forward " \t")))
  3395. (end (point)))
  3396. (list 'superscript
  3397. (list :begin begin
  3398. :end end
  3399. :use-brackets-p bracketsp
  3400. :contents-begin contents-begin
  3401. :contents-end contents-end
  3402. :post-blank post-blank))))))
  3403. (defun org-element-superscript-interpreter (superscript contents)
  3404. "Interpret SUPERSCRIPT object as Org syntax.
  3405. CONTENTS is the contents of the object."
  3406. (format
  3407. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3408. contents))
  3409. ;;;; Table Cell
  3410. (defun org-element-table-cell-parser ()
  3411. "Parse table cell at point.
  3412. Return a list whose car is `table-cell' and cdr is a plist
  3413. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3414. and `:post-blank' keywords."
  3415. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3416. (let* ((begin (match-beginning 0))
  3417. (end (match-end 0))
  3418. (contents-begin (match-beginning 1))
  3419. (contents-end (match-end 1)))
  3420. (list 'table-cell
  3421. (list :begin begin
  3422. :end end
  3423. :contents-begin contents-begin
  3424. :contents-end contents-end
  3425. :post-blank 0))))
  3426. (defun org-element-table-cell-interpreter (_ contents)
  3427. "Interpret table-cell element as Org syntax.
  3428. CONTENTS is the contents of the cell, or nil."
  3429. (concat " " contents " |"))
  3430. ;;;; Target
  3431. (defun org-element-target-parser ()
  3432. "Parse target at point, if any.
  3433. When at a target, return a list whose car is `target' and cdr
  3434. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3435. keywords. Otherwise, return nil.
  3436. Assume point is at the target."
  3437. (save-excursion
  3438. (when (looking-at org-target-regexp)
  3439. (let ((begin (point))
  3440. (value (match-string-no-properties 1))
  3441. (post-blank (progn (goto-char (match-end 0))
  3442. (skip-chars-forward " \t")))
  3443. (end (point)))
  3444. (list 'target
  3445. (list :begin begin
  3446. :end end
  3447. :value value
  3448. :post-blank post-blank))))))
  3449. (defun org-element-target-interpreter (target _)
  3450. "Interpret TARGET object as Org syntax."
  3451. (format "<<%s>>" (org-element-property :value target)))
  3452. ;;;; Timestamp
  3453. (defconst org-element--timestamp-regexp
  3454. (concat org-ts-regexp-both
  3455. "\\|"
  3456. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3457. "\\|"
  3458. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3459. "Regexp matching any timestamp type object.")
  3460. (defun org-element-timestamp-parser ()
  3461. "Parse time stamp at point, if any.
  3462. When at a time stamp, return a list whose car is `timestamp', and
  3463. cdr a plist with `:type', `:raw-value', `:year-start',
  3464. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3465. `:year-end', `:month-end', `:day-end', `:hour-end',
  3466. `:minute-end', `:repeater-type', `:repeater-value',
  3467. `:repeater-unit', `:warning-type', `:warning-value',
  3468. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3469. Otherwise, return nil.
  3470. Assume point is at the beginning of the timestamp."
  3471. (when (looking-at-p org-element--timestamp-regexp)
  3472. (save-excursion
  3473. (let* ((begin (point))
  3474. (activep (eq (char-after) ?<))
  3475. (raw-value
  3476. (progn
  3477. (looking-at (concat "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\("
  3478. org-ts-regexp-both
  3479. "\\)\\)?"))
  3480. (match-string-no-properties 0)))
  3481. (date-start (match-string-no-properties 1))
  3482. (date-end (match-string 3))
  3483. (diaryp (match-beginning 2))
  3484. (post-blank (progn (goto-char (match-end 0))
  3485. (skip-chars-forward " \t")))
  3486. (end (point))
  3487. (time-range
  3488. (and (not diaryp)
  3489. (string-match
  3490. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3491. date-start)
  3492. (cons (string-to-number (match-string 2 date-start))
  3493. (string-to-number (match-string 3 date-start)))))
  3494. (type (cond (diaryp 'diary)
  3495. ((and activep (or date-end time-range)) 'active-range)
  3496. (activep 'active)
  3497. ((or date-end time-range) 'inactive-range)
  3498. (t 'inactive)))
  3499. (repeater-props
  3500. (and (not diaryp)
  3501. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3502. raw-value)
  3503. (list
  3504. :repeater-type
  3505. (let ((type (match-string 1 raw-value)))
  3506. (cond ((equal "++" type) 'catch-up)
  3507. ((equal ".+" type) 'restart)
  3508. (t 'cumulate)))
  3509. :repeater-value (string-to-number (match-string 2 raw-value))
  3510. :repeater-unit
  3511. (pcase (string-to-char (match-string 3 raw-value))
  3512. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3513. (warning-props
  3514. (and (not diaryp)
  3515. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3516. (list
  3517. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3518. :warning-value (string-to-number (match-string 2 raw-value))
  3519. :warning-unit
  3520. (pcase (string-to-char (match-string 3 raw-value))
  3521. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3522. year-start month-start day-start hour-start minute-start year-end
  3523. month-end day-end hour-end minute-end)
  3524. ;; Parse date-start.
  3525. (unless diaryp
  3526. (let ((date (org-parse-time-string date-start t)))
  3527. (setq year-start (nth 5 date)
  3528. month-start (nth 4 date)
  3529. day-start (nth 3 date)
  3530. hour-start (nth 2 date)
  3531. minute-start (nth 1 date))))
  3532. ;; Compute date-end. It can be provided directly in time-stamp,
  3533. ;; or extracted from time range. Otherwise, it defaults to the
  3534. ;; same values as date-start.
  3535. (unless diaryp
  3536. (let ((date (and date-end (org-parse-time-string date-end t))))
  3537. (setq year-end (or (nth 5 date) year-start)
  3538. month-end (or (nth 4 date) month-start)
  3539. day-end (or (nth 3 date) day-start)
  3540. hour-end (or (nth 2 date) (car time-range) hour-start)
  3541. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3542. (list 'timestamp
  3543. (nconc (list :type type
  3544. :raw-value raw-value
  3545. :year-start year-start
  3546. :month-start month-start
  3547. :day-start day-start
  3548. :hour-start hour-start
  3549. :minute-start minute-start
  3550. :year-end year-end
  3551. :month-end month-end
  3552. :day-end day-end
  3553. :hour-end hour-end
  3554. :minute-end minute-end
  3555. :begin begin
  3556. :end end
  3557. :post-blank post-blank)
  3558. repeater-props
  3559. warning-props))))))
  3560. (defun org-element-timestamp-interpreter (timestamp _)
  3561. "Interpret TIMESTAMP object as Org syntax."
  3562. (let* ((repeat-string
  3563. (concat
  3564. (pcase (org-element-property :repeater-type timestamp)
  3565. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3566. (let ((val (org-element-property :repeater-value timestamp)))
  3567. (and val (number-to-string val)))
  3568. (pcase (org-element-property :repeater-unit timestamp)
  3569. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3570. (warning-string
  3571. (concat
  3572. (pcase (org-element-property :warning-type timestamp)
  3573. (`first "--") (`all "-"))
  3574. (let ((val (org-element-property :warning-value timestamp)))
  3575. (and val (number-to-string val)))
  3576. (pcase (org-element-property :warning-unit timestamp)
  3577. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3578. (build-ts-string
  3579. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3580. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3581. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3582. ;; specify a time range in the timestamp. REPEAT-STRING is
  3583. ;; the repeater string, if any.
  3584. (lambda (time activep &optional with-time-p hour-end minute-end)
  3585. (let ((ts (format-time-string
  3586. (funcall (if with-time-p #'cdr #'car)
  3587. org-time-stamp-formats)
  3588. time)))
  3589. (when (and hour-end minute-end)
  3590. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3591. (setq ts
  3592. (replace-match
  3593. (format "\\&-%02d:%02d" hour-end minute-end)
  3594. nil nil ts)))
  3595. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3596. (dolist (s (list repeat-string warning-string))
  3597. (when (org-string-nw-p s)
  3598. (setq ts (concat (substring ts 0 -1)
  3599. " "
  3600. s
  3601. (substring ts -1)))))
  3602. ;; Return value.
  3603. ts)))
  3604. (type (org-element-property :type timestamp)))
  3605. (pcase type
  3606. ((or `active `inactive)
  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. (time-range-p (and hour-start hour-end minute-start minute-end
  3612. (or (/= hour-start hour-end)
  3613. (/= minute-start minute-end)))))
  3614. (funcall
  3615. build-ts-string
  3616. (encode-time 0
  3617. (or minute-start 0)
  3618. (or hour-start 0)
  3619. (org-element-property :day-start timestamp)
  3620. (org-element-property :month-start timestamp)
  3621. (org-element-property :year-start timestamp))
  3622. (eq type 'active)
  3623. (and hour-start minute-start)
  3624. (and time-range-p hour-end)
  3625. (and time-range-p minute-end))))
  3626. ((or `active-range `inactive-range)
  3627. (let ((minute-start (org-element-property :minute-start timestamp))
  3628. (minute-end (org-element-property :minute-end timestamp))
  3629. (hour-start (org-element-property :hour-start timestamp))
  3630. (hour-end (org-element-property :hour-end timestamp)))
  3631. (concat
  3632. (funcall
  3633. build-ts-string (encode-time
  3634. 0
  3635. (or minute-start 0)
  3636. (or hour-start 0)
  3637. (org-element-property :day-start timestamp)
  3638. (org-element-property :month-start timestamp)
  3639. (org-element-property :year-start timestamp))
  3640. (eq type 'active-range)
  3641. (and hour-start minute-start))
  3642. "--"
  3643. (funcall build-ts-string
  3644. (encode-time 0
  3645. (or minute-end 0)
  3646. (or hour-end 0)
  3647. (org-element-property :day-end timestamp)
  3648. (org-element-property :month-end timestamp)
  3649. (org-element-property :year-end timestamp))
  3650. (eq type 'active-range)
  3651. (and hour-end minute-end)))))
  3652. (_ (org-element-property :raw-value timestamp)))))
  3653. ;;;; Underline
  3654. (defun org-element-underline-parser ()
  3655. "Parse underline object at point, if any.
  3656. When at an underline object, return a list whose car is
  3657. `underline' and cdr is a plist with `:begin', `:end',
  3658. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3659. Otherwise, return nil.
  3660. Assume point is at the first underscore marker."
  3661. (org-element--parse-generic-emphasis "_" 'underline))
  3662. (defun org-element-underline-interpreter (_ contents)
  3663. "Interpret underline object as Org syntax.
  3664. CONTENTS is the contents of the object."
  3665. (format "_%s_" contents))
  3666. ;;;; Verbatim
  3667. (defun org-element-verbatim-parser ()
  3668. "Parse verbatim object at point, if any.
  3669. When at a verbatim object, return a list whose car is `verbatim'
  3670. and cdr is a plist with `:value', `:begin', `:end' and
  3671. `:post-blank' keywords. Otherwise, return nil.
  3672. Assume point is at the first equal sign marker."
  3673. (org-element--parse-generic-emphasis "=" 'verbatim))
  3674. (defun org-element-verbatim-interpreter (verbatim _)
  3675. "Interpret VERBATIM object as Org syntax."
  3676. (format "=%s=" (org-element-property :value verbatim)))
  3677. ;;; Parsing Element Starting At Point
  3678. ;;
  3679. ;; `org-element--current-element' is the core function of this section.
  3680. ;; It returns the Lisp representation of the element starting at
  3681. ;; point.
  3682. (defvar org-element--cache-sync-requests); Declared later
  3683. (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
  3684. "Parse the element starting at point.
  3685. Return value is a list like (TYPE PROPS) where TYPE is the type
  3686. of the element and PROPS a plist of properties associated to the
  3687. element.
  3688. Possible types are defined in `org-element-all-elements'.
  3689. LIMIT bounds the search.
  3690. Optional argument GRANULARITY determines the depth of the
  3691. recursion. Allowed values are `headline', `greater-element',
  3692. `element', `object' or nil. When it is broader than `object' (or
  3693. nil), secondary values will not be parsed, since they only
  3694. contain objects.
  3695. Optional argument MODE, when non-nil, can be either
  3696. `first-section', `item', `node-property', `planning',
  3697. `property-drawer', `section', `table-row', or `top-comment'.
  3698. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3699. computed.
  3700. Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
  3701. will also add current element to cache if it is not yet there. Use
  3702. this argument with care, as validity of the element in parse tree is
  3703. not checked.
  3704. This function assumes point is always at the beginning of the
  3705. element it has to parse."
  3706. (let* ((element (and (not (buffer-narrowed-p))
  3707. (org-element--cache-active-p)
  3708. (not org-element--cache-sync-requests)
  3709. (org-element--cache-find (point) t)))
  3710. (element (progn (while (and element
  3711. (not (and (eq (point) (org-element-property :begin element))
  3712. (eq mode (org-element-property :mode element)))))
  3713. (setq element (org-element-property :parent element)))
  3714. element))
  3715. (old-element element)
  3716. (element (when
  3717. (pcase (org-element-property :granularity element)
  3718. (`nil t)
  3719. (`object t)
  3720. (`element (not (memq granularity '(nil object))))
  3721. (`greater-element (not (memq granularity '(nil object element))))
  3722. (`headline (eq granularity 'headline)))
  3723. element)))
  3724. (if element
  3725. element
  3726. (save-excursion
  3727. (let ((case-fold-search t)
  3728. ;; Determine if parsing depth allows for secondary strings
  3729. ;; parsing. It only applies to elements referenced in
  3730. ;; `org-element-secondary-value-alist'.
  3731. (raw-secondary-p (and granularity (not (eq granularity 'object))))
  3732. result)
  3733. (setq
  3734. result
  3735. (cond
  3736. ;; Item.
  3737. ((eq mode 'item)
  3738. (org-element-item-parser limit structure raw-secondary-p))
  3739. ;; Table Row.
  3740. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3741. ;; Node Property.
  3742. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3743. ;; Headline.
  3744. ((org-with-limited-levels (looking-at-p org-outline-regexp-bol))
  3745. (org-element-headline-parser limit raw-secondary-p))
  3746. ;; Sections (must be checked after headline).
  3747. ((eq mode 'section) (org-element-section-parser limit))
  3748. ((eq mode 'first-section)
  3749. (org-element-section-parser
  3750. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3751. limit)))
  3752. ;; Comments.
  3753. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3754. (org-element-comment-parser limit))
  3755. ;; Planning.
  3756. ((and (eq mode 'planning)
  3757. (eq ?* (char-after (line-beginning-position 0)))
  3758. (looking-at org-element-planning-line-re))
  3759. (org-element-planning-parser limit))
  3760. ;; Property drawer.
  3761. ((and (pcase mode
  3762. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3763. ((or `property-drawer `top-comment)
  3764. (save-excursion
  3765. (beginning-of-line 0)
  3766. (not (looking-at "[[:blank:]]*$"))))
  3767. (_ nil))
  3768. (looking-at org-property-drawer-re))
  3769. (org-element-property-drawer-parser limit))
  3770. ;; When not at bol, point is at the beginning of an item or
  3771. ;; a footnote definition: next item is always a paragraph.
  3772. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3773. ;; Clock.
  3774. ((looking-at org-element-clock-line-re)
  3775. (org-element-clock-parser limit))
  3776. ;; Inlinetask.
  3777. ((looking-at "^\\*+ ")
  3778. (org-element-inlinetask-parser limit raw-secondary-p))
  3779. ;; From there, elements can have affiliated keywords.
  3780. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3781. limit (memq granularity '(nil object)))))
  3782. (cond
  3783. ;; Jumping over affiliated keywords put point off-limits.
  3784. ;; Parse them as regular keywords.
  3785. ((and (cdr affiliated) (>= (point) limit))
  3786. (goto-char (car affiliated))
  3787. (org-element-keyword-parser limit nil))
  3788. ;; LaTeX Environment.
  3789. ((looking-at org-element--latex-begin-environment)
  3790. (org-element-latex-environment-parser limit affiliated))
  3791. ;; Drawer.
  3792. ((looking-at org-element-drawer-re)
  3793. (org-element-drawer-parser limit affiliated))
  3794. ;; Fixed Width
  3795. ((looking-at "[ \t]*:\\( \\|$\\)")
  3796. (org-element-fixed-width-parser limit affiliated))
  3797. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3798. ;; Keywords.
  3799. ((looking-at "[ \t]*#\\+")
  3800. (goto-char (match-end 0))
  3801. (cond
  3802. ((looking-at "BEGIN_\\(\\S-+\\)")
  3803. (beginning-of-line)
  3804. (funcall (pcase (upcase (match-string 1))
  3805. ("CENTER" #'org-element-center-block-parser)
  3806. ("COMMENT" #'org-element-comment-block-parser)
  3807. ("EXAMPLE" #'org-element-example-block-parser)
  3808. ("EXPORT" #'org-element-export-block-parser)
  3809. ("QUOTE" #'org-element-quote-block-parser)
  3810. ("SRC" #'org-element-src-block-parser)
  3811. ("VERSE" #'org-element-verse-block-parser)
  3812. (_ #'org-element-special-block-parser))
  3813. limit
  3814. affiliated))
  3815. ((looking-at "CALL:")
  3816. (beginning-of-line)
  3817. (org-element-babel-call-parser limit affiliated))
  3818. ((save-excursion
  3819. (beginning-of-line)
  3820. (looking-at org-element-dynamic-block-open-re))
  3821. (beginning-of-line)
  3822. (org-element-dynamic-block-parser limit affiliated))
  3823. ((looking-at "\\S-+:")
  3824. (beginning-of-line)
  3825. (org-element-keyword-parser limit affiliated))
  3826. (t
  3827. (beginning-of-line)
  3828. (org-element-paragraph-parser limit affiliated))))
  3829. ;; Footnote Definition.
  3830. ((looking-at org-footnote-definition-re)
  3831. (org-element-footnote-definition-parser limit affiliated))
  3832. ;; Horizontal Rule.
  3833. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3834. (org-element-horizontal-rule-parser limit affiliated))
  3835. ;; Diary Sexp.
  3836. ((looking-at "%%(")
  3837. (org-element-diary-sexp-parser limit affiliated))
  3838. ;; Table.
  3839. ((or (looking-at "[ \t]*|")
  3840. ;; There is no strict definition of a table.el
  3841. ;; table. Try to prevent false positive while being
  3842. ;; quick.
  3843. (let ((rule-regexp
  3844. (rx (zero-or-more (any " \t"))
  3845. "+"
  3846. (one-or-more (one-or-more "-") "+")
  3847. (zero-or-more (any " \t"))
  3848. eol))
  3849. (non-table.el-line
  3850. (rx bol
  3851. (zero-or-more (any " \t"))
  3852. (or eol (not (any "+| \t")))))
  3853. (next (line-beginning-position 2)))
  3854. ;; Start with a full rule.
  3855. (and
  3856. (looking-at rule-regexp)
  3857. (< next limit) ;no room for a table.el table
  3858. (save-excursion
  3859. (end-of-line)
  3860. (cond
  3861. ;; Must end with a full rule.
  3862. ((not (re-search-forward non-table.el-line limit 'move))
  3863. (if (bolp) (forward-line -1) (beginning-of-line))
  3864. (looking-at rule-regexp))
  3865. ;; Ignore pseudo-tables with a single
  3866. ;; rule.
  3867. ((= next (line-beginning-position))
  3868. nil)
  3869. ;; Must end with a full rule.
  3870. (t
  3871. (forward-line -1)
  3872. (looking-at rule-regexp)))))))
  3873. (org-element-table-parser limit affiliated))
  3874. ;; List.
  3875. ((looking-at (org-item-re))
  3876. (org-element-plain-list-parser
  3877. limit affiliated
  3878. (or structure (org-element--list-struct limit))))
  3879. ;; Default element: Paragraph.
  3880. (t (org-element-paragraph-parser limit affiliated)))))))
  3881. (when result
  3882. (org-element-put-property result :mode mode)
  3883. (org-element-put-property result :granularity granularity))
  3884. (when (and (not (buffer-narrowed-p))
  3885. (org-element--cache-active-p)
  3886. (not org-element--cache-sync-requests)
  3887. add-to-cache)
  3888. (if (not old-element)
  3889. (setq result (org-element--cache-put result))
  3890. (org-element-set-element old-element result)
  3891. (setq result old-element)))
  3892. result)))))
  3893. ;; Most elements can have affiliated keywords. When looking for an
  3894. ;; element beginning, we want to move before them, as they belong to
  3895. ;; that element, and, in the meantime, collect information they give
  3896. ;; into appropriate properties. Hence the following function.
  3897. (defun org-element--collect-affiliated-keywords (limit parse)
  3898. "Collect affiliated keywords from point down to LIMIT.
  3899. Return a list whose CAR is the position at the first of them and
  3900. CDR a plist of keywords and values and move point to the
  3901. beginning of the first line after them.
  3902. As a special case, if element doesn't start at the beginning of
  3903. the line (e.g., a paragraph starting an item), CAR is current
  3904. position of point and CDR is nil.
  3905. When PARSE is non-nil, values from keywords belonging to
  3906. `org-element-parsed-keywords' are parsed as secondary strings."
  3907. (if (not (bolp)) (list (point))
  3908. (let ((case-fold-search t)
  3909. (origin (point))
  3910. ;; RESTRICT is the list of objects allowed in parsed
  3911. ;; keywords value. If PARSE is nil, no object is allowed.
  3912. (restrict (and parse (org-element-restriction 'keyword)))
  3913. output)
  3914. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3915. (let* ((raw-kwd (upcase (match-string 1)))
  3916. ;; Apply translation to RAW-KWD. From there, KWD is
  3917. ;; the official keyword.
  3918. (kwd (or (cdr (assoc raw-kwd
  3919. org-element-keyword-translation-alist))
  3920. raw-kwd))
  3921. ;; PARSED? is non-nil when keyword should have its
  3922. ;; value parsed.
  3923. (parsed? (member kwd org-element-parsed-keywords))
  3924. ;; Find main value for any keyword.
  3925. (value
  3926. (let ((beg (match-end 0))
  3927. (end (save-excursion
  3928. (end-of-line)
  3929. (skip-chars-backward " \t")
  3930. (point))))
  3931. (if parsed?
  3932. (save-match-data
  3933. (org-element--parse-objects beg end nil restrict))
  3934. (org-trim (buffer-substring-no-properties beg end)))))
  3935. ;; If KWD is a dual keyword, find its secondary value.
  3936. ;; Maybe parse it.
  3937. (dual? (member kwd org-element-dual-keywords))
  3938. (dual-value
  3939. (and dual?
  3940. (let ((sec (match-string-no-properties 2)))
  3941. (cond
  3942. ((and sec parsed?)
  3943. (save-match-data
  3944. (org-element--parse-objects
  3945. (match-beginning 2) (match-end 2) nil restrict)))
  3946. (sec sec)))))
  3947. ;; Attribute a property name to KWD.
  3948. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3949. ;; Now set final shape for VALUE.
  3950. (when dual?
  3951. (setq value (and (or value dual-value) (cons value dual-value))))
  3952. (when (or (member kwd org-element-multiple-keywords)
  3953. ;; Attributes can always appear on multiple lines.
  3954. (string-match "^ATTR_" kwd))
  3955. (setq value (cons value (plist-get output kwd-sym))))
  3956. ;; Eventually store the new value in OUTPUT.
  3957. (setq output (plist-put output kwd-sym value))
  3958. ;; Move to next keyword.
  3959. (forward-line)))
  3960. ;; If affiliated keywords are orphaned: move back to first one.
  3961. ;; They will be parsed as a paragraph.
  3962. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3963. ;; Return value.
  3964. (cons origin output))))
  3965. ;;; The Org Parser
  3966. ;;
  3967. ;; The two major functions here are `org-element-parse-buffer', which
  3968. ;; parses Org syntax inside the current buffer, taking into account
  3969. ;; region, narrowing, or even visibility if specified, and
  3970. ;; `org-element-parse-secondary-string', which parses objects within
  3971. ;; a given string.
  3972. ;;
  3973. ;; The (almost) almighty `org-element-map' allows applying a function
  3974. ;; on elements or objects matching some type, and accumulating the
  3975. ;; resulting values. In an export situation, it also skips unneeded
  3976. ;; parts of the parse tree.
  3977. (defun org-element-parse-buffer (&optional granularity visible-only)
  3978. "Recursively parse the buffer and return structure.
  3979. If narrowing is in effect, only parse the visible part of the
  3980. buffer.
  3981. Optional argument GRANULARITY determines the depth of the
  3982. recursion. It can be set to the following symbols:
  3983. `headline' Only parse headlines.
  3984. `greater-element' Don't recurse into greater elements except
  3985. headlines and sections. Thus, elements
  3986. parsed are the top-level ones.
  3987. `element' Parse everything but objects and plain text.
  3988. `object' Parse the complete buffer (default).
  3989. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3990. elements.
  3991. An element or object is represented as a list with the
  3992. pattern (TYPE PROPERTIES CONTENTS), where :
  3993. TYPE is a symbol describing the element or object. See
  3994. `org-element-all-elements' and `org-element-all-objects' for an
  3995. exhaustive list of such symbols. One can retrieve it with
  3996. `org-element-type' function.
  3997. PROPERTIES is the list of attributes attached to the element or
  3998. object, as a plist. Although most of them are specific to the
  3999. element or object type, all types share `:begin', `:end',
  4000. `:post-blank' and `:parent' properties, which respectively
  4001. refer to buffer position where the element or object starts,
  4002. ends, the number of white spaces or blank lines after it, and
  4003. the element or object containing it. Properties values can be
  4004. obtained by using `org-element-property' function.
  4005. CONTENTS is a list of elements, objects or raw strings
  4006. contained in the current element or object, when applicable.
  4007. One can access them with `org-element-contents' function.
  4008. The Org buffer has `org-data' as type and nil as properties.
  4009. `org-element-map' function can be used to find specific elements
  4010. or objects within the parse tree.
  4011. This function assumes that current major mode is `org-mode'."
  4012. (save-excursion
  4013. (goto-char (point-min))
  4014. (let ((org-data (org-element-org-data-parser))
  4015. (gc-cons-threshold #x40000000))
  4016. (org-skip-whitespace)
  4017. (org-element--parse-elements
  4018. (point-at-bol) (point-max)
  4019. ;; Start in `first-section' mode so text before the first
  4020. ;; headline belongs to a section.
  4021. 'first-section nil granularity visible-only org-data))))
  4022. (defun org-element-parse-secondary-string (string restriction &optional parent)
  4023. "Recursively parse objects in STRING and return structure.
  4024. RESTRICTION is a symbol limiting the object types that will be
  4025. looked after.
  4026. Optional argument PARENT, when non-nil, is the element or object
  4027. containing the secondary string. It is used to set correctly
  4028. `:parent' property within the string.
  4029. If STRING is the empty string or nil, return nil."
  4030. (cond
  4031. ((not string) nil)
  4032. ((equal string "") nil)
  4033. (t (let ((local-variables (buffer-local-variables)))
  4034. (with-temp-buffer
  4035. (dolist (v local-variables)
  4036. (ignore-errors
  4037. (if (symbolp v) (makunbound v)
  4038. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  4039. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  4040. (set (make-local-variable (car v)) (cdr v))))))
  4041. ;; Transferring local variables may put the temporary buffer
  4042. ;; into a read-only state. Make sure we can insert STRING.
  4043. (let ((inhibit-read-only t)) (insert string))
  4044. ;; Prevent "Buffer *temp* modified; kill anyway?".
  4045. (restore-buffer-modified-p nil)
  4046. (org-element--parse-objects
  4047. (point-min) (point-max) nil restriction parent))))))
  4048. (defun org-element-map
  4049. (data types fun &optional info first-match no-recursion with-affiliated)
  4050. "Map a function on selected elements or objects.
  4051. DATA is a parse tree (for example, returned by
  4052. `org-element-parse-buffer'), an element, an object, a string, or a
  4053. list of such constructs. TYPES is a symbol or list of symbols of
  4054. elements or object types (see `org-element-all-elements' and
  4055. `org-element-all-objects' for a complete list of types). FUN is the
  4056. function called on the matching element or object. It has to accept
  4057. one argument: the element or object itself.
  4058. When optional argument INFO is non-nil, it should be a plist
  4059. holding export options. In that case, parts of the parse tree
  4060. not exportable according to that property list will be skipped.
  4061. When optional argument FIRST-MATCH is non-nil, stop at the first
  4062. match for which FUN doesn't return nil, and return that value.
  4063. Optional argument NO-RECURSION is a symbol or a list of symbols
  4064. representing elements or objects types. `org-element-map' won't
  4065. enter any recursive element or object whose type belongs to that
  4066. list. Though, FUN can still be applied on them.
  4067. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  4068. apply to matching objects within parsed affiliated keywords (see
  4069. `org-element-parsed-keywords').
  4070. Nil values returned from FUN do not appear in the results.
  4071. Examples:
  4072. ---------
  4073. Assuming TREE is a variable containing an Org buffer parse tree,
  4074. the following example will return a flat list of all `src-block'
  4075. and `example-block' elements in it:
  4076. (setq tree (org-element-parse-buffer))
  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. (--ignore-list (plist-get info :ignore-list))
  4118. --acc)
  4119. (letrec ((--walk-tree
  4120. (lambda (--data)
  4121. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  4122. ;; holding contextual information.
  4123. (let ((--type (org-element-type --data)))
  4124. (cond
  4125. ((not --data))
  4126. ;; Ignored element in an export context.
  4127. ((and info (memq --data --ignore-list)))
  4128. ;; List of elements or objects.
  4129. ((not --type) (mapc --walk-tree --data))
  4130. ;; Unconditionally enter parse trees.
  4131. ((eq --type 'org-data)
  4132. (mapc --walk-tree (org-element-contents --data)))
  4133. (t
  4134. ;; Check if TYPE is matching among TYPES. If so,
  4135. ;; apply FUN to --DATA and accumulate return value
  4136. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  4137. (when (memq --type types)
  4138. (let ((result (funcall fun --data)))
  4139. (cond ((not result))
  4140. (first-match (throw :--map-first-match result))
  4141. (t (push result --acc)))))
  4142. ;; If --DATA has a secondary string that can contain
  4143. ;; objects with their type among TYPES, look inside.
  4144. (when (and (eq --category 'objects) (not (stringp --data)))
  4145. (dolist (p (cdr (assq --type
  4146. org-element-secondary-value-alist)))
  4147. (funcall --walk-tree (org-element-property p --data))))
  4148. ;; If --DATA has any parsed affiliated keywords and
  4149. ;; WITH-AFFILIATED is non-nil, look for objects in
  4150. ;; them.
  4151. (when (and with-affiliated
  4152. (eq --category 'objects)
  4153. (eq (org-element-class --data) 'element))
  4154. (dolist (kwd-pair org-element--parsed-properties-alist)
  4155. (let ((kwd (car kwd-pair))
  4156. (value (org-element-property (cdr kwd-pair) --data)))
  4157. ;; Pay attention to the type of parsed
  4158. ;; keyword. In particular, preserve order for
  4159. ;; multiple keywords.
  4160. (cond
  4161. ((not value))
  4162. ((member kwd org-element-dual-keywords)
  4163. (if (member kwd org-element-multiple-keywords)
  4164. (dolist (line (reverse value))
  4165. (funcall --walk-tree (cdr line))
  4166. (funcall --walk-tree (car line)))
  4167. (funcall --walk-tree (cdr value))
  4168. (funcall --walk-tree (car value))))
  4169. ((member kwd org-element-multiple-keywords)
  4170. (mapc --walk-tree (reverse value)))
  4171. (t (funcall --walk-tree value))))))
  4172. ;; Determine if a recursion into --DATA is possible.
  4173. (cond
  4174. ;; --TYPE is explicitly removed from recursion.
  4175. ((memq --type no-recursion))
  4176. ;; --DATA has no contents.
  4177. ((not (org-element-contents --data)))
  4178. ;; Looking for greater elements but --DATA is
  4179. ;; simply an element or an object.
  4180. ((and (eq --category 'greater-elements)
  4181. (not (memq --type org-element-greater-elements))))
  4182. ;; Looking for elements but --DATA is an object.
  4183. ((and (eq --category 'elements)
  4184. (eq (org-element-class --data) 'object)))
  4185. ;; In any other case, map contents.
  4186. (t (mapc --walk-tree (org-element-contents --data))))))))))
  4187. (catch :--map-first-match
  4188. (funcall --walk-tree data)
  4189. ;; Return value in a proper order.
  4190. (nreverse --acc)))))
  4191. ;; The following functions are internal parts of the parser.
  4192. ;;
  4193. ;; The first one, `org-element--parse-elements' acts at the element's
  4194. ;; level.
  4195. ;;
  4196. ;; The second one, `org-element--parse-objects' applies on all objects
  4197. ;; of a paragraph or a secondary string. It calls
  4198. ;; `org-element--object-lex' to find the next object in the current
  4199. ;; container.
  4200. (defsubst org-element--next-mode (mode type parent?)
  4201. "Return next mode according to current one.
  4202. MODE is a symbol representing the expectation about the next
  4203. element or object. Meaningful values are `first-section',
  4204. `item', `node-property', `planning', `property-drawer',
  4205. `section', `table-row', `top-comment', and nil.
  4206. TYPE is the type of the current element or object.
  4207. If PARENT? is non-nil, assume the next element or object will be
  4208. located inside the current one."
  4209. (if parent?
  4210. (pcase type
  4211. (`headline 'section)
  4212. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4213. ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
  4214. ((and (guard (not mode)) `org-data) 'first-section)
  4215. (`inlinetask 'planning)
  4216. (`plain-list 'item)
  4217. (`property-drawer 'node-property)
  4218. (`section 'planning)
  4219. (`table 'table-row))
  4220. (pcase mode
  4221. (`item 'item)
  4222. (`node-property 'node-property)
  4223. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4224. (`table-row 'table-row)
  4225. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4226. (defun org-element--parse-elements
  4227. (beg end mode structure granularity visible-only acc)
  4228. "Parse elements between BEG and END positions.
  4229. MODE prioritizes some elements over the others. It can be set to
  4230. `first-section', `item', `node-property', `planning',
  4231. `property-drawer', `section', `table-row', `top-comment', or nil.
  4232. When value is `item', STRUCTURE will be used as the current list
  4233. structure.
  4234. GRANULARITY determines the depth of the recursion. See
  4235. `org-element-parse-buffer' for more information.
  4236. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4237. elements.
  4238. Elements are accumulated into ACC."
  4239. (save-excursion
  4240. (goto-char beg)
  4241. ;; When parsing only headlines, skip any text before first one.
  4242. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4243. (org-with-limited-levels (outline-next-heading)))
  4244. (let (elements)
  4245. (while (< (point) end)
  4246. ;; Visible only: skip invisible parts due to folding.
  4247. (if (and visible-only (org-invisible-p nil t))
  4248. (progn
  4249. (goto-char (org-find-visible))
  4250. (when (and (eolp) (not (eobp))) (forward-char)))
  4251. ;; Find current element's type and parse it accordingly to
  4252. ;; its category.
  4253. (let* ((element (org-element-copy
  4254. ;; `org-element--current-element' may return cached
  4255. ;; elements. Below code reassigns
  4256. ;; `:parent' property of the element and
  4257. ;; may interfere with cache
  4258. ;; synchronisation if parent element is not
  4259. ;; yet in cache. Moreover, the returned
  4260. ;; structure may be altered by caller code
  4261. ;; arbitrarily. Hence, we return a copy of
  4262. ;; the potentially cached element to make
  4263. ;; potential modifications safe for element
  4264. ;; cache.
  4265. (org-element--current-element
  4266. end granularity mode structure)))
  4267. (type (org-element-type element))
  4268. (cbeg (org-element-property :contents-begin element)))
  4269. (goto-char (org-element-property :end element))
  4270. ;; Fill ELEMENT contents by side-effect.
  4271. (cond
  4272. ;; If element has no contents, don't modify it.
  4273. ((not cbeg))
  4274. ;; Greater element: parse it between `contents-begin' and
  4275. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4276. ;; or ELEMENT is a headline, in which case going inside
  4277. ;; is mandatory, in order to get sub-level headings.
  4278. ((and (memq type org-element-greater-elements)
  4279. (or (memq granularity '(element object nil))
  4280. (and (eq granularity 'greater-element)
  4281. (eq type 'section))
  4282. (eq type 'headline)))
  4283. (org-element--parse-elements
  4284. cbeg (org-element-property :contents-end element)
  4285. ;; Possibly switch to a special mode.
  4286. (org-element--next-mode mode type t)
  4287. (and (memq type '(item plain-list))
  4288. (org-element-property :structure element))
  4289. granularity visible-only element))
  4290. ;; ELEMENT has contents. Parse objects inside, if
  4291. ;; GRANULARITY allows it.
  4292. ((memq granularity '(object nil))
  4293. (org-element--parse-objects
  4294. cbeg (org-element-property :contents-end element) element
  4295. (org-element-restriction type))))
  4296. (push (org-element-put-property element :parent acc) elements)
  4297. ;; Update mode.
  4298. (setq mode (org-element--next-mode mode type nil)))))
  4299. ;; Return result.
  4300. (org-element-put-property acc :granularity granularity)
  4301. (apply #'org-element-set-contents acc (nreverse elements)))))
  4302. (defun org-element--object-lex (restriction)
  4303. "Return next object in current buffer or nil.
  4304. RESTRICTION is a list of object types, as symbols, that should be
  4305. looked after. This function assumes that the buffer is narrowed
  4306. to an appropriate container (e.g., a paragraph)."
  4307. (cond
  4308. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4309. ((memq 'citation-reference restriction)
  4310. (org-element-citation-reference-parser))
  4311. (t
  4312. (let* ((start (point))
  4313. (limit
  4314. ;; Object regexp sometimes needs to have a peek at
  4315. ;; a character ahead. Therefore, when there is a hard
  4316. ;; limit, make it one more than the true beginning of the
  4317. ;; radio target.
  4318. (save-excursion
  4319. (cond ((not org-target-link-regexp) nil)
  4320. ((not (memq 'link restriction)) nil)
  4321. ((progn
  4322. (unless (bolp) (forward-char -1))
  4323. (not (re-search-forward org-target-link-regexp nil t)))
  4324. nil)
  4325. ;; Since we moved backward, we do not want to
  4326. ;; match again an hypothetical 1-character long
  4327. ;; radio link before us. Realizing that this can
  4328. ;; only happen if such a radio link starts at
  4329. ;; beginning of line, we prevent this here.
  4330. ((and (= start (1+ (line-beginning-position)))
  4331. (= start (match-end 1)))
  4332. (and (re-search-forward org-target-link-regexp nil t)
  4333. (1+ (match-beginning 1))))
  4334. (t (1+ (match-beginning 1))))))
  4335. found)
  4336. (save-excursion
  4337. (while (and (not found)
  4338. (re-search-forward org-element--object-regexp limit 'move))
  4339. (goto-char (match-beginning 0))
  4340. (let ((result (match-string 0)))
  4341. (setq found
  4342. (cond
  4343. ((string-prefix-p "call_" result t)
  4344. (and (memq 'inline-babel-call restriction)
  4345. (org-element-inline-babel-call-parser)))
  4346. ((string-prefix-p "src_" result t)
  4347. (and (memq 'inline-src-block restriction)
  4348. (org-element-inline-src-block-parser)))
  4349. (t
  4350. (pcase (char-after)
  4351. (?^ (and (memq 'superscript restriction)
  4352. (org-element-superscript-parser)))
  4353. (?_ (or (and (memq 'subscript restriction)
  4354. (org-element-subscript-parser))
  4355. (and (memq 'underline restriction)
  4356. (org-element-underline-parser))))
  4357. (?* (and (memq 'bold restriction)
  4358. (org-element-bold-parser)))
  4359. (?/ (and (memq 'italic restriction)
  4360. (org-element-italic-parser)))
  4361. (?~ (and (memq 'code restriction)
  4362. (org-element-code-parser)))
  4363. (?= (and (memq 'verbatim restriction)
  4364. (org-element-verbatim-parser)))
  4365. (?+ (and (memq 'strike-through restriction)
  4366. (org-element-strike-through-parser)))
  4367. (?@ (and (memq 'export-snippet restriction)
  4368. (org-element-export-snippet-parser)))
  4369. (?{ (and (memq 'macro restriction)
  4370. (org-element-macro-parser)))
  4371. (?$ (and (memq 'latex-fragment restriction)
  4372. (org-element-latex-fragment-parser)))
  4373. (?<
  4374. (if (eq (aref result 1) ?<)
  4375. (or (and (memq 'radio-target restriction)
  4376. (org-element-radio-target-parser))
  4377. (and (memq 'target restriction)
  4378. (org-element-target-parser)))
  4379. (or (and (memq 'timestamp restriction)
  4380. (org-element-timestamp-parser))
  4381. (and (memq 'link restriction)
  4382. (org-element-link-parser)))))
  4383. (?\\
  4384. (if (eq (aref result 1) ?\\)
  4385. (and (memq 'line-break restriction)
  4386. (org-element-line-break-parser))
  4387. (or (and (memq 'entity restriction)
  4388. (org-element-entity-parser))
  4389. (and (memq 'latex-fragment restriction)
  4390. (org-element-latex-fragment-parser)))))
  4391. (?\[
  4392. (pcase (aref result 1)
  4393. ((and ?\[
  4394. (guard (memq 'link restriction)))
  4395. (org-element-link-parser))
  4396. ((and ?f
  4397. (guard (memq 'footnote-reference restriction)))
  4398. (org-element-footnote-reference-parser))
  4399. ((and ?c
  4400. (guard (memq 'citation restriction)))
  4401. (org-element-citation-parser))
  4402. ((and (or ?% ?/)
  4403. (guard (memq 'statistics-cookie restriction)))
  4404. (org-element-statistics-cookie-parser))
  4405. (_
  4406. (or (and (memq 'timestamp restriction)
  4407. (org-element-timestamp-parser))
  4408. (and (memq 'statistics-cookie restriction)
  4409. (org-element-statistics-cookie-parser))))))
  4410. ;; This is probably a plain link.
  4411. (_ (and (memq 'link restriction)
  4412. (org-element-link-parser)))))))
  4413. (or (eobp) (forward-char))))
  4414. (cond (found)
  4415. (limit (forward-char -1)
  4416. (org-element-link-parser)) ;radio link
  4417. (t nil)))))))
  4418. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4419. "Parse objects between BEG and END and return recursive structure.
  4420. Objects are accumulated in ACC. RESTRICTION is a list of object
  4421. successors which are allowed in the current object.
  4422. ACC becomes the parent for all parsed objects. However, if ACC
  4423. is nil (i.e., a secondary string is being parsed) and optional
  4424. argument PARENT is non-nil, use it as the parent for all objects.
  4425. Eventually, if both ACC and PARENT are nil, the common parent is
  4426. the list of objects itself."
  4427. (save-excursion
  4428. (save-restriction
  4429. (narrow-to-region beg end)
  4430. (goto-char (point-min))
  4431. (let (next-object contents)
  4432. (while (and (not (eobp))
  4433. (setq next-object (org-element--object-lex restriction)))
  4434. ;; Text before any object.
  4435. (let ((obj-beg (org-element-property :begin next-object)))
  4436. (unless (= (point) obj-beg)
  4437. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4438. (push (if acc (org-element-put-property text :parent acc) text)
  4439. contents))))
  4440. ;; Object...
  4441. (let ((obj-end (org-element-property :end next-object))
  4442. (cont-beg (org-element-property :contents-begin next-object)))
  4443. (when acc (org-element-put-property next-object :parent acc))
  4444. (push (if cont-beg
  4445. ;; Fill contents of NEXT-OBJECT if possible.
  4446. (org-element--parse-objects
  4447. cont-beg
  4448. (org-element-property :contents-end next-object)
  4449. next-object
  4450. (org-element-restriction next-object))
  4451. next-object)
  4452. contents)
  4453. (goto-char obj-end)))
  4454. ;; Text after last object.
  4455. (unless (eobp)
  4456. (let ((text (buffer-substring-no-properties (point) end)))
  4457. (push (if acc (org-element-put-property text :parent acc) text)
  4458. contents)))
  4459. ;; Result. Set appropriate parent.
  4460. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4461. (let* ((contents (nreverse contents))
  4462. (parent (or parent contents)))
  4463. (dolist (datum contents contents)
  4464. (org-element-put-property datum :parent parent))))))))
  4465. ;;; Towards A Bijective Process
  4466. ;;
  4467. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4468. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4469. ;; interpreted and expanded into a string with canonical Org syntax.
  4470. ;; Hence `org-element-interpret-data'.
  4471. ;;
  4472. ;; The function relies internally on
  4473. ;; `org-element--interpret-affiliated-keywords'.
  4474. ;;;###autoload
  4475. (defun org-element-interpret-data (data)
  4476. "Interpret DATA as Org syntax.
  4477. DATA is a parse tree, an element, an object or a secondary string
  4478. to interpret. Return Org syntax as a string."
  4479. (letrec ((fun
  4480. (lambda (data parent)
  4481. (let* ((type (org-element-type data))
  4482. ;; Find interpreter for current object or
  4483. ;; element. If it doesn't exist (e.g. this is
  4484. ;; a pseudo object or element), return contents,
  4485. ;; if any.
  4486. (interpret
  4487. (let ((fun (intern
  4488. (format "org-element-%s-interpreter" type))))
  4489. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4490. (results
  4491. (cond
  4492. ;; Secondary string.
  4493. ((not type)
  4494. (mapconcat (lambda (obj) (funcall fun obj parent))
  4495. data
  4496. ""))
  4497. ;; Full Org document.
  4498. ((eq type 'org-data)
  4499. (mapconcat (lambda (obj) (funcall fun obj parent))
  4500. (org-element-contents data)
  4501. ""))
  4502. ;; Plain text: return it.
  4503. ((stringp data) data)
  4504. ;; Element or object without contents.
  4505. ((not (org-element-contents data))
  4506. (funcall interpret data nil))
  4507. ;; Element or object with contents.
  4508. (t
  4509. (funcall
  4510. interpret
  4511. data
  4512. ;; Recursively interpret contents.
  4513. (mapconcat
  4514. (lambda (datum) (funcall fun datum data))
  4515. (org-element-contents
  4516. (if (not (memq type '(paragraph verse-block)))
  4517. data
  4518. ;; Fix indentation of elements containing
  4519. ;; objects. We ignore `table-row'
  4520. ;; elements as they are one line long
  4521. ;; anyway.
  4522. (org-element-normalize-contents
  4523. data
  4524. ;; When normalizing first paragraph of
  4525. ;; an item or a footnote-definition,
  4526. ;; ignore first line's indentation.
  4527. (and (eq type 'paragraph)
  4528. (memq (org-element-type parent)
  4529. '(footnote-definition item))
  4530. (eq data (car (org-element-contents parent)))
  4531. (eq (org-element-property :pre-blank parent)
  4532. 0)))))
  4533. ""))))))
  4534. (if (memq type '(org-data nil)) results
  4535. ;; Build white spaces. If no `:post-blank' property
  4536. ;; is specified, assume its value is 0.
  4537. (let ((blank (or (org-element-property :post-blank data) 0)))
  4538. (if (eq (org-element-class data parent) 'object)
  4539. (concat results (make-string blank ?\s))
  4540. (concat (org-element--interpret-affiliated-keywords data)
  4541. (org-element-normalize-string results)
  4542. (make-string blank ?\n)))))))))
  4543. (funcall fun data nil)))
  4544. (defun org-element--interpret-affiliated-keywords (element)
  4545. "Return ELEMENT's affiliated keywords as Org syntax.
  4546. If there is no affiliated keyword, return the empty string."
  4547. (let ((keyword-to-org
  4548. (lambda (key value)
  4549. (let (dual)
  4550. (when (member key org-element-dual-keywords)
  4551. (setq dual (cdr value) value (car value)))
  4552. (concat "#+" (downcase key)
  4553. (and dual
  4554. (format "[%s]" (org-element-interpret-data dual)))
  4555. ": "
  4556. (if (member key org-element-parsed-keywords)
  4557. (org-element-interpret-data value)
  4558. value)
  4559. "\n")))))
  4560. (mapconcat
  4561. (lambda (prop)
  4562. (let ((value (org-element-property prop element))
  4563. (keyword (upcase (substring (symbol-name prop) 1))))
  4564. (when value
  4565. (if (or (member keyword org-element-multiple-keywords)
  4566. ;; All attribute keywords can have multiple lines.
  4567. (string-match "^ATTR_" keyword))
  4568. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4569. (reverse value)
  4570. "")
  4571. (funcall keyword-to-org keyword value)))))
  4572. ;; List all ELEMENT's properties matching an attribute line or an
  4573. ;; affiliated keyword, but ignore translated keywords since they
  4574. ;; cannot belong to the property list.
  4575. (cl-loop for prop in (nth 1 element) by 'cddr
  4576. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4577. (or (string-match "^ATTR_" keyword)
  4578. (and
  4579. (member keyword org-element-affiliated-keywords)
  4580. (not (assoc keyword
  4581. org-element-keyword-translation-alist)))))
  4582. collect prop)
  4583. "")))
  4584. ;; Because interpretation of the parse tree must return the same
  4585. ;; number of blank lines between elements and the same number of white
  4586. ;; space after objects, some special care must be given to white
  4587. ;; spaces.
  4588. ;;
  4589. ;; The first function, `org-element-normalize-string', ensures any
  4590. ;; string different from the empty string will end with a single
  4591. ;; newline character.
  4592. ;;
  4593. ;; The second function, `org-element-normalize-contents', removes
  4594. ;; global indentation from the contents of the current element.
  4595. (defun org-element-normalize-string (s)
  4596. "Ensure string S ends with a single newline character.
  4597. If S isn't a string return it unchanged. If S is the empty
  4598. string, return it. Otherwise, return a new string with a single
  4599. newline character at its end."
  4600. (cond
  4601. ((not (stringp s)) s)
  4602. ((string= "" s) "")
  4603. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4604. (replace-match "\n" nil nil s)))))
  4605. (defun org-element-normalize-contents (element &optional ignore-first)
  4606. "Normalize plain text in ELEMENT's contents.
  4607. ELEMENT must only contain plain text and objects.
  4608. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4609. indentation to compute maximal common indentation.
  4610. Return the normalized element that is element with global
  4611. indentation removed from its contents."
  4612. (letrec ((find-min-ind
  4613. ;; Return minimal common indentation within BLOB. This is
  4614. ;; done by walking recursively BLOB and updating MIN-IND
  4615. ;; along the way. FIRST-FLAG is non-nil when the next
  4616. ;; object is expected to be a string that doesn't start
  4617. ;; with a newline character. It happens for strings at
  4618. ;; the beginnings of the contents or right after a line
  4619. ;; break.
  4620. (lambda (blob first-flag min-ind)
  4621. (dolist (datum (org-element-contents blob) min-ind)
  4622. (when first-flag
  4623. (setq first-flag nil)
  4624. (cond
  4625. ;; Objects cannot start with spaces: in this
  4626. ;; case, indentation is 0.
  4627. ((not (stringp datum)) (throw :zero 0))
  4628. ((not (string-match
  4629. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4630. (throw :zero 0))
  4631. ((equal (match-string 2 datum) "\n")
  4632. (put-text-property
  4633. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4634. (t
  4635. (let ((i (string-width (match-string 1 datum))))
  4636. (put-text-property
  4637. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4638. (setq min-ind (min i min-ind))))))
  4639. (cond
  4640. ((stringp datum)
  4641. (let ((s 0))
  4642. (while (string-match
  4643. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4644. (setq s (match-end 1))
  4645. (cond
  4646. ((equal (match-string 1 datum) "")
  4647. (unless (member (match-string 2 datum) '("" "\n"))
  4648. (throw :zero 0)))
  4649. ((equal (match-string 2 datum) "\n")
  4650. (put-text-property (match-beginning 1) (match-end 1)
  4651. 'org-ind 'empty datum))
  4652. (t
  4653. (let ((i (string-width (match-string 1 datum))))
  4654. (put-text-property (match-beginning 1) (match-end 1)
  4655. 'org-ind i datum)
  4656. (setq min-ind (min i min-ind))))))))
  4657. ((eq (org-element-type datum) 'line-break)
  4658. (setq first-flag t))
  4659. ((memq (org-element-type datum) org-element-recursive-objects)
  4660. (setq min-ind
  4661. (funcall find-min-ind datum first-flag min-ind)))))))
  4662. (min-ind
  4663. (catch :zero
  4664. (funcall find-min-ind
  4665. element (not ignore-first) most-positive-fixnum))))
  4666. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4667. ;; Build ELEMENT back, replacing each string with the same
  4668. ;; string minus common indentation.
  4669. (letrec ((build
  4670. (lambda (datum)
  4671. ;; Return DATUM with all its strings indentation
  4672. ;; shortened from MIN-IND white spaces.
  4673. (setcdr
  4674. (cdr datum)
  4675. (mapcar
  4676. (lambda (object)
  4677. (cond
  4678. ((stringp object)
  4679. (with-temp-buffer
  4680. (insert object)
  4681. (let ((s (point-min)))
  4682. (while (setq s (text-property-not-all
  4683. s (point-max) 'org-ind nil))
  4684. (goto-char s)
  4685. (let ((i (get-text-property s 'org-ind)))
  4686. (delete-region s (progn
  4687. (skip-chars-forward " \t")
  4688. (point)))
  4689. (when (integerp i) (indent-to (- i min-ind))))))
  4690. (buffer-string)))
  4691. ((memq (org-element-type object)
  4692. org-element-recursive-objects)
  4693. (funcall build object))
  4694. (t object)))
  4695. (org-element-contents datum)))
  4696. datum)))
  4697. (funcall build element)))))
  4698. ;;; Cache
  4699. ;;
  4700. ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
  4701. ;; fast mapping across Org elements in `org-element-cache-map', which see.
  4702. ;;
  4703. ;; When cache is enabled, the elements returned by `org-element-at-point' and
  4704. ;; `org-element-context' are returned by reference. Altering these elements will
  4705. ;; also alter their cache representation. The same is true for
  4706. ;; elements passed to mapping function in `org-element-cache-map'.
  4707. ;;
  4708. ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
  4709. ;; `org-element-cache-map'.
  4710. ;;
  4711. ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
  4712. ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
  4713. ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
  4714. ;;
  4715. ;; Internally, parsed elements are stored in an AVL tree,
  4716. ;; `org-element--cache'. This tree is updated lazily: whenever
  4717. ;; a change happens to the buffer, a synchronization request is
  4718. ;; registered in `org-element--cache-sync-requests' (see
  4719. ;; `org-element--cache-submit-request'). During idle time, requests
  4720. ;; are processed by `org-element--cache-sync'. Synchronization also
  4721. ;; happens when an element is required from the cache. In this case,
  4722. ;; the process stops as soon as the needed element is up-to-date.
  4723. ;;
  4724. ;; A synchronization request can only apply on a synchronized part of
  4725. ;; the cache. Therefore, the cache is updated at least to the
  4726. ;; location where the new request applies. Thus, requests are ordered
  4727. ;; from left to right and all elements starting before the first
  4728. ;; request are correct. This property is used by functions like
  4729. ;; `org-element--cache-find' to retrieve elements in the part of the
  4730. ;; cache that can be trusted.
  4731. ;;
  4732. ;; A request applies to every element, starting from its original
  4733. ;; location (or key, see below). When a request is processed, it
  4734. ;; moves forward and may collide the next one. In this case, both
  4735. ;; requests are merged into a new one that starts from that element.
  4736. ;; As a consequence, the whole synchronization complexity does not
  4737. ;; depend on the number of pending requests, but on the number of
  4738. ;; elements the very first request will be applied on.
  4739. ;;
  4740. ;; Elements cannot be accessed through their beginning position, which
  4741. ;; may or may not be up-to-date. Instead, each element in the tree is
  4742. ;; associated to a key, obtained with `org-element--cache-key'. This
  4743. ;; mechanism is robust enough to preserve total order among elements
  4744. ;; even when the tree is only partially synchronized.
  4745. ;;
  4746. ;; The cache code debuggin is fairly complex because cache request
  4747. ;; state is often hard to reproduce. An extensive diagnostics
  4748. ;; functionality is built into the cache code to assist hunting bugs.
  4749. ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
  4750. ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
  4751. ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
  4752. ;; `org-element--cache-map-statistics-threshold'.
  4753. (defvar org-element-use-cache t
  4754. "Non-nil when Org parser should cache its results.")
  4755. (defvar org-element-cache-persistent t
  4756. "Non-nil when cache should persist between Emacs sessions.")
  4757. (defvar org-element-cache-sync-idle-time 0.6
  4758. "Length, in seconds, of idle time before syncing cache.")
  4759. (defvar org-element-cache-sync-duration 0.04
  4760. "Maximum duration, as a time value, for a cache synchronization.
  4761. If the synchronization is not over after this delay, the process
  4762. pauses and resumes after `org-element-cache-sync-break'
  4763. seconds.")
  4764. (defvar org-element-cache-sync-break 0.3
  4765. "Duration, as a time value, of the pause between synchronizations.
  4766. See `org-element-cache-sync-duration' for more information.")
  4767. (defvar org-element--cache-self-verify t
  4768. "Activate extra consistency checks for the cache.
  4769. This may cause serious performance degradation depending on the value
  4770. of `org-element--cache-self-verify-frequency'.
  4771. When set to symbol `backtrace', record and display backtrace log if
  4772. any inconsistency is detected.")
  4773. (defvar org-element--cache-self-verify-frequency 0.03
  4774. "Frequency of cache element verification.
  4775. This number is a probability to check an element requested from cache
  4776. to be correct. Setting this to a value less than 0.0001 is useless.")
  4777. (defvar org-element--cache-diagnostics nil
  4778. "Print detailed diagnostics of cache processing.")
  4779. (defvar org-element--cache-map-statistics nil
  4780. "Print statistics for `org-element-cache-map'.")
  4781. (defvar org-element--cache-map-statistics-threshold 0.1
  4782. "Time threshold in seconds to log statistics for `org-element-cache-map'.")
  4783. (defvar org-element--cache-diagnostics-level 2
  4784. "Detail level of the diagnostics.")
  4785. (defvar-local org-element--cache-diagnostics-ring nil
  4786. "Ring containing last `org-element--cache-diagnostics-ring-size'
  4787. cache process log entries.")
  4788. (defvar org-element--cache-diagnostics-ring-size 5000
  4789. "Size of `org-element--cache-diagnostics-ring'.")
  4790. ;;;; Data Structure
  4791. (defvar-local org-element--cache nil
  4792. "AVL tree used to cache elements.
  4793. Each node of the tree contains an element. Comparison is done
  4794. with `org-element--cache-compare'. This cache is used in
  4795. `org-element-at-point'.")
  4796. (defvar-local org-element--headline-cache nil
  4797. "AVL tree used to cache headline and inlinetask elements.
  4798. Each node of the tree contains an element. Comparison is done
  4799. with `org-element--cache-compare'. This cache is used in
  4800. `org-element-cache-map'.")
  4801. (defconst org-element--cache-hash-size 16
  4802. "Cache size for recent cached calls to `org-element--cache-find'.
  4803. This extra caching is based on the following paper:
  4804. Pugh [Information Processing Letters] (1990) Slow optimally balanced
  4805. search strategies vs. cached fast uniformly balanced search
  4806. strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
  4807. Also, see `org-element--cache-hash-left' and `org-element--cache-hash-right'.")
  4808. (defvar-local org-element--cache-hash-left nil
  4809. "Cached elements from `org-element--cache' for fast O(1) lookup.
  4810. When non-nil, it should be a vector representing POS arguments of
  4811. `org-element--cache-find' called with nil SIDE argument.
  4812. Also, see `org-element--cache-hash-size'.")
  4813. (defvar-local org-element--cache-hash-right nil
  4814. "Cached elements from `org-element--cache' for fast O(1) lookup.
  4815. When non-nil, it should be a vector representing POS arguments of
  4816. `org-element--cache-find' called with non-nil, non-`both' SIDE argument.
  4817. Also, see `org-element--cache-hash-size'.")
  4818. (defvar org-element--cache-hash-statistics '(0 . 0)
  4819. "Cons cell storing how Org makes use of `org-element--cache-find' caching.
  4820. The car is the number of successful uses and cdr is the total calls to
  4821. `org-element--cache-find'.")
  4822. (defvar org-element--cache-hash-nocache 0
  4823. "Number of calls to `org-element--cache-has' with `both' SIDE argument.
  4824. These calls are not cached by hash. See `org-element--cache-hash-size'.")
  4825. (defvar-local org-element--cache-size 0
  4826. "Size of the `org-element--cache'.
  4827. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4828. (defvar-local org-element--headline-cache-size 0
  4829. "Size of the `org-element--headline-cache'.
  4830. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4831. (defvar-local org-element--cache-sync-requests nil
  4832. "List of pending synchronization requests.
  4833. A request is a vector with the following pattern:
  4834. [NEXT BEG END OFFSET PARENT PHASE]
  4835. Processing a synchronization request consists of three phases:
  4836. 0. Delete modified elements,
  4837. 1. Fill missing area in cache,
  4838. 2. Shift positions and re-parent elements after the changes.
  4839. During phase 0, NEXT is the key of the first element to be
  4840. removed, BEG and END is buffer position delimiting the
  4841. modifications. Elements starting between them (inclusive) are
  4842. removed. So are elements whose parent is removed. PARENT, when
  4843. non-nil, is the common parent of all the elements between BEG and END.
  4844. It is guaranteed that only a single phase 0 request exists at any
  4845. moment of time. If it does, it must be the first request in the list.
  4846. During phase 1, NEXT is the key of the next known element in
  4847. cache and BEG its beginning position. Parse buffer between that
  4848. element and the one before it in order to determine the parent of
  4849. the next element. Set PARENT to the element containing NEXT.
  4850. During phase 2, NEXT is the key of the next element to shift in
  4851. the parse tree. All elements starting from this one have their
  4852. properties relative to buffer positions shifted by integer
  4853. OFFSET and, if they belong to element PARENT, are adopted by it.
  4854. PHASE specifies the phase number, as an integer.
  4855. For any synchronisation request, all the later requests in the cache
  4856. must not start at or before END. See `org-element--cache-submit-request'.")
  4857. (defvar-local org-element--cache-sync-timer nil
  4858. "Timer used for cache synchronization.")
  4859. (defvar-local org-element--cache-sync-keys-value nil
  4860. "Id value used to identify keys during synchronisation.
  4861. See `org-element--cache-key' for more information.")
  4862. (defvar-local org-element--cache-change-tic nil
  4863. "Last `buffer-chars-modified-tick' for registered changes.")
  4864. (defvar-local org-element--cache-last-buffer-size nil
  4865. "Last value of `buffer-size' for registered changes.")
  4866. (defvar org-element--cache-non-modifying-commands
  4867. '(org-agenda
  4868. org-agenda-redo
  4869. org-sparse-tree
  4870. org-occur
  4871. org-columns
  4872. org-columns-redo
  4873. org-columns-new
  4874. org-columns-delete
  4875. org-columns-compute
  4876. org-columns-insert-dblock
  4877. org-agenda-columns
  4878. org-ctrl-c-ctrl-c)
  4879. "List of commands that are not expected to change the cache state.
  4880. This variable is used to determine when re-parsing buffer is not going
  4881. to slow down the command.
  4882. If the commends end up modifying the cache, the worst case scenario is
  4883. performance drop. So, advicing these commands is safe. Yet, it is
  4884. better to remove the commands adviced in such way from this list.")
  4885. (defmacro org-element--request-key (request)
  4886. "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
  4887. `(aref ,request 0))
  4888. (defmacro org-element--request-beg (request)
  4889. "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
  4890. `(aref ,request 1))
  4891. (defmacro org-element--request-end (request)
  4892. "Get END part of a `org-element--cache-sync-requests' REQUEST."
  4893. `(aref ,request 2))
  4894. (defmacro org-element--request-offset (request)
  4895. "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
  4896. `(aref ,request 3))
  4897. (defmacro org-element--request-parent (request)
  4898. "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
  4899. `(aref ,request 4))
  4900. (defmacro org-element--request-phase (request)
  4901. "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
  4902. `(aref ,request 5))
  4903. (defmacro org-element--format-element (element)
  4904. "Format ELEMENT for printing in diagnostics."
  4905. `(let ((print-length 50)
  4906. (print-level 5))
  4907. (prin1-to-string ,element)))
  4908. (defmacro org-element--cache-log-message (format-string &rest args)
  4909. "Add a new log message for org-element-cache."
  4910. `(when (or org-element--cache-diagnostics
  4911. (eq org-element--cache-self-verify 'backtrace))
  4912. (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
  4913. (buffer-name (current-buffer)))
  4914. ,format-string))
  4915. (format-string (funcall #'format format-string ,@args)))
  4916. (if org-element--cache-diagnostics
  4917. (display-warning 'org-element-cache format-string)
  4918. (unless org-element--cache-diagnostics-ring
  4919. (setq org-element--cache-diagnostics-ring
  4920. (make-ring org-element--cache-diagnostics-ring-size)))
  4921. (ring-insert org-element--cache-diagnostics-ring format-string)))))
  4922. (defmacro org-element--cache-warn (format-string &rest args)
  4923. "Raise warning for org-element-cache."
  4924. `(let* ((format-string (funcall #'format ,format-string ,@args))
  4925. (format-string
  4926. (if (or (not org-element--cache-diagnostics-ring)
  4927. (not (eq 'backtrace org-element--cache-self-verify)))
  4928. format-string
  4929. (prog1
  4930. (concat (format "Warning(%s): "
  4931. (buffer-name (current-buffer)))
  4932. format-string
  4933. "\nBacktrace:\n "
  4934. (mapconcat #'identity
  4935. (ring-elements org-element--cache-diagnostics-ring)
  4936. "\n "))
  4937. (setq org-element--cache-diagnostics-ring nil)))))
  4938. (if (and (boundp 'org-batch-test) org-batch-test)
  4939. (error "%s" (concat "org-element--cache: " format-string))
  4940. (display-warning 'org-element-cache
  4941. (concat "org-element--cache: " format-string)))))
  4942. (defsubst org-element--cache-key (element)
  4943. "Return a unique key for ELEMENT in cache tree.
  4944. Keys are used to keep a total order among elements in the cache.
  4945. Comparison is done with `org-element--cache-key-less-p'.
  4946. When no synchronization is taking place, a key is simply the
  4947. beginning position of the element, or that position plus one in
  4948. the case of an first item (respectively row) in
  4949. a list (respectively a table). They key of a section is its beginning
  4950. position minus one.
  4951. During a synchronization, the key is the one the element had when
  4952. the cache was synchronized for the last time. Elements added to
  4953. cache during the synchronization get a new key generated with
  4954. `org-element--cache-generate-key'.
  4955. Such keys are stored inside the element property
  4956. `:org-element--cache-sync-key'. The property is a cons containing
  4957. current `org-element--cache-sync-keys-value' and the element key."
  4958. (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
  4959. (cdr (org-element-property :org-element--cache-sync-key element)))
  4960. (let* ((begin (org-element-property :begin element))
  4961. ;; Increase beginning position of items (respectively
  4962. ;; table rows) by one, so the first item can get
  4963. ;; a different key from its parent list (respectively
  4964. ;; table).
  4965. (key (if (memq (org-element-type element) '(item table-row))
  4966. (1+ begin)
  4967. ;; Decrease beginning position of sections by one,
  4968. ;; so that the first element of the section get
  4969. ;; different key from the parent section.
  4970. (if (eq (org-element-type element) 'section)
  4971. (1- begin)
  4972. (if (eq (org-element-type element) 'org-data)
  4973. (- begin 2)
  4974. begin)))))
  4975. (when org-element--cache-sync-requests
  4976. (org-element-put-property
  4977. element
  4978. :org-element--cache-sync-key
  4979. (cons org-element--cache-sync-keys-value key)))
  4980. key)))
  4981. (defun org-element--cache-generate-key (lower upper)
  4982. "Generate a key between LOWER and UPPER.
  4983. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4984. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4985. a unique key, as an integer or a list of integers, according to
  4986. the following rules:
  4987. - LOWER and UPPER are compared level-wise until values differ.
  4988. - If, at a given level, LOWER and UPPER differ from more than
  4989. 2, the new key shares all the levels above with LOWER and
  4990. gets a new level. Its value is the mean between LOWER and
  4991. UPPER:
  4992. (1 2) + (1 4) --> (1 3)
  4993. - If LOWER has no value to compare with, it is assumed that its
  4994. value is `most-negative-fixnum'. E.g.,
  4995. (1 1) + (1 1 2)
  4996. is equivalent to
  4997. (1 1 m) + (1 1 2)
  4998. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4999. short of levels, the current value is `most-positive-fixnum'.
  5000. - If they differ from only one, the new key inherits from
  5001. current LOWER level and fork it at the next level. E.g.,
  5002. (2 1) + (3 3)
  5003. is equivalent to
  5004. (2 1) + (2 M)
  5005. where M is `most-positive-fixnum'.
  5006. - If the key is only one level long, it is returned as an
  5007. integer:
  5008. (1 2) + (3 2) --> 2
  5009. When they are not equals, the function assumes that LOWER is
  5010. lesser than UPPER, per `org-element--cache-key-less-p'."
  5011. (if (equal lower upper) lower
  5012. (let ((lower (if (integerp lower) (list lower) lower))
  5013. (upper (if (integerp upper) (list upper) upper))
  5014. skip-upper key)
  5015. (catch 'exit
  5016. (while t
  5017. (let ((min (or (car lower) most-negative-fixnum))
  5018. (max (cond (skip-upper most-positive-fixnum)
  5019. ((car upper))
  5020. (t most-positive-fixnum))))
  5021. (if (< (1+ min) max)
  5022. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  5023. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  5024. (when (and (< min max) (not skip-upper))
  5025. ;; When at a given level, LOWER and UPPER differ from
  5026. ;; 1, ignore UPPER altogether. Instead create a key
  5027. ;; between LOWER and the greatest key with the same
  5028. ;; prefix as LOWER so far.
  5029. (setq skip-upper t))
  5030. (push min key)
  5031. (setq lower (cdr lower) upper (cdr upper)))))))))
  5032. (defsubst org-element--cache-key-less-p (a b)
  5033. "Non-nil if key A is less than key B.
  5034. A and B are either integers or lists of integers, as returned by
  5035. `org-element--cache-key'.
  5036. Note that it is not reliable to compare buffer position with the cache
  5037. keys. They keys may be larger compared to actual element :begin
  5038. position."
  5039. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  5040. (if (integerp b) (< (car a) b)
  5041. (catch 'exit
  5042. (while (and a b)
  5043. (cond ((car-less-than-car a b) (throw 'exit t))
  5044. ((car-less-than-car b a) (throw 'exit nil))
  5045. (t (setq a (cdr a) b (cdr b)))))
  5046. ;; If A is empty, either keys are equal (B is also empty) and
  5047. ;; we return nil, or A is lesser than B (B is longer) and we
  5048. ;; return a non-nil value.
  5049. ;;
  5050. ;; If A is not empty, B is necessarily empty and A is greater
  5051. ;; than B (A is longer). Therefore, return nil.
  5052. (and (null a) b)))))
  5053. (defun org-element--cache-compare (a b)
  5054. "Non-nil when element A is located before element B."
  5055. (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
  5056. (defsubst org-element--cache-root ()
  5057. "Return root value in `org-element--cache' .
  5058. This function assumes `org-element--cache' is a valid AVL tree."
  5059. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  5060. (defsubst org-element--headline-cache-root ()
  5061. "Return root value in `org-element--headline-cache' .
  5062. This function assumes `org-element--headline-cache' is a valid AVL tree."
  5063. (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
  5064. ;;;; Tools
  5065. (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
  5066. "Non-nil when cache is active in current buffer."
  5067. (and org-element-use-cache
  5068. org-element--cache
  5069. (derived-mode-p 'org-mode)
  5070. (or called-from-cache-change-func-p
  5071. (and
  5072. ;; org-num-mode calls some Org structure analysis functions
  5073. ;; that can trigger cache update in the middle of changes. See
  5074. ;; `org-num--verify' calling `org-num--skip-value' calling
  5075. ;; `org-entry-get' that uses cache.
  5076. ;; Forcefully disable cache when called from inside a
  5077. ;; modification hook, where `inhibit-modification-hooks' is set
  5078. ;; to t.
  5079. (not inhibit-modification-hooks)
  5080. ;; `combine-change-calls' sets `after-change-functions' to
  5081. ;; nil. We need not to use cache inside
  5082. ;; `combine-change-calls' because the buffer is potentially
  5083. ;; changed without notice (the change will be registered
  5084. ;; after exiting the `combine-change-calls' body though).
  5085. (memq #'org-element--cache-after-change after-change-functions))
  5086. (eq org-element--cache-change-tic (buffer-chars-modified-tick)))))
  5087. ;; FIXME: Remove after we establish that hashing is effective.
  5088. (defun org-element-cache-hash-show-statistics ()
  5089. "Display efficiency of O(1) query cache for `org-element--cache-find'.
  5090. This extra caching is based on the following paper:
  5091. Pugh [Information Processing Letters] (1990) Slow optimally balanced
  5092. search strategies vs. cached fast uniformly balanced search
  5093. strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
  5094. Also, see `org-element--cache-size'."
  5095. (interactive)
  5096. (message "%.2f%% of cache searches hashed, %.2f%% non-hashable."
  5097. (* 100
  5098. (/ (float (car org-element--cache-hash-statistics))
  5099. (cdr org-element--cache-hash-statistics)))
  5100. (* 100
  5101. (/ (float org-element--cache-hash-nocache)
  5102. (cdr org-element--cache-hash-statistics)))))
  5103. (defun org-element--cache-find (pos &optional side)
  5104. "Find element in cache starting at POS or before.
  5105. POS refers to a buffer position.
  5106. When optional argument SIDE is non-nil, the function checks for
  5107. elements starting at or past POS instead. If SIDE is `both', the
  5108. function returns a cons cell where car is the first element
  5109. starting at or before POS and cdr the first element starting
  5110. after POS.
  5111. The function can only find elements in the synchronized part of
  5112. the cache."
  5113. (with-current-buffer (or (buffer-base-buffer) (current-buffer))
  5114. (let* ((limit (and org-element--cache-sync-requests
  5115. (org-element--request-key (car org-element--cache-sync-requests))))
  5116. (node (org-element--cache-root))
  5117. (hash-pos (unless (eq side 'both)
  5118. (mod (org-knuth-hash pos)
  5119. org-element--cache-hash-size)))
  5120. (hashed (if (not side)
  5121. (aref org-element--cache-hash-left hash-pos)
  5122. (unless (eq side 'both)
  5123. (aref org-element--cache-hash-right hash-pos))))
  5124. lower upper)
  5125. ;; `org-element--cache-key-less-p' does not accept markers.
  5126. (when (markerp pos) (setq pos (marker-position pos)))
  5127. (cl-incf (cdr org-element--cache-hash-statistics))
  5128. (when (eq side 'both) (cl-incf org-element--cache-hash-nocache))
  5129. (if (and hashed (not (eq side 'both))
  5130. (or (not limit)
  5131. ;; Limit can be a list key.
  5132. (org-element--cache-key-less-p
  5133. (org-element--cache-key hashed)
  5134. limit))
  5135. (= pos (org-element-property :begin hashed))
  5136. ;; We cannot rely on element :begin for elements with
  5137. ;; children starting at the same pos.
  5138. (not (memq (org-element-type hashed)
  5139. '(section org-data table)))
  5140. (org-element-property :cached hashed))
  5141. (progn
  5142. (cl-incf (car org-element--cache-hash-statistics))
  5143. hashed)
  5144. (while node
  5145. (let* ((element (avl-tree--node-data node))
  5146. (begin (org-element-property :begin element)))
  5147. (cond
  5148. ((and limit
  5149. (not (org-element--cache-key-less-p
  5150. (org-element--cache-key element) limit)))
  5151. (setq node (avl-tree--node-left node)))
  5152. ((> begin pos)
  5153. (setq upper element
  5154. node (avl-tree--node-left node)))
  5155. ((or (< begin pos)
  5156. ;; If the element is section or org-data, we also need
  5157. ;; to check the following element.
  5158. (memq (org-element-type element) '(section org-data)))
  5159. (setq lower element
  5160. node (avl-tree--node-right node)))
  5161. ;; We found an element in cache starting at POS. If `side'
  5162. ;; is `both' we also want the next one in order to generate
  5163. ;; a key in-between.
  5164. ;;
  5165. ;; If the element is the first row or item in a table or
  5166. ;; a plain list, we always return the table or the plain
  5167. ;; list.
  5168. ;;
  5169. ;; In any other case, we return the element found.
  5170. ((eq side 'both)
  5171. (setq lower element)
  5172. (setq node (avl-tree--node-right node)))
  5173. ((and (memq (org-element-type element) '(item table-row))
  5174. (let ((parent (org-element-property :parent element)))
  5175. (and (= (org-element-property :begin element)
  5176. (org-element-property :contents-begin parent))
  5177. (setq node nil
  5178. lower parent
  5179. upper parent)))))
  5180. (t
  5181. (setq node nil
  5182. lower element
  5183. upper element)))))
  5184. (if (not side)
  5185. (aset org-element--cache-hash-left hash-pos lower)
  5186. (unless (eq side 'both)
  5187. (aset org-element--cache-hash-right hash-pos lower)))
  5188. (pcase side
  5189. (`both (cons lower upper))
  5190. (`nil lower)
  5191. (_ upper))))))
  5192. (defun org-element--cache-put (element)
  5193. "Store ELEMENT in current buffer's cache, if allowed."
  5194. (when (org-element--cache-active-p)
  5195. (when org-element--cache-sync-requests
  5196. ;; During synchronization, first build an appropriate key for
  5197. ;; the new element so `avl-tree-enter' can insert it at the
  5198. ;; right spot in the cache.
  5199. (let* ((keys (org-element--cache-find
  5200. (org-element-property :begin element) 'both))
  5201. (new-key (org-element--cache-generate-key
  5202. (and (car keys) (org-element--cache-key (car keys)))
  5203. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  5204. (org-element--cache-sync-requests
  5205. (org-element--request-key (car org-element--cache-sync-requests)))))))
  5206. (org-element-put-property
  5207. element
  5208. :org-element--cache-sync-key
  5209. (cons org-element--cache-sync-keys-value new-key))))
  5210. (when (>= org-element--cache-diagnostics-level 2)
  5211. (org-element--cache-log-message
  5212. "Added new element with %S key: %S"
  5213. (org-element-property :org-element--cache-sync-key element)
  5214. (org-element--format-element element)))
  5215. (org-element-put-property element :cached t)
  5216. (when (memq (org-element-type element) '(headline inlinetask))
  5217. (cl-incf org-element--headline-cache-size)
  5218. (avl-tree-enter org-element--headline-cache element))
  5219. (cl-incf org-element--cache-size)
  5220. (avl-tree-enter org-element--cache element)))
  5221. (defsubst org-element--cache-remove (element)
  5222. "Remove ELEMENT from cache.
  5223. Assume ELEMENT belongs to cache and that a cache is active."
  5224. (org-element-put-property element :cached nil)
  5225. (cl-decf org-element--cache-size)
  5226. ;; Invalidate contents of parent.
  5227. (when (and (org-element-property :parent element)
  5228. (org-element-contents (org-element-property :parent element)))
  5229. (org-element-set-contents (org-element-property :parent element) nil))
  5230. (when (memq (org-element-type element) '(headline inlinetask))
  5231. (cl-decf org-element--headline-cache-size)
  5232. (avl-tree-delete org-element--headline-cache element))
  5233. (or (avl-tree-delete org-element--cache element)
  5234. (progn
  5235. ;; This should not happen, but if it is, would be better to know
  5236. ;; where it happens.
  5237. (org-element--cache-warn
  5238. "Failed to delete %S element in %S at %S. The element cache key was %S.
  5239. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5240. (org-element-type element)
  5241. (current-buffer)
  5242. (org-element-property :begin element)
  5243. (org-element-property :org-element--cache-sync-key element))
  5244. (org-element-cache-reset)
  5245. (throw 'quit nil))))
  5246. ;;;; Synchronization
  5247. (defsubst org-element--cache-set-timer (buffer)
  5248. "Set idle timer for cache synchronization in BUFFER."
  5249. (when org-element--cache-sync-timer
  5250. (cancel-timer org-element--cache-sync-timer))
  5251. (setq org-element--cache-sync-timer
  5252. (run-with-idle-timer
  5253. (let ((idle (current-idle-time)))
  5254. (if idle (time-add idle org-element-cache-sync-break)
  5255. org-element-cache-sync-idle-time))
  5256. nil
  5257. #'org-element--cache-sync
  5258. buffer)))
  5259. (defsubst org-element--cache-interrupt-p (time-limit)
  5260. "Non-nil when synchronization process should be interrupted.
  5261. TIME-LIMIT is a time value or nil."
  5262. (and time-limit
  5263. (or (input-pending-p)
  5264. (time-less-p time-limit nil))))
  5265. (defsubst org-element--cache-shift-positions (element offset &optional props)
  5266. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  5267. Properties containing buffer positions are `:begin', `:end',
  5268. `:contents-begin', `:contents-end' and `:structure'. When
  5269. optional argument PROPS is a list of keywords, only shift
  5270. properties provided in that list.
  5271. Properties are modified by side-effect."
  5272. (let ((properties (nth 1 element)))
  5273. ;; Shift `:structure' property for the first plain list only: it
  5274. ;; is the only one that really matters and it prevents from
  5275. ;; shifting it more than once.
  5276. (when (and (or (not props) (memq :structure props))
  5277. (eq (org-element-type element) 'plain-list)
  5278. (not (eq (org-element-type (plist-get properties :parent)) 'item)))
  5279. (dolist (item (plist-get properties :structure))
  5280. (cl-incf (car item) offset)
  5281. (cl-incf (nth 6 item) offset)))
  5282. (dolist (key '( :begin :contents-begin :contents-end :end
  5283. :post-affiliated :robust-begin :robust-end))
  5284. (let ((value (and (or (not props) (memq key props))
  5285. (plist-get properties key))))
  5286. (and value (plist-put properties key (+ offset value)))))))
  5287. (defvar org-element--cache-interrupt-C-g t
  5288. "When non-nil, allow the user to abort `org-element--cache-sync'.
  5289. The execution is aborted upon pressing `\\[keyboard-quit]'
  5290. `org-element--cache-interrupt-C-g-max-count' times.")
  5291. (defvar org-element--cache-interrupt-C-g-max-count 5
  5292. "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
  5293. See `org-element--cache-interrupt-C-g'.")
  5294. (defvar org-element--cache-interrupt-C-g-count 0
  5295. "Current number of `org-element--cache-sync' calls.
  5296. See `org-element--cache-interrupt-C-g'.")
  5297. (defvar org-element--cache-change-warning nil
  5298. "Non-nil when a sensitive line is about to be changed.
  5299. It is a symbol among nil, t, or a number representing smallest level of
  5300. modified headline. The level considers headline levels both before
  5301. and after the modification.")
  5302. (defun org-element--cache-sync (buffer &optional threshold future-change offset)
  5303. "Synchronize cache with recent modification in BUFFER.
  5304. When optional argument THRESHOLD is non-nil, do the
  5305. synchronization for all elements starting before or at threshold,
  5306. then exit. Otherwise, synchronize cache for as long as
  5307. `org-element-cache-sync-duration' or until Emacs leaves idle
  5308. state.
  5309. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  5310. not registered yet in the cache are going to happen. OFFSET is the
  5311. change offset. It is used in `org-element--cache-submit-request',
  5312. where cache is partially updated before current modification are
  5313. actually submitted."
  5314. (when (buffer-live-p buffer)
  5315. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  5316. ;; Do not sync when, for example, in the middle of
  5317. ;; `combine-change-calls'. See the commentary inside
  5318. ;; `org-element--cache-active-p'.
  5319. (when (org-element--cache-active-p)
  5320. ;; Check if the buffer have been changed outside visibility of
  5321. ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
  5322. (if (/= org-element--cache-last-buffer-size (buffer-size))
  5323. (progn
  5324. (org-element--cache-warn
  5325. "Unregistered buffer modifications detected. Resetting.
  5326. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  5327. The buffer is: %s\n Current command: %S\n Backtrace:\n%S"
  5328. (buffer-name (current-buffer))
  5329. this-command
  5330. (when (and (fboundp 'backtrace-get-frames)
  5331. (fboundp 'backtrace-to-string))
  5332. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  5333. (org-element-cache-reset))
  5334. (let ((inhibit-quit t) request next)
  5335. (setq org-element--cache-interrupt-C-g-count 0)
  5336. (when org-element--cache-sync-timer
  5337. (cancel-timer org-element--cache-sync-timer))
  5338. (let ((time-limit (time-add nil org-element-cache-sync-duration)))
  5339. (catch 'org-element--cache-interrupt
  5340. (when org-element--cache-sync-requests
  5341. (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
  5342. (while org-element--cache-sync-requests
  5343. (setq request (car org-element--cache-sync-requests)
  5344. next (nth 1 org-element--cache-sync-requests))
  5345. (org-element--cache-process-request
  5346. request
  5347. (when next (org-element--request-key next))
  5348. threshold
  5349. (unless threshold time-limit)
  5350. future-change
  5351. offset)
  5352. ;; Re-assign current and next requests. It could have
  5353. ;; been altered during phase 1.
  5354. (setq request (car org-element--cache-sync-requests)
  5355. next (nth 1 org-element--cache-sync-requests))
  5356. ;; Request processed. Merge current and next offsets and
  5357. ;; transfer ending position.
  5358. (when next
  5359. ;; The following requests can only be either phase 1
  5360. ;; or phase 2 requests. We need to let them know
  5361. ;; that additional shifting happened ahead of them.
  5362. (cl-incf (org-element--request-offset next) (org-element--request-offset request))
  5363. (org-element--cache-log-message
  5364. "Updating next request offset to %S: %s"
  5365. (org-element--request-offset next)
  5366. (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
  5367. ;; FIXME: END part of the request only matters for
  5368. ;; phase 0 requests. However, the only possible
  5369. ;; phase 0 request must be the first request in the
  5370. ;; list all the time. END position should be
  5371. ;; unused.
  5372. (setf (org-element--request-end next) (org-element--request-end request)))
  5373. (setq org-element--cache-sync-requests
  5374. (cdr org-element--cache-sync-requests)))))
  5375. ;; If more requests are awaiting, set idle timer accordingly.
  5376. ;; Otherwise, reset keys.
  5377. (if org-element--cache-sync-requests
  5378. (org-element--cache-set-timer buffer)
  5379. (setq org-element--cache-change-warning nil)
  5380. (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value)))))))))
  5381. (defun org-element--cache-process-request
  5382. (request next-request-key threshold time-limit future-change offset)
  5383. "Process synchronization REQUEST for all entries before NEXT.
  5384. REQUEST is a vector, built by `org-element--cache-submit-request'.
  5385. NEXT-REQUEST-KEY is a cache key of the next request, as returned by
  5386. `org-element--cache-key'.
  5387. When non-nil, THRESHOLD is a buffer position. Synchronization
  5388. stops as soon as a shifted element begins after it.
  5389. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  5390. after this time or when Emacs exits idle state.
  5391. When non-nil, FUTURE-CHANGE is a buffer position where changes not
  5392. registered yet in the cache are going to happen. OFFSET is the
  5393. changed text length. See `org-element--cache-submit-request' for more
  5394. information.
  5395. Throw `org-element--cache-interrupt' if the process stops before
  5396. completing the request."
  5397. (org-element--cache-log-message
  5398. "org-element-cache: Processing request %s up to %S-%S, next: %S"
  5399. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5400. future-change
  5401. threshold
  5402. next-request-key)
  5403. (catch 'org-element--cache-quit
  5404. (when (= (org-element--request-phase request) 0)
  5405. ;; Phase 0.
  5406. ;;
  5407. ;; Delete all elements starting after beginning of the element
  5408. ;; with request key NEXT, but not after buffer position END.
  5409. ;;
  5410. ;; At each iteration, we start again at tree root since
  5411. ;; a deletion modifies structure of the balanced tree.
  5412. (org-element--cache-log-message "Phase 0")
  5413. (catch 'org-element--cache-end-phase
  5414. (let ((deletion-count 0))
  5415. (while t
  5416. (when (org-element--cache-interrupt-p time-limit)
  5417. (org-element--cache-log-message "Interrupt: time limit")
  5418. (throw 'org-element--cache-interrupt nil))
  5419. (let ((request-key (org-element--request-key request))
  5420. (end (org-element--request-end request))
  5421. (node (org-element--cache-root))
  5422. data data-key)
  5423. ;; Find first element in cache with key REQUEST-KEY or
  5424. ;; after it.
  5425. (while node
  5426. (let* ((element (avl-tree--node-data node))
  5427. (key (org-element--cache-key element)))
  5428. (cond
  5429. ((org-element--cache-key-less-p key request-key)
  5430. (setq node (avl-tree--node-right node)))
  5431. ((org-element--cache-key-less-p request-key key)
  5432. (setq data element
  5433. data-key key
  5434. node (avl-tree--node-left node)))
  5435. (t (setq data element
  5436. data-key key
  5437. node nil)))))
  5438. (if data
  5439. ;; We found first element in cache starting at or
  5440. ;; after REQUEST-KEY.
  5441. (let ((pos (org-element-property :begin data)))
  5442. ;; FIXME: Maybe simply (< pos end)?
  5443. (if (<= pos end)
  5444. (progn
  5445. (org-element--cache-log-message "removing %S::%S"
  5446. (org-element-property :org-element--cache-sync-key data)
  5447. (org-element--format-element data))
  5448. (cl-incf deletion-count)
  5449. (org-element--cache-remove data)
  5450. (when (and (> (log org-element--cache-size 2) 10)
  5451. (> deletion-count
  5452. (/ org-element--cache-size (log org-element--cache-size 2))))
  5453. (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
  5454. deletion-count
  5455. org-element--cache-size
  5456. (log org-element--cache-size 2))
  5457. (org-element-cache-reset)
  5458. (throw 'org-element--cache-quit t)))
  5459. ;; Done deleting everything starting before END.
  5460. ;; DATA-KEY is the first known element after END.
  5461. ;; Move on to phase 1.
  5462. (org-element--cache-log-message
  5463. "found element after %S: %S::%S"
  5464. end
  5465. (org-element-property :org-element--cache-sync-key data)
  5466. (org-element--format-element data))
  5467. (setf (org-element--request-key request) data-key)
  5468. (setf (org-element--request-beg request) pos)
  5469. (setf (org-element--request-phase request) 1)
  5470. (throw 'org-element--cache-end-phase nil)))
  5471. ;; No element starting after modifications left in
  5472. ;; cache: further processing is futile.
  5473. (org-element--cache-log-message
  5474. "Phase 0 deleted all elements in cache after %S!"
  5475. request-key)
  5476. (throw 'org-element--cache-quit t)))))))
  5477. (when (= (org-element--request-phase request) 1)
  5478. ;; Phase 1.
  5479. ;;
  5480. ;; Phase 0 left a hole in the cache. Some elements after it
  5481. ;; could have parents within. For example, in the following
  5482. ;; buffer:
  5483. ;;
  5484. ;; - item
  5485. ;;
  5486. ;;
  5487. ;; Paragraph1
  5488. ;;
  5489. ;; Paragraph2
  5490. ;;
  5491. ;; if we remove a blank line between "item" and "Paragraph1",
  5492. ;; everything down to "Paragraph2" is removed from cache. But
  5493. ;; the paragraph now belongs to the list, and its `:parent'
  5494. ;; property no longer is accurate.
  5495. ;;
  5496. ;; Therefore we need to parse again elements in the hole, or at
  5497. ;; least in its last section, so that we can re-parent
  5498. ;; subsequent elements, during phase 2.
  5499. ;;
  5500. ;; Note that we only need to get the parent from the first
  5501. ;; element in cache after the hole.
  5502. ;;
  5503. ;; When next key is lesser or equal to the current one, current
  5504. ;; request is inside a to-be-shifted part of the cache. It is
  5505. ;; fine because the order of elements will not be altered by
  5506. ;; shifting. However, we cannot know the real position of the
  5507. ;; unshifted NEXT element in the current request. So, we need
  5508. ;; to sort the request list according to keys and re-start
  5509. ;; processing from the new leftmost request.
  5510. (org-element--cache-log-message "Phase 1")
  5511. (let ((key (org-element--request-key request)))
  5512. (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
  5513. ;; In theory, the only case when requests are not
  5514. ;; ordered is when key of the next request is either the
  5515. ;; same with current key or it is a key for a removed
  5516. ;; element. Either way, we can simply merge the two
  5517. ;; requests.
  5518. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5519. (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
  5520. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5521. (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
  5522. (setf (org-element--request-key next-request) key)
  5523. (setf (org-element--request-beg next-request) (org-element--request-beg request))
  5524. (setf (org-element--request-phase next-request) 1)
  5525. (throw 'org-element--cache-quit t))))
  5526. ;; Next element will start at its beginning position plus
  5527. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  5528. ;; contains the real beginning position of the first element to
  5529. ;; shift and re-parent.
  5530. (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request)))
  5531. cached-before)
  5532. (cond ((and threshold (> limit threshold))
  5533. (org-element--cache-log-message "Interrupt: position %S after threshold %S" limit threshold)
  5534. (throw 'org-element--cache-interrupt nil))
  5535. ((and future-change (>= limit future-change))
  5536. ;; Changes happened around this element and they will
  5537. ;; trigger another phase 1 request. Skip re-parenting
  5538. ;; and simply proceed with shifting (phase 2) to make
  5539. ;; sure that followup phase 0 request for the recent
  5540. ;; changes can operate on the correctly shifted cache.
  5541. (org-element--cache-log-message "position %S after future change %S" limit future-change)
  5542. (setf (org-element--request-parent request) nil)
  5543. (setf (org-element--request-phase request) 2))
  5544. (t
  5545. (when future-change
  5546. ;; Changes happened, but not yet registered after
  5547. ;; this element. However, we a not yet safe to look
  5548. ;; at the buffer and parse elements in the cache gap.
  5549. ;; Some of the parents to be added to cache may end
  5550. ;; after the changes. Parsing this parents will
  5551. ;; assign the :end correct value for cache state
  5552. ;; after future-change. Then, when the future change
  5553. ;; is going to be processed, such parent boundary
  5554. ;; will be altered unnecessarily. To avoid this,
  5555. ;; we alter the new parents by -OFFSET.
  5556. ;; For now, just save last known cached element and
  5557. ;; then check all the parents below.
  5558. (setq cached-before (org-element--cache-find (1- limit) nil)))
  5559. ;; No relevant changes happened after submitting this
  5560. ;; request. We are safe to look at the actual Org
  5561. ;; buffer and calculate the new parent.
  5562. (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
  5563. (when future-change
  5564. ;; Check all the newly added parents to not
  5565. ;; intersect with future change.
  5566. (let ((up parent))
  5567. (while (and up
  5568. (or (not cached-before)
  5569. (> (org-element-property :begin up)
  5570. (org-element-property :begin cached-before))))
  5571. (when (> (org-element-property :end up) future-change)
  5572. ;; Offset future cache request.
  5573. (org-element--cache-shift-positions
  5574. up (- offset)
  5575. (if (and (org-element-property :robust-begin up)
  5576. (org-element-property :robust-end up))
  5577. '(:contents-end :end :robust-end)
  5578. '(:contents-end :end))))
  5579. (setq up (org-element-property :parent up)))))
  5580. (org-element--cache-log-message
  5581. "New parent at %S: %S::%S"
  5582. limit
  5583. (org-element-property :org-element--cache-sync-key parent)
  5584. (org-element--format-element parent))
  5585. (setf (org-element--request-parent request) parent)
  5586. (setf (org-element--request-phase request) 2))))))
  5587. ;; Phase 2.
  5588. ;;
  5589. ;; Shift all elements starting from key START, but before NEXT, by
  5590. ;; OFFSET, and re-parent them when appropriate.
  5591. ;;
  5592. ;; Elements are modified by side-effect so the tree structure
  5593. ;; remains intact.
  5594. ;;
  5595. ;; Once THRESHOLD, if any, is reached, or once there is an input
  5596. ;; pending, exit. Before leaving, the current synchronization
  5597. ;; request is updated.
  5598. (org-element--cache-log-message "Phase 2")
  5599. (let ((start (org-element--request-key request))
  5600. (offset (org-element--request-offset request))
  5601. (parent (org-element--request-parent request))
  5602. (node (org-element--cache-root))
  5603. (stack (list nil))
  5604. (leftp t)
  5605. exit-flag continue-flag)
  5606. ;; No re-parenting nor shifting planned: request is over.
  5607. (when (and (not parent) (zerop offset))
  5608. (org-element--cache-log-message "Empty offset. Request completed.")
  5609. (throw 'org-element--cache-quit t))
  5610. (while node
  5611. (let* ((data (avl-tree--node-data node))
  5612. (key (org-element--cache-key data)))
  5613. ;; Traverse the cache tree. Ignore all the elements before
  5614. ;; START. Note that `avl-tree-stack' would not bypass the
  5615. ;; elements before START and thus would have beeen less
  5616. ;; efficient.
  5617. (if (and leftp (avl-tree--node-left node)
  5618. (not (org-element--cache-key-less-p key start)))
  5619. (progn (push node stack)
  5620. (setq node (avl-tree--node-left node)))
  5621. ;; Shift and re-parent when current node starts at or
  5622. ;; after START, but before NEXT.
  5623. (unless (org-element--cache-key-less-p key start)
  5624. ;; We reached NEXT. Request is complete.
  5625. (when (and next-request-key
  5626. (not (org-element--cache-key-less-p key next-request-key)))
  5627. (org-element--cache-log-message "Reached next request.")
  5628. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5629. (unless (and (org-element-property :cached (org-element--request-parent next-request))
  5630. (org-element-property :begin (org-element--request-parent next-request))
  5631. parent
  5632. (> (org-element-property :begin (org-element--request-parent next-request))
  5633. (org-element-property :begin parent)))
  5634. (setf (org-element--request-parent next-request) parent)))
  5635. (throw 'org-element--cache-quit t))
  5636. ;; Handle interruption request. Update current request.
  5637. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  5638. (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
  5639. (setf (org-element--request-key request) key)
  5640. (setf (org-element--request-parent request) parent)
  5641. (throw 'org-element--cache-interrupt nil))
  5642. ;; Shift element.
  5643. (unless (zerop offset)
  5644. (when (>= org-element--cache-diagnostics-level 3)
  5645. (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
  5646. offset
  5647. (org-element-property :org-element--cache-sync-key data)
  5648. (org-element--format-element data)))
  5649. (org-element--cache-shift-positions data offset))
  5650. (let ((begin (org-element-property :begin data)))
  5651. ;; Update PARENT and re-parent DATA, only when
  5652. ;; necessary. Propagate new structures for lists.
  5653. (while (and parent
  5654. (<= (org-element-property :end parent) begin))
  5655. (setq parent (org-element-property :parent parent)))
  5656. (cond ((and (not parent) (zerop offset)) (throw 'org-element--cache-quit nil))
  5657. ;; Consider scenario when DATA lays within
  5658. ;; sensitive lines of PARENT that was found
  5659. ;; during phase 2. For example:
  5660. ;;
  5661. ;; #+ begin_quote
  5662. ;; Paragraph
  5663. ;; #+end_quote
  5664. ;;
  5665. ;; In the above source block, remove space in
  5666. ;; the first line will trigger re-parenting of
  5667. ;; the paragraph and "#+end_quote" that is also
  5668. ;; considered paragraph before the modification.
  5669. ;; However, the paragraph element stored in
  5670. ;; cache must be deleted instead.
  5671. ((and parent
  5672. (or (not (memq (org-element-type parent) org-element-greater-elements))
  5673. (and (org-element-property :contents-begin parent)
  5674. (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
  5675. (and (org-element-property :contents-end parent)
  5676. (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
  5677. (> (org-element-property :end data) (org-element-property :end parent))
  5678. (and (org-element-property :contents-end data)
  5679. (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
  5680. (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
  5681. (org-element-property :org-element--cache-sync-key data)
  5682. (org-element--format-element data))
  5683. (org-element--cache-remove data)
  5684. ;; We altered the tree structure. The tree
  5685. ;; traversal needs to be restarted.
  5686. (setf (org-element--request-key request) key)
  5687. (setf (org-element--request-parent request) parent)
  5688. ;; Restart tree traversal.
  5689. (setq node (org-element--cache-root)
  5690. stack (list nil)
  5691. leftp t
  5692. begin -1
  5693. continue-flag t))
  5694. ((and parent
  5695. (not (eq parent data))
  5696. (let ((p (org-element-property :parent data)))
  5697. (or (not p)
  5698. (< (org-element-property :begin p)
  5699. (org-element-property :begin parent))
  5700. (unless (eq p parent)
  5701. (not (org-element-property :cached p))
  5702. ;; (not (avl-tree-member-p org-element--cache p))
  5703. ))))
  5704. (org-element--cache-log-message
  5705. "Updating parent in %S\n Old parent: %S\n New parent: %S"
  5706. (org-element--format-element data)
  5707. (org-element--format-element (org-element-property :parent data))
  5708. (org-element--format-element parent))
  5709. (when (and (eq 'org-data (org-element-type parent))
  5710. (not (eq 'headline (org-element-type data))))
  5711. ;; FIXME: This check is here to see whether
  5712. ;; such error happens within
  5713. ;; `org-element--cache-process-request' or somewhere
  5714. ;; else.
  5715. (org-element--cache-warn
  5716. "Added org-data parent to non-headline element: %S
  5717. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5718. data)
  5719. (org-element-cache-reset)
  5720. (throw 'org-element--cache-quit t))
  5721. (org-element-put-property data :parent parent)
  5722. (let ((s (org-element-property :structure parent)))
  5723. (when (and s (org-element-property :structure data))
  5724. (org-element-put-property data :structure s)))))
  5725. ;; Cache is up-to-date past THRESHOLD. Request
  5726. ;; interruption.
  5727. (when (and threshold (> begin threshold))
  5728. (org-element--cache-log-message "Reached threshold %S: %S"
  5729. threshold
  5730. (org-element--format-element data))
  5731. (setq exit-flag t))))
  5732. (if continue-flag
  5733. (setq continue-flag nil)
  5734. (setq node (if (setq leftp (avl-tree--node-right node))
  5735. (avl-tree--node-right node)
  5736. (pop stack)))))))
  5737. ;; We reached end of tree: synchronization complete.
  5738. t))
  5739. (org-element--cache-log-message
  5740. "org-element-cache: Finished process. The cache size is %S. The remaining sync requests: %S"
  5741. org-element--cache-size
  5742. (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests))))
  5743. (defsubst org-element--open-end-p (element)
  5744. "Check if ELEMENT in current buffer contains extra blank lines after
  5745. it and does not have closing term.
  5746. Examples of such elements are: section, headline, org-data,
  5747. and footnote-definition."
  5748. (and (org-element-property :contents-end element)
  5749. (= (org-element-property :contents-end element)
  5750. (save-excursion
  5751. (goto-char (org-element-property :end element))
  5752. (skip-chars-backward " \r\n\t")
  5753. (line-beginning-position 2)))))
  5754. (defun org-element--parse-to (pos &optional syncp time-limit)
  5755. "Parse elements in current section, down to POS.
  5756. Start parsing from the closest between the last known element in
  5757. cache or headline above. Return the smallest element containing
  5758. POS.
  5759. When optional argument SYNCP is non-nil, return the parent of the
  5760. element containing POS instead. In that case, it is also
  5761. possible to provide TIME-LIMIT, which is a time value specifying
  5762. when the parsing should stop. The function throws
  5763. `org-element--cache-interrupt' if the process stopped before finding
  5764. the expected result."
  5765. (catch 'exit
  5766. (save-match-data
  5767. (org-with-wide-buffer
  5768. (goto-char pos)
  5769. (save-excursion
  5770. (end-of-line)
  5771. (skip-chars-backward " \r\t\n")
  5772. ;; Within blank lines at the beginning of buffer, return nil.
  5773. (when (bobp) (throw 'exit nil)))
  5774. (let* ((cached (and (org-element--cache-active-p)
  5775. (org-element--cache-find pos nil)))
  5776. (mode (org-element-property :mode cached))
  5777. element next)
  5778. (cond
  5779. ;; Nothing in cache before point: start parsing from first
  5780. ;; element in buffer down to POS or from the beginning of the
  5781. ;; file.
  5782. ((and (not cached) (org-element--cache-active-p))
  5783. (setq element (org-element-org-data-parser))
  5784. (unless (org-element-property :begin element)
  5785. (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
  5786. (org-element--cache-log-message
  5787. "Nothing in cache. Adding org-data: %S"
  5788. (org-element--format-element element))
  5789. (org-element--cache-put element)
  5790. (goto-char (org-element-property :contents-begin element))
  5791. (setq mode 'org-data))
  5792. ;; Nothing in cache before point because cache is not active.
  5793. ;; Parse from previous heading to avoid re-parsing the whole
  5794. ;; buffer above. This comes at the cost of not calculating
  5795. ;; `:parent' property for headings.
  5796. ((not cached)
  5797. (if (org-with-limited-levels (outline-previous-heading))
  5798. (progn
  5799. (setq element (org-element-headline-parser nil 'fast))
  5800. (setq mode 'planning)
  5801. (forward-line))
  5802. (setq element (org-element-org-data-parser))
  5803. (setq mode 'org-data))
  5804. (org-skip-whitespace)
  5805. (beginning-of-line))
  5806. ;; Check if CACHED or any of its ancestors contain point.
  5807. ;;
  5808. ;; If there is such an element, we inspect it in order to know
  5809. ;; if we return it or if we need to parse its contents.
  5810. ;; Otherwise, we just start parsing from location, which is
  5811. ;; right after the top-most element containing CACHED but
  5812. ;; still before POS.
  5813. ;;
  5814. ;; As a special case, if POS is at the end of the buffer, we
  5815. ;; want to return the innermost element ending there.
  5816. ;;
  5817. ;; Also, if we find an ancestor and discover that we need to
  5818. ;; parse its contents, make sure we don't start from
  5819. ;; `:contents-begin', as we would otherwise go past CACHED
  5820. ;; again. Instead, in that situation, we will resume parsing
  5821. ;; from NEXT, which is located after CACHED or its higher
  5822. ;; ancestor not containing point.
  5823. (t
  5824. (let ((up cached)
  5825. (pos (if (= (point-max) pos) (1- pos) pos)))
  5826. (while (and up (<= (org-element-property :end up) pos))
  5827. (goto-char (org-element-property :end up))
  5828. (setq element up
  5829. mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
  5830. up (org-element-property :parent up)
  5831. next (point)))
  5832. (when up (setq element up)))))
  5833. ;; Parse successively each element until we reach POS.
  5834. (let ((end (or (org-element-property :end element) (point-max)))
  5835. (parent (org-element-property :parent element)))
  5836. (while t
  5837. (when (org-element--cache-interrupt-p time-limit)
  5838. (throw 'org-element--cache-interrupt nil))
  5839. (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
  5840. (when quit-flag
  5841. (cl-incf org-element--cache-interrupt-C-g-count)
  5842. (setq quit-flag nil))
  5843. (when (>= org-element--cache-interrupt-C-g-count
  5844. org-element--cache-interrupt-C-g-max-count)
  5845. (setq quit-flag t)
  5846. (setq org-element--cache-interrupt-C-g-count 0)
  5847. (org-element-cache-reset)
  5848. (error "org-element: Parsing aborted by user. Cache has been cleared.
  5849. If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
  5850. (message (substitute-command-keys
  5851. "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
  5852. (- org-element--cache-interrupt-C-g-max-count
  5853. org-element--cache-interrupt-C-g-count)))
  5854. (unless element
  5855. ;; Do not try to parse within blank at EOB.
  5856. (unless (save-excursion
  5857. (org-skip-whitespace)
  5858. (eobp))
  5859. (org-element-with-disabled-cache
  5860. (setq element (org-element--current-element
  5861. end 'element mode
  5862. (org-element-property :structure parent)))))
  5863. ;; Make sure that we return referenced element in cache
  5864. ;; that can be altered directly.
  5865. (if element
  5866. (setq element (or (org-element--cache-put element) element))
  5867. ;; Nothing to parse (i.e. empty file).
  5868. (throw 'exit parent))
  5869. (unless (or (not (org-element--cache-active-p)) parent)
  5870. (org-element--cache-warn
  5871. "Got empty parent while parsing. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n Backtrace:\n%S"
  5872. (when (and (fboundp 'backtrace-get-frames)
  5873. (fboundp 'backtrace-to-string))
  5874. (backtrace-to-string (backtrace-get-frames 'backtrace))
  5875. (org-element-cache-reset)
  5876. (error "org-element--cache: Emergency exit"))))
  5877. (org-element-put-property element :parent parent))
  5878. (let ((elem-end (org-element-property :end element))
  5879. (type (org-element-type element)))
  5880. (cond
  5881. ;; Skip any element ending before point. Also skip
  5882. ;; element ending at point (unless it is also the end of
  5883. ;; buffer) since we're sure that another element begins
  5884. ;; after it.
  5885. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5886. ;; Avoid parsing headline siblings above.
  5887. (goto-char elem-end)
  5888. (when (eq type 'headline)
  5889. (save-match-data
  5890. (unless (when (and (/= 1 (org-element-property :level element))
  5891. (re-search-forward
  5892. (rx-to-string
  5893. `(and bol (repeat 1 ,(1- (let ((level (org-element-property :level element)))
  5894. (if org-odd-levels-only (1- (* level 2)) level)))
  5895. "*")
  5896. " "))
  5897. pos t))
  5898. (beginning-of-line)
  5899. t)
  5900. ;; There are headings with lower level than
  5901. ;; ELEMENT between ELEM-END and POS. Siblings
  5902. ;; may exist though. Parse starting from the
  5903. ;; last sibling or from ELEM-END if there are
  5904. ;; no other siblings.
  5905. (goto-char pos)
  5906. (unless
  5907. (re-search-backward
  5908. (rx-to-string
  5909. `(and bol (repeat ,(let ((level (org-element-property :level element)))
  5910. (if org-odd-levels-only (1- (* level 2)) level))
  5911. "*")
  5912. " "))
  5913. elem-end t)
  5914. ;; Roll-back to normal parsing.
  5915. (goto-char elem-end)))))
  5916. (setq mode (org-element--next-mode mode type nil)))
  5917. ;; A non-greater element contains point: return it.
  5918. ((not (memq type org-element-greater-elements))
  5919. (throw 'exit (if syncp parent element)))
  5920. ;; Otherwise, we have to decide if ELEMENT really
  5921. ;; contains POS. In that case we start parsing from
  5922. ;; contents' beginning.
  5923. ;;
  5924. ;; If POS is at contents' beginning but it is also at
  5925. ;; the beginning of the first item in a list or a table.
  5926. ;; In that case, we need to create an anchor for that
  5927. ;; list or table, so return it.
  5928. ;;
  5929. ;; Also, if POS is at the end of the buffer, no element
  5930. ;; can start after it, but more than one may end there.
  5931. ;; Arbitrarily, we choose to return the innermost of
  5932. ;; such elements.
  5933. ((let ((cbeg (org-element-property :contents-begin element))
  5934. (cend (org-element-property :contents-end element)))
  5935. (when (and cbeg cend
  5936. (or (< cbeg pos)
  5937. (and (= cbeg pos)
  5938. (not (memq type '(plain-list table)))))
  5939. (or (> cend pos)
  5940. ;; When we are at cend or within blank
  5941. ;; lines after, it is a special case:
  5942. ;; 1. At the end of buffer we return
  5943. ;; the innermost element.
  5944. ;; 2. At cend of element with return
  5945. ;; that element.
  5946. ;; 3. At the end of element, we would
  5947. ;; return in the earlier cond form.
  5948. ;; 4. Within blank lines after cend,
  5949. ;; when element does not have a
  5950. ;; closing keyword, we return that
  5951. ;; outermost element, unless the
  5952. ;; outermost element is a non-empty
  5953. ;; headline. In the latter case, we
  5954. ;; return the outermost element inside
  5955. ;; the headline section.
  5956. (and (org-element--open-end-p element)
  5957. (or (= (org-element-property :end element) (point-max))
  5958. (and (>= pos (org-element-property :contents-end element))
  5959. (memq (org-element-type element) '(org-data section headline)))))))
  5960. (goto-char (or next cbeg))
  5961. (setq mode (if next mode (org-element--next-mode mode type t))
  5962. next nil
  5963. parent element
  5964. end (if (org-element--open-end-p element)
  5965. (org-element-property :end element)
  5966. (org-element-property :contents-end element))))))
  5967. ;; Otherwise, return ELEMENT as it is the smallest
  5968. ;; element containing POS.
  5969. (t (throw 'exit (if syncp parent element)))))
  5970. (setq element nil))))))))
  5971. ;;;; Staging Buffer Changes
  5972. (defconst org-element--cache-sensitive-re
  5973. (concat
  5974. "^\\*+ " "\\|"
  5975. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5976. "^[ \t]*\\(?:"
  5977. "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
  5978. org-list-full-item-re "\\|"
  5979. ":\\(?: \\|$\\)" "\\|"
  5980. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  5981. "\\)")
  5982. "Regexp matching a sensitive line, structure wise.
  5983. A sensitive line is a headline, inlinetask, block, drawer, or
  5984. latex-environment boundary. When such a line is modified,
  5985. structure changes in the document may propagate in the whole
  5986. section, possibly making cache invalid.")
  5987. (defun org-element--cache-before-change (beg end)
  5988. "Detect modifications in sensitive parts of Org buffer.
  5989. BEG and END are the beginning and end of the range of changed
  5990. text. See `before-change-functions' for more information.
  5991. The function returns the new value of `org-element--cache-change-warning'."
  5992. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  5993. (current-buffer))
  5994. (when (org-element--cache-active-p t)
  5995. (org-with-wide-buffer
  5996. (setq org-element--cache-change-tic (buffer-chars-modified-tick))
  5997. (setq org-element--cache-last-buffer-size (buffer-size))
  5998. (goto-char beg)
  5999. (beginning-of-line)
  6000. (let ((bottom (save-excursion
  6001. (goto-char end)
  6002. (if (and (bolp)
  6003. ;; When beg == end, still extent to eol.
  6004. (> (point) beg))
  6005. ;; FIXME: Potential pitfall.
  6006. ;; We are appending to an element end.
  6007. ;; Unless the last inserted char is not
  6008. ;; newline, the next element is not broken
  6009. ;; and does not need to be purged from the
  6010. ;; cache.
  6011. end
  6012. (line-end-position)))))
  6013. (prog1
  6014. ;; Use the worst change warning to not miss important edits.
  6015. ;; This function is called before edit and after edit by
  6016. ;; `org-element--cache-after-change'. Before the edit, we still
  6017. ;; want to use the old value if it comes from previous
  6018. ;; not yet processed edit (they may be merged by
  6019. ;; `org-element--cache-submit-request'). After the edit, we want to
  6020. ;; look if there was a sensitive removed during edit.
  6021. ;; FIXME: This is not the most efficient way and we now
  6022. ;; have to delete more elements than needed in some
  6023. ;; cases. A better approach may be storing the warning
  6024. ;; in the modification request itself.
  6025. (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
  6026. (org-element--cache-change-warning-after))
  6027. (setq org-element--cache-change-warning-after
  6028. (save-match-data
  6029. (let ((case-fold-search t))
  6030. (when (re-search-forward
  6031. org-element--cache-sensitive-re bottom t)
  6032. (goto-char beg)
  6033. (beginning-of-line)
  6034. (let (min-level)
  6035. (cl-loop while (re-search-forward
  6036. (rx-to-string
  6037. (if (and min-level
  6038. (> min-level 1))
  6039. `(and bol (repeat 1 ,(1- min-level) "*") " ")
  6040. `(and bol (+ "*") " ")))
  6041. bottom t)
  6042. do (setq min-level (1- (length (match-string 0))))
  6043. until (= min-level 1))
  6044. (goto-char beg)
  6045. (beginning-of-line)
  6046. (or (and min-level (org-reduced-level min-level))
  6047. (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
  6048. 'org-data)
  6049. t))))))
  6050. (setq org-element--cache-change-warning
  6051. (cond
  6052. ((and (numberp org-element--cache-change-warning-before)
  6053. (numberp org-element--cache-change-warning-after))
  6054. (min org-element--cache-change-warning-after
  6055. org-element--cache-change-warning-before))
  6056. ((numberp org-element--cache-change-warning-before)
  6057. org-element--cache-change-warning-before)
  6058. ((numberp org-element--cache-change-warning-after)
  6059. org-element--cache-change-warning-after)
  6060. (t (or org-element--cache-change-warning-after
  6061. org-element--cache-change-warning-before)))))
  6062. (org-element--cache-log-message
  6063. "%S is about to modify text: warning %S"
  6064. this-command
  6065. org-element--cache-change-warning)))))))
  6066. (defun org-element--cache-after-change (beg end pre)
  6067. "Update buffer modifications for current buffer.
  6068. BEG and END are the beginning and end of the range of changed
  6069. text, and the length in bytes of the pre-change text replaced by
  6070. that range. See `after-change-functions' for more information."
  6071. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6072. (current-buffer))
  6073. (when (org-element--cache-active-p t)
  6074. (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
  6075. (org-element--cache-log-message "After change")
  6076. (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
  6077. ;; If beg is right after spaces in front of an element, we
  6078. ;; risk affecting previous element, so move beg to bol, making
  6079. ;; sure that we capture preceding element.
  6080. (setq beg (save-excursion
  6081. (goto-char beg)
  6082. (cl-incf pre (- beg (line-beginning-position)))
  6083. (line-beginning-position)))
  6084. ;; Store synchronization request.
  6085. (let ((offset (- end beg pre)))
  6086. (save-match-data
  6087. (org-element--cache-submit-request beg (- end offset) offset)))
  6088. ;; Activate a timer to process the request during idle time.
  6089. (org-element--cache-set-timer (current-buffer))))))
  6090. (defun org-element--cache-setup-change-functions ()
  6091. "Setup `before-change-functions' and `after-change-functions'."
  6092. (when (and (derived-mode-p 'org-mode) org-element-use-cache)
  6093. (add-hook 'before-change-functions
  6094. #'org-element--cache-before-change nil t)
  6095. ;; Run `org-element--cache-after-change' early to handle cases
  6096. ;; when other `after-change-functions' require element cache.
  6097. (add-hook 'after-change-functions
  6098. #'org-element--cache-after-change -1 t)))
  6099. (defvar org-element--cache-avoid-synchronous-headline-re-parsing nil
  6100. "This variable controls how buffer changes are handled by the cache.
  6101. By default (when this variable is nil), cache re-parses modified
  6102. headlines immediately after modification preserving all the unaffected
  6103. elements inside the headline.
  6104. The default behaviour works best when users types inside Org buffer of
  6105. when buffer modifications are mixed with cache requests. However,
  6106. large automated edits inserting/deleting many headlines are somewhat
  6107. slower by default (as in `org-archive-subtree'). Let-binding this
  6108. variable to non-nil will reduce cache latency after every singular edit
  6109. (`after-change-functions') at the cost of slower cache queries.")
  6110. (defun org-element--cache-for-removal (beg end offset)
  6111. "Return first element to remove from cache.
  6112. BEG and END are buffer positions delimiting buffer modifications.
  6113. OFFSET is the size of the changes.
  6114. Returned element is usually the first element in cache containing
  6115. any position between BEG and END. As an exception, greater
  6116. elements around the changes that are robust to contents
  6117. modifications are preserved and updated according to the
  6118. changes. In the latter case, the returned element is the outermost
  6119. non-robust element affected by the changes. Note that the returned
  6120. element may end before END position in which case some cached element
  6121. starting after the returned may still be affected by the changes.
  6122. Also, when there are no elements in cache before BEG, return first
  6123. known element in cache (it may start after END)."
  6124. (let* ((elements (org-element--cache-find (1- beg) 'both))
  6125. (before (car elements))
  6126. (after (cdr elements)))
  6127. (if (not before) after
  6128. ;; If BEFORE is a keyword, it may need to be removed to become
  6129. ;; an affiliated keyword.
  6130. (when (eq 'keyword (org-element-type before))
  6131. (let ((prev before))
  6132. (while (eq 'keyword (org-element-type prev))
  6133. (setq before prev
  6134. beg (org-element-property :begin prev))
  6135. (setq prev (org-element--cache-find (1- (org-element-property :begin before)))))))
  6136. (let ((up before)
  6137. (robust-flag t))
  6138. (while up
  6139. (if (let ((type (org-element-type up)))
  6140. (or (and (memq type '( center-block dynamic-block
  6141. quote-block special-block
  6142. drawer))
  6143. (or (not (eq type 'drawer))
  6144. (not (string= "PROPERTIES" (org-element-property :drawer-name up))))
  6145. ;; Sensitive change. This is
  6146. ;; unconditionally non-robust change.
  6147. (not org-element--cache-change-warning)
  6148. (let ((cbeg (org-element-property :contents-begin up))
  6149. (cend (org-element-property :contents-end up)))
  6150. (and cbeg
  6151. (<= cbeg beg)
  6152. (or (> cend end)
  6153. (and (= cend end)
  6154. (= (+ end offset) (point-max)))))))
  6155. (and (memq type '(headline section org-data))
  6156. (let ((rbeg (org-element-property :robust-begin up))
  6157. (rend (org-element-property :robust-end up)))
  6158. (and rbeg rend
  6159. (<= rbeg beg)
  6160. (or (> rend end)
  6161. (and (= rend end)
  6162. (= (+ end offset) (point-max))))))
  6163. (pcase type
  6164. ;; Sensitive change in section. Need to
  6165. ;; re-parse.
  6166. (`section (not org-element--cache-change-warning))
  6167. ;; Headline might be inserted. This is non-robust
  6168. ;; change when `up' is a `headline' or `section'
  6169. ;; with `>' level compared to the inserted headline.
  6170. ;;
  6171. ;; Also, planning info/property drawer
  6172. ;; could have been inserted. It is not
  6173. ;; robust change then.
  6174. (`headline
  6175. (and
  6176. (or (not (numberp org-element--cache-change-warning))
  6177. (> org-element--cache-change-warning
  6178. (org-element-property :level up)))
  6179. (org-with-point-at (org-element-property :contents-begin up)
  6180. (unless
  6181. (save-match-data
  6182. (when (looking-at-p org-element-planning-line-re)
  6183. (forward-line))
  6184. (when (looking-at org-property-drawer-re)
  6185. (< beg (match-end 0))))
  6186. 'robust))))
  6187. (`org-data (and (not (eq org-element--cache-change-warning 'org-data))
  6188. ;; Property drawer could
  6189. ;; have been inserted. It
  6190. ;; is not robust change
  6191. ;; then.
  6192. (org-with-wide-buffer
  6193. (goto-char (point-min))
  6194. (while (and (org-at-comment-p) (bolp)) (forward-line))
  6195. ;; Should not see property
  6196. ;; drawer within changed
  6197. ;; region.
  6198. (save-match-data
  6199. (or (not (looking-at org-property-drawer-re))
  6200. (> beg (match-end 0)))))))
  6201. (_ 'robust)))))
  6202. ;; UP is a robust greater element containing changes.
  6203. ;; We only need to extend its ending boundaries.
  6204. (progn
  6205. (org-element--cache-shift-positions
  6206. up offset
  6207. (if (and (org-element-property :robust-begin up)
  6208. (org-element-property :robust-end up))
  6209. '(:contents-end :end :robust-end)
  6210. '(:contents-end :end)))
  6211. (org-element--cache-log-message
  6212. "Shifting end positions of robust parent: %S"
  6213. (org-element--format-element up)))
  6214. (unless (or
  6215. ;; UP is non-robust. Yet, if UP is headline, flagging
  6216. ;; everything inside for removal may be to
  6217. ;; costly. Instead, we should better re-parse only the
  6218. ;; headline itself when possible. If a headline is still
  6219. ;; starting from old :begin position, we do not care that
  6220. ;; its boundaries could have extended to shrunk - we
  6221. ;; will re-parent and shift them anyway.
  6222. (and (eq 'headline (org-element-type up))
  6223. (not org-element--cache-avoid-synchronous-headline-re-parsing)
  6224. ;; The change is not inside headline. Not
  6225. ;; updating here.
  6226. (not (<= beg (org-element-property :begin up)))
  6227. (not (> end (org-element-property :end up)))
  6228. (let ((current (org-with-point-at (org-element-property :begin up)
  6229. (org-element-with-disabled-cache
  6230. (and (looking-at-p org-element-headline-re)
  6231. (org-element-headline-parser))))))
  6232. (when (eq 'headline (org-element-type current))
  6233. (org-element--cache-log-message
  6234. "Found non-robust headline that can be updated individually: %S"
  6235. (org-element--format-element current))
  6236. (org-element-set-element up current)
  6237. t)))
  6238. ;; If UP is org-data, the situation is similar to
  6239. ;; headline case. We just need to re-parse the
  6240. ;; org-data itself, unless the change is made
  6241. ;; within blank lines at BOB (that could
  6242. ;; potentially alter first-section).
  6243. (when (and (eq 'org-data (org-element-type up))
  6244. (>= beg (org-element-property :contents-begin up)))
  6245. (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
  6246. (org-element--cache-log-message
  6247. "Found non-robust change invalidating org-data. Re-parsing: %S"
  6248. (org-element--format-element up))
  6249. t))
  6250. (org-element--cache-log-message
  6251. "Found non-robust element: %S"
  6252. (org-element--format-element up))
  6253. (setq before up)
  6254. (when robust-flag (setq robust-flag nil))))
  6255. (unless (or (org-element-property :parent up)
  6256. (eq 'org-data (org-element-type up)))
  6257. (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)
  6258. (org-element-cache-reset)
  6259. (error "org-element--cache: Emergency exit"))
  6260. (setq up (org-element-property :parent up)))
  6261. ;; We're at top level element containing ELEMENT: if it's
  6262. ;; altered by buffer modifications, it is first element in
  6263. ;; cache to be removed. Otherwise, that first element is the
  6264. ;; following one.
  6265. ;;
  6266. ;; As a special case, do not remove BEFORE if it is a robust
  6267. ;; container for current changes.
  6268. (if (or (< (org-element-property :end before) beg) robust-flag) after
  6269. before)))))
  6270. (defun org-element--cache-submit-request (beg end offset)
  6271. "Submit a new cache synchronization request for current buffer.
  6272. BEG and END are buffer positions delimiting the minimal area
  6273. where cache data should be removed. OFFSET is the size of the
  6274. change, as an integer."
  6275. (org-element--cache-log-message
  6276. "Submitting new synchronization request for [%S..%S]𝝙%S"
  6277. beg end offset)
  6278. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6279. (current-buffer))
  6280. (let ((next (car org-element--cache-sync-requests))
  6281. delete-to delete-from)
  6282. (if (and next
  6283. ;; First existing sync request is in phase 0.
  6284. (= 0 (org-element--request-phase next))
  6285. ;; Current changes intersect with the first sync request.
  6286. (> (setq delete-to (+ (org-element--request-end next)
  6287. (org-element--request-offset next)))
  6288. end)
  6289. (<= (setq delete-from (org-element--request-beg next))
  6290. end))
  6291. ;; Current changes can be merged with first sync request: we
  6292. ;; can save a partial cache synchronization.
  6293. (progn
  6294. (org-element--cache-log-message "Found another phase 0 request intersecting with current")
  6295. ;; Update OFFSET of the existing request.
  6296. (cl-incf (org-element--request-offset next) offset)
  6297. ;; If last change happened within area to be removed, extend
  6298. ;; boundaries of robust parents, if any. Otherwise, find
  6299. ;; first element to remove and update request accordingly.
  6300. (if (> beg delete-from)
  6301. ;; The current modification is completely inside NEXT.
  6302. ;; We already added the current OFFSET to the NEXT
  6303. ;; request. However, the robust elements around
  6304. ;; modifications also need to be shifted. Moreover, the
  6305. ;; new modification may also have non-nil
  6306. ;; `org-element--cache-change-warning'. In the latter case, we
  6307. ;; also need to update the request.
  6308. (let ((first (org-element--cache-for-removal delete-from end offset) ; Shift as needed.
  6309. ))
  6310. (org-element--cache-log-message
  6311. "Current request is inside next. Candidate parent: %S"
  6312. (org-element--format-element first))
  6313. (when
  6314. ;; Non-robust element is now before NEXT. Need to
  6315. ;; update.
  6316. (and first
  6317. (org-element--cache-key-less-p
  6318. (org-element--cache-key first)
  6319. (org-element--request-key next)))
  6320. (org-element--cache-log-message
  6321. "Current request is inside next. New parent: %S"
  6322. (org-element--format-element first))
  6323. (setf (org-element--request-key next)
  6324. (org-element--cache-key first))
  6325. (setf (org-element--request-beg next)
  6326. (org-element-property :begin first))
  6327. (setf (org-element--request-end next)
  6328. (max (org-element-property :end first)
  6329. (org-element--request-end next)))
  6330. (setf (org-element--request-parent next)
  6331. (org-element-property :parent first))))
  6332. ;; The current and NEXT modifications are intersecting
  6333. ;; with current modification starting before NEXT and NEXT
  6334. ;; ending after current. We need to update the common
  6335. ;; non-robust parent for the new extended modification
  6336. ;; region.
  6337. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  6338. (org-element--cache-log-message
  6339. "Current request intersects with next. Candidate parent: %S"
  6340. (org-element--format-element first))
  6341. (when (and first
  6342. (org-element--cache-key-less-p
  6343. (org-element--cache-key first)
  6344. (org-element--request-key next)))
  6345. (org-element--cache-log-message
  6346. "Current request intersects with next. Updating. New parent: %S"
  6347. (org-element--format-element first))
  6348. (setf (org-element--request-key next) (org-element--cache-key first))
  6349. (setf (org-element--request-beg next) (org-element-property :begin first))
  6350. (setf (org-element--request-end next)
  6351. (max (org-element-property :end first)
  6352. (org-element--request-end next)))
  6353. (setf (org-element--request-parent next) (org-element-property :parent first))))))
  6354. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  6355. ;; if any, is no longer a 0-phase request, thus ensuring that
  6356. ;; phases are properly ordered. We need to provide OFFSET as
  6357. ;; optional parameter since current modifications are not known
  6358. ;; yet to the otherwise correct part of the cache (i.e, before
  6359. ;; the first request).
  6360. (org-element--cache-log-message "Adding new phase 0 request")
  6361. (when next (org-element--cache-sync (current-buffer) end beg offset))
  6362. (let ((first (org-element--cache-for-removal beg end offset)))
  6363. (if first
  6364. (push (let ((first-beg (org-element-property :begin first))
  6365. (key (org-element--cache-key first)))
  6366. (cond
  6367. ;; When changes happen before the first known
  6368. ;; element, re-parent and shift the rest of the
  6369. ;; cache.
  6370. ((> first-beg end)
  6371. (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
  6372. (vector key first-beg nil offset nil 1))
  6373. ;; Otherwise, we find the first non robust
  6374. ;; element containing END. All elements between
  6375. ;; FIRST and this one are to be removed.
  6376. ;;
  6377. ;; The current modification is completely inside
  6378. ;; FIRST. Clear and update cached elements in
  6379. ;; region containing FIRST.
  6380. ((let ((first-end (org-element-property :end first)))
  6381. (when (> first-end end)
  6382. (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
  6383. (vector key first-beg first-end offset (org-element-property :parent first) 0))))
  6384. (t
  6385. ;; Now, FIRST is the first element after BEG or
  6386. ;; non-robust element containing BEG. However,
  6387. ;; FIRST ends before END and there might be
  6388. ;; another ELEMENT before END that spans beyond
  6389. ;; END. If there is such element, we need to
  6390. ;; extend the region down to end of the common
  6391. ;; parent of FIRST and everything inside
  6392. ;; BEG..END.
  6393. (let* ((element (org-element--cache-find end))
  6394. (element-end (org-element-property :end element))
  6395. (up element))
  6396. (while (and (not (eq up first))
  6397. (setq up (org-element-property :parent up))
  6398. (>= (org-element-property :begin up) first-beg))
  6399. ;; Note that UP might have been already
  6400. ;; shifted if it is a robust element. After
  6401. ;; deletion, it can put it's end before yet
  6402. ;; unprocessed ELEMENT.
  6403. (setq element-end (max (org-element-property :end up) element-end)
  6404. element up))
  6405. ;; Extend region to remove elements between
  6406. ;; beginning of first and the end of outermost
  6407. ;; element starting before END but after
  6408. ;; beginning of first.
  6409. ;; of the FIRST.
  6410. (org-element--cache-log-message
  6411. "Extending to all elements between:\n 1: %S\n 2: %S"
  6412. (org-element--format-element first)
  6413. (org-element--format-element element))
  6414. (vector key first-beg element-end offset up 0)))))
  6415. org-element--cache-sync-requests)
  6416. ;; No element to remove. No need to re-parent either.
  6417. ;; Simply shift additional elements, if any, by OFFSET.
  6418. (if org-element--cache-sync-requests
  6419. (progn
  6420. (org-element--cache-log-message
  6421. "Nothing to remove. Updating offset of the next request by 𝝙%S: %S"
  6422. offset
  6423. (let ((print-level 3))
  6424. (car org-element--cache-sync-requests)))
  6425. (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
  6426. offset))
  6427. (org-element--cache-log-message
  6428. "Nothing to remove. No elements in cache after %S. Terminating."
  6429. end))))))
  6430. (setq org-element--cache-change-warning nil)))
  6431. (defun org-element--cache-verify-element (element)
  6432. "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
  6433. Return non-nil when verification failed."
  6434. ;; Verify correct parent for the element.
  6435. (unless (or (org-element-property :parent element)
  6436. (eq 'org-data (org-element-type element)))
  6437. (org-element--cache-warn "Got element without parent (cache active?: %S). Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" (org-element--cache-active-p) element)
  6438. (org-element-cache-reset))
  6439. (let ((org-element--cache-self-verify
  6440. (or org-element--cache-self-verify
  6441. (and (boundp 'org-batch-test) org-batch-test)))
  6442. (org-element--cache-self-verify-frequency
  6443. (if (and (boundp 'org-batch-test) org-batch-test)
  6444. 1
  6445. org-element--cache-self-verify-frequency)))
  6446. (when (and org-element--cache-self-verify
  6447. (org-element--cache-active-p)
  6448. (derived-mode-p 'org-mode)
  6449. (org-element-property :parent element)
  6450. (eq 'headline (org-element-type element))
  6451. ;; Avoid too much slowdown
  6452. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6453. (org-with-point-at (org-element-property :begin element)
  6454. (org-element-with-disabled-cache (org-up-heading-or-point-min))
  6455. (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
  6456. (eq (point) (point-min)))
  6457. (org-element--cache-warn
  6458. "Cached element has wrong parent in %s. Resetting.
  6459. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6460. The element is: %S\n The parent is: %S\n The real parent is: %S"
  6461. (buffer-name (current-buffer))
  6462. (org-element--format-element element)
  6463. (org-element--format-element (org-element-property :parent element))
  6464. (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
  6465. (org-element-cache-reset))
  6466. (org-element--cache-verify-element (org-element-property :parent element))))
  6467. ;; Verify the element itself.
  6468. (when (and org-element--cache-self-verify
  6469. (org-element--cache-active-p)
  6470. element
  6471. (not (memq (org-element-type element) '(section org-data)))
  6472. ;; Avoid too much slowdown
  6473. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6474. (let ((real-element (let (org-element-use-cache)
  6475. (org-element--parse-to
  6476. (if (memq (org-element-type element) '(table-row item))
  6477. (1+ (org-element-property :begin element))
  6478. (org-element-property :begin element))))))
  6479. (unless (and (eq (org-element-type real-element) (org-element-type element))
  6480. (eq (org-element-property :begin real-element) (org-element-property :begin element))
  6481. (eq (org-element-property :end real-element) (org-element-property :end element))
  6482. (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
  6483. (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
  6484. (or (not (org-element-property :ID real-element))
  6485. (string= (org-element-property :ID real-element) (org-element-property :ID element))))
  6486. (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
  6487. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6488. The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
  6489. this-command
  6490. (buffer-name (current-buffer))
  6491. (if (/= org-element--cache-change-tic
  6492. (buffer-chars-modified-tick))
  6493. "no" "yes")
  6494. (org-element--format-element element)
  6495. (org-element--format-element real-element)
  6496. (org-element--cache-find (1- (org-element-property :begin real-element)))
  6497. (car (org-element--cache-find (org-element-property :begin real-element) 'both))
  6498. (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
  6499. (org-element-cache-reset))))))
  6500. ;;; Cache persistence
  6501. (defun org-element--cache-persist-before-write (container &optional associated)
  6502. "Sync cache before saving."
  6503. (when (equal container '(elisp org-element--cache))
  6504. (if (and org-element-use-cache
  6505. (plist-get associated :file)
  6506. (get-file-buffer (plist-get associated :file))
  6507. org-element-cache-persistent)
  6508. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6509. (if (and (derived-mode-p 'org-mode)
  6510. org-element--cache)
  6511. (org-with-wide-buffer
  6512. (org-element--cache-sync (current-buffer) (point-max))
  6513. ;; Cleanup cache request keys to avoid collisions during next
  6514. ;; Emacs session.
  6515. (avl-tree-mapc
  6516. (lambda (el)
  6517. (org-element-put-property el :org-element--cache-sync-key nil))
  6518. org-element--cache)
  6519. nil)
  6520. 'forbid))
  6521. 'forbid)))
  6522. (defun org-element--cache-persist-before-read (container &optional associated)
  6523. "Avoid reading cache before Org mode is loaded."
  6524. (when (equal container '(elisp org-element--cache))
  6525. (if (not (and (plist-get associated :file)
  6526. (get-file-buffer (plist-get associated :file))))
  6527. 'forbid
  6528. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6529. (unless (and org-element-use-cache
  6530. org-element-cache-persistent
  6531. (derived-mode-p 'org-mode)
  6532. (equal (secure-hash 'md5 (current-buffer))
  6533. (plist-get associated :hash)))
  6534. 'forbid)))))
  6535. (defun org-element--cache-persist-after-read (container &optional associated)
  6536. "Setup restored cache."
  6537. (when (and (plist-get associated :file)
  6538. (get-file-buffer (plist-get associated :file)))
  6539. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6540. (when (and org-element-use-cache org-element-cache-persistent)
  6541. (when (and (equal container '(elisp org-element--cache)) org-element--cache)
  6542. (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
  6543. (when (and (equal container '(elisp org-element--headline-cache)) org-element--headline-cache)
  6544. (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache)))))))
  6545. (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
  6546. (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
  6547. (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
  6548. ;;;; Public Functions
  6549. (defvar-local org-element--cache-gapless nil
  6550. "An alist containing (granularity . `org-element--cache-change-tic') elements.
  6551. Each element indicates the latest `org-element--cache-change-tic' when
  6552. change did not contain gaps.")
  6553. ;;;###autoload
  6554. (defun org-element-cache-reset (&optional all)
  6555. "Reset cache in current buffer.
  6556. When optional argument ALL is non-nil, reset cache in all Org
  6557. buffers."
  6558. (interactive "P")
  6559. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  6560. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  6561. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  6562. (when (not org-element-cache-persistent)
  6563. (org-persist-unregister 'org-element--headline-cache (current-buffer))
  6564. (org-persist-unregister 'org-element--cache (current-buffer)))
  6565. (when (and org-element-cache-persistent
  6566. (buffer-file-name (current-buffer)))
  6567. (org-persist-register 'org-element--cache (current-buffer))
  6568. (org-persist-register 'org-element--headline-cache
  6569. (current-buffer)
  6570. :inherit 'org-element--cache))
  6571. (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
  6572. (setq-local org-element--cache-last-buffer-size (buffer-size))
  6573. (setq-local org-element--cache-gapless nil)
  6574. (setq-local org-element--cache
  6575. (avl-tree-create #'org-element--cache-compare))
  6576. (setq-local org-element--headline-cache
  6577. (avl-tree-create #'org-element--cache-compare))
  6578. (setq-local org-element--cache-hash-left (make-vector org-element--cache-hash-size nil))
  6579. (setq-local org-element--cache-hash-right (make-vector org-element--cache-hash-size nil))
  6580. (setq-local org-element--cache-size 0)
  6581. (setq-local org-element--headline-cache-size 0)
  6582. (setq-local org-element--cache-sync-keys-value 0)
  6583. (setq-local org-element--cache-change-warning nil)
  6584. (setq-local org-element--cache-sync-requests nil)
  6585. (setq-local org-element--cache-sync-timer nil)
  6586. (org-element--cache-setup-change-functions)
  6587. ;; Make sure that `org-element--cache-after-change' and
  6588. ;; `org-element--cache-before-change' are working inside properly created
  6589. ;; indirect buffers. Note that `clone-indirect-buffer-hook'
  6590. ;; will not work inside indirect buffers not created by
  6591. ;; calling `clone-indirect-buffer'. We consider that the code
  6592. ;; not using `clone-indirect-buffer' to be written with
  6593. ;; awareness about possible consequences.
  6594. (add-hook 'clone-indirect-buffer-hook
  6595. #'org-element--cache-setup-change-functions)))))
  6596. ;;;###autoload
  6597. (defun org-element-cache-refresh (pos)
  6598. "Refresh cache at position POS."
  6599. (when (org-element--cache-active-p)
  6600. (org-element--cache-sync (current-buffer) pos)
  6601. (org-element--cache-submit-request pos pos 0)
  6602. (org-element--cache-set-timer (current-buffer))))
  6603. (defvar warning-minimum-log-level) ; Defined in warning.el
  6604. (defvar org-element-cache-map--recurse nil)
  6605. (defvar org-element-cache-map-continue-from nil
  6606. "Position from where mapping should continue.
  6607. This variable can be set by called function, especially when the
  6608. function modified the buffer.")
  6609. ;;;###autoload
  6610. (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
  6611. next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
  6612. narrow)
  6613. "Map all elements in current buffer with FUNC according to
  6614. GRANULARITY. Collect non-nil return values into result list.
  6615. FUNC should accept a single argument - the element.
  6616. FUNC can modify the buffer, but doing so may reduce performance. If
  6617. buffer is modified, the mapping will continue from an element starting
  6618. after the last mapped element. If the last mapped element is deleted,
  6619. the subsequent element will be skipped as it cannot be distinguished
  6620. deterministically from a changed element. If FUNC is expected to
  6621. delete the element, it should directly set the value of
  6622. `org-element-cache-map-continue-from' to force `org-element-cache-map'
  6623. continue from the right point in buffer.
  6624. If some elements are not yet in cache, they will be added.
  6625. GRANULARITY can be `headline', `headline+inlinetask'
  6626. `greater-element', or `element'. The default is
  6627. `headline+inlinetask'. `object' granularity is not supported.
  6628. RESTRICT-ELEMENTS is a list of element types to be mapped over.
  6629. NEXT-RE is a regexp used to search next candidate match when FUNC
  6630. returns non-nil and to search the first candidate match. FAIL-RE is a
  6631. regexp used to search next candidate match when FUNC returns nil. The
  6632. mapping will continue starting from headline at the RE match.
  6633. FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
  6634. mapped elements to elements starting at of after FROM-POS but before
  6635. TO-POS.
  6636. AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
  6637. after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
  6638. map all the elements starting from first element inside section, but
  6639. not including the section).
  6640. LIMIT-COUNT limits mapping to that many first matches where FUNC
  6641. returns non-nil.
  6642. NARROW controls whether current buffer narrowing should be preserved.
  6643. This function does a subset of what `org-element-map' does, but with
  6644. much better performance. Cached elements are supplied as the single
  6645. argument of FUNC. Changes to elements made in FUNC will also alter
  6646. the cache."
  6647. (unless (org-element--cache-active-p)
  6648. (error "Cache must be active."))
  6649. (unless (memq granularity '( headline headline+inlinetask
  6650. greater-element element))
  6651. (error "Unsupported granularity: %S" granularity))
  6652. ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
  6653. ;; process.
  6654. (unless (markerp to-pos)
  6655. (let ((mk (make-marker)))
  6656. (set-marker mk to-pos)
  6657. (setq to-pos mk)))
  6658. ;; Make sure that garbage collector does not stand on the way to
  6659. ;; maximum performance.
  6660. (let ((gc-cons-threshold #x40000000)
  6661. ;; Bind variables used inside loop to avoid memory
  6662. ;; re-allocation on every iteration.
  6663. ;; See https://emacsconf.org/2021/talks/faster/
  6664. tmpnext-start tmpparent tmpelement)
  6665. (save-excursion
  6666. (save-restriction
  6667. (unless narrow (widen))
  6668. ;; Synchronise cache up to the end of mapped region.
  6669. (org-element-at-point to-pos)
  6670. (cl-macrolet ((cache-root
  6671. ;; Use the most optimal version of cache available.
  6672. () `(if (memq granularity '(headline headline+inlinetask))
  6673. (org-element--headline-cache-root)
  6674. (org-element--cache-root)))
  6675. (cache-size
  6676. ;; Use the most optimal version of cache available.
  6677. () `(if (memq granularity '(headline headline+inlinetask))
  6678. org-element--headline-cache-size
  6679. org-element--cache-size))
  6680. (cache-walk-restart
  6681. ;; Restart tree traversal after AVL tree re-balance.
  6682. () `(when node
  6683. (org-element-at-point (point-max))
  6684. (setq node (cache-root)
  6685. stack (list nil)
  6686. leftp t
  6687. continue-flag t)))
  6688. (cache-walk-abort
  6689. ;; Abort tree traversal.
  6690. () `(setq continue-flag t
  6691. node nil))
  6692. (element-match-at-point
  6693. ;; Returning the first element to match around point.
  6694. ;; For example, if point is inside headline and
  6695. ;; granularity is restricted to headlines only, skip
  6696. ;; over all the child elements inside the headline
  6697. ;; and return the first parent headline.
  6698. ;; When we are inside a cache gap, calling
  6699. ;; `org-element-at-point' also fills the cache gap down to
  6700. ;; point.
  6701. () `(progn
  6702. ;; Parsing is one of the performance
  6703. ;; bottlenecks. Make sure to optimise it as
  6704. ;; much as possible.
  6705. ;;
  6706. ;; Avoid extra staff like timer cancels et al
  6707. ;; and only call `org-element--cache-sync-requests' when
  6708. ;; there are pending requests.
  6709. (when org-element--cache-sync-requests
  6710. (org-element--cache-sync (current-buffer)))
  6711. ;; Call `org-element--parse-to' directly avoiding any
  6712. ;; kind of `org-element-at-point' overheads.
  6713. (if restrict-elements
  6714. ;; Search directly instead of calling
  6715. ;; `org-element-lineage' to avoid funcall overheads
  6716. ;; and making sure that we do not go all
  6717. ;; the way to `org-data' as `org-element-lineage'
  6718. ;; does.
  6719. (progn
  6720. (setq tmpelement (org-element--parse-to (point)))
  6721. (while (and tmpelement (not (memq (org-element-type tmpelement) restrict-elements)))
  6722. (setq tmpelement (org-element-property :parent tmpelement)))
  6723. tmpelement)
  6724. (org-element--parse-to (point)))))
  6725. ;; Starting from (point), search RE and move START to
  6726. ;; the next valid element to be matched according to
  6727. ;; restriction. Abort cache walk if no next element
  6728. ;; can be found. When RE is nil, just find element at
  6729. ;; point.
  6730. (move-start-to-next-match
  6731. (re) `(save-match-data
  6732. (if (or (not ,re)
  6733. (if org-element--cache-map-statistics
  6734. (progn
  6735. (setq before-time (float-time))
  6736. (re-search-forward (or (car-safe ,re) ,re) nil 'move)
  6737. (cl-incf re-search-time
  6738. (- (float-time)
  6739. before-time)))
  6740. (re-search-forward (or (car-safe ,re) ,re) nil 'move)))
  6741. (unless (or (< (point) (or start -1))
  6742. (and data
  6743. (< (point) (org-element-property :begin data))))
  6744. (if (cdr-safe ,re)
  6745. ;; Avoid parsing when we are 100%
  6746. ;; sure that regexp is good enough
  6747. ;; to find new START.
  6748. (setq start (match-beginning 0))
  6749. (setq start (max (or start -1)
  6750. (or (org-element-property :begin data) -1)
  6751. (or (org-element-property :begin (element-match-at-point)) -1))))
  6752. (when (>= start to-pos) (cache-walk-abort))
  6753. (when (eq start -1) (setq start nil)))
  6754. (cache-walk-abort))))
  6755. ;; Find expected begin position of an element after
  6756. ;; DATA.
  6757. (next-element-start
  6758. () `(progn
  6759. (setq tmpnext-start nil)
  6760. (if (memq granularity '(headline headline+inlinetask))
  6761. (setq tmpnext-start (or (when (memq (org-element-type data) '(headline org-data))
  6762. (org-element-property :contents-begin data))
  6763. (org-element-property :end data)))
  6764. (setq tmpnext-start (or (when (memq (org-element-type data) org-element-greater-elements)
  6765. (org-element-property :contents-begin data))
  6766. (org-element-property :end data))))
  6767. ;; DATA end may be the last element inside
  6768. ;; i.e. source block. Skip up to the end
  6769. ;; of parent in such case.
  6770. (setq tmpparent data)
  6771. (catch :exit
  6772. (when (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6773. (setq tmpnext-start (org-element-property :end tmpparent)))
  6774. (while (setq tmpparent (org-element-property :parent tmpparent))
  6775. (if (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6776. (setq tmpnext-start (org-element-property :end tmpparent))
  6777. (throw :exit t))))
  6778. tmpnext-start))
  6779. ;; Check if cache does not have gaps.
  6780. (cache-gapless-p
  6781. () `(eq org-element--cache-change-tic
  6782. (alist-get granularity org-element--cache-gapless))))
  6783. ;; The core algorithm is simple walk along binary tree. However,
  6784. ;; instead of checking all the tree elements from first to last
  6785. ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
  6786. ;; the elements before FROM-POS efficiently: O(logN) instead of
  6787. ;; O(Nbefore).
  6788. ;;
  6789. ;; Later, we may also not check every single element in the
  6790. ;; binary tree after FROM-POS. Instead, we can find position of
  6791. ;; next candidate elements by means of regexp search and skip the
  6792. ;; binary tree branches that are before the next candidate:
  6793. ;; again, O(logN) instead of O(Nbetween).
  6794. ;;
  6795. ;; Some elements might not yet be in the tree. So, we also parse
  6796. ;; the empty gaps in cache as needed making sure that we do not
  6797. ;; miss anything.
  6798. (let* (;; START is always beginning of an element. When there is
  6799. ;; no element in cache at START, we are inside cache gap
  6800. ;; and need to fill it.
  6801. (start (and from-pos
  6802. (progn
  6803. (goto-char from-pos)
  6804. (org-element-property :begin (element-match-at-point)))))
  6805. ;; Some elements may start at the same position, so we
  6806. ;; also keep track of the last processed element and make
  6807. ;; sure that we do not try to search it again.
  6808. (prev after-element)
  6809. (node (cache-root))
  6810. data
  6811. (stack (list nil))
  6812. (leftp t)
  6813. result
  6814. ;; Whether previous element matched FUNC (FUNC
  6815. ;; returned non-nil).
  6816. (last-match t)
  6817. continue-flag
  6818. ;; Generic regexp to search next potential match. If it
  6819. ;; is a cons of (regexp . 'match-beg), we are 100% sure
  6820. ;; that the match beginning is the existing element
  6821. ;; beginning.
  6822. (next-element-re (pcase granularity
  6823. ((or `headline
  6824. (guard (eq '(headline)
  6825. restrict-elements)))
  6826. (cons
  6827. (org-with-limited-levels
  6828. org-element-headline-re)
  6829. 'match-beg))
  6830. (`headline+inlinetask
  6831. (cons
  6832. (if (eq '(inlinetask) restrict-elements)
  6833. (org-inlinetask-outline-regexp)
  6834. org-element-headline-re)
  6835. 'match-beg))
  6836. ;; TODO: May add other commonly
  6837. ;; searched elements as needed.
  6838. (_)))
  6839. ;; Make sure that we are not checking the same regexp twice.
  6840. (next-re (unless (and next-re
  6841. (string= next-re
  6842. (or (car-safe next-element-re)
  6843. next-element-re)))
  6844. next-re))
  6845. (fail-re (unless (and fail-re
  6846. (string= fail-re
  6847. (or (car-safe next-element-re)
  6848. next-element-re)))
  6849. fail-re))
  6850. (restrict-elements (or restrict-elements
  6851. (pcase granularity
  6852. (`headline
  6853. '(headline))
  6854. (`headline+inlinetask
  6855. '(headline inlinetask))
  6856. (`greater-element
  6857. org-element-greater-elements)
  6858. (_ nil))))
  6859. ;; Statistics
  6860. (time (float-time))
  6861. (predicate-time 0)
  6862. (pre-process-time 0)
  6863. (re-search-time 0)
  6864. (count-predicate-calls-match 0)
  6865. (count-predicate-calls-fail 0)
  6866. ;; Bind variables used inside loop to avoid memory
  6867. ;; re-allocation on every iteration.
  6868. ;; See https://emacsconf.org/2021/talks/faster/
  6869. cache-size before-time modified-tic)
  6870. ;; Skip to first element within region.
  6871. (goto-char (or start (point-min)))
  6872. (move-start-to-next-match next-element-re)
  6873. (unless (and start (>= start to-pos))
  6874. ;; Pre-process cache filling all the gaps.
  6875. (unless (or org-element-cache-map--recurse
  6876. (cache-gapless-p)
  6877. ;; Pre-processing all the elements in large
  6878. ;; buffers when NEXT-RE/FAIL-RE are provided
  6879. ;; may be much slower compared to using
  6880. ;; regexp.
  6881. (and (eq granularity 'element)
  6882. (or next-re fail-re)))
  6883. (let ((org-element-cache-map--recurse t))
  6884. (setq before-time (float-time))
  6885. (org-element-cache-map
  6886. #'ignore
  6887. :granularity granularity)
  6888. (cl-incf pre-process-time
  6889. (- (float-time)
  6890. before-time))
  6891. ;; Re-assign the cache root after filling the cache
  6892. ;; gaps.
  6893. (setq node (cache-root)))
  6894. (setf (alist-get granularity org-element--cache-gapless)
  6895. org-element--cache-change-tic))
  6896. (while node
  6897. (setq data (avl-tree--node-data node))
  6898. (if (and leftp (avl-tree--node-left node) ; Left branch.
  6899. ;; Do not move to left branch when we are before
  6900. ;; PREV.
  6901. (or (not prev)
  6902. (not (org-element--cache-key-less-p
  6903. (org-element--cache-key data)
  6904. (org-element--cache-key prev))))
  6905. ;; ... or when we are before START.
  6906. (or (not start)
  6907. (not (> start (org-element-property :begin data)))))
  6908. (progn (push node stack)
  6909. (setq node (avl-tree--node-left node)))
  6910. ;; The whole tree left to DATA is before START and
  6911. ;; PREV. DATA may still be before START (i.e. when
  6912. ;; DATA is the root or when START moved), at START, or
  6913. ;; after START.
  6914. ;;
  6915. ;; If DATA is before start, skip it over and move to
  6916. ;; subsequent elements.
  6917. ;; If DATA is at start, run FUNC if necessary and
  6918. ;; update START according and NEXT-RE, FAIL-RE,
  6919. ;; NEXT-ELEMENT-RE.
  6920. ;; If DATA is after start, we have found a cache gap
  6921. ;; and need to fill it.
  6922. (unless (or (and start (< (org-element-property :begin data) start))
  6923. (and prev (not (org-element--cache-key-less-p
  6924. (org-element--cache-key prev)
  6925. (org-element--cache-key data)))))
  6926. ;; DATA is at of after START and PREV.
  6927. (if (or (not start) (= (org-element-property :begin data) start))
  6928. ;; DATA is at START. Match it.
  6929. ;; In the process, we may alter the buffer,
  6930. ;; so also keep track of the cache state.
  6931. (progn
  6932. (setq modified-tic org-element--cache-change-tic)
  6933. (setq cache-size (cache-size))
  6934. ;; When NEXT-RE/FAIL-RE is provided, skip to
  6935. ;; next regexp match after :begin of the current
  6936. ;; element.
  6937. (when (if last-match next-re fail-re)
  6938. (goto-char (org-element-property :begin data))
  6939. (move-start-to-next-match
  6940. (if last-match next-re fail-re)))
  6941. (when (and (or (not start) (eq (org-element-property :begin data) start))
  6942. (< (org-element-property :begin data) to-pos))
  6943. ;; Calculate where next possible element
  6944. ;; starts and update START if needed.
  6945. (setq start (next-element-start))
  6946. (goto-char start)
  6947. ;; Move START further if possible.
  6948. (when (and next-element-re
  6949. ;; Do not move if we know for
  6950. ;; sure that cache does not
  6951. ;; contain gaps. Regexp
  6952. ;; searches are not cheap.
  6953. (not (cache-gapless-p)))
  6954. (move-start-to-next-match next-element-re)
  6955. ;; Make sure that point is at START
  6956. ;; before running FUNC.
  6957. (goto-char start))
  6958. ;; Try FUNC if DATA matches all the
  6959. ;; restrictions. Calculate new START.
  6960. (when (or (not restrict-elements)
  6961. (memq (org-element-type data) restrict-elements))
  6962. ;; DATA matches restriction. FUNC may
  6963. ;;
  6964. ;; Call FUNC. FUNC may move point.
  6965. (setq org-element-cache-map-continue-from nil)
  6966. (if org-element--cache-map-statistics
  6967. (progn
  6968. (setq before-time (float-time))
  6969. (push (funcall func data) result)
  6970. (cl-incf predicate-time
  6971. (- (float-time)
  6972. before-time))
  6973. (if (car result)
  6974. (cl-incf count-predicate-calls-match)
  6975. (cl-incf count-predicate-calls-fail)))
  6976. (push (funcall func data) result)
  6977. (when (car result) (cl-incf count-predicate-calls-match)))
  6978. ;; Set `last-match'.
  6979. (setq last-match (car result))
  6980. ;; If FUNC moved point forward, update
  6981. ;; START.
  6982. (when org-element-cache-map-continue-from
  6983. (goto-char org-element-cache-map-continue-from))
  6984. (when (> (point) start)
  6985. (move-start-to-next-match nil))
  6986. ;; Drop nil.
  6987. (unless (car result) (pop result)))
  6988. ;; If FUNC did not move the point and we
  6989. ;; know for sure that cache does not contain
  6990. ;; gaps, do not try to calculate START in
  6991. ;; advance but simply loop to the next cache
  6992. ;; element.
  6993. (when (and (cache-gapless-p)
  6994. (eq (next-element-start)
  6995. start))
  6996. (setq start nil))
  6997. ;; Check if the buffer has been modified.
  6998. (unless (and (eq modified-tic org-element--cache-change-tic)
  6999. (eq cache-size (cache-size)))
  7000. ;; START may no longer be valid, update
  7001. ;; it to beginning of real element.
  7002. ;; Upon modification, START may lay
  7003. ;; inside an element. We want to move
  7004. ;; it to real beginning then despite
  7005. ;; START being larger.
  7006. (setq start nil)
  7007. (move-start-to-next-match nil)
  7008. ;; The new element may now start before
  7009. ;; or at already processed position.
  7010. ;; Make sure that we continue from an
  7011. ;; element past already processed
  7012. ;; place.
  7013. (when (and start
  7014. (<= start (org-element-property :begin data))
  7015. (not org-element-cache-map-continue-from))
  7016. (goto-char start)
  7017. (setq data (element-match-at-point))
  7018. ;; If DATA is nil, buffer is
  7019. ;; empty. Abort.
  7020. (when data
  7021. (goto-char (next-element-start))
  7022. (move-start-to-next-match next-element-re)))
  7023. (org-element-at-point to-pos)
  7024. (cache-walk-restart))
  7025. ;; Reached LIMIT-COUNT. Abort.
  7026. (when (and limit-count
  7027. (>= count-predicate-calls-match
  7028. limit-count))
  7029. (cache-walk-abort))
  7030. (if (org-element-property :cached data)
  7031. (setq prev data)
  7032. (setq prev nil))))
  7033. ;; DATA is after START. Fill the gap.
  7034. (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
  7035. ;; Tables and lists are special, we need a
  7036. ;; trickery to make items/rows be populated
  7037. ;; into cache.
  7038. (org-element--parse-to (1+ start)))
  7039. ;; Restart tree traversal as AVL tree is
  7040. ;; re-balanced upon adding elements. We can no
  7041. ;; longer trust STACK.
  7042. (cache-walk-restart)))
  7043. ;; Second, move to the right branch of the tree or skip
  7044. ;; it alltogether.
  7045. (if continue-flag
  7046. (setq continue-flag nil)
  7047. (setq node (if (and (car stack)
  7048. ;; If START advanced beyond stack parent, skip the right branch.
  7049. (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
  7050. (and prev (org-element--cache-key-less-p
  7051. (org-element--cache-key (avl-tree--node-data (car stack)))
  7052. (org-element--cache-key prev)))))
  7053. (progn
  7054. (setq leftp nil)
  7055. (pop stack))
  7056. ;; Otherwise, move ahead into the right
  7057. ;; branch when it exists.
  7058. (if (setq leftp (avl-tree--node-right node))
  7059. (avl-tree--node-right node)
  7060. (pop stack))))))))
  7061. (when (and org-element--cache-map-statistics
  7062. (or (not org-element--cache-map-statistics-threshold)
  7063. (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
  7064. (message "Mapped over elements in %S. %d/%d predicate matches. Total time: %f sec. Pre-process time: %f sec. Predicate time: %f sec. Re-search time: %f sec.
  7065. 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"
  7066. (current-buffer)
  7067. count-predicate-calls-match
  7068. (+ count-predicate-calls-match
  7069. count-predicate-calls-fail)
  7070. (- (float-time) time)
  7071. pre-process-time
  7072. predicate-time
  7073. re-search-time
  7074. granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
  7075. ;; Return result.
  7076. (nreverse result)))))))
  7077. ;;; The Toolbox
  7078. ;;
  7079. ;; The first move is to implement a way to obtain the smallest element
  7080. ;; containing point. This is the job of `org-element-at-point'. It
  7081. ;; basically jumps back to the beginning of section containing point
  7082. ;; and proceed, one element after the other, with
  7083. ;; `org-element--current-element' until the container is found. Note:
  7084. ;; When using `org-element-at-point', secondary values are never
  7085. ;; parsed since the function focuses on elements, not on objects.
  7086. ;;
  7087. ;; At a deeper level, `org-element-context' lists all elements and
  7088. ;; objects containing point.
  7089. ;;
  7090. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  7091. ;; internally by navigation and manipulation tools.
  7092. ;;;###autoload
  7093. (defun org-element-at-point (&optional pom cached-only)
  7094. "Determine closest element around point or POM.
  7095. Only check cached element when CACHED-ONLY is non-nil and return nil
  7096. unconditionally when element at POM is not in cache.
  7097. Return value is a list like (TYPE PROPS) where TYPE is the type
  7098. of the element and PROPS a plist of properties associated to the
  7099. element.
  7100. Possible types are defined in `org-element-all-elements'.
  7101. Properties depend on element or object type, but always include
  7102. `:begin', `:end', and `:post-blank' properties.
  7103. As a special case, if point is at the very beginning of the first
  7104. item in a list or sub-list, returned element will be that list
  7105. instead of the item. Likewise, if point is at the beginning of
  7106. the first row of a table, returned element will be the table
  7107. instead of the first row.
  7108. When point is at the end of the buffer, return the innermost
  7109. element ending there."
  7110. (setq pom (or pom (point)))
  7111. ;; Allow re-parsing when the command can benefit from it.
  7112. (when (and cached-only
  7113. (memq this-command org-element--cache-non-modifying-commands))
  7114. (setq cached-only nil))
  7115. (let (element)
  7116. (when (org-element--cache-active-p)
  7117. (if (not org-element--cache) (org-element-cache-reset)
  7118. (unless cached-only (org-element--cache-sync (current-buffer) pom))))
  7119. (setq element (if cached-only
  7120. (when (and (org-element--cache-active-p)
  7121. (or (not org-element--cache-sync-requests)
  7122. (< pom
  7123. (org-element--request-beg
  7124. (car org-element--cache-sync-requests)))))
  7125. (org-element--cache-find pom))
  7126. (condition-case err
  7127. (org-element--parse-to pom)
  7128. (error
  7129. (org-element--cache-warn
  7130. "Org parser error in %s::%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)."
  7131. (buffer-name (current-buffer))
  7132. pom
  7133. err
  7134. (when (and (fboundp 'backtrace-get-frames)
  7135. (fboundp 'backtrace-to-string))
  7136. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  7137. (org-element-cache-reset)
  7138. (org-element--parse-to pom)))))
  7139. (when (and (org-element--cache-active-p)
  7140. element
  7141. (org-element--cache-verify-element element))
  7142. (setq element (org-element--parse-to pom)))
  7143. (unless (eq 'org-data (org-element-type element))
  7144. (unless (and cached-only
  7145. (not (and element
  7146. (or (= pom (org-element-property :begin element))
  7147. (and (not (memq (org-element-type element) org-element-greater-elements))
  7148. (>= pom (org-element-property :begin element))
  7149. (< pom (org-element-property :end element)))
  7150. (and (org-element-property :contents-begin element)
  7151. (>= pom (org-element-property :begin element))
  7152. (< pom (org-element-property :contents-begin element)))
  7153. (and (not (org-element-property :contents-end element))
  7154. (>= pom (org-element-property :begin element))
  7155. (< pom (org-element-property :end element)))))))
  7156. (if (not (eq (org-element-type element) 'section))
  7157. element
  7158. (org-element-at-point (1+ pom) cached-only))))))
  7159. ;;;###autoload
  7160. (defsubst org-element-at-point-no-context (&optional pom)
  7161. "Quickly find element at point or POM.
  7162. It is a faster version of `org-element-at-point' that is not
  7163. guaranteed to return correct `:parent' properties even when cache is
  7164. enabled."
  7165. (or (org-element-at-point pom 'cached-only)
  7166. (let (org-element-use-cache) (org-element-at-point pom))))
  7167. ;;;###autoload
  7168. (defun org-element-context (&optional element)
  7169. "Return smallest element or object around point.
  7170. Return value is a list like (TYPE PROPS) where TYPE is the type
  7171. of the element or object and PROPS a plist of properties
  7172. associated to it.
  7173. Possible types are defined in `org-element-all-elements' and
  7174. `org-element-all-objects'. Properties depend on element or
  7175. object type, but always include `:begin', `:end', `:parent' and
  7176. `:post-blank'.
  7177. As a special case, if point is right after an object and not at
  7178. the beginning of any other object, return that object.
  7179. Optional argument ELEMENT, when non-nil, is the closest element
  7180. containing point, as returned by `org-element-at-point'.
  7181. Providing it allows for quicker computation."
  7182. (catch 'objects-forbidden
  7183. (org-with-wide-buffer
  7184. (let* ((pos (point))
  7185. (element (or element (org-element-at-point)))
  7186. (type (org-element-type element))
  7187. (post (org-element-property :post-affiliated element)))
  7188. ;; If point is inside an element containing objects or
  7189. ;; a secondary string, narrow buffer to the container and
  7190. ;; proceed with parsing. Otherwise, return ELEMENT.
  7191. (cond
  7192. ;; At a parsed affiliated keyword, check if we're inside main
  7193. ;; or dual value.
  7194. ((and post (< pos post))
  7195. (beginning-of-line)
  7196. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  7197. (cond
  7198. ((not (member-ignore-case (match-string 1)
  7199. org-element-parsed-keywords))
  7200. (throw 'objects-forbidden element))
  7201. ((< (match-end 0) pos)
  7202. (narrow-to-region (match-end 0) (line-end-position)))
  7203. ((and (match-beginning 2)
  7204. (>= pos (match-beginning 2))
  7205. (< pos (match-end 2)))
  7206. (narrow-to-region (match-beginning 2) (match-end 2)))
  7207. (t (throw 'objects-forbidden element)))
  7208. ;; Also change type to retrieve correct restrictions.
  7209. (setq type 'keyword))
  7210. ;; At an item, objects can only be located within tag, if any.
  7211. ((eq type 'item)
  7212. (let ((tag (org-element-property :tag element)))
  7213. (if (or (not tag) (/= (line-beginning-position) post))
  7214. (throw 'objects-forbidden element)
  7215. (beginning-of-line)
  7216. (search-forward tag (line-end-position))
  7217. (goto-char (match-beginning 0))
  7218. (if (and (>= pos (point)) (< pos (match-end 0)))
  7219. (narrow-to-region (point) (match-end 0))
  7220. (throw 'objects-forbidden element)))))
  7221. ;; At an headline or inlinetask, objects are in title.
  7222. ((memq type '(headline inlinetask))
  7223. (let ((case-fold-search nil))
  7224. (goto-char (org-element-property :begin element))
  7225. (looking-at org-complex-heading-regexp)
  7226. (let ((end (match-end 4)))
  7227. (if (not end) (throw 'objects-forbidden element)
  7228. (goto-char (match-beginning 4))
  7229. (when (looking-at org-element-comment-string)
  7230. (goto-char (match-end 0)))
  7231. (if (>= (point) end) (throw 'objects-forbidden element)
  7232. (narrow-to-region (point) end))))))
  7233. ;; At a paragraph, a table-row or a verse block, objects are
  7234. ;; located within their contents.
  7235. ((memq type '(paragraph table-row verse-block))
  7236. (let ((cbeg (org-element-property :contents-begin element))
  7237. (cend (org-element-property :contents-end element)))
  7238. ;; CBEG is nil for table rules.
  7239. (if (and cbeg cend (>= pos cbeg)
  7240. (or (< pos cend) (and (= pos cend) (eobp))))
  7241. (narrow-to-region cbeg cend)
  7242. (throw 'objects-forbidden element))))
  7243. (t (throw 'objects-forbidden element)))
  7244. (goto-char (point-min))
  7245. (let ((restriction (org-element-restriction type))
  7246. (parent element)
  7247. last)
  7248. (catch 'exit
  7249. (while t
  7250. (let ((next (org-element--object-lex restriction)))
  7251. (when next (org-element-put-property next :parent parent))
  7252. ;; Process NEXT, if any, in order to know if we need to
  7253. ;; skip it, return it or move into it.
  7254. (if (or (not next) (> (org-element-property :begin next) pos))
  7255. (throw 'exit (or last parent))
  7256. (let ((end (org-element-property :end next))
  7257. (cbeg (org-element-property :contents-begin next))
  7258. (cend (org-element-property :contents-end next)))
  7259. (cond
  7260. ;; Skip objects ending before point. Also skip
  7261. ;; objects ending at point unless it is also the
  7262. ;; end of buffer, since we want to return the
  7263. ;; innermost object.
  7264. ((and (<= end pos) (/= (point-max) end))
  7265. (goto-char end)
  7266. ;; For convenience, when object ends at POS,
  7267. ;; without any space, store it in LAST, as we
  7268. ;; will return it if no object starts here.
  7269. (when (and (= end pos)
  7270. (not (memq (char-before) '(?\s ?\t))))
  7271. (setq last next)))
  7272. ;; If POS is within a container object, move into
  7273. ;; that object.
  7274. ((and cbeg cend
  7275. (>= pos cbeg)
  7276. (or (< pos cend)
  7277. ;; At contents' end, if there is no
  7278. ;; space before point, also move into
  7279. ;; object, for consistency with
  7280. ;; convenience feature above.
  7281. (and (= pos cend)
  7282. (or (= (point-max) pos)
  7283. (not (memq (char-before pos)
  7284. '(?\s ?\t)))))))
  7285. (goto-char cbeg)
  7286. (narrow-to-region (point) cend)
  7287. (setq parent next)
  7288. (setq restriction (org-element-restriction next)))
  7289. ;; Otherwise, return NEXT.
  7290. (t (throw 'exit next)))))))))))))
  7291. (defun org-element-lineage (datum &optional types with-self)
  7292. "List all ancestors of a given element or object.
  7293. DATUM is an object or element.
  7294. Return ancestors from the closest to the farthest. When optional
  7295. argument TYPES is a list of symbols, return the first element or
  7296. object in the lineage whose type belongs to that list instead.
  7297. When optional argument WITH-SELF is non-nil, lineage includes
  7298. DATUM itself as the first element, and TYPES, if provided, also
  7299. apply to it.
  7300. When DATUM is obtained through `org-element-context' or
  7301. `org-element-at-point', only ancestors from its section can be
  7302. found. There is no such limitation when DATUM belongs to a full
  7303. parse tree."
  7304. (let ((up (if with-self datum (org-element-property :parent datum)))
  7305. ancestors)
  7306. (while (and up (not (memq (org-element-type up) types)))
  7307. (unless types (push up ancestors))
  7308. (setq up (org-element-property :parent up)))
  7309. (if types up (nreverse ancestors))))
  7310. (defun org-element-nested-p (elem-A elem-B)
  7311. "Non-nil when elements ELEM-A and ELEM-B are nested."
  7312. (let ((beg-A (org-element-property :begin elem-A))
  7313. (beg-B (org-element-property :begin elem-B))
  7314. (end-A (org-element-property :end elem-A))
  7315. (end-B (org-element-property :end elem-B)))
  7316. (or (and (>= beg-A beg-B) (<= end-A end-B))
  7317. (and (>= beg-B beg-A) (<= end-B end-A)))))
  7318. (defun org-element-swap-A-B--overlays (elem-A elem-B)
  7319. "Swap elements ELEM-A and ELEM-B.
  7320. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7321. end of ELEM-A."
  7322. (goto-char (org-element-property :begin elem-A))
  7323. ;; There are two special cases when an element doesn't start at bol:
  7324. ;; the first paragraph in an item or in a footnote definition.
  7325. (let ((specialp (not (bolp))))
  7326. ;; Only a paragraph without any affiliated keyword can be moved at
  7327. ;; ELEM-A position in such a situation. Note that the case of
  7328. ;; a footnote definition is impossible: it cannot contain two
  7329. ;; paragraphs in a row because it cannot contain a blank line.
  7330. (when (and specialp
  7331. (or (not (eq (org-element-type elem-B) 'paragraph))
  7332. (/= (org-element-property :begin elem-B)
  7333. (org-element-property :contents-begin elem-B))))
  7334. (error "Cannot swap elements"))
  7335. ;; In a special situation, ELEM-A will have no indentation. We'll
  7336. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7337. (let* ((ind-B (when specialp
  7338. (goto-char (org-element-property :begin elem-B))
  7339. (current-indentation)))
  7340. (beg-A (org-element-property :begin elem-A))
  7341. (end-A (save-excursion
  7342. (goto-char (org-element-property :end elem-A))
  7343. (skip-chars-backward " \r\t\n")
  7344. (point-at-eol)))
  7345. (beg-B (org-element-property :begin elem-B))
  7346. (end-B (save-excursion
  7347. (goto-char (org-element-property :end elem-B))
  7348. (skip-chars-backward " \r\t\n")
  7349. (point-at-eol)))
  7350. ;; Store inner overlays responsible for visibility status.
  7351. ;; We also need to store their boundaries as they will be
  7352. ;; removed from buffer.
  7353. (overlays
  7354. (cons
  7355. (delq nil
  7356. (mapcar (lambda (o)
  7357. (and (>= (overlay-start o) beg-A)
  7358. (<= (overlay-end o) end-A)
  7359. (list o (overlay-start o) (overlay-end o))))
  7360. (overlays-in beg-A end-A)))
  7361. (delq nil
  7362. (mapcar (lambda (o)
  7363. (and (>= (overlay-start o) beg-B)
  7364. (<= (overlay-end o) end-B)
  7365. (list o (overlay-start o) (overlay-end o))))
  7366. (overlays-in beg-B end-B)))))
  7367. ;; Get contents.
  7368. (body-A (buffer-substring beg-A end-A))
  7369. (body-B (delete-and-extract-region beg-B end-B)))
  7370. (goto-char beg-B)
  7371. (when specialp
  7372. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7373. (indent-to-column ind-B))
  7374. (insert body-A)
  7375. ;; Restore ex ELEM-A overlays.
  7376. (let ((offset (- beg-B beg-A)))
  7377. (dolist (o (car overlays))
  7378. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  7379. (goto-char beg-A)
  7380. (delete-region beg-A end-A)
  7381. (insert body-B)
  7382. ;; Restore ex ELEM-B overlays.
  7383. (dolist (o (cdr overlays))
  7384. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  7385. (goto-char (org-element-property :end elem-B)))))
  7386. (defun org-element-swap-A-B--text-properties (elem-A elem-B)
  7387. "Swap elements ELEM-A and ELEM-B.
  7388. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7389. end of ELEM-A."
  7390. (goto-char (org-element-property :begin elem-A))
  7391. ;; There are two special cases when an element doesn't start at bol:
  7392. ;; the first paragraph in an item or in a footnote definition.
  7393. (let ((specialp (not (bolp))))
  7394. ;; Only a paragraph without any affiliated keyword can be moved at
  7395. ;; ELEM-A position in such a situation. Note that the case of
  7396. ;; a footnote definition is impossible: it cannot contain two
  7397. ;; paragraphs in a row because it cannot contain a blank line.
  7398. (when (and specialp
  7399. (or (not (eq (org-element-type elem-B) 'paragraph))
  7400. (/= (org-element-property :begin elem-B)
  7401. (org-element-property :contents-begin elem-B))))
  7402. (error "Cannot swap elements"))
  7403. ;; In a special situation, ELEM-A will have no indentation. We'll
  7404. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7405. (org-fold-core-ignore-modifications ;; Preserve folding state
  7406. (let* ((ind-B (when specialp
  7407. (goto-char (org-element-property :begin elem-B))
  7408. (current-indentation)))
  7409. (beg-A (org-element-property :begin elem-A))
  7410. (end-A (save-excursion
  7411. (goto-char (org-element-property :end elem-A))
  7412. (skip-chars-backward " \r\t\n")
  7413. (point-at-eol)))
  7414. (beg-B (org-element-property :begin elem-B))
  7415. (end-B (save-excursion
  7416. (goto-char (org-element-property :end elem-B))
  7417. (skip-chars-backward " \r\t\n")
  7418. (point-at-eol)))
  7419. ;; Get contents.
  7420. (body-A (buffer-substring beg-A end-A))
  7421. (body-B (delete-and-extract-region beg-B end-B)))
  7422. (goto-char beg-B)
  7423. (when specialp
  7424. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7425. (indent-to-column ind-B))
  7426. (insert body-A)
  7427. (goto-char beg-A)
  7428. (delete-region beg-A end-A)
  7429. (insert body-B)
  7430. (goto-char (org-element-property :end elem-B))))))
  7431. (defsubst org-element-swap-A-B (elem-A elem-B)
  7432. "Swap elements ELEM-A and ELEM-B.
  7433. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7434. end of ELEM-A."
  7435. (if (eq org-fold-core-style 'text-properties)
  7436. (org-element-swap-A-B--text-properties elem-A elem-B)
  7437. (org-element-swap-A-B--overlays elem-A elem-B)))
  7438. (provide 'org-element)
  7439. ;; Local variables:
  7440. ;; generated-autoload-file: "org-loaddefs.el"
  7441. ;; End:
  7442. ;;; org-element.el ends here