org-element.el 330 KB

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