org-element.el 330 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
  19. ;; Org syntax.
  20. ;;
  21. ;; Lisp-wise, a syntax object can be represented as a list.
  22. ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
  23. ;; TYPE is a symbol describing the object.
  24. ;; PROPERTIES is the property list attached to it. See docstring of
  25. ;; appropriate parsing function to get an exhaustive list.
  26. ;; CONTENTS is a list of syntax objects or raw strings contained
  27. ;; in the current object, when applicable.
  28. ;;
  29. ;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
  30. ;;
  31. ;; The first part of this file defines constants for the Org syntax,
  32. ;; while the second one provide accessors and setters functions.
  33. ;;
  34. ;; The next part implements a parser and an interpreter for each
  35. ;; element and object type in Org syntax.
  36. ;;
  37. ;; The following part creates a fully recursive buffer parser. It
  38. ;; also provides a tool to map a function to elements or objects
  39. ;; matching some criteria in the parse tree. Functions of interest
  40. ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
  41. ;; extent, `org-element-parse-secondary-string'.
  42. ;;
  43. ;; The penultimate part is the cradle of an interpreter for the
  44. ;; obtained parse tree: `org-element-interpret-data'.
  45. ;;
  46. ;; The library ends by furnishing `org-element-at-point' function, and
  47. ;; a way to give information about document structure around point
  48. ;; with `org-element-context'. A cache mechanism is also provided for
  49. ;; these functions.
  50. ;;; Code:
  51. (require 'avl-tree)
  52. (require 'ring)
  53. (require 'cl-lib)
  54. (require 'ol)
  55. (require 'org)
  56. (require 'org-persist)
  57. (require 'org-compat)
  58. (require 'org-entities)
  59. (require 'org-footnote)
  60. (require 'org-list)
  61. (require 'org-macs)
  62. (require 'org-table)
  63. (require 'org-fold-core)
  64. (declare-function org-at-heading-p "org" (&optional _))
  65. (declare-function org-escape-code-in-string "org-src" (s))
  66. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  67. (declare-function org-macro-extract-arguments "org-macro" (s))
  68. (declare-function org-reduced-level "org" (l))
  69. (declare-function org-unescape-code-in-string "org-src" (s))
  70. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  71. (declare-function outline-next-heading "outline" ())
  72. (declare-function outline-previous-heading "outline" ())
  73. (defvar org-complex-heading-regexp)
  74. (defvar org-done-keywords)
  75. (defvar org-edit-src-content-indentation)
  76. (defvar org-match-substring-regexp)
  77. (defvar org-odd-levels-only)
  78. (defvar org-property-drawer-re)
  79. (defvar org-property-format)
  80. (defvar org-property-re)
  81. (defvar org-src-preserve-indentation)
  82. (defvar org-tags-column)
  83. (defvar org-time-stamp-formats)
  84. (defvar org-todo-regexp)
  85. (defvar org-ts-regexp-both)
  86. ;;; Definitions And Rules
  87. ;;
  88. ;; Define elements, greater elements and specify recursive objects,
  89. ;; along with the affiliated keywords recognized. Also set up
  90. ;; restrictions on recursive objects combinations.
  91. ;;
  92. ;; `org-element-update-syntax' builds proper syntax regexps according
  93. ;; to current setup.
  94. (defconst org-element-archive-tag "ARCHIVE"
  95. "Tag marking a substree as archived.")
  96. (defconst org-element-citation-key-re
  97. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  98. "Regexp matching a citation key.
  99. Key is located in match group 1.")
  100. (defconst org-element-citation-prefix-re
  101. (rx "[cite"
  102. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  103. ":"
  104. (zero-or-more (any "\t\n ")))
  105. "Regexp matching a citation prefix.
  106. Style, if any, is located in match group 1.")
  107. (defconst org-element-clock-line-re
  108. (rx line-start (0+ (or ?\t ?\s)) "CLOCK:")
  109. "Regexp matching a clock line.")
  110. (defconst org-element-comment-string "COMMENT"
  111. "String marker for commented headlines.")
  112. (defconst org-element-closed-keyword "CLOSED:"
  113. "Keyword used to close TODO entries.")
  114. (defconst org-element-deadline-keyword "DEADLINE:"
  115. "Keyword used to mark deadline entries.")
  116. (defconst org-element-scheduled-keyword "SCHEDULED:"
  117. "Keyword used to mark scheduled entries.")
  118. (defconst org-element-planning-keywords-re
  119. (regexp-opt (list org-element-closed-keyword
  120. org-element-deadline-keyword
  121. org-element-scheduled-keyword))
  122. "Regexp matching any planning line keyword.")
  123. (defconst org-element-planning-line-re
  124. (rx-to-string
  125. `(seq line-start (0+ (any ?\s ?\t))
  126. (group (regexp ,org-element-planning-keywords-re))))
  127. "Regexp matching a planning line.")
  128. (defconst org-element-drawer-re
  129. (rx line-start (0+ (any ?\s ?\t))
  130. ":" (group (1+ (any ?- ?_ word))) ":"
  131. (0+ (any ?\s ?\t)) line-end)
  132. "Regexp matching opening or closing line of a drawer.
  133. Drawer's name is located in match group 1.")
  134. (defconst org-element-dynamic-block-open-re
  135. (rx line-start (0+ (any ?\s ?\t))
  136. "#+BEGIN:" (0+ (any ?\s ?\t))
  137. (group (1+ word))
  138. (opt
  139. (1+ (any ?\s ?\t))
  140. (group (1+ nonl))))
  141. "Regexp matching the opening line of a dynamic block.
  142. Dynamic block's name is located in match group 1.
  143. Parameters are in match group 2.")
  144. (defconst org-element-headline-re
  145. (rx line-start (1+ "*") " ")
  146. "Regexp matching a headline.")
  147. (defvar org-element-paragraph-separate nil
  148. "Regexp to separate paragraphs in an Org buffer.
  149. In the case of lines starting with \"#\" and \":\", this regexp
  150. is not sufficient to know if point is at a paragraph ending. See
  151. `org-element-paragraph-parser' for more information.")
  152. (defvar org-element--object-regexp nil
  153. "Regexp possibly matching the beginning of an object.
  154. This regexp allows false positives. Dedicated parser (e.g.,
  155. `org-export-bold-parser') will take care of further filtering.
  156. Radio links are not matched by this regexp, as they are treated
  157. specially in `org-element--object-lex'.")
  158. (defun org-element--set-regexps ()
  159. "Build variable syntax regexps."
  160. (setq org-element-paragraph-separate
  161. (concat "^\\(?:"
  162. ;; Headlines, inlinetasks.
  163. "\\*+ " "\\|"
  164. ;; Footnote definitions.
  165. "\\[fn:[-_[:word:]]+\\]" "\\|"
  166. ;; Diary sexps.
  167. "%%(" "\\|"
  168. "[ \t]*\\(?:"
  169. ;; Empty lines.
  170. "$" "\\|"
  171. ;; Tables (any type).
  172. "|" "\\|"
  173. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  174. ;; Comments, keyword-like or block-like constructs.
  175. ;; Blocks and keywords with dual values need to be
  176. ;; double-checked.
  177. "#\\(?: \\|$\\|\\+\\(?:"
  178. "BEGIN_\\S-+" "\\|"
  179. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  180. "\\|"
  181. ;; Drawers (any type) and fixed-width areas. Drawers
  182. ;; need to be double-checked.
  183. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  184. ;; Horizontal rules.
  185. "-\\{5,\\}[ \t]*$" "\\|"
  186. ;; LaTeX environments.
  187. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  188. ;; Clock lines.
  189. "CLOCK:" "\\|"
  190. ;; Lists.
  191. (let ((term (pcase org-plain-list-ordered-item-terminator
  192. (?\) ")") (?. "\\.") (_ "[.)]")))
  193. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  194. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  195. "\\(?:[ \t]\\|$\\)"))
  196. "\\)\\)")
  197. org-element--object-regexp
  198. (mapconcat #'identity
  199. (let ((link-types (regexp-opt (org-link-types))))
  200. (list
  201. ;; Sub/superscript.
  202. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  203. ;; Bold, code, italic, strike-through, underline
  204. ;; and verbatim.
  205. (rx (or "*" "~" "=" "+" "_" "/") (not space))
  206. ;; Plain links.
  207. (concat "\\<" link-types ":")
  208. ;; Objects starting with "[": citations,
  209. ;; footnote reference, statistics cookie,
  210. ;; timestamp (inactive) and regular link.
  211. (format "\\[\\(?:%s\\)"
  212. (mapconcat
  213. #'identity
  214. (list "cite[:/]"
  215. "fn:"
  216. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  217. "\\[")
  218. "\\|"))
  219. ;; Objects starting with "@": export snippets.
  220. "@@"
  221. ;; Objects starting with "{": macro.
  222. "{{{"
  223. ;; Objects starting with "<" : timestamp
  224. ;; (active, diary), target, radio target and
  225. ;; angular links.
  226. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  227. ;; Objects starting with "$": latex fragment.
  228. "\\$"
  229. ;; Objects starting with "\": line break,
  230. ;; entity, latex fragment.
  231. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  232. ;; Objects starting with raw text: inline Babel
  233. ;; source block, inline Babel call.
  234. "\\(?:call\\|src\\)_"))
  235. "\\|")))
  236. (org-element--set-regexps)
  237. ;;;###autoload
  238. (defun org-element-update-syntax ()
  239. "Update parser internals."
  240. (interactive)
  241. (org-element--set-regexps)
  242. (org-element-cache-reset 'all))
  243. (defconst org-element-all-elements
  244. '(babel-call center-block clock comment comment-block diary-sexp drawer
  245. dynamic-block example-block export-block fixed-width
  246. footnote-definition headline horizontal-rule inlinetask item
  247. keyword latex-environment node-property paragraph plain-list
  248. planning property-drawer quote-block section
  249. special-block src-block table table-row verse-block)
  250. "Complete list of element types.")
  251. (defconst org-element-greater-elements
  252. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  253. item plain-list property-drawer quote-block section
  254. special-block table org-data)
  255. "List of recursive element types aka Greater Elements.")
  256. (defconst org-element-all-objects
  257. '(bold citation citation-reference code entity export-snippet
  258. footnote-reference inline-babel-call inline-src-block italic line-break
  259. latex-fragment link macro radio-target statistics-cookie strike-through
  260. subscript superscript table-cell target timestamp underline verbatim)
  261. "Complete list of object types.")
  262. (defconst org-element-recursive-objects
  263. '(bold citation footnote-reference italic link subscript radio-target
  264. strike-through superscript table-cell underline)
  265. "List of recursive object types.")
  266. (defconst org-element-object-containers
  267. (append org-element-recursive-objects '(paragraph table-row verse-block))
  268. "List of object or element types that can directly contain objects.")
  269. (defconst org-element-affiliated-keywords
  270. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  271. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  272. "List of affiliated keywords as strings.
  273. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  274. are affiliated keywords and need not to be in this list.")
  275. (defconst org-element-keyword-translation-alist
  276. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  277. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  278. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  279. "Alist of usual translations for keywords.
  280. The key is the old name and the value the new one. The property
  281. holding their value will be named after the translated name.")
  282. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  283. "List of affiliated keywords that can occur more than once in an element.
  284. Their value will be consed into a list of strings, which will be
  285. returned as the value of the property.
  286. This list is checked after translations have been applied. See
  287. `org-element-keyword-translation-alist'.
  288. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  289. allow multiple occurrences and need not to be in this list.")
  290. (defconst org-element-parsed-keywords '("CAPTION")
  291. "List of affiliated keywords whose value can be parsed.
  292. Their value will be stored as a secondary string: a list of
  293. strings and objects.
  294. This list is checked after translations have been applied. See
  295. `org-element-keyword-translation-alist'.")
  296. (defconst org-element--parsed-properties-alist
  297. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  298. org-element-parsed-keywords)
  299. "Alist of parsed keywords and associated properties.
  300. This is generated from `org-element-parsed-keywords', which
  301. see.")
  302. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  303. "List of affiliated keywords which can have a secondary value.
  304. In Org syntax, they can be written with optional square brackets
  305. before the colons. For example, RESULTS keyword can be
  306. associated to a hash value with the following:
  307. #+RESULTS[hash-string]: some-source
  308. This list is checked after translations have been applied. See
  309. `org-element-keyword-translation-alist'.")
  310. (defconst org-element--affiliated-re
  311. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  312. (concat
  313. ;; Dual affiliated keywords.
  314. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  315. (regexp-opt org-element-dual-keywords))
  316. "\\|"
  317. ;; Regular affiliated keywords.
  318. (format "\\(?1:%s\\)"
  319. (regexp-opt
  320. (cl-remove-if
  321. (lambda (k) (member k org-element-dual-keywords))
  322. org-element-affiliated-keywords)))
  323. "\\|"
  324. ;; Export attributes.
  325. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  326. "Regexp matching any affiliated keyword.
  327. Keyword name is put in match group 1. Moreover, if keyword
  328. belongs to `org-element-dual-keywords', put the dual value in
  329. match group 2.
  330. Don't modify it, set `org-element-affiliated-keywords' instead.")
  331. (defconst org-element-object-restrictions
  332. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  333. subscript superscript underline verbatim))
  334. (standard-set
  335. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  336. (standard-set-no-line-break (remq 'line-break standard-set)))
  337. `((bold ,@standard-set)
  338. (citation citation-reference)
  339. (citation-reference ,@minimal-set)
  340. (footnote-reference ,@standard-set)
  341. (headline ,@standard-set-no-line-break)
  342. (inlinetask ,@standard-set-no-line-break)
  343. (italic ,@standard-set)
  344. (item ,@standard-set-no-line-break)
  345. (keyword ,@(remq 'footnote-reference standard-set))
  346. ;; Ignore all links in a link description. Also ignore
  347. ;; radio-targets and line breaks.
  348. (link export-snippet inline-babel-call inline-src-block macro
  349. statistics-cookie ,@minimal-set)
  350. (paragraph ,@standard-set)
  351. ;; Remove any variable object from radio target as it would
  352. ;; prevent it from being properly recognized.
  353. (radio-target ,@minimal-set)
  354. (strike-through ,@standard-set)
  355. (subscript ,@standard-set)
  356. (superscript ,@standard-set)
  357. ;; Ignore inline babel call and inline source block as formulas
  358. ;; are possible. Also ignore line breaks and statistics
  359. ;; cookies.
  360. (table-cell citation export-snippet footnote-reference link macro
  361. radio-target target timestamp ,@minimal-set)
  362. (table-row table-cell)
  363. (underline ,@standard-set)
  364. (verse-block ,@standard-set)))
  365. "Alist of objects restrictions.
  366. key is an element or object type containing objects and value is
  367. a list of types that can be contained within an element or object
  368. of such type.
  369. This alist also applies to secondary string. For example, an
  370. `headline' type element doesn't directly contain objects, but
  371. still has an entry since one of its properties (`:title') does.")
  372. (defconst org-element-secondary-value-alist
  373. '((citation :prefix :suffix)
  374. (headline :title)
  375. (inlinetask :title)
  376. (item :tag)
  377. (citation-reference :prefix :suffix))
  378. "Alist between element types and locations of secondary values.")
  379. (defconst org-element--pair-round-table
  380. (let ((table (make-char-table 'syntax-table '(2))))
  381. (modify-syntax-entry ?\( "()" table)
  382. (modify-syntax-entry ?\) ")(" table)
  383. table)
  384. "Table used internally to pair only round brackets.")
  385. (defconst org-element--pair-square-table
  386. (let ((table (make-char-table 'syntax-table '(2))))
  387. (modify-syntax-entry ?\[ "(]" table)
  388. (modify-syntax-entry ?\] ")[" table)
  389. table)
  390. "Table used internally to pair only square brackets.")
  391. (defconst org-element--pair-curly-table
  392. (let ((table (make-char-table 'syntax-table '(2))))
  393. (modify-syntax-entry ?\{ "(}" table)
  394. (modify-syntax-entry ?\} "){" table)
  395. table)
  396. "Table used internally to pair only curly brackets.")
  397. (defun org-element--parse-paired-brackets (char)
  398. "Parse paired brackets at point.
  399. CHAR is the opening bracket to consider, as a character. Return
  400. contents between brackets, as a string, or nil. Also move point
  401. past the brackets."
  402. (when (eq char (char-after))
  403. (let ((syntax-table (pcase char
  404. (?\{ org-element--pair-curly-table)
  405. (?\[ org-element--pair-square-table)
  406. (?\( org-element--pair-round-table)
  407. (_ nil)))
  408. (pos (point)))
  409. (when syntax-table
  410. (with-syntax-table syntax-table
  411. (let ((end (ignore-errors (scan-lists pos 1 0))))
  412. (when end
  413. (goto-char end)
  414. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  415. ;;; Accessors and Setters
  416. ;;
  417. ;; Provide four accessors: `org-element-type', `org-element-property'
  418. ;; `org-element-contents' and `org-element-restriction'.
  419. ;;
  420. ;; Setter functions allow modification of elements by side effect.
  421. ;; There is `org-element-put-property', `org-element-set-contents'.
  422. ;; These low-level functions are useful to build a parse tree.
  423. ;;
  424. ;; `org-element-adopt-elements', `org-element-set-element',
  425. ;; `org-element-extract-element' and `org-element-insert-before' are
  426. ;; high-level functions useful to modify a parse tree.
  427. ;;
  428. ;; `org-element-secondary-p' is a predicate used to know if a given
  429. ;; object belongs to a secondary string. `org-element-class' tells if
  430. ;; some parsed data is an element or an object, handling pseudo
  431. ;; elements and objects. `org-element-copy' returns an element or
  432. ;; object, stripping its parent property in the process.
  433. (defsubst org-element-type (element)
  434. "Return type of ELEMENT.
  435. The function returns the type of the element or object provided.
  436. It can also return the following special value:
  437. `plain-text' for a string
  438. `org-data' for a complete document
  439. nil in any other case."
  440. (cond
  441. ((not (consp element)) (and (stringp element) 'plain-text))
  442. ((symbolp (car element)) (car element))))
  443. (defsubst org-element-property (property element)
  444. "Extract the value from the PROPERTY of an ELEMENT."
  445. (if (stringp element) (get-text-property 0 property element)
  446. (plist-get (nth 1 element) property)))
  447. (defsubst org-element-contents (element)
  448. "Extract contents from an ELEMENT."
  449. (cond ((not (consp element)) nil)
  450. ((symbolp (car element)) (nthcdr 2 element))
  451. (t element)))
  452. (defsubst org-element-restriction (element)
  453. "Return restriction associated to ELEMENT.
  454. ELEMENT can be an element, an object or a symbol representing an
  455. element or object type."
  456. (cdr (assq (if (symbolp element) element (org-element-type element))
  457. org-element-object-restrictions)))
  458. (defsubst org-element-put-property (element property value)
  459. "In ELEMENT set PROPERTY to VALUE.
  460. Return modified element."
  461. (if (stringp element) (org-add-props element nil property value)
  462. (setcar (cdr element) (plist-put (nth 1 element) property value))
  463. element))
  464. (defsubst org-element-set-contents (element &rest contents)
  465. "Set ELEMENT's contents to CONTENTS.
  466. Return ELEMENT."
  467. (cond ((null element) contents)
  468. ((not (symbolp (car element))) contents)
  469. ((cdr element) (setcdr (cdr element) contents) element)
  470. (t (nconc element contents))))
  471. (defun org-element-secondary-p (object)
  472. "Non-nil when OBJECT directly belongs to a secondary string.
  473. Return value is the property name, as a keyword, or nil."
  474. (let* ((parent (org-element-property :parent object))
  475. (properties (cdr (assq (org-element-type parent)
  476. org-element-secondary-value-alist))))
  477. (catch 'exit
  478. (dolist (p properties)
  479. (and (memq object (org-element-property p parent))
  480. (throw 'exit p))))))
  481. (defsubst org-element-class (datum &optional parent)
  482. "Return class for ELEMENT, as a symbol.
  483. Class is either `element' or `object'. Optional argument PARENT
  484. is the element or object containing DATUM. It defaults to the
  485. value of DATUM `:parent' property."
  486. (let ((type (org-element-type datum))
  487. (parent (or parent (org-element-property :parent datum))))
  488. (cond
  489. ;; Trivial cases.
  490. ((memq type org-element-all-objects) 'object)
  491. ((memq type org-element-all-elements) 'element)
  492. ;; Special cases.
  493. ((eq type 'org-data) 'element)
  494. ((eq type 'plain-text) 'object)
  495. ((not type) 'object)
  496. ;; Pseudo object or elements. Make a guess about its class.
  497. ;; Basically a pseudo object is contained within another object,
  498. ;; a secondary string or a container element.
  499. ((not parent) 'element)
  500. (t
  501. (let ((parent-type (org-element-type parent)))
  502. (cond ((not parent-type) 'object)
  503. ((memq parent-type org-element-object-containers) 'object)
  504. ((org-element-secondary-p datum) 'object)
  505. (t 'element)))))))
  506. (defsubst org-element-adopt-elements (parent &rest children)
  507. "Append elements to the contents of another element.
  508. PARENT is an element or object. CHILDREN can be elements,
  509. objects, or a strings.
  510. The function takes care of setting `:parent' property for CHILD.
  511. Return parent element."
  512. (declare (indent 1))
  513. (if (not children) parent
  514. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  515. ;; string: parent is the list itself.
  516. (dolist (child children)
  517. (org-element-put-property child :parent (or parent children)))
  518. ;; Add CHILDREN at the end of PARENT contents.
  519. (when parent
  520. (apply #'org-element-set-contents
  521. parent
  522. (nconc (org-element-contents parent) children)))
  523. ;; Return modified PARENT element.
  524. (or parent children)))
  525. (defun org-element-extract-element (element)
  526. "Extract ELEMENT from parse tree.
  527. Remove element from the parse tree by side-effect, and return it
  528. with its `:parent' property stripped out."
  529. (let ((parent (org-element-property :parent element))
  530. (secondary (org-element-secondary-p element)))
  531. (if secondary
  532. (org-element-put-property
  533. parent secondary
  534. (delq element (org-element-property secondary parent)))
  535. (apply #'org-element-set-contents
  536. parent
  537. (delq element (org-element-contents parent))))
  538. ;; Return ELEMENT with its :parent removed.
  539. (org-element-put-property element :parent nil)))
  540. (defun org-element-insert-before (element location)
  541. "Insert ELEMENT before LOCATION in parse tree.
  542. LOCATION is an element, object or string within the parse tree.
  543. Parse tree is modified by side effect."
  544. (let* ((parent (org-element-property :parent location))
  545. (property (org-element-secondary-p location))
  546. (siblings (if property (org-element-property property parent)
  547. (org-element-contents parent)))
  548. ;; Special case: LOCATION is the first element of an
  549. ;; independent secondary string (e.g. :title property). Add
  550. ;; ELEMENT in-place.
  551. (specialp (and (not property)
  552. (eq siblings parent)
  553. (eq (car parent) location))))
  554. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  555. (cond (specialp)
  556. ((or (null siblings) (eq (car siblings) location))
  557. (push element siblings))
  558. ((null location) (nconc siblings (list element)))
  559. (t
  560. (let ((index (cl-position location siblings)))
  561. (unless index (error "No location found to insert element"))
  562. (push element (cdr (nthcdr (1- index) siblings))))))
  563. ;; Store SIBLINGS at appropriate place in parse tree.
  564. (cond
  565. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  566. (property (org-element-put-property parent property siblings))
  567. (t (apply #'org-element-set-contents parent siblings)))
  568. ;; Set appropriate :parent property.
  569. (org-element-put-property element :parent parent)))
  570. (defconst org-element--cache-element-properties '(:cached
  571. :org-element--cache-sync-key)
  572. "List of element properties used internally by cache.")
  573. (defun org-element-set-element (old new)
  574. "Replace element or object OLD with element or object NEW.
  575. The function takes care of setting `:parent' property for NEW."
  576. ;; Ensure OLD and NEW have the same parent.
  577. (org-element-put-property new :parent (org-element-property :parent old))
  578. (dolist (p org-element--cache-element-properties)
  579. (when (org-element-property p old)
  580. (org-element-put-property new p (org-element-property p old))))
  581. (if (or (memq (org-element-type old) '(plain-text nil))
  582. (memq (org-element-type new) '(plain-text nil)))
  583. ;; We cannot replace OLD with NEW since one of them is not an
  584. ;; object or element. We take the long path.
  585. (progn (org-element-insert-before new old)
  586. (org-element-extract-element old))
  587. ;; Since OLD is going to be changed into NEW by side-effect, first
  588. ;; make sure that every element or object within NEW has OLD as
  589. ;; parent.
  590. (dolist (blob (org-element-contents new))
  591. (org-element-put-property blob :parent old))
  592. ;; Transfer contents.
  593. (apply #'org-element-set-contents old (org-element-contents new))
  594. ;; Overwrite OLD's properties with NEW's.
  595. (setcar (cdr old) (nth 1 new))
  596. ;; Transfer type.
  597. (setcar old (car new))))
  598. (defun org-element-create (type &optional props &rest children)
  599. "Create a new element of type TYPE.
  600. Optional argument PROPS, when non-nil, is a plist defining the
  601. properties of the element. CHILDREN can be elements, objects or
  602. strings."
  603. (apply #'org-element-adopt-elements (list type props) children))
  604. (defun org-element-copy (datum)
  605. "Return a copy of DATUM.
  606. DATUM is an element, object, string or nil. `:parent' property
  607. is cleared and contents are removed in the process."
  608. (when datum
  609. (let ((type (org-element-type datum)))
  610. (pcase type
  611. (`org-data (list 'org-data nil))
  612. (`plain-text (substring-no-properties datum))
  613. (`nil (copy-sequence datum))
  614. (_
  615. (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
  616. ;; We cannot simply return the copies property list. When
  617. ;; DATUM is i.e. a headline, it's property list (`:title'
  618. ;; in case of headline) can contain parsed objects. The
  619. ;; objects will contain `:parent' property set to the DATUM
  620. ;; iteself. When copied, these inner `:parent' propery
  621. ;; values will contain incorrect object decoupled from
  622. ;; DATUM. Changes to the DATUM copy will not longer be
  623. ;; reflected in the `:parent' properties. So, we need to
  624. ;; reassign inner `:parent' propreties to the DATUM copy
  625. ;; explicitly.
  626. (org-element-map element-copy (cons 'plain-text org-element-all-objects)
  627. (lambda (obj) (when (equal datum (org-element-property :parent obj))
  628. (org-element-put-property obj :parent element-copy))))
  629. element-copy))))))
  630. ;;; Greater elements
  631. ;;
  632. ;; For each greater element type, we define a parser and an
  633. ;; interpreter.
  634. ;;
  635. ;; A parser returns the element or object as the list described above.
  636. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  637. ;; every element containing a secondary string (see
  638. ;; `org-element-secondary-value-alist') will accept an optional
  639. ;; argument to toggle parsing of these secondary strings. Moreover,
  640. ;; `item' parser requires current list's structure as its first
  641. ;; element.
  642. ;;
  643. ;; An interpreter accepts two arguments: the list representation of
  644. ;; the element or object, and its contents. The latter may be nil,
  645. ;; depending on the element or object considered. It returns the
  646. ;; appropriate Org syntax, as a string.
  647. ;;
  648. ;; Parsing functions must follow the naming convention:
  649. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  650. ;; defined in `org-element-greater-elements'.
  651. ;;
  652. ;; Similarly, interpreting functions must follow the naming
  653. ;; convention: org-element-TYPE-interpreter.
  654. ;;
  655. ;; With the exception of `headline' and `item' types, greater elements
  656. ;; cannot contain other greater elements of their own type.
  657. ;;
  658. ;; Beside implementing a parser and an interpreter, adding a new
  659. ;; greater element requires tweaking `org-element--current-element'.
  660. ;; Moreover, the newly defined type must be added to both
  661. ;; `org-element-all-elements' and `org-element-greater-elements'.
  662. ;;;; Center Block
  663. (defun org-element-center-block-parser (limit affiliated)
  664. "Parse a center block.
  665. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  666. the buffer position at the beginning of the first affiliated
  667. keyword and CDR is a plist of affiliated keywords along with
  668. their value.
  669. Return a list whose CAR is `center-block' and CDR is a plist
  670. containing `:begin', `:end', `:contents-begin', `:contents-end',
  671. `:post-blank' and `:post-affiliated' keywords.
  672. Assume point is at the beginning of the block."
  673. (let ((case-fold-search t))
  674. (if (not (save-excursion
  675. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  676. ;; Incomplete block: parse it as a paragraph.
  677. (org-element-paragraph-parser limit affiliated)
  678. (let ((block-end-line (match-beginning 0)))
  679. (let* ((begin (car affiliated))
  680. (post-affiliated (point))
  681. ;; Empty blocks have no contents.
  682. (contents-begin (progn (forward-line)
  683. (and (< (point) block-end-line)
  684. (point))))
  685. (contents-end (and contents-begin block-end-line))
  686. (pos-before-blank (progn (goto-char block-end-line)
  687. (forward-line)
  688. (point)))
  689. (end (save-excursion
  690. (skip-chars-forward " \r\t\n" limit)
  691. (if (eobp) (point) (line-beginning-position)))))
  692. (list 'center-block
  693. (nconc
  694. (list :begin begin
  695. :end end
  696. :contents-begin contents-begin
  697. :contents-end contents-end
  698. :post-blank (count-lines pos-before-blank end)
  699. :post-affiliated post-affiliated)
  700. (cdr affiliated))))))))
  701. (defun org-element-center-block-interpreter (_ contents)
  702. "Interpret a center-block element as Org syntax.
  703. CONTENTS is the contents of the element."
  704. (format "#+begin_center\n%s#+end_center" contents))
  705. ;;;; Drawer
  706. (defun org-element-drawer-parser (limit affiliated)
  707. "Parse a drawer.
  708. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  709. the buffer position at the beginning of the first affiliated
  710. keyword and CDR is a plist of affiliated keywords along with
  711. their value.
  712. Return a list whose CAR is `drawer' and CDR is a plist containing
  713. `:drawer-name', `:begin', `:end', `:contents-begin',
  714. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  715. Assume point is at beginning of drawer."
  716. (let ((case-fold-search t))
  717. (if (not (save-excursion
  718. (goto-char (min limit (line-end-position)))
  719. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  720. ;; Incomplete drawer: parse it as a paragraph.
  721. (org-element-paragraph-parser limit affiliated)
  722. (save-excursion
  723. (let* ((drawer-end-line (match-beginning 0))
  724. (name
  725. (progn
  726. (looking-at org-element-drawer-re)
  727. (match-string-no-properties 1)))
  728. (begin (car affiliated))
  729. (post-affiliated (point))
  730. ;; Empty drawers have no contents.
  731. (contents-begin (progn (forward-line)
  732. (and (< (point) drawer-end-line)
  733. (point))))
  734. (contents-end (and contents-begin drawer-end-line))
  735. (pos-before-blank (progn (goto-char drawer-end-line)
  736. (forward-line)
  737. (point)))
  738. (end (progn (skip-chars-forward " \r\t\n" limit)
  739. (if (eobp) (point) (line-beginning-position)))))
  740. (list 'drawer
  741. (nconc
  742. (list :begin begin
  743. :end end
  744. :drawer-name name
  745. :contents-begin contents-begin
  746. :contents-end contents-end
  747. :post-blank (count-lines pos-before-blank end)
  748. :post-affiliated post-affiliated)
  749. (cdr affiliated))))))))
  750. (defun org-element-drawer-interpreter (drawer contents)
  751. "Interpret DRAWER element as Org syntax.
  752. CONTENTS is the contents of the element."
  753. (format ":%s:\n%s:END:"
  754. (org-element-property :drawer-name drawer)
  755. contents))
  756. ;;;; Dynamic Block
  757. (defun org-element-dynamic-block-parser (limit affiliated)
  758. "Parse a dynamic block.
  759. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  760. the buffer position at the beginning of the first affiliated
  761. keyword and CDR is a plist of affiliated keywords along with
  762. their value.
  763. Return a list whose CAR is `dynamic-block' and CDR is a plist
  764. containing `:block-name', `:begin', `:end', `:contents-begin',
  765. `:contents-end', `:arguments', `:post-blank' and
  766. `:post-affiliated' keywords.
  767. Assume point is at beginning of dynamic block."
  768. (let ((case-fold-search t))
  769. (if (not (save-excursion
  770. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  771. ;; Incomplete block: parse it as a paragraph.
  772. (org-element-paragraph-parser limit affiliated)
  773. (let ((block-end-line (match-beginning 0)))
  774. (save-excursion
  775. (let* ((name (progn
  776. (looking-at org-element-dynamic-block-open-re)
  777. (match-string-no-properties 1)))
  778. (arguments (match-string-no-properties 2))
  779. (begin (car affiliated))
  780. (post-affiliated (point))
  781. ;; Empty blocks have no contents.
  782. (contents-begin (progn (forward-line)
  783. (and (< (point) block-end-line)
  784. (point))))
  785. (contents-end (and contents-begin block-end-line))
  786. (pos-before-blank (progn (goto-char block-end-line)
  787. (forward-line)
  788. (point)))
  789. (end (progn (skip-chars-forward " \r\t\n" limit)
  790. (if (eobp) (point) (line-beginning-position)))))
  791. (list 'dynamic-block
  792. (nconc
  793. (list :begin begin
  794. :end end
  795. :block-name name
  796. :arguments arguments
  797. :contents-begin contents-begin
  798. :contents-end contents-end
  799. :post-blank (count-lines pos-before-blank end)
  800. :post-affiliated post-affiliated)
  801. (cdr affiliated)))))))))
  802. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  803. "Interpret DYNAMIC-BLOCK element as Org syntax.
  804. CONTENTS is the contents of the element."
  805. (format "#+begin: %s%s\n%s#+end:"
  806. (org-element-property :block-name dynamic-block)
  807. (let ((args (org-element-property :arguments dynamic-block)))
  808. (if args (concat " " args) ""))
  809. contents))
  810. ;;;; Footnote Definition
  811. (defconst org-element--footnote-separator
  812. (concat org-element-headline-re "\\|"
  813. org-footnote-definition-re "\\|"
  814. "^\\([ \t]*\n\\)\\{2,\\}")
  815. "Regexp used as a footnote definition separator.")
  816. (defun org-element-footnote-definition-parser (limit affiliated)
  817. "Parse a footnote definition.
  818. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  819. the buffer position at the beginning of the first affiliated
  820. keyword and CDR is a plist of affiliated keywords along with
  821. their value.
  822. Return a list whose CAR is `footnote-definition' and CDR is
  823. a plist containing `:label', `:begin' `:end', `:contents-begin',
  824. `:contents-end', `:pre-blank',`:post-blank' and
  825. `:post-affiliated' keywords.
  826. Assume point is at the beginning of the footnote definition."
  827. (save-excursion
  828. (let* ((label (progn (looking-at org-footnote-definition-re)
  829. (match-string-no-properties 1)))
  830. (begin (car affiliated))
  831. (post-affiliated (point))
  832. (end
  833. (save-excursion
  834. (end-of-line)
  835. (cond
  836. ((not
  837. (re-search-forward org-element--footnote-separator limit t))
  838. limit)
  839. ((eq ?\[ (char-after (match-beginning 0)))
  840. ;; At a new footnote definition, make sure we end
  841. ;; before any affiliated keyword above.
  842. (forward-line -1)
  843. (while (and (> (point) post-affiliated)
  844. (looking-at-p org-element--affiliated-re))
  845. (forward-line -1))
  846. (line-beginning-position 2))
  847. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  848. (t (skip-chars-forward " \r\t\n" limit)
  849. (if (= limit (point)) limit (line-beginning-position))))))
  850. (pre-blank 0)
  851. (contents-begin
  852. (progn (search-forward "]")
  853. (skip-chars-forward " \r\t\n" end)
  854. (cond ((= (point) end) nil)
  855. ((= (line-beginning-position) post-affiliated) (point))
  856. (t
  857. (setq pre-blank
  858. (count-lines (line-beginning-position) begin))
  859. (line-beginning-position)))))
  860. (contents-end
  861. (progn (goto-char end)
  862. (skip-chars-backward " \r\t\n")
  863. (line-beginning-position 2))))
  864. (list 'footnote-definition
  865. (nconc
  866. (list :label label
  867. :begin begin
  868. :end end
  869. :contents-begin contents-begin
  870. :contents-end (and contents-begin contents-end)
  871. :pre-blank pre-blank
  872. :post-blank (count-lines contents-end end)
  873. :post-affiliated post-affiliated)
  874. (cdr affiliated))))))
  875. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  876. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  877. CONTENTS is the contents of the footnote-definition."
  878. (let ((pre-blank
  879. (min (or (org-element-property :pre-blank footnote-definition)
  880. ;; 0 is specific to paragraphs at the beginning of
  881. ;; the footnote definition, so we use 1 as
  882. ;; a fall-back value, which is more universal.
  883. 1)
  884. ;; Footnote ends after more than two consecutive empty
  885. ;; lines: limit ourselves to 2 newline characters.
  886. 2)))
  887. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  888. (if (= pre-blank 0) (concat " " (org-trim contents))
  889. (concat (make-string pre-blank ?\n) contents)))))
  890. ;;;; Headline
  891. (defun org-element--get-node-properties (&optional at-point-p?)
  892. "Return node properties for headline or property drawer at point.
  893. Upcase property names. It avoids confusion between properties
  894. obtained through property drawer and default properties from the
  895. parser (e.g. `:end' and :END:). Return value is a plist.
  896. When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
  897. parse properties for property drawer at point."
  898. (save-excursion
  899. (unless at-point-p?
  900. (forward-line)
  901. (when (looking-at-p org-element-planning-line-re) (forward-line)))
  902. (when (looking-at org-property-drawer-re)
  903. (forward-line)
  904. (let ((end (match-end 0)) properties)
  905. (while (< (line-end-position) end)
  906. (looking-at org-property-re)
  907. (let* ((property-name (concat ":" (upcase (match-string 2))))
  908. (property-name-symbol (intern property-name))
  909. (property-value (match-string-no-properties 3)))
  910. (cond
  911. ((and (plist-member properties property-name-symbol)
  912. (string-match-p "+$" property-name))
  913. (let ((val (plist-get properties property-name-symbol)))
  914. (if (listp val)
  915. (setq properties
  916. (plist-put properties
  917. property-name-symbol
  918. (append (plist-get properties property-name-symbol)
  919. (list property-value))))
  920. (plist-put properties property-name-symbol (list val property-value)))))
  921. (t (setq properties (plist-put properties property-name-symbol property-value)))))
  922. (forward-line))
  923. properties))))
  924. (defun org-element--get-time-properties ()
  925. "Return time properties associated to headline at point.
  926. Return value is a plist."
  927. (save-excursion
  928. (when (progn (forward-line) (looking-at org-element-planning-line-re))
  929. (let ((end (line-end-position))
  930. plist)
  931. (while (re-search-forward org-element-planning-keywords-re end t)
  932. (skip-chars-forward " \t")
  933. (let ((keyword (match-string 0))
  934. (time (org-element-timestamp-parser)))
  935. (cond ((equal keyword org-element-scheduled-keyword)
  936. (setq plist (plist-put plist :scheduled time)))
  937. ((equal keyword org-element-deadline-keyword)
  938. (setq plist (plist-put plist :deadline time)))
  939. (t (setq plist (plist-put plist :closed time))))))
  940. plist))))
  941. (defun org-element-headline-parser (&optional _ raw-secondary-p)
  942. "Parse a headline.
  943. Return a list whose CAR is `headline' and CDR is a plist
  944. containing `:raw-value', `:title', `:begin', `:end',
  945. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  946. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  947. `:deadline', `:closed', `:archivedp', `:commentedp'
  948. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  949. keywords.
  950. The plist also contains any property set in the property drawer,
  951. with its name in upper cases and colons added at the
  952. beginning (e.g., `:CUSTOM_ID').
  953. When RAW-SECONDARY-P is non-nil, headline's title will not be
  954. parsed as a secondary string, but as a plain string instead.
  955. Assume point is at beginning of the headline."
  956. (save-excursion
  957. (let* ((begin (point))
  958. (true-level (prog1 (skip-chars-forward "*")
  959. (skip-chars-forward " \t")))
  960. (level (org-reduced-level true-level))
  961. (todo (and org-todo-regexp
  962. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  963. (progn (goto-char (match-end 0))
  964. (skip-chars-forward " \t")
  965. (match-string 1))))
  966. (todo-type
  967. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  968. (priority (and (looking-at "\\[#.\\][ \t]*")
  969. (progn (goto-char (match-end 0))
  970. (aref (match-string 0) 2))))
  971. (commentedp
  972. (and (let ((case-fold-search nil))
  973. (looking-at org-element-comment-string))
  974. (goto-char (match-end 0))))
  975. (title-start (prog1 (point)
  976. (unless (or todo priority commentedp)
  977. ;; Headline like "* :tag:"
  978. (skip-chars-backward " \t"))))
  979. (tags (when (re-search-forward
  980. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  981. (line-end-position)
  982. 'move)
  983. (goto-char (match-beginning 0))
  984. (org-split-string (match-string 1) ":")))
  985. (title-end (point))
  986. (raw-value (org-trim
  987. (buffer-substring-no-properties title-start title-end)))
  988. (archivedp (member org-element-archive-tag tags))
  989. (footnote-section-p (and org-footnote-section
  990. (string= org-footnote-section raw-value)))
  991. (standard-props (org-element--get-node-properties))
  992. (time-props (org-element--get-time-properties))
  993. (end
  994. (save-excursion
  995. (let ((re (rx-to-string
  996. `(seq line-start (** 1 ,true-level "*") " "))))
  997. (if (re-search-forward re nil t)
  998. (line-beginning-position)
  999. (point-max)))))
  1000. (contents-begin (save-excursion
  1001. (forward-line)
  1002. (skip-chars-forward " \r\t\n" end)
  1003. (and (/= (point) end) (line-beginning-position))))
  1004. (contents-end (and contents-begin
  1005. (progn (goto-char end)
  1006. (skip-chars-backward " \r\t\n")
  1007. (line-beginning-position 2))))
  1008. (robust-begin (and contents-begin
  1009. (progn (goto-char contents-begin)
  1010. (when (looking-at-p org-element-planning-line-re)
  1011. (forward-line))
  1012. (when (looking-at org-property-drawer-re)
  1013. (goto-char (match-end 0)))
  1014. ;; If there is :pre-blank, we
  1015. ;; need to be careful about
  1016. ;; robust beginning.
  1017. (max (if (< (+ 2 contents-begin) contents-end)
  1018. (+ 2 contents-begin)
  1019. 0)
  1020. (point)))))
  1021. (robust-end (and robust-begin
  1022. (when (> (- contents-end 2) robust-begin)
  1023. (- contents-end 2)))))
  1024. (unless robust-end (setq robust-begin nil))
  1025. (let ((headline
  1026. (list 'headline
  1027. (nconc
  1028. (list :raw-value raw-value
  1029. :begin begin
  1030. :end end
  1031. :pre-blank
  1032. (if (not contents-begin) 0
  1033. (1- (count-lines begin contents-begin)))
  1034. :contents-begin contents-begin
  1035. :contents-end contents-end
  1036. :robust-begin robust-begin
  1037. :robust-end robust-end
  1038. :level level
  1039. :priority priority
  1040. :tags tags
  1041. :todo-keyword todo
  1042. :todo-type todo-type
  1043. :post-blank
  1044. (if contents-end
  1045. (count-lines contents-end end)
  1046. (1- (count-lines begin end)))
  1047. :footnote-section-p footnote-section-p
  1048. :archivedp archivedp
  1049. :commentedp commentedp
  1050. :post-affiliated begin)
  1051. time-props
  1052. standard-props))))
  1053. (org-element-put-property
  1054. headline :title
  1055. (if raw-secondary-p raw-value
  1056. (org-element--parse-objects
  1057. (progn (goto-char title-start)
  1058. (skip-chars-forward " \t")
  1059. (point))
  1060. (progn (goto-char title-end)
  1061. (skip-chars-backward " \t")
  1062. (point))
  1063. nil
  1064. (org-element-restriction 'headline)
  1065. headline)))))))
  1066. (defun org-element-headline-interpreter (headline contents)
  1067. "Interpret HEADLINE element as Org syntax.
  1068. CONTENTS is the contents of the element."
  1069. (let* ((level (org-element-property :level headline))
  1070. (todo (org-element-property :todo-keyword headline))
  1071. (priority (org-element-property :priority headline))
  1072. (title (org-element-interpret-data
  1073. (org-element-property :title headline)))
  1074. (tags (let ((tag-list (org-element-property :tags headline)))
  1075. (and tag-list
  1076. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  1077. (commentedp (org-element-property :commentedp headline))
  1078. (pre-blank (or (org-element-property :pre-blank headline) 0))
  1079. (heading
  1080. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  1081. ?*)
  1082. (and todo (concat " " todo))
  1083. (and commentedp (concat " " org-element-comment-string))
  1084. (and priority (format " [#%c]" priority))
  1085. " "
  1086. (if (and org-footnote-section
  1087. (org-element-property :footnote-section-p headline))
  1088. org-footnote-section
  1089. title))))
  1090. (concat
  1091. heading
  1092. ;; Align tags.
  1093. (when tags
  1094. (cond
  1095. ((zerop org-tags-column) (format " %s" tags))
  1096. ((< org-tags-column 0)
  1097. (concat
  1098. (make-string
  1099. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1100. ?\s)
  1101. tags))
  1102. (t
  1103. (concat
  1104. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1105. tags))))
  1106. (make-string (1+ pre-blank) ?\n)
  1107. contents)))
  1108. ;;;; org-data
  1109. (defun org-element--get-global-node-properties ()
  1110. "Return node properties associated with the whole Org buffer.
  1111. Upcase property names. It avoids confusion between properties
  1112. obtained through property drawer and default properties from the
  1113. parser (e.g. `:end' and :END:). Return value is a plist."
  1114. (org-with-wide-buffer
  1115. (goto-char (point-min))
  1116. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1117. (org-element--get-node-properties t)))
  1118. (defvar org-element-org-data-parser--recurse nil)
  1119. (defun org-element-org-data-parser (&optional _)
  1120. "Parse org-data."
  1121. (org-with-wide-buffer
  1122. (let* ((begin 1)
  1123. (contents-begin (progn
  1124. (goto-char 1)
  1125. (org-skip-whitespace)
  1126. (beginning-of-line)
  1127. (point)))
  1128. (end (point-max))
  1129. (pos-before-blank (progn (goto-char (point-max))
  1130. (skip-chars-backward " \r\t\n")
  1131. (line-beginning-position 2)))
  1132. (robust-end (when (> (- pos-before-blank 2) contents-begin)
  1133. (- pos-before-blank 2)))
  1134. (robust-begin (when (and robust-end
  1135. (< (+ 2 contents-begin) pos-before-blank))
  1136. (or
  1137. (org-with-wide-buffer
  1138. (goto-char (point-min))
  1139. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1140. (when (looking-at org-property-drawer-re)
  1141. (goto-char (match-end 0))
  1142. (skip-chars-backward " \t")
  1143. (min robust-end (point))))
  1144. (+ 2 contents-begin))))
  1145. (category (cond ((null org-category)
  1146. (when (with-current-buffer
  1147. (or (buffer-base-buffer)
  1148. (current-buffer))
  1149. buffer-file-name)
  1150. (file-name-sans-extension
  1151. (file-name-nondirectory
  1152. (with-current-buffer
  1153. (or (buffer-base-buffer)
  1154. (current-buffer))
  1155. buffer-file-name)))))
  1156. ((symbolp org-category) (symbol-name org-category))
  1157. (t org-category)))
  1158. (category (catch 'buffer-category
  1159. (unless org-element-org-data-parser--recurse
  1160. (org-with-point-at end
  1161. ;; Avoid recusrive calls from
  1162. ;; `org-element-at-point-no-context'.
  1163. (let ((org-element-org-data-parser--recurse t))
  1164. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  1165. (org-element-with-disabled-cache
  1166. (let ((element (org-element-at-point-no-context)))
  1167. (when (eq (org-element-type element) 'keyword)
  1168. (throw 'buffer-category
  1169. (org-element-property :value element)))))))))
  1170. category))
  1171. (properties (org-element--get-global-node-properties)))
  1172. (unless (plist-get properties :CATEGORY)
  1173. (setq properties (plist-put properties :CATEGORY category)))
  1174. (list 'org-data
  1175. (nconc
  1176. (list :begin begin
  1177. :contents-begin contents-begin
  1178. :contents-end pos-before-blank
  1179. :end end
  1180. :robust-begin robust-begin
  1181. :robust-end robust-end
  1182. :post-blank (count-lines pos-before-blank end)
  1183. :post-affiliated begin
  1184. :path (buffer-file-name)
  1185. :mode 'org-data)
  1186. properties)))))
  1187. (defun org-element-org-data-interpreter (_ contents)
  1188. "Interpret ORG-DATA element as Org syntax.
  1189. CONTENTS is the contents of the element."
  1190. contents)
  1191. ;;;; Inlinetask
  1192. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1193. "Parse an inline task.
  1194. Return a list whose CAR is `inlinetask' and CDR is a plist
  1195. containing `:title', `:begin', `:end', `:pre-blank',
  1196. `:contents-begin' and `:contents-end', `:level', `:priority',
  1197. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1198. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1199. `:post-affiliated' keywords.
  1200. The plist also contains any property set in the property drawer,
  1201. with its name in upper cases and colons added at the
  1202. beginning (e.g., `:CUSTOM_ID').
  1203. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1204. title will not be parsed as a secondary string, but as a plain
  1205. string instead.
  1206. Assume point is at beginning of the inline task."
  1207. (save-excursion
  1208. (let* ((begin (point))
  1209. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1210. (skip-chars-forward " \t")))
  1211. (todo (and org-todo-regexp
  1212. (let (case-fold-search) (looking-at org-todo-regexp))
  1213. (progn (goto-char (match-end 0))
  1214. (skip-chars-forward " \t")
  1215. (match-string 0))))
  1216. (todo-type (and todo
  1217. (if (member todo org-done-keywords) 'done 'todo)))
  1218. (priority (and (looking-at "\\[#.\\][ \t]*")
  1219. (progn (goto-char (match-end 0))
  1220. (aref (match-string 0) 2))))
  1221. (title-start (point))
  1222. (tags (when (re-search-forward
  1223. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1224. (line-end-position)
  1225. 'move)
  1226. (goto-char (match-beginning 0))
  1227. (org-split-string (match-string 1) ":")))
  1228. (title-end (point))
  1229. (raw-value (org-trim
  1230. (buffer-substring-no-properties title-start title-end)))
  1231. (task-end (save-excursion
  1232. (end-of-line)
  1233. (and (re-search-forward org-element-headline-re limit t)
  1234. (looking-at-p "[ \t]*END[ \t]*$")
  1235. (line-beginning-position))))
  1236. (standard-props (and task-end (org-element--get-node-properties)))
  1237. (time-props (and task-end (org-element--get-time-properties)))
  1238. (contents-begin (and task-end
  1239. (< (point) task-end)
  1240. (progn
  1241. (forward-line)
  1242. (skip-chars-forward " \t\n")
  1243. (line-beginning-position))))
  1244. (contents-end (and contents-begin task-end))
  1245. (end (progn (when task-end (goto-char task-end))
  1246. (forward-line)
  1247. (skip-chars-forward " \r\t\n" limit)
  1248. (if (eobp) (point) (line-beginning-position))))
  1249. (inlinetask
  1250. (list 'inlinetask
  1251. (nconc
  1252. (list :raw-value raw-value
  1253. :begin begin
  1254. :end end
  1255. :pre-blank
  1256. (if (not contents-begin) 0
  1257. (1- (count-lines begin contents-begin)))
  1258. :contents-begin contents-begin
  1259. :contents-end contents-end
  1260. :level level
  1261. :priority priority
  1262. :tags tags
  1263. :todo-keyword todo
  1264. :todo-type todo-type
  1265. :post-blank (1- (count-lines (or task-end begin) end))
  1266. :post-affiliated begin)
  1267. time-props
  1268. standard-props))))
  1269. (org-element-put-property
  1270. inlinetask :title
  1271. (if raw-secondary-p raw-value
  1272. (org-element--parse-objects
  1273. (progn (goto-char title-start)
  1274. (skip-chars-forward " \t")
  1275. (point))
  1276. (progn (goto-char title-end)
  1277. (skip-chars-backward " \t")
  1278. (point))
  1279. nil
  1280. (org-element-restriction 'inlinetask)
  1281. inlinetask))))))
  1282. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1283. "Interpret INLINETASK element as Org syntax.
  1284. CONTENTS is the contents of inlinetask."
  1285. (let* ((level (org-element-property :level inlinetask))
  1286. (todo (org-element-property :todo-keyword inlinetask))
  1287. (priority (org-element-property :priority inlinetask))
  1288. (title (org-element-interpret-data
  1289. (org-element-property :title inlinetask)))
  1290. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1291. (and tag-list
  1292. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1293. (task (concat (make-string level ?*)
  1294. (and todo (concat " " todo))
  1295. (and priority (format " [#%c]" priority))
  1296. (and title (concat " " title)))))
  1297. (concat task
  1298. ;; Align tags.
  1299. (when tags
  1300. (cond
  1301. ((zerop org-tags-column) (format " %s" tags))
  1302. ((< org-tags-column 0)
  1303. (concat
  1304. (make-string
  1305. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1306. ?\s)
  1307. tags))
  1308. (t
  1309. (concat
  1310. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1311. tags))))
  1312. ;; Prefer degenerate inlinetasks when there are no
  1313. ;; contents.
  1314. (when contents
  1315. (concat "\n"
  1316. contents
  1317. (make-string level ?*) " end")))))
  1318. ;;;; Item
  1319. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1320. "Parse an item.
  1321. STRUCT is the structure of the plain list.
  1322. Return a list whose CAR is `item' and CDR is a plist containing
  1323. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1324. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1325. `:post-blank' and `:post-affiliated' keywords.
  1326. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1327. any, will not be parsed as a secondary string, but as a plain
  1328. string instead.
  1329. Assume point is at the beginning of the item."
  1330. (save-excursion
  1331. (beginning-of-line)
  1332. (looking-at org-list-full-item-re)
  1333. (let* ((begin (point))
  1334. (bullet (match-string-no-properties 1))
  1335. (checkbox (let ((box (match-string 3)))
  1336. (cond ((equal "[ ]" box) 'off)
  1337. ((equal "[X]" box) 'on)
  1338. ((equal "[-]" box) 'trans))))
  1339. (counter (let ((c (match-string 2)))
  1340. (save-match-data
  1341. (cond
  1342. ((not c) nil)
  1343. ((string-match "[A-Za-z]" c)
  1344. (- (string-to-char (upcase (match-string 0 c)))
  1345. 64))
  1346. ((string-match "[0-9]+" c)
  1347. (string-to-number (match-string 0 c)))))))
  1348. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1349. (if (bolp) (point) (line-beginning-position 2))))
  1350. (pre-blank 0)
  1351. (contents-begin
  1352. (progn
  1353. (goto-char
  1354. ;; Ignore tags in un-ordered lists: they are just
  1355. ;; a part of item's body.
  1356. (if (and (match-beginning 4)
  1357. (save-match-data (string-match "[.)]" bullet)))
  1358. (match-beginning 4)
  1359. (match-end 0)))
  1360. (skip-chars-forward " \r\t\n" end)
  1361. (cond ((= (point) end) nil)
  1362. ;; If first line isn't empty, contents really
  1363. ;; start at the text after item's meta-data.
  1364. ((= (line-beginning-position) begin) (point))
  1365. (t
  1366. (setq pre-blank
  1367. (count-lines (line-beginning-position) begin))
  1368. (line-beginning-position)))))
  1369. (contents-end (and contents-begin
  1370. (progn (goto-char end)
  1371. (skip-chars-backward " \r\t\n")
  1372. (line-beginning-position 2))))
  1373. (item
  1374. (list 'item
  1375. (list :bullet bullet
  1376. :begin begin
  1377. :end end
  1378. :contents-begin contents-begin
  1379. :contents-end contents-end
  1380. :checkbox checkbox
  1381. :counter counter
  1382. :structure struct
  1383. :pre-blank pre-blank
  1384. :post-blank (count-lines (or contents-end begin) end)
  1385. :post-affiliated begin))))
  1386. (org-element-put-property
  1387. item :tag
  1388. (let ((raw (org-list-get-tag begin struct)))
  1389. (when raw
  1390. (if raw-secondary-p raw
  1391. (org-element--parse-objects
  1392. (match-beginning 4) (match-end 4) nil
  1393. (org-element-restriction 'item)
  1394. item))))))))
  1395. (defun org-element-item-interpreter (item contents)
  1396. "Interpret ITEM element as Org syntax.
  1397. CONTENTS is the contents of the element."
  1398. (let ((tag (pcase (org-element-property :tag item)
  1399. (`nil nil)
  1400. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1401. (bullet
  1402. (org-list-bullet-string
  1403. (cond
  1404. ((not (string-match-p "[0-9a-zA-Z]"
  1405. (org-element-property :bullet item))) "- ")
  1406. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1407. (t "1.")))))
  1408. (concat
  1409. bullet
  1410. (pcase (org-element-property :counter item)
  1411. (`nil nil)
  1412. (counter (format "[@%d] " counter)))
  1413. (pcase (org-element-property :checkbox item)
  1414. (`on "[X] ")
  1415. (`off "[ ] ")
  1416. (`trans "[-] ")
  1417. (_ nil))
  1418. tag
  1419. (when contents
  1420. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1421. (pre-blank
  1422. (min (or (org-element-property :pre-blank item)
  1423. ;; 0 is specific to paragraphs at the
  1424. ;; beginning of the item, so we use 1 as
  1425. ;; a fall-back value, which is more universal.
  1426. 1)
  1427. ;; Lists ends after more than two consecutive
  1428. ;; empty lines: limit ourselves to 2 newline
  1429. ;; characters.
  1430. 2))
  1431. (contents (replace-regexp-in-string
  1432. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1433. (if (= pre-blank 0) (org-trim contents)
  1434. (concat (make-string pre-blank ?\n) contents)))))))
  1435. ;;;; Plain List
  1436. (defun org-element--list-struct (limit)
  1437. ;; Return structure of list at point. Internal function. See
  1438. ;; `org-list-struct' for details.
  1439. (let ((case-fold-search t)
  1440. (top-ind limit)
  1441. (item-re (org-item-re))
  1442. (inlinetask-re (and (featurep 'org-inlinetask)
  1443. (boundp 'org-inlinetask-min-level)
  1444. (boundp 'org-inlinetask-max-level)
  1445. (format "^\\*\\{%d,%d\\}+ "
  1446. org-inlinetask-min-level
  1447. org-inlinetask-max-level)))
  1448. items struct)
  1449. (save-excursion
  1450. (catch :exit
  1451. (while t
  1452. (cond
  1453. ;; At limit: end all items.
  1454. ((>= (point) limit)
  1455. (let ((end (progn (skip-chars-backward " \r\t\n")
  1456. (line-beginning-position 2))))
  1457. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1458. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1459. ;; At list end: end all items.
  1460. ((looking-at org-list-end-re)
  1461. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1462. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1463. ;; At a new item: end previous sibling.
  1464. ((looking-at item-re)
  1465. (let ((ind (save-excursion (skip-chars-forward " \t")
  1466. (current-column))))
  1467. (setq top-ind (min top-ind ind))
  1468. (while (and items (<= ind (nth 1 (car items))))
  1469. (let ((item (pop items)))
  1470. (setcar (nthcdr 6 item) (point))
  1471. (push item struct)))
  1472. (push (progn (looking-at org-list-full-item-re)
  1473. (let ((bullet (match-string-no-properties 1)))
  1474. (list (point)
  1475. ind
  1476. bullet
  1477. (match-string-no-properties 2) ; counter
  1478. (match-string-no-properties 3) ; checkbox
  1479. ;; Description tag.
  1480. (and (save-match-data
  1481. (string-match "[-+*]" bullet))
  1482. (match-string-no-properties 4))
  1483. ;; Ending position, unknown so far.
  1484. nil)))
  1485. items))
  1486. (forward-line))
  1487. ;; Skip empty lines.
  1488. ((looking-at "^[ \t]*$") (forward-line))
  1489. ;; Skip inline tasks and blank lines along the way.
  1490. ((and inlinetask-re (looking-at inlinetask-re))
  1491. (forward-line)
  1492. (let ((origin (point)))
  1493. (when (re-search-forward inlinetask-re limit t)
  1494. (if (looking-at-p "END[ \t]*$") (forward-line)
  1495. (goto-char origin)))))
  1496. ;; At some text line. Check if it ends any previous item.
  1497. (t
  1498. (let ((ind (save-excursion
  1499. (skip-chars-forward " \t")
  1500. (current-column)))
  1501. (end (save-excursion
  1502. (skip-chars-backward " \r\t\n")
  1503. (line-beginning-position 2))))
  1504. (while (<= ind (nth 1 (car items)))
  1505. (let ((item (pop items)))
  1506. (setcar (nthcdr 6 item) end)
  1507. (push item struct)
  1508. (unless items
  1509. (throw :exit (sort struct #'car-less-than-car))))))
  1510. ;; Skip blocks (any type) and drawers contents.
  1511. (cond
  1512. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1513. (re-search-forward
  1514. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1515. limit t)))
  1516. ((and (looking-at org-element-drawer-re)
  1517. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1518. (forward-line))))))))
  1519. (defun org-element-plain-list-parser (limit affiliated structure)
  1520. "Parse a plain list.
  1521. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1522. the buffer position at the beginning of the first affiliated
  1523. keyword and CDR is a plist of affiliated keywords along with
  1524. their value. STRUCTURE is the structure of the plain list being
  1525. parsed.
  1526. Return a list whose CAR is `plain-list' and CDR is a plist
  1527. containing `:type', `:begin', `:end', `:contents-begin' and
  1528. `:contents-end', `:structure', `:post-blank' and
  1529. `:post-affiliated' keywords.
  1530. Assume point is at the beginning of the list."
  1531. (save-excursion
  1532. (let* ((struct (or structure (org-element--list-struct limit)))
  1533. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1534. ((nth 5 (assq (point) struct)) 'descriptive)
  1535. (t 'unordered)))
  1536. (contents-begin (point))
  1537. (begin (car affiliated))
  1538. (contents-end (let* ((item (assq contents-begin struct))
  1539. (ind (nth 1 item))
  1540. (pos (nth 6 item)))
  1541. (while (and (setq item (assq pos struct))
  1542. (= (nth 1 item) ind))
  1543. (setq pos (nth 6 item)))
  1544. pos))
  1545. (end (progn (goto-char contents-end)
  1546. (skip-chars-forward " \r\t\n" limit)
  1547. (if (= (point) limit) limit (line-beginning-position)))))
  1548. ;; Return value.
  1549. (list 'plain-list
  1550. (nconc
  1551. (list :type type
  1552. :begin begin
  1553. :end end
  1554. :contents-begin contents-begin
  1555. :contents-end contents-end
  1556. :structure struct
  1557. :post-blank (count-lines contents-end end)
  1558. :post-affiliated contents-begin)
  1559. (cdr affiliated))))))
  1560. (defun org-element-plain-list-interpreter (_ contents)
  1561. "Interpret plain-list element as Org syntax.
  1562. CONTENTS is the contents of the element."
  1563. (with-temp-buffer
  1564. (insert contents)
  1565. (goto-char (point-min))
  1566. (org-list-repair)
  1567. (buffer-string)))
  1568. ;;;; Property Drawer
  1569. (defun org-element-property-drawer-parser (limit)
  1570. "Parse a property drawer.
  1571. LIMIT bounds the search.
  1572. Return a list whose car is `property-drawer' and cdr is a plist
  1573. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1574. `:post-blank' and `:post-affiliated' keywords.
  1575. Assume point is at the beginning of the property drawer."
  1576. (save-excursion
  1577. (let ((case-fold-search t)
  1578. (begin (point))
  1579. (contents-begin (line-beginning-position 2)))
  1580. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1581. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1582. (match-beginning 0)))
  1583. (before-blank (progn (forward-line) (point)))
  1584. (end (progn (skip-chars-forward " \r\t\n" limit)
  1585. (if (eobp) (point) (line-beginning-position)))))
  1586. (list 'property-drawer
  1587. (list :begin begin
  1588. :end end
  1589. :contents-begin (and contents-end contents-begin)
  1590. :contents-end contents-end
  1591. :post-blank (count-lines before-blank end)
  1592. :post-affiliated begin))))))
  1593. (defun org-element-property-drawer-interpreter (_ contents)
  1594. "Interpret property-drawer element as Org syntax.
  1595. CONTENTS is the properties within the drawer."
  1596. (format ":PROPERTIES:\n%s:END:" contents))
  1597. ;;;; Quote Block
  1598. (defun org-element-quote-block-parser (limit affiliated)
  1599. "Parse a quote block.
  1600. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1601. the buffer position at the beginning of the first affiliated
  1602. keyword and CDR is a plist of affiliated keywords along with
  1603. their value.
  1604. Return a list whose CAR is `quote-block' and CDR is a plist
  1605. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1606. `:post-blank' and `:post-affiliated' keywords.
  1607. Assume point is at the beginning of the block."
  1608. (let ((case-fold-search t))
  1609. (if (not (save-excursion
  1610. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1611. ;; Incomplete block: parse it as a paragraph.
  1612. (org-element-paragraph-parser limit affiliated)
  1613. (let ((block-end-line (match-beginning 0)))
  1614. (save-excursion
  1615. (let* ((begin (car affiliated))
  1616. (post-affiliated (point))
  1617. ;; Empty blocks have no contents.
  1618. (contents-begin (progn (forward-line)
  1619. (and (< (point) block-end-line)
  1620. (point))))
  1621. (contents-end (and contents-begin block-end-line))
  1622. (pos-before-blank (progn (goto-char block-end-line)
  1623. (forward-line)
  1624. (point)))
  1625. (end (progn (skip-chars-forward " \r\t\n" limit)
  1626. (if (eobp) (point) (line-beginning-position)))))
  1627. (list 'quote-block
  1628. (nconc
  1629. (list :begin begin
  1630. :end end
  1631. :contents-begin contents-begin
  1632. :contents-end contents-end
  1633. :post-blank (count-lines pos-before-blank end)
  1634. :post-affiliated post-affiliated)
  1635. (cdr affiliated)))))))))
  1636. (defun org-element-quote-block-interpreter (_ contents)
  1637. "Interpret quote-block element as Org syntax.
  1638. CONTENTS is the contents of the element."
  1639. (format "#+begin_quote\n%s#+end_quote" contents))
  1640. ;;;; Section
  1641. (defun org-element-section-parser (_)
  1642. "Parse a section.
  1643. Return a list whose CAR is `section' and CDR is a plist
  1644. containing `:begin', `:end', `:contents-begin', `contents-end',
  1645. `:post-blank' and `:post-affiliated' keywords."
  1646. (save-excursion
  1647. ;; Beginning of section is the beginning of the first non-blank
  1648. ;; line after previous headline.
  1649. (let* ((begin (point))
  1650. (end (progn (org-with-limited-levels (outline-next-heading))
  1651. (point)))
  1652. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1653. (line-beginning-position 2)))
  1654. (robust-end (when (> (- pos-before-blank 2) begin)
  1655. (- pos-before-blank 2)))
  1656. (robust-begin (when robust-end begin))
  1657. )
  1658. (list 'section
  1659. (list :begin begin
  1660. :end end
  1661. :contents-begin begin
  1662. :contents-end pos-before-blank
  1663. :robust-begin robust-begin
  1664. :robust-end robust-end
  1665. :post-blank (count-lines pos-before-blank end)
  1666. :post-affiliated begin)))))
  1667. (defun org-element-section-interpreter (_ contents)
  1668. "Interpret section element as Org syntax.
  1669. CONTENTS is the contents of the element."
  1670. contents)
  1671. ;;;; Special Block
  1672. (defun org-element-special-block-parser (limit affiliated)
  1673. "Parse a special block.
  1674. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1675. the buffer position at the beginning of the first affiliated
  1676. keyword and CDR is a plist of affiliated keywords along with
  1677. their value.
  1678. Return a list whose CAR is `special-block' and CDR is a plist
  1679. containing `:type', `:begin', `:end', `:contents-begin',
  1680. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1681. Assume point is at the beginning of the block."
  1682. (let* ((case-fold-search t)
  1683. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1684. (match-string-no-properties 1))))
  1685. (if (not (save-excursion
  1686. (re-search-forward
  1687. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1688. limit t)))
  1689. ;; Incomplete block: parse it as a paragraph.
  1690. (org-element-paragraph-parser limit affiliated)
  1691. (let ((block-end-line (match-beginning 0)))
  1692. (save-excursion
  1693. (let* ((begin (car affiliated))
  1694. (post-affiliated (point))
  1695. ;; Empty blocks have no contents.
  1696. (contents-begin (progn (forward-line)
  1697. (and (< (point) block-end-line)
  1698. (point))))
  1699. (contents-end (and contents-begin block-end-line))
  1700. (pos-before-blank (progn (goto-char block-end-line)
  1701. (forward-line)
  1702. (point)))
  1703. (end (progn (skip-chars-forward " \r\t\n" limit)
  1704. (if (eobp) (point) (line-beginning-position)))))
  1705. (list 'special-block
  1706. (nconc
  1707. (list :type type
  1708. :begin begin
  1709. :end end
  1710. :contents-begin contents-begin
  1711. :contents-end contents-end
  1712. :post-blank (count-lines pos-before-blank end)
  1713. :post-affiliated post-affiliated)
  1714. (cdr affiliated)))))))))
  1715. (defun org-element-special-block-interpreter (special-block contents)
  1716. "Interpret SPECIAL-BLOCK element as Org syntax.
  1717. CONTENTS is the contents of the element."
  1718. (let ((block-type (org-element-property :type special-block)))
  1719. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1720. ;;; Elements
  1721. ;;
  1722. ;; For each element, a parser and an interpreter are also defined.
  1723. ;; Both follow the same naming convention used for greater elements.
  1724. ;;
  1725. ;; Also, as for greater elements, adding a new element type is done
  1726. ;; through the following steps: implement a parser and an interpreter,
  1727. ;; tweak `org-element--current-element' so that it recognizes the new
  1728. ;; type and add that new type to `org-element-all-elements'.
  1729. ;;;; Babel Call
  1730. (defun org-element-babel-call-parser (limit affiliated)
  1731. "Parse a babel call.
  1732. LIMIT bounds the search. AFFILIATED is a list of which car is
  1733. the buffer position at the beginning of the first affiliated
  1734. keyword and cdr is a plist of affiliated keywords along with
  1735. their value.
  1736. Return a list whose car is `babel-call' and cdr is a plist
  1737. containing `:call', `:inside-header', `:arguments',
  1738. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1739. `:post-affiliated' as keywords."
  1740. (save-excursion
  1741. (let* ((begin (car affiliated))
  1742. (post-affiliated (point))
  1743. (before-blank (line-beginning-position 2))
  1744. (value (progn (search-forward ":" before-blank t)
  1745. (skip-chars-forward " \t")
  1746. (org-trim
  1747. (buffer-substring-no-properties
  1748. (point) (line-end-position)))))
  1749. (call
  1750. (or (org-string-nw-p
  1751. (buffer-substring-no-properties
  1752. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1753. (point))))))
  1754. (inside-header (org-element--parse-paired-brackets ?\[))
  1755. (arguments (org-string-nw-p
  1756. (org-element--parse-paired-brackets ?\()))
  1757. (end-header
  1758. (org-string-nw-p
  1759. (org-trim
  1760. (buffer-substring-no-properties (point) (line-end-position)))))
  1761. (end (progn (forward-line)
  1762. (skip-chars-forward " \r\t\n" limit)
  1763. (if (eobp) (point) (line-beginning-position)))))
  1764. (list 'babel-call
  1765. (nconc
  1766. (list :call call
  1767. :inside-header inside-header
  1768. :arguments arguments
  1769. :end-header end-header
  1770. :begin begin
  1771. :end end
  1772. :value value
  1773. :post-blank (count-lines before-blank end)
  1774. :post-affiliated post-affiliated)
  1775. (cdr affiliated))))))
  1776. (defun org-element-babel-call-interpreter (babel-call _)
  1777. "Interpret BABEL-CALL element as Org syntax."
  1778. (concat "#+call: "
  1779. (org-element-property :call babel-call)
  1780. (let ((h (org-element-property :inside-header babel-call)))
  1781. (and h (format "[%s]" h)))
  1782. (concat "(" (org-element-property :arguments babel-call) ")")
  1783. (let ((h (org-element-property :end-header babel-call)))
  1784. (and h (concat " " h)))))
  1785. ;;;; Clock
  1786. (defun org-element-clock-parser (limit)
  1787. "Parse a clock.
  1788. LIMIT bounds the search.
  1789. Return a list whose CAR is `clock' and CDR is a plist containing
  1790. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1791. `:post-affiliated' as keywords."
  1792. (save-excursion
  1793. (let* ((case-fold-search nil)
  1794. (begin (point))
  1795. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1796. (skip-chars-forward " \t")
  1797. (org-element-timestamp-parser)))
  1798. (duration (and (search-forward " => " (line-end-position) t)
  1799. (progn (skip-chars-forward " \t")
  1800. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1801. (match-string-no-properties 1)))
  1802. (status (if duration 'closed 'running))
  1803. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1804. (skip-chars-forward " \r\t\n" limit)
  1805. (skip-chars-backward " \t")
  1806. (unless (bolp) (end-of-line))
  1807. (count-lines before-blank (point))))
  1808. (end (point)))
  1809. (list 'clock
  1810. (list :status status
  1811. :value value
  1812. :duration duration
  1813. :begin begin
  1814. :end end
  1815. :post-blank post-blank
  1816. :post-affiliated begin)))))
  1817. (defun org-element-clock-interpreter (clock _)
  1818. "Interpret CLOCK element as Org syntax."
  1819. (concat "CLOCK: "
  1820. (org-element-timestamp-interpreter
  1821. (org-element-property :value clock) nil)
  1822. (let ((duration (org-element-property :duration clock)))
  1823. (and duration
  1824. (concat " => "
  1825. (apply 'format
  1826. "%2s:%02s"
  1827. (org-split-string duration ":")))))))
  1828. ;;;; Comment
  1829. (defun org-element-comment-parser (limit)
  1830. "Parse a comment.
  1831. LIMIT bounds the search.
  1832. Return a list whose CAR is `comment' and CDR is a plist
  1833. containing `:begin', `:end', `:value', `:post-blank',
  1834. `:post-affiliated' keywords.
  1835. Assume point is at comment beginning."
  1836. (save-excursion
  1837. (let* ((begin (point))
  1838. (value (prog2 (looking-at "[ \t]*# ?")
  1839. (buffer-substring-no-properties
  1840. (match-end 0) (line-end-position))
  1841. (forward-line)))
  1842. (com-end
  1843. ;; Get comments ending.
  1844. (progn
  1845. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1846. ;; Accumulate lines without leading hash and first
  1847. ;; whitespace.
  1848. (setq value
  1849. (concat value
  1850. "\n"
  1851. (buffer-substring-no-properties
  1852. (match-end 0) (line-end-position))))
  1853. (forward-line))
  1854. (point)))
  1855. (end (progn (goto-char com-end)
  1856. (skip-chars-forward " \r\t\n" limit)
  1857. (if (eobp) (point) (line-beginning-position)))))
  1858. (list 'comment
  1859. (list :begin begin
  1860. :end end
  1861. :value value
  1862. :post-blank (count-lines com-end end)
  1863. :post-affiliated begin)))))
  1864. (defun org-element-comment-interpreter (comment _)
  1865. "Interpret COMMENT element as Org syntax.
  1866. CONTENTS is nil."
  1867. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1868. ;;;; Comment Block
  1869. (defun org-element-comment-block-parser (limit affiliated)
  1870. "Parse an export block.
  1871. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1872. the buffer position at the beginning of the first affiliated
  1873. keyword and CDR is a plist of affiliated keywords along with
  1874. their value.
  1875. Return a list whose CAR is `comment-block' and CDR is a plist
  1876. containing `:begin', `:end', `:value', `:post-blank' and
  1877. `:post-affiliated' keywords.
  1878. Assume point is at comment block beginning."
  1879. (let ((case-fold-search t))
  1880. (if (not (save-excursion
  1881. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1882. ;; Incomplete block: parse it as a paragraph.
  1883. (org-element-paragraph-parser limit affiliated)
  1884. (let ((contents-end (match-beginning 0)))
  1885. (save-excursion
  1886. (let* ((begin (car affiliated))
  1887. (post-affiliated (point))
  1888. (contents-begin (progn (forward-line) (point)))
  1889. (pos-before-blank (progn (goto-char contents-end)
  1890. (forward-line)
  1891. (point)))
  1892. (end (progn (skip-chars-forward " \r\t\n" limit)
  1893. (if (eobp) (point) (line-beginning-position))))
  1894. (value (buffer-substring-no-properties
  1895. contents-begin contents-end)))
  1896. (list 'comment-block
  1897. (nconc
  1898. (list :begin begin
  1899. :end end
  1900. :value value
  1901. :post-blank (count-lines pos-before-blank end)
  1902. :post-affiliated post-affiliated)
  1903. (cdr affiliated)))))))))
  1904. (defun org-element-comment-block-interpreter (comment-block _)
  1905. "Interpret COMMENT-BLOCK element as Org syntax."
  1906. (format "#+begin_comment\n%s#+end_comment"
  1907. (org-element-normalize-string
  1908. (org-remove-indentation
  1909. (org-element-property :value comment-block)))))
  1910. ;;;; Diary Sexp
  1911. (defun org-element-diary-sexp-parser (limit affiliated)
  1912. "Parse a diary sexp.
  1913. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1914. the buffer position at the beginning of the first affiliated
  1915. keyword and CDR is a plist of affiliated keywords along with
  1916. their value.
  1917. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1918. containing `:begin', `:end', `:value', `:post-blank' and
  1919. `:post-affiliated' keywords."
  1920. (save-excursion
  1921. (let ((begin (car affiliated))
  1922. (post-affiliated (point))
  1923. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1924. (match-string-no-properties 1)))
  1925. (pos-before-blank (progn (forward-line) (point)))
  1926. (end (progn (skip-chars-forward " \r\t\n" limit)
  1927. (if (eobp) (point) (line-beginning-position)))))
  1928. (list 'diary-sexp
  1929. (nconc
  1930. (list :value value
  1931. :begin begin
  1932. :end end
  1933. :post-blank (count-lines pos-before-blank end)
  1934. :post-affiliated post-affiliated)
  1935. (cdr affiliated))))))
  1936. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1937. "Interpret DIARY-SEXP as Org syntax."
  1938. (org-element-property :value diary-sexp))
  1939. ;;;; Example Block
  1940. (defun org-element-example-block-parser (limit affiliated)
  1941. "Parse an example block.
  1942. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1943. the buffer position at the beginning of the first affiliated
  1944. keyword and CDR is a plist of affiliated keywords along with
  1945. their value.
  1946. Return a list whose CAR is `example-block' and CDR is a plist
  1947. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1948. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1949. `:value', `:post-blank' and `:post-affiliated' keywords."
  1950. (let ((case-fold-search t))
  1951. (if (not (save-excursion
  1952. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1953. ;; Incomplete block: parse it as a paragraph.
  1954. (org-element-paragraph-parser limit affiliated)
  1955. (let ((contents-end (match-beginning 0)))
  1956. (save-excursion
  1957. (let* ((switches
  1958. (progn
  1959. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1960. (match-string-no-properties 1)))
  1961. ;; Switches analysis.
  1962. (number-lines
  1963. (and switches
  1964. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1965. switches)
  1966. (cons
  1967. (if (equal (match-string 1 switches) "-")
  1968. 'new
  1969. 'continued)
  1970. (if (not (match-end 2)) 0
  1971. ;; Subtract 1 to give number of lines before
  1972. ;; first line.
  1973. (1- (string-to-number (match-string 2 switches)))))))
  1974. (preserve-indent
  1975. (and switches (string-match "-i\\>" switches)))
  1976. ;; Should labels be retained in (or stripped from) example
  1977. ;; blocks?
  1978. (retain-labels
  1979. (or (not switches)
  1980. (not (string-match "-r\\>" switches))
  1981. (and number-lines (string-match "-k\\>" switches))))
  1982. ;; What should code-references use - labels or
  1983. ;; line-numbers?
  1984. (use-labels
  1985. (or (not switches)
  1986. (and retain-labels
  1987. (not (string-match "-k\\>" switches)))))
  1988. (label-fmt
  1989. (and switches
  1990. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1991. (match-string 1 switches)))
  1992. ;; Standard block parsing.
  1993. (begin (car affiliated))
  1994. (post-affiliated (point))
  1995. (contents-begin (line-beginning-position 2))
  1996. (value (org-unescape-code-in-string
  1997. (buffer-substring-no-properties
  1998. contents-begin contents-end)))
  1999. (pos-before-blank (progn (goto-char contents-end)
  2000. (forward-line)
  2001. (point)))
  2002. (end (progn (skip-chars-forward " \r\t\n" limit)
  2003. (if (eobp) (point) (line-beginning-position)))))
  2004. (list 'example-block
  2005. (nconc
  2006. (list :begin begin
  2007. :end end
  2008. :value value
  2009. :switches switches
  2010. :number-lines number-lines
  2011. :preserve-indent preserve-indent
  2012. :retain-labels retain-labels
  2013. :use-labels use-labels
  2014. :label-fmt label-fmt
  2015. :post-blank (count-lines pos-before-blank end)
  2016. :post-affiliated post-affiliated)
  2017. (cdr affiliated)))))))))
  2018. (defun org-element-example-block-interpreter (example-block _)
  2019. "Interpret EXAMPLE-BLOCK element as Org syntax."
  2020. (let ((switches (org-element-property :switches example-block))
  2021. (value
  2022. (let ((val (org-element-property :value example-block)))
  2023. (cond
  2024. ((or org-src-preserve-indentation
  2025. (org-element-property :preserve-indent example-block))
  2026. val)
  2027. ((= 0 org-edit-src-content-indentation)
  2028. (org-remove-indentation val))
  2029. (t
  2030. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2031. (replace-regexp-in-string "^[ \t]*\\S-"
  2032. (concat ind "\\&")
  2033. (org-remove-indentation val))))))))
  2034. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  2035. (org-element-normalize-string (org-escape-code-in-string value))
  2036. "#+end_example")))
  2037. ;;;; Export Block
  2038. (defun org-element-export-block-parser (limit affiliated)
  2039. "Parse an export block.
  2040. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2041. the buffer position at the beginning of the first affiliated
  2042. keyword and CDR is a plist of affiliated keywords along with
  2043. their value.
  2044. Return a list whose CAR is `export-block' and CDR is a plist
  2045. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  2046. `:post-affiliated' keywords.
  2047. Assume point is at export-block beginning."
  2048. (let* ((case-fold-search t))
  2049. (if (not (save-excursion
  2050. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  2051. ;; Incomplete block: parse it as a paragraph.
  2052. (org-element-paragraph-parser limit affiliated)
  2053. (save-excursion
  2054. (let* ((contents-end (match-beginning 0))
  2055. (backend
  2056. (progn
  2057. (looking-at
  2058. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  2059. (match-string-no-properties 1)))
  2060. (begin (car affiliated))
  2061. (post-affiliated (point))
  2062. (contents-begin (progn (forward-line) (point)))
  2063. (pos-before-blank (progn (goto-char contents-end)
  2064. (forward-line)
  2065. (point)))
  2066. (end (progn (skip-chars-forward " \r\t\n" limit)
  2067. (if (eobp) (point) (line-beginning-position))))
  2068. (value (org-unescape-code-in-string
  2069. (buffer-substring-no-properties contents-begin
  2070. contents-end))))
  2071. (list 'export-block
  2072. (nconc
  2073. (list :type (and backend (upcase backend))
  2074. :begin begin
  2075. :end end
  2076. :value value
  2077. :post-blank (count-lines pos-before-blank end)
  2078. :post-affiliated post-affiliated)
  2079. (cdr affiliated))))))))
  2080. (defun org-element-export-block-interpreter (export-block _)
  2081. "Interpret EXPORT-BLOCK element as Org syntax."
  2082. (format "#+begin_export %s\n%s#+end_export"
  2083. (org-element-property :type export-block)
  2084. (org-element-property :value export-block)))
  2085. ;;;; Fixed-width
  2086. (defun org-element-fixed-width-parser (limit affiliated)
  2087. "Parse a fixed-width section.
  2088. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2089. the buffer position at the beginning of the first affiliated
  2090. keyword and CDR is a plist of affiliated keywords along with
  2091. their value.
  2092. Return a list whose CAR is `fixed-width' and CDR is a plist
  2093. containing `:begin', `:end', `:value', `:post-blank' and
  2094. `:post-affiliated' keywords.
  2095. Assume point is at the beginning of the fixed-width area."
  2096. (save-excursion
  2097. (let* ((begin (car affiliated))
  2098. (post-affiliated (point))
  2099. (end-area
  2100. (progn
  2101. (while (and (< (point) limit)
  2102. (looking-at "[ \t]*:\\( \\|$\\)"))
  2103. (forward-line))
  2104. (if (bolp) (line-end-position 0) (point))))
  2105. (end (progn (skip-chars-forward " \r\t\n" limit)
  2106. (if (eobp) (point) (line-beginning-position)))))
  2107. (list 'fixed-width
  2108. (nconc
  2109. (list :begin begin
  2110. :end end
  2111. :value (replace-regexp-in-string
  2112. "^[ \t]*: ?" ""
  2113. (buffer-substring-no-properties post-affiliated
  2114. end-area))
  2115. :post-blank (count-lines end-area end)
  2116. :post-affiliated post-affiliated)
  2117. (cdr affiliated))))))
  2118. (defun org-element-fixed-width-interpreter (fixed-width _)
  2119. "Interpret FIXED-WIDTH element as Org syntax."
  2120. (let ((value (org-element-property :value fixed-width)))
  2121. (and value (replace-regexp-in-string "^" ": " value))))
  2122. ;;;; Horizontal Rule
  2123. (defun org-element-horizontal-rule-parser (limit affiliated)
  2124. "Parse an horizontal rule.
  2125. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2126. the buffer position at the beginning of the first affiliated
  2127. keyword and CDR is a plist of affiliated keywords along with
  2128. their value.
  2129. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  2130. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  2131. keywords."
  2132. (save-excursion
  2133. (let ((begin (car affiliated))
  2134. (post-affiliated (point))
  2135. (post-hr (progn (forward-line) (point)))
  2136. (end (progn (skip-chars-forward " \r\t\n" limit)
  2137. (if (eobp) (point) (line-beginning-position)))))
  2138. (list 'horizontal-rule
  2139. (nconc
  2140. (list :begin begin
  2141. :end end
  2142. :post-blank (count-lines post-hr end)
  2143. :post-affiliated post-affiliated)
  2144. (cdr affiliated))))))
  2145. (defun org-element-horizontal-rule-interpreter (&rest _)
  2146. "Interpret HORIZONTAL-RULE element as Org syntax."
  2147. "-----")
  2148. ;;;; Keyword
  2149. (defun org-element-keyword-parser (limit affiliated)
  2150. "Parse a keyword at point.
  2151. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2152. the buffer position at the beginning of the first affiliated
  2153. keyword and CDR is a plist of affiliated keywords along with
  2154. their value.
  2155. Return a list whose CAR is a normalized `keyword' (uppercase) and
  2156. CDR is a plist containing `:key', `:value', `:begin', `:end',
  2157. `:post-blank' and `:post-affiliated' keywords."
  2158. (save-excursion
  2159. ;; An orphaned affiliated keyword is considered as a regular
  2160. ;; keyword. In this case AFFILIATED is nil, so we take care of
  2161. ;; this corner case.
  2162. (let ((begin (or (car affiliated) (point)))
  2163. (post-affiliated (point))
  2164. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  2165. (upcase (match-string-no-properties 1))))
  2166. (value (org-trim (buffer-substring-no-properties
  2167. (match-end 0) (point-at-eol))))
  2168. (pos-before-blank (progn (forward-line) (point)))
  2169. (end (progn (skip-chars-forward " \r\t\n" limit)
  2170. (if (eobp) (point) (line-beginning-position)))))
  2171. (list 'keyword
  2172. (nconc
  2173. (list :key key
  2174. :value value
  2175. :begin begin
  2176. :end end
  2177. :post-blank (count-lines pos-before-blank end)
  2178. :post-affiliated post-affiliated)
  2179. (cdr affiliated))))))
  2180. (defun org-element-keyword-interpreter (keyword _)
  2181. "Interpret KEYWORD element as Org syntax."
  2182. (format "#+%s: %s"
  2183. (downcase (org-element-property :key keyword))
  2184. (org-element-property :value keyword)))
  2185. ;;;; Latex Environment
  2186. (defconst org-element--latex-begin-environment
  2187. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2188. "Regexp matching the beginning of a LaTeX environment.
  2189. The environment is captured by the first group.
  2190. See also `org-element--latex-end-environment'.")
  2191. (defconst org-element--latex-end-environment
  2192. "\\\\end{%s}[ \t]*$"
  2193. "Format string matching the ending of a LaTeX environment.
  2194. See also `org-element--latex-begin-environment'.")
  2195. (defun org-element-latex-environment-parser (limit affiliated)
  2196. "Parse a LaTeX environment.
  2197. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2198. the buffer position at the beginning of the first affiliated
  2199. keyword and CDR is a plist of affiliated keywords along with
  2200. their value.
  2201. Return a list whose CAR is `latex-environment' and CDR is a plist
  2202. containing `:begin', `:end', `:value', `:post-blank' and
  2203. `:post-affiliated' keywords.
  2204. Assume point is at the beginning of the latex environment."
  2205. (save-excursion
  2206. (let ((case-fold-search t)
  2207. (code-begin (point)))
  2208. (looking-at org-element--latex-begin-environment)
  2209. (if (not (re-search-forward (format org-element--latex-end-environment
  2210. (regexp-quote (match-string 1)))
  2211. limit t))
  2212. ;; Incomplete latex environment: parse it as a paragraph.
  2213. (org-element-paragraph-parser limit affiliated)
  2214. (let* ((code-end (progn (forward-line) (point)))
  2215. (begin (car affiliated))
  2216. (value (buffer-substring-no-properties code-begin code-end))
  2217. (end (progn (skip-chars-forward " \r\t\n" limit)
  2218. (if (eobp) (point) (line-beginning-position)))))
  2219. (list 'latex-environment
  2220. (nconc
  2221. (list :begin begin
  2222. :end end
  2223. :value value
  2224. :post-blank (count-lines code-end end)
  2225. :post-affiliated code-begin)
  2226. (cdr affiliated))))))))
  2227. (defun org-element-latex-environment-interpreter (latex-environment _)
  2228. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2229. (org-element-property :value latex-environment))
  2230. ;;;; Node Property
  2231. (defun org-element-node-property-parser (limit)
  2232. "Parse a node-property at point.
  2233. LIMIT bounds the search.
  2234. Return a list whose CAR is `node-property' and CDR is a plist
  2235. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2236. `:post-affiliated' keywords."
  2237. (looking-at org-property-re)
  2238. (let ((case-fold-search t)
  2239. (begin (point))
  2240. (key (match-string-no-properties 2))
  2241. (value (match-string-no-properties 3))
  2242. (end (save-excursion
  2243. (end-of-line)
  2244. (if (re-search-forward org-property-re limit t)
  2245. (line-beginning-position)
  2246. limit))))
  2247. (list 'node-property
  2248. (list :key key
  2249. :value value
  2250. :begin begin
  2251. :end end
  2252. :post-blank 0
  2253. :post-affiliated begin))))
  2254. (defun org-element-node-property-interpreter (node-property _)
  2255. "Interpret NODE-PROPERTY element as Org syntax."
  2256. (format org-property-format
  2257. (format ":%s:" (org-element-property :key node-property))
  2258. (or (org-element-property :value node-property) "")))
  2259. ;;;; Paragraph
  2260. (defun org-element-paragraph-parser (limit affiliated)
  2261. "Parse a paragraph.
  2262. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2263. the buffer position at the beginning of the first affiliated
  2264. keyword and CDR is a plist of affiliated keywords along with
  2265. their value.
  2266. Return a list whose CAR is `paragraph' and CDR is a plist
  2267. containing `:begin', `:end', `:contents-begin' and
  2268. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2269. Assume point is at the beginning of the paragraph."
  2270. (save-excursion
  2271. (let* ((begin (car affiliated))
  2272. (contents-begin (point))
  2273. (before-blank
  2274. (let ((case-fold-search t))
  2275. (end-of-line)
  2276. ;; A matching `org-element-paragraph-separate' is not
  2277. ;; necessarily the end of the paragraph. In particular,
  2278. ;; drawers, blocks or LaTeX environments opening lines
  2279. ;; must be closed. Moreover keywords with a secondary
  2280. ;; value must belong to "dual keywords".
  2281. (while (not
  2282. (cond
  2283. ((not (and (re-search-forward
  2284. org-element-paragraph-separate limit 'move)
  2285. (progn (beginning-of-line) t))))
  2286. ((looking-at org-element-drawer-re)
  2287. (save-excursion
  2288. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2289. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2290. (save-excursion
  2291. (re-search-forward
  2292. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2293. (regexp-quote (match-string 1)))
  2294. limit t)))
  2295. ((looking-at org-element--latex-begin-environment)
  2296. (save-excursion
  2297. (re-search-forward
  2298. (format org-element--latex-end-environment
  2299. (regexp-quote (match-string 1)))
  2300. limit t)))
  2301. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2302. (member-ignore-case (match-string 1)
  2303. org-element-dual-keywords))
  2304. ;; Everything else is unambiguous.
  2305. (t)))
  2306. (end-of-line))
  2307. (if (= (point) limit) limit
  2308. (goto-char (line-beginning-position)))))
  2309. (contents-end (save-excursion
  2310. (skip-chars-backward " \r\t\n" contents-begin)
  2311. (line-beginning-position 2)))
  2312. (end (progn (skip-chars-forward " \r\t\n" limit)
  2313. (if (eobp) (point) (line-beginning-position)))))
  2314. (list 'paragraph
  2315. (nconc
  2316. (list :begin begin
  2317. :end end
  2318. :contents-begin contents-begin
  2319. :contents-end contents-end
  2320. :post-blank (count-lines before-blank end)
  2321. :post-affiliated contents-begin)
  2322. (cdr affiliated))))))
  2323. (defun org-element-paragraph-interpreter (_ contents)
  2324. "Interpret paragraph element as Org syntax.
  2325. CONTENTS is the contents of the element."
  2326. contents)
  2327. ;;;; Planning
  2328. (defun org-element-planning-parser (limit)
  2329. "Parse a planning.
  2330. LIMIT bounds the search.
  2331. Return a list whose CAR is `planning' and CDR is a plist
  2332. containing `:closed', `:deadline', `:scheduled', `:begin',
  2333. `:end', `:post-blank' and `:post-affiliated' keywords."
  2334. (save-excursion
  2335. (let* ((case-fold-search nil)
  2336. (begin (point))
  2337. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2338. (skip-chars-forward " \r\t\n" limit)
  2339. (skip-chars-backward " \t")
  2340. (unless (bolp) (end-of-line))
  2341. (count-lines before-blank (point))))
  2342. (end (point))
  2343. closed deadline scheduled)
  2344. (goto-char begin)
  2345. (while (re-search-forward org-element-planning-keywords-re end t)
  2346. (skip-chars-forward " \t" end)
  2347. (let ((keyword (match-string 0))
  2348. (time (org-element-timestamp-parser)))
  2349. (cond
  2350. ((equal keyword org-element-closed-keyword) (setq closed time))
  2351. ((equal keyword org-element-deadline-keyword) (setq deadline time))
  2352. (t (setq scheduled time)))))
  2353. (list 'planning
  2354. (list :closed closed
  2355. :deadline deadline
  2356. :scheduled scheduled
  2357. :begin begin
  2358. :end end
  2359. :post-blank post-blank
  2360. :post-affiliated begin)))))
  2361. (defun org-element-planning-interpreter (planning _)
  2362. "Interpret PLANNING element as Org syntax."
  2363. (mapconcat
  2364. #'identity
  2365. (delq nil
  2366. (list (let ((deadline (org-element-property :deadline planning)))
  2367. (when deadline
  2368. (concat org-element-deadline-keyword " "
  2369. (org-element-timestamp-interpreter deadline nil))))
  2370. (let ((scheduled (org-element-property :scheduled planning)))
  2371. (when scheduled
  2372. (concat org-element-scheduled-keyword " "
  2373. (org-element-timestamp-interpreter scheduled nil))))
  2374. (let ((closed (org-element-property :closed planning)))
  2375. (when closed
  2376. (concat org-element-closed-keyword " "
  2377. (org-element-timestamp-interpreter closed nil))))))
  2378. " "))
  2379. ;;;; Src Block
  2380. (defun org-element-src-block-parser (limit affiliated)
  2381. "Parse a source block.
  2382. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2383. the buffer position at the beginning of the first affiliated
  2384. keyword and CDR is a plist of affiliated keywords along with
  2385. their value.
  2386. Return a list whose CAR is `src-block' and CDR is a plist
  2387. containing `:language', `:switches', `:parameters', `:begin',
  2388. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2389. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2390. `:post-affiliated' keywords.
  2391. Assume point is at the beginning of the block."
  2392. (let ((case-fold-search t))
  2393. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2394. limit t)))
  2395. ;; Incomplete block: parse it as a paragraph.
  2396. (org-element-paragraph-parser limit affiliated)
  2397. (let ((contents-end (match-beginning 0)))
  2398. (save-excursion
  2399. (let* ((begin (car affiliated))
  2400. (post-affiliated (point))
  2401. ;; Get language as a string.
  2402. (language
  2403. (progn
  2404. (looking-at
  2405. "^[ \t]*#\\+BEGIN_SRC\
  2406. \\(?: +\\(\\S-+\\)\\)?\
  2407. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2408. \\(.*\\)[ \t]*$")
  2409. (match-string-no-properties 1)))
  2410. ;; Get switches.
  2411. (switches (match-string-no-properties 2))
  2412. ;; Get parameters.
  2413. (parameters (match-string-no-properties 3))
  2414. ;; Switches analysis.
  2415. (number-lines
  2416. (and switches
  2417. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2418. switches)
  2419. (cons
  2420. (if (equal (match-string 1 switches) "-")
  2421. 'new
  2422. 'continued)
  2423. (if (not (match-end 2)) 0
  2424. ;; Subtract 1 to give number of lines before
  2425. ;; first line.
  2426. (1- (string-to-number (match-string 2 switches)))))))
  2427. (preserve-indent (and switches
  2428. (string-match "-i\\>" switches)))
  2429. (label-fmt
  2430. (and switches
  2431. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2432. (match-string 1 switches)))
  2433. ;; Should labels be retained in (or stripped from)
  2434. ;; source blocks?
  2435. (retain-labels
  2436. (or (not switches)
  2437. (not (string-match "-r\\>" switches))
  2438. (and number-lines (string-match "-k\\>" switches))))
  2439. ;; What should code-references use - labels or
  2440. ;; line-numbers?
  2441. (use-labels
  2442. (or (not switches)
  2443. (and retain-labels
  2444. (not (string-match "-k\\>" switches)))))
  2445. ;; Retrieve code.
  2446. (value (org-unescape-code-in-string
  2447. (buffer-substring-no-properties
  2448. (line-beginning-position 2) contents-end)))
  2449. (pos-before-blank (progn (goto-char contents-end)
  2450. (forward-line)
  2451. (point)))
  2452. ;; Get position after ending blank lines.
  2453. (end (progn (skip-chars-forward " \r\t\n" limit)
  2454. (if (eobp) (point) (line-beginning-position)))))
  2455. (list 'src-block
  2456. (nconc
  2457. (list :language language
  2458. :switches (and (org-string-nw-p switches)
  2459. (org-trim switches))
  2460. :parameters (and (org-string-nw-p parameters)
  2461. (org-trim parameters))
  2462. :begin begin
  2463. :end end
  2464. :number-lines number-lines
  2465. :preserve-indent preserve-indent
  2466. :retain-labels retain-labels
  2467. :use-labels use-labels
  2468. :label-fmt label-fmt
  2469. :value value
  2470. :post-blank (count-lines pos-before-blank end)
  2471. :post-affiliated post-affiliated)
  2472. (cdr affiliated)))))))))
  2473. (defun org-element-src-block-interpreter (src-block _)
  2474. "Interpret SRC-BLOCK element as Org syntax."
  2475. (let ((lang (org-element-property :language src-block))
  2476. (switches (org-element-property :switches src-block))
  2477. (params (org-element-property :parameters src-block))
  2478. (value
  2479. (let ((val (org-element-property :value src-block)))
  2480. (cond
  2481. ((or org-src-preserve-indentation
  2482. (org-element-property :preserve-indent src-block))
  2483. val)
  2484. ((zerop org-edit-src-content-indentation)
  2485. (org-remove-indentation val))
  2486. (t
  2487. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2488. (replace-regexp-in-string "^[ \t]*\\S-"
  2489. (concat ind "\\&")
  2490. (org-remove-indentation val))))))))
  2491. (format "#+begin_src%s\n%s#+end_src"
  2492. (concat (and lang (concat " " lang))
  2493. (and switches (concat " " switches))
  2494. (and params (concat " " params)))
  2495. (org-element-normalize-string (org-escape-code-in-string value)))))
  2496. ;;;; Table
  2497. (defun org-element-table-parser (limit affiliated)
  2498. "Parse a table at point.
  2499. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2500. the buffer position at the beginning of the first affiliated
  2501. keyword and CDR is a plist of affiliated keywords along with
  2502. their value.
  2503. Return a list whose CAR is `table' and CDR is a plist containing
  2504. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2505. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2506. keywords.
  2507. Assume point is at the beginning of the table."
  2508. (save-excursion
  2509. (let* ((case-fold-search t)
  2510. (table-begin (point))
  2511. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2512. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2513. (if (eq type 'org) "" "+")))
  2514. (begin (car affiliated))
  2515. (table-end
  2516. (if (re-search-forward end-re limit 'move)
  2517. (goto-char (match-beginning 0))
  2518. (point)))
  2519. (tblfm (let (acc)
  2520. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2521. (push (match-string-no-properties 1) acc)
  2522. (forward-line))
  2523. acc))
  2524. (pos-before-blank (point))
  2525. (end (progn (skip-chars-forward " \r\t\n" limit)
  2526. (if (eobp) (point) (line-beginning-position)))))
  2527. (list 'table
  2528. (nconc
  2529. (list :begin begin
  2530. :end end
  2531. :type type
  2532. :tblfm tblfm
  2533. ;; Only `org' tables have contents. `table.el' tables
  2534. ;; use a `:value' property to store raw table as
  2535. ;; a string.
  2536. :contents-begin (and (eq type 'org) table-begin)
  2537. :contents-end (and (eq type 'org) table-end)
  2538. :value (and (eq type 'table.el)
  2539. (buffer-substring-no-properties
  2540. table-begin table-end))
  2541. :post-blank (count-lines pos-before-blank end)
  2542. :post-affiliated table-begin)
  2543. (cdr affiliated))))))
  2544. (defun org-element-table-interpreter (table contents)
  2545. "Interpret TABLE element as Org syntax.
  2546. CONTENTS is a string, if table's type is `org', or nil."
  2547. (if (eq (org-element-property :type table) 'table.el)
  2548. (org-remove-indentation (org-element-property :value table))
  2549. (concat (with-temp-buffer (insert contents)
  2550. (org-table-align)
  2551. (buffer-string))
  2552. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2553. (reverse (org-element-property :tblfm table))
  2554. "\n"))))
  2555. ;;;; Table Row
  2556. (defun org-element-table-row-parser (_)
  2557. "Parse table row at point.
  2558. Return a list whose CAR is `table-row' and CDR is a plist
  2559. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2560. `:type', `:post-blank' and `:post-affiliated' keywords."
  2561. (save-excursion
  2562. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2563. (begin (point))
  2564. ;; A table rule has no contents. In that case, ensure
  2565. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2566. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2567. (contents-end (and (eq type 'standard)
  2568. (progn
  2569. (end-of-line)
  2570. (skip-chars-backward " \t")
  2571. (point))))
  2572. (end (line-beginning-position 2)))
  2573. (list 'table-row
  2574. (list :type type
  2575. :begin begin
  2576. :end end
  2577. :contents-begin contents-begin
  2578. :contents-end contents-end
  2579. :post-blank 0
  2580. :post-affiliated begin)))))
  2581. (defun org-element-table-row-interpreter (table-row contents)
  2582. "Interpret TABLE-ROW element as Org syntax.
  2583. CONTENTS is the contents of the table row."
  2584. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2585. (concat "|" contents)))
  2586. ;;;; Verse Block
  2587. (defun org-element-verse-block-parser (limit affiliated)
  2588. "Parse a verse block.
  2589. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2590. the buffer position at the beginning of the first affiliated
  2591. keyword and CDR is a plist of affiliated keywords along with
  2592. their value.
  2593. Return a list whose CAR is `verse-block' and CDR is a plist
  2594. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2595. `:post-blank' and `:post-affiliated' keywords.
  2596. Assume point is at beginning of the block."
  2597. (let ((case-fold-search t))
  2598. (if (not (save-excursion
  2599. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2600. ;; Incomplete block: parse it as a paragraph.
  2601. (org-element-paragraph-parser limit affiliated)
  2602. (let ((contents-end (match-beginning 0)))
  2603. (save-excursion
  2604. (let* ((begin (car affiliated))
  2605. (post-affiliated (point))
  2606. (contents-begin (progn (forward-line) (point)))
  2607. (pos-before-blank (progn (goto-char contents-end)
  2608. (forward-line)
  2609. (point)))
  2610. (end (progn (skip-chars-forward " \r\t\n" limit)
  2611. (if (eobp) (point) (line-beginning-position)))))
  2612. (list 'verse-block
  2613. (nconc
  2614. (list :begin begin
  2615. :end end
  2616. :contents-begin contents-begin
  2617. :contents-end contents-end
  2618. :post-blank (count-lines pos-before-blank end)
  2619. :post-affiliated post-affiliated)
  2620. (cdr affiliated)))))))))
  2621. (defun org-element-verse-block-interpreter (_ contents)
  2622. "Interpret verse-block element as Org syntax.
  2623. CONTENTS is verse block contents."
  2624. (format "#+begin_verse\n%s#+end_verse" contents))
  2625. ;;; Objects
  2626. ;;
  2627. ;; Unlike to elements, raw text can be found between objects. Hence,
  2628. ;; `org-element--object-lex' is provided to find the next object in
  2629. ;; buffer.
  2630. ;;
  2631. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2632. ;; object types they can contain will be specified in
  2633. ;; `org-element-object-restrictions'.
  2634. ;;
  2635. ;; Creating a new type of object requires to alter
  2636. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2637. ;; new type in `org-element-all-objects', and possibly add
  2638. ;; restrictions in `org-element-object-restrictions'.
  2639. ;;;; Bold
  2640. (defun org-element--parse-generic-emphasis (mark type)
  2641. "Parse emphasis object at point, if any.
  2642. MARK is the delimiter string used. TYPE is a symbol among
  2643. ‘bold’, ‘code’, ‘italic’, ‘strike-through’, ‘underline’, and
  2644. ‘verbatim’.
  2645. Assume point is at first MARK."
  2646. (save-excursion
  2647. (let ((origin (point)))
  2648. (unless (bolp) (forward-char -1))
  2649. (let ((opening-re
  2650. (rx-to-string
  2651. `(seq (or line-start (any space ?- ?\( ?' ?\" ?\{))
  2652. ,mark
  2653. (not space)))))
  2654. (when (looking-at opening-re)
  2655. (goto-char (1+ origin))
  2656. (let ((closing-re
  2657. (rx-to-string
  2658. `(seq
  2659. (not space)
  2660. (group ,mark)
  2661. (or (any space ?- ?. ?, ?\; ?: ?! ?? ?' ?\" ?\) ?\} ?\\ ?\[)
  2662. line-end)))))
  2663. (when (re-search-forward closing-re nil t)
  2664. (let ((closing (match-end 1)))
  2665. (goto-char closing)
  2666. (let* ((post-blank (skip-chars-forward " \t"))
  2667. (contents-begin (1+ origin))
  2668. (contents-end (1- closing)))
  2669. (list type
  2670. (append
  2671. (list :begin origin
  2672. :end (point)
  2673. :post-blank post-blank)
  2674. (if (memq type '(code verbatim))
  2675. (list :value
  2676. (and (memq type '(code verbatim))
  2677. (buffer-substring
  2678. contents-begin contents-end)))
  2679. (list :contents-begin contents-begin
  2680. :contents-end contents-end)))))))))))))
  2681. (defun org-element-bold-parser ()
  2682. "Parse bold object at point, if any.
  2683. When at a bold object, return a list whose car is `bold' and cdr
  2684. is a plist with `:begin', `:end', `:contents-begin' and
  2685. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2686. nil.
  2687. Assume point is at the first star marker."
  2688. (org-element--parse-generic-emphasis "*" 'bold))
  2689. (defun org-element-bold-interpreter (_ contents)
  2690. "Interpret bold object as Org syntax.
  2691. CONTENTS is the contents of the object."
  2692. (format "*%s*" contents))
  2693. ;;;; Citation
  2694. (defun org-element-citation-parser ()
  2695. "Parse citation object at point, if any.
  2696. When at a citation object, return a list whose car is `citation'
  2697. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2698. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2699. keywords. Otherwise, return nil.
  2700. Assume point is at the beginning of the citation."
  2701. (when (looking-at org-element-citation-prefix-re)
  2702. (let* ((begin (point))
  2703. (style (and (match-end 1)
  2704. (match-string-no-properties 1)))
  2705. ;; Ignore blanks between cite type and prefix or key.
  2706. (start (match-end 0))
  2707. (closing (with-syntax-table org-element--pair-square-table
  2708. (ignore-errors (scan-lists begin 1 0)))))
  2709. (save-excursion
  2710. (when (and closing
  2711. (re-search-forward org-element-citation-key-re closing t))
  2712. ;; Find prefix, if any.
  2713. (let ((first-key-end (match-end 0))
  2714. (types (org-element-restriction 'citation-reference))
  2715. (cite
  2716. (list 'citation
  2717. (list :style style
  2718. :begin begin
  2719. :post-blank (progn
  2720. (goto-char closing)
  2721. (skip-chars-forward " \t"))
  2722. :end (point)))))
  2723. ;; `:contents-begin' depends on the presence of
  2724. ;; a non-empty common prefix.
  2725. (goto-char first-key-end)
  2726. (if (not (search-backward ";" start t))
  2727. (org-element-put-property cite :contents-begin start)
  2728. (when (< start (point))
  2729. (org-element-put-property
  2730. cite :prefix
  2731. (org-element--parse-objects start (point) nil types cite)))
  2732. (forward-char)
  2733. (org-element-put-property cite :contents-begin (point)))
  2734. ;; `:contents-end' depends on the presence of a non-empty
  2735. ;; common suffix.
  2736. (goto-char (1- closing))
  2737. (skip-chars-backward " \r\t\n")
  2738. (let ((end (point)))
  2739. (if (or (not (search-backward ";" first-key-end t))
  2740. (re-search-forward org-element-citation-key-re end t))
  2741. (org-element-put-property cite :contents-end end)
  2742. (forward-char)
  2743. (when (< (point) end)
  2744. (org-element-put-property
  2745. cite :suffix
  2746. (org-element--parse-objects (point) end nil types cite)))
  2747. (org-element-put-property cite :contents-end (point))))
  2748. cite))))))
  2749. (defun org-element-citation-interpreter (citation contents)
  2750. "Interpret CITATION object as Org syntax.
  2751. CONTENTS is the contents of the object, as a string."
  2752. (let ((prefix (org-element-property :prefix citation))
  2753. (suffix (org-element-property :suffix citation))
  2754. (style (org-element-property :style citation)))
  2755. (concat "[cite"
  2756. (and style (concat "/" style))
  2757. ":"
  2758. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2759. (if suffix
  2760. (concat contents (org-element-interpret-data suffix))
  2761. ;; Remove spurious semicolon.
  2762. (substring contents nil -1))
  2763. "]")))
  2764. ;;;; Citation Reference
  2765. (defun org-element-citation-reference-parser ()
  2766. "Parse citation reference object at point, if any.
  2767. When at a reference, return a list whose car is
  2768. `citation-reference', and cdr is a plist with `:key',
  2769. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2770. Assume point is at the beginning of the reference."
  2771. (save-excursion
  2772. (let ((begin (point)))
  2773. (when (re-search-forward org-element-citation-key-re nil t)
  2774. (let* ((key (match-string-no-properties 1))
  2775. (key-start (match-beginning 0))
  2776. (key-end (match-end 0))
  2777. (separator (search-forward ";" nil t))
  2778. (end (or separator (point-max)))
  2779. (suffix-end (if separator (1- end) end))
  2780. (types (org-element-restriction 'citation-reference))
  2781. (reference
  2782. (list 'citation-reference
  2783. (list :key key
  2784. :begin begin
  2785. :end end
  2786. :post-blank 0))))
  2787. (when (< begin key-start)
  2788. (org-element-put-property
  2789. reference :prefix
  2790. (org-element--parse-objects begin key-start nil types reference)))
  2791. (when (< key-end suffix-end)
  2792. (org-element-put-property
  2793. reference :suffix
  2794. (org-element--parse-objects key-end suffix-end nil types reference)))
  2795. reference)))))
  2796. (defun org-element-citation-reference-interpreter (citation-reference _)
  2797. "Interpret CITATION-REFERENCE object as Org syntax."
  2798. (concat (org-element-interpret-data
  2799. (org-element-property :prefix citation-reference))
  2800. "@" (org-element-property :key citation-reference)
  2801. (org-element-interpret-data
  2802. (org-element-property :suffix citation-reference))
  2803. ";"))
  2804. ;;;; Code
  2805. (defun org-element-code-parser ()
  2806. "Parse code object at point, if any.
  2807. When at a code object, return a list whose car is `code' and cdr
  2808. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2809. keywords. Otherwise, return nil.
  2810. Assume point is at the first tilde marker."
  2811. (org-element--parse-generic-emphasis "~" 'code))
  2812. (defun org-element-code-interpreter (code _)
  2813. "Interpret CODE object as Org syntax."
  2814. (format "~%s~" (org-element-property :value code)))
  2815. ;;;; Entity
  2816. (defun org-element-entity-parser ()
  2817. "Parse entity at point, if any.
  2818. When at an entity, return a list whose car is `entity' and cdr
  2819. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2820. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2821. `:post-blank' as keywords. Otherwise, return nil.
  2822. Assume point is at the beginning of the entity."
  2823. (catch 'no-object
  2824. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2825. (save-excursion
  2826. (let* ((value (or (org-entity-get (match-string 1))
  2827. (throw 'no-object nil)))
  2828. (begin (match-beginning 0))
  2829. (bracketsp (string= (match-string 2) "{}"))
  2830. (post-blank (progn (goto-char (match-end 1))
  2831. (when bracketsp (forward-char 2))
  2832. (skip-chars-forward " \t")))
  2833. (end (point)))
  2834. (list 'entity
  2835. (list :name (car value)
  2836. :latex (nth 1 value)
  2837. :latex-math-p (nth 2 value)
  2838. :html (nth 3 value)
  2839. :ascii (nth 4 value)
  2840. :latin1 (nth 5 value)
  2841. :utf-8 (nth 6 value)
  2842. :begin begin
  2843. :end end
  2844. :use-brackets-p bracketsp
  2845. :post-blank post-blank)))))))
  2846. (defun org-element-entity-interpreter (entity _)
  2847. "Interpret ENTITY object as Org syntax."
  2848. (concat "\\"
  2849. (org-element-property :name entity)
  2850. (when (org-element-property :use-brackets-p entity) "{}")))
  2851. ;;;; Export Snippet
  2852. (defun org-element-export-snippet-parser ()
  2853. "Parse export snippet at point.
  2854. When at an export snippet, return a list whose car is
  2855. `export-snippet' and cdr a plist with `:begin', `:end',
  2856. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2857. return nil.
  2858. Assume point is at the beginning of the snippet."
  2859. (save-excursion
  2860. (let (contents-end)
  2861. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2862. (setq contents-end
  2863. (save-match-data (goto-char (match-end 0))
  2864. (when
  2865. (re-search-forward "@@" nil t)
  2866. (match-beginning 0)))))
  2867. (let* ((begin (match-beginning 0))
  2868. (back-end (match-string-no-properties 1))
  2869. (value (buffer-substring-no-properties
  2870. (match-end 0) contents-end))
  2871. (post-blank (skip-chars-forward " \t"))
  2872. (end (point)))
  2873. (list 'export-snippet
  2874. (list :back-end back-end
  2875. :value value
  2876. :begin begin
  2877. :end end
  2878. :post-blank post-blank)))))))
  2879. (defun org-element-export-snippet-interpreter (export-snippet _)
  2880. "Interpret EXPORT-SNIPPET object as Org syntax."
  2881. (format "@@%s:%s@@"
  2882. (org-element-property :back-end export-snippet)
  2883. (org-element-property :value export-snippet)))
  2884. ;;;; Footnote Reference
  2885. (defun org-element-footnote-reference-parser ()
  2886. "Parse footnote reference at point, if any.
  2887. When at a footnote reference, return a list whose car is
  2888. `footnote-reference' and cdr a plist with `:label', `:type',
  2889. `:begin', `:end', `:contents-begin', `:contents-end' and
  2890. `:post-blank' as keywords. Otherwise, return nil."
  2891. (when (looking-at org-footnote-re)
  2892. (let ((closing (with-syntax-table org-element--pair-square-table
  2893. (ignore-errors (scan-lists (point) 1 0)))))
  2894. (when closing
  2895. (save-excursion
  2896. (let* ((begin (point))
  2897. (label (match-string-no-properties 1))
  2898. (inner-begin (match-end 0))
  2899. (inner-end (1- closing))
  2900. (type (if (match-end 2) 'inline 'standard))
  2901. (post-blank (progn (goto-char closing)
  2902. (skip-chars-forward " \t")))
  2903. (end (point)))
  2904. (list 'footnote-reference
  2905. (list :label label
  2906. :type type
  2907. :begin begin
  2908. :end end
  2909. :contents-begin (and (eq type 'inline) inner-begin)
  2910. :contents-end (and (eq type 'inline) inner-end)
  2911. :post-blank post-blank))))))))
  2912. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2913. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2914. CONTENTS is its definition, when inline, or nil."
  2915. (format "[fn:%s%s]"
  2916. (or (org-element-property :label footnote-reference) "")
  2917. (if contents (concat ":" contents) "")))
  2918. ;;;; Inline Babel Call
  2919. (defun org-element-inline-babel-call-parser ()
  2920. "Parse inline babel call at point, if any.
  2921. When at an inline babel call, return a list whose car is
  2922. `inline-babel-call' and cdr a plist with `:call',
  2923. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2924. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2925. Assume point is at the beginning of the babel call."
  2926. (save-excursion
  2927. (catch :no-object
  2928. (when (let ((case-fold-search nil))
  2929. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2930. (goto-char (match-end 1))
  2931. (let* ((begin (match-beginning 0))
  2932. (call (match-string-no-properties 1))
  2933. (inside-header
  2934. (let ((p (org-element--parse-paired-brackets ?\[)))
  2935. (and (org-string-nw-p p)
  2936. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2937. (arguments (org-string-nw-p
  2938. (or (org-element--parse-paired-brackets ?\()
  2939. ;; Parenthesis are mandatory.
  2940. (throw :no-object nil))))
  2941. (end-header
  2942. (let ((p (org-element--parse-paired-brackets ?\[)))
  2943. (and (org-string-nw-p p)
  2944. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2945. (value (buffer-substring-no-properties begin (point)))
  2946. (post-blank (skip-chars-forward " \t"))
  2947. (end (point)))
  2948. (list 'inline-babel-call
  2949. (list :call call
  2950. :inside-header inside-header
  2951. :arguments arguments
  2952. :end-header end-header
  2953. :begin begin
  2954. :end end
  2955. :value value
  2956. :post-blank post-blank)))))))
  2957. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2958. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2959. (concat "call_"
  2960. (org-element-property :call inline-babel-call)
  2961. (let ((h (org-element-property :inside-header inline-babel-call)))
  2962. (and h (format "[%s]" h)))
  2963. "(" (org-element-property :arguments inline-babel-call) ")"
  2964. (let ((h (org-element-property :end-header inline-babel-call)))
  2965. (and h (format "[%s]" h)))))
  2966. ;;;; Inline Src Block
  2967. (defun org-element-inline-src-block-parser ()
  2968. "Parse inline source block at point, if any.
  2969. When at an inline source block, return a list whose car is
  2970. `inline-src-block' and cdr a plist with `:begin', `:end',
  2971. `:language', `:value', `:parameters' and `:post-blank' as
  2972. keywords. Otherwise, return nil.
  2973. Assume point is at the beginning of the inline source block."
  2974. (save-excursion
  2975. (catch :no-object
  2976. (when (let ((case-fold-search nil))
  2977. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2978. (goto-char (match-end 1))
  2979. (let ((begin (match-beginning 0))
  2980. (language (match-string-no-properties 1))
  2981. (parameters
  2982. (let ((p (org-element--parse-paired-brackets ?\[)))
  2983. (and (org-string-nw-p p)
  2984. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2985. (value (or (org-element--parse-paired-brackets ?\{)
  2986. (throw :no-object nil)))
  2987. (post-blank (skip-chars-forward " \t")))
  2988. (list 'inline-src-block
  2989. (list :language language
  2990. :value value
  2991. :parameters parameters
  2992. :begin begin
  2993. :end (point)
  2994. :post-blank post-blank)))))))
  2995. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2996. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2997. (let ((language (org-element-property :language inline-src-block))
  2998. (arguments (org-element-property :parameters inline-src-block))
  2999. (body (org-element-property :value inline-src-block)))
  3000. (format "src_%s%s{%s}"
  3001. language
  3002. (if arguments (format "[%s]" arguments) "")
  3003. body)))
  3004. ;;;; Italic
  3005. (defun org-element-italic-parser ()
  3006. "Parse italic object at point, if any.
  3007. When at an italic object, return a list whose car is `italic' and
  3008. cdr is a plist with `:begin', `:end', `:contents-begin' and
  3009. `:contents-end' and `:post-blank' keywords. Otherwise, return
  3010. nil.
  3011. Assume point is at the first slash marker."
  3012. (org-element--parse-generic-emphasis "/" 'italic))
  3013. (defun org-element-italic-interpreter (_ contents)
  3014. "Interpret italic object as Org syntax.
  3015. CONTENTS is the contents of the object."
  3016. (format "/%s/" contents))
  3017. ;;;; Latex Fragment
  3018. (defun org-element-latex-fragment-parser ()
  3019. "Parse LaTeX fragment at point, if any.
  3020. When at a LaTeX fragment, return a list whose car is
  3021. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  3022. and `:post-blank' as keywords. Otherwise, return nil.
  3023. Assume point is at the beginning of the LaTeX fragment."
  3024. (catch 'no-object
  3025. (save-excursion
  3026. (let* ((begin (point))
  3027. (after-fragment
  3028. (cond
  3029. ((not (eq ?$ (char-after)))
  3030. (pcase (char-after (1+ (point)))
  3031. (?\( (search-forward "\\)" nil t))
  3032. (?\[ (search-forward "\\]" nil t))
  3033. (_
  3034. ;; Macro.
  3035. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  3036. \\|\\({[^{}\n]*}\\)\\)*")
  3037. (match-end 0)))))
  3038. ((eq ?$ (char-after (1+ (point))))
  3039. (search-forward "$$" nil t 2))
  3040. (t
  3041. (and (not (eq ?$ (char-before)))
  3042. (not (memq (char-after (1+ (point)))
  3043. '(?\s ?\t ?\n ?, ?. ?\;)))
  3044. (search-forward "$" nil t 2)
  3045. (not (memq (char-before (match-beginning 0))
  3046. '(?\s ?\t ?\n ?, ?.)))
  3047. (looking-at-p
  3048. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  3049. (point)))))
  3050. (post-blank
  3051. (if (not after-fragment) (throw 'no-object nil)
  3052. (goto-char after-fragment)
  3053. (skip-chars-forward " \t")))
  3054. (end (point)))
  3055. (list 'latex-fragment
  3056. (list :value (buffer-substring-no-properties begin after-fragment)
  3057. :begin begin
  3058. :end end
  3059. :post-blank post-blank))))))
  3060. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  3061. "Interpret LATEX-FRAGMENT object as Org syntax."
  3062. (org-element-property :value latex-fragment))
  3063. ;;;; Line Break
  3064. (defun org-element-line-break-parser ()
  3065. "Parse line break at point, if any.
  3066. When at a line break, return a list whose car is `line-break',
  3067. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  3068. Otherwise, return nil.
  3069. Assume point is at the beginning of the line break."
  3070. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  3071. (not (eq (char-before) ?\\)))
  3072. (list 'line-break
  3073. (list :begin (point)
  3074. :end (line-beginning-position 2)
  3075. :post-blank 0))))
  3076. (defun org-element-line-break-interpreter (&rest _)
  3077. "Interpret LINE-BREAK object as Org syntax."
  3078. "\\\\\n")
  3079. ;;;; Link
  3080. (defun org-element-link-parser ()
  3081. "Parse link at point, if any.
  3082. When at a link, return a list whose car is `link' and cdr a plist
  3083. with `:type', `:path', `:format', `:raw-link', `:application',
  3084. `:search-option', `:begin', `:end', `:contents-begin',
  3085. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  3086. nil.
  3087. Assume point is at the beginning of the link."
  3088. (catch 'no-object
  3089. (let ((begin (point))
  3090. end contents-begin contents-end link-end post-blank path type format
  3091. raw-link search-option application)
  3092. (cond
  3093. ;; Type 1: Text targeted from a radio target.
  3094. ((and org-target-link-regexp
  3095. (save-excursion (or (bolp) (backward-char))
  3096. (looking-at org-target-link-regexp)))
  3097. (setq type "radio")
  3098. (setq format 'plain)
  3099. (setq link-end (match-end 1))
  3100. (setq path (match-string-no-properties 1))
  3101. (setq contents-begin (match-beginning 1))
  3102. (setq contents-end (match-end 1)))
  3103. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  3104. ((looking-at org-link-bracket-re)
  3105. (setq format 'bracket)
  3106. (setq contents-begin (match-beginning 2))
  3107. (setq contents-end (match-end 2))
  3108. (setq link-end (match-end 0))
  3109. ;; RAW-LINK is the original link. Decode any encoding.
  3110. ;; Expand any abbreviation in it.
  3111. ;;
  3112. ;; Also treat any newline character and associated
  3113. ;; indentation as a single space character. This is not
  3114. ;; compatible with RFC 3986, which requires to ignore
  3115. ;; them altogether. However, doing so would require
  3116. ;; users to encode spaces on the fly when writing links
  3117. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  3118. ;; [[shell:ls *.org]], which defeats Org's focus on
  3119. ;; simplicity.
  3120. (setq raw-link (org-link-expand-abbrev
  3121. (org-link-unescape
  3122. (replace-regexp-in-string
  3123. "[ \t]*\n[ \t]*" " "
  3124. (match-string-no-properties 1)))))
  3125. ;; Determine TYPE of link and set PATH accordingly. According
  3126. ;; to RFC 3986, remove whitespaces from URI in external links.
  3127. ;; In internal ones, treat indentation as a single space.
  3128. (cond
  3129. ;; File type.
  3130. ((or (file-name-absolute-p raw-link)
  3131. (string-match "\\`\\.\\.?/" raw-link))
  3132. (setq type "file")
  3133. (setq path raw-link))
  3134. ;; Explicit type (http, irc, bbdb...).
  3135. ((string-match org-link-types-re raw-link)
  3136. (setq type (match-string 1 raw-link))
  3137. (setq path (substring raw-link (match-end 0))))
  3138. ;; Code-ref type: PATH is the name of the reference.
  3139. ((and (string-match-p "\\`(" raw-link)
  3140. (string-match-p ")\\'" raw-link))
  3141. (setq type "coderef")
  3142. (setq path (substring raw-link 1 -1)))
  3143. ;; Custom-id type: PATH is the name of the custom id.
  3144. ((= (string-to-char raw-link) ?#)
  3145. (setq type "custom-id")
  3146. (setq path (substring raw-link 1)))
  3147. ;; Fuzzy type: Internal link either matches a target, an
  3148. ;; headline name or nothing. PATH is the target or
  3149. ;; headline's name.
  3150. (t
  3151. (setq type "fuzzy")
  3152. (setq path raw-link))))
  3153. ;; Type 3: Plain link, e.g., https://orgmode.org
  3154. ((looking-at org-link-plain-re)
  3155. (setq format 'plain)
  3156. (setq raw-link (match-string-no-properties 0))
  3157. (setq type (match-string-no-properties 1))
  3158. (setq link-end (match-end 0))
  3159. (setq path (match-string-no-properties 2)))
  3160. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  3161. ;; bracket links, follow RFC 3986 and remove any extra
  3162. ;; whitespace in URI.
  3163. ((looking-at org-link-angle-re)
  3164. (setq format 'angle)
  3165. (setq type (match-string-no-properties 1))
  3166. (setq link-end (match-end 0))
  3167. (setq raw-link
  3168. (buffer-substring-no-properties
  3169. (match-beginning 1) (match-end 2)))
  3170. (setq path (replace-regexp-in-string
  3171. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  3172. (t (throw 'no-object nil)))
  3173. ;; In any case, deduce end point after trailing white space from
  3174. ;; LINK-END variable.
  3175. (save-excursion
  3176. (setq post-blank
  3177. (progn (goto-char link-end) (skip-chars-forward " \t")))
  3178. (setq end (point)))
  3179. ;; Special "file"-type link processing. Extract opening
  3180. ;; application and search option, if any. Also normalize URI.
  3181. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  3182. (setq application (match-string 1 type))
  3183. (setq type "file")
  3184. (when (string-match "::\\(.*\\)\\'" path)
  3185. (setq search-option (match-string 1 path))
  3186. (setq path (replace-match "" nil nil path)))
  3187. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3188. ;; Translate link, if `org-link-translation-function' is set.
  3189. (let ((trans (and (functionp org-link-translation-function)
  3190. (funcall org-link-translation-function type path))))
  3191. (when trans
  3192. (setq type (car trans))
  3193. (setq path (cdr trans))))
  3194. (list 'link
  3195. (list :type type
  3196. :path path
  3197. :format format
  3198. :raw-link (or raw-link path)
  3199. :application application
  3200. :search-option search-option
  3201. :begin begin
  3202. :end end
  3203. :contents-begin contents-begin
  3204. :contents-end contents-end
  3205. :post-blank post-blank)))))
  3206. (defun org-element-link-interpreter (link contents)
  3207. "Interpret LINK object as Org syntax.
  3208. CONTENTS is the contents of the object, or nil."
  3209. (let ((type (org-element-property :type link))
  3210. (path (org-element-property :path link)))
  3211. (if (string= type "radio") path
  3212. (let ((fmt (pcase (org-element-property :format link)
  3213. ;; Links with contents and internal links have to
  3214. ;; use bracket syntax. Ignore `:format' in these
  3215. ;; cases. This is also the default syntax when the
  3216. ;; property is not defined, e.g., when the object
  3217. ;; was crafted by the user.
  3218. ((guard contents)
  3219. (format "[[%%s][%s]]"
  3220. ;; Since this is going to be used as
  3221. ;; a format string, escape percent signs
  3222. ;; in description.
  3223. (replace-regexp-in-string "%" "%%" contents)))
  3224. ((or `bracket
  3225. `nil
  3226. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3227. "[[%s]]")
  3228. ;; Otherwise, just obey to `:format'.
  3229. (`angle "<%s>")
  3230. (`plain "%s")
  3231. (f (error "Wrong `:format' value: %s" f)))))
  3232. (format fmt
  3233. (pcase type
  3234. ("coderef" (format "(%s)" path))
  3235. ("custom-id" (concat "#" path))
  3236. ("file"
  3237. (let ((app (org-element-property :application link))
  3238. (opt (org-element-property :search-option link)))
  3239. (concat type (and app (concat "+" app)) ":"
  3240. path
  3241. (and opt (concat "::" opt)))))
  3242. ("fuzzy" path)
  3243. (_ (concat type ":" path))))))))
  3244. ;;;; Macro
  3245. (defun org-element-macro-parser ()
  3246. "Parse macro at point, if any.
  3247. When at a macro, return a list whose car is `macro' and cdr
  3248. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3249. `:post-blank' as keywords. Otherwise, return nil.
  3250. Assume point is at the macro."
  3251. (save-excursion
  3252. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3253. (let ((begin (point))
  3254. (key (downcase (match-string-no-properties 1)))
  3255. (value (match-string-no-properties 0))
  3256. (post-blank (progn (goto-char (match-end 0))
  3257. (skip-chars-forward " \t")))
  3258. (end (point))
  3259. (args (pcase (match-string-no-properties 3)
  3260. (`nil nil)
  3261. (a (org-macro-extract-arguments
  3262. (replace-regexp-in-string
  3263. "[ \t\r\n]+" " " (org-trim a)))))))
  3264. (list 'macro
  3265. (list :key key
  3266. :value value
  3267. :args args
  3268. :begin begin
  3269. :end end
  3270. :post-blank post-blank))))))
  3271. (defun org-element-macro-interpreter (macro _)
  3272. "Interpret MACRO object as Org syntax."
  3273. (format "{{{%s%s}}}"
  3274. (org-element-property :key macro)
  3275. (pcase (org-element-property :args macro)
  3276. (`nil "")
  3277. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3278. ;;;; Radio-target
  3279. (defun org-element-radio-target-parser ()
  3280. "Parse radio target at point, if any.
  3281. When at a radio target, return a list whose car is `radio-target'
  3282. and cdr a plist with `:begin', `:end', `:contents-begin',
  3283. `:contents-end', `:value' and `:post-blank' as keywords.
  3284. Otherwise, return nil.
  3285. Assume point is at the radio target."
  3286. (save-excursion
  3287. (when (looking-at org-radio-target-regexp)
  3288. (let ((begin (point))
  3289. (contents-begin (match-beginning 1))
  3290. (contents-end (match-end 1))
  3291. (value (match-string-no-properties 1))
  3292. (post-blank (progn (goto-char (match-end 0))
  3293. (skip-chars-forward " \t")))
  3294. (end (point)))
  3295. (list 'radio-target
  3296. (list :begin begin
  3297. :end end
  3298. :contents-begin contents-begin
  3299. :contents-end contents-end
  3300. :post-blank post-blank
  3301. :value value))))))
  3302. (defun org-element-radio-target-interpreter (_ contents)
  3303. "Interpret target object as Org syntax.
  3304. CONTENTS is the contents of the object."
  3305. (concat "<<<" contents ">>>"))
  3306. ;;;; Statistics Cookie
  3307. (defun org-element-statistics-cookie-parser ()
  3308. "Parse statistics cookie at point, if any.
  3309. When at a statistics cookie, return a list whose car is
  3310. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3311. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3312. Assume point is at the beginning of the statistics-cookie."
  3313. (save-excursion
  3314. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3315. (let* ((begin (point))
  3316. (value (buffer-substring-no-properties
  3317. (match-beginning 0) (match-end 0)))
  3318. (post-blank (progn (goto-char (match-end 0))
  3319. (skip-chars-forward " \t")))
  3320. (end (point)))
  3321. (list 'statistics-cookie
  3322. (list :begin begin
  3323. :end end
  3324. :value value
  3325. :post-blank post-blank))))))
  3326. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3327. "Interpret STATISTICS-COOKIE object as Org syntax."
  3328. (org-element-property :value statistics-cookie))
  3329. ;;;; Strike-Through
  3330. (defun org-element-strike-through-parser ()
  3331. "Parse strike-through object at point, if any.
  3332. When at a strike-through object, return a list whose car is
  3333. `strike-through' and cdr is a plist with `:begin', `:end',
  3334. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3335. Otherwise, return nil.
  3336. Assume point is at the first plus sign marker."
  3337. (org-element--parse-generic-emphasis "+" 'strike-through))
  3338. (defun org-element-strike-through-interpreter (_ contents)
  3339. "Interpret strike-through object as Org syntax.
  3340. CONTENTS is the contents of the object."
  3341. (format "+%s+" contents))
  3342. ;;;; Subscript
  3343. (defun org-element-subscript-parser ()
  3344. "Parse subscript at point, if any.
  3345. When at a subscript object, return a list whose car is
  3346. `subscript' and cdr a plist with `:begin', `:end',
  3347. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3348. `:post-blank' as keywords. Otherwise, return nil.
  3349. Assume point is at the underscore."
  3350. (save-excursion
  3351. (unless (bolp) (backward-char))
  3352. (when (looking-at org-match-substring-regexp)
  3353. (let ((bracketsp (match-beginning 4))
  3354. (begin (match-beginning 2))
  3355. (contents-begin (or (match-beginning 4)
  3356. (match-beginning 3)))
  3357. (contents-end (or (match-end 4) (match-end 3)))
  3358. (post-blank (progn (goto-char (match-end 0))
  3359. (skip-chars-forward " \t")))
  3360. (end (point)))
  3361. (list 'subscript
  3362. (list :begin begin
  3363. :end end
  3364. :use-brackets-p bracketsp
  3365. :contents-begin contents-begin
  3366. :contents-end contents-end
  3367. :post-blank post-blank))))))
  3368. (defun org-element-subscript-interpreter (subscript contents)
  3369. "Interpret SUBSCRIPT object as Org syntax.
  3370. CONTENTS is the contents of the object."
  3371. (format
  3372. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3373. contents))
  3374. ;;;; Superscript
  3375. (defun org-element-superscript-parser ()
  3376. "Parse superscript at point, if any.
  3377. When at a superscript object, return a list whose car is
  3378. `superscript' and cdr a plist with `:begin', `:end',
  3379. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3380. `:post-blank' as keywords. Otherwise, return nil.
  3381. Assume point is at the caret."
  3382. (save-excursion
  3383. (unless (bolp) (backward-char))
  3384. (when (looking-at org-match-substring-regexp)
  3385. (let ((bracketsp (match-beginning 4))
  3386. (begin (match-beginning 2))
  3387. (contents-begin (or (match-beginning 4)
  3388. (match-beginning 3)))
  3389. (contents-end (or (match-end 4) (match-end 3)))
  3390. (post-blank (progn (goto-char (match-end 0))
  3391. (skip-chars-forward " \t")))
  3392. (end (point)))
  3393. (list 'superscript
  3394. (list :begin begin
  3395. :end end
  3396. :use-brackets-p bracketsp
  3397. :contents-begin contents-begin
  3398. :contents-end contents-end
  3399. :post-blank post-blank))))))
  3400. (defun org-element-superscript-interpreter (superscript contents)
  3401. "Interpret SUPERSCRIPT object as Org syntax.
  3402. CONTENTS is the contents of the object."
  3403. (format
  3404. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3405. contents))
  3406. ;;;; Table Cell
  3407. (defun org-element-table-cell-parser ()
  3408. "Parse table cell at point.
  3409. Return a list whose car is `table-cell' and cdr is a plist
  3410. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3411. and `:post-blank' keywords."
  3412. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3413. (let* ((begin (match-beginning 0))
  3414. (end (match-end 0))
  3415. (contents-begin (match-beginning 1))
  3416. (contents-end (match-end 1)))
  3417. (list 'table-cell
  3418. (list :begin begin
  3419. :end end
  3420. :contents-begin contents-begin
  3421. :contents-end contents-end
  3422. :post-blank 0))))
  3423. (defun org-element-table-cell-interpreter (_ contents)
  3424. "Interpret table-cell element as Org syntax.
  3425. CONTENTS is the contents of the cell, or nil."
  3426. (concat " " contents " |"))
  3427. ;;;; Target
  3428. (defun org-element-target-parser ()
  3429. "Parse target at point, if any.
  3430. When at a target, return a list whose car is `target' and cdr
  3431. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3432. keywords. Otherwise, return nil.
  3433. Assume point is at the target."
  3434. (save-excursion
  3435. (when (looking-at org-target-regexp)
  3436. (let ((begin (point))
  3437. (value (match-string-no-properties 1))
  3438. (post-blank (progn (goto-char (match-end 0))
  3439. (skip-chars-forward " \t")))
  3440. (end (point)))
  3441. (list 'target
  3442. (list :begin begin
  3443. :end end
  3444. :value value
  3445. :post-blank post-blank))))))
  3446. (defun org-element-target-interpreter (target _)
  3447. "Interpret TARGET object as Org syntax."
  3448. (format "<<%s>>" (org-element-property :value target)))
  3449. ;;;; Timestamp
  3450. (defconst org-element--timestamp-regexp
  3451. (concat org-ts-regexp-both
  3452. "\\|"
  3453. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3454. "\\|"
  3455. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3456. "Regexp matching any timestamp type object.")
  3457. (defun org-element-timestamp-parser ()
  3458. "Parse time stamp at point, if any.
  3459. When at a time stamp, return a list whose car is `timestamp', and
  3460. cdr a plist with `:type', `:raw-value', `:year-start',
  3461. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3462. `:year-end', `:month-end', `:day-end', `:hour-end',
  3463. `:minute-end', `:repeater-type', `:repeater-value',
  3464. `:repeater-unit', `:warning-type', `:warning-value',
  3465. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3466. Otherwise, return nil.
  3467. Assume point is at the beginning of the timestamp."
  3468. (when (looking-at-p org-element--timestamp-regexp)
  3469. (save-excursion
  3470. (let* ((begin (point))
  3471. (activep (eq (char-after) ?<))
  3472. (raw-value
  3473. (progn
  3474. (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
  3475. (match-string-no-properties 0)))
  3476. (date-start (match-string-no-properties 1))
  3477. (date-end (match-string 3))
  3478. (diaryp (match-beginning 2))
  3479. (post-blank (progn (goto-char (match-end 0))
  3480. (skip-chars-forward " \t")))
  3481. (end (point))
  3482. (time-range
  3483. (and (not diaryp)
  3484. (string-match
  3485. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3486. date-start)
  3487. (cons (string-to-number (match-string 2 date-start))
  3488. (string-to-number (match-string 3 date-start)))))
  3489. (type (cond (diaryp 'diary)
  3490. ((and activep (or date-end time-range)) 'active-range)
  3491. (activep 'active)
  3492. ((or date-end time-range) 'inactive-range)
  3493. (t 'inactive)))
  3494. (repeater-props
  3495. (and (not diaryp)
  3496. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3497. raw-value)
  3498. (list
  3499. :repeater-type
  3500. (let ((type (match-string 1 raw-value)))
  3501. (cond ((equal "++" type) 'catch-up)
  3502. ((equal ".+" type) 'restart)
  3503. (t 'cumulate)))
  3504. :repeater-value (string-to-number (match-string 2 raw-value))
  3505. :repeater-unit
  3506. (pcase (string-to-char (match-string 3 raw-value))
  3507. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3508. (warning-props
  3509. (and (not diaryp)
  3510. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3511. (list
  3512. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3513. :warning-value (string-to-number (match-string 2 raw-value))
  3514. :warning-unit
  3515. (pcase (string-to-char (match-string 3 raw-value))
  3516. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3517. year-start month-start day-start hour-start minute-start year-end
  3518. month-end day-end hour-end minute-end)
  3519. ;; Parse date-start.
  3520. (unless diaryp
  3521. (let ((date (org-parse-time-string date-start t)))
  3522. (setq year-start (nth 5 date)
  3523. month-start (nth 4 date)
  3524. day-start (nth 3 date)
  3525. hour-start (nth 2 date)
  3526. minute-start (nth 1 date))))
  3527. ;; Compute date-end. It can be provided directly in time-stamp,
  3528. ;; or extracted from time range. Otherwise, it defaults to the
  3529. ;; same values as date-start.
  3530. (unless diaryp
  3531. (let ((date (and date-end (org-parse-time-string date-end t))))
  3532. (setq year-end (or (nth 5 date) year-start)
  3533. month-end (or (nth 4 date) month-start)
  3534. day-end (or (nth 3 date) day-start)
  3535. hour-end (or (nth 2 date) (car time-range) hour-start)
  3536. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3537. (list 'timestamp
  3538. (nconc (list :type type
  3539. :raw-value raw-value
  3540. :year-start year-start
  3541. :month-start month-start
  3542. :day-start day-start
  3543. :hour-start hour-start
  3544. :minute-start minute-start
  3545. :year-end year-end
  3546. :month-end month-end
  3547. :day-end day-end
  3548. :hour-end hour-end
  3549. :minute-end minute-end
  3550. :begin begin
  3551. :end end
  3552. :post-blank post-blank)
  3553. repeater-props
  3554. warning-props))))))
  3555. (defun org-element-timestamp-interpreter (timestamp _)
  3556. "Interpret TIMESTAMP object as Org syntax."
  3557. (let* ((repeat-string
  3558. (concat
  3559. (pcase (org-element-property :repeater-type timestamp)
  3560. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3561. (let ((val (org-element-property :repeater-value timestamp)))
  3562. (and val (number-to-string val)))
  3563. (pcase (org-element-property :repeater-unit timestamp)
  3564. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3565. (warning-string
  3566. (concat
  3567. (pcase (org-element-property :warning-type timestamp)
  3568. (`first "--") (`all "-"))
  3569. (let ((val (org-element-property :warning-value timestamp)))
  3570. (and val (number-to-string val)))
  3571. (pcase (org-element-property :warning-unit timestamp)
  3572. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3573. (build-ts-string
  3574. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3575. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3576. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3577. ;; specify a time range in the timestamp. REPEAT-STRING is
  3578. ;; the repeater string, if any.
  3579. (lambda (time activep &optional with-time-p hour-end minute-end)
  3580. (let ((ts (format-time-string
  3581. (funcall (if with-time-p #'cdr #'car)
  3582. org-time-stamp-formats)
  3583. time)))
  3584. (when (and hour-end minute-end)
  3585. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3586. (setq ts
  3587. (replace-match
  3588. (format "\\&-%02d:%02d" hour-end minute-end)
  3589. nil nil ts)))
  3590. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3591. (dolist (s (list repeat-string warning-string))
  3592. (when (org-string-nw-p s)
  3593. (setq ts (concat (substring ts 0 -1)
  3594. " "
  3595. s
  3596. (substring ts -1)))))
  3597. ;; Return value.
  3598. ts)))
  3599. (type (org-element-property :type timestamp)))
  3600. (pcase type
  3601. ((or `active `inactive)
  3602. (let* ((minute-start (org-element-property :minute-start timestamp))
  3603. (minute-end (org-element-property :minute-end timestamp))
  3604. (hour-start (org-element-property :hour-start timestamp))
  3605. (hour-end (org-element-property :hour-end timestamp))
  3606. (time-range-p (and hour-start hour-end minute-start minute-end
  3607. (or (/= hour-start hour-end)
  3608. (/= minute-start minute-end)))))
  3609. (funcall
  3610. build-ts-string
  3611. (encode-time 0
  3612. (or minute-start 0)
  3613. (or hour-start 0)
  3614. (org-element-property :day-start timestamp)
  3615. (org-element-property :month-start timestamp)
  3616. (org-element-property :year-start timestamp))
  3617. (eq type 'active)
  3618. (and hour-start minute-start)
  3619. (and time-range-p hour-end)
  3620. (and time-range-p minute-end))))
  3621. ((or `active-range `inactive-range)
  3622. (let ((minute-start (org-element-property :minute-start timestamp))
  3623. (minute-end (org-element-property :minute-end timestamp))
  3624. (hour-start (org-element-property :hour-start timestamp))
  3625. (hour-end (org-element-property :hour-end timestamp)))
  3626. (concat
  3627. (funcall
  3628. build-ts-string (encode-time
  3629. 0
  3630. (or minute-start 0)
  3631. (or hour-start 0)
  3632. (org-element-property :day-start timestamp)
  3633. (org-element-property :month-start timestamp)
  3634. (org-element-property :year-start timestamp))
  3635. (eq type 'active-range)
  3636. (and hour-start minute-start))
  3637. "--"
  3638. (funcall build-ts-string
  3639. (encode-time 0
  3640. (or minute-end 0)
  3641. (or hour-end 0)
  3642. (org-element-property :day-end timestamp)
  3643. (org-element-property :month-end timestamp)
  3644. (org-element-property :year-end timestamp))
  3645. (eq type 'active-range)
  3646. (and hour-end minute-end)))))
  3647. (_ (org-element-property :raw-value timestamp)))))
  3648. ;;;; Underline
  3649. (defun org-element-underline-parser ()
  3650. "Parse underline object at point, if any.
  3651. When at an underline object, return a list whose car is
  3652. `underline' and cdr is a plist with `:begin', `:end',
  3653. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3654. Otherwise, return nil.
  3655. Assume point is at the first underscore marker."
  3656. (org-element--parse-generic-emphasis "_" 'underline))
  3657. (defun org-element-underline-interpreter (_ contents)
  3658. "Interpret underline object as Org syntax.
  3659. CONTENTS is the contents of the object."
  3660. (format "_%s_" contents))
  3661. ;;;; Verbatim
  3662. (defun org-element-verbatim-parser ()
  3663. "Parse verbatim object at point, if any.
  3664. When at a verbatim object, return a list whose car is `verbatim'
  3665. and cdr is a plist with `:value', `:begin', `:end' and
  3666. `:post-blank' keywords. Otherwise, return nil.
  3667. Assume point is at the first equal sign marker."
  3668. (org-element--parse-generic-emphasis "=" 'verbatim))
  3669. (defun org-element-verbatim-interpreter (verbatim _)
  3670. "Interpret VERBATIM object as Org syntax."
  3671. (format "=%s=" (org-element-property :value verbatim)))
  3672. ;;; Parsing Element Starting At Point
  3673. ;;
  3674. ;; `org-element--current-element' is the core function of this section.
  3675. ;; It returns the Lisp representation of the element starting at
  3676. ;; point.
  3677. (defvar org-element--cache-sync-requests); Declared later
  3678. (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
  3679. "Parse the element starting at point.
  3680. Return value is a list like (TYPE PROPS) where TYPE is the type
  3681. of the element and PROPS a plist of properties associated to the
  3682. element.
  3683. Possible types are defined in `org-element-all-elements'.
  3684. LIMIT bounds the search.
  3685. Optional argument GRANULARITY determines the depth of the
  3686. recursion. Allowed values are `headline', `greater-element',
  3687. `element', `object' or nil. When it is broader than `object' (or
  3688. nil), secondary values will not be parsed, since they only
  3689. contain objects.
  3690. Optional argument MODE, when non-nil, can be either
  3691. `first-section', `item', `node-property', `planning',
  3692. `property-drawer', `section', `table-row', or `top-comment'.
  3693. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3694. computed.
  3695. Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
  3696. will also add current element to cache if it is not yet there. Use
  3697. this argument with care, as validity of the element in parse tree is
  3698. not checked.
  3699. This function assumes point is always at the beginning of the
  3700. element it has to parse."
  3701. (let* ((element (and (not (buffer-narrowed-p))
  3702. (org-element--cache-active-p)
  3703. (not org-element--cache-sync-requests)
  3704. (org-element--cache-find (point) t)))
  3705. (element (progn (while (and element
  3706. (not (and (eq (point) (org-element-property :begin element))
  3707. (eq mode (org-element-property :mode element)))))
  3708. (setq element (org-element-property :parent element)))
  3709. element))
  3710. (old-element element)
  3711. (element (when
  3712. (pcase (org-element-property :granularity element)
  3713. (`nil t)
  3714. (`object t)
  3715. (`element (not (memq granularity '(nil object))))
  3716. (`greater-element (not (memq granularity '(nil object element))))
  3717. (`headline (eq granularity 'headline)))
  3718. element)))
  3719. (if element
  3720. element
  3721. (save-excursion
  3722. (let ((case-fold-search t)
  3723. ;; Determine if parsing depth allows for secondary strings
  3724. ;; parsing. It only applies to elements referenced in
  3725. ;; `org-element-secondary-value-alist'.
  3726. (raw-secondary-p (and granularity (not (eq granularity 'object))))
  3727. result)
  3728. (setq
  3729. result
  3730. (cond
  3731. ;; Item.
  3732. ((eq mode 'item)
  3733. (org-element-item-parser limit structure raw-secondary-p))
  3734. ;; Table Row.
  3735. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3736. ;; Node Property.
  3737. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3738. ;; Headline.
  3739. ((org-with-limited-levels (looking-at-p org-outline-regexp-bol))
  3740. (org-element-headline-parser limit raw-secondary-p))
  3741. ;; Sections (must be checked after headline).
  3742. ((eq mode 'section) (org-element-section-parser limit))
  3743. ((eq mode 'first-section)
  3744. (org-element-section-parser
  3745. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3746. limit)))
  3747. ;; Comments.
  3748. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3749. (org-element-comment-parser limit))
  3750. ;; Planning.
  3751. ((and (eq mode 'planning)
  3752. (eq ?* (char-after (line-beginning-position 0)))
  3753. (looking-at org-element-planning-line-re))
  3754. (org-element-planning-parser limit))
  3755. ;; Property drawer.
  3756. ((and (pcase mode
  3757. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3758. ((or `property-drawer `top-comment)
  3759. (save-excursion
  3760. (beginning-of-line 0)
  3761. (not (looking-at "[[:blank:]]*$"))))
  3762. (_ nil))
  3763. (looking-at org-property-drawer-re))
  3764. (org-element-property-drawer-parser limit))
  3765. ;; When not at bol, point is at the beginning of an item or
  3766. ;; a footnote definition: next item is always a paragraph.
  3767. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3768. ;; Clock.
  3769. ((looking-at org-element-clock-line-re)
  3770. (org-element-clock-parser limit))
  3771. ;; Inlinetask.
  3772. ((looking-at "^\\*+ ")
  3773. (org-element-inlinetask-parser limit raw-secondary-p))
  3774. ;; From there, elements can have affiliated keywords.
  3775. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3776. limit (memq granularity '(nil object)))))
  3777. (cond
  3778. ;; Jumping over affiliated keywords put point off-limits.
  3779. ;; Parse them as regular keywords.
  3780. ((and (cdr affiliated) (>= (point) limit))
  3781. (goto-char (car affiliated))
  3782. (org-element-keyword-parser limit nil))
  3783. ;; LaTeX Environment.
  3784. ((looking-at org-element--latex-begin-environment)
  3785. (org-element-latex-environment-parser limit affiliated))
  3786. ;; Drawer.
  3787. ((looking-at org-element-drawer-re)
  3788. (org-element-drawer-parser limit affiliated))
  3789. ;; Fixed Width
  3790. ((looking-at "[ \t]*:\\( \\|$\\)")
  3791. (org-element-fixed-width-parser limit affiliated))
  3792. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3793. ;; Keywords.
  3794. ((looking-at "[ \t]*#\\+")
  3795. (goto-char (match-end 0))
  3796. (cond
  3797. ((looking-at "BEGIN_\\(\\S-+\\)")
  3798. (beginning-of-line)
  3799. (funcall (pcase (upcase (match-string 1))
  3800. ("CENTER" #'org-element-center-block-parser)
  3801. ("COMMENT" #'org-element-comment-block-parser)
  3802. ("EXAMPLE" #'org-element-example-block-parser)
  3803. ("EXPORT" #'org-element-export-block-parser)
  3804. ("QUOTE" #'org-element-quote-block-parser)
  3805. ("SRC" #'org-element-src-block-parser)
  3806. ("VERSE" #'org-element-verse-block-parser)
  3807. (_ #'org-element-special-block-parser))
  3808. limit
  3809. affiliated))
  3810. ((looking-at "CALL:")
  3811. (beginning-of-line)
  3812. (org-element-babel-call-parser limit affiliated))
  3813. ((save-excursion
  3814. (beginning-of-line)
  3815. (looking-at org-element-dynamic-block-open-re))
  3816. (beginning-of-line)
  3817. (org-element-dynamic-block-parser limit affiliated))
  3818. ((looking-at "\\S-+:")
  3819. (beginning-of-line)
  3820. (org-element-keyword-parser limit affiliated))
  3821. (t
  3822. (beginning-of-line)
  3823. (org-element-paragraph-parser limit affiliated))))
  3824. ;; Footnote Definition.
  3825. ((looking-at org-footnote-definition-re)
  3826. (org-element-footnote-definition-parser limit affiliated))
  3827. ;; Horizontal Rule.
  3828. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3829. (org-element-horizontal-rule-parser limit affiliated))
  3830. ;; Diary Sexp.
  3831. ((looking-at "%%(")
  3832. (org-element-diary-sexp-parser limit affiliated))
  3833. ;; Table.
  3834. ((or (looking-at "[ \t]*|")
  3835. ;; There is no strict definition of a table.el
  3836. ;; table. Try to prevent false positive while being
  3837. ;; quick.
  3838. (let ((rule-regexp
  3839. (rx (zero-or-more (any " \t"))
  3840. "+"
  3841. (one-or-more (one-or-more "-") "+")
  3842. (zero-or-more (any " \t"))
  3843. eol))
  3844. (non-table.el-line
  3845. (rx bol
  3846. (zero-or-more (any " \t"))
  3847. (or eol (not (any "+| \t")))))
  3848. (next (line-beginning-position 2)))
  3849. ;; Start with a full rule.
  3850. (and
  3851. (looking-at rule-regexp)
  3852. (< next limit) ;no room for a table.el table
  3853. (save-excursion
  3854. (end-of-line)
  3855. (cond
  3856. ;; Must end with a full rule.
  3857. ((not (re-search-forward non-table.el-line limit 'move))
  3858. (if (bolp) (forward-line -1) (beginning-of-line))
  3859. (looking-at rule-regexp))
  3860. ;; Ignore pseudo-tables with a single
  3861. ;; rule.
  3862. ((= next (line-beginning-position))
  3863. nil)
  3864. ;; Must end with a full rule.
  3865. (t
  3866. (forward-line -1)
  3867. (looking-at rule-regexp)))))))
  3868. (org-element-table-parser limit affiliated))
  3869. ;; List.
  3870. ((looking-at (org-item-re))
  3871. (org-element-plain-list-parser
  3872. limit affiliated
  3873. (or structure (org-element--list-struct limit))))
  3874. ;; Default element: Paragraph.
  3875. (t (org-element-paragraph-parser limit affiliated)))))))
  3876. (when result
  3877. (org-element-put-property result :mode mode)
  3878. (org-element-put-property result :granularity granularity))
  3879. (when (and (not (buffer-narrowed-p))
  3880. (org-element--cache-active-p)
  3881. (not org-element--cache-sync-requests)
  3882. add-to-cache)
  3883. (if (not old-element)
  3884. (setq result (org-element--cache-put result))
  3885. (org-element-set-element old-element result)
  3886. (setq result old-element)))
  3887. result)))))
  3888. ;; Most elements can have affiliated keywords. When looking for an
  3889. ;; element beginning, we want to move before them, as they belong to
  3890. ;; that element, and, in the meantime, collect information they give
  3891. ;; into appropriate properties. Hence the following function.
  3892. (defun org-element--collect-affiliated-keywords (limit parse)
  3893. "Collect affiliated keywords from point down to LIMIT.
  3894. Return a list whose CAR is the position at the first of them and
  3895. CDR a plist of keywords and values and move point to the
  3896. beginning of the first line after them.
  3897. As a special case, if element doesn't start at the beginning of
  3898. the line (e.g., a paragraph starting an item), CAR is current
  3899. position of point and CDR is nil.
  3900. When PARSE is non-nil, values from keywords belonging to
  3901. `org-element-parsed-keywords' are parsed as secondary strings."
  3902. (if (not (bolp)) (list (point))
  3903. (let ((case-fold-search t)
  3904. (origin (point))
  3905. ;; RESTRICT is the list of objects allowed in parsed
  3906. ;; keywords value. If PARSE is nil, no object is allowed.
  3907. (restrict (and parse (org-element-restriction 'keyword)))
  3908. output)
  3909. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3910. (let* ((raw-kwd (upcase (match-string 1)))
  3911. ;; Apply translation to RAW-KWD. From there, KWD is
  3912. ;; the official keyword.
  3913. (kwd (or (cdr (assoc raw-kwd
  3914. org-element-keyword-translation-alist))
  3915. raw-kwd))
  3916. ;; PARSED? is non-nil when keyword should have its
  3917. ;; value parsed.
  3918. (parsed? (member kwd org-element-parsed-keywords))
  3919. ;; Find main value for any keyword.
  3920. (value
  3921. (let ((beg (match-end 0))
  3922. (end (save-excursion
  3923. (end-of-line)
  3924. (skip-chars-backward " \t")
  3925. (point))))
  3926. (if parsed?
  3927. (save-match-data
  3928. (org-element--parse-objects beg end nil restrict))
  3929. (org-trim (buffer-substring-no-properties beg end)))))
  3930. ;; If KWD is a dual keyword, find its secondary value.
  3931. ;; Maybe parse it.
  3932. (dual? (member kwd org-element-dual-keywords))
  3933. (dual-value
  3934. (and dual?
  3935. (let ((sec (match-string-no-properties 2)))
  3936. (cond
  3937. ((and sec parsed?)
  3938. (save-match-data
  3939. (org-element--parse-objects
  3940. (match-beginning 2) (match-end 2) nil restrict)))
  3941. (sec sec)))))
  3942. ;; Attribute a property name to KWD.
  3943. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3944. ;; Now set final shape for VALUE.
  3945. (when dual?
  3946. (setq value (and (or value dual-value) (cons value dual-value))))
  3947. (when (or (member kwd org-element-multiple-keywords)
  3948. ;; Attributes can always appear on multiple lines.
  3949. (string-match "^ATTR_" kwd))
  3950. (setq value (cons value (plist-get output kwd-sym))))
  3951. ;; Eventually store the new value in OUTPUT.
  3952. (setq output (plist-put output kwd-sym value))
  3953. ;; Move to next keyword.
  3954. (forward-line)))
  3955. ;; If affiliated keywords are orphaned: move back to first one.
  3956. ;; They will be parsed as a paragraph.
  3957. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3958. ;; Return value.
  3959. (cons origin output))))
  3960. ;;; The Org Parser
  3961. ;;
  3962. ;; The two major functions here are `org-element-parse-buffer', which
  3963. ;; parses Org syntax inside the current buffer, taking into account
  3964. ;; region, narrowing, or even visibility if specified, and
  3965. ;; `org-element-parse-secondary-string', which parses objects within
  3966. ;; a given string.
  3967. ;;
  3968. ;; The (almost) almighty `org-element-map' allows applying a function
  3969. ;; on elements or objects matching some type, and accumulating the
  3970. ;; resulting values. In an export situation, it also skips unneeded
  3971. ;; parts of the parse tree.
  3972. (defun org-element-parse-buffer (&optional granularity visible-only)
  3973. "Recursively parse the buffer and return structure.
  3974. If narrowing is in effect, only parse the visible part of the
  3975. buffer.
  3976. Optional argument GRANULARITY determines the depth of the
  3977. recursion. It can be set to the following symbols:
  3978. `headline' Only parse headlines.
  3979. `greater-element' Don't recurse into greater elements except
  3980. headlines and sections. Thus, elements
  3981. parsed are the top-level ones.
  3982. `element' Parse everything but objects and plain text.
  3983. `object' Parse the complete buffer (default).
  3984. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3985. elements.
  3986. An element or object is represented as a list with the
  3987. pattern (TYPE PROPERTIES CONTENTS), where :
  3988. TYPE is a symbol describing the element or object. See
  3989. `org-element-all-elements' and `org-element-all-objects' for an
  3990. exhaustive list of such symbols. One can retrieve it with
  3991. `org-element-type' function.
  3992. PROPERTIES is the list of attributes attached to the element or
  3993. object, as a plist. Although most of them are specific to the
  3994. element or object type, all types share `:begin', `:end',
  3995. `:post-blank' and `:parent' properties, which respectively
  3996. refer to buffer position where the element or object starts,
  3997. ends, the number of white spaces or blank lines after it, and
  3998. the element or object containing it. Properties values can be
  3999. obtained by using `org-element-property' function.
  4000. CONTENTS is a list of elements, objects or raw strings
  4001. contained in the current element or object, when applicable.
  4002. One can access them with `org-element-contents' function.
  4003. The Org buffer has `org-data' as type and nil as properties.
  4004. `org-element-map' function can be used to find specific elements
  4005. or objects within the parse tree.
  4006. This function assumes that current major mode is `org-mode'."
  4007. (save-excursion
  4008. (goto-char (point-min))
  4009. (let ((org-data (org-element-org-data-parser))
  4010. (gc-cons-threshold #x40000000))
  4011. (org-skip-whitespace)
  4012. (org-element--parse-elements
  4013. (point-at-bol) (point-max)
  4014. ;; Start in `first-section' mode so text before the first
  4015. ;; headline belongs to a section.
  4016. 'first-section nil granularity visible-only org-data))))
  4017. (defun org-element-parse-secondary-string (string restriction &optional parent)
  4018. "Recursively parse objects in STRING and return structure.
  4019. RESTRICTION is a symbol limiting the object types that will be
  4020. looked after.
  4021. Optional argument PARENT, when non-nil, is the element or object
  4022. containing the secondary string. It is used to set correctly
  4023. `:parent' property within the string.
  4024. If STRING is the empty string or nil, return nil."
  4025. (cond
  4026. ((not string) nil)
  4027. ((equal string "") nil)
  4028. (t (let ((local-variables (buffer-local-variables)))
  4029. (with-temp-buffer
  4030. (dolist (v local-variables)
  4031. (ignore-errors
  4032. (if (symbolp v) (makunbound v)
  4033. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  4034. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  4035. (set (make-local-variable (car v)) (cdr v))))))
  4036. ;; Transferring local variables may put the temporary buffer
  4037. ;; into a read-only state. Make sure we can insert STRING.
  4038. (let ((inhibit-read-only t)) (insert string))
  4039. ;; Prevent "Buffer *temp* modified; kill anyway?".
  4040. (restore-buffer-modified-p nil)
  4041. (org-element--parse-objects
  4042. (point-min) (point-max) nil restriction parent))))))
  4043. (defun org-element-map
  4044. (data types fun &optional info first-match no-recursion with-affiliated)
  4045. "Map a function on selected elements or objects.
  4046. DATA is a parse tree (for example, returned by
  4047. `org-element-parse-buffer'), an element, an object, a string, or a
  4048. list of such constructs. TYPES is a symbol or list of symbols of
  4049. elements or object types (see `org-element-all-elements' and
  4050. `org-element-all-objects' for a complete list of types). FUN is the
  4051. function called on the matching element or object. It has to accept
  4052. one argument: the element or object itself.
  4053. When optional argument INFO is non-nil, it should be a plist
  4054. holding export options. In that case, parts of the parse tree
  4055. not exportable according to that property list will be skipped.
  4056. When optional argument FIRST-MATCH is non-nil, stop at the first
  4057. match for which FUN doesn't return nil, and return that value.
  4058. Optional argument NO-RECURSION is a symbol or a list of symbols
  4059. representing elements or objects types. `org-element-map' won't
  4060. enter any recursive element or object whose type belongs to that
  4061. list. Though, FUN can still be applied on them.
  4062. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  4063. apply to matching objects within parsed affiliated keywords (see
  4064. `org-element-parsed-keywords').
  4065. Nil values returned from FUN do not appear in the results.
  4066. Examples:
  4067. ---------
  4068. Assuming TREE is a variable containing an Org buffer parse tree,
  4069. the following example will return a flat list of all `src-block'
  4070. and `example-block' elements in it:
  4071. (setq tree (org-element-parse-buffer))
  4072. (org-element-map tree \\='(example-block src-block) #\\='identity)
  4073. The following snippet will find the first headline with a level
  4074. of 1 and a \"phone\" tag, and will return its beginning position:
  4075. (org-element-map tree \\='headline
  4076. (lambda (hl)
  4077. (and (= (org-element-property :level hl) 1)
  4078. (member \"phone\" (org-element-property :tags hl))
  4079. (org-element-property :begin hl)))
  4080. nil t)
  4081. The next example will return a flat list of all `plain-list' type
  4082. elements in TREE that are not a sub-list themselves:
  4083. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  4084. Eventually, this example will return a flat list of all `bold'
  4085. type objects containing a `latex-snippet' type object, even
  4086. looking into captions:
  4087. (org-element-map tree \\='bold
  4088. (lambda (b)
  4089. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  4090. nil nil nil t)"
  4091. (declare (indent 2))
  4092. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  4093. (let* ((types (if (listp types) types (list types)))
  4094. (no-recursion (if (listp no-recursion) no-recursion
  4095. (list no-recursion)))
  4096. ;; Recursion depth is determined by --CATEGORY.
  4097. (--category
  4098. (catch :--found
  4099. (let ((category 'greater-elements)
  4100. (all-objects (cons 'plain-text org-element-all-objects)))
  4101. (dolist (type types category)
  4102. (cond ((memq type all-objects)
  4103. ;; If one object is found, the function has
  4104. ;; to recurse into every object.
  4105. (throw :--found 'objects))
  4106. ((not (memq type org-element-greater-elements))
  4107. ;; If one regular element is found, the
  4108. ;; function has to recurse, at least, into
  4109. ;; every element it encounters.
  4110. (and (not (eq category 'elements))
  4111. (setq category 'elements))))))))
  4112. --acc)
  4113. (letrec ((--walk-tree
  4114. (lambda (--data)
  4115. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  4116. ;; holding contextual information.
  4117. (let ((--type (org-element-type --data)))
  4118. (cond
  4119. ((not --data))
  4120. ;; Ignored element in an export context.
  4121. ((and info (memq --data (plist-get info :ignore-list))))
  4122. ;; List of elements or objects.
  4123. ((not --type) (mapc --walk-tree --data))
  4124. ;; Unconditionally enter parse trees.
  4125. ((eq --type 'org-data)
  4126. (mapc --walk-tree (org-element-contents --data)))
  4127. (t
  4128. ;; Check if TYPE is matching among TYPES. If so,
  4129. ;; apply FUN to --DATA and accumulate return value
  4130. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  4131. (when (memq --type types)
  4132. (let ((result (funcall fun --data)))
  4133. (cond ((not result))
  4134. (first-match (throw :--map-first-match result))
  4135. (t (push result --acc)))))
  4136. ;; If --DATA has a secondary string that can contain
  4137. ;; objects with their type among TYPES, look inside.
  4138. (when (and (eq --category 'objects) (not (stringp --data)))
  4139. (dolist (p (cdr (assq --type
  4140. org-element-secondary-value-alist)))
  4141. (funcall --walk-tree (org-element-property p --data))))
  4142. ;; If --DATA has any parsed affiliated keywords and
  4143. ;; WITH-AFFILIATED is non-nil, look for objects in
  4144. ;; them.
  4145. (when (and with-affiliated
  4146. (eq --category 'objects)
  4147. (eq (org-element-class --data) 'element))
  4148. (dolist (kwd-pair org-element--parsed-properties-alist)
  4149. (let ((kwd (car kwd-pair))
  4150. (value (org-element-property (cdr kwd-pair) --data)))
  4151. ;; Pay attention to the type of parsed
  4152. ;; keyword. In particular, preserve order for
  4153. ;; multiple keywords.
  4154. (cond
  4155. ((not value))
  4156. ((member kwd org-element-dual-keywords)
  4157. (if (member kwd org-element-multiple-keywords)
  4158. (dolist (line (reverse value))
  4159. (funcall --walk-tree (cdr line))
  4160. (funcall --walk-tree (car line)))
  4161. (funcall --walk-tree (cdr value))
  4162. (funcall --walk-tree (car value))))
  4163. ((member kwd org-element-multiple-keywords)
  4164. (mapc --walk-tree (reverse value)))
  4165. (t (funcall --walk-tree value))))))
  4166. ;; Determine if a recursion into --DATA is possible.
  4167. (cond
  4168. ;; --TYPE is explicitly removed from recursion.
  4169. ((memq --type no-recursion))
  4170. ;; --DATA has no contents.
  4171. ((not (org-element-contents --data)))
  4172. ;; Looking for greater elements but --DATA is
  4173. ;; simply an element or an object.
  4174. ((and (eq --category 'greater-elements)
  4175. (not (memq --type org-element-greater-elements))))
  4176. ;; Looking for elements but --DATA is an object.
  4177. ((and (eq --category 'elements)
  4178. (eq (org-element-class --data) 'object)))
  4179. ;; In any other case, map contents.
  4180. (t (mapc --walk-tree (org-element-contents --data))))))))))
  4181. (catch :--map-first-match
  4182. (funcall --walk-tree data)
  4183. ;; Return value in a proper order.
  4184. (nreverse --acc)))))
  4185. ;; The following functions are internal parts of the parser.
  4186. ;;
  4187. ;; The first one, `org-element--parse-elements' acts at the element's
  4188. ;; level.
  4189. ;;
  4190. ;; The second one, `org-element--parse-objects' applies on all objects
  4191. ;; of a paragraph or a secondary string. It calls
  4192. ;; `org-element--object-lex' to find the next object in the current
  4193. ;; container.
  4194. (defsubst org-element--next-mode (mode type parent?)
  4195. "Return next mode according to current one.
  4196. MODE is a symbol representing the expectation about the next
  4197. element or object. Meaningful values are `first-section',
  4198. `item', `node-property', `planning', `property-drawer',
  4199. `section', `table-row', `top-comment', and nil.
  4200. TYPE is the type of the current element or object.
  4201. If PARENT? is non-nil, assume the next element or object will be
  4202. located inside the current one."
  4203. (if parent?
  4204. (pcase type
  4205. (`headline 'section)
  4206. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4207. ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
  4208. ((and (guard (not mode)) `org-data) 'first-section)
  4209. (`inlinetask 'planning)
  4210. (`plain-list 'item)
  4211. (`property-drawer 'node-property)
  4212. (`section 'planning)
  4213. (`table 'table-row))
  4214. (pcase mode
  4215. (`item 'item)
  4216. (`node-property 'node-property)
  4217. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4218. (`table-row 'table-row)
  4219. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4220. (defun org-element--parse-elements
  4221. (beg end mode structure granularity visible-only acc)
  4222. "Parse elements between BEG and END positions.
  4223. MODE prioritizes some elements over the others. It can be set to
  4224. `first-section', `item', `node-property', `planning',
  4225. `property-drawer', `section', `table-row', `top-comment', or nil.
  4226. When value is `item', STRUCTURE will be used as the current list
  4227. structure.
  4228. GRANULARITY determines the depth of the recursion. See
  4229. `org-element-parse-buffer' for more information.
  4230. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4231. elements.
  4232. Elements are accumulated into ACC."
  4233. (save-excursion
  4234. (goto-char beg)
  4235. ;; When parsing only headlines, skip any text before first one.
  4236. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4237. (org-with-limited-levels (outline-next-heading)))
  4238. (let (elements)
  4239. (while (< (point) end)
  4240. ;; Visible only: skip invisible parts due to folding.
  4241. (if (and visible-only (org-invisible-p nil t))
  4242. (progn
  4243. (goto-char (org-find-visible))
  4244. (when (and (eolp) (not (eobp))) (forward-char)))
  4245. ;; Find current element's type and parse it accordingly to
  4246. ;; its category.
  4247. (let* ((element (org-element-copy
  4248. ;; `org-element--current-element' may return cached
  4249. ;; elements. Below code reassigns
  4250. ;; `:parent' property of the element and
  4251. ;; may interfere with cache
  4252. ;; synchronisation if parent element is not
  4253. ;; yet in cache. Moreover, the returned
  4254. ;; structure may be altered by caller code
  4255. ;; arbitrarily. Hence, we return a copy of
  4256. ;; the potentially cached element to make
  4257. ;; potential modifications safe for element
  4258. ;; cache.
  4259. (org-element--current-element
  4260. end granularity mode structure)))
  4261. (type (org-element-type element))
  4262. (cbeg (org-element-property :contents-begin element)))
  4263. (goto-char (org-element-property :end element))
  4264. ;; Fill ELEMENT contents by side-effect.
  4265. (cond
  4266. ;; If element has no contents, don't modify it.
  4267. ((not cbeg))
  4268. ;; Greater element: parse it between `contents-begin' and
  4269. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4270. ;; or ELEMENT is a headline, in which case going inside
  4271. ;; is mandatory, in order to get sub-level headings.
  4272. ((and (memq type org-element-greater-elements)
  4273. (or (memq granularity '(element object nil))
  4274. (and (eq granularity 'greater-element)
  4275. (eq type 'section))
  4276. (eq type 'headline)))
  4277. (org-element--parse-elements
  4278. cbeg (org-element-property :contents-end element)
  4279. ;; Possibly switch to a special mode.
  4280. (org-element--next-mode mode type t)
  4281. (and (memq type '(item plain-list))
  4282. (org-element-property :structure element))
  4283. granularity visible-only element))
  4284. ;; ELEMENT has contents. Parse objects inside, if
  4285. ;; GRANULARITY allows it.
  4286. ((memq granularity '(object nil))
  4287. (org-element--parse-objects
  4288. cbeg (org-element-property :contents-end element) element
  4289. (org-element-restriction type))))
  4290. (push (org-element-put-property element :parent acc) elements)
  4291. ;; Update mode.
  4292. (setq mode (org-element--next-mode mode type nil)))))
  4293. ;; Return result.
  4294. (org-element-put-property acc :granularity granularity)
  4295. (apply #'org-element-set-contents acc (nreverse elements)))))
  4296. (defun org-element--object-lex (restriction)
  4297. "Return next object in current buffer or nil.
  4298. RESTRICTION is a list of object types, as symbols, that should be
  4299. looked after. This function assumes that the buffer is narrowed
  4300. to an appropriate container (e.g., a paragraph)."
  4301. (cond
  4302. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4303. ((memq 'citation-reference restriction)
  4304. (org-element-citation-reference-parser))
  4305. (t
  4306. (let* ((start (point))
  4307. (limit
  4308. ;; Object regexp sometimes needs to have a peek at
  4309. ;; a character ahead. Therefore, when there is a hard
  4310. ;; limit, make it one more than the true beginning of the
  4311. ;; radio target.
  4312. (save-excursion
  4313. (cond ((not org-target-link-regexp) nil)
  4314. ((not (memq 'link restriction)) nil)
  4315. ((progn
  4316. (unless (bolp) (forward-char -1))
  4317. (not (re-search-forward org-target-link-regexp nil t)))
  4318. nil)
  4319. ;; Since we moved backward, we do not want to
  4320. ;; match again an hypothetical 1-character long
  4321. ;; radio link before us. Realizing that this can
  4322. ;; only happen if such a radio link starts at
  4323. ;; beginning of line, we prevent this here.
  4324. ((and (= start (1+ (line-beginning-position)))
  4325. (= start (match-end 1)))
  4326. (and (re-search-forward org-target-link-regexp nil t)
  4327. (1+ (match-beginning 1))))
  4328. (t (1+ (match-beginning 1))))))
  4329. found)
  4330. (save-excursion
  4331. (while (and (not found)
  4332. (re-search-forward org-element--object-regexp limit 'move))
  4333. (goto-char (match-beginning 0))
  4334. (let ((result (match-string 0)))
  4335. (setq found
  4336. (cond
  4337. ((string-prefix-p "call_" result t)
  4338. (and (memq 'inline-babel-call restriction)
  4339. (org-element-inline-babel-call-parser)))
  4340. ((string-prefix-p "src_" result t)
  4341. (and (memq 'inline-src-block restriction)
  4342. (org-element-inline-src-block-parser)))
  4343. (t
  4344. (pcase (char-after)
  4345. (?^ (and (memq 'superscript restriction)
  4346. (org-element-superscript-parser)))
  4347. (?_ (or (and (memq 'subscript restriction)
  4348. (org-element-subscript-parser))
  4349. (and (memq 'underline restriction)
  4350. (org-element-underline-parser))))
  4351. (?* (and (memq 'bold restriction)
  4352. (org-element-bold-parser)))
  4353. (?/ (and (memq 'italic restriction)
  4354. (org-element-italic-parser)))
  4355. (?~ (and (memq 'code restriction)
  4356. (org-element-code-parser)))
  4357. (?= (and (memq 'verbatim restriction)
  4358. (org-element-verbatim-parser)))
  4359. (?+ (and (memq 'strike-through restriction)
  4360. (org-element-strike-through-parser)))
  4361. (?@ (and (memq 'export-snippet restriction)
  4362. (org-element-export-snippet-parser)))
  4363. (?{ (and (memq 'macro restriction)
  4364. (org-element-macro-parser)))
  4365. (?$ (and (memq 'latex-fragment restriction)
  4366. (org-element-latex-fragment-parser)))
  4367. (?<
  4368. (if (eq (aref result 1) ?<)
  4369. (or (and (memq 'radio-target restriction)
  4370. (org-element-radio-target-parser))
  4371. (and (memq 'target restriction)
  4372. (org-element-target-parser)))
  4373. (or (and (memq 'timestamp restriction)
  4374. (org-element-timestamp-parser))
  4375. (and (memq 'link restriction)
  4376. (org-element-link-parser)))))
  4377. (?\\
  4378. (if (eq (aref result 1) ?\\)
  4379. (and (memq 'line-break restriction)
  4380. (org-element-line-break-parser))
  4381. (or (and (memq 'entity restriction)
  4382. (org-element-entity-parser))
  4383. (and (memq 'latex-fragment restriction)
  4384. (org-element-latex-fragment-parser)))))
  4385. (?\[
  4386. (pcase (aref result 1)
  4387. ((and ?\[
  4388. (guard (memq 'link restriction)))
  4389. (org-element-link-parser))
  4390. ((and ?f
  4391. (guard (memq 'footnote-reference restriction)))
  4392. (org-element-footnote-reference-parser))
  4393. ((and ?c
  4394. (guard (memq 'citation restriction)))
  4395. (org-element-citation-parser))
  4396. ((and (or ?% ?/)
  4397. (guard (memq 'statistics-cookie restriction)))
  4398. (org-element-statistics-cookie-parser))
  4399. (_
  4400. (or (and (memq 'timestamp restriction)
  4401. (org-element-timestamp-parser))
  4402. (and (memq 'statistics-cookie restriction)
  4403. (org-element-statistics-cookie-parser))))))
  4404. ;; This is probably a plain link.
  4405. (_ (and (memq 'link restriction)
  4406. (org-element-link-parser)))))))
  4407. (or (eobp) (forward-char))))
  4408. (cond (found)
  4409. (limit (forward-char -1)
  4410. (org-element-link-parser)) ;radio link
  4411. (t nil)))))))
  4412. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4413. "Parse objects between BEG and END and return recursive structure.
  4414. Objects are accumulated in ACC. RESTRICTION is a list of object
  4415. successors which are allowed in the current object.
  4416. ACC becomes the parent for all parsed objects. However, if ACC
  4417. is nil (i.e., a secondary string is being parsed) and optional
  4418. argument PARENT is non-nil, use it as the parent for all objects.
  4419. Eventually, if both ACC and PARENT are nil, the common parent is
  4420. the list of objects itself."
  4421. (save-excursion
  4422. (save-restriction
  4423. (narrow-to-region beg end)
  4424. (goto-char (point-min))
  4425. (let (next-object contents)
  4426. (while (and (not (eobp))
  4427. (setq next-object (org-element--object-lex restriction)))
  4428. ;; Text before any object.
  4429. (let ((obj-beg (org-element-property :begin next-object)))
  4430. (unless (= (point) obj-beg)
  4431. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4432. (push (if acc (org-element-put-property text :parent acc) text)
  4433. contents))))
  4434. ;; Object...
  4435. (let ((obj-end (org-element-property :end next-object))
  4436. (cont-beg (org-element-property :contents-begin next-object)))
  4437. (when acc (org-element-put-property next-object :parent acc))
  4438. (push (if cont-beg
  4439. ;; Fill contents of NEXT-OBJECT if possible.
  4440. (org-element--parse-objects
  4441. cont-beg
  4442. (org-element-property :contents-end next-object)
  4443. next-object
  4444. (org-element-restriction next-object))
  4445. next-object)
  4446. contents)
  4447. (goto-char obj-end)))
  4448. ;; Text after last object.
  4449. (unless (eobp)
  4450. (let ((text (buffer-substring-no-properties (point) end)))
  4451. (push (if acc (org-element-put-property text :parent acc) text)
  4452. contents)))
  4453. ;; Result. Set appropriate parent.
  4454. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4455. (let* ((contents (nreverse contents))
  4456. (parent (or parent contents)))
  4457. (dolist (datum contents contents)
  4458. (org-element-put-property datum :parent parent))))))))
  4459. ;;; Towards A Bijective Process
  4460. ;;
  4461. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4462. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4463. ;; interpreted and expanded into a string with canonical Org syntax.
  4464. ;; Hence `org-element-interpret-data'.
  4465. ;;
  4466. ;; The function relies internally on
  4467. ;; `org-element--interpret-affiliated-keywords'.
  4468. ;;;###autoload
  4469. (defun org-element-interpret-data (data)
  4470. "Interpret DATA as Org syntax.
  4471. DATA is a parse tree, an element, an object or a secondary string
  4472. to interpret. Return Org syntax as a string."
  4473. (letrec ((fun
  4474. (lambda (data parent)
  4475. (let* ((type (org-element-type data))
  4476. ;; Find interpreter for current object or
  4477. ;; element. If it doesn't exist (e.g. this is
  4478. ;; a pseudo object or element), return contents,
  4479. ;; if any.
  4480. (interpret
  4481. (let ((fun (intern
  4482. (format "org-element-%s-interpreter" type))))
  4483. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4484. (results
  4485. (cond
  4486. ;; Secondary string.
  4487. ((not type)
  4488. (mapconcat (lambda (obj) (funcall fun obj parent))
  4489. data
  4490. ""))
  4491. ;; Full Org document.
  4492. ((eq type 'org-data)
  4493. (mapconcat (lambda (obj) (funcall fun obj parent))
  4494. (org-element-contents data)
  4495. ""))
  4496. ;; Plain text: return it.
  4497. ((stringp data) data)
  4498. ;; Element or object without contents.
  4499. ((not (org-element-contents data))
  4500. (funcall interpret data nil))
  4501. ;; Element or object with contents.
  4502. (t
  4503. (funcall
  4504. interpret
  4505. data
  4506. ;; Recursively interpret contents.
  4507. (mapconcat
  4508. (lambda (datum) (funcall fun datum data))
  4509. (org-element-contents
  4510. (if (not (memq type '(paragraph verse-block)))
  4511. data
  4512. ;; Fix indentation of elements containing
  4513. ;; objects. We ignore `table-row'
  4514. ;; elements as they are one line long
  4515. ;; anyway.
  4516. (org-element-normalize-contents
  4517. data
  4518. ;; When normalizing first paragraph of
  4519. ;; an item or a footnote-definition,
  4520. ;; ignore first line's indentation.
  4521. (and (eq type 'paragraph)
  4522. (memq (org-element-type parent)
  4523. '(footnote-definition item))
  4524. (eq data (car (org-element-contents parent)))
  4525. (eq (org-element-property :pre-blank parent)
  4526. 0)))))
  4527. ""))))))
  4528. (if (memq type '(org-data nil)) results
  4529. ;; Build white spaces. If no `:post-blank' property
  4530. ;; is specified, assume its value is 0.
  4531. (let ((blank (or (org-element-property :post-blank data) 0)))
  4532. (if (eq (org-element-class data parent) 'object)
  4533. (concat results (make-string blank ?\s))
  4534. (concat (org-element--interpret-affiliated-keywords data)
  4535. (org-element-normalize-string results)
  4536. (make-string blank ?\n)))))))))
  4537. (funcall fun data nil)))
  4538. (defun org-element--interpret-affiliated-keywords (element)
  4539. "Return ELEMENT's affiliated keywords as Org syntax.
  4540. If there is no affiliated keyword, return the empty string."
  4541. (let ((keyword-to-org
  4542. (lambda (key value)
  4543. (let (dual)
  4544. (when (member key org-element-dual-keywords)
  4545. (setq dual (cdr value) value (car value)))
  4546. (concat "#+" (downcase key)
  4547. (and dual
  4548. (format "[%s]" (org-element-interpret-data dual)))
  4549. ": "
  4550. (if (member key org-element-parsed-keywords)
  4551. (org-element-interpret-data value)
  4552. value)
  4553. "\n")))))
  4554. (mapconcat
  4555. (lambda (prop)
  4556. (let ((value (org-element-property prop element))
  4557. (keyword (upcase (substring (symbol-name prop) 1))))
  4558. (when value
  4559. (if (or (member keyword org-element-multiple-keywords)
  4560. ;; All attribute keywords can have multiple lines.
  4561. (string-match "^ATTR_" keyword))
  4562. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4563. (reverse value)
  4564. "")
  4565. (funcall keyword-to-org keyword value)))))
  4566. ;; List all ELEMENT's properties matching an attribute line or an
  4567. ;; affiliated keyword, but ignore translated keywords since they
  4568. ;; cannot belong to the property list.
  4569. (cl-loop for prop in (nth 1 element) by 'cddr
  4570. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4571. (or (string-match "^ATTR_" keyword)
  4572. (and
  4573. (member keyword org-element-affiliated-keywords)
  4574. (not (assoc keyword
  4575. org-element-keyword-translation-alist)))))
  4576. collect prop)
  4577. "")))
  4578. ;; Because interpretation of the parse tree must return the same
  4579. ;; number of blank lines between elements and the same number of white
  4580. ;; space after objects, some special care must be given to white
  4581. ;; spaces.
  4582. ;;
  4583. ;; The first function, `org-element-normalize-string', ensures any
  4584. ;; string different from the empty string will end with a single
  4585. ;; newline character.
  4586. ;;
  4587. ;; The second function, `org-element-normalize-contents', removes
  4588. ;; global indentation from the contents of the current element.
  4589. (defun org-element-normalize-string (s)
  4590. "Ensure string S ends with a single newline character.
  4591. If S isn't a string return it unchanged. If S is the empty
  4592. string, return it. Otherwise, return a new string with a single
  4593. newline character at its end."
  4594. (cond
  4595. ((not (stringp s)) s)
  4596. ((string= "" s) "")
  4597. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4598. (replace-match "\n" nil nil s)))))
  4599. (defun org-element-normalize-contents (element &optional ignore-first)
  4600. "Normalize plain text in ELEMENT's contents.
  4601. ELEMENT must only contain plain text and objects.
  4602. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4603. indentation to compute maximal common indentation.
  4604. Return the normalized element that is element with global
  4605. indentation removed from its contents."
  4606. (letrec ((find-min-ind
  4607. ;; Return minimal common indentation within BLOB. This is
  4608. ;; done by walking recursively BLOB and updating MIN-IND
  4609. ;; along the way. FIRST-FLAG is non-nil when the next
  4610. ;; object is expected to be a string that doesn't start
  4611. ;; with a newline character. It happens for strings at
  4612. ;; the beginnings of the contents or right after a line
  4613. ;; break.
  4614. (lambda (blob first-flag min-ind)
  4615. (dolist (datum (org-element-contents blob) min-ind)
  4616. (when first-flag
  4617. (setq first-flag nil)
  4618. (cond
  4619. ;; Objects cannot start with spaces: in this
  4620. ;; case, indentation is 0.
  4621. ((not (stringp datum)) (throw :zero 0))
  4622. ((not (string-match
  4623. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4624. (throw :zero 0))
  4625. ((equal (match-string 2 datum) "\n")
  4626. (put-text-property
  4627. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4628. (t
  4629. (let ((i (string-width (match-string 1 datum))))
  4630. (put-text-property
  4631. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4632. (setq min-ind (min i min-ind))))))
  4633. (cond
  4634. ((stringp datum)
  4635. (let ((s 0))
  4636. (while (string-match
  4637. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4638. (setq s (match-end 1))
  4639. (cond
  4640. ((equal (match-string 1 datum) "")
  4641. (unless (member (match-string 2 datum) '("" "\n"))
  4642. (throw :zero 0)))
  4643. ((equal (match-string 2 datum) "\n")
  4644. (put-text-property (match-beginning 1) (match-end 1)
  4645. 'org-ind 'empty datum))
  4646. (t
  4647. (let ((i (string-width (match-string 1 datum))))
  4648. (put-text-property (match-beginning 1) (match-end 1)
  4649. 'org-ind i datum)
  4650. (setq min-ind (min i min-ind))))))))
  4651. ((eq (org-element-type datum) 'line-break)
  4652. (setq first-flag t))
  4653. ((memq (org-element-type datum) org-element-recursive-objects)
  4654. (setq min-ind
  4655. (funcall find-min-ind datum first-flag min-ind)))))))
  4656. (min-ind
  4657. (catch :zero
  4658. (funcall find-min-ind
  4659. element (not ignore-first) most-positive-fixnum))))
  4660. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4661. ;; Build ELEMENT back, replacing each string with the same
  4662. ;; string minus common indentation.
  4663. (letrec ((build
  4664. (lambda (datum)
  4665. ;; Return DATUM with all its strings indentation
  4666. ;; shortened from MIN-IND white spaces.
  4667. (setcdr
  4668. (cdr datum)
  4669. (mapcar
  4670. (lambda (object)
  4671. (cond
  4672. ((stringp object)
  4673. (with-temp-buffer
  4674. (insert object)
  4675. (let ((s (point-min)))
  4676. (while (setq s (text-property-not-all
  4677. s (point-max) 'org-ind nil))
  4678. (goto-char s)
  4679. (let ((i (get-text-property s 'org-ind)))
  4680. (delete-region s (progn
  4681. (skip-chars-forward " \t")
  4682. (point)))
  4683. (when (integerp i) (indent-to (- i min-ind))))))
  4684. (buffer-string)))
  4685. ((memq (org-element-type object)
  4686. org-element-recursive-objects)
  4687. (funcall build object))
  4688. (t object)))
  4689. (org-element-contents datum)))
  4690. datum)))
  4691. (funcall build element)))))
  4692. ;;; Cache
  4693. ;;
  4694. ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
  4695. ;; fast mapping across Org elements in `org-element-cache-map', which see.
  4696. ;;
  4697. ;; When cache is enabled, the elements returned by `org-element-at-point' and
  4698. ;; `org-element-context' are returned by reference. Altering these elements will
  4699. ;; also alter their cache representation. The same is true for
  4700. ;; elements passed to mapping function in `org-element-cache-map'.
  4701. ;;
  4702. ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
  4703. ;; `org-element-cache-map'.
  4704. ;;
  4705. ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
  4706. ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
  4707. ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
  4708. ;;
  4709. ;; Internally, parsed elements are stored in an AVL tree,
  4710. ;; `org-element--cache'. This tree is updated lazily: whenever
  4711. ;; a change happens to the buffer, a synchronization request is
  4712. ;; registered in `org-element--cache-sync-requests' (see
  4713. ;; `org-element--cache-submit-request'). During idle time, requests
  4714. ;; are processed by `org-element--cache-sync'. Synchronization also
  4715. ;; happens when an element is required from the cache. In this case,
  4716. ;; the process stops as soon as the needed element is up-to-date.
  4717. ;;
  4718. ;; A synchronization request can only apply on a synchronized part of
  4719. ;; the cache. Therefore, the cache is updated at least to the
  4720. ;; location where the new request applies. Thus, requests are ordered
  4721. ;; from left to right and all elements starting before the first
  4722. ;; request are correct. This property is used by functions like
  4723. ;; `org-element--cache-find' to retrieve elements in the part of the
  4724. ;; cache that can be trusted.
  4725. ;;
  4726. ;; A request applies to every element, starting from its original
  4727. ;; location (or key, see below). When a request is processed, it
  4728. ;; moves forward and may collide the next one. In this case, both
  4729. ;; requests are merged into a new one that starts from that element.
  4730. ;; As a consequence, the whole synchronization complexity does not
  4731. ;; depend on the number of pending requests, but on the number of
  4732. ;; elements the very first request will be applied on.
  4733. ;;
  4734. ;; Elements cannot be accessed through their beginning position, which
  4735. ;; may or may not be up-to-date. Instead, each element in the tree is
  4736. ;; associated to a key, obtained with `org-element--cache-key'. This
  4737. ;; mechanism is robust enough to preserve total order among elements
  4738. ;; even when the tree is only partially synchronized.
  4739. ;;
  4740. ;; The cache code debuggin is fairly complex because cache request
  4741. ;; state is often hard to reproduce. An extensive diagnostics
  4742. ;; functionality is built into the cache code to assist hunting bugs.
  4743. ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
  4744. ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
  4745. ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
  4746. ;; `org-element--cache-map-statistics-threshold'.
  4747. (defvar org-element-use-cache t
  4748. "Non-nil when Org parser should cache its results.")
  4749. (defvar org-element-cache-persistent t
  4750. "Non-nil when cache should persist between Emacs sessions.")
  4751. (defvar org-element-cache-sync-idle-time 0.6
  4752. "Length, in seconds, of idle time before syncing cache.")
  4753. (defvar org-element-cache-sync-duration 0.04
  4754. "Maximum duration, as a time value, for a cache synchronization.
  4755. If the synchronization is not over after this delay, the process
  4756. pauses and resumes after `org-element-cache-sync-break'
  4757. seconds.")
  4758. (defvar org-element-cache-sync-break 0.3
  4759. "Duration, as a time value, of the pause between synchronizations.
  4760. See `org-element-cache-sync-duration' for more information.")
  4761. (defvar org-element--cache-self-verify t
  4762. "Activate extra consistency checks for the cache.
  4763. This may cause serious performance degradation depending on the value
  4764. of `org-element--cache-self-verify-frequency'.
  4765. When set to symbol `backtrace', record and display backtrace log if
  4766. any inconsistency is detected.")
  4767. (defvar org-element--cache-self-verify-frequency 0.03
  4768. "Frequency of cache element verification.
  4769. This number is a probability to check an element requested from cache
  4770. to be correct. Setting this to a value less than 0.0001 is useless.")
  4771. (defvar org-element--cache-diagnostics nil
  4772. "Print detailed diagnostics of cache processing.")
  4773. (defvar org-element--cache-map-statistics nil
  4774. "Print statistics for `org-element-cache-map'.")
  4775. (defvar org-element--cache-map-statistics-threshold 0.1
  4776. "Time threshold in seconds to log statistics for `org-element-cache-map'.")
  4777. (defvar org-element--cache-diagnostics-modifications t
  4778. "Non-nil enables cache warnings when for silent modifications.
  4779. Silent modifications are the modifications in Org buffers that are not
  4780. registered by `org-element--cache-before-change' and
  4781. `org-element--cache-after-change'.
  4782. This variable may cause false-positives because some Emacs versions
  4783. can change `buffer-chars-modified-tick' internally even though no
  4784. visible changes in buffer are being made. Some of such expected cases
  4785. are covered by heuristics, but not all.")
  4786. (defvar org-element--cache-silent-modification-check t
  4787. "Detect changes in buffer made inside `with-silent-modifications'.
  4788. Note that some internal Emacs functions may also trigger a warning and
  4789. cache reset. The warning can be suppressed by setting
  4790. `org-element--cache-diagnostics-modifications' to nil, but the cache
  4791. will still be refreshed to be safe.
  4792. WARNING: Setting this variable to nil may cause cache corruption is some
  4793. third-party packages make undetected changes in buffers.")
  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. (defvar-local org-element--cache-size 0
  4813. "Size of the `org-element--cache'.
  4814. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4815. (defvar-local org-element--headline-cache-size 0
  4816. "Size of the `org-element--headline-cache'.
  4817. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4818. (defvar-local org-element--cache-sync-requests nil
  4819. "List of pending synchronization requests.
  4820. A request is a vector with the following pattern:
  4821. [NEXT BEG END OFFSET PARENT PHASE]
  4822. Processing a synchronization request consists of three phases:
  4823. 0. Delete modified elements,
  4824. 1. Fill missing area in cache,
  4825. 2. Shift positions and re-parent elements after the changes.
  4826. During phase 0, NEXT is the key of the first element to be
  4827. removed, BEG and END is buffer position delimiting the
  4828. modifications. Elements starting between them (inclusive) are
  4829. removed. So are elements whose parent is removed. PARENT, when
  4830. non-nil, is the common parent of all the elements between BEG and END.
  4831. It is guaranteed that only a single phase 0 request exists at any
  4832. moment of time. If it does, it must be the first request in the list.
  4833. During phase 1, NEXT is the key of the next known element in
  4834. cache and BEG its beginning position. Parse buffer between that
  4835. element and the one before it in order to determine the parent of
  4836. the next element. Set PARENT to the element containing NEXT.
  4837. During phase 2, NEXT is the key of the next element to shift in
  4838. the parse tree. All elements starting from this one have their
  4839. properties relative to buffer positions shifted by integer
  4840. OFFSET and, if they belong to element PARENT, are adopted by it.
  4841. PHASE specifies the phase number, as an integer.
  4842. For any synchronisation request, all the later requests in the cache
  4843. must not start at or before END. See `org-element--cache-submit-request'.")
  4844. (defvar-local org-element--cache-sync-timer nil
  4845. "Timer used for cache synchronization.")
  4846. (defvar-local org-element--cache-sync-keys-value nil
  4847. "Id value used to identify keys during synchronisation.
  4848. See `org-element--cache-key' for more information.")
  4849. (defvar-local org-element--cache-change-tic nil
  4850. "Last `buffer-chars-modified-tick' for registered changes.")
  4851. (defvar org-element--cache-non-modifying-commands '(org-agenda
  4852. org-agenda-redo
  4853. org-sparse-tree
  4854. org-occur
  4855. org-columns
  4856. org-columns-redo
  4857. org-columns-new
  4858. org-columns-delete
  4859. org-columns-compute
  4860. org-columns-insert-dblock
  4861. org-agenda-columns
  4862. org-ctrl-c-ctrl-c)
  4863. "List of commands that are not expected to change the cache state.
  4864. This variable is used to determine when re-parsing buffer is not going
  4865. to slow down the command.
  4866. If the commends end up modifying the cache, the worst case scenario is
  4867. performance drop. So, advicing these commands is safe. Yet, it is
  4868. better to remove the commands adviced in such way from this list.")
  4869. (defmacro org-element--request-key (request)
  4870. "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
  4871. `(aref ,request 0))
  4872. (defmacro org-element--request-beg (request)
  4873. "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
  4874. `(aref ,request 1))
  4875. (defmacro org-element--request-end (request)
  4876. "Get END part of a `org-element--cache-sync-requests' REQUEST."
  4877. `(aref ,request 2))
  4878. (defmacro org-element--request-offset (request)
  4879. "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
  4880. `(aref ,request 3))
  4881. (defmacro org-element--request-parent (request)
  4882. "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
  4883. `(aref ,request 4))
  4884. (defmacro org-element--request-phase (request)
  4885. "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
  4886. `(aref ,request 5))
  4887. (defmacro org-element--format-element (element)
  4888. "Format ELEMENT for printing in diagnostics."
  4889. `(let ((print-length 50)
  4890. (print-level 5))
  4891. (prin1-to-string ,element)))
  4892. (defmacro org-element--cache-log-message (format-string &rest args)
  4893. "Add a new log message for org-element-cache."
  4894. `(when (or org-element--cache-diagnostics
  4895. (eq org-element--cache-self-verify 'backtrace))
  4896. (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
  4897. (buffer-name (current-buffer)))
  4898. ,format-string))
  4899. (format-string (funcall #'format format-string ,@args)))
  4900. (if org-element--cache-diagnostics
  4901. (display-warning 'org-element-cache format-string)
  4902. (unless org-element--cache-diagnostics-ring
  4903. (setq org-element--cache-diagnostics-ring
  4904. (make-ring org-element--cache-diagnostics-ring-size)))
  4905. (ring-insert org-element--cache-diagnostics-ring format-string)))))
  4906. (defmacro org-element--cache-warn (format-string &rest args)
  4907. "Raise warning for org-element-cache."
  4908. `(let* ((format-string (funcall #'format ,format-string ,@args))
  4909. (format-string
  4910. (if (or (not org-element--cache-diagnostics-ring)
  4911. (not (eq 'backtrace org-element--cache-self-verify)))
  4912. format-string
  4913. (prog1
  4914. (concat (format "Warning(%s): "
  4915. (buffer-name (current-buffer)))
  4916. format-string
  4917. "\nBacktrace:\n "
  4918. (mapconcat #'identity
  4919. (ring-elements org-element--cache-diagnostics-ring)
  4920. "\n "))
  4921. (setq org-element--cache-diagnostics-ring nil)))))
  4922. (if (and (boundp 'org-batch-test) org-batch-test)
  4923. (error "%s" (concat "org-element--cache: " format-string))
  4924. (display-warning 'org-element-cache
  4925. (concat "org-element--cache: " format-string)))))
  4926. (defsubst org-element--cache-key (element)
  4927. "Return a unique key for ELEMENT in cache tree.
  4928. Keys are used to keep a total order among elements in the cache.
  4929. Comparison is done with `org-element--cache-key-less-p'.
  4930. When no synchronization is taking place, a key is simply the
  4931. beginning position of the element, or that position plus one in
  4932. the case of an first item (respectively row) in
  4933. a list (respectively a table). They key of a section is its beginning
  4934. position minus one.
  4935. During a synchronization, the key is the one the element had when
  4936. the cache was synchronized for the last time. Elements added to
  4937. cache during the synchronization get a new key generated with
  4938. `org-element--cache-generate-key'.
  4939. Such keys are stored inside the element property
  4940. `:org-element--cache-sync-key'. The property is a cons containing
  4941. current `org-element--cache-sync-keys-value' and the element key."
  4942. (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
  4943. (cdr (org-element-property :org-element--cache-sync-key element)))
  4944. (let* ((begin (org-element-property :begin element))
  4945. ;; Increase beginning position of items (respectively
  4946. ;; table rows) by one, so the first item can get
  4947. ;; a different key from its parent list (respectively
  4948. ;; table).
  4949. (key (if (memq (org-element-type element) '(item table-row))
  4950. (1+ begin)
  4951. ;; Decrease beginning position of sections by one,
  4952. ;; so that the first element of the section get
  4953. ;; different key from the parent section.
  4954. (if (eq (org-element-type element) 'section)
  4955. (1- begin)
  4956. (if (eq (org-element-type element) 'org-data)
  4957. (- begin 2)
  4958. begin)))))
  4959. (when org-element--cache-sync-requests
  4960. (org-element-put-property element
  4961. :org-element--cache-sync-key
  4962. (cons org-element--cache-sync-keys-value key)))
  4963. key)))
  4964. (defun org-element--cache-generate-key (lower upper)
  4965. "Generate a key between LOWER and UPPER.
  4966. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4967. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4968. a unique key, as an integer or a list of integers, according to
  4969. the following rules:
  4970. - LOWER and UPPER are compared level-wise until values differ.
  4971. - If, at a given level, LOWER and UPPER differ from more than
  4972. 2, the new key shares all the levels above with LOWER and
  4973. gets a new level. Its value is the mean between LOWER and
  4974. UPPER:
  4975. (1 2) + (1 4) --> (1 3)
  4976. - If LOWER has no value to compare with, it is assumed that its
  4977. value is `most-negative-fixnum'. E.g.,
  4978. (1 1) + (1 1 2)
  4979. is equivalent to
  4980. (1 1 m) + (1 1 2)
  4981. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4982. short of levels, the current value is `most-positive-fixnum'.
  4983. - If they differ from only one, the new key inherits from
  4984. current LOWER level and fork it at the next level. E.g.,
  4985. (2 1) + (3 3)
  4986. is equivalent to
  4987. (2 1) + (2 M)
  4988. where M is `most-positive-fixnum'.
  4989. - If the key is only one level long, it is returned as an
  4990. integer:
  4991. (1 2) + (3 2) --> 2
  4992. When they are not equals, the function assumes that LOWER is
  4993. lesser than UPPER, per `org-element--cache-key-less-p'."
  4994. (if (equal lower upper) lower
  4995. (let ((lower (if (integerp lower) (list lower) lower))
  4996. (upper (if (integerp upper) (list upper) upper))
  4997. skip-upper key)
  4998. (catch 'exit
  4999. (while t
  5000. (let ((min (or (car lower) most-negative-fixnum))
  5001. (max (cond (skip-upper most-positive-fixnum)
  5002. ((car upper))
  5003. (t most-positive-fixnum))))
  5004. (if (< (1+ min) max)
  5005. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  5006. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  5007. (when (and (< min max) (not skip-upper))
  5008. ;; When at a given level, LOWER and UPPER differ from
  5009. ;; 1, ignore UPPER altogether. Instead create a key
  5010. ;; between LOWER and the greatest key with the same
  5011. ;; prefix as LOWER so far.
  5012. (setq skip-upper t))
  5013. (push min key)
  5014. (setq lower (cdr lower) upper (cdr upper)))))))))
  5015. (defsubst org-element--cache-key-less-p (a b)
  5016. "Non-nil if key A is less than key B.
  5017. A and B are either integers or lists of integers, as returned by
  5018. `org-element--cache-key'."
  5019. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  5020. (if (integerp b) (< (car a) b)
  5021. (catch 'exit
  5022. (while (and a b)
  5023. (cond ((car-less-than-car a b) (throw 'exit t))
  5024. ((car-less-than-car b a) (throw 'exit nil))
  5025. (t (setq a (cdr a) b (cdr b)))))
  5026. ;; If A is empty, either keys are equal (B is also empty) and
  5027. ;; we return nil, or A is lesser than B (B is longer) and we
  5028. ;; return a non-nil value.
  5029. ;;
  5030. ;; If A is not empty, B is necessarily empty and A is greater
  5031. ;; than B (A is longer). Therefore, return nil.
  5032. (and (null a) b)))))
  5033. (defun org-element--cache-compare (a b)
  5034. "Non-nil when element A is located before element B."
  5035. (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
  5036. (defsubst org-element--cache-root ()
  5037. "Return root value in `org-element--cache' .
  5038. This function assumes `org-element--cache' is a valid AVL tree."
  5039. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  5040. (defsubst org-element--headline-cache-root ()
  5041. "Return root value in `org-element--headline-cache' .
  5042. This function assumes `org-element--headline-cache' is a valid AVL tree."
  5043. (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
  5044. ;;;; Tools
  5045. (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
  5046. "Non-nil when cache is active in current buffer."
  5047. (and org-element-use-cache
  5048. org-element--cache
  5049. (derived-mode-p 'org-mode)
  5050. (or called-from-cache-change-func-p
  5051. (and
  5052. ;; org-num-mode calls some Org structure analysis functions
  5053. ;; that can trigger cache update in the middle of changes. See
  5054. ;; `org-num--verify' calling `org-num--skip-value' calling
  5055. ;; `org-entry-get' that uses cache.
  5056. ;; Forcefully disable cache when called from inside a
  5057. ;; modification hook, where `inhibit-modification-hooks' is set
  5058. ;; to t.
  5059. (not inhibit-modification-hooks)
  5060. ;; `combine-change-calls' sets `after-change-functions' to
  5061. ;; nil. We need not to use cache inside
  5062. ;; `combine-change-calls' because the buffer is potentially
  5063. ;; changed without notice (the change will be registered
  5064. ;; after exiting the `combine-change-calls' body though).
  5065. (memq #'org-element--cache-after-change after-change-functions))
  5066. (eq org-element--cache-change-tic (buffer-chars-modified-tick)))))
  5067. (defun org-element--cache-find (pos &optional side)
  5068. "Find element in cache starting at POS or before.
  5069. POS refers to a buffer position.
  5070. When optional argument SIDE is non-nil, the function checks for
  5071. elements starting at or past POS instead. If SIDE is `both', the
  5072. function returns a cons cell where car is the first element
  5073. starting at or before POS and cdr the first element starting
  5074. after POS.
  5075. The function can only find elements in the synchronized part of
  5076. the cache."
  5077. (with-current-buffer (or (buffer-base-buffer) (current-buffer))
  5078. (let ((limit (and org-element--cache-sync-requests
  5079. (org-element--request-key (car org-element--cache-sync-requests))))
  5080. (node (org-element--cache-root))
  5081. lower upper)
  5082. (while node
  5083. (let* ((element (avl-tree--node-data node))
  5084. (begin (org-element-property :begin element)))
  5085. (cond
  5086. ((and limit
  5087. (not (org-element--cache-key-less-p
  5088. (org-element--cache-key element) limit)))
  5089. (setq node (avl-tree--node-left node)))
  5090. ((> begin pos)
  5091. (setq upper element
  5092. node (avl-tree--node-left node)))
  5093. ((or (< begin pos)
  5094. ;; If the element is section or org-data, we also need
  5095. ;; to check the following element.
  5096. (memq (org-element-type element) '(section org-data)))
  5097. (setq lower element
  5098. node (avl-tree--node-right node)))
  5099. ;; We found an element in cache starting at POS. If `side'
  5100. ;; is `both' we also want the next one in order to generate
  5101. ;; a key in-between.
  5102. ;;
  5103. ;; If the element is the first row or item in a table or
  5104. ;; a plain list, we always return the table or the plain
  5105. ;; list.
  5106. ;;
  5107. ;; In any other case, we return the element found.
  5108. ((eq side 'both)
  5109. (setq lower element)
  5110. (setq node (avl-tree--node-right node)))
  5111. ((and (memq (org-element-type element) '(item table-row))
  5112. (let ((parent (org-element-property :parent element)))
  5113. (and (= (org-element-property :begin element)
  5114. (org-element-property :contents-begin parent))
  5115. (setq node nil
  5116. lower parent
  5117. upper parent)))))
  5118. (t
  5119. (setq node nil
  5120. lower element
  5121. upper element)))))
  5122. (pcase side
  5123. (`both (cons lower upper))
  5124. (`nil lower)
  5125. (_ upper)))))
  5126. (defun org-element--cache-put (element)
  5127. "Store ELEMENT in current buffer's cache, if allowed."
  5128. (when (org-element--cache-active-p)
  5129. (when org-element--cache-sync-requests
  5130. ;; During synchronization, first build an appropriate key for
  5131. ;; the new element so `avl-tree-enter' can insert it at the
  5132. ;; right spot in the cache.
  5133. (let* ((keys (org-element--cache-find
  5134. (org-element-property :begin element) 'both))
  5135. (new-key (org-element--cache-generate-key
  5136. (and (car keys) (org-element--cache-key (car keys)))
  5137. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  5138. (org-element--cache-sync-requests
  5139. (org-element--request-key (car org-element--cache-sync-requests)))))))
  5140. (org-element-put-property element
  5141. :org-element--cache-sync-key
  5142. (cons org-element--cache-sync-keys-value new-key))))
  5143. (when (>= org-element--cache-diagnostics-level 2)
  5144. (org-element--cache-log-message "Added new element with %S key: %S"
  5145. (org-element-property :org-element--cache-sync-key element)
  5146. (org-element--format-element element)))
  5147. (org-element-put-property element :cached t)
  5148. (when (memq (org-element-type element) '(headline inlinetask))
  5149. (cl-incf org-element--headline-cache-size)
  5150. (avl-tree-enter org-element--headline-cache element))
  5151. (cl-incf org-element--cache-size)
  5152. (avl-tree-enter org-element--cache element)))
  5153. (defsubst org-element--cache-remove (element)
  5154. "Remove ELEMENT from cache.
  5155. Assume ELEMENT belongs to cache and that a cache is active."
  5156. (org-element-put-property element :cached nil)
  5157. (cl-decf org-element--cache-size)
  5158. ;; Invalidate contents of parent.
  5159. (when (and (org-element-property :parent element)
  5160. (org-element-contents (org-element-property :parent element)))
  5161. (org-element-set-contents (org-element-property :parent element) nil))
  5162. (when (memq (org-element-type element) '(headline inlinetask))
  5163. (cl-decf org-element--headline-cache-size)
  5164. (avl-tree-delete org-element--headline-cache element))
  5165. (or (avl-tree-delete org-element--cache element)
  5166. (progn
  5167. ;; This should not happen, but if it is, would be better to know
  5168. ;; where it happens.
  5169. (org-element--cache-warn "Failed to delete %S element in %S at %S. The element cache key was %S.
  5170. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5171. (org-element-type element)
  5172. (current-buffer)
  5173. (org-element-property :begin element)
  5174. (org-element-property :org-element--cache-sync-key element))
  5175. (org-element-cache-reset)
  5176. (throw 'quit nil))))
  5177. ;;;; Synchronization
  5178. (defsubst org-element--cache-set-timer (buffer)
  5179. "Set idle timer for cache synchronization in BUFFER."
  5180. (when org-element--cache-sync-timer
  5181. (cancel-timer org-element--cache-sync-timer))
  5182. (setq org-element--cache-sync-timer
  5183. (run-with-idle-timer
  5184. (let ((idle (current-idle-time)))
  5185. (if idle (time-add idle org-element-cache-sync-break)
  5186. org-element-cache-sync-idle-time))
  5187. nil
  5188. #'org-element--cache-sync
  5189. buffer)))
  5190. (defsubst org-element--cache-interrupt-p (time-limit)
  5191. "Non-nil when synchronization process should be interrupted.
  5192. TIME-LIMIT is a time value or nil."
  5193. (and time-limit
  5194. (or (input-pending-p)
  5195. (time-less-p time-limit nil))))
  5196. (defsubst org-element--cache-shift-positions (element offset &optional props)
  5197. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  5198. Properties containing buffer positions are `:begin', `:end',
  5199. `:contents-begin', `:contents-end' and `:structure'. When
  5200. optional argument PROPS is a list of keywords, only shift
  5201. properties provided in that list.
  5202. Properties are modified by side-effect."
  5203. (let ((properties (nth 1 element)))
  5204. ;; Shift `:structure' property for the first plain list only: it
  5205. ;; is the only one that really matters and it prevents from
  5206. ;; shifting it more than once.
  5207. (when (and (or (not props) (memq :structure props))
  5208. (eq (org-element-type element) 'plain-list)
  5209. (not (eq (org-element-type (plist-get properties :parent)) 'item)))
  5210. (dolist (item (plist-get properties :structure))
  5211. (cl-incf (car item) offset)
  5212. (cl-incf (nth 6 item) offset)))
  5213. (dolist (key '( :begin :contents-begin :contents-end :end
  5214. :post-affiliated :robust-begin :robust-end))
  5215. (let ((value (and (or (not props) (memq key props))
  5216. (plist-get properties key))))
  5217. (and value (plist-put properties key (+ offset value)))))))
  5218. (defvar org-element--cache-interrupt-C-g t
  5219. "When non-nil, allow the user to abort `org-element--cache-sync'.
  5220. The execution is aborted upon pressing `\\[keyboard-quit]'
  5221. `org-element--cache-interrupt-C-g-max-count' times.")
  5222. (defvar org-element--cache-interrupt-C-g-max-count 5
  5223. "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
  5224. See `org-element--cache-interrupt-C-g'.")
  5225. (defvar org-element--cache-interrupt-C-g-count 0
  5226. "Current number of `org-element--cache-sync' calls.
  5227. See `org-element--cache-interrupt-C-g'.")
  5228. (defvar org-element--cache-change-warning nil
  5229. "Non-nil when a sensitive line is about to be changed.
  5230. It is a symbol among nil, t, or a number representing smallest level of
  5231. modified headline. The level considers headline levels both before
  5232. and after the modification.")
  5233. (defun org-element--cache-sync (buffer &optional threshold future-change offset)
  5234. "Synchronize cache with recent modification in BUFFER.
  5235. When optional argument THRESHOLD is non-nil, do the
  5236. synchronization for all elements starting before or at threshold,
  5237. then exit. Otherwise, synchronize cache for as long as
  5238. `org-element-cache-sync-duration' or until Emacs leaves idle
  5239. state.
  5240. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  5241. not registered yet in the cache are going to happen. OFFSET is the
  5242. change offset. It is used in `org-element--cache-submit-request',
  5243. where cache is partially updated before current modification are
  5244. actually submitted."
  5245. (when (buffer-live-p buffer)
  5246. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  5247. ;; Check if the buffer have been changed outside visibility of
  5248. ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
  5249. (if (and (/= org-element--cache-change-tic
  5250. (buffer-chars-modified-tick))
  5251. org-element--cache-silent-modification-check
  5252. ;; FIXME: Below is a heuristics noticed by observation.
  5253. ;; quail.el with non-latin input does silent
  5254. ;; modifications in buffer increasing the tick counter
  5255. ;; but not actually changing the buffer text:
  5256. ;; https://list.orgmode.org/87sfw2luhj.fsf@localhost/T/#you
  5257. ;; https://lists.gnu.org/archive/html/bug-gnu-emacs/2021-11/msg00894.html
  5258. ;; However, the values of `buffer-chars-modified-tick'
  5259. ;; and `buffer-modified-tick' appear to be same after
  5260. ;; the quail.el's changes in buffer. We do not
  5261. ;; consider these exact changes as a dangerous silent
  5262. ;; edit.
  5263. (/= (buffer-chars-modified-tick)
  5264. (buffer-modified-tick)))
  5265. (progn
  5266. (when (or (and org-element--cache-diagnostics-modifications
  5267. ;; A number of Emacs internal operations in
  5268. ;; Emacs 26 and 27 alter
  5269. ;; `buffer-chars-modified-tick' (see
  5270. ;; https://list.orgmode.org/87ee7jdv70.fsf@localhost/T/#t
  5271. ;; https://list.orgmode.org/2022-01-06T12-13-17@devnull.Karl-Voit.at/T/#mb3771758f81b31721ba2f420878a4d16081dc483).
  5272. ;; We have no way to distinguish them from
  5273. ;; dangerious silent edits. So, we can
  5274. ;; only reset the cache, but do not show
  5275. ;; warning to not irritate the users.)
  5276. (not (version< emacs-version "28")))
  5277. (and (boundp 'org-batch-test) org-batch-test))
  5278. (org-element--cache-warn "Unregistered buffer modifications detected. Resetting.
  5279. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  5280. The buffer is: %s\n Current command: %S\n Chars modified: %S\n Buffer modified: %S\n Backtrace:\n%S"
  5281. (buffer-name (current-buffer))
  5282. (list this-command (buffer-chars-modified-tick) (buffer-modified-tick))
  5283. (buffer-chars-modified-tick)
  5284. (buffer-modified-tick)
  5285. (when (and (fboundp 'backtrace-get-frames)
  5286. (fboundp 'backtrace-to-string))
  5287. (backtrace-to-string (backtrace-get-frames 'backtrace)))))
  5288. (org-element-cache-reset))
  5289. (let ((inhibit-quit t) request next)
  5290. (setq org-element--cache-interrupt-C-g-count 0)
  5291. (when org-element--cache-sync-timer
  5292. (cancel-timer org-element--cache-sync-timer))
  5293. (let ((time-limit (time-add nil org-element-cache-sync-duration)))
  5294. (catch 'org-element--cache-interrupt
  5295. (when org-element--cache-sync-requests
  5296. (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
  5297. (while org-element--cache-sync-requests
  5298. (setq request (car org-element--cache-sync-requests)
  5299. next (nth 1 org-element--cache-sync-requests))
  5300. (org-element--cache-process-request
  5301. request
  5302. (when next (org-element--request-key next))
  5303. threshold
  5304. (unless threshold time-limit)
  5305. future-change
  5306. offset)
  5307. ;; Re-assign current and next requests. It could have
  5308. ;; been altered during phase 1.
  5309. (setq request (car org-element--cache-sync-requests)
  5310. next (nth 1 org-element--cache-sync-requests))
  5311. ;; Request processed. Merge current and next offsets and
  5312. ;; transfer ending position.
  5313. (when next
  5314. ;; The following requests can only be either phase 1
  5315. ;; or phase 2 requests. We need to let them know
  5316. ;; that additional shifting happened ahead of them.
  5317. (cl-incf (org-element--request-offset next) (org-element--request-offset request))
  5318. (org-element--cache-log-message "Updating next request offset to %S: %s"
  5319. (org-element--request-offset next)
  5320. (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
  5321. ;; FIXME: END part of the request only matters for
  5322. ;; phase 0 requests. However, the only possible
  5323. ;; phase 0 request must be the first request in the
  5324. ;; list all the time. END position should be
  5325. ;; unused.
  5326. (setf (org-element--request-end next) (org-element--request-end request)))
  5327. (setq org-element--cache-sync-requests
  5328. (cdr org-element--cache-sync-requests)))))
  5329. ;; If more requests are awaiting, set idle timer accordingly.
  5330. ;; Otherwise, reset keys.
  5331. (if org-element--cache-sync-requests
  5332. (org-element--cache-set-timer buffer)
  5333. (setq org-element--cache-change-warning nil)
  5334. (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value))))))))
  5335. (defun org-element--cache-process-request
  5336. (request next-request-key threshold time-limit future-change offset)
  5337. "Process synchronization REQUEST for all entries before NEXT.
  5338. REQUEST is a vector, built by `org-element--cache-submit-request'.
  5339. NEXT-REQUEST-KEY is a cache key of the next request, as returned by
  5340. `org-element--cache-key'.
  5341. When non-nil, THRESHOLD is a buffer position. Synchronization
  5342. stops as soon as a shifted element begins after it.
  5343. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  5344. after this time or when Emacs exits idle state.
  5345. When non-nil, FUTURE-CHANGE is a buffer position where changes not
  5346. registered yet in the cache are going to happen. OFFSET is the
  5347. changed text length. See `org-element--cache-submit-request' for more
  5348. information.
  5349. Throw `org-element--cache-interrupt' if the process stops before
  5350. completing the request."
  5351. (org-element--cache-log-message "org-element-cache: Processing request %s up to %S-%S, next: %S"
  5352. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5353. future-change
  5354. threshold
  5355. next-request-key)
  5356. (catch 'org-element--cache-quit
  5357. (when (= (org-element--request-phase request) 0)
  5358. ;; Phase 0.
  5359. ;;
  5360. ;; Delete all elements starting after beginning of the element
  5361. ;; with request key NEXT, but not after buffer position END.
  5362. ;;
  5363. ;; At each iteration, we start again at tree root since
  5364. ;; a deletion modifies structure of the balanced tree.
  5365. (org-element--cache-log-message "Phase 0")
  5366. (catch 'org-element--cache-end-phase
  5367. (let ((deletion-count 0))
  5368. (while t
  5369. (when (org-element--cache-interrupt-p time-limit)
  5370. (org-element--cache-log-message "Interrupt: time limit")
  5371. (throw 'org-element--cache-interrupt nil))
  5372. (let ((request-key (org-element--request-key request))
  5373. (end (org-element--request-end request))
  5374. (node (org-element--cache-root))
  5375. data data-key)
  5376. ;; Find first element in cache with key REQUEST-KEY or
  5377. ;; after it.
  5378. (while node
  5379. (let* ((element (avl-tree--node-data node))
  5380. (key (org-element--cache-key element)))
  5381. (cond
  5382. ((org-element--cache-key-less-p key request-key)
  5383. (setq node (avl-tree--node-right node)))
  5384. ((org-element--cache-key-less-p request-key key)
  5385. (setq data element
  5386. data-key key
  5387. node (avl-tree--node-left node)))
  5388. (t (setq data element
  5389. data-key key
  5390. node nil)))))
  5391. (if data
  5392. ;; We found first element in cache starting at or
  5393. ;; after REQUEST-KEY.
  5394. (let ((pos (org-element-property :begin data)))
  5395. ;; FIXME: Maybe simply (< pos end)?
  5396. (if (<= pos end)
  5397. (progn
  5398. (org-element--cache-log-message "removing %S::%S"
  5399. (org-element-property :org-element--cache-sync-key data)
  5400. (org-element--format-element data))
  5401. (cl-incf deletion-count)
  5402. (org-element--cache-remove data)
  5403. (when (and (> (log org-element--cache-size 2) 10)
  5404. (> deletion-count
  5405. (/ org-element--cache-size (log org-element--cache-size 2))))
  5406. (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
  5407. deletion-count
  5408. org-element--cache-size
  5409. (log org-element--cache-size 2))
  5410. (org-element-cache-reset)
  5411. (throw 'org-element--cache-quit t)))
  5412. ;; Done deleting everthing starting before END.
  5413. ;; DATA-KEY is the first known element after END.
  5414. ;; Move on to phase 1.
  5415. (org-element--cache-log-message "found element after %S: %S::%S"
  5416. end
  5417. (org-element-property :org-element--cache-sync-key data)
  5418. (org-element--format-element data))
  5419. (setf (org-element--request-key request) data-key)
  5420. (setf (org-element--request-beg request) pos)
  5421. (setf (org-element--request-phase request) 1)
  5422. (throw 'org-element--cache-end-phase nil)))
  5423. ;; No element starting after modifications left in
  5424. ;; cache: further processing is futile.
  5425. (org-element--cache-log-message "Phase 0 deleted all elements in cache after %S!"
  5426. request-key)
  5427. (throw 'org-element--cache-quit t)))))))
  5428. (when (= (org-element--request-phase request) 1)
  5429. ;; Phase 1.
  5430. ;;
  5431. ;; Phase 0 left a hole in the cache. Some elements after it
  5432. ;; could have parents within. For example, in the following
  5433. ;; buffer:
  5434. ;;
  5435. ;; - item
  5436. ;;
  5437. ;;
  5438. ;; Paragraph1
  5439. ;;
  5440. ;; Paragraph2
  5441. ;;
  5442. ;; if we remove a blank line between "item" and "Paragraph1",
  5443. ;; everything down to "Paragraph2" is removed from cache. But
  5444. ;; the paragraph now belongs to the list, and its `:parent'
  5445. ;; property no longer is accurate.
  5446. ;;
  5447. ;; Therefore we need to parse again elements in the hole, or at
  5448. ;; least in its last section, so that we can re-parent
  5449. ;; subsequent elements, during phase 2.
  5450. ;;
  5451. ;; Note that we only need to get the parent from the first
  5452. ;; element in cache after the hole.
  5453. ;;
  5454. ;; When next key is lesser or equal to the current one, current
  5455. ;; request is inside a to-be-shifted part of the cache. It is
  5456. ;; fine because the order of elements will not be altered by
  5457. ;; shifting. However, we cannot know the real position of the
  5458. ;; unshifted NEXT element in the current request. So, we need
  5459. ;; to sort the request list according to keys and re-start
  5460. ;; processing from the new leftmost request.
  5461. (org-element--cache-log-message "Phase 1")
  5462. (let ((key (org-element--request-key request)))
  5463. (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
  5464. ;; In theory, the only case when requests are not
  5465. ;; ordered is when key of the next request is either the
  5466. ;; same with current key or it is a key for a removed
  5467. ;; element. Either way, we can simply merge the two
  5468. ;; requests.
  5469. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5470. (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
  5471. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5472. (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
  5473. (setf (org-element--request-key next-request) key)
  5474. (setf (org-element--request-beg next-request) (org-element--request-beg request))
  5475. (setf (org-element--request-phase next-request) 1)
  5476. (throw 'org-element--cache-quit t))))
  5477. ;; Next element will start at its beginning position plus
  5478. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  5479. ;; contains the real beginning position of the first element to
  5480. ;; shift and re-parent.
  5481. (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request)))
  5482. cached-before)
  5483. (cond ((and threshold (> limit threshold))
  5484. (org-element--cache-log-message "Interrupt: position %S after threshold %S" limit threshold)
  5485. (throw 'org-element--cache-interrupt nil))
  5486. ((and future-change (>= limit future-change))
  5487. ;; Changes happened around this element and they will
  5488. ;; trigger another phase 1 request. Skip re-parenting
  5489. ;; and simply proceed with shifting (phase 2) to make
  5490. ;; sure that followup phase 0 request for the recent
  5491. ;; changes can operate on the correctly shifted cache.
  5492. (org-element--cache-log-message "position %S after future change %S" limit future-change)
  5493. (setf (org-element--request-parent request) nil)
  5494. (setf (org-element--request-phase request) 2))
  5495. (t
  5496. (when future-change
  5497. ;; Changes happened, but not yet registered after
  5498. ;; this element. However, we a not yet safe to look
  5499. ;; at the buffer and parse elements in the cache gap.
  5500. ;; Some of the parents to be added to cache may end
  5501. ;; after the changes. Parsing this parents will
  5502. ;; assign the :end correct value for cache state
  5503. ;; after future-change. Then, when the future change
  5504. ;; is going to be processed, such parent boundary
  5505. ;; will be altered unnecessarily. To avoid this,
  5506. ;; we alter the new parents by -OFFSET.
  5507. ;; For now, just save last known cached element and
  5508. ;; then check all the parents below.
  5509. (setq cached-before (org-element--cache-find (1- limit) nil)))
  5510. ;; No relevant changes happened after submitting this
  5511. ;; request. We are safe to look at the actual Org
  5512. ;; buffer and calculate the new parent.
  5513. (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
  5514. (when future-change
  5515. ;; Check all the newly added parents to not
  5516. ;; intersect with future change.
  5517. (let ((up parent))
  5518. (while (and up
  5519. (or (not cached-before)
  5520. (> (org-element-property :begin up)
  5521. (org-element-property :begin cached-before))))
  5522. (when (> (org-element-property :end up) future-change)
  5523. ;; Offset future cache request.
  5524. (org-element--cache-shift-positions
  5525. up (- offset)
  5526. (if (and (org-element-property :robust-begin up)
  5527. (org-element-property :robust-end up))
  5528. '(:contents-end :end :robust-end)
  5529. '(:contents-end :end))))
  5530. (setq up (org-element-property :parent up)))))
  5531. (org-element--cache-log-message "New parent at %S: %S::%S"
  5532. limit
  5533. (org-element-property :org-element--cache-sync-key parent)
  5534. (org-element--format-element parent))
  5535. (setf (org-element--request-parent request) parent)
  5536. (setf (org-element--request-phase request) 2))))))
  5537. ;; Phase 2.
  5538. ;;
  5539. ;; Shift all elements starting from key START, but before NEXT, by
  5540. ;; OFFSET, and re-parent them when appropriate.
  5541. ;;
  5542. ;; Elements are modified by side-effect so the tree structure
  5543. ;; remains intact.
  5544. ;;
  5545. ;; Once THRESHOLD, if any, is reached, or once there is an input
  5546. ;; pending, exit. Before leaving, the current synchronization
  5547. ;; request is updated.
  5548. (org-element--cache-log-message "Phase 2")
  5549. (let ((start (org-element--request-key request))
  5550. (offset (org-element--request-offset request))
  5551. (parent (org-element--request-parent request))
  5552. (node (org-element--cache-root))
  5553. (stack (list nil))
  5554. (leftp t)
  5555. exit-flag continue-flag)
  5556. ;; No re-parenting nor shifting planned: request is over.
  5557. (when (and (not parent) (zerop offset))
  5558. (org-element--cache-log-message "Empty offset. Request completed.")
  5559. (throw 'org-element--cache-quit t))
  5560. (while node
  5561. (let* ((data (avl-tree--node-data node))
  5562. (key (org-element--cache-key data)))
  5563. ;; Traverse the cache tree. Ignore all the elements before
  5564. ;; START. Note that `avl-tree-stack' would not bypass the
  5565. ;; elements before START and thus would have beeen less
  5566. ;; efficient.
  5567. (if (and leftp (avl-tree--node-left node)
  5568. (not (org-element--cache-key-less-p key start)))
  5569. (progn (push node stack)
  5570. (setq node (avl-tree--node-left node)))
  5571. ;; Shift and re-parent when current node starts at or
  5572. ;; after START, but before NEXT.
  5573. (unless (org-element--cache-key-less-p key start)
  5574. ;; We reached NEXT. Request is complete.
  5575. (when (and next-request-key
  5576. (not (org-element--cache-key-less-p key next-request-key)))
  5577. (org-element--cache-log-message "Reached next request.")
  5578. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5579. (unless (and (org-element-property :cached (org-element--request-parent next-request))
  5580. (org-element-property :begin (org-element--request-parent next-request))
  5581. parent
  5582. (> (org-element-property :begin (org-element--request-parent next-request))
  5583. (org-element-property :begin parent)))
  5584. (setf (org-element--request-parent next-request) parent)))
  5585. (throw 'org-element--cache-quit t))
  5586. ;; Handle interruption request. Update current request.
  5587. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  5588. (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
  5589. (setf (org-element--request-key request) key)
  5590. (setf (org-element--request-parent request) parent)
  5591. (throw 'org-element--cache-interrupt nil))
  5592. ;; Shift element.
  5593. (unless (zerop offset)
  5594. (when (>= org-element--cache-diagnostics-level 3)
  5595. (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
  5596. offset
  5597. (org-element-property :org-element--cache-sync-key data)
  5598. (org-element--format-element data)))
  5599. (org-element--cache-shift-positions data offset))
  5600. (let ((begin (org-element-property :begin data)))
  5601. ;; Update PARENT and re-parent DATA, only when
  5602. ;; necessary. Propagate new structures for lists.
  5603. (while (and parent
  5604. (<= (org-element-property :end parent) begin))
  5605. (setq parent (org-element-property :parent parent)))
  5606. (cond ((and (not parent) (zerop offset)) (throw 'org-element--cache-quit nil))
  5607. ;; Consider scenario when DATA lays within
  5608. ;; sensitive lines of PARENT that was found
  5609. ;; during phase 2. For example:
  5610. ;;
  5611. ;; #+ begin_quote
  5612. ;; Paragraph
  5613. ;; #+end_quote
  5614. ;;
  5615. ;; In the above source block, remove space in
  5616. ;; the first line will trigger re-parenting of
  5617. ;; the paragraph and "#+end_quote" that is also
  5618. ;; considered paragraph before the modification.
  5619. ;; However, the paragraph element stored in
  5620. ;; cache must be deleted instead.
  5621. ((and parent
  5622. (or (not (memq (org-element-type parent) org-element-greater-elements))
  5623. (and (org-element-property :contents-begin parent)
  5624. (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
  5625. (and (org-element-property :contents-end parent)
  5626. (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
  5627. (> (org-element-property :end data) (org-element-property :end parent))
  5628. (and (org-element-property :contents-end data)
  5629. (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
  5630. (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
  5631. (org-element-property :org-element--cache-sync-key data)
  5632. (org-element--format-element data))
  5633. (org-element--cache-remove data)
  5634. ;; We altered the tree structure. The tree
  5635. ;; traversal needs to be restarted.
  5636. (setf (org-element--request-key request) key)
  5637. (setf (org-element--request-parent request) parent)
  5638. ;; Restart tree traversal.
  5639. (setq node (org-element--cache-root)
  5640. stack (list nil)
  5641. leftp t
  5642. begin -1
  5643. continue-flag t))
  5644. ((and parent
  5645. (not (eq parent data))
  5646. (let ((p (org-element-property :parent data)))
  5647. (or (not p)
  5648. (< (org-element-property :begin p)
  5649. (org-element-property :begin parent))
  5650. (unless (eq p parent)
  5651. (not (org-element-property :cached p))
  5652. ;; (not (avl-tree-member-p org-element--cache p))
  5653. ))))
  5654. (org-element--cache-log-message "Updating parent in %S\n Old parent: %S\n New parent: %S"
  5655. (org-element--format-element data)
  5656. (org-element--format-element (org-element-property :parent data))
  5657. (org-element--format-element parent))
  5658. (when (and (eq 'org-data (org-element-type parent))
  5659. (not (eq 'headline (org-element-type data))))
  5660. ;; FIXME: This check is here to see whether
  5661. ;; such error happens within
  5662. ;; `org-element--cache-process-request' or somewhere
  5663. ;; else.
  5664. (org-element--cache-warn "Added org-data parent to non-headline element: %S
  5665. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5666. data)
  5667. (org-element-cache-reset)
  5668. (throw 'org-element--cache-quit t))
  5669. (org-element-put-property data :parent parent)
  5670. (let ((s (org-element-property :structure parent)))
  5671. (when (and s (org-element-property :structure data))
  5672. (org-element-put-property data :structure s)))))
  5673. ;; Cache is up-to-date past THRESHOLD. Request
  5674. ;; interruption.
  5675. (when (and threshold (> begin threshold))
  5676. (org-element--cache-log-message "Reached threshold %S: %S"
  5677. threshold
  5678. (org-element--format-element data))
  5679. (setq exit-flag t))))
  5680. (if continue-flag
  5681. (setq continue-flag nil)
  5682. (setq node (if (setq leftp (avl-tree--node-right node))
  5683. (avl-tree--node-right node)
  5684. (pop stack)))))))
  5685. ;; We reached end of tree: synchronization complete.
  5686. t))
  5687. (org-element--cache-log-message "org-element-cache: Finished process. The cache size is %S. The remaining sync requests: %S"
  5688. org-element--cache-size
  5689. (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests))))
  5690. (defsubst org-element--open-end-p (element)
  5691. "Check if ELEMENT in current buffer contains extra blank lines after
  5692. it and does not have closing term.
  5693. Examples of such elements are: section, headline, org-data,
  5694. and footnote-definition."
  5695. (and (org-element-property :contents-end element)
  5696. (= (org-element-property :contents-end element)
  5697. (save-excursion
  5698. (goto-char (org-element-property :end element))
  5699. (skip-chars-backward " \r\n\t")
  5700. (line-beginning-position 2)))))
  5701. (defun org-element--parse-to (pos &optional syncp time-limit)
  5702. "Parse elements in current section, down to POS.
  5703. Start parsing from the closest between the last known element in
  5704. cache or headline above. Return the smallest element containing
  5705. POS.
  5706. When optional argument SYNCP is non-nil, return the parent of the
  5707. element containing POS instead. In that case, it is also
  5708. possible to provide TIME-LIMIT, which is a time value specifying
  5709. when the parsing should stop. The function throws
  5710. `org-element--cache-interrupt' if the process stopped before finding
  5711. the expected result."
  5712. (catch 'exit
  5713. (save-match-data
  5714. (org-with-wide-buffer
  5715. (goto-char pos)
  5716. (save-excursion
  5717. (end-of-line)
  5718. (skip-chars-backward " \r\t\n")
  5719. ;; Within blank lines at the beginning of buffer, return nil.
  5720. (when (bobp) (throw 'exit nil)))
  5721. (let* ((cached (and (org-element--cache-active-p)
  5722. (org-element--cache-find pos nil)))
  5723. (mode (org-element-property :mode cached))
  5724. element next)
  5725. (cond
  5726. ;; Nothing in cache before point: start parsing from first
  5727. ;; element in buffer down to POS or from the beginning of the
  5728. ;; file.
  5729. ((and (not cached) (org-element--cache-active-p))
  5730. (setq element (org-element-org-data-parser))
  5731. (unless (org-element-property :begin element)
  5732. (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
  5733. (org-element--cache-log-message "Nothing in cache. Adding org-data: %S"
  5734. (org-element--format-element element))
  5735. (org-element--cache-put element)
  5736. (goto-char (org-element-property :contents-begin element))
  5737. (setq mode 'org-data))
  5738. ;; Nothing in cache before point because cache is not active.
  5739. ;; Parse from previous heading to avoid re-parsing the whole
  5740. ;; buffer above. This comes at the cost of not calculating
  5741. ;; `:parent' property for headings.
  5742. ((not cached)
  5743. (if (org-with-limited-levels (outline-previous-heading))
  5744. (progn
  5745. (setq element (org-element-headline-parser nil 'fast))
  5746. (setq mode 'planning)
  5747. (forward-line))
  5748. (setq element (org-element-org-data-parser))
  5749. (setq mode 'org-data))
  5750. (org-skip-whitespace)
  5751. (beginning-of-line))
  5752. ;; Check if CACHED or any of its ancestors contain point.
  5753. ;;
  5754. ;; If there is such an element, we inspect it in order to know
  5755. ;; if we return it or if we need to parse its contents.
  5756. ;; Otherwise, we just start parsing from location, which is
  5757. ;; right after the top-most element containing CACHED but
  5758. ;; still before POS.
  5759. ;;
  5760. ;; As a special case, if POS is at the end of the buffer, we
  5761. ;; want to return the innermost element ending there.
  5762. ;;
  5763. ;; Also, if we find an ancestor and discover that we need to
  5764. ;; parse its contents, make sure we don't start from
  5765. ;; `:contents-begin', as we would otherwise go past CACHED
  5766. ;; again. Instead, in that situation, we will resume parsing
  5767. ;; from NEXT, which is located after CACHED or its higher
  5768. ;; ancestor not containing point.
  5769. (t
  5770. (let ((up cached)
  5771. (pos (if (= (point-max) pos) (1- pos) pos)))
  5772. (while (and up (<= (org-element-property :end up) pos))
  5773. (goto-char (org-element-property :end up))
  5774. (setq element up
  5775. mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
  5776. up (org-element-property :parent up)
  5777. next (point)))
  5778. (when up (setq element up)))))
  5779. ;; Parse successively each element until we reach POS.
  5780. (let ((end (or (org-element-property :end element) (point-max)))
  5781. (parent (org-element-property :parent element)))
  5782. (while t
  5783. (when (org-element--cache-interrupt-p time-limit)
  5784. (throw 'org-element--cache-interrupt nil))
  5785. (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
  5786. (when quit-flag
  5787. (cl-incf org-element--cache-interrupt-C-g-count)
  5788. (setq quit-flag nil))
  5789. (when (>= org-element--cache-interrupt-C-g-count
  5790. org-element--cache-interrupt-C-g-max-count)
  5791. (setq quit-flag t)
  5792. (setq org-element--cache-interrupt-C-g-count 0)
  5793. (org-element-cache-reset)
  5794. (error "org-element: Parsing aborted by user. Cache has been cleared.
  5795. If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
  5796. (message (substitute-command-keys
  5797. "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
  5798. (- org-element--cache-interrupt-C-g-max-count
  5799. org-element--cache-interrupt-C-g-count)))
  5800. (unless element
  5801. ;; Do not try to parse within blank at EOB.
  5802. (unless (save-excursion
  5803. (org-skip-whitespace)
  5804. (eobp))
  5805. (org-element-with-disabled-cache
  5806. (setq element (org-element--current-element
  5807. end 'element mode
  5808. (org-element-property :structure parent)))))
  5809. ;; Make sure that we return referenced element in cache
  5810. ;; that can be altered directly.
  5811. (if element
  5812. (setq element (or (org-element--cache-put element) element))
  5813. ;; Nothing to parse (i.e. empty file).
  5814. (throw 'exit parent))
  5815. (unless (or (not (org-element--cache-active-p)) parent)
  5816. (org-element--cache-warn "Got empty parent while parsing. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n Backtrace:\n%S"
  5817. (when (and (fboundp 'backtrace-get-frames)
  5818. (fboundp 'backtrace-to-string))
  5819. (backtrace-to-string (backtrace-get-frames 'backtrace))
  5820. (org-element-cache-reset)
  5821. (error "org-element--cache: Emergency exit"))))
  5822. (org-element-put-property element :parent parent))
  5823. (let ((elem-end (org-element-property :end element))
  5824. (type (org-element-type element)))
  5825. (cond
  5826. ;; Skip any element ending before point. Also skip
  5827. ;; element ending at point (unless it is also the end of
  5828. ;; buffer) since we're sure that another element begins
  5829. ;; after it.
  5830. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5831. ;; Avoid parsing headline siblings above.
  5832. (goto-char elem-end)
  5833. (when (eq type 'headline)
  5834. (save-match-data
  5835. (unless (when (and (/= 1 (org-element-property :level element))
  5836. (re-search-forward
  5837. (rx-to-string
  5838. `(and bol (repeat 1 ,(1- (let ((level (org-element-property :level element)))
  5839. (if org-odd-levels-only (1- (* level 2)) level)))
  5840. "*")
  5841. " "))
  5842. pos t))
  5843. (beginning-of-line)
  5844. t)
  5845. ;; There are headings with lower level than
  5846. ;; ELEMENT between ELEM-END and POS. Siblings
  5847. ;; may exist though. Parse starting from the
  5848. ;; last sibling or from ELEM-END if there are
  5849. ;; no other siblings.
  5850. (goto-char pos)
  5851. (unless
  5852. (re-search-backward
  5853. (rx-to-string
  5854. `(and bol (repeat ,(let ((level (org-element-property :level element)))
  5855. (if org-odd-levels-only (1- (* level 2)) level))
  5856. "*")
  5857. " "))
  5858. elem-end t)
  5859. ;; Roll-back to normal parsing.
  5860. (goto-char elem-end)))))
  5861. (setq mode (org-element--next-mode mode type nil)))
  5862. ;; A non-greater element contains point: return it.
  5863. ((not (memq type org-element-greater-elements))
  5864. (throw 'exit (if syncp parent element)))
  5865. ;; Otherwise, we have to decide if ELEMENT really
  5866. ;; contains POS. In that case we start parsing from
  5867. ;; contents' beginning.
  5868. ;;
  5869. ;; If POS is at contents' beginning but it is also at
  5870. ;; the beginning of the first item in a list or a table.
  5871. ;; In that case, we need to create an anchor for that
  5872. ;; list or table, so return it.
  5873. ;;
  5874. ;; Also, if POS is at the end of the buffer, no element
  5875. ;; can start after it, but more than one may end there.
  5876. ;; Arbitrarily, we choose to return the innermost of
  5877. ;; such elements.
  5878. ((let ((cbeg (org-element-property :contents-begin element))
  5879. (cend (org-element-property :contents-end element)))
  5880. (when (and cbeg cend
  5881. (or (< cbeg pos)
  5882. (and (= cbeg pos)
  5883. (not (memq type '(plain-list table)))))
  5884. (or (> cend pos)
  5885. ;; When we are at cend or within blank
  5886. ;; lines after, it is a special case:
  5887. ;; 1. At the end of buffer we return
  5888. ;; the innermost element.
  5889. ;; 2. At cend of element with return
  5890. ;; that element.
  5891. ;; 3. At the end of element, we would
  5892. ;; return in the earlier cond form.
  5893. ;; 4. Within blank lines after cend,
  5894. ;; when element does not have a
  5895. ;; closing keyword, we return that
  5896. ;; outermost element, unless the
  5897. ;; outermost element is a non-empty
  5898. ;; headline. In the latter case, we
  5899. ;; return the outermost element inside
  5900. ;; the headline section.
  5901. (and (org-element--open-end-p element)
  5902. (or (= (org-element-property :end element) (point-max))
  5903. (and (>= pos (org-element-property :contents-end element))
  5904. (memq (org-element-type element) '(org-data section headline)))))))
  5905. (goto-char (or next cbeg))
  5906. (setq mode (if next mode (org-element--next-mode mode type t))
  5907. next nil
  5908. parent element
  5909. end (if (org-element--open-end-p element)
  5910. (org-element-property :end element)
  5911. (org-element-property :contents-end element))))))
  5912. ;; Otherwise, return ELEMENT as it is the smallest
  5913. ;; element containing POS.
  5914. (t (throw 'exit (if syncp parent element)))))
  5915. (setq element nil))))))))
  5916. ;;;; Staging Buffer Changes
  5917. (defconst org-element--cache-sensitive-re
  5918. (concat
  5919. "^\\*+ " "\\|"
  5920. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5921. "^[ \t]*\\(?:"
  5922. "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
  5923. org-list-full-item-re "\\|"
  5924. ":\\(?: \\|$\\)" "\\|"
  5925. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  5926. "\\)")
  5927. "Regexp matching a sensitive line, structure wise.
  5928. A sensitive line is a headline, inlinetask, block, drawer, or
  5929. latex-environment boundary. When such a line is modified,
  5930. structure changes in the document may propagate in the whole
  5931. section, possibly making cache invalid.")
  5932. (defun org-element--cache-before-change (beg end)
  5933. "Detect modifications in sensitive parts of Org buffer.
  5934. BEG and END are the beginning and end of the range of changed
  5935. text. See `before-change-functions' for more information.
  5936. The function returns the new value of `org-element--cache-change-warning'."
  5937. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  5938. (current-buffer))
  5939. (when (org-element--cache-active-p t)
  5940. (org-with-wide-buffer
  5941. (setq org-element--cache-change-tic (buffer-chars-modified-tick))
  5942. (goto-char beg)
  5943. (beginning-of-line)
  5944. (let ((bottom (save-excursion
  5945. (goto-char end)
  5946. (if (and (bolp)
  5947. ;; When beg == end, still extent to eol.
  5948. (> (point) beg))
  5949. ;; FIXME: Potential pitfall.
  5950. ;; We are appending to an element end.
  5951. ;; Unless the last inserted char is not
  5952. ;; newline, the next element is not broken
  5953. ;; and does not need to be purged from the
  5954. ;; cache.
  5955. end
  5956. (line-end-position)))))
  5957. (prog1
  5958. ;; Use the worst change warning to not miss important edits.
  5959. ;; This function is called before edit and after edit by
  5960. ;; `org-element--cache-after-change'. Before the edit, we still
  5961. ;; want to use the old value if it comes from previous
  5962. ;; not yet processed edit (they may be merged by
  5963. ;; `org-element--cache-submit-request'). After the edit, we want to
  5964. ;; look if there was a sensitive removed during edit.
  5965. ;; FIXME: This is not the most efficient way and we now
  5966. ;; have to delete more elemetns than needed in some
  5967. ;; cases. A better approach may be storing the warning
  5968. ;; in the modification request itself.
  5969. (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
  5970. (org-element--cache-change-warning-after))
  5971. (setq org-element--cache-change-warning-after
  5972. (save-match-data
  5973. (let ((case-fold-search t))
  5974. (when (re-search-forward
  5975. org-element--cache-sensitive-re bottom t)
  5976. (goto-char beg)
  5977. (beginning-of-line)
  5978. (let (min-level)
  5979. (cl-loop while (re-search-forward
  5980. (rx-to-string
  5981. (if (and min-level
  5982. (> min-level 1))
  5983. `(and bol (repeat 1 ,(1- min-level) "*") " ")
  5984. `(and bol (+ "*") " ")))
  5985. bottom t)
  5986. do (setq min-level (1- (length (match-string 0))))
  5987. until (= min-level 1))
  5988. (goto-char beg)
  5989. (beginning-of-line)
  5990. (or (and min-level (org-reduced-level min-level))
  5991. (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
  5992. 'org-data)
  5993. t))))))
  5994. (setq org-element--cache-change-warning
  5995. (cond
  5996. ((and (numberp org-element--cache-change-warning-before)
  5997. (numberp org-element--cache-change-warning-after))
  5998. (min org-element--cache-change-warning-after
  5999. org-element--cache-change-warning-before))
  6000. ((numberp org-element--cache-change-warning-before)
  6001. org-element--cache-change-warning-before)
  6002. ((numberp org-element--cache-change-warning-after)
  6003. org-element--cache-change-warning-after)
  6004. (t (or org-element--cache-change-warning-after
  6005. org-element--cache-change-warning-before)))))
  6006. (org-element--cache-log-message "%S is about to modify text: warning %S"
  6007. this-command
  6008. org-element--cache-change-warning)))))))
  6009. (defun org-element--cache-after-change (beg end pre)
  6010. "Update buffer modifications for current buffer.
  6011. BEG and END are the beginning and end of the range of changed
  6012. text, and the length in bytes of the pre-change text replaced by
  6013. that range. See `after-change-functions' for more information."
  6014. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6015. (current-buffer))
  6016. (when (org-element--cache-active-p t)
  6017. (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
  6018. (org-element--cache-log-message "After change")
  6019. (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
  6020. ;; If beg is right after spaces in front of an element, we
  6021. ;; risk affecting previous element, so move beg to bol, making
  6022. ;; sure that we capture preceding element.
  6023. (setq beg (save-excursion
  6024. (goto-char beg)
  6025. (cl-incf pre (- beg (line-beginning-position)))
  6026. (line-beginning-position)))
  6027. ;; Store synchronization request.
  6028. (let ((offset (- end beg pre)))
  6029. (save-match-data
  6030. (org-element--cache-submit-request beg (- end offset) offset)))
  6031. ;; Activate a timer to process the request during idle time.
  6032. (org-element--cache-set-timer (current-buffer))))))
  6033. (defvar org-element--cache-avoid-synchronous-headline-re-parsing nil
  6034. "This variable controls how buffer changes are handled by the cache.
  6035. By default (when this variable is nil), cache re-parses modified
  6036. headlines immidiately after modification preserving all the unaffected
  6037. elements inside the headline.
  6038. The default behaviour works best when users types inside Org buffer of
  6039. when buffer modifications are mixed with cache requests. However,
  6040. large automated edits inserting/deleting many headlines are somewhat
  6041. slower by default (as in `org-archive-subtree'). Let-binding this
  6042. variable to non-nil will reduce cache latency after every singular edit
  6043. (`after-change-functions') at the cost of slower cache queries.")
  6044. (defun org-element--cache-for-removal (beg end offset)
  6045. "Return first element to remove from cache.
  6046. BEG and END are buffer positions delimiting buffer modifications.
  6047. OFFSET is the size of the changes.
  6048. Returned element is usually the first element in cache containing
  6049. any position between BEG and END. As an exception, greater
  6050. elements around the changes that are robust to contents
  6051. modifications are preserved and updated according to the
  6052. changes. In the latter case, the returned element is the outermost
  6053. non-robust element affected by the changes. Note that the returned
  6054. element may end before END position in which case some cached element
  6055. starting after the returned may still be affected by the changes.
  6056. Also, when there are no elements in cache before BEG, return first
  6057. known element in cache (it may start after END)."
  6058. (let* ((elements (org-element--cache-find (1- beg) 'both))
  6059. (before (car elements))
  6060. (after (cdr elements)))
  6061. (if (not before) after
  6062. ;; If BEFORE is a keyword, it may need to be removed to become
  6063. ;; an affiliated keyword.
  6064. (when (eq 'keyword (org-element-type before))
  6065. (let ((prev before))
  6066. (while (eq 'keyword (org-element-type prev))
  6067. (setq before prev
  6068. beg (org-element-property :begin prev))
  6069. (setq prev (org-element--cache-find (1- (org-element-property :begin before)))))))
  6070. (let ((up before)
  6071. (robust-flag t))
  6072. (while up
  6073. (if (let ((type (org-element-type up)))
  6074. (or (and (memq type '( center-block dynamic-block
  6075. quote-block special-block
  6076. drawer))
  6077. (or (not (eq type 'drawer))
  6078. (not (string= "PROPERTIES" (org-element-property :drawer-name up))))
  6079. ;; Sensitive change. This is
  6080. ;; unconditionally non-robust change.
  6081. (not org-element--cache-change-warning)
  6082. (let ((cbeg (org-element-property :contents-begin up))
  6083. (cend (org-element-property :contents-end up)))
  6084. (and cbeg
  6085. (<= cbeg beg)
  6086. (or (> cend end)
  6087. (and (= cend end)
  6088. (= (+ end offset) (point-max)))))))
  6089. (and (memq type '(headline section org-data))
  6090. (let ((rbeg (org-element-property :robust-begin up))
  6091. (rend (org-element-property :robust-end up)))
  6092. (and rbeg rend
  6093. (<= rbeg beg)
  6094. (or (> rend end)
  6095. (and (= rend end)
  6096. (= (+ end offset) (point-max))))))
  6097. (pcase type
  6098. ;; Sensitive change in section. Need to
  6099. ;; re-parse.
  6100. (`section (not org-element--cache-change-warning))
  6101. ;; Headline might be inserted. This is non-robust
  6102. ;; change when `up' is a `headline' or `section'
  6103. ;; with `>' level compared to the inserted headline.
  6104. ;;
  6105. ;; Also, planning info/property drawer
  6106. ;; could have been inserted. It is not
  6107. ;; robust change then.
  6108. (`headline
  6109. (and
  6110. (or (not (numberp org-element--cache-change-warning))
  6111. (> org-element--cache-change-warning
  6112. (org-element-property :level up)))
  6113. (org-with-point-at (org-element-property :contents-begin up)
  6114. (unless
  6115. (save-match-data
  6116. (when (looking-at-p org-element-planning-line-re)
  6117. (forward-line))
  6118. (when (looking-at org-property-drawer-re)
  6119. (< beg (match-end 0))))
  6120. 'robust))))
  6121. (`org-data (and (not (eq org-element--cache-change-warning 'org-data))
  6122. ;; Property drawer could
  6123. ;; have been inserted. It
  6124. ;; is not robust change
  6125. ;; then.
  6126. (org-with-wide-buffer
  6127. (goto-char (point-min))
  6128. (while (and (org-at-comment-p) (bolp)) (forward-line))
  6129. ;; Should not see property
  6130. ;; drawer within changed
  6131. ;; region.
  6132. (save-match-data
  6133. (or (not (looking-at org-property-drawer-re))
  6134. (> beg (match-end 0)))))))
  6135. (_ 'robust)))))
  6136. ;; UP is a robust greater element containing changes.
  6137. ;; We only need to extend its ending boundaries.
  6138. (progn
  6139. (org-element--cache-shift-positions
  6140. up offset
  6141. (if (and (org-element-property :robust-begin up)
  6142. (org-element-property :robust-end up))
  6143. '(:contents-end :end :robust-end)
  6144. '(:contents-end :end)))
  6145. (org-element--cache-log-message "Shifting end positions of robust parent: %S"
  6146. (org-element--format-element up)))
  6147. (unless (or
  6148. ;; UP is non-robust. Yet, if UP is headline, flagging
  6149. ;; everything inside for removal may be to
  6150. ;; costly. Instead, we should better re-parse only the
  6151. ;; headline itself when possible. If a headline is still
  6152. ;; starting from old :begin position, we do not care that
  6153. ;; its boundaries could have extended to shrinked - we
  6154. ;; will re-parent and shift them anyway.
  6155. (and (eq 'headline (org-element-type up))
  6156. (not org-element--cache-avoid-synchronous-headline-re-parsing)
  6157. ;; The change is not inside headline. Not
  6158. ;; updating here.
  6159. (not (<= beg (org-element-property :begin up)))
  6160. (not (> end (org-element-property :end up)))
  6161. (let ((current (org-with-point-at (org-element-property :begin up)
  6162. (org-element-with-disabled-cache
  6163. (org-element--current-element (point-max))))))
  6164. (when (eq 'headline (org-element-type current))
  6165. (org-element--cache-log-message "Found non-robust headline that can be updated individually: %S"
  6166. (org-element--format-element current))
  6167. (org-element-set-element up current)
  6168. t)))
  6169. ;; If UP is org-data, the situation is similar to
  6170. ;; headline case. We just need to re-parse the
  6171. ;; org-data itself, unless the change is made
  6172. ;; within blank lines at BOB (that could
  6173. ;; potentially alter first-section).
  6174. (when (and (eq 'org-data (org-element-type up))
  6175. (>= beg (org-element-property :contents-begin up)))
  6176. (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
  6177. (org-element--cache-log-message "Found non-robust change invalidating org-data. Re-parsing: %S"
  6178. (org-element--format-element up))
  6179. t))
  6180. (org-element--cache-log-message "Found non-robust element: %S"
  6181. (org-element--format-element up))
  6182. (setq before up)
  6183. (when robust-flag (setq robust-flag nil))))
  6184. (unless (or (org-element-property :parent up)
  6185. (eq 'org-data (org-element-type up)))
  6186. (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)
  6187. (org-element-cache-reset)
  6188. (error "org-element--cache: Emergency exit"))
  6189. (setq up (org-element-property :parent up)))
  6190. ;; We're at top level element containing ELEMENT: if it's
  6191. ;; altered by buffer modifications, it is first element in
  6192. ;; cache to be removed. Otherwise, that first element is the
  6193. ;; following one.
  6194. ;;
  6195. ;; As a special case, do not remove BEFORE if it is a robust
  6196. ;; container for current changes.
  6197. (if (or (< (org-element-property :end before) beg) robust-flag) after
  6198. before)))))
  6199. (defun org-element--cache-submit-request (beg end offset)
  6200. "Submit a new cache synchronization request for current buffer.
  6201. BEG and END are buffer positions delimiting the minimal area
  6202. where cache data should be removed. OFFSET is the size of the
  6203. change, as an integer."
  6204. (org-element--cache-log-message "Submitting new synchronization request for [%S..%S]𝝙%S"
  6205. beg end offset)
  6206. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6207. (current-buffer))
  6208. (let ((next (car org-element--cache-sync-requests))
  6209. delete-to delete-from)
  6210. (if (and next
  6211. ;; First existing sync request is in phase 0.
  6212. (= 0 (org-element--request-phase next))
  6213. ;; Current changes intersect with the first sync request.
  6214. (> (setq delete-to (+ (org-element--request-end next)
  6215. (org-element--request-offset next)))
  6216. end)
  6217. (<= (setq delete-from (org-element--request-beg next))
  6218. end))
  6219. ;; Current changes can be merged with first sync request: we
  6220. ;; can save a partial cache synchronization.
  6221. (progn
  6222. (org-element--cache-log-message "Found another phase 0 request intersecting with current")
  6223. ;; Update OFFSET of the existing request.
  6224. (cl-incf (org-element--request-offset next) offset)
  6225. ;; If last change happened within area to be removed, extend
  6226. ;; boundaries of robust parents, if any. Otherwise, find
  6227. ;; first element to remove and update request accordingly.
  6228. (if (> beg delete-from)
  6229. ;; The current modification is completely inside NEXT.
  6230. ;; We already added the current OFFSET to the NEXT
  6231. ;; request. However, the robust elements around
  6232. ;; modifications also need to be shifted. Moreover, the
  6233. ;; new modification may also have non-nil
  6234. ;; `org-element--cache-change-warning'. In the latter case, we
  6235. ;; also need to update the request.
  6236. (let ((first (org-element--cache-for-removal delete-from end offset) ; Shift as needed.
  6237. ))
  6238. (org-element--cache-log-message "Current request is inside next. Candidate parent: %S"
  6239. (org-element--format-element first))
  6240. (when
  6241. ;; Non-robust element is now before NEXT. Need to
  6242. ;; update.
  6243. (and first
  6244. (org-element--cache-key-less-p (org-element--cache-key first)
  6245. (org-element--request-key next)))
  6246. (org-element--cache-log-message "Current request is inside next. New parent: %S"
  6247. (org-element--format-element first))
  6248. (setf (org-element--request-key next) (org-element--cache-key first))
  6249. (setf (org-element--request-beg next) (org-element-property :begin first))
  6250. (setf (org-element--request-end next) (max (org-element-property :end first)
  6251. (org-element--request-end next)))
  6252. (setf (org-element--request-parent next) (org-element-property :parent first))))
  6253. ;; The current and NEXT modifications are intersecting
  6254. ;; with current modification starting before NEXT and NEXT
  6255. ;; ending after current. We need to update the common
  6256. ;; non-robust parent for the new extended modification
  6257. ;; region.
  6258. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  6259. (org-element--cache-log-message "Current request intersects with next. Candidate parent: %S"
  6260. (org-element--format-element first))
  6261. (when (and first
  6262. (org-element--cache-key-less-p (org-element--cache-key first)
  6263. (org-element--request-key next)))
  6264. (org-element--cache-log-message "Current request intersects with next. Updating. New parent: %S"
  6265. (org-element--format-element first))
  6266. (setf (org-element--request-key next) (org-element--cache-key first))
  6267. (setf (org-element--request-beg next) (org-element-property :begin first))
  6268. (setf (org-element--request-end next) (max (org-element-property :end first)
  6269. (org-element--request-end next)))
  6270. (setf (org-element--request-parent next) (org-element-property :parent first))))))
  6271. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  6272. ;; if any, is no longer a 0-phase request, thus ensuring that
  6273. ;; phases are properly ordered. We need to provide OFFSET as
  6274. ;; optional parameter since current modifications are not known
  6275. ;; yet to the otherwise correct part of the cache (i.e, before
  6276. ;; the first request).
  6277. (org-element--cache-log-message "Adding new phase 0 request")
  6278. (when next (org-element--cache-sync (current-buffer) end beg offset))
  6279. (let ((first (org-element--cache-for-removal beg end offset)))
  6280. (if first
  6281. (push (let ((first-beg (org-element-property :begin first))
  6282. (key (org-element--cache-key first)))
  6283. (cond
  6284. ;; When changes happen before the first known
  6285. ;; element, re-parent and shift the rest of the
  6286. ;; cache.
  6287. ((> first-beg end)
  6288. (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
  6289. (vector key first-beg nil offset nil 1))
  6290. ;; Otherwise, we find the first non robust
  6291. ;; element containing END. All elements between
  6292. ;; FIRST and this one are to be removed.
  6293. ;;
  6294. ;; The current modification is completely inside
  6295. ;; FIRST. Clear and update cached elements in
  6296. ;; region containing FIRST.
  6297. ((let ((first-end (org-element-property :end first)))
  6298. (when (> first-end end)
  6299. (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
  6300. (vector key first-beg first-end offset (org-element-property :parent first) 0))))
  6301. (t
  6302. ;; Now, FIRST is the first element after BEG or
  6303. ;; non-robust element containing BEG. However,
  6304. ;; FIRST ends before END and there might be
  6305. ;; another ELEMENT before END that spans beyond
  6306. ;; END. If there is such element, we need to
  6307. ;; extend the region down to end of the common
  6308. ;; parent of FIRST and everything inside
  6309. ;; BEG..END.
  6310. (let* ((element (org-element--cache-find end))
  6311. (element-end (org-element-property :end element))
  6312. (up element))
  6313. (while (and (not (eq up first))
  6314. (setq up (org-element-property :parent up))
  6315. (>= (org-element-property :begin up) first-beg))
  6316. ;; Note that UP might have been already
  6317. ;; shifted if it is a robust element. After
  6318. ;; deletion, it can put it's end before yet
  6319. ;; unprocessed ELEMENT.
  6320. (setq element-end (max (org-element-property :end up) element-end)
  6321. element up))
  6322. ;; Extend region to remove elements between
  6323. ;; beginning of first and the end of outermost
  6324. ;; element starting before END but after
  6325. ;; beginning of first.
  6326. ;; of the FIRST.
  6327. (org-element--cache-log-message "Extending to all elements between:\n 1: %S\n 2: %S"
  6328. (org-element--format-element first)
  6329. (org-element--format-element element))
  6330. (vector key first-beg element-end offset up 0)))))
  6331. org-element--cache-sync-requests)
  6332. ;; No element to remove. No need to re-parent either.
  6333. ;; Simply shift additional elements, if any, by OFFSET.
  6334. (if org-element--cache-sync-requests
  6335. (progn
  6336. (org-element--cache-log-message "Nothing to remove. Updating offset of the next request by 𝝙%S: %S"
  6337. offset
  6338. (let ((print-level 3))
  6339. (car org-element--cache-sync-requests)))
  6340. (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
  6341. offset))
  6342. (org-element--cache-log-message "Nothing to remove. No elements in cache after %S. Terminating."
  6343. end))))))
  6344. (setq org-element--cache-change-warning nil)))
  6345. (defun org-element--cache-verify-element (element)
  6346. "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
  6347. Return non-nil when verification failed."
  6348. ;; Verify correct parent for the element.
  6349. (unless (or (org-element-property :parent element)
  6350. (eq 'org-data (org-element-type element)))
  6351. (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)
  6352. (org-element-cache-reset))
  6353. (let ((org-element--cache-self-verify (or org-element--cache-self-verify
  6354. (and (boundp 'org-batch-test) org-batch-test)))
  6355. (org-element--cache-self-verify-frequency (if (and (boundp 'org-batch-test) org-batch-test)
  6356. 1
  6357. org-element--cache-self-verify-frequency)))
  6358. (when (and org-element--cache-self-verify
  6359. (org-element--cache-active-p)
  6360. (derived-mode-p 'org-mode)
  6361. (org-element-property :parent element)
  6362. (eq 'headline (org-element-type element))
  6363. ;; Avoid too much slowdown
  6364. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6365. (org-with-point-at (org-element-property :begin element)
  6366. (org-element-with-disabled-cache (org-up-heading-or-point-min))
  6367. (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
  6368. (eq (point) (point-min)))
  6369. (org-element--cache-warn "Cached element has wrong parent in %s. Resetting.
  6370. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6371. The element is: %S\n The parent is: %S\n The real parent is: %S"
  6372. (buffer-name (current-buffer))
  6373. (org-element--format-element element)
  6374. (org-element--format-element (org-element-property :parent element))
  6375. (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
  6376. (org-element-cache-reset))
  6377. (org-element--cache-verify-element (org-element-property :parent element))))
  6378. ;; Verify the element itself.
  6379. (when (and org-element--cache-self-verify
  6380. (org-element--cache-active-p)
  6381. element
  6382. (not (memq (org-element-type element) '(section org-data)))
  6383. ;; Avoid too much slowdown
  6384. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6385. (let ((real-element (let (org-element-use-cache)
  6386. (org-element--parse-to
  6387. (if (memq (org-element-type element) '(table-row item))
  6388. (1+ (org-element-property :begin element))
  6389. (org-element-property :begin element))))))
  6390. (unless (and (eq (org-element-type real-element) (org-element-type element))
  6391. (eq (org-element-property :begin real-element) (org-element-property :begin element))
  6392. (eq (org-element-property :end real-element) (org-element-property :end element))
  6393. (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
  6394. (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
  6395. (or (not (org-element-property :ID real-element))
  6396. (string= (org-element-property :ID real-element) (org-element-property :ID element))))
  6397. (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
  6398. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6399. The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
  6400. this-command
  6401. (buffer-name (current-buffer))
  6402. (if (/= org-element--cache-change-tic
  6403. (buffer-chars-modified-tick))
  6404. "no" "yes")
  6405. (org-element--format-element element)
  6406. (org-element--format-element real-element)
  6407. (org-element--cache-find (1- (org-element-property :begin real-element)))
  6408. (car (org-element--cache-find (org-element-property :begin real-element) 'both))
  6409. (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
  6410. (org-element-cache-reset))))))
  6411. ;;; Cache persistance
  6412. (defun org-element--cache-persist-before-write (container &optional associated)
  6413. "Sync cache before saving."
  6414. (when (equal container '(elisp org-element--cache))
  6415. (if (and org-element-use-cache
  6416. (plist-get associated :file)
  6417. (get-file-buffer (plist-get associated :file))
  6418. org-element-cache-persistent)
  6419. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6420. (if (and (derived-mode-p 'org-mode)
  6421. org-element--cache)
  6422. (progn
  6423. ;; Cleanup cache request keys to avoid collisions during next
  6424. ;; Emacs session.
  6425. (avl-tree-mapc
  6426. (lambda (el)
  6427. (org-element-put-property el :org-element--cache-sync-key nil))
  6428. org-element--cache)
  6429. (org-with-wide-buffer
  6430. (org-element-at-point (point-max)))
  6431. nil)
  6432. 'forbid))
  6433. 'forbid)))
  6434. (defun org-element--cache-persist-before-read (container &optional associated)
  6435. "Avoid reading cache before Org mode is loaded."
  6436. (when (equal container '(elisp org-element--cache))
  6437. (if (not (and (plist-get associated :file)
  6438. (get-file-buffer (plist-get associated :file))))
  6439. 'forbid
  6440. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6441. (unless (and org-element-use-cache
  6442. org-element-cache-persistent
  6443. (derived-mode-p 'org-mode)
  6444. (equal (secure-hash 'md5 (current-buffer))
  6445. (plist-get associated :hash)))
  6446. 'forbid)))))
  6447. (defun org-element--cache-persist-after-read (container &optional associated)
  6448. "Setup restored cache."
  6449. (when (and (plist-get associated :file)
  6450. (get-file-buffer (plist-get associated :file)))
  6451. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6452. (when (and org-element-use-cache org-element-cache-persistent)
  6453. (when (and (equal container '(elisp org-element--cache)) org-element--cache)
  6454. (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
  6455. (when (and (equal container '(elisp org-element--headline-cache)) org-element--headline-cache)
  6456. (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache)))))))
  6457. (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
  6458. (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
  6459. (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
  6460. ;;;; Public Functions
  6461. (defvar-local org-element--cache-gapless nil
  6462. "An alist containing (granularity . `org-element--cache-change-tic') elements.
  6463. Each element indicates the latest `org-element--cache-change-tic' when
  6464. change did not contain gaps.")
  6465. ;;;###autoload
  6466. (defun org-element-cache-reset (&optional all)
  6467. "Reset cache in current buffer.
  6468. When optional argument ALL is non-nil, reset cache in all Org
  6469. buffers."
  6470. (interactive "P")
  6471. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  6472. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  6473. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  6474. (when (not org-element-cache-persistent)
  6475. (org-persist-unregister 'org-element--headline-cache (current-buffer))
  6476. (org-persist-unregister 'org-element--cache (current-buffer)))
  6477. (when (and org-element-cache-persistent
  6478. (buffer-file-name (current-buffer)))
  6479. (org-persist-register 'org-element--cache (current-buffer))
  6480. (org-persist-register 'org-element--headline-cache
  6481. (current-buffer)
  6482. :inherit 'org-element--cache))
  6483. (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
  6484. (setq-local org-element--cache-gapless nil)
  6485. (setq-local org-element--cache
  6486. (avl-tree-create #'org-element--cache-compare))
  6487. (setq-local org-element--headline-cache
  6488. (avl-tree-create #'org-element--cache-compare))
  6489. (setq-local org-element--cache-size 0)
  6490. (setq-local org-element--headline-cache-size 0)
  6491. (setq-local org-element--cache-sync-keys-value 0)
  6492. (setq-local org-element--cache-change-warning nil)
  6493. (setq-local org-element--cache-sync-requests nil)
  6494. (setq-local org-element--cache-sync-timer nil)
  6495. (add-hook 'before-change-functions
  6496. #'org-element--cache-before-change nil t)
  6497. (add-hook 'after-change-functions
  6498. #'org-element--cache-after-change nil t)))))
  6499. ;;;###autoload
  6500. (defun org-element-cache-refresh (pos)
  6501. "Refresh cache at position POS."
  6502. (when (org-element--cache-active-p)
  6503. (org-element--cache-sync (current-buffer) pos)
  6504. (org-element--cache-submit-request pos pos 0)
  6505. (org-element--cache-set-timer (current-buffer))))
  6506. (defvar warning-minimum-log-level) ; Defined in warning.el
  6507. (defvar org-element-cache-map--recurse nil)
  6508. (defvar org-element-cache-map-continue-from nil
  6509. "Position from where mapping should continue.
  6510. This variable can be set by called function, especially when the
  6511. function modified the buffer.")
  6512. ;;;###autoload
  6513. (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
  6514. next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
  6515. narrow)
  6516. "Map all elements in current buffer with FUNC according to
  6517. GRANULARITY. Collect non-nil return values into result list.
  6518. FUNC should accept a single argument - the element.
  6519. FUNC can modify the buffer, but doing so may reduce performance. If
  6520. buffer is modified, the mapping will continue from an element starting
  6521. after the last mapped element. If the last mapped element is deleted,
  6522. the subsequent element will be skipped as it cannot be distinguished
  6523. deterministically from a changed element. If FUNC is expected to
  6524. delete the element, it should directly set the value of
  6525. `org-element-cache-map-continue-from' to force `org-element-cache-map'
  6526. continue from the right point in buffer.
  6527. If some elements are not yet in cache, they will be added.
  6528. GRANULARITY can be `headline', `headline+inlinetask'
  6529. `greater-element', or `element'. The default is
  6530. `headline+inlinetask'. `object' granularity is not supported.
  6531. RESTRICT-ELEMENTS is a list of element types to be mapped over.
  6532. NEXT-RE is a regexp used to search next candidate match when FUNC
  6533. returns non-nil and to search the first candidate match. FAIL-RE is a
  6534. regexp used to search next candidate match when FUNC returns nil. The
  6535. mapping will continue starting from headline at the RE match.
  6536. FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
  6537. mapped elements to elements starting at of after FROM-POS but before
  6538. TO-POS.
  6539. AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
  6540. after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
  6541. map all the elements starting from first element inside section, but
  6542. not including the section).
  6543. LIMIT-COUNT limits mapping to that many first matches where FUNC
  6544. returns non-nil.
  6545. NARROW controls whether current buffer narrowing should be preserved.
  6546. This function does a subset of what `org-element-map' does, but with
  6547. much better performance. Cached elements are supplied as the single
  6548. argument of FUNC. Changes to elements made in FUNC will also alter
  6549. the cache."
  6550. (unless (org-element--cache-active-p)
  6551. (error "Cache must be active."))
  6552. (unless (memq granularity '( headline headline+inlinetask
  6553. greater-element element))
  6554. (error "Unsupported granularity: %S" granularity))
  6555. ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
  6556. ;; process.
  6557. (unless (markerp to-pos)
  6558. (let ((mk (make-marker)))
  6559. (set-marker mk to-pos)
  6560. (setq to-pos mk)))
  6561. ;; Make sure that garbage collector does not stand on the way to
  6562. ;; maximum performance.
  6563. (let ((gc-cons-threshold #x40000000)
  6564. ;; Bind variables used inside loop to avoid memory
  6565. ;; re-allocation on every iteration.
  6566. ;; See https://emacsconf.org/2021/talks/faster/
  6567. tmpnext-start tmpparent tmpelement)
  6568. (save-excursion
  6569. (save-restriction
  6570. (unless narrow (widen))
  6571. ;; Synchronise cache up to the end of mapped region.
  6572. (org-element-at-point to-pos)
  6573. (cl-macrolet ((cache-root
  6574. ;; Use the most optimal version of cache available.
  6575. () `(if (memq granularity '(headline headline+inlinetask))
  6576. (org-element--headline-cache-root)
  6577. (org-element--cache-root)))
  6578. (cache-size
  6579. ;; Use the most optimal version of cache available.
  6580. () `(if (memq granularity '(headline headline+inlinetask))
  6581. org-element--headline-cache-size
  6582. org-element--cache-size))
  6583. (cache-walk-restart
  6584. ;; Restart tree traversal after AVL tree re-balance.
  6585. () `(when node
  6586. (org-element-at-point (point-max))
  6587. (setq node (cache-root)
  6588. stack (list nil)
  6589. leftp t
  6590. continue-flag t)))
  6591. (cache-walk-abort
  6592. ;; Abort tree traversal.
  6593. () `(setq continue-flag t
  6594. node nil))
  6595. (element-match-at-point
  6596. ;; Returning the first element to match around point.
  6597. ;; For example, if point is inside headline and
  6598. ;; granularity is restricted to headlines only, skip
  6599. ;; over all the child elements inside the headline
  6600. ;; and return the first parent headline.
  6601. ;; When we are inside a cache gap, calling
  6602. ;; `org-element-at-point' also fills the cache gap down to
  6603. ;; point.
  6604. () `(progn
  6605. ;; Parsing is one of the performance
  6606. ;; bottlenecks. Make sure to optimise it as
  6607. ;; much as possible.
  6608. ;;
  6609. ;; Avoid extra staff like timer cancels et al
  6610. ;; and only call `org-element--cache-sync-requests' when
  6611. ;; there are pending requests.
  6612. (when org-element--cache-sync-requests
  6613. (org-element--cache-sync (current-buffer)))
  6614. ;; Call `org-element--parse-to' directly avoiding any
  6615. ;; kind of `org-element-at-point' overheads.
  6616. (if restrict-elements
  6617. ;; Search directly instead of calling
  6618. ;; `org-element-lineage' to avoid funcall overheads
  6619. ;; and making sure that we do not go all
  6620. ;; the way to `org-data' as `org-element-lineage'
  6621. ;; does.
  6622. (progn
  6623. (setq tmpelement (org-element--parse-to (point)))
  6624. (while (and tmpelement (not (memq (org-element-type tmpelement) restrict-elements)))
  6625. (setq tmpelement (org-element-property :parent tmpelement)))
  6626. tmpelement)
  6627. (org-element--parse-to (point)))))
  6628. ;; Starting from (point), search RE and move START to
  6629. ;; the next valid element to be matched according to
  6630. ;; restriction. Abort cache walk if no next element
  6631. ;; can be found. When RE is nil, just find element at
  6632. ;; point.
  6633. (move-start-to-next-match
  6634. (re) `(save-match-data
  6635. (if (or (not ,re) (if org-element--cache-map-statistics
  6636. (progn
  6637. (setq before-time (float-time))
  6638. (re-search-forward (or (car-safe ,re) ,re) nil 'move)
  6639. (cl-incf re-search-time
  6640. (- (float-time)
  6641. before-time)))
  6642. (re-search-forward (or (car-safe ,re) ,re) nil 'move)))
  6643. (unless (or (< (point) (or start -1))
  6644. (and data
  6645. (< (point) (org-element-property :begin data))))
  6646. (if (cdr-safe ,re)
  6647. ;; Avoid parsing when we are 100%
  6648. ;; sure that regexp is good enough
  6649. ;; to find new START.
  6650. (setq start (match-beginning 0))
  6651. (setq start (max (or start -1)
  6652. (or (org-element-property :begin data) -1)
  6653. (or (org-element-property :begin (element-match-at-point)) -1))))
  6654. (when (>= start to-pos) (cache-walk-abort))
  6655. (when (eq start -1) (setq start nil)))
  6656. (cache-walk-abort))))
  6657. ;; Find expected begin position of an element after
  6658. ;; DATA.
  6659. (next-element-start
  6660. () `(progn
  6661. (setq tmpnext-start nil)
  6662. (if (memq granularity '(headline headline+inlinetask))
  6663. (setq tmpnext-start (or (when (memq (org-element-type data) '(headline org-data))
  6664. (org-element-property :contents-begin data))
  6665. (org-element-property :end data)))
  6666. (setq tmpnext-start (or (when (memq (org-element-type data) org-element-greater-elements)
  6667. (org-element-property :contents-begin data))
  6668. (org-element-property :end data))))
  6669. ;; DATA end may be the last element inside
  6670. ;; i.e. source block. Skip up to the end
  6671. ;; of parent in such case.
  6672. (setq tmpparent data)
  6673. (catch :exit
  6674. (when (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6675. (setq tmpnext-start (org-element-property :end tmpparent)))
  6676. (while (setq tmpparent (org-element-property :parent tmpparent))
  6677. (if (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6678. (setq tmpnext-start (org-element-property :end tmpparent))
  6679. (throw :exit t))))
  6680. tmpnext-start))
  6681. ;; Check if cache does not have gaps.
  6682. (cache-gapless-p
  6683. () `(eq org-element--cache-change-tic
  6684. (alist-get granularity org-element--cache-gapless))))
  6685. ;; The core algorithm is simple walk along binary tree. However,
  6686. ;; instead of checking all the tree elements from first to last
  6687. ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
  6688. ;; the elements before FROM-POS efficiently: O(logN) instead of
  6689. ;; O(Nbefore).
  6690. ;;
  6691. ;; Later, we may also not check every single element in the
  6692. ;; binary tree after FROM-POS. Instead, we can find position of
  6693. ;; next candidate elements by means of regexp search and skip the
  6694. ;; binary tree branches that are before the next candidate:
  6695. ;; again, O(logN) instead of O(Nbetween).
  6696. ;;
  6697. ;; Some elements might not yet be in the tree. So, we also parse
  6698. ;; the empty gaps in cache as needed making sure that we do not
  6699. ;; miss anything.
  6700. (let* (;; START is always beginning of an element. When there is
  6701. ;; no element in cache at START, we are inside cache gap
  6702. ;; and need to fill it.
  6703. (start (and from-pos
  6704. (progn
  6705. (goto-char from-pos)
  6706. (org-element-property :begin (element-match-at-point)))))
  6707. ;; Some elements may start at the same position, so we
  6708. ;; also keep track of the last processed element and make
  6709. ;; sure that we do not try to search it again.
  6710. (prev after-element)
  6711. (node (cache-root))
  6712. data
  6713. (stack (list nil))
  6714. (leftp t)
  6715. result
  6716. ;; Whether previous element matched FUNC (FUNC
  6717. ;; returned non-nil).
  6718. (last-match t)
  6719. continue-flag
  6720. ;; Generic regexp to search next potential match. If it
  6721. ;; is a cons of (regexp . 'match-beg), we are 100% sure
  6722. ;; that the match beginning is the existing element
  6723. ;; beginning.
  6724. (next-element-re (pcase granularity
  6725. ((or `headline
  6726. (guard (eq '(headline)
  6727. restrict-elements)))
  6728. (cons
  6729. (org-with-limited-levels
  6730. org-element-headline-re)
  6731. 'match-beg))
  6732. (`headline+inlinetask
  6733. (cons
  6734. (if (eq '(inlinetask) restrict-elements)
  6735. (org-inlinetask-outline-regexp)
  6736. org-element-headline-re)
  6737. 'match-beg))
  6738. ;; TODO: May add other commonly
  6739. ;; searched elements as needed.
  6740. (_)))
  6741. ;; Make sure that we are not checking the same regexp twice.
  6742. (next-re (unless (and next-re
  6743. (string= next-re
  6744. (or (car-safe next-element-re)
  6745. next-element-re)))
  6746. next-re))
  6747. (fail-re (unless (and fail-re
  6748. (string= fail-re
  6749. (or (car-safe next-element-re)
  6750. next-element-re)))
  6751. fail-re))
  6752. (restrict-elements (or restrict-elements
  6753. (pcase granularity
  6754. (`headline
  6755. '(headline))
  6756. (`headline+inlinetask
  6757. '(headline inlinetask))
  6758. (`greater-element
  6759. org-element-greater-elements)
  6760. (_ nil))))
  6761. ;; Statistics
  6762. (time (float-time))
  6763. (predicate-time 0)
  6764. (pre-process-time 0)
  6765. (re-search-time 0)
  6766. (count-predicate-calls-match 0)
  6767. (count-predicate-calls-fail 0)
  6768. ;; Bind variables used inside loop to avoid memory
  6769. ;; re-allocation on every iteration.
  6770. ;; See https://emacsconf.org/2021/talks/faster/
  6771. cache-size before-time modified-tic)
  6772. ;; Skip to first element within region.
  6773. (goto-char (or start (point-min)))
  6774. (move-start-to-next-match next-element-re)
  6775. (unless (and start (>= start to-pos))
  6776. ;; Pre-process cache filling all the gaps.
  6777. (unless (or org-element-cache-map--recurse
  6778. (cache-gapless-p)
  6779. ;; Pre-processing all the elements in large
  6780. ;; buffers when NEXT-RE/FAIL-RE are provided
  6781. ;; may be much slower compared to using
  6782. ;; regexp.
  6783. (and (eq granularity 'element)
  6784. (or next-re fail-re)))
  6785. (let ((org-element-cache-map--recurse t))
  6786. (setq before-time (float-time))
  6787. (org-element-cache-map
  6788. #'ignore
  6789. :granularity granularity)
  6790. (cl-incf pre-process-time
  6791. (- (float-time)
  6792. before-time))
  6793. ;; Re-assign the cache root after filling the cache
  6794. ;; gaps.
  6795. (setq node (cache-root)))
  6796. (setf (alist-get granularity org-element--cache-gapless)
  6797. org-element--cache-change-tic))
  6798. (while node
  6799. (setq data (avl-tree--node-data node))
  6800. (if (and leftp (avl-tree--node-left node) ; Left branch.
  6801. ;; Do not move to left branch when we are before
  6802. ;; PREV.
  6803. (or (not prev)
  6804. (not (org-element--cache-key-less-p
  6805. (org-element--cache-key data)
  6806. (org-element--cache-key prev))))
  6807. ;; ... or when we are before START.
  6808. (or (not start)
  6809. (not (> start (org-element-property :begin data)))))
  6810. (progn (push node stack)
  6811. (setq node (avl-tree--node-left node)))
  6812. ;; The whole tree left to DATA is before START and
  6813. ;; PREV. DATA may still be before START (i.e. when
  6814. ;; DATA is the root or when START moved), at START, or
  6815. ;; after START.
  6816. ;;
  6817. ;; If DATA is before start, skip it over and move to
  6818. ;; subsequent elements.
  6819. ;; If DATA is at start, run FUNC if necessary and
  6820. ;; update START according and NEXT-RE, FAIL-RE,
  6821. ;; NEXT-ELEMENT-RE.
  6822. ;; If DATA is after start, we have found a cache gap
  6823. ;; and need to fill it.
  6824. (unless (or (and start (< (org-element-property :begin data) start))
  6825. (and prev (not (org-element--cache-key-less-p
  6826. (org-element--cache-key prev)
  6827. (org-element--cache-key data)))))
  6828. ;; DATA is at of after START and PREV.
  6829. (if (or (not start) (= (org-element-property :begin data) start))
  6830. ;; DATA is at START. Match it.
  6831. ;; In the process, we may alter the buffer,
  6832. ;; so also keep track of the cache state.
  6833. (progn
  6834. (setq modified-tic org-element--cache-change-tic)
  6835. (setq cache-size (cache-size))
  6836. ;; When NEXT-RE/FAIL-RE is provided, skip to
  6837. ;; next regexp match after :begin of the current
  6838. ;; element.
  6839. (when (if last-match next-re fail-re)
  6840. (goto-char (org-element-property :begin data))
  6841. (move-start-to-next-match
  6842. (if last-match next-re fail-re)))
  6843. (when (and (or (not start) (eq (org-element-property :begin data) start))
  6844. (< (org-element-property :begin data) to-pos))
  6845. ;; Calculate where next possible element
  6846. ;; starts and update START if needed.
  6847. (setq start (next-element-start))
  6848. (goto-char start)
  6849. ;; Move START further if possible.
  6850. (when (and next-element-re
  6851. ;; Do not move if we know for
  6852. ;; sure that cache does not
  6853. ;; contain gaps. Regexp
  6854. ;; searches are not cheap.
  6855. (not (cache-gapless-p)))
  6856. (move-start-to-next-match next-element-re)
  6857. ;; Make sure that point is at START
  6858. ;; before running FUNC.
  6859. (goto-char start))
  6860. ;; Try FUNC if DATA matches all the
  6861. ;; restrictions. Calculate new START.
  6862. (when (or (not restrict-elements)
  6863. (memq (org-element-type data) restrict-elements))
  6864. ;; DATA matches restriction. FUNC may
  6865. ;;
  6866. ;; Call FUNC. FUNC may move point.
  6867. (setq org-element-cache-map-continue-from nil)
  6868. (if org-element--cache-map-statistics
  6869. (progn
  6870. (setq before-time (float-time))
  6871. (push (funcall func data) result)
  6872. (cl-incf predicate-time
  6873. (- (float-time)
  6874. before-time))
  6875. (if (car result)
  6876. (cl-incf count-predicate-calls-match)
  6877. (cl-incf count-predicate-calls-fail)))
  6878. (push (funcall func data) result)
  6879. (when (car result) (cl-incf count-predicate-calls-match)))
  6880. ;; Set `last-match'.
  6881. (setq last-match (car result))
  6882. ;; If FUNC moved point forward, update
  6883. ;; START.
  6884. (when org-element-cache-map-continue-from
  6885. (goto-char org-element-cache-map-continue-from))
  6886. (when (> (point) start)
  6887. (move-start-to-next-match nil))
  6888. ;; Drop nil.
  6889. (unless (car result) (pop result)))
  6890. ;; If FUNC did not move the point and we
  6891. ;; know for sure that cache does not contain
  6892. ;; gaps, do not try to calculate START in
  6893. ;; advance but simply loop to the next cache
  6894. ;; element.
  6895. (when (and (cache-gapless-p)
  6896. (eq (next-element-start)
  6897. start))
  6898. (setq start nil))
  6899. ;; Check if the buffer has been modified.
  6900. (unless (and (eq modified-tic org-element--cache-change-tic)
  6901. (eq cache-size (cache-size)))
  6902. ;; START may no longer be valid, update
  6903. ;; it to beginning of real element.
  6904. ;; Upon modification, START may lay
  6905. ;; inside an element. We want to move
  6906. ;; it to real beginning then despite
  6907. ;; START being larger.
  6908. (setq start nil)
  6909. (move-start-to-next-match nil)
  6910. ;; The new element may now start before
  6911. ;; or at already processed position.
  6912. ;; Make sure that we continue from an
  6913. ;; element past already processed
  6914. ;; place.
  6915. (when (and start
  6916. (<= start (org-element-property :begin data))
  6917. (not org-element-cache-map-continue-from))
  6918. (goto-char start)
  6919. (setq data (element-match-at-point))
  6920. ;; If DATA is nil, buffer is
  6921. ;; empty. Abort.
  6922. (when data
  6923. (goto-char (next-element-start))
  6924. (move-start-to-next-match next-element-re)))
  6925. (org-element-at-point to-pos)
  6926. (cache-walk-restart))
  6927. ;; Reached LIMIT-COUNT. Abort.
  6928. (when (and limit-count
  6929. (>= count-predicate-calls-match
  6930. limit-count))
  6931. (cache-walk-abort))
  6932. (if (org-element-property :cached data)
  6933. (setq prev data)
  6934. (setq prev nil))))
  6935. ;; DATA is after START. Fill the gap.
  6936. (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
  6937. ;; Tables and lists are special, we need a
  6938. ;; trickery to make items/rows be populated
  6939. ;; into cache.
  6940. (org-element--parse-to (1+ start)))
  6941. ;; Restart tree traversal as AVL tree is
  6942. ;; re-balanced upon adding elements. We can no
  6943. ;; longer trust STACK.
  6944. (cache-walk-restart)))
  6945. ;; Second, move to the right branch of the tree or skip
  6946. ;; it alltogether.
  6947. (if continue-flag
  6948. (setq continue-flag nil)
  6949. (setq node (if (and (car stack)
  6950. ;; If START advanced beyond stack parent, skip the right branch.
  6951. (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
  6952. (and prev (org-element--cache-key-less-p
  6953. (org-element--cache-key (avl-tree--node-data (car stack)))
  6954. (org-element--cache-key prev)))))
  6955. (progn
  6956. (setq leftp nil)
  6957. (pop stack))
  6958. ;; Otherwise, move ahead into the right
  6959. ;; branch when it exists.
  6960. (if (setq leftp (avl-tree--node-right node))
  6961. (avl-tree--node-right node)
  6962. (pop stack))))))))
  6963. (when (and org-element--cache-map-statistics
  6964. (or (not org-element--cache-map-statistics-threshold)
  6965. (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
  6966. (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.
  6967. 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"
  6968. (current-buffer)
  6969. count-predicate-calls-match
  6970. (+ count-predicate-calls-match
  6971. count-predicate-calls-fail)
  6972. (- (float-time) time)
  6973. pre-process-time
  6974. predicate-time
  6975. re-search-time
  6976. granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
  6977. ;; Return result.
  6978. (nreverse result)))))))
  6979. ;;; The Toolbox
  6980. ;;
  6981. ;; The first move is to implement a way to obtain the smallest element
  6982. ;; containing point. This is the job of `org-element-at-point'. It
  6983. ;; basically jumps back to the beginning of section containing point
  6984. ;; and proceed, one element after the other, with
  6985. ;; `org-element--current-element' until the container is found. Note:
  6986. ;; When using `org-element-at-point', secondary values are never
  6987. ;; parsed since the function focuses on elements, not on objects.
  6988. ;;
  6989. ;; At a deeper level, `org-element-context' lists all elements and
  6990. ;; objects containing point.
  6991. ;;
  6992. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  6993. ;; internally by navigation and manipulation tools.
  6994. ;;;###autoload
  6995. (defun org-element-at-point (&optional pom cached-only)
  6996. "Determine closest element around point or POM.
  6997. Only check cached element when CACHED-ONLY is non-nil and return nil
  6998. unconditionally when element at POM is not in cache.
  6999. Return value is a list like (TYPE PROPS) where TYPE is the type
  7000. of the element and PROPS a plist of properties associated to the
  7001. element.
  7002. Possible types are defined in `org-element-all-elements'.
  7003. Properties depend on element or object type, but always include
  7004. `:begin', `:end', and `:post-blank' properties.
  7005. As a special case, if point is at the very beginning of the first
  7006. item in a list or sub-list, returned element will be that list
  7007. instead of the item. Likewise, if point is at the beginning of
  7008. the first row of a table, returned element will be the table
  7009. instead of the first row.
  7010. When point is at the end of the buffer, return the innermost
  7011. element ending there."
  7012. (setq pom (or pom (point)))
  7013. ;; Allow re-parsing when the command can benefit from it.
  7014. (when (and cached-only
  7015. (memq this-command org-element--cache-non-modifying-commands))
  7016. (setq cached-only nil))
  7017. (let (element)
  7018. (when (org-element--cache-active-p)
  7019. (if (not org-element--cache) (org-element-cache-reset)
  7020. (unless cached-only (org-element--cache-sync (current-buffer) pom))))
  7021. (setq element (if cached-only
  7022. (and (org-element--cache-active-p)
  7023. (or (not org-element--cache-sync-requests)
  7024. (org-element--cache-key-less-p pom (org-element--request-key (car org-element--cache-sync-requests))))
  7025. (org-element--cache-find pom))
  7026. (condition-case err
  7027. (org-element--parse-to pom)
  7028. (error
  7029. (org-element--cache-warn "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)."
  7030. (buffer-name (current-buffer))
  7031. pom
  7032. err
  7033. (when (and (fboundp 'backtrace-get-frames)
  7034. (fboundp 'backtrace-to-string))
  7035. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  7036. (org-element-cache-reset)
  7037. (org-element--parse-to pom)))))
  7038. (when (and (org-element--cache-active-p)
  7039. element
  7040. (org-element--cache-verify-element element))
  7041. (setq element (org-element--parse-to pom)))
  7042. (unless (eq 'org-data (org-element-type element))
  7043. (unless (and cached-only
  7044. (not (and element
  7045. (or (= pom (org-element-property :begin element))
  7046. (and (not (memq (org-element-type element) org-element-greater-elements))
  7047. (>= pom (org-element-property :begin element))
  7048. (< pom (org-element-property :end element)))
  7049. (and (org-element-property :contents-begin element)
  7050. (>= pom (org-element-property :begin element))
  7051. (< pom (org-element-property :contents-begin element)))
  7052. (and (not (org-element-property :contents-end element))
  7053. (>= pom (org-element-property :begin element))
  7054. (< pom (org-element-property :end element)))))))
  7055. (if (not (eq (org-element-type element) 'section))
  7056. element
  7057. (org-element-at-point (1+ pom) cached-only))))))
  7058. ;;;###autoload
  7059. (defsubst org-element-at-point-no-context (&optional pom)
  7060. "Quickly find element at point or POM.
  7061. It is a faster version of `org-element-at-point' that is not
  7062. guaranteed to return correct `:parent' properties even when cache is
  7063. enabled."
  7064. (or (org-element-at-point pom 'cached-only)
  7065. (let (org-element-use-cache) (org-element-at-point pom))))
  7066. ;;;###autoload
  7067. (defun org-element-context (&optional element)
  7068. "Return smallest element or object around point.
  7069. Return value is a list like (TYPE PROPS) where TYPE is the type
  7070. of the element or object and PROPS a plist of properties
  7071. associated to it.
  7072. Possible types are defined in `org-element-all-elements' and
  7073. `org-element-all-objects'. Properties depend on element or
  7074. object type, but always include `:begin', `:end', `:parent' and
  7075. `:post-blank'.
  7076. As a special case, if point is right after an object and not at
  7077. the beginning of any other object, return that object.
  7078. Optional argument ELEMENT, when non-nil, is the closest element
  7079. containing point, as returned by `org-element-at-point'.
  7080. Providing it allows for quicker computation."
  7081. (catch 'objects-forbidden
  7082. (org-with-wide-buffer
  7083. (let* ((pos (point))
  7084. (element (or element (org-element-at-point)))
  7085. (type (org-element-type element))
  7086. (post (org-element-property :post-affiliated element)))
  7087. ;; If point is inside an element containing objects or
  7088. ;; a secondary string, narrow buffer to the container and
  7089. ;; proceed with parsing. Otherwise, return ELEMENT.
  7090. (cond
  7091. ;; At a parsed affiliated keyword, check if we're inside main
  7092. ;; or dual value.
  7093. ((and post (< pos post))
  7094. (beginning-of-line)
  7095. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  7096. (cond
  7097. ((not (member-ignore-case (match-string 1)
  7098. org-element-parsed-keywords))
  7099. (throw 'objects-forbidden element))
  7100. ((< (match-end 0) pos)
  7101. (narrow-to-region (match-end 0) (line-end-position)))
  7102. ((and (match-beginning 2)
  7103. (>= pos (match-beginning 2))
  7104. (< pos (match-end 2)))
  7105. (narrow-to-region (match-beginning 2) (match-end 2)))
  7106. (t (throw 'objects-forbidden element)))
  7107. ;; Also change type to retrieve correct restrictions.
  7108. (setq type 'keyword))
  7109. ;; At an item, objects can only be located within tag, if any.
  7110. ((eq type 'item)
  7111. (let ((tag (org-element-property :tag element)))
  7112. (if (or (not tag) (/= (line-beginning-position) post))
  7113. (throw 'objects-forbidden element)
  7114. (beginning-of-line)
  7115. (search-forward tag (line-end-position))
  7116. (goto-char (match-beginning 0))
  7117. (if (and (>= pos (point)) (< pos (match-end 0)))
  7118. (narrow-to-region (point) (match-end 0))
  7119. (throw 'objects-forbidden element)))))
  7120. ;; At an headline or inlinetask, objects are in title.
  7121. ((memq type '(headline inlinetask))
  7122. (let ((case-fold-search nil))
  7123. (goto-char (org-element-property :begin element))
  7124. (looking-at org-complex-heading-regexp)
  7125. (let ((end (match-end 4)))
  7126. (if (not end) (throw 'objects-forbidden element)
  7127. (goto-char (match-beginning 4))
  7128. (when (looking-at org-element-comment-string)
  7129. (goto-char (match-end 0)))
  7130. (if (>= (point) end) (throw 'objects-forbidden element)
  7131. (narrow-to-region (point) end))))))
  7132. ;; At a paragraph, a table-row or a verse block, objects are
  7133. ;; located within their contents.
  7134. ((memq type '(paragraph table-row verse-block))
  7135. (let ((cbeg (org-element-property :contents-begin element))
  7136. (cend (org-element-property :contents-end element)))
  7137. ;; CBEG is nil for table rules.
  7138. (if (and cbeg cend (>= pos cbeg)
  7139. (or (< pos cend) (and (= pos cend) (eobp))))
  7140. (narrow-to-region cbeg cend)
  7141. (throw 'objects-forbidden element))))
  7142. (t (throw 'objects-forbidden element)))
  7143. (goto-char (point-min))
  7144. (let ((restriction (org-element-restriction type))
  7145. (parent element)
  7146. last)
  7147. (catch 'exit
  7148. (while t
  7149. (let ((next (org-element--object-lex restriction)))
  7150. (when next (org-element-put-property next :parent parent))
  7151. ;; Process NEXT, if any, in order to know if we need to
  7152. ;; skip it, return it or move into it.
  7153. (if (or (not next) (> (org-element-property :begin next) pos))
  7154. (throw 'exit (or last parent))
  7155. (let ((end (org-element-property :end next))
  7156. (cbeg (org-element-property :contents-begin next))
  7157. (cend (org-element-property :contents-end next)))
  7158. (cond
  7159. ;; Skip objects ending before point. Also skip
  7160. ;; objects ending at point unless it is also the
  7161. ;; end of buffer, since we want to return the
  7162. ;; innermost object.
  7163. ((and (<= end pos) (/= (point-max) end))
  7164. (goto-char end)
  7165. ;; For convenience, when object ends at POS,
  7166. ;; without any space, store it in LAST, as we
  7167. ;; will return it if no object starts here.
  7168. (when (and (= end pos)
  7169. (not (memq (char-before) '(?\s ?\t))))
  7170. (setq last next)))
  7171. ;; If POS is within a container object, move into
  7172. ;; that object.
  7173. ((and cbeg cend
  7174. (>= pos cbeg)
  7175. (or (< pos cend)
  7176. ;; At contents' end, if there is no
  7177. ;; space before point, also move into
  7178. ;; object, for consistency with
  7179. ;; convenience feature above.
  7180. (and (= pos cend)
  7181. (or (= (point-max) pos)
  7182. (not (memq (char-before pos)
  7183. '(?\s ?\t)))))))
  7184. (goto-char cbeg)
  7185. (narrow-to-region (point) cend)
  7186. (setq parent next)
  7187. (setq restriction (org-element-restriction next)))
  7188. ;; Otherwise, return NEXT.
  7189. (t (throw 'exit next)))))))))))))
  7190. (defun org-element-lineage (datum &optional types with-self)
  7191. "List all ancestors of a given element or object.
  7192. DATUM is an object or element.
  7193. Return ancestors from the closest to the farthest. When optional
  7194. argument TYPES is a list of symbols, return the first element or
  7195. object in the lineage whose type belongs to that list instead.
  7196. When optional argument WITH-SELF is non-nil, lineage includes
  7197. DATUM itself as the first element, and TYPES, if provided, also
  7198. apply to it.
  7199. When DATUM is obtained through `org-element-context' or
  7200. `org-element-at-point', only ancestors from its section can be
  7201. found. There is no such limitation when DATUM belongs to a full
  7202. parse tree."
  7203. (let ((up (if with-self datum (org-element-property :parent datum)))
  7204. ancestors)
  7205. (while (and up (not (memq (org-element-type up) types)))
  7206. (unless types (push up ancestors))
  7207. (setq up (org-element-property :parent up)))
  7208. (if types up (nreverse ancestors))))
  7209. (defun org-element-nested-p (elem-A elem-B)
  7210. "Non-nil when elements ELEM-A and ELEM-B are nested."
  7211. (let ((beg-A (org-element-property :begin elem-A))
  7212. (beg-B (org-element-property :begin elem-B))
  7213. (end-A (org-element-property :end elem-A))
  7214. (end-B (org-element-property :end elem-B)))
  7215. (or (and (>= beg-A beg-B) (<= end-A end-B))
  7216. (and (>= beg-B beg-A) (<= end-B end-A)))))
  7217. (defun org-element-swap-A-B--overlays (elem-A elem-B)
  7218. "Swap elements ELEM-A and ELEM-B.
  7219. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7220. end of ELEM-A."
  7221. (goto-char (org-element-property :begin elem-A))
  7222. ;; There are two special cases when an element doesn't start at bol:
  7223. ;; the first paragraph in an item or in a footnote definition.
  7224. (let ((specialp (not (bolp))))
  7225. ;; Only a paragraph without any affiliated keyword can be moved at
  7226. ;; ELEM-A position in such a situation. Note that the case of
  7227. ;; a footnote definition is impossible: it cannot contain two
  7228. ;; paragraphs in a row because it cannot contain a blank line.
  7229. (when (and specialp
  7230. (or (not (eq (org-element-type elem-B) 'paragraph))
  7231. (/= (org-element-property :begin elem-B)
  7232. (org-element-property :contents-begin elem-B))))
  7233. (error "Cannot swap elements"))
  7234. ;; In a special situation, ELEM-A will have no indentation. We'll
  7235. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7236. (let* ((ind-B (when specialp
  7237. (goto-char (org-element-property :begin elem-B))
  7238. (current-indentation)))
  7239. (beg-A (org-element-property :begin elem-A))
  7240. (end-A (save-excursion
  7241. (goto-char (org-element-property :end elem-A))
  7242. (skip-chars-backward " \r\t\n")
  7243. (point-at-eol)))
  7244. (beg-B (org-element-property :begin elem-B))
  7245. (end-B (save-excursion
  7246. (goto-char (org-element-property :end elem-B))
  7247. (skip-chars-backward " \r\t\n")
  7248. (point-at-eol)))
  7249. ;; Store inner overlays responsible for visibility status.
  7250. ;; We also need to store their boundaries as they will be
  7251. ;; removed from buffer.
  7252. (overlays
  7253. (cons
  7254. (delq nil
  7255. (mapcar (lambda (o)
  7256. (and (>= (overlay-start o) beg-A)
  7257. (<= (overlay-end o) end-A)
  7258. (list o (overlay-start o) (overlay-end o))))
  7259. (overlays-in beg-A end-A)))
  7260. (delq nil
  7261. (mapcar (lambda (o)
  7262. (and (>= (overlay-start o) beg-B)
  7263. (<= (overlay-end o) end-B)
  7264. (list o (overlay-start o) (overlay-end o))))
  7265. (overlays-in beg-B end-B)))))
  7266. ;; Get contents.
  7267. (body-A (buffer-substring beg-A end-A))
  7268. (body-B (delete-and-extract-region beg-B end-B)))
  7269. (goto-char beg-B)
  7270. (when specialp
  7271. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7272. (indent-to-column ind-B))
  7273. (insert body-A)
  7274. ;; Restore ex ELEM-A overlays.
  7275. (let ((offset (- beg-B beg-A)))
  7276. (dolist (o (car overlays))
  7277. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  7278. (goto-char beg-A)
  7279. (delete-region beg-A end-A)
  7280. (insert body-B)
  7281. ;; Restore ex ELEM-B overlays.
  7282. (dolist (o (cdr overlays))
  7283. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  7284. (goto-char (org-element-property :end elem-B)))))
  7285. (defun org-element-swap-A-B--text-properties (elem-A elem-B)
  7286. "Swap elements ELEM-A and ELEM-B.
  7287. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7288. end of ELEM-A."
  7289. (goto-char (org-element-property :begin elem-A))
  7290. ;; There are two special cases when an element doesn't start at bol:
  7291. ;; the first paragraph in an item or in a footnote definition.
  7292. (let ((specialp (not (bolp))))
  7293. ;; Only a paragraph without any affiliated keyword can be moved at
  7294. ;; ELEM-A position in such a situation. Note that the case of
  7295. ;; a footnote definition is impossible: it cannot contain two
  7296. ;; paragraphs in a row because it cannot contain a blank line.
  7297. (when (and specialp
  7298. (or (not (eq (org-element-type elem-B) 'paragraph))
  7299. (/= (org-element-property :begin elem-B)
  7300. (org-element-property :contents-begin elem-B))))
  7301. (error "Cannot swap elements"))
  7302. ;; In a special situation, ELEM-A will have no indentation. We'll
  7303. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7304. (org-fold-core-ignore-modifications ;; Preserve folding state
  7305. (let* ((ind-B (when specialp
  7306. (goto-char (org-element-property :begin elem-B))
  7307. (current-indentation)))
  7308. (beg-A (org-element-property :begin elem-A))
  7309. (end-A (save-excursion
  7310. (goto-char (org-element-property :end elem-A))
  7311. (skip-chars-backward " \r\t\n")
  7312. (point-at-eol)))
  7313. (beg-B (org-element-property :begin elem-B))
  7314. (end-B (save-excursion
  7315. (goto-char (org-element-property :end elem-B))
  7316. (skip-chars-backward " \r\t\n")
  7317. (point-at-eol)))
  7318. ;; Get contents.
  7319. (body-A (buffer-substring beg-A end-A))
  7320. (body-B (delete-and-extract-region beg-B end-B)))
  7321. (goto-char beg-B)
  7322. (when specialp
  7323. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7324. (indent-to-column ind-B))
  7325. (insert body-A)
  7326. (goto-char beg-A)
  7327. (delete-region beg-A end-A)
  7328. (insert body-B)
  7329. (goto-char (org-element-property :end elem-B))))))
  7330. (defsubst org-element-swap-A-B (elem-A elem-B)
  7331. "Swap elements ELEM-A and ELEM-B.
  7332. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7333. end of ELEM-A."
  7334. (if (eq org-fold-core-style 'text-properties)
  7335. (org-element-swap-A-B--text-properties elem-A elem-B)
  7336. (org-element-swap-A-B--overlays elem-A elem-B)))
  7337. (provide 'org-element)
  7338. ;; Local variables:
  7339. ;; generated-autoload-file: "org-loaddefs.el"
  7340. ;; End:
  7341. ;;; org-element.el ends here