org-element.el 330 KB

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