org-element.el 329 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
  19. ;; Org syntax.
  20. ;;
  21. ;; Lisp-wise, a syntax object can be represented as a list.
  22. ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
  23. ;; TYPE is a symbol describing the object.
  24. ;; PROPERTIES is the property list attached to it. See docstring of
  25. ;; appropriate parsing function to get an exhaustive list.
  26. ;; CONTENTS is a list of syntax objects or raw strings contained
  27. ;; in the current object, when applicable.
  28. ;;
  29. ;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
  30. ;;
  31. ;; The first part of this file defines constants for the Org syntax,
  32. ;; while the second one provide accessors and setters functions.
  33. ;;
  34. ;; The next part implements a parser and an interpreter for each
  35. ;; element and object type in Org syntax.
  36. ;;
  37. ;; The following part creates a fully recursive buffer parser. It
  38. ;; also provides a tool to map a function to elements or objects
  39. ;; matching some criteria in the parse tree. Functions of interest
  40. ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
  41. ;; extent, `org-element-parse-secondary-string'.
  42. ;;
  43. ;; The penultimate part is the cradle of an interpreter for the
  44. ;; obtained parse tree: `org-element-interpret-data'.
  45. ;;
  46. ;; The library ends by furnishing `org-element-at-point' function, and
  47. ;; a way to give information about document structure around point
  48. ;; with `org-element-context'. A cache mechanism is also provided for
  49. ;; these functions.
  50. ;;; Code:
  51. (require 'avl-tree)
  52. (require 'ring)
  53. (require 'cl-lib)
  54. (require 'ol)
  55. (require 'org)
  56. (require 'org-persist)
  57. (require 'org-compat)
  58. (require 'org-entities)
  59. (require 'org-footnote)
  60. (require 'org-list)
  61. (require 'org-macs)
  62. (require 'org-table)
  63. (require 'org-fold-core)
  64. (declare-function org-at-heading-p "org" (&optional _))
  65. (declare-function org-escape-code-in-string "org-src" (s))
  66. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  67. (declare-function org-macro-extract-arguments "org-macro" (s))
  68. (declare-function org-reduced-level "org" (l))
  69. (declare-function org-unescape-code-in-string "org-src" (s))
  70. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  71. (declare-function outline-next-heading "outline" ())
  72. (declare-function outline-previous-heading "outline" ())
  73. (defvar org-complex-heading-regexp)
  74. (defvar org-done-keywords)
  75. (defvar org-edit-src-content-indentation)
  76. (defvar org-match-substring-regexp)
  77. (defvar org-odd-levels-only)
  78. (defvar org-property-drawer-re)
  79. (defvar org-property-format)
  80. (defvar org-property-re)
  81. (defvar org-src-preserve-indentation)
  82. (defvar org-tags-column)
  83. (defvar org-time-stamp-formats)
  84. (defvar org-todo-regexp)
  85. (defvar org-ts-regexp-both)
  86. ;;; Definitions And Rules
  87. ;;
  88. ;; Define elements, greater elements and specify recursive objects,
  89. ;; along with the affiliated keywords recognized. Also set up
  90. ;; restrictions on recursive objects combinations.
  91. ;;
  92. ;; `org-element-update-syntax' builds proper syntax regexps according
  93. ;; to current setup.
  94. (defconst org-element-archive-tag "ARCHIVE"
  95. "Tag marking a substree as archived.")
  96. (defconst org-element-citation-key-re
  97. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  98. "Regexp matching a citation key.
  99. Key is located in match group 1.")
  100. (defconst org-element-citation-prefix-re
  101. (rx "[cite"
  102. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  103. ":"
  104. (zero-or-more (any "\t\n ")))
  105. "Regexp matching a citation prefix.
  106. Style, if any, is located in match group 1.")
  107. (defconst org-element-clock-line-re
  108. (rx line-start (0+ (or ?\t ?\s)) "CLOCK:")
  109. "Regexp matching a clock line.")
  110. (defconst org-element-comment-string "COMMENT"
  111. "String marker for commented headlines.")
  112. (defconst org-element-closed-keyword "CLOSED:"
  113. "Keyword used to close TODO entries.")
  114. (defconst org-element-deadline-keyword "DEADLINE:"
  115. "Keyword used to mark deadline entries.")
  116. (defconst org-element-scheduled-keyword "SCHEDULED:"
  117. "Keyword used to mark scheduled entries.")
  118. (defconst org-element-planning-keywords-re
  119. (regexp-opt (list org-element-closed-keyword
  120. org-element-deadline-keyword
  121. org-element-scheduled-keyword))
  122. "Regexp matching any planning line keyword.")
  123. (defconst org-element-planning-line-re
  124. (rx-to-string
  125. `(seq line-start (0+ (any ?\s ?\t))
  126. (group (regexp ,org-element-planning-keywords-re))))
  127. "Regexp matching a planning line.")
  128. (defconst org-element-drawer-re
  129. (rx line-start (0+ (any ?\s ?\t))
  130. ":" (group (1+ (any ?- ?_ word))) ":"
  131. (0+ (any ?\s ?\t)) line-end)
  132. "Regexp matching opening or closing line of a drawer.
  133. Drawer's name is located in match group 1.")
  134. (defconst org-element-dynamic-block-open-re
  135. (rx line-start (0+ (any ?\s ?\t))
  136. "#+BEGIN:" (0+ (any ?\s ?\t))
  137. (group (1+ word))
  138. (opt
  139. (1+ (any ?\s ?\t))
  140. (group (1+ nonl))))
  141. "Regexp matching the opening line of a dynamic block.
  142. Dynamic block's name is located in match group 1.
  143. Parameters are in match group 2.")
  144. (defconst org-element-headline-re
  145. (rx line-start (1+ "*") " ")
  146. "Regexp matching a headline.")
  147. (defvar org-element-paragraph-separate nil
  148. "Regexp to separate paragraphs in an Org buffer.
  149. In the case of lines starting with \"#\" and \":\", this regexp
  150. is not sufficient to know if point is at a paragraph ending. See
  151. `org-element-paragraph-parser' for more information.")
  152. (defvar org-element--object-regexp nil
  153. "Regexp possibly matching the beginning of an object.
  154. This regexp allows false positives. Dedicated parser (e.g.,
  155. `org-export-bold-parser') will take care of further filtering.
  156. Radio links are not matched by this regexp, as they are treated
  157. specially in `org-element--object-lex'.")
  158. (defun org-element--set-regexps ()
  159. "Build variable syntax regexps."
  160. (setq org-element-paragraph-separate
  161. (concat "^\\(?:"
  162. ;; Headlines, inlinetasks.
  163. "\\*+ " "\\|"
  164. ;; Footnote definitions.
  165. "\\[fn:[-_[:word:]]+\\]" "\\|"
  166. ;; Diary sexps.
  167. "%%(" "\\|"
  168. "[ \t]*\\(?:"
  169. ;; Empty lines.
  170. "$" "\\|"
  171. ;; Tables (any type).
  172. "|" "\\|"
  173. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  174. ;; Comments, keyword-like or block-like constructs.
  175. ;; Blocks and keywords with dual values need to be
  176. ;; double-checked.
  177. "#\\(?: \\|$\\|\\+\\(?:"
  178. "BEGIN_\\S-+" "\\|"
  179. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  180. "\\|"
  181. ;; Drawers (any type) and fixed-width areas. Drawers
  182. ;; need to be double-checked.
  183. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  184. ;; Horizontal rules.
  185. "-\\{5,\\}[ \t]*$" "\\|"
  186. ;; LaTeX environments.
  187. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  188. ;; Clock lines.
  189. "CLOCK:" "\\|"
  190. ;; Lists.
  191. (let ((term (pcase org-plain-list-ordered-item-terminator
  192. (?\) ")") (?. "\\.") (_ "[.)]")))
  193. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  194. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  195. "\\(?:[ \t]\\|$\\)"))
  196. "\\)\\)")
  197. org-element--object-regexp
  198. (mapconcat #'identity
  199. (let ((link-types (regexp-opt (org-link-types))))
  200. (list
  201. ;; Sub/superscript.
  202. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  203. ;; Bold, code, italic, strike-through, underline
  204. ;; and verbatim.
  205. (rx (or "*" "~" "=" "+" "_" "/") (not space))
  206. ;; Plain links.
  207. (concat "\\<" link-types ":")
  208. ;; Objects starting with "[": citations,
  209. ;; footnote reference, statistics cookie,
  210. ;; timestamp (inactive) and regular link.
  211. (format "\\[\\(?:%s\\)"
  212. (mapconcat
  213. #'identity
  214. (list "cite[:/]"
  215. "fn:"
  216. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  217. "\\[")
  218. "\\|"))
  219. ;; Objects starting with "@": export snippets.
  220. "@@"
  221. ;; Objects starting with "{": macro.
  222. "{{{"
  223. ;; Objects starting with "<" : timestamp
  224. ;; (active, diary), target, radio target and
  225. ;; angular links.
  226. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  227. ;; Objects starting with "$": latex fragment.
  228. "\\$"
  229. ;; Objects starting with "\": line break,
  230. ;; entity, latex fragment.
  231. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  232. ;; Objects starting with raw text: inline Babel
  233. ;; source block, inline Babel call.
  234. "\\(?:call\\|src\\)_"))
  235. "\\|")))
  236. (org-element--set-regexps)
  237. ;;;###autoload
  238. (defun org-element-update-syntax ()
  239. "Update parser internals."
  240. (interactive)
  241. (org-element--set-regexps)
  242. (org-element-cache-reset 'all))
  243. (defconst org-element-all-elements
  244. '(babel-call center-block clock comment comment-block diary-sexp drawer
  245. dynamic-block example-block export-block fixed-width
  246. footnote-definition headline horizontal-rule inlinetask item
  247. keyword latex-environment node-property paragraph plain-list
  248. planning property-drawer quote-block section
  249. special-block src-block table table-row verse-block)
  250. "Complete list of element types.")
  251. (defconst org-element-greater-elements
  252. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  253. item plain-list property-drawer quote-block section
  254. special-block table org-data)
  255. "List of recursive element types aka Greater Elements.")
  256. (defconst org-element-all-objects
  257. '(bold citation citation-reference code entity export-snippet
  258. footnote-reference inline-babel-call inline-src-block italic line-break
  259. latex-fragment link macro radio-target statistics-cookie strike-through
  260. subscript superscript table-cell target timestamp underline verbatim)
  261. "Complete list of object types.")
  262. (defconst org-element-recursive-objects
  263. '(bold citation footnote-reference italic link subscript radio-target
  264. strike-through superscript table-cell underline)
  265. "List of recursive object types.")
  266. (defconst org-element-object-containers
  267. (append org-element-recursive-objects '(paragraph table-row verse-block))
  268. "List of object or element types that can directly contain objects.")
  269. (defconst org-element-affiliated-keywords
  270. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  271. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  272. "List of affiliated keywords as strings.
  273. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  274. are affiliated keywords and need not to be in this list.")
  275. (defconst org-element-keyword-translation-alist
  276. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  277. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  278. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  279. "Alist of usual translations for keywords.
  280. The key is the old name and the value the new one. The property
  281. holding their value will be named after the translated name.")
  282. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  283. "List of affiliated keywords that can occur more than once in an element.
  284. Their value will be consed into a list of strings, which will be
  285. returned as the value of the property.
  286. This list is checked after translations have been applied. See
  287. `org-element-keyword-translation-alist'.
  288. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  289. allow multiple occurrences and need not to be in this list.")
  290. (defconst org-element-parsed-keywords '("CAPTION")
  291. "List of affiliated keywords whose value can be parsed.
  292. Their value will be stored as a secondary string: a list of
  293. strings and objects.
  294. This list is checked after translations have been applied. See
  295. `org-element-keyword-translation-alist'.")
  296. (defconst org-element--parsed-properties-alist
  297. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  298. org-element-parsed-keywords)
  299. "Alist of parsed keywords and associated properties.
  300. This is generated from `org-element-parsed-keywords', which
  301. see.")
  302. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  303. "List of affiliated keywords which can have a secondary value.
  304. In Org syntax, they can be written with optional square brackets
  305. before the colons. For example, RESULTS keyword can be
  306. associated to a hash value with the following:
  307. #+RESULTS[hash-string]: some-source
  308. This list is checked after translations have been applied. See
  309. `org-element-keyword-translation-alist'.")
  310. (defconst org-element--affiliated-re
  311. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  312. (concat
  313. ;; Dual affiliated keywords.
  314. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  315. (regexp-opt org-element-dual-keywords))
  316. "\\|"
  317. ;; Regular affiliated keywords.
  318. (format "\\(?1:%s\\)"
  319. (regexp-opt
  320. (cl-remove-if
  321. (lambda (k) (member k org-element-dual-keywords))
  322. org-element-affiliated-keywords)))
  323. "\\|"
  324. ;; Export attributes.
  325. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  326. "Regexp matching any affiliated keyword.
  327. Keyword name is put in match group 1. Moreover, if keyword
  328. belongs to `org-element-dual-keywords', put the dual value in
  329. match group 2.
  330. Don't modify it, set `org-element-affiliated-keywords' instead.")
  331. (defconst org-element-object-restrictions
  332. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  333. subscript superscript underline verbatim))
  334. (standard-set
  335. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  336. (standard-set-no-line-break (remq 'line-break standard-set)))
  337. `((bold ,@standard-set)
  338. (citation citation-reference)
  339. (citation-reference ,@minimal-set)
  340. (footnote-reference ,@standard-set)
  341. (headline ,@standard-set-no-line-break)
  342. (inlinetask ,@standard-set-no-line-break)
  343. (italic ,@standard-set)
  344. (item ,@standard-set-no-line-break)
  345. (keyword ,@(remq 'footnote-reference standard-set))
  346. ;; Ignore all links in a link description. Also ignore
  347. ;; radio-targets and line breaks.
  348. (link export-snippet inline-babel-call inline-src-block macro
  349. statistics-cookie ,@minimal-set)
  350. (paragraph ,@standard-set)
  351. ;; Remove any variable object from radio target as it would
  352. ;; prevent it from being properly recognized.
  353. (radio-target ,@minimal-set)
  354. (strike-through ,@standard-set)
  355. (subscript ,@standard-set)
  356. (superscript ,@standard-set)
  357. ;; Ignore inline babel call and inline source block as formulas
  358. ;; are possible. Also ignore line breaks and statistics
  359. ;; cookies.
  360. (table-cell citation export-snippet footnote-reference link macro
  361. radio-target target timestamp ,@minimal-set)
  362. (table-row table-cell)
  363. (underline ,@standard-set)
  364. (verse-block ,@standard-set)))
  365. "Alist of objects restrictions.
  366. key is an element or object type containing objects and value is
  367. a list of types that can be contained within an element or object
  368. of such type.
  369. This alist also applies to secondary string. For example, an
  370. `headline' type element doesn't directly contain objects, but
  371. still has an entry since one of its properties (`:title') does.")
  372. (defconst org-element-secondary-value-alist
  373. '((citation :prefix :suffix)
  374. (headline :title)
  375. (inlinetask :title)
  376. (item :tag)
  377. (citation-reference :prefix :suffix))
  378. "Alist between element types and locations of secondary values.")
  379. (defconst org-element--pair-round-table
  380. (let ((table (make-char-table 'syntax-table '(2))))
  381. (modify-syntax-entry ?\( "()" table)
  382. (modify-syntax-entry ?\) ")(" table)
  383. table)
  384. "Table used internally to pair only round brackets.")
  385. (defconst org-element--pair-square-table
  386. (let ((table (make-char-table 'syntax-table '(2))))
  387. (modify-syntax-entry ?\[ "(]" table)
  388. (modify-syntax-entry ?\] ")[" table)
  389. table)
  390. "Table used internally to pair only square brackets.")
  391. (defconst org-element--pair-curly-table
  392. (let ((table (make-char-table 'syntax-table '(2))))
  393. (modify-syntax-entry ?\{ "(}" table)
  394. (modify-syntax-entry ?\} "){" table)
  395. table)
  396. "Table used internally to pair only curly brackets.")
  397. (defun org-element--parse-paired-brackets (char)
  398. "Parse paired brackets at point.
  399. CHAR is the opening bracket to consider, as a character. Return
  400. contents between brackets, as a string, or nil. Also move point
  401. past the brackets."
  402. (when (eq char (char-after))
  403. (let ((syntax-table (pcase char
  404. (?\{ org-element--pair-curly-table)
  405. (?\[ org-element--pair-square-table)
  406. (?\( org-element--pair-round-table)
  407. (_ nil)))
  408. (pos (point)))
  409. (when syntax-table
  410. (with-syntax-table syntax-table
  411. (let ((end (ignore-errors (scan-lists pos 1 0))))
  412. (when end
  413. (goto-char end)
  414. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  415. ;;; Accessors and Setters
  416. ;;
  417. ;; Provide four accessors: `org-element-type', `org-element-property'
  418. ;; `org-element-contents' and `org-element-restriction'.
  419. ;;
  420. ;; Setter functions allow modification of elements by side effect.
  421. ;; There is `org-element-put-property', `org-element-set-contents'.
  422. ;; These low-level functions are useful to build a parse tree.
  423. ;;
  424. ;; `org-element-adopt-elements', `org-element-set-element',
  425. ;; `org-element-extract-element' and `org-element-insert-before' are
  426. ;; high-level functions useful to modify a parse tree.
  427. ;;
  428. ;; `org-element-secondary-p' is a predicate used to know if a given
  429. ;; object belongs to a secondary string. `org-element-class' tells if
  430. ;; some parsed data is an element or an object, handling pseudo
  431. ;; elements and objects. `org-element-copy' returns an element or
  432. ;; object, stripping its parent property in the process.
  433. (defsubst org-element-type (element)
  434. "Return type of ELEMENT.
  435. The function returns the type of the element or object provided.
  436. It can also return the following special value:
  437. `plain-text' for a string
  438. `org-data' for a complete document
  439. nil in any other case."
  440. (cond
  441. ((not (consp element)) (and (stringp element) 'plain-text))
  442. ((symbolp (car element)) (car element))))
  443. (defsubst org-element-property (property element)
  444. "Extract the value from the PROPERTY of an ELEMENT."
  445. (if (stringp element) (get-text-property 0 property element)
  446. (plist-get (nth 1 element) property)))
  447. (defsubst org-element-contents (element)
  448. "Extract contents from an ELEMENT."
  449. (cond ((not (consp element)) nil)
  450. ((symbolp (car element)) (nthcdr 2 element))
  451. (t element)))
  452. (defsubst org-element-restriction (element)
  453. "Return restriction associated to ELEMENT.
  454. ELEMENT can be an element, an object or a symbol representing an
  455. element or object type."
  456. (cdr (assq (if (symbolp element) element (org-element-type element))
  457. org-element-object-restrictions)))
  458. (defsubst org-element-put-property (element property value)
  459. "In ELEMENT set PROPERTY to VALUE.
  460. Return modified element."
  461. (if (stringp element) (org-add-props element nil property value)
  462. (setcar (cdr element) (plist-put (nth 1 element) property value))
  463. element))
  464. (defsubst org-element-set-contents (element &rest contents)
  465. "Set ELEMENT's contents to CONTENTS.
  466. Return ELEMENT."
  467. (cond ((null element) contents)
  468. ((not (symbolp (car element))) contents)
  469. ((cdr element) (setcdr (cdr element) contents) element)
  470. (t (nconc element contents))))
  471. (defun org-element-secondary-p (object)
  472. "Non-nil when OBJECT directly belongs to a secondary string.
  473. Return value is the property name, as a keyword, or nil."
  474. (let* ((parent (org-element-property :parent object))
  475. (properties (cdr (assq (org-element-type parent)
  476. org-element-secondary-value-alist))))
  477. (catch 'exit
  478. (dolist (p properties)
  479. (and (memq object (org-element-property p parent))
  480. (throw 'exit p))))))
  481. (defsubst org-element-class (datum &optional parent)
  482. "Return class for ELEMENT, as a symbol.
  483. Class is either `element' or `object'. Optional argument PARENT
  484. is the element or object containing DATUM. It defaults to the
  485. value of DATUM `:parent' property."
  486. (let ((type (org-element-type datum))
  487. (parent (or parent (org-element-property :parent datum))))
  488. (cond
  489. ;; Trivial cases.
  490. ((memq type org-element-all-objects) 'object)
  491. ((memq type org-element-all-elements) 'element)
  492. ;; Special cases.
  493. ((eq type 'org-data) 'element)
  494. ((eq type 'plain-text) 'object)
  495. ((not type) 'object)
  496. ;; Pseudo object or elements. Make a guess about its class.
  497. ;; Basically a pseudo object is contained within another object,
  498. ;; a secondary string or a container element.
  499. ((not parent) 'element)
  500. (t
  501. (let ((parent-type (org-element-type parent)))
  502. (cond ((not parent-type) 'object)
  503. ((memq parent-type org-element-object-containers) 'object)
  504. ((org-element-secondary-p datum) 'object)
  505. (t 'element)))))))
  506. (defsubst org-element-adopt-elements (parent &rest children)
  507. "Append elements to the contents of another element.
  508. PARENT is an element or object. CHILDREN can be elements,
  509. objects, or a strings.
  510. The function takes care of setting `:parent' property for CHILD.
  511. Return parent element."
  512. (declare (indent 1))
  513. (if (not children) parent
  514. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  515. ;; string: parent is the list itself.
  516. (dolist (child children)
  517. (org-element-put-property child :parent (or parent children)))
  518. ;; Add CHILDREN at the end of PARENT contents.
  519. (when parent
  520. (apply #'org-element-set-contents
  521. parent
  522. (nconc (org-element-contents parent) children)))
  523. ;; Return modified PARENT element.
  524. (or parent children)))
  525. (defun org-element-extract-element (element)
  526. "Extract ELEMENT from parse tree.
  527. Remove element from the parse tree by side-effect, and return it
  528. with its `:parent' property stripped out."
  529. (let ((parent (org-element-property :parent element))
  530. (secondary (org-element-secondary-p element)))
  531. (if secondary
  532. (org-element-put-property
  533. parent secondary
  534. (delq element (org-element-property secondary parent)))
  535. (apply #'org-element-set-contents
  536. parent
  537. (delq element (org-element-contents parent))))
  538. ;; Return ELEMENT with its :parent removed.
  539. (org-element-put-property element :parent nil)))
  540. (defun org-element-insert-before (element location)
  541. "Insert ELEMENT before LOCATION in parse tree.
  542. LOCATION is an element, object or string within the parse tree.
  543. Parse tree is modified by side effect."
  544. (let* ((parent (org-element-property :parent location))
  545. (property (org-element-secondary-p location))
  546. (siblings (if property (org-element-property property parent)
  547. (org-element-contents parent)))
  548. ;; Special case: LOCATION is the first element of an
  549. ;; independent secondary string (e.g. :title property). Add
  550. ;; ELEMENT in-place.
  551. (specialp (and (not property)
  552. (eq siblings parent)
  553. (eq (car parent) location))))
  554. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  555. (cond (specialp)
  556. ((or (null siblings) (eq (car siblings) location))
  557. (push element siblings))
  558. ((null location) (nconc siblings (list element)))
  559. (t
  560. (let ((index (cl-position location siblings)))
  561. (unless index (error "No location found to insert element"))
  562. (push element (cdr (nthcdr (1- index) siblings))))))
  563. ;; Store SIBLINGS at appropriate place in parse tree.
  564. (cond
  565. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  566. (property (org-element-put-property parent property siblings))
  567. (t (apply #'org-element-set-contents parent siblings)))
  568. ;; Set appropriate :parent property.
  569. (org-element-put-property element :parent parent)))
  570. (defconst org-element--cache-element-properties
  571. '(:cached
  572. :org-element--cache-sync-key)
  573. "List of element properties used internally by cache.")
  574. (defun org-element-set-element (old new)
  575. "Replace element or object OLD with element or object NEW.
  576. The function takes care of setting `:parent' property for NEW."
  577. ;; Ensure OLD and NEW have the same parent.
  578. (org-element-put-property new :parent (org-element-property :parent old))
  579. (dolist (p org-element--cache-element-properties)
  580. (when (org-element-property p old)
  581. (org-element-put-property new p (org-element-property p old))))
  582. (if (or (memq (org-element-type old) '(plain-text nil))
  583. (memq (org-element-type new) '(plain-text nil)))
  584. ;; We cannot replace OLD with NEW since one of them is not an
  585. ;; object or element. We take the long path.
  586. (progn (org-element-insert-before new old)
  587. (org-element-extract-element old))
  588. ;; Since OLD is going to be changed into NEW by side-effect, first
  589. ;; make sure that every element or object within NEW has OLD as
  590. ;; parent.
  591. (dolist (blob (org-element-contents new))
  592. (org-element-put-property blob :parent old))
  593. ;; Transfer contents.
  594. (apply #'org-element-set-contents old (org-element-contents new))
  595. ;; Overwrite OLD's properties with NEW's.
  596. (setcar (cdr old) (nth 1 new))
  597. ;; Transfer type.
  598. (setcar old (car new))))
  599. (defun org-element-create (type &optional props &rest children)
  600. "Create a new element of type TYPE.
  601. Optional argument PROPS, when non-nil, is a plist defining the
  602. properties of the element. CHILDREN can be elements, objects or
  603. strings."
  604. (apply #'org-element-adopt-elements (list type props) children))
  605. (defun org-element-copy (datum)
  606. "Return a copy of DATUM.
  607. DATUM is an element, object, string or nil. `:parent' property
  608. is cleared and contents are removed in the process."
  609. (when datum
  610. (let ((type (org-element-type datum)))
  611. (pcase type
  612. (`org-data (list 'org-data nil))
  613. (`plain-text (substring-no-properties datum))
  614. (`nil (copy-sequence datum))
  615. (_
  616. (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
  617. ;; We cannot simply return the copies property list. When
  618. ;; DATUM is i.e. a headline, it's property list (`:title'
  619. ;; in case of headline) can contain parsed objects. The
  620. ;; objects will contain `:parent' property set to the DATUM
  621. ;; iteself. When copied, these inner `:parent' propery
  622. ;; values will contain incorrect object decoupled from
  623. ;; DATUM. Changes to the DATUM copy will not longer be
  624. ;; reflected in the `:parent' properties. So, we need to
  625. ;; reassign inner `:parent' propreties to the DATUM copy
  626. ;; explicitly.
  627. (org-element-map element-copy (cons 'plain-text org-element-all-objects)
  628. (lambda (obj) (when (equal datum (org-element-property :parent obj))
  629. (org-element-put-property obj :parent element-copy))))
  630. element-copy))))))
  631. ;;; Greater elements
  632. ;;
  633. ;; For each greater element type, we define a parser and an
  634. ;; interpreter.
  635. ;;
  636. ;; A parser returns the element or object as the list described above.
  637. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  638. ;; every element containing a secondary string (see
  639. ;; `org-element-secondary-value-alist') will accept an optional
  640. ;; argument to toggle parsing of these secondary strings. Moreover,
  641. ;; `item' parser requires current list's structure as its first
  642. ;; element.
  643. ;;
  644. ;; An interpreter accepts two arguments: the list representation of
  645. ;; the element or object, and its contents. The latter may be nil,
  646. ;; depending on the element or object considered. It returns the
  647. ;; appropriate Org syntax, as a string.
  648. ;;
  649. ;; Parsing functions must follow the naming convention:
  650. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  651. ;; defined in `org-element-greater-elements'.
  652. ;;
  653. ;; Similarly, interpreting functions must follow the naming
  654. ;; convention: org-element-TYPE-interpreter.
  655. ;;
  656. ;; With the exception of `headline' and `item' types, greater elements
  657. ;; cannot contain other greater elements of their own type.
  658. ;;
  659. ;; Beside implementing a parser and an interpreter, adding a new
  660. ;; greater element requires tweaking `org-element--current-element'.
  661. ;; Moreover, the newly defined type must be added to both
  662. ;; `org-element-all-elements' and `org-element-greater-elements'.
  663. ;;;; Center Block
  664. (defun org-element-center-block-parser (limit affiliated)
  665. "Parse a center block.
  666. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  667. the buffer position at the beginning of the first affiliated
  668. keyword and CDR is a plist of affiliated keywords along with
  669. their value.
  670. Return a list whose CAR is `center-block' and CDR is a plist
  671. containing `:begin', `:end', `:contents-begin', `:contents-end',
  672. `:post-blank' and `:post-affiliated' keywords.
  673. Assume point is at the beginning of the block."
  674. (let ((case-fold-search t))
  675. (if (not (save-excursion
  676. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  677. ;; Incomplete block: parse it as a paragraph.
  678. (org-element-paragraph-parser limit affiliated)
  679. (let ((block-end-line (match-beginning 0)))
  680. (let* ((begin (car affiliated))
  681. (post-affiliated (point))
  682. ;; Empty blocks have no contents.
  683. (contents-begin (progn (forward-line)
  684. (and (< (point) block-end-line)
  685. (point))))
  686. (contents-end (and contents-begin block-end-line))
  687. (pos-before-blank (progn (goto-char block-end-line)
  688. (forward-line)
  689. (point)))
  690. (end (save-excursion
  691. (skip-chars-forward " \r\t\n" limit)
  692. (if (eobp) (point) (line-beginning-position)))))
  693. (list 'center-block
  694. (nconc
  695. (list :begin begin
  696. :end end
  697. :contents-begin contents-begin
  698. :contents-end contents-end
  699. :post-blank (count-lines pos-before-blank end)
  700. :post-affiliated post-affiliated)
  701. (cdr affiliated))))))))
  702. (defun org-element-center-block-interpreter (_ contents)
  703. "Interpret a center-block element as Org syntax.
  704. CONTENTS is the contents of the element."
  705. (format "#+begin_center\n%s#+end_center" contents))
  706. ;;;; Drawer
  707. (defun org-element-drawer-parser (limit affiliated)
  708. "Parse a drawer.
  709. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  710. the buffer position at the beginning of the first affiliated
  711. keyword and CDR is a plist of affiliated keywords along with
  712. their value.
  713. Return a list whose CAR is `drawer' and CDR is a plist containing
  714. `:drawer-name', `:begin', `:end', `:contents-begin',
  715. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  716. Assume point is at beginning of drawer."
  717. (let ((case-fold-search t))
  718. (if (not (save-excursion
  719. (goto-char (min limit (line-end-position)))
  720. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  721. ;; Incomplete drawer: parse it as a paragraph.
  722. (org-element-paragraph-parser limit affiliated)
  723. (save-excursion
  724. (let* ((drawer-end-line (match-beginning 0))
  725. (name
  726. (progn
  727. (looking-at org-element-drawer-re)
  728. (match-string-no-properties 1)))
  729. (begin (car affiliated))
  730. (post-affiliated (point))
  731. ;; Empty drawers have no contents.
  732. (contents-begin (progn (forward-line)
  733. (and (< (point) drawer-end-line)
  734. (point))))
  735. (contents-end (and contents-begin drawer-end-line))
  736. (pos-before-blank (progn (goto-char drawer-end-line)
  737. (forward-line)
  738. (point)))
  739. (end (progn (skip-chars-forward " \r\t\n" limit)
  740. (if (eobp) (point) (line-beginning-position)))))
  741. (list 'drawer
  742. (nconc
  743. (list :begin begin
  744. :end end
  745. :drawer-name name
  746. :contents-begin contents-begin
  747. :contents-end contents-end
  748. :post-blank (count-lines pos-before-blank end)
  749. :post-affiliated post-affiliated)
  750. (cdr affiliated))))))))
  751. (defun org-element-drawer-interpreter (drawer contents)
  752. "Interpret DRAWER element as Org syntax.
  753. CONTENTS is the contents of the element."
  754. (format ":%s:\n%s:END:"
  755. (org-element-property :drawer-name drawer)
  756. contents))
  757. ;;;; Dynamic Block
  758. (defun org-element-dynamic-block-parser (limit affiliated)
  759. "Parse a dynamic block.
  760. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  761. the buffer position at the beginning of the first affiliated
  762. keyword and CDR is a plist of affiliated keywords along with
  763. their value.
  764. Return a list whose CAR is `dynamic-block' and CDR is a plist
  765. containing `:block-name', `:begin', `:end', `:contents-begin',
  766. `:contents-end', `:arguments', `:post-blank' and
  767. `:post-affiliated' keywords.
  768. Assume point is at beginning of dynamic block."
  769. (let ((case-fold-search t))
  770. (if (not (save-excursion
  771. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  772. ;; Incomplete block: parse it as a paragraph.
  773. (org-element-paragraph-parser limit affiliated)
  774. (let ((block-end-line (match-beginning 0)))
  775. (save-excursion
  776. (let* ((name (progn
  777. (looking-at org-element-dynamic-block-open-re)
  778. (match-string-no-properties 1)))
  779. (arguments (match-string-no-properties 2))
  780. (begin (car affiliated))
  781. (post-affiliated (point))
  782. ;; Empty blocks have no contents.
  783. (contents-begin (progn (forward-line)
  784. (and (< (point) block-end-line)
  785. (point))))
  786. (contents-end (and contents-begin block-end-line))
  787. (pos-before-blank (progn (goto-char block-end-line)
  788. (forward-line)
  789. (point)))
  790. (end (progn (skip-chars-forward " \r\t\n" limit)
  791. (if (eobp) (point) (line-beginning-position)))))
  792. (list 'dynamic-block
  793. (nconc
  794. (list :begin begin
  795. :end end
  796. :block-name name
  797. :arguments arguments
  798. :contents-begin contents-begin
  799. :contents-end contents-end
  800. :post-blank (count-lines pos-before-blank end)
  801. :post-affiliated post-affiliated)
  802. (cdr affiliated)))))))))
  803. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  804. "Interpret DYNAMIC-BLOCK element as Org syntax.
  805. CONTENTS is the contents of the element."
  806. (format "#+begin: %s%s\n%s#+end:"
  807. (org-element-property :block-name dynamic-block)
  808. (let ((args (org-element-property :arguments dynamic-block)))
  809. (if args (concat " " args) ""))
  810. contents))
  811. ;;;; Footnote Definition
  812. (defconst org-element--footnote-separator
  813. (concat org-element-headline-re "\\|"
  814. org-footnote-definition-re "\\|"
  815. "^\\([ \t]*\n\\)\\{2,\\}")
  816. "Regexp used as a footnote definition separator.")
  817. (defun org-element-footnote-definition-parser (limit affiliated)
  818. "Parse a footnote definition.
  819. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  820. the buffer position at the beginning of the first affiliated
  821. keyword and CDR is a plist of affiliated keywords along with
  822. their value.
  823. Return a list whose CAR is `footnote-definition' and CDR is
  824. a plist containing `:label', `:begin' `:end', `:contents-begin',
  825. `:contents-end', `:pre-blank',`:post-blank' and
  826. `:post-affiliated' keywords.
  827. Assume point is at the beginning of the footnote definition."
  828. (save-excursion
  829. (let* ((label (progn (looking-at org-footnote-definition-re)
  830. (match-string-no-properties 1)))
  831. (begin (car affiliated))
  832. (post-affiliated (point))
  833. (end
  834. (save-excursion
  835. (end-of-line)
  836. (cond
  837. ((not
  838. (re-search-forward org-element--footnote-separator limit t))
  839. limit)
  840. ((eq ?\[ (char-after (match-beginning 0)))
  841. ;; At a new footnote definition, make sure we end
  842. ;; before any affiliated keyword above.
  843. (forward-line -1)
  844. (while (and (> (point) post-affiliated)
  845. (looking-at-p org-element--affiliated-re))
  846. (forward-line -1))
  847. (line-beginning-position 2))
  848. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  849. (t (skip-chars-forward " \r\t\n" limit)
  850. (if (= limit (point)) limit (line-beginning-position))))))
  851. (pre-blank 0)
  852. (contents-begin
  853. (progn (search-forward "]")
  854. (skip-chars-forward " \r\t\n" end)
  855. (cond ((= (point) end) nil)
  856. ((= (line-beginning-position) post-affiliated) (point))
  857. (t
  858. (setq pre-blank
  859. (count-lines (line-beginning-position) begin))
  860. (line-beginning-position)))))
  861. (contents-end
  862. (progn (goto-char end)
  863. (skip-chars-backward " \r\t\n")
  864. (line-beginning-position 2))))
  865. (list 'footnote-definition
  866. (nconc
  867. (list :label label
  868. :begin begin
  869. :end end
  870. :contents-begin contents-begin
  871. :contents-end (and contents-begin contents-end)
  872. :pre-blank pre-blank
  873. :post-blank (count-lines contents-end end)
  874. :post-affiliated post-affiliated)
  875. (cdr affiliated))))))
  876. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  877. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  878. CONTENTS is the contents of the footnote-definition."
  879. (let ((pre-blank
  880. (min (or (org-element-property :pre-blank footnote-definition)
  881. ;; 0 is specific to paragraphs at the beginning of
  882. ;; the footnote definition, so we use 1 as
  883. ;; a fall-back value, which is more universal.
  884. 1)
  885. ;; Footnote ends after more than two consecutive empty
  886. ;; lines: limit ourselves to 2 newline characters.
  887. 2)))
  888. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  889. (if (= pre-blank 0) (concat " " (org-trim contents))
  890. (concat (make-string pre-blank ?\n) contents)))))
  891. ;;;; Headline
  892. (defun org-element--get-node-properties (&optional at-point-p?)
  893. "Return node properties for headline or property drawer at point.
  894. Upcase property names. It avoids confusion between properties
  895. obtained through property drawer and default properties from the
  896. parser (e.g. `:end' and :END:). Return value is a plist.
  897. When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
  898. parse properties for property drawer at point."
  899. (save-excursion
  900. (unless at-point-p?
  901. (forward-line)
  902. (when (looking-at-p org-element-planning-line-re) (forward-line)))
  903. (when (looking-at org-property-drawer-re)
  904. (forward-line)
  905. (let ((end (match-end 0)) properties)
  906. (while (< (line-end-position) end)
  907. (looking-at org-property-re)
  908. (let* ((property-name (concat ":" (upcase (match-string 2))))
  909. (property-name-symbol (intern property-name))
  910. (property-value (match-string-no-properties 3)))
  911. (cond
  912. ((and (plist-member properties property-name-symbol)
  913. (string-match-p "+$" property-name))
  914. (let ((val (plist-get properties property-name-symbol)))
  915. (if (listp val)
  916. (setq properties
  917. (plist-put properties
  918. property-name-symbol
  919. (append (plist-get properties property-name-symbol)
  920. (list property-value))))
  921. (plist-put properties property-name-symbol (list val property-value)))))
  922. (t (setq properties (plist-put properties property-name-symbol property-value)))))
  923. (forward-line))
  924. properties))))
  925. (defun org-element--get-time-properties ()
  926. "Return time properties associated to headline at point.
  927. Return value is a plist."
  928. (save-excursion
  929. (when (progn (forward-line) (looking-at org-element-planning-line-re))
  930. (let ((end (line-end-position))
  931. plist)
  932. (while (re-search-forward org-element-planning-keywords-re end t)
  933. (skip-chars-forward " \t")
  934. (let ((keyword (match-string 0))
  935. (time (org-element-timestamp-parser)))
  936. (cond ((equal keyword org-element-scheduled-keyword)
  937. (setq plist (plist-put plist :scheduled time)))
  938. ((equal keyword org-element-deadline-keyword)
  939. (setq plist (plist-put plist :deadline time)))
  940. (t (setq plist (plist-put plist :closed time))))))
  941. plist))))
  942. (defun org-element-headline-parser (&optional _ raw-secondary-p)
  943. "Parse a headline.
  944. Return a list whose CAR is `headline' and CDR is a plist
  945. containing `:raw-value', `:title', `:begin', `:end',
  946. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  947. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  948. `:deadline', `:closed', `:archivedp', `:commentedp'
  949. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  950. keywords.
  951. The plist also contains any property set in the property drawer,
  952. with its name in upper cases and colons added at the
  953. beginning (e.g., `:CUSTOM_ID').
  954. When RAW-SECONDARY-P is non-nil, headline's title will not be
  955. parsed as a secondary string, but as a plain string instead.
  956. Assume point is at beginning of the headline."
  957. (save-excursion
  958. (let* ((begin (point))
  959. (true-level (prog1 (skip-chars-forward "*")
  960. (skip-chars-forward " \t")))
  961. (level (org-reduced-level true-level))
  962. (todo (and org-todo-regexp
  963. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  964. (progn (goto-char (match-end 0))
  965. (skip-chars-forward " \t")
  966. (match-string 1))))
  967. (todo-type
  968. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  969. (priority (and (looking-at "\\[#.\\][ \t]*")
  970. (progn (goto-char (match-end 0))
  971. (aref (match-string 0) 2))))
  972. (commentedp
  973. (and (let ((case-fold-search nil))
  974. (looking-at org-element-comment-string))
  975. (goto-char (match-end 0))))
  976. (title-start (prog1 (point)
  977. (unless (or todo priority commentedp)
  978. ;; Headline like "* :tag:"
  979. (skip-chars-backward " \t"))))
  980. (tags (when (re-search-forward
  981. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  982. (line-end-position)
  983. 'move)
  984. (goto-char (match-beginning 0))
  985. (org-split-string (match-string 1) ":")))
  986. (title-end (point))
  987. (raw-value (org-trim
  988. (buffer-substring-no-properties title-start title-end)))
  989. (archivedp (member org-element-archive-tag tags))
  990. (footnote-section-p (and org-footnote-section
  991. (string= org-footnote-section raw-value)))
  992. (standard-props (org-element--get-node-properties))
  993. (time-props (org-element--get-time-properties))
  994. (end
  995. (save-excursion
  996. (let ((re (rx-to-string
  997. `(seq line-start (** 1 ,true-level "*") " "))))
  998. (if (re-search-forward re nil t)
  999. (line-beginning-position)
  1000. (point-max)))))
  1001. (contents-begin (save-excursion
  1002. (forward-line)
  1003. (skip-chars-forward " \r\t\n" end)
  1004. (and (/= (point) end) (line-beginning-position))))
  1005. (contents-end (and contents-begin
  1006. (progn (goto-char end)
  1007. (skip-chars-backward " \r\t\n")
  1008. (line-beginning-position 2))))
  1009. (robust-begin (and contents-begin
  1010. (progn (goto-char contents-begin)
  1011. (when (looking-at-p org-element-planning-line-re)
  1012. (forward-line))
  1013. (when (looking-at org-property-drawer-re)
  1014. (goto-char (match-end 0)))
  1015. ;; If there is :pre-blank, we
  1016. ;; need to be careful about
  1017. ;; robust beginning.
  1018. (max (if (< (+ 2 contents-begin) contents-end)
  1019. (+ 2 contents-begin)
  1020. 0)
  1021. (point)))))
  1022. (robust-end (and robust-begin
  1023. (when (> (- contents-end 2) robust-begin)
  1024. (- contents-end 2)))))
  1025. (unless robust-end (setq robust-begin nil))
  1026. (let ((headline
  1027. (list 'headline
  1028. (nconc
  1029. (list :raw-value raw-value
  1030. :begin begin
  1031. :end end
  1032. :pre-blank
  1033. (if (not contents-begin) 0
  1034. (1- (count-lines begin contents-begin)))
  1035. :contents-begin contents-begin
  1036. :contents-end contents-end
  1037. :robust-begin robust-begin
  1038. :robust-end robust-end
  1039. :level level
  1040. :priority priority
  1041. :tags tags
  1042. :todo-keyword todo
  1043. :todo-type todo-type
  1044. :post-blank
  1045. (if contents-end
  1046. (count-lines contents-end end)
  1047. (1- (count-lines begin end)))
  1048. :footnote-section-p footnote-section-p
  1049. :archivedp archivedp
  1050. :commentedp commentedp
  1051. :post-affiliated begin)
  1052. time-props
  1053. standard-props))))
  1054. (org-element-put-property
  1055. headline :title
  1056. (if raw-secondary-p raw-value
  1057. (org-element--parse-objects
  1058. (progn (goto-char title-start)
  1059. (skip-chars-forward " \t")
  1060. (point))
  1061. (progn (goto-char title-end)
  1062. (skip-chars-backward " \t")
  1063. (point))
  1064. nil
  1065. (org-element-restriction 'headline)
  1066. headline)))))))
  1067. (defun org-element-headline-interpreter (headline contents)
  1068. "Interpret HEADLINE element as Org syntax.
  1069. CONTENTS is the contents of the element."
  1070. (let* ((level (org-element-property :level headline))
  1071. (todo (org-element-property :todo-keyword headline))
  1072. (priority (org-element-property :priority headline))
  1073. (title (org-element-interpret-data
  1074. (org-element-property :title headline)))
  1075. (tags (let ((tag-list (org-element-property :tags headline)))
  1076. (and tag-list
  1077. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  1078. (commentedp (org-element-property :commentedp headline))
  1079. (pre-blank (or (org-element-property :pre-blank headline) 0))
  1080. (heading
  1081. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  1082. ?*)
  1083. (and todo (concat " " todo))
  1084. (and commentedp (concat " " org-element-comment-string))
  1085. (and priority (format " [#%c]" priority))
  1086. " "
  1087. (if (and org-footnote-section
  1088. (org-element-property :footnote-section-p headline))
  1089. org-footnote-section
  1090. title))))
  1091. (concat
  1092. heading
  1093. ;; Align tags.
  1094. (when tags
  1095. (cond
  1096. ((zerop org-tags-column) (format " %s" tags))
  1097. ((< org-tags-column 0)
  1098. (concat
  1099. (make-string
  1100. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1101. ?\s)
  1102. tags))
  1103. (t
  1104. (concat
  1105. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1106. tags))))
  1107. (make-string (1+ pre-blank) ?\n)
  1108. contents)))
  1109. ;;;; org-data
  1110. (defun org-element--get-global-node-properties ()
  1111. "Return node properties associated with the whole Org buffer.
  1112. Upcase property names. It avoids confusion between properties
  1113. obtained through property drawer and default properties from the
  1114. parser (e.g. `:end' and :END:). Return value is a plist."
  1115. (org-with-wide-buffer
  1116. (goto-char (point-min))
  1117. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1118. (org-element--get-node-properties t)))
  1119. (defvar org-element-org-data-parser--recurse nil)
  1120. (defun org-element-org-data-parser (&optional _)
  1121. "Parse org-data."
  1122. (org-with-wide-buffer
  1123. (let* ((begin 1)
  1124. (contents-begin (progn
  1125. (goto-char 1)
  1126. (org-skip-whitespace)
  1127. (beginning-of-line)
  1128. (point)))
  1129. (end (point-max))
  1130. (pos-before-blank (progn (goto-char (point-max))
  1131. (skip-chars-backward " \r\t\n")
  1132. (line-beginning-position 2)))
  1133. (robust-end (when (> (- pos-before-blank 2) contents-begin)
  1134. (- pos-before-blank 2)))
  1135. (robust-begin (when (and robust-end
  1136. (< (+ 2 contents-begin) pos-before-blank))
  1137. (or
  1138. (org-with-wide-buffer
  1139. (goto-char (point-min))
  1140. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1141. (when (looking-at org-property-drawer-re)
  1142. (goto-char (match-end 0))
  1143. (skip-chars-backward " \t")
  1144. (min robust-end (point))))
  1145. (+ 2 contents-begin))))
  1146. (category (cond ((null org-category)
  1147. (when (with-current-buffer
  1148. (or (buffer-base-buffer)
  1149. (current-buffer))
  1150. buffer-file-name)
  1151. (file-name-sans-extension
  1152. (file-name-nondirectory
  1153. (with-current-buffer
  1154. (or (buffer-base-buffer)
  1155. (current-buffer))
  1156. buffer-file-name)))))
  1157. ((symbolp org-category) (symbol-name org-category))
  1158. (t org-category)))
  1159. (category (catch 'buffer-category
  1160. (unless org-element-org-data-parser--recurse
  1161. (org-with-point-at end
  1162. ;; Avoid recusrive calls from
  1163. ;; `org-element-at-point-no-context'.
  1164. (let ((org-element-org-data-parser--recurse t))
  1165. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  1166. (org-element-with-disabled-cache
  1167. (let ((element (org-element-at-point-no-context)))
  1168. (when (eq (org-element-type element) 'keyword)
  1169. (throw 'buffer-category
  1170. (org-element-property :value element)))))))))
  1171. category))
  1172. (properties (org-element--get-global-node-properties)))
  1173. (unless (plist-get properties :CATEGORY)
  1174. (setq properties (plist-put properties :CATEGORY category)))
  1175. (list 'org-data
  1176. (nconc
  1177. (list :begin begin
  1178. :contents-begin contents-begin
  1179. :contents-end pos-before-blank
  1180. :end end
  1181. :robust-begin robust-begin
  1182. :robust-end robust-end
  1183. :post-blank (count-lines pos-before-blank end)
  1184. :post-affiliated begin
  1185. :path (buffer-file-name)
  1186. :mode 'org-data)
  1187. properties)))))
  1188. (defun org-element-org-data-interpreter (_ contents)
  1189. "Interpret ORG-DATA element as Org syntax.
  1190. CONTENTS is the contents of the element."
  1191. contents)
  1192. ;;;; Inlinetask
  1193. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1194. "Parse an inline task.
  1195. Return a list whose CAR is `inlinetask' and CDR is a plist
  1196. containing `:title', `:begin', `:end', `:pre-blank',
  1197. `:contents-begin' and `:contents-end', `:level', `:priority',
  1198. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1199. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1200. `:post-affiliated' keywords.
  1201. The plist also contains any property set in the property drawer,
  1202. with its name in upper cases and colons added at the
  1203. beginning (e.g., `:CUSTOM_ID').
  1204. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1205. title will not be parsed as a secondary string, but as a plain
  1206. string instead.
  1207. Assume point is at beginning of the inline task."
  1208. (save-excursion
  1209. (let* ((begin (point))
  1210. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1211. (skip-chars-forward " \t")))
  1212. (todo (and org-todo-regexp
  1213. (let (case-fold-search) (looking-at org-todo-regexp))
  1214. (progn (goto-char (match-end 0))
  1215. (skip-chars-forward " \t")
  1216. (match-string 0))))
  1217. (todo-type (and todo
  1218. (if (member todo org-done-keywords) 'done 'todo)))
  1219. (priority (and (looking-at "\\[#.\\][ \t]*")
  1220. (progn (goto-char (match-end 0))
  1221. (aref (match-string 0) 2))))
  1222. (title-start (point))
  1223. (tags (when (re-search-forward
  1224. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1225. (line-end-position)
  1226. 'move)
  1227. (goto-char (match-beginning 0))
  1228. (org-split-string (match-string 1) ":")))
  1229. (title-end (point))
  1230. (raw-value (org-trim
  1231. (buffer-substring-no-properties title-start title-end)))
  1232. (task-end (save-excursion
  1233. (end-of-line)
  1234. (and (re-search-forward org-element-headline-re limit t)
  1235. (looking-at-p "[ \t]*END[ \t]*$")
  1236. (line-beginning-position))))
  1237. (standard-props (and task-end (org-element--get-node-properties)))
  1238. (time-props (and task-end (org-element--get-time-properties)))
  1239. (contents-begin (and task-end
  1240. (< (point) task-end)
  1241. (progn
  1242. (forward-line)
  1243. (skip-chars-forward " \t\n")
  1244. (line-beginning-position))))
  1245. (contents-end (and contents-begin task-end))
  1246. (end (progn (when task-end (goto-char task-end))
  1247. (forward-line)
  1248. (skip-chars-forward " \r\t\n" limit)
  1249. (if (eobp) (point) (line-beginning-position))))
  1250. (inlinetask
  1251. (list 'inlinetask
  1252. (nconc
  1253. (list :raw-value raw-value
  1254. :begin begin
  1255. :end end
  1256. :pre-blank
  1257. (if (not contents-begin) 0
  1258. (1- (count-lines begin contents-begin)))
  1259. :contents-begin contents-begin
  1260. :contents-end contents-end
  1261. :level level
  1262. :priority priority
  1263. :tags tags
  1264. :todo-keyword todo
  1265. :todo-type todo-type
  1266. :post-blank (1- (count-lines (or task-end begin) end))
  1267. :post-affiliated begin)
  1268. time-props
  1269. standard-props))))
  1270. (org-element-put-property
  1271. inlinetask :title
  1272. (if raw-secondary-p raw-value
  1273. (org-element--parse-objects
  1274. (progn (goto-char title-start)
  1275. (skip-chars-forward " \t")
  1276. (point))
  1277. (progn (goto-char title-end)
  1278. (skip-chars-backward " \t")
  1279. (point))
  1280. nil
  1281. (org-element-restriction 'inlinetask)
  1282. inlinetask))))))
  1283. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1284. "Interpret INLINETASK element as Org syntax.
  1285. CONTENTS is the contents of inlinetask."
  1286. (let* ((level (org-element-property :level inlinetask))
  1287. (todo (org-element-property :todo-keyword inlinetask))
  1288. (priority (org-element-property :priority inlinetask))
  1289. (title (org-element-interpret-data
  1290. (org-element-property :title inlinetask)))
  1291. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1292. (and tag-list
  1293. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1294. (task (concat (make-string level ?*)
  1295. (and todo (concat " " todo))
  1296. (and priority (format " [#%c]" priority))
  1297. (and title (concat " " title)))))
  1298. (concat task
  1299. ;; Align tags.
  1300. (when tags
  1301. (cond
  1302. ((zerop org-tags-column) (format " %s" tags))
  1303. ((< org-tags-column 0)
  1304. (concat
  1305. (make-string
  1306. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1307. ?\s)
  1308. tags))
  1309. (t
  1310. (concat
  1311. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1312. tags))))
  1313. ;; Prefer degenerate inlinetasks when there are no
  1314. ;; contents.
  1315. (when contents
  1316. (concat "\n"
  1317. contents
  1318. (make-string level ?*) " end")))))
  1319. ;;;; Item
  1320. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1321. "Parse an item.
  1322. STRUCT is the structure of the plain list.
  1323. Return a list whose CAR is `item' and CDR is a plist containing
  1324. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1325. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1326. `:post-blank' and `:post-affiliated' keywords.
  1327. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1328. any, will not be parsed as a secondary string, but as a plain
  1329. string instead.
  1330. Assume point is at the beginning of the item."
  1331. (save-excursion
  1332. (beginning-of-line)
  1333. (looking-at org-list-full-item-re)
  1334. (let* ((begin (point))
  1335. (bullet (match-string-no-properties 1))
  1336. (checkbox (let ((box (match-string 3)))
  1337. (cond ((equal "[ ]" box) 'off)
  1338. ((equal "[X]" box) 'on)
  1339. ((equal "[-]" box) 'trans))))
  1340. (counter (let ((c (match-string 2)))
  1341. (save-match-data
  1342. (cond
  1343. ((not c) nil)
  1344. ((string-match "[A-Za-z]" c)
  1345. (- (string-to-char (upcase (match-string 0 c)))
  1346. 64))
  1347. ((string-match "[0-9]+" c)
  1348. (string-to-number (match-string 0 c)))))))
  1349. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1350. (if (bolp) (point) (line-beginning-position 2))))
  1351. (pre-blank 0)
  1352. (contents-begin
  1353. (progn
  1354. (goto-char
  1355. ;; Ignore tags in un-ordered lists: they are just
  1356. ;; a part of item's body.
  1357. (if (and (match-beginning 4)
  1358. (save-match-data (string-match "[.)]" bullet)))
  1359. (match-beginning 4)
  1360. (match-end 0)))
  1361. (skip-chars-forward " \r\t\n" end)
  1362. (cond ((= (point) end) nil)
  1363. ;; If first line isn't empty, contents really
  1364. ;; start at the text after item's meta-data.
  1365. ((= (line-beginning-position) begin) (point))
  1366. (t
  1367. (setq pre-blank
  1368. (count-lines (line-beginning-position) begin))
  1369. (line-beginning-position)))))
  1370. (contents-end (and contents-begin
  1371. (progn (goto-char end)
  1372. (skip-chars-backward " \r\t\n")
  1373. (line-beginning-position 2))))
  1374. (item
  1375. (list 'item
  1376. (list :bullet bullet
  1377. :begin begin
  1378. :end end
  1379. :contents-begin contents-begin
  1380. :contents-end contents-end
  1381. :checkbox checkbox
  1382. :counter counter
  1383. :structure struct
  1384. :pre-blank pre-blank
  1385. :post-blank (count-lines (or contents-end begin) end)
  1386. :post-affiliated begin))))
  1387. (org-element-put-property
  1388. item :tag
  1389. (let ((raw (org-list-get-tag begin struct)))
  1390. (when raw
  1391. (if raw-secondary-p raw
  1392. (org-element--parse-objects
  1393. (match-beginning 4) (match-end 4) nil
  1394. (org-element-restriction 'item)
  1395. item))))))))
  1396. (defun org-element-item-interpreter (item contents)
  1397. "Interpret ITEM element as Org syntax.
  1398. CONTENTS is the contents of the element."
  1399. (let ((tag (pcase (org-element-property :tag item)
  1400. (`nil nil)
  1401. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1402. (bullet
  1403. (org-list-bullet-string
  1404. (cond
  1405. ((not (string-match-p "[0-9a-zA-Z]"
  1406. (org-element-property :bullet item))) "- ")
  1407. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1408. (t "1.")))))
  1409. (concat
  1410. bullet
  1411. (pcase (org-element-property :counter item)
  1412. (`nil nil)
  1413. (counter (format "[@%d] " counter)))
  1414. (pcase (org-element-property :checkbox item)
  1415. (`on "[X] ")
  1416. (`off "[ ] ")
  1417. (`trans "[-] ")
  1418. (_ nil))
  1419. tag
  1420. (when contents
  1421. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1422. (pre-blank
  1423. (min (or (org-element-property :pre-blank item)
  1424. ;; 0 is specific to paragraphs at the
  1425. ;; beginning of the item, so we use 1 as
  1426. ;; a fall-back value, which is more universal.
  1427. 1)
  1428. ;; Lists ends after more than two consecutive
  1429. ;; empty lines: limit ourselves to 2 newline
  1430. ;; characters.
  1431. 2))
  1432. (contents (replace-regexp-in-string
  1433. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1434. (if (= pre-blank 0) (org-trim contents)
  1435. (concat (make-string pre-blank ?\n) contents)))))))
  1436. ;;;; Plain List
  1437. (defun org-element--list-struct (limit)
  1438. ;; Return structure of list at point. Internal function. See
  1439. ;; `org-list-struct' for details.
  1440. (let ((case-fold-search t)
  1441. (top-ind limit)
  1442. (item-re (org-item-re))
  1443. (inlinetask-re (and (featurep 'org-inlinetask)
  1444. (boundp 'org-inlinetask-min-level)
  1445. (boundp 'org-inlinetask-max-level)
  1446. (format "^\\*\\{%d,%d\\}+ "
  1447. org-inlinetask-min-level
  1448. org-inlinetask-max-level)))
  1449. items struct)
  1450. (save-excursion
  1451. (catch :exit
  1452. (while t
  1453. (cond
  1454. ;; At limit: end all items.
  1455. ((>= (point) limit)
  1456. (let ((end (progn (skip-chars-backward " \r\t\n")
  1457. (line-beginning-position 2))))
  1458. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1459. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1460. ;; At list end: end all items.
  1461. ((looking-at org-list-end-re)
  1462. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1463. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1464. ;; At a new item: end previous sibling.
  1465. ((looking-at item-re)
  1466. (let ((ind (save-excursion (skip-chars-forward " \t")
  1467. (current-column))))
  1468. (setq top-ind (min top-ind ind))
  1469. (while (and items (<= ind (nth 1 (car items))))
  1470. (let ((item (pop items)))
  1471. (setcar (nthcdr 6 item) (point))
  1472. (push item struct)))
  1473. (push (progn (looking-at org-list-full-item-re)
  1474. (let ((bullet (match-string-no-properties 1)))
  1475. (list (point)
  1476. ind
  1477. bullet
  1478. (match-string-no-properties 2) ; counter
  1479. (match-string-no-properties 3) ; checkbox
  1480. ;; Description tag.
  1481. (and (save-match-data
  1482. (string-match "[-+*]" bullet))
  1483. (match-string-no-properties 4))
  1484. ;; Ending position, unknown so far.
  1485. nil)))
  1486. items))
  1487. (forward-line))
  1488. ;; Skip empty lines.
  1489. ((looking-at "^[ \t]*$") (forward-line))
  1490. ;; Skip inline tasks and blank lines along the way.
  1491. ((and inlinetask-re (looking-at inlinetask-re))
  1492. (forward-line)
  1493. (let ((origin (point)))
  1494. (when (re-search-forward inlinetask-re limit t)
  1495. (if (looking-at-p "END[ \t]*$") (forward-line)
  1496. (goto-char origin)))))
  1497. ;; At some text line. Check if it ends any previous item.
  1498. (t
  1499. (let ((ind (save-excursion
  1500. (skip-chars-forward " \t")
  1501. (current-column)))
  1502. (end (save-excursion
  1503. (skip-chars-backward " \r\t\n")
  1504. (line-beginning-position 2))))
  1505. (while (<= ind (nth 1 (car items)))
  1506. (let ((item (pop items)))
  1507. (setcar (nthcdr 6 item) end)
  1508. (push item struct)
  1509. (unless items
  1510. (throw :exit (sort struct #'car-less-than-car))))))
  1511. ;; Skip blocks (any type) and drawers contents.
  1512. (cond
  1513. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1514. (re-search-forward
  1515. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1516. limit t)))
  1517. ((and (looking-at org-element-drawer-re)
  1518. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1519. (forward-line))))))))
  1520. (defun org-element-plain-list-parser (limit affiliated structure)
  1521. "Parse a plain list.
  1522. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1523. the buffer position at the beginning of the first affiliated
  1524. keyword and CDR is a plist of affiliated keywords along with
  1525. their value. STRUCTURE is the structure of the plain list being
  1526. parsed.
  1527. Return a list whose CAR is `plain-list' and CDR is a plist
  1528. containing `:type', `:begin', `:end', `:contents-begin' and
  1529. `:contents-end', `:structure', `:post-blank' and
  1530. `:post-affiliated' keywords.
  1531. Assume point is at the beginning of the list."
  1532. (save-excursion
  1533. (let* ((struct (or structure (org-element--list-struct limit)))
  1534. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1535. ((nth 5 (assq (point) struct)) 'descriptive)
  1536. (t 'unordered)))
  1537. (contents-begin (point))
  1538. (begin (car affiliated))
  1539. (contents-end (let* ((item (assq contents-begin struct))
  1540. (ind (nth 1 item))
  1541. (pos (nth 6 item)))
  1542. (while (and (setq item (assq pos struct))
  1543. (= (nth 1 item) ind))
  1544. (setq pos (nth 6 item)))
  1545. pos))
  1546. (end (progn (goto-char contents-end)
  1547. (skip-chars-forward " \r\t\n" limit)
  1548. (if (= (point) limit) limit (line-beginning-position)))))
  1549. ;; Return value.
  1550. (list 'plain-list
  1551. (nconc
  1552. (list :type type
  1553. :begin begin
  1554. :end end
  1555. :contents-begin contents-begin
  1556. :contents-end contents-end
  1557. :structure struct
  1558. :post-blank (count-lines contents-end end)
  1559. :post-affiliated contents-begin)
  1560. (cdr affiliated))))))
  1561. (defun org-element-plain-list-interpreter (_ contents)
  1562. "Interpret plain-list element as Org syntax.
  1563. CONTENTS is the contents of the element."
  1564. (with-temp-buffer
  1565. (insert contents)
  1566. (goto-char (point-min))
  1567. (org-list-repair)
  1568. (buffer-string)))
  1569. ;;;; Property Drawer
  1570. (defun org-element-property-drawer-parser (limit)
  1571. "Parse a property drawer.
  1572. LIMIT bounds the search.
  1573. Return a list whose car is `property-drawer' and cdr is a plist
  1574. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1575. `:post-blank' and `:post-affiliated' keywords.
  1576. Assume point is at the beginning of the property drawer."
  1577. (save-excursion
  1578. (let ((case-fold-search t)
  1579. (begin (point))
  1580. (contents-begin (line-beginning-position 2)))
  1581. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1582. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1583. (match-beginning 0)))
  1584. (before-blank (progn (forward-line) (point)))
  1585. (end (progn (skip-chars-forward " \r\t\n" limit)
  1586. (if (eobp) (point) (line-beginning-position)))))
  1587. (list 'property-drawer
  1588. (list :begin begin
  1589. :end end
  1590. :contents-begin (and contents-end contents-begin)
  1591. :contents-end contents-end
  1592. :post-blank (count-lines before-blank end)
  1593. :post-affiliated begin))))))
  1594. (defun org-element-property-drawer-interpreter (_ contents)
  1595. "Interpret property-drawer element as Org syntax.
  1596. CONTENTS is the properties within the drawer."
  1597. (format ":PROPERTIES:\n%s:END:" contents))
  1598. ;;;; Quote Block
  1599. (defun org-element-quote-block-parser (limit affiliated)
  1600. "Parse a quote block.
  1601. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1602. the buffer position at the beginning of the first affiliated
  1603. keyword and CDR is a plist of affiliated keywords along with
  1604. their value.
  1605. Return a list whose CAR is `quote-block' and CDR is a plist
  1606. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1607. `:post-blank' and `:post-affiliated' keywords.
  1608. Assume point is at the beginning of the block."
  1609. (let ((case-fold-search t))
  1610. (if (not (save-excursion
  1611. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1612. ;; Incomplete block: parse it as a paragraph.
  1613. (org-element-paragraph-parser limit affiliated)
  1614. (let ((block-end-line (match-beginning 0)))
  1615. (save-excursion
  1616. (let* ((begin (car affiliated))
  1617. (post-affiliated (point))
  1618. ;; Empty blocks have no contents.
  1619. (contents-begin (progn (forward-line)
  1620. (and (< (point) block-end-line)
  1621. (point))))
  1622. (contents-end (and contents-begin block-end-line))
  1623. (pos-before-blank (progn (goto-char block-end-line)
  1624. (forward-line)
  1625. (point)))
  1626. (end (progn (skip-chars-forward " \r\t\n" limit)
  1627. (if (eobp) (point) (line-beginning-position)))))
  1628. (list 'quote-block
  1629. (nconc
  1630. (list :begin begin
  1631. :end end
  1632. :contents-begin contents-begin
  1633. :contents-end contents-end
  1634. :post-blank (count-lines pos-before-blank end)
  1635. :post-affiliated post-affiliated)
  1636. (cdr affiliated)))))))))
  1637. (defun org-element-quote-block-interpreter (_ contents)
  1638. "Interpret quote-block element as Org syntax.
  1639. CONTENTS is the contents of the element."
  1640. (format "#+begin_quote\n%s#+end_quote" contents))
  1641. ;;;; Section
  1642. (defun org-element-section-parser (_)
  1643. "Parse a section.
  1644. Return a list whose CAR is `section' and CDR is a plist
  1645. containing `:begin', `:end', `:contents-begin', `contents-end',
  1646. `:post-blank' and `:post-affiliated' keywords."
  1647. (save-excursion
  1648. ;; Beginning of section is the beginning of the first non-blank
  1649. ;; line after previous headline.
  1650. (let* ((begin (point))
  1651. (end (progn (org-with-limited-levels (outline-next-heading))
  1652. (point)))
  1653. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1654. (line-beginning-position 2)))
  1655. (robust-end (when (> (- pos-before-blank 2) begin)
  1656. (- pos-before-blank 2)))
  1657. (robust-begin (when robust-end begin))
  1658. )
  1659. (list 'section
  1660. (list :begin begin
  1661. :end end
  1662. :contents-begin begin
  1663. :contents-end pos-before-blank
  1664. :robust-begin robust-begin
  1665. :robust-end robust-end
  1666. :post-blank (count-lines pos-before-blank end)
  1667. :post-affiliated begin)))))
  1668. (defun org-element-section-interpreter (_ contents)
  1669. "Interpret section element as Org syntax.
  1670. CONTENTS is the contents of the element."
  1671. contents)
  1672. ;;;; Special Block
  1673. (defun org-element-special-block-parser (limit affiliated)
  1674. "Parse a special block.
  1675. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1676. the buffer position at the beginning of the first affiliated
  1677. keyword and CDR is a plist of affiliated keywords along with
  1678. their value.
  1679. Return a list whose CAR is `special-block' and CDR is a plist
  1680. containing `:type', `:begin', `:end', `:contents-begin',
  1681. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1682. Assume point is at the beginning of the block."
  1683. (let* ((case-fold-search t)
  1684. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1685. (match-string-no-properties 1))))
  1686. (if (not (save-excursion
  1687. (re-search-forward
  1688. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1689. limit t)))
  1690. ;; Incomplete block: parse it as a paragraph.
  1691. (org-element-paragraph-parser limit affiliated)
  1692. (let ((block-end-line (match-beginning 0)))
  1693. (save-excursion
  1694. (let* ((begin (car affiliated))
  1695. (post-affiliated (point))
  1696. ;; Empty blocks have no contents.
  1697. (contents-begin (progn (forward-line)
  1698. (and (< (point) block-end-line)
  1699. (point))))
  1700. (contents-end (and contents-begin block-end-line))
  1701. (pos-before-blank (progn (goto-char block-end-line)
  1702. (forward-line)
  1703. (point)))
  1704. (end (progn (skip-chars-forward " \r\t\n" limit)
  1705. (if (eobp) (point) (line-beginning-position)))))
  1706. (list 'special-block
  1707. (nconc
  1708. (list :type type
  1709. :begin begin
  1710. :end end
  1711. :contents-begin contents-begin
  1712. :contents-end contents-end
  1713. :post-blank (count-lines pos-before-blank end)
  1714. :post-affiliated post-affiliated)
  1715. (cdr affiliated)))))))))
  1716. (defun org-element-special-block-interpreter (special-block contents)
  1717. "Interpret SPECIAL-BLOCK element as Org syntax.
  1718. CONTENTS is the contents of the element."
  1719. (let ((block-type (org-element-property :type special-block)))
  1720. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1721. ;;; Elements
  1722. ;;
  1723. ;; For each element, a parser and an interpreter are also defined.
  1724. ;; Both follow the same naming convention used for greater elements.
  1725. ;;
  1726. ;; Also, as for greater elements, adding a new element type is done
  1727. ;; through the following steps: implement a parser and an interpreter,
  1728. ;; tweak `org-element--current-element' so that it recognizes the new
  1729. ;; type and add that new type to `org-element-all-elements'.
  1730. ;;;; Babel Call
  1731. (defun org-element-babel-call-parser (limit affiliated)
  1732. "Parse a babel call.
  1733. LIMIT bounds the search. AFFILIATED is a list of which car is
  1734. the buffer position at the beginning of the first affiliated
  1735. keyword and cdr is a plist of affiliated keywords along with
  1736. their value.
  1737. Return a list whose car is `babel-call' and cdr is a plist
  1738. containing `:call', `:inside-header', `:arguments',
  1739. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1740. `:post-affiliated' as keywords."
  1741. (save-excursion
  1742. (let* ((begin (car affiliated))
  1743. (post-affiliated (point))
  1744. (before-blank (line-beginning-position 2))
  1745. (value (progn (search-forward ":" before-blank t)
  1746. (skip-chars-forward " \t")
  1747. (org-trim
  1748. (buffer-substring-no-properties
  1749. (point) (line-end-position)))))
  1750. (call
  1751. (or (org-string-nw-p
  1752. (buffer-substring-no-properties
  1753. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1754. (point))))))
  1755. (inside-header (org-element--parse-paired-brackets ?\[))
  1756. (arguments (org-string-nw-p
  1757. (org-element--parse-paired-brackets ?\()))
  1758. (end-header
  1759. (org-string-nw-p
  1760. (org-trim
  1761. (buffer-substring-no-properties (point) (line-end-position)))))
  1762. (end (progn (forward-line)
  1763. (skip-chars-forward " \r\t\n" limit)
  1764. (if (eobp) (point) (line-beginning-position)))))
  1765. (list 'babel-call
  1766. (nconc
  1767. (list :call call
  1768. :inside-header inside-header
  1769. :arguments arguments
  1770. :end-header end-header
  1771. :begin begin
  1772. :end end
  1773. :value value
  1774. :post-blank (count-lines before-blank end)
  1775. :post-affiliated post-affiliated)
  1776. (cdr affiliated))))))
  1777. (defun org-element-babel-call-interpreter (babel-call _)
  1778. "Interpret BABEL-CALL element as Org syntax."
  1779. (concat "#+call: "
  1780. (org-element-property :call babel-call)
  1781. (let ((h (org-element-property :inside-header babel-call)))
  1782. (and h (format "[%s]" h)))
  1783. (concat "(" (org-element-property :arguments babel-call) ")")
  1784. (let ((h (org-element-property :end-header babel-call)))
  1785. (and h (concat " " h)))))
  1786. ;;;; Clock
  1787. (defun org-element-clock-parser (limit)
  1788. "Parse a clock.
  1789. LIMIT bounds the search.
  1790. Return a list whose CAR is `clock' and CDR is a plist containing
  1791. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1792. `:post-affiliated' as keywords."
  1793. (save-excursion
  1794. (let* ((case-fold-search nil)
  1795. (begin (point))
  1796. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1797. (skip-chars-forward " \t")
  1798. (org-element-timestamp-parser)))
  1799. (duration (and (search-forward " => " (line-end-position) t)
  1800. (progn (skip-chars-forward " \t")
  1801. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1802. (match-string-no-properties 1)))
  1803. (status (if duration 'closed 'running))
  1804. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1805. (skip-chars-forward " \r\t\n" limit)
  1806. (skip-chars-backward " \t")
  1807. (unless (bolp) (end-of-line))
  1808. (count-lines before-blank (point))))
  1809. (end (point)))
  1810. (list 'clock
  1811. (list :status status
  1812. :value value
  1813. :duration duration
  1814. :begin begin
  1815. :end end
  1816. :post-blank post-blank
  1817. :post-affiliated begin)))))
  1818. (defun org-element-clock-interpreter (clock _)
  1819. "Interpret CLOCK element as Org syntax."
  1820. (concat "CLOCK: "
  1821. (org-element-timestamp-interpreter
  1822. (org-element-property :value clock) nil)
  1823. (let ((duration (org-element-property :duration clock)))
  1824. (and duration
  1825. (concat " => "
  1826. (apply 'format
  1827. "%2s:%02s"
  1828. (org-split-string duration ":")))))))
  1829. ;;;; Comment
  1830. (defun org-element-comment-parser (limit)
  1831. "Parse a comment.
  1832. LIMIT bounds the search.
  1833. Return a list whose CAR is `comment' and CDR is a plist
  1834. containing `:begin', `:end', `:value', `:post-blank',
  1835. `:post-affiliated' keywords.
  1836. Assume point is at comment beginning."
  1837. (save-excursion
  1838. (let* ((begin (point))
  1839. (value (prog2 (looking-at "[ \t]*# ?")
  1840. (buffer-substring-no-properties
  1841. (match-end 0) (line-end-position))
  1842. (forward-line)))
  1843. (com-end
  1844. ;; Get comments ending.
  1845. (progn
  1846. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1847. ;; Accumulate lines without leading hash and first
  1848. ;; whitespace.
  1849. (setq value
  1850. (concat value
  1851. "\n"
  1852. (buffer-substring-no-properties
  1853. (match-end 0) (line-end-position))))
  1854. (forward-line))
  1855. (point)))
  1856. (end (progn (goto-char com-end)
  1857. (skip-chars-forward " \r\t\n" limit)
  1858. (if (eobp) (point) (line-beginning-position)))))
  1859. (list 'comment
  1860. (list :begin begin
  1861. :end end
  1862. :value value
  1863. :post-blank (count-lines com-end end)
  1864. :post-affiliated begin)))))
  1865. (defun org-element-comment-interpreter (comment _)
  1866. "Interpret COMMENT element as Org syntax.
  1867. CONTENTS is nil."
  1868. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1869. ;;;; Comment Block
  1870. (defun org-element-comment-block-parser (limit affiliated)
  1871. "Parse an export block.
  1872. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1873. the buffer position at the beginning of the first affiliated
  1874. keyword and CDR is a plist of affiliated keywords along with
  1875. their value.
  1876. Return a list whose CAR is `comment-block' and CDR is a plist
  1877. containing `:begin', `:end', `:value', `:post-blank' and
  1878. `:post-affiliated' keywords.
  1879. Assume point is at comment block beginning."
  1880. (let ((case-fold-search t))
  1881. (if (not (save-excursion
  1882. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1883. ;; Incomplete block: parse it as a paragraph.
  1884. (org-element-paragraph-parser limit affiliated)
  1885. (let ((contents-end (match-beginning 0)))
  1886. (save-excursion
  1887. (let* ((begin (car affiliated))
  1888. (post-affiliated (point))
  1889. (contents-begin (progn (forward-line) (point)))
  1890. (pos-before-blank (progn (goto-char contents-end)
  1891. (forward-line)
  1892. (point)))
  1893. (end (progn (skip-chars-forward " \r\t\n" limit)
  1894. (if (eobp) (point) (line-beginning-position))))
  1895. (value (buffer-substring-no-properties
  1896. contents-begin contents-end)))
  1897. (list 'comment-block
  1898. (nconc
  1899. (list :begin begin
  1900. :end end
  1901. :value value
  1902. :post-blank (count-lines pos-before-blank end)
  1903. :post-affiliated post-affiliated)
  1904. (cdr affiliated)))))))))
  1905. (defun org-element-comment-block-interpreter (comment-block _)
  1906. "Interpret COMMENT-BLOCK element as Org syntax."
  1907. (format "#+begin_comment\n%s#+end_comment"
  1908. (org-element-normalize-string
  1909. (org-remove-indentation
  1910. (org-element-property :value comment-block)))))
  1911. ;;;; Diary Sexp
  1912. (defun org-element-diary-sexp-parser (limit affiliated)
  1913. "Parse a diary sexp.
  1914. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1915. the buffer position at the beginning of the first affiliated
  1916. keyword and CDR is a plist of affiliated keywords along with
  1917. their value.
  1918. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1919. containing `:begin', `:end', `:value', `:post-blank' and
  1920. `:post-affiliated' keywords."
  1921. (save-excursion
  1922. (let ((begin (car affiliated))
  1923. (post-affiliated (point))
  1924. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1925. (match-string-no-properties 1)))
  1926. (pos-before-blank (progn (forward-line) (point)))
  1927. (end (progn (skip-chars-forward " \r\t\n" limit)
  1928. (if (eobp) (point) (line-beginning-position)))))
  1929. (list 'diary-sexp
  1930. (nconc
  1931. (list :value value
  1932. :begin begin
  1933. :end end
  1934. :post-blank (count-lines pos-before-blank end)
  1935. :post-affiliated post-affiliated)
  1936. (cdr affiliated))))))
  1937. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1938. "Interpret DIARY-SEXP as Org syntax."
  1939. (org-element-property :value diary-sexp))
  1940. ;;;; Example Block
  1941. (defun org-element-example-block-parser (limit affiliated)
  1942. "Parse an example block.
  1943. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1944. the buffer position at the beginning of the first affiliated
  1945. keyword and CDR is a plist of affiliated keywords along with
  1946. their value.
  1947. Return a list whose CAR is `example-block' and CDR is a plist
  1948. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1949. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1950. `:value', `:post-blank' and `:post-affiliated' keywords."
  1951. (let ((case-fold-search t))
  1952. (if (not (save-excursion
  1953. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1954. ;; Incomplete block: parse it as a paragraph.
  1955. (org-element-paragraph-parser limit affiliated)
  1956. (let ((contents-end (match-beginning 0)))
  1957. (save-excursion
  1958. (let* ((switches
  1959. (progn
  1960. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1961. (match-string-no-properties 1)))
  1962. ;; Switches analysis.
  1963. (number-lines
  1964. (and switches
  1965. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1966. switches)
  1967. (cons
  1968. (if (equal (match-string 1 switches) "-")
  1969. 'new
  1970. 'continued)
  1971. (if (not (match-end 2)) 0
  1972. ;; Subtract 1 to give number of lines before
  1973. ;; first line.
  1974. (1- (string-to-number (match-string 2 switches)))))))
  1975. (preserve-indent
  1976. (and switches (string-match "-i\\>" switches)))
  1977. ;; Should labels be retained in (or stripped from) example
  1978. ;; blocks?
  1979. (retain-labels
  1980. (or (not switches)
  1981. (not (string-match "-r\\>" switches))
  1982. (and number-lines (string-match "-k\\>" switches))))
  1983. ;; What should code-references use - labels or
  1984. ;; line-numbers?
  1985. (use-labels
  1986. (or (not switches)
  1987. (and retain-labels
  1988. (not (string-match "-k\\>" switches)))))
  1989. (label-fmt
  1990. (and switches
  1991. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1992. (match-string 1 switches)))
  1993. ;; Standard block parsing.
  1994. (begin (car affiliated))
  1995. (post-affiliated (point))
  1996. (contents-begin (line-beginning-position 2))
  1997. (value (org-unescape-code-in-string
  1998. (buffer-substring-no-properties
  1999. contents-begin contents-end)))
  2000. (pos-before-blank (progn (goto-char contents-end)
  2001. (forward-line)
  2002. (point)))
  2003. (end (progn (skip-chars-forward " \r\t\n" limit)
  2004. (if (eobp) (point) (line-beginning-position)))))
  2005. (list 'example-block
  2006. (nconc
  2007. (list :begin begin
  2008. :end end
  2009. :value value
  2010. :switches switches
  2011. :number-lines number-lines
  2012. :preserve-indent preserve-indent
  2013. :retain-labels retain-labels
  2014. :use-labels use-labels
  2015. :label-fmt label-fmt
  2016. :post-blank (count-lines pos-before-blank end)
  2017. :post-affiliated post-affiliated)
  2018. (cdr affiliated)))))))))
  2019. (defun org-element-example-block-interpreter (example-block _)
  2020. "Interpret EXAMPLE-BLOCK element as Org syntax."
  2021. (let ((switches (org-element-property :switches example-block))
  2022. (value
  2023. (let ((val (org-element-property :value example-block)))
  2024. (cond
  2025. ((or org-src-preserve-indentation
  2026. (org-element-property :preserve-indent example-block))
  2027. val)
  2028. ((= 0 org-edit-src-content-indentation)
  2029. (org-remove-indentation val))
  2030. (t
  2031. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2032. (replace-regexp-in-string "^[ \t]*\\S-"
  2033. (concat ind "\\&")
  2034. (org-remove-indentation val))))))))
  2035. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  2036. (org-element-normalize-string (org-escape-code-in-string value))
  2037. "#+end_example")))
  2038. ;;;; Export Block
  2039. (defun org-element-export-block-parser (limit affiliated)
  2040. "Parse an export block.
  2041. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2042. the buffer position at the beginning of the first affiliated
  2043. keyword and CDR is a plist of affiliated keywords along with
  2044. their value.
  2045. Return a list whose CAR is `export-block' and CDR is a plist
  2046. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  2047. `:post-affiliated' keywords.
  2048. Assume point is at export-block beginning."
  2049. (let* ((case-fold-search t))
  2050. (if (not (save-excursion
  2051. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  2052. ;; Incomplete block: parse it as a paragraph.
  2053. (org-element-paragraph-parser limit affiliated)
  2054. (save-excursion
  2055. (let* ((contents-end (match-beginning 0))
  2056. (backend
  2057. (progn
  2058. (looking-at
  2059. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  2060. (match-string-no-properties 1)))
  2061. (begin (car affiliated))
  2062. (post-affiliated (point))
  2063. (contents-begin (progn (forward-line) (point)))
  2064. (pos-before-blank (progn (goto-char contents-end)
  2065. (forward-line)
  2066. (point)))
  2067. (end (progn (skip-chars-forward " \r\t\n" limit)
  2068. (if (eobp) (point) (line-beginning-position))))
  2069. (value (org-unescape-code-in-string
  2070. (buffer-substring-no-properties contents-begin
  2071. contents-end))))
  2072. (list 'export-block
  2073. (nconc
  2074. (list :type (and backend (upcase backend))
  2075. :begin begin
  2076. :end end
  2077. :value value
  2078. :post-blank (count-lines pos-before-blank end)
  2079. :post-affiliated post-affiliated)
  2080. (cdr affiliated))))))))
  2081. (defun org-element-export-block-interpreter (export-block _)
  2082. "Interpret EXPORT-BLOCK element as Org syntax."
  2083. (format "#+begin_export %s\n%s#+end_export"
  2084. (org-element-property :type export-block)
  2085. (org-element-property :value export-block)))
  2086. ;;;; Fixed-width
  2087. (defun org-element-fixed-width-parser (limit affiliated)
  2088. "Parse a fixed-width section.
  2089. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2090. the buffer position at the beginning of the first affiliated
  2091. keyword and CDR is a plist of affiliated keywords along with
  2092. their value.
  2093. Return a list whose CAR is `fixed-width' and CDR is a plist
  2094. containing `:begin', `:end', `:value', `:post-blank' and
  2095. `:post-affiliated' keywords.
  2096. Assume point is at the beginning of the fixed-width area."
  2097. (save-excursion
  2098. (let* ((begin (car affiliated))
  2099. (post-affiliated (point))
  2100. (end-area
  2101. (progn
  2102. (while (and (< (point) limit)
  2103. (looking-at "[ \t]*:\\( \\|$\\)"))
  2104. (forward-line))
  2105. (if (bolp) (line-end-position 0) (point))))
  2106. (end (progn (skip-chars-forward " \r\t\n" limit)
  2107. (if (eobp) (point) (line-beginning-position)))))
  2108. (list 'fixed-width
  2109. (nconc
  2110. (list :begin begin
  2111. :end end
  2112. :value (replace-regexp-in-string
  2113. "^[ \t]*: ?" ""
  2114. (buffer-substring-no-properties post-affiliated
  2115. end-area))
  2116. :post-blank (count-lines end-area end)
  2117. :post-affiliated post-affiliated)
  2118. (cdr affiliated))))))
  2119. (defun org-element-fixed-width-interpreter (fixed-width _)
  2120. "Interpret FIXED-WIDTH element as Org syntax."
  2121. (let ((value (org-element-property :value fixed-width)))
  2122. (and value (replace-regexp-in-string "^" ": " value))))
  2123. ;;;; Horizontal Rule
  2124. (defun org-element-horizontal-rule-parser (limit affiliated)
  2125. "Parse an horizontal rule.
  2126. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2127. the buffer position at the beginning of the first affiliated
  2128. keyword and CDR is a plist of affiliated keywords along with
  2129. their value.
  2130. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  2131. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  2132. keywords."
  2133. (save-excursion
  2134. (let ((begin (car affiliated))
  2135. (post-affiliated (point))
  2136. (post-hr (progn (forward-line) (point)))
  2137. (end (progn (skip-chars-forward " \r\t\n" limit)
  2138. (if (eobp) (point) (line-beginning-position)))))
  2139. (list 'horizontal-rule
  2140. (nconc
  2141. (list :begin begin
  2142. :end end
  2143. :post-blank (count-lines post-hr end)
  2144. :post-affiliated post-affiliated)
  2145. (cdr affiliated))))))
  2146. (defun org-element-horizontal-rule-interpreter (&rest _)
  2147. "Interpret HORIZONTAL-RULE element as Org syntax."
  2148. "-----")
  2149. ;;;; Keyword
  2150. (defun org-element-keyword-parser (limit affiliated)
  2151. "Parse a keyword at point.
  2152. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2153. the buffer position at the beginning of the first affiliated
  2154. keyword and CDR is a plist of affiliated keywords along with
  2155. their value.
  2156. Return a list whose CAR is a normalized `keyword' (uppercase) and
  2157. CDR is a plist containing `:key', `:value', `:begin', `:end',
  2158. `:post-blank' and `:post-affiliated' keywords."
  2159. (save-excursion
  2160. ;; An orphaned affiliated keyword is considered as a regular
  2161. ;; keyword. In this case AFFILIATED is nil, so we take care of
  2162. ;; this corner case.
  2163. (let ((begin (or (car affiliated) (point)))
  2164. (post-affiliated (point))
  2165. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  2166. (upcase (match-string-no-properties 1))))
  2167. (value (org-trim (buffer-substring-no-properties
  2168. (match-end 0) (point-at-eol))))
  2169. (pos-before-blank (progn (forward-line) (point)))
  2170. (end (progn (skip-chars-forward " \r\t\n" limit)
  2171. (if (eobp) (point) (line-beginning-position)))))
  2172. (list 'keyword
  2173. (nconc
  2174. (list :key key
  2175. :value value
  2176. :begin begin
  2177. :end end
  2178. :post-blank (count-lines pos-before-blank end)
  2179. :post-affiliated post-affiliated)
  2180. (cdr affiliated))))))
  2181. (defun org-element-keyword-interpreter (keyword _)
  2182. "Interpret KEYWORD element as Org syntax."
  2183. (format "#+%s: %s"
  2184. (downcase (org-element-property :key keyword))
  2185. (org-element-property :value keyword)))
  2186. ;;;; Latex Environment
  2187. (defconst org-element--latex-begin-environment
  2188. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2189. "Regexp matching the beginning of a LaTeX environment.
  2190. The environment is captured by the first group.
  2191. See also `org-element--latex-end-environment'.")
  2192. (defconst org-element--latex-end-environment
  2193. "\\\\end{%s}[ \t]*$"
  2194. "Format string matching the ending of a LaTeX environment.
  2195. See also `org-element--latex-begin-environment'.")
  2196. (defun org-element-latex-environment-parser (limit affiliated)
  2197. "Parse a LaTeX environment.
  2198. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2199. the buffer position at the beginning of the first affiliated
  2200. keyword and CDR is a plist of affiliated keywords along with
  2201. their value.
  2202. Return a list whose CAR is `latex-environment' and CDR is a plist
  2203. containing `:begin', `:end', `:value', `:post-blank' and
  2204. `:post-affiliated' keywords.
  2205. Assume point is at the beginning of the latex environment."
  2206. (save-excursion
  2207. (let ((case-fold-search t)
  2208. (code-begin (point)))
  2209. (looking-at org-element--latex-begin-environment)
  2210. (if (not (re-search-forward (format org-element--latex-end-environment
  2211. (regexp-quote (match-string 1)))
  2212. limit t))
  2213. ;; Incomplete latex environment: parse it as a paragraph.
  2214. (org-element-paragraph-parser limit affiliated)
  2215. (let* ((code-end (progn (forward-line) (point)))
  2216. (begin (car affiliated))
  2217. (value (buffer-substring-no-properties code-begin code-end))
  2218. (end (progn (skip-chars-forward " \r\t\n" limit)
  2219. (if (eobp) (point) (line-beginning-position)))))
  2220. (list 'latex-environment
  2221. (nconc
  2222. (list :begin begin
  2223. :end end
  2224. :value value
  2225. :post-blank (count-lines code-end end)
  2226. :post-affiliated code-begin)
  2227. (cdr affiliated))))))))
  2228. (defun org-element-latex-environment-interpreter (latex-environment _)
  2229. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2230. (org-element-property :value latex-environment))
  2231. ;;;; Node Property
  2232. (defun org-element-node-property-parser (limit)
  2233. "Parse a node-property at point.
  2234. LIMIT bounds the search.
  2235. Return a list whose CAR is `node-property' and CDR is a plist
  2236. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2237. `:post-affiliated' keywords."
  2238. (looking-at org-property-re)
  2239. (let ((case-fold-search t)
  2240. (begin (point))
  2241. (key (match-string-no-properties 2))
  2242. (value (match-string-no-properties 3))
  2243. (end (save-excursion
  2244. (end-of-line)
  2245. (if (re-search-forward org-property-re limit t)
  2246. (line-beginning-position)
  2247. limit))))
  2248. (list 'node-property
  2249. (list :key key
  2250. :value value
  2251. :begin begin
  2252. :end end
  2253. :post-blank 0
  2254. :post-affiliated begin))))
  2255. (defun org-element-node-property-interpreter (node-property _)
  2256. "Interpret NODE-PROPERTY element as Org syntax."
  2257. (format org-property-format
  2258. (format ":%s:" (org-element-property :key node-property))
  2259. (or (org-element-property :value node-property) "")))
  2260. ;;;; Paragraph
  2261. (defun org-element-paragraph-parser (limit affiliated)
  2262. "Parse a paragraph.
  2263. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2264. the buffer position at the beginning of the first affiliated
  2265. keyword and CDR is a plist of affiliated keywords along with
  2266. their value.
  2267. Return a list whose CAR is `paragraph' and CDR is a plist
  2268. containing `:begin', `:end', `:contents-begin' and
  2269. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2270. Assume point is at the beginning of the paragraph."
  2271. (save-excursion
  2272. (let* ((begin (car affiliated))
  2273. (contents-begin (point))
  2274. (before-blank
  2275. (let ((case-fold-search t))
  2276. (end-of-line)
  2277. ;; A matching `org-element-paragraph-separate' is not
  2278. ;; necessarily the end of the paragraph. In particular,
  2279. ;; drawers, blocks or LaTeX environments opening lines
  2280. ;; must be closed. Moreover keywords with a secondary
  2281. ;; value must belong to "dual keywords".
  2282. (while (not
  2283. (cond
  2284. ((not (and (re-search-forward
  2285. org-element-paragraph-separate limit 'move)
  2286. (progn (beginning-of-line) t))))
  2287. ((looking-at org-element-drawer-re)
  2288. (save-excursion
  2289. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2290. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2291. (save-excursion
  2292. (re-search-forward
  2293. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2294. (regexp-quote (match-string 1)))
  2295. limit t)))
  2296. ((looking-at org-element--latex-begin-environment)
  2297. (save-excursion
  2298. (re-search-forward
  2299. (format org-element--latex-end-environment
  2300. (regexp-quote (match-string 1)))
  2301. limit t)))
  2302. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2303. (member-ignore-case (match-string 1)
  2304. org-element-dual-keywords))
  2305. ;; Everything else is unambiguous.
  2306. (t)))
  2307. (end-of-line))
  2308. (if (= (point) limit) limit
  2309. (goto-char (line-beginning-position)))))
  2310. (contents-end (save-excursion
  2311. (skip-chars-backward " \r\t\n" contents-begin)
  2312. (line-beginning-position 2)))
  2313. (end (progn (skip-chars-forward " \r\t\n" limit)
  2314. (if (eobp) (point) (line-beginning-position)))))
  2315. (list 'paragraph
  2316. (nconc
  2317. (list :begin begin
  2318. :end end
  2319. :contents-begin contents-begin
  2320. :contents-end contents-end
  2321. :post-blank (count-lines before-blank end)
  2322. :post-affiliated contents-begin)
  2323. (cdr affiliated))))))
  2324. (defun org-element-paragraph-interpreter (_ contents)
  2325. "Interpret paragraph element as Org syntax.
  2326. CONTENTS is the contents of the element."
  2327. contents)
  2328. ;;;; Planning
  2329. (defun org-element-planning-parser (limit)
  2330. "Parse a planning.
  2331. LIMIT bounds the search.
  2332. Return a list whose CAR is `planning' and CDR is a plist
  2333. containing `:closed', `:deadline', `:scheduled', `:begin',
  2334. `:end', `:post-blank' and `:post-affiliated' keywords."
  2335. (save-excursion
  2336. (let* ((case-fold-search nil)
  2337. (begin (point))
  2338. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2339. (skip-chars-forward " \r\t\n" limit)
  2340. (skip-chars-backward " \t")
  2341. (unless (bolp) (end-of-line))
  2342. (count-lines before-blank (point))))
  2343. (end (point))
  2344. closed deadline scheduled)
  2345. (goto-char begin)
  2346. (while (re-search-forward org-element-planning-keywords-re end t)
  2347. (skip-chars-forward " \t" end)
  2348. (let ((keyword (match-string 0))
  2349. (time (org-element-timestamp-parser)))
  2350. (cond
  2351. ((equal keyword org-element-closed-keyword) (setq closed time))
  2352. ((equal keyword org-element-deadline-keyword) (setq deadline time))
  2353. (t (setq scheduled time)))))
  2354. (list 'planning
  2355. (list :closed closed
  2356. :deadline deadline
  2357. :scheduled scheduled
  2358. :begin begin
  2359. :end end
  2360. :post-blank post-blank
  2361. :post-affiliated begin)))))
  2362. (defun org-element-planning-interpreter (planning _)
  2363. "Interpret PLANNING element as Org syntax."
  2364. (mapconcat
  2365. #'identity
  2366. (delq nil
  2367. (list (let ((deadline (org-element-property :deadline planning)))
  2368. (when deadline
  2369. (concat org-element-deadline-keyword " "
  2370. (org-element-timestamp-interpreter deadline nil))))
  2371. (let ((scheduled (org-element-property :scheduled planning)))
  2372. (when scheduled
  2373. (concat org-element-scheduled-keyword " "
  2374. (org-element-timestamp-interpreter scheduled nil))))
  2375. (let ((closed (org-element-property :closed planning)))
  2376. (when closed
  2377. (concat org-element-closed-keyword " "
  2378. (org-element-timestamp-interpreter closed nil))))))
  2379. " "))
  2380. ;;;; Src Block
  2381. (defun org-element-src-block-parser (limit affiliated)
  2382. "Parse a source block.
  2383. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2384. the buffer position at the beginning of the first affiliated
  2385. keyword and CDR is a plist of affiliated keywords along with
  2386. their value.
  2387. Return a list whose CAR is `src-block' and CDR is a plist
  2388. containing `:language', `:switches', `:parameters', `:begin',
  2389. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2390. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2391. `:post-affiliated' keywords.
  2392. Assume point is at the beginning of the block."
  2393. (let ((case-fold-search t))
  2394. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2395. limit t)))
  2396. ;; Incomplete block: parse it as a paragraph.
  2397. (org-element-paragraph-parser limit affiliated)
  2398. (let ((contents-end (match-beginning 0)))
  2399. (save-excursion
  2400. (let* ((begin (car affiliated))
  2401. (post-affiliated (point))
  2402. ;; Get language as a string.
  2403. (language
  2404. (progn
  2405. (looking-at
  2406. "^[ \t]*#\\+BEGIN_SRC\
  2407. \\(?: +\\(\\S-+\\)\\)?\
  2408. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2409. \\(.*\\)[ \t]*$")
  2410. (match-string-no-properties 1)))
  2411. ;; Get switches.
  2412. (switches (match-string-no-properties 2))
  2413. ;; Get parameters.
  2414. (parameters (match-string-no-properties 3))
  2415. ;; Switches analysis.
  2416. (number-lines
  2417. (and switches
  2418. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2419. switches)
  2420. (cons
  2421. (if (equal (match-string 1 switches) "-")
  2422. 'new
  2423. 'continued)
  2424. (if (not (match-end 2)) 0
  2425. ;; Subtract 1 to give number of lines before
  2426. ;; first line.
  2427. (1- (string-to-number (match-string 2 switches)))))))
  2428. (preserve-indent (and switches
  2429. (string-match "-i\\>" switches)))
  2430. (label-fmt
  2431. (and switches
  2432. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2433. (match-string 1 switches)))
  2434. ;; Should labels be retained in (or stripped from)
  2435. ;; source blocks?
  2436. (retain-labels
  2437. (or (not switches)
  2438. (not (string-match "-r\\>" switches))
  2439. (and number-lines (string-match "-k\\>" switches))))
  2440. ;; What should code-references use - labels or
  2441. ;; line-numbers?
  2442. (use-labels
  2443. (or (not switches)
  2444. (and retain-labels
  2445. (not (string-match "-k\\>" switches)))))
  2446. ;; Retrieve code.
  2447. (value (org-unescape-code-in-string
  2448. (buffer-substring-no-properties
  2449. (line-beginning-position 2) contents-end)))
  2450. (pos-before-blank (progn (goto-char contents-end)
  2451. (forward-line)
  2452. (point)))
  2453. ;; Get position after ending blank lines.
  2454. (end (progn (skip-chars-forward " \r\t\n" limit)
  2455. (if (eobp) (point) (line-beginning-position)))))
  2456. (list 'src-block
  2457. (nconc
  2458. (list :language language
  2459. :switches (and (org-string-nw-p switches)
  2460. (org-trim switches))
  2461. :parameters (and (org-string-nw-p parameters)
  2462. (org-trim parameters))
  2463. :begin begin
  2464. :end end
  2465. :number-lines number-lines
  2466. :preserve-indent preserve-indent
  2467. :retain-labels retain-labels
  2468. :use-labels use-labels
  2469. :label-fmt label-fmt
  2470. :value value
  2471. :post-blank (count-lines pos-before-blank end)
  2472. :post-affiliated post-affiliated)
  2473. (cdr affiliated)))))))))
  2474. (defun org-element-src-block-interpreter (src-block _)
  2475. "Interpret SRC-BLOCK element as Org syntax."
  2476. (let ((lang (org-element-property :language src-block))
  2477. (switches (org-element-property :switches src-block))
  2478. (params (org-element-property :parameters src-block))
  2479. (value
  2480. (let ((val (org-element-property :value src-block)))
  2481. (cond
  2482. ((or org-src-preserve-indentation
  2483. (org-element-property :preserve-indent src-block))
  2484. val)
  2485. ((zerop org-edit-src-content-indentation)
  2486. (org-remove-indentation val))
  2487. (t
  2488. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2489. (replace-regexp-in-string "^[ \t]*\\S-"
  2490. (concat ind "\\&")
  2491. (org-remove-indentation val))))))))
  2492. (format "#+begin_src%s\n%s#+end_src"
  2493. (concat (and lang (concat " " lang))
  2494. (and switches (concat " " switches))
  2495. (and params (concat " " params)))
  2496. (org-element-normalize-string (org-escape-code-in-string value)))))
  2497. ;;;; Table
  2498. (defun org-element-table-parser (limit affiliated)
  2499. "Parse a table at point.
  2500. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2501. the buffer position at the beginning of the first affiliated
  2502. keyword and CDR is a plist of affiliated keywords along with
  2503. their value.
  2504. Return a list whose CAR is `table' and CDR is a plist containing
  2505. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2506. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2507. keywords.
  2508. Assume point is at the beginning of the table."
  2509. (save-excursion
  2510. (let* ((case-fold-search t)
  2511. (table-begin (point))
  2512. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2513. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2514. (if (eq type 'org) "" "+")))
  2515. (begin (car affiliated))
  2516. (table-end
  2517. (if (re-search-forward end-re limit 'move)
  2518. (goto-char (match-beginning 0))
  2519. (point)))
  2520. (tblfm (let (acc)
  2521. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2522. (push (match-string-no-properties 1) acc)
  2523. (forward-line))
  2524. acc))
  2525. (pos-before-blank (point))
  2526. (end (progn (skip-chars-forward " \r\t\n" limit)
  2527. (if (eobp) (point) (line-beginning-position)))))
  2528. (list 'table
  2529. (nconc
  2530. (list :begin begin
  2531. :end end
  2532. :type type
  2533. :tblfm tblfm
  2534. ;; Only `org' tables have contents. `table.el' tables
  2535. ;; use a `:value' property to store raw table as
  2536. ;; a string.
  2537. :contents-begin (and (eq type 'org) table-begin)
  2538. :contents-end (and (eq type 'org) table-end)
  2539. :value (and (eq type 'table.el)
  2540. (buffer-substring-no-properties
  2541. table-begin table-end))
  2542. :post-blank (count-lines pos-before-blank end)
  2543. :post-affiliated table-begin)
  2544. (cdr affiliated))))))
  2545. (defun org-element-table-interpreter (table contents)
  2546. "Interpret TABLE element as Org syntax.
  2547. CONTENTS is a string, if table's type is `org', or nil."
  2548. (if (eq (org-element-property :type table) 'table.el)
  2549. (org-remove-indentation (org-element-property :value table))
  2550. (concat (with-temp-buffer (insert contents)
  2551. (org-table-align)
  2552. (buffer-string))
  2553. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2554. (reverse (org-element-property :tblfm table))
  2555. "\n"))))
  2556. ;;;; Table Row
  2557. (defun org-element-table-row-parser (_)
  2558. "Parse table row at point.
  2559. Return a list whose CAR is `table-row' and CDR is a plist
  2560. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2561. `:type', `:post-blank' and `:post-affiliated' keywords."
  2562. (save-excursion
  2563. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2564. (begin (point))
  2565. ;; A table rule has no contents. In that case, ensure
  2566. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2567. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2568. (contents-end (and (eq type 'standard)
  2569. (progn
  2570. (end-of-line)
  2571. (skip-chars-backward " \t")
  2572. (point))))
  2573. (end (line-beginning-position 2)))
  2574. (list 'table-row
  2575. (list :type type
  2576. :begin begin
  2577. :end end
  2578. :contents-begin contents-begin
  2579. :contents-end contents-end
  2580. :post-blank 0
  2581. :post-affiliated begin)))))
  2582. (defun org-element-table-row-interpreter (table-row contents)
  2583. "Interpret TABLE-ROW element as Org syntax.
  2584. CONTENTS is the contents of the table row."
  2585. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2586. (concat "|" contents)))
  2587. ;;;; Verse Block
  2588. (defun org-element-verse-block-parser (limit affiliated)
  2589. "Parse a verse block.
  2590. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2591. the buffer position at the beginning of the first affiliated
  2592. keyword and CDR is a plist of affiliated keywords along with
  2593. their value.
  2594. Return a list whose CAR is `verse-block' and CDR is a plist
  2595. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2596. `:post-blank' and `:post-affiliated' keywords.
  2597. Assume point is at beginning of the block."
  2598. (let ((case-fold-search t))
  2599. (if (not (save-excursion
  2600. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2601. ;; Incomplete block: parse it as a paragraph.
  2602. (org-element-paragraph-parser limit affiliated)
  2603. (let ((contents-end (match-beginning 0)))
  2604. (save-excursion
  2605. (let* ((begin (car affiliated))
  2606. (post-affiliated (point))
  2607. (contents-begin (progn (forward-line) (point)))
  2608. (pos-before-blank (progn (goto-char contents-end)
  2609. (forward-line)
  2610. (point)))
  2611. (end (progn (skip-chars-forward " \r\t\n" limit)
  2612. (if (eobp) (point) (line-beginning-position)))))
  2613. (list 'verse-block
  2614. (nconc
  2615. (list :begin begin
  2616. :end end
  2617. :contents-begin contents-begin
  2618. :contents-end contents-end
  2619. :post-blank (count-lines pos-before-blank end)
  2620. :post-affiliated post-affiliated)
  2621. (cdr affiliated)))))))))
  2622. (defun org-element-verse-block-interpreter (_ contents)
  2623. "Interpret verse-block element as Org syntax.
  2624. CONTENTS is verse block contents."
  2625. (format "#+begin_verse\n%s#+end_verse" contents))
  2626. ;;; Objects
  2627. ;;
  2628. ;; Unlike to elements, raw text can be found between objects. Hence,
  2629. ;; `org-element--object-lex' is provided to find the next object in
  2630. ;; buffer.
  2631. ;;
  2632. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2633. ;; object types they can contain will be specified in
  2634. ;; `org-element-object-restrictions'.
  2635. ;;
  2636. ;; Creating a new type of object requires to alter
  2637. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2638. ;; new type in `org-element-all-objects', and possibly add
  2639. ;; restrictions in `org-element-object-restrictions'.
  2640. ;;;; Bold
  2641. (defun org-element--parse-generic-emphasis (mark type)
  2642. "Parse emphasis object at point, if any.
  2643. MARK is the delimiter string used. TYPE is a symbol among
  2644. ‘bold’, ‘code’, ‘italic’, ‘strike-through’, ‘underline’, and
  2645. ‘verbatim’.
  2646. Assume point is at first MARK."
  2647. (save-excursion
  2648. (let ((origin (point)))
  2649. (unless (bolp) (forward-char -1))
  2650. (let ((opening-re
  2651. (rx-to-string
  2652. `(seq (or line-start (any space ?- ?\( ?' ?\" ?\{))
  2653. ,mark
  2654. (not space)))))
  2655. (when (looking-at opening-re)
  2656. (goto-char (1+ origin))
  2657. (let ((closing-re
  2658. (rx-to-string
  2659. `(seq
  2660. (not space)
  2661. (group ,mark)
  2662. (or (any space ?- ?. ?, ?\; ?: ?! ?? ?' ?\" ?\) ?\} ?\\ ?\[)
  2663. line-end)))))
  2664. (when (re-search-forward closing-re nil t)
  2665. (let ((closing (match-end 1)))
  2666. (goto-char closing)
  2667. (let* ((post-blank (skip-chars-forward " \t"))
  2668. (contents-begin (1+ origin))
  2669. (contents-end (1- closing)))
  2670. (list type
  2671. (append
  2672. (list :begin origin
  2673. :end (point)
  2674. :post-blank post-blank)
  2675. (if (memq type '(code verbatim))
  2676. (list :value
  2677. (and (memq type '(code verbatim))
  2678. (buffer-substring
  2679. contents-begin contents-end)))
  2680. (list :contents-begin contents-begin
  2681. :contents-end contents-end)))))))))))))
  2682. (defun org-element-bold-parser ()
  2683. "Parse bold object at point, if any.
  2684. When at a bold object, return a list whose car is `bold' and cdr
  2685. is a plist with `:begin', `:end', `:contents-begin' and
  2686. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2687. nil.
  2688. Assume point is at the first star marker."
  2689. (org-element--parse-generic-emphasis "*" 'bold))
  2690. (defun org-element-bold-interpreter (_ contents)
  2691. "Interpret bold object as Org syntax.
  2692. CONTENTS is the contents of the object."
  2693. (format "*%s*" contents))
  2694. ;;;; Citation
  2695. (defun org-element-citation-parser ()
  2696. "Parse citation object at point, if any.
  2697. When at a citation object, return a list whose car is `citation'
  2698. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2699. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2700. keywords. Otherwise, return nil.
  2701. Assume point is at the beginning of the citation."
  2702. (when (looking-at org-element-citation-prefix-re)
  2703. (let* ((begin (point))
  2704. (style (and (match-end 1)
  2705. (match-string-no-properties 1)))
  2706. ;; Ignore blanks between cite type and prefix or key.
  2707. (start (match-end 0))
  2708. (closing (with-syntax-table org-element--pair-square-table
  2709. (ignore-errors (scan-lists begin 1 0)))))
  2710. (save-excursion
  2711. (when (and closing
  2712. (re-search-forward org-element-citation-key-re closing t))
  2713. ;; Find prefix, if any.
  2714. (let ((first-key-end (match-end 0))
  2715. (types (org-element-restriction 'citation-reference))
  2716. (cite
  2717. (list 'citation
  2718. (list :style style
  2719. :begin begin
  2720. :post-blank (progn
  2721. (goto-char closing)
  2722. (skip-chars-forward " \t"))
  2723. :end (point)))))
  2724. ;; `:contents-begin' depends on the presence of
  2725. ;; a non-empty common prefix.
  2726. (goto-char first-key-end)
  2727. (if (not (search-backward ";" start t))
  2728. (org-element-put-property cite :contents-begin start)
  2729. (when (< start (point))
  2730. (org-element-put-property
  2731. cite :prefix
  2732. (org-element--parse-objects start (point) nil types cite)))
  2733. (forward-char)
  2734. (org-element-put-property cite :contents-begin (point)))
  2735. ;; `:contents-end' depends on the presence of a non-empty
  2736. ;; common suffix.
  2737. (goto-char (1- closing))
  2738. (skip-chars-backward " \r\t\n")
  2739. (let ((end (point)))
  2740. (if (or (not (search-backward ";" first-key-end t))
  2741. (re-search-forward org-element-citation-key-re end t))
  2742. (org-element-put-property cite :contents-end end)
  2743. (forward-char)
  2744. (when (< (point) end)
  2745. (org-element-put-property
  2746. cite :suffix
  2747. (org-element--parse-objects (point) end nil types cite)))
  2748. (org-element-put-property cite :contents-end (point))))
  2749. cite))))))
  2750. (defun org-element-citation-interpreter (citation contents)
  2751. "Interpret CITATION object as Org syntax.
  2752. CONTENTS is the contents of the object, as a string."
  2753. (let ((prefix (org-element-property :prefix citation))
  2754. (suffix (org-element-property :suffix citation))
  2755. (style (org-element-property :style citation)))
  2756. (concat "[cite"
  2757. (and style (concat "/" style))
  2758. ":"
  2759. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2760. (if suffix
  2761. (concat contents (org-element-interpret-data suffix))
  2762. ;; Remove spurious semicolon.
  2763. (substring contents nil -1))
  2764. "]")))
  2765. ;;;; Citation Reference
  2766. (defun org-element-citation-reference-parser ()
  2767. "Parse citation reference object at point, if any.
  2768. When at a reference, return a list whose car is
  2769. `citation-reference', and cdr is a plist with `:key',
  2770. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2771. Assume point is at the beginning of the reference."
  2772. (save-excursion
  2773. (let ((begin (point)))
  2774. (when (re-search-forward org-element-citation-key-re nil t)
  2775. (let* ((key (match-string-no-properties 1))
  2776. (key-start (match-beginning 0))
  2777. (key-end (match-end 0))
  2778. (separator (search-forward ";" nil t))
  2779. (end (or separator (point-max)))
  2780. (suffix-end (if separator (1- end) end))
  2781. (types (org-element-restriction 'citation-reference))
  2782. (reference
  2783. (list 'citation-reference
  2784. (list :key key
  2785. :begin begin
  2786. :end end
  2787. :post-blank 0))))
  2788. (when (< begin key-start)
  2789. (org-element-put-property
  2790. reference :prefix
  2791. (org-element--parse-objects begin key-start nil types reference)))
  2792. (when (< key-end suffix-end)
  2793. (org-element-put-property
  2794. reference :suffix
  2795. (org-element--parse-objects key-end suffix-end nil types reference)))
  2796. reference)))))
  2797. (defun org-element-citation-reference-interpreter (citation-reference _)
  2798. "Interpret CITATION-REFERENCE object as Org syntax."
  2799. (concat (org-element-interpret-data
  2800. (org-element-property :prefix citation-reference))
  2801. "@" (org-element-property :key citation-reference)
  2802. (org-element-interpret-data
  2803. (org-element-property :suffix citation-reference))
  2804. ";"))
  2805. ;;;; Code
  2806. (defun org-element-code-parser ()
  2807. "Parse code object at point, if any.
  2808. When at a code object, return a list whose car is `code' and cdr
  2809. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2810. keywords. Otherwise, return nil.
  2811. Assume point is at the first tilde marker."
  2812. (org-element--parse-generic-emphasis "~" 'code))
  2813. (defun org-element-code-interpreter (code _)
  2814. "Interpret CODE object as Org syntax."
  2815. (format "~%s~" (org-element-property :value code)))
  2816. ;;;; Entity
  2817. (defun org-element-entity-parser ()
  2818. "Parse entity at point, if any.
  2819. When at an entity, return a list whose car is `entity' and cdr
  2820. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2821. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2822. `:post-blank' as keywords. Otherwise, return nil.
  2823. Assume point is at the beginning of the entity."
  2824. (catch 'no-object
  2825. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2826. (save-excursion
  2827. (let* ((value (or (org-entity-get (match-string 1))
  2828. (throw 'no-object nil)))
  2829. (begin (match-beginning 0))
  2830. (bracketsp (string= (match-string 2) "{}"))
  2831. (post-blank (progn (goto-char (match-end 1))
  2832. (when bracketsp (forward-char 2))
  2833. (skip-chars-forward " \t")))
  2834. (end (point)))
  2835. (list 'entity
  2836. (list :name (car value)
  2837. :latex (nth 1 value)
  2838. :latex-math-p (nth 2 value)
  2839. :html (nth 3 value)
  2840. :ascii (nth 4 value)
  2841. :latin1 (nth 5 value)
  2842. :utf-8 (nth 6 value)
  2843. :begin begin
  2844. :end end
  2845. :use-brackets-p bracketsp
  2846. :post-blank post-blank)))))))
  2847. (defun org-element-entity-interpreter (entity _)
  2848. "Interpret ENTITY object as Org syntax."
  2849. (concat "\\"
  2850. (org-element-property :name entity)
  2851. (when (org-element-property :use-brackets-p entity) "{}")))
  2852. ;;;; Export Snippet
  2853. (defun org-element-export-snippet-parser ()
  2854. "Parse export snippet at point.
  2855. When at an export snippet, return a list whose car is
  2856. `export-snippet' and cdr a plist with `:begin', `:end',
  2857. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2858. return nil.
  2859. Assume point is at the beginning of the snippet."
  2860. (save-excursion
  2861. (let (contents-end)
  2862. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2863. (setq contents-end
  2864. (save-match-data (goto-char (match-end 0))
  2865. (when
  2866. (re-search-forward "@@" nil t)
  2867. (match-beginning 0)))))
  2868. (let* ((begin (match-beginning 0))
  2869. (back-end (match-string-no-properties 1))
  2870. (value (buffer-substring-no-properties
  2871. (match-end 0) contents-end))
  2872. (post-blank (skip-chars-forward " \t"))
  2873. (end (point)))
  2874. (list 'export-snippet
  2875. (list :back-end back-end
  2876. :value value
  2877. :begin begin
  2878. :end end
  2879. :post-blank post-blank)))))))
  2880. (defun org-element-export-snippet-interpreter (export-snippet _)
  2881. "Interpret EXPORT-SNIPPET object as Org syntax."
  2882. (format "@@%s:%s@@"
  2883. (org-element-property :back-end export-snippet)
  2884. (org-element-property :value export-snippet)))
  2885. ;;;; Footnote Reference
  2886. (defun org-element-footnote-reference-parser ()
  2887. "Parse footnote reference at point, if any.
  2888. When at a footnote reference, return a list whose car is
  2889. `footnote-reference' and cdr a plist with `:label', `:type',
  2890. `:begin', `:end', `:contents-begin', `:contents-end' and
  2891. `:post-blank' as keywords. Otherwise, return nil."
  2892. (when (looking-at org-footnote-re)
  2893. (let ((closing (with-syntax-table org-element--pair-square-table
  2894. (ignore-errors (scan-lists (point) 1 0)))))
  2895. (when closing
  2896. (save-excursion
  2897. (let* ((begin (point))
  2898. (label (match-string-no-properties 1))
  2899. (inner-begin (match-end 0))
  2900. (inner-end (1- closing))
  2901. (type (if (match-end 2) 'inline 'standard))
  2902. (post-blank (progn (goto-char closing)
  2903. (skip-chars-forward " \t")))
  2904. (end (point)))
  2905. (list 'footnote-reference
  2906. (list :label label
  2907. :type type
  2908. :begin begin
  2909. :end end
  2910. :contents-begin (and (eq type 'inline) inner-begin)
  2911. :contents-end (and (eq type 'inline) inner-end)
  2912. :post-blank post-blank))))))))
  2913. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2914. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2915. CONTENTS is its definition, when inline, or nil."
  2916. (format "[fn:%s%s]"
  2917. (or (org-element-property :label footnote-reference) "")
  2918. (if contents (concat ":" contents) "")))
  2919. ;;;; Inline Babel Call
  2920. (defun org-element-inline-babel-call-parser ()
  2921. "Parse inline babel call at point, if any.
  2922. When at an inline babel call, return a list whose car is
  2923. `inline-babel-call' and cdr a plist with `:call',
  2924. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2925. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2926. Assume point is at the beginning of the babel call."
  2927. (save-excursion
  2928. (catch :no-object
  2929. (when (let ((case-fold-search nil))
  2930. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2931. (goto-char (match-end 1))
  2932. (let* ((begin (match-beginning 0))
  2933. (call (match-string-no-properties 1))
  2934. (inside-header
  2935. (let ((p (org-element--parse-paired-brackets ?\[)))
  2936. (and (org-string-nw-p p)
  2937. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2938. (arguments (org-string-nw-p
  2939. (or (org-element--parse-paired-brackets ?\()
  2940. ;; Parenthesis are mandatory.
  2941. (throw :no-object nil))))
  2942. (end-header
  2943. (let ((p (org-element--parse-paired-brackets ?\[)))
  2944. (and (org-string-nw-p p)
  2945. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2946. (value (buffer-substring-no-properties begin (point)))
  2947. (post-blank (skip-chars-forward " \t"))
  2948. (end (point)))
  2949. (list 'inline-babel-call
  2950. (list :call call
  2951. :inside-header inside-header
  2952. :arguments arguments
  2953. :end-header end-header
  2954. :begin begin
  2955. :end end
  2956. :value value
  2957. :post-blank post-blank)))))))
  2958. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2959. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2960. (concat "call_"
  2961. (org-element-property :call inline-babel-call)
  2962. (let ((h (org-element-property :inside-header inline-babel-call)))
  2963. (and h (format "[%s]" h)))
  2964. "(" (org-element-property :arguments inline-babel-call) ")"
  2965. (let ((h (org-element-property :end-header inline-babel-call)))
  2966. (and h (format "[%s]" h)))))
  2967. ;;;; Inline Src Block
  2968. (defun org-element-inline-src-block-parser ()
  2969. "Parse inline source block at point, if any.
  2970. When at an inline source block, return a list whose car is
  2971. `inline-src-block' and cdr a plist with `:begin', `:end',
  2972. `:language', `:value', `:parameters' and `:post-blank' as
  2973. keywords. Otherwise, return nil.
  2974. Assume point is at the beginning of the inline source block."
  2975. (save-excursion
  2976. (catch :no-object
  2977. (when (let ((case-fold-search nil))
  2978. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2979. (goto-char (match-end 1))
  2980. (let ((begin (match-beginning 0))
  2981. (language (match-string-no-properties 1))
  2982. (parameters
  2983. (let ((p (org-element--parse-paired-brackets ?\[)))
  2984. (and (org-string-nw-p p)
  2985. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2986. (value (or (org-element--parse-paired-brackets ?\{)
  2987. (throw :no-object nil)))
  2988. (post-blank (skip-chars-forward " \t")))
  2989. (list 'inline-src-block
  2990. (list :language language
  2991. :value value
  2992. :parameters parameters
  2993. :begin begin
  2994. :end (point)
  2995. :post-blank post-blank)))))))
  2996. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2997. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2998. (let ((language (org-element-property :language inline-src-block))
  2999. (arguments (org-element-property :parameters inline-src-block))
  3000. (body (org-element-property :value inline-src-block)))
  3001. (format "src_%s%s{%s}"
  3002. language
  3003. (if arguments (format "[%s]" arguments) "")
  3004. body)))
  3005. ;;;; Italic
  3006. (defun org-element-italic-parser ()
  3007. "Parse italic object at point, if any.
  3008. When at an italic object, return a list whose car is `italic' and
  3009. cdr is a plist with `:begin', `:end', `:contents-begin' and
  3010. `:contents-end' and `:post-blank' keywords. Otherwise, return
  3011. nil.
  3012. Assume point is at the first slash marker."
  3013. (org-element--parse-generic-emphasis "/" 'italic))
  3014. (defun org-element-italic-interpreter (_ contents)
  3015. "Interpret italic object as Org syntax.
  3016. CONTENTS is the contents of the object."
  3017. (format "/%s/" contents))
  3018. ;;;; Latex Fragment
  3019. (defun org-element-latex-fragment-parser ()
  3020. "Parse LaTeX fragment at point, if any.
  3021. When at a LaTeX fragment, return a list whose car is
  3022. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  3023. and `:post-blank' as keywords. Otherwise, return nil.
  3024. Assume point is at the beginning of the LaTeX fragment."
  3025. (catch 'no-object
  3026. (save-excursion
  3027. (let* ((begin (point))
  3028. (after-fragment
  3029. (cond
  3030. ((not (eq ?$ (char-after)))
  3031. (pcase (char-after (1+ (point)))
  3032. (?\( (search-forward "\\)" nil t))
  3033. (?\[ (search-forward "\\]" nil t))
  3034. (_
  3035. ;; Macro.
  3036. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  3037. \\|\\({[^{}\n]*}\\)\\)*")
  3038. (match-end 0)))))
  3039. ((eq ?$ (char-after (1+ (point))))
  3040. (search-forward "$$" nil t 2))
  3041. (t
  3042. (and (not (eq ?$ (char-before)))
  3043. (not (memq (char-after (1+ (point)))
  3044. '(?\s ?\t ?\n ?, ?. ?\;)))
  3045. (search-forward "$" nil t 2)
  3046. (not (memq (char-before (match-beginning 0))
  3047. '(?\s ?\t ?\n ?, ?.)))
  3048. (looking-at-p
  3049. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  3050. (point)))))
  3051. (post-blank
  3052. (if (not after-fragment) (throw 'no-object nil)
  3053. (goto-char after-fragment)
  3054. (skip-chars-forward " \t")))
  3055. (end (point)))
  3056. (list 'latex-fragment
  3057. (list :value (buffer-substring-no-properties begin after-fragment)
  3058. :begin begin
  3059. :end end
  3060. :post-blank post-blank))))))
  3061. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  3062. "Interpret LATEX-FRAGMENT object as Org syntax."
  3063. (org-element-property :value latex-fragment))
  3064. ;;;; Line Break
  3065. (defun org-element-line-break-parser ()
  3066. "Parse line break at point, if any.
  3067. When at a line break, return a list whose car is `line-break',
  3068. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  3069. Otherwise, return nil.
  3070. Assume point is at the beginning of the line break."
  3071. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  3072. (not (eq (char-before) ?\\)))
  3073. (list 'line-break
  3074. (list :begin (point)
  3075. :end (line-beginning-position 2)
  3076. :post-blank 0))))
  3077. (defun org-element-line-break-interpreter (&rest _)
  3078. "Interpret LINE-BREAK object as Org syntax."
  3079. "\\\\\n")
  3080. ;;;; Link
  3081. (defun org-element-link-parser ()
  3082. "Parse link at point, if any.
  3083. When at a link, return a list whose car is `link' and cdr a plist
  3084. with `:type', `:path', `:format', `:raw-link', `:application',
  3085. `:search-option', `:begin', `:end', `:contents-begin',
  3086. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  3087. nil.
  3088. Assume point is at the beginning of the link."
  3089. (catch 'no-object
  3090. (let ((begin (point))
  3091. end contents-begin contents-end link-end post-blank path type format
  3092. raw-link search-option application)
  3093. (cond
  3094. ;; Type 1: Text targeted from a radio target.
  3095. ((and org-target-link-regexp
  3096. (save-excursion (or (bolp) (backward-char))
  3097. (looking-at org-target-link-regexp)))
  3098. (setq type "radio")
  3099. (setq format 'plain)
  3100. (setq link-end (match-end 1))
  3101. (setq path (match-string-no-properties 1))
  3102. (setq contents-begin (match-beginning 1))
  3103. (setq contents-end (match-end 1)))
  3104. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  3105. ((looking-at org-link-bracket-re)
  3106. (setq format 'bracket)
  3107. (setq contents-begin (match-beginning 2))
  3108. (setq contents-end (match-end 2))
  3109. (setq link-end (match-end 0))
  3110. ;; RAW-LINK is the original link. Decode any encoding.
  3111. ;; Expand any abbreviation in it.
  3112. ;;
  3113. ;; Also treat any newline character and associated
  3114. ;; indentation as a single space character. This is not
  3115. ;; compatible with RFC 3986, which requires to ignore
  3116. ;; them altogether. However, doing so would require
  3117. ;; users to encode spaces on the fly when writing links
  3118. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  3119. ;; [[shell:ls *.org]], which defeats Org's focus on
  3120. ;; simplicity.
  3121. (setq raw-link (org-link-expand-abbrev
  3122. (org-link-unescape
  3123. (replace-regexp-in-string
  3124. "[ \t]*\n[ \t]*" " "
  3125. (match-string-no-properties 1)))))
  3126. ;; Determine TYPE of link and set PATH accordingly. According
  3127. ;; to RFC 3986, remove whitespaces from URI in external links.
  3128. ;; In internal ones, treat indentation as a single space.
  3129. (cond
  3130. ;; File type.
  3131. ((or (file-name-absolute-p raw-link)
  3132. (string-match "\\`\\.\\.?/" raw-link))
  3133. (setq type "file")
  3134. (setq path raw-link))
  3135. ;; Explicit type (http, irc, bbdb...).
  3136. ((string-match org-link-types-re raw-link)
  3137. (setq type (match-string 1 raw-link))
  3138. (setq path (substring raw-link (match-end 0))))
  3139. ;; Code-ref type: PATH is the name of the reference.
  3140. ((and (string-match-p "\\`(" raw-link)
  3141. (string-match-p ")\\'" raw-link))
  3142. (setq type "coderef")
  3143. (setq path (substring raw-link 1 -1)))
  3144. ;; Custom-id type: PATH is the name of the custom id.
  3145. ((= (string-to-char raw-link) ?#)
  3146. (setq type "custom-id")
  3147. (setq path (substring raw-link 1)))
  3148. ;; Fuzzy type: Internal link either matches a target, an
  3149. ;; headline name or nothing. PATH is the target or
  3150. ;; headline's name.
  3151. (t
  3152. (setq type "fuzzy")
  3153. (setq path raw-link))))
  3154. ;; Type 3: Plain link, e.g., https://orgmode.org
  3155. ((looking-at org-link-plain-re)
  3156. (setq format 'plain)
  3157. (setq raw-link (match-string-no-properties 0))
  3158. (setq type (match-string-no-properties 1))
  3159. (setq link-end (match-end 0))
  3160. (setq path (match-string-no-properties 2)))
  3161. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  3162. ;; bracket links, follow RFC 3986 and remove any extra
  3163. ;; whitespace in URI.
  3164. ((looking-at org-link-angle-re)
  3165. (setq format 'angle)
  3166. (setq type (match-string-no-properties 1))
  3167. (setq link-end (match-end 0))
  3168. (setq raw-link
  3169. (buffer-substring-no-properties
  3170. (match-beginning 1) (match-end 2)))
  3171. (setq path (replace-regexp-in-string
  3172. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  3173. (t (throw 'no-object nil)))
  3174. ;; In any case, deduce end point after trailing white space from
  3175. ;; LINK-END variable.
  3176. (save-excursion
  3177. (setq post-blank
  3178. (progn (goto-char link-end) (skip-chars-forward " \t")))
  3179. (setq end (point)))
  3180. ;; Special "file"-type link processing. Extract opening
  3181. ;; application and search option, if any. Also normalize URI.
  3182. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  3183. (setq application (match-string 1 type))
  3184. (setq type "file")
  3185. (when (string-match "::\\(.*\\)\\'" path)
  3186. (setq search-option (match-string 1 path))
  3187. (setq path (replace-match "" nil nil path)))
  3188. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3189. ;; Translate link, if `org-link-translation-function' is set.
  3190. (let ((trans (and (functionp org-link-translation-function)
  3191. (funcall org-link-translation-function type path))))
  3192. (when trans
  3193. (setq type (car trans))
  3194. (setq path (cdr trans))))
  3195. (list 'link
  3196. (list :type type
  3197. :path path
  3198. :format format
  3199. :raw-link (or raw-link path)
  3200. :application application
  3201. :search-option search-option
  3202. :begin begin
  3203. :end end
  3204. :contents-begin contents-begin
  3205. :contents-end contents-end
  3206. :post-blank post-blank)))))
  3207. (defun org-element-link-interpreter (link contents)
  3208. "Interpret LINK object as Org syntax.
  3209. CONTENTS is the contents of the object, or nil."
  3210. (let ((type (org-element-property :type link))
  3211. (path (org-element-property :path link)))
  3212. (if (string= type "radio") path
  3213. (let ((fmt (pcase (org-element-property :format link)
  3214. ;; Links with contents and internal links have to
  3215. ;; use bracket syntax. Ignore `:format' in these
  3216. ;; cases. This is also the default syntax when the
  3217. ;; property is not defined, e.g., when the object
  3218. ;; was crafted by the user.
  3219. ((guard contents)
  3220. (format "[[%%s][%s]]"
  3221. ;; Since this is going to be used as
  3222. ;; a format string, escape percent signs
  3223. ;; in description.
  3224. (replace-regexp-in-string "%" "%%" contents)))
  3225. ((or `bracket
  3226. `nil
  3227. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3228. "[[%s]]")
  3229. ;; Otherwise, just obey to `:format'.
  3230. (`angle "<%s>")
  3231. (`plain "%s")
  3232. (f (error "Wrong `:format' value: %s" f)))))
  3233. (format fmt
  3234. (pcase type
  3235. ("coderef" (format "(%s)" path))
  3236. ("custom-id" (concat "#" path))
  3237. ("file"
  3238. (let ((app (org-element-property :application link))
  3239. (opt (org-element-property :search-option link)))
  3240. (concat type (and app (concat "+" app)) ":"
  3241. path
  3242. (and opt (concat "::" opt)))))
  3243. ("fuzzy" path)
  3244. (_ (concat type ":" path))))))))
  3245. ;;;; Macro
  3246. (defun org-element-macro-parser ()
  3247. "Parse macro at point, if any.
  3248. When at a macro, return a list whose car is `macro' and cdr
  3249. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3250. `:post-blank' as keywords. Otherwise, return nil.
  3251. Assume point is at the macro."
  3252. (save-excursion
  3253. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3254. (let ((begin (point))
  3255. (key (downcase (match-string-no-properties 1)))
  3256. (value (match-string-no-properties 0))
  3257. (post-blank (progn (goto-char (match-end 0))
  3258. (skip-chars-forward " \t")))
  3259. (end (point))
  3260. (args (pcase (match-string-no-properties 3)
  3261. (`nil nil)
  3262. (a (org-macro-extract-arguments
  3263. (replace-regexp-in-string
  3264. "[ \t\r\n]+" " " (org-trim a)))))))
  3265. (list 'macro
  3266. (list :key key
  3267. :value value
  3268. :args args
  3269. :begin begin
  3270. :end end
  3271. :post-blank post-blank))))))
  3272. (defun org-element-macro-interpreter (macro _)
  3273. "Interpret MACRO object as Org syntax."
  3274. (format "{{{%s%s}}}"
  3275. (org-element-property :key macro)
  3276. (pcase (org-element-property :args macro)
  3277. (`nil "")
  3278. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3279. ;;;; Radio-target
  3280. (defun org-element-radio-target-parser ()
  3281. "Parse radio target at point, if any.
  3282. When at a radio target, return a list whose car is `radio-target'
  3283. and cdr a plist with `:begin', `:end', `:contents-begin',
  3284. `:contents-end', `:value' and `:post-blank' as keywords.
  3285. Otherwise, return nil.
  3286. Assume point is at the radio target."
  3287. (save-excursion
  3288. (when (looking-at org-radio-target-regexp)
  3289. (let ((begin (point))
  3290. (contents-begin (match-beginning 1))
  3291. (contents-end (match-end 1))
  3292. (value (match-string-no-properties 1))
  3293. (post-blank (progn (goto-char (match-end 0))
  3294. (skip-chars-forward " \t")))
  3295. (end (point)))
  3296. (list 'radio-target
  3297. (list :begin begin
  3298. :end end
  3299. :contents-begin contents-begin
  3300. :contents-end contents-end
  3301. :post-blank post-blank
  3302. :value value))))))
  3303. (defun org-element-radio-target-interpreter (_ contents)
  3304. "Interpret target object as Org syntax.
  3305. CONTENTS is the contents of the object."
  3306. (concat "<<<" contents ">>>"))
  3307. ;;;; Statistics Cookie
  3308. (defun org-element-statistics-cookie-parser ()
  3309. "Parse statistics cookie at point, if any.
  3310. When at a statistics cookie, return a list whose car is
  3311. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3312. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3313. Assume point is at the beginning of the statistics-cookie."
  3314. (save-excursion
  3315. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3316. (let* ((begin (point))
  3317. (value (buffer-substring-no-properties
  3318. (match-beginning 0) (match-end 0)))
  3319. (post-blank (progn (goto-char (match-end 0))
  3320. (skip-chars-forward " \t")))
  3321. (end (point)))
  3322. (list 'statistics-cookie
  3323. (list :begin begin
  3324. :end end
  3325. :value value
  3326. :post-blank post-blank))))))
  3327. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3328. "Interpret STATISTICS-COOKIE object as Org syntax."
  3329. (org-element-property :value statistics-cookie))
  3330. ;;;; Strike-Through
  3331. (defun org-element-strike-through-parser ()
  3332. "Parse strike-through object at point, if any.
  3333. When at a strike-through object, return a list whose car is
  3334. `strike-through' and cdr is a plist with `:begin', `:end',
  3335. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3336. Otherwise, return nil.
  3337. Assume point is at the first plus sign marker."
  3338. (org-element--parse-generic-emphasis "+" 'strike-through))
  3339. (defun org-element-strike-through-interpreter (_ contents)
  3340. "Interpret strike-through object as Org syntax.
  3341. CONTENTS is the contents of the object."
  3342. (format "+%s+" contents))
  3343. ;;;; Subscript
  3344. (defun org-element-subscript-parser ()
  3345. "Parse subscript at point, if any.
  3346. When at a subscript object, return a list whose car is
  3347. `subscript' and cdr a plist with `:begin', `:end',
  3348. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3349. `:post-blank' as keywords. Otherwise, return nil.
  3350. Assume point is at the underscore."
  3351. (save-excursion
  3352. (unless (bolp) (backward-char))
  3353. (when (looking-at org-match-substring-regexp)
  3354. (let ((bracketsp (match-beginning 4))
  3355. (begin (match-beginning 2))
  3356. (contents-begin (or (match-beginning 4)
  3357. (match-beginning 3)))
  3358. (contents-end (or (match-end 4) (match-end 3)))
  3359. (post-blank (progn (goto-char (match-end 0))
  3360. (skip-chars-forward " \t")))
  3361. (end (point)))
  3362. (list 'subscript
  3363. (list :begin begin
  3364. :end end
  3365. :use-brackets-p bracketsp
  3366. :contents-begin contents-begin
  3367. :contents-end contents-end
  3368. :post-blank post-blank))))))
  3369. (defun org-element-subscript-interpreter (subscript contents)
  3370. "Interpret SUBSCRIPT object as Org syntax.
  3371. CONTENTS is the contents of the object."
  3372. (format
  3373. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3374. contents))
  3375. ;;;; Superscript
  3376. (defun org-element-superscript-parser ()
  3377. "Parse superscript at point, if any.
  3378. When at a superscript object, return a list whose car is
  3379. `superscript' and cdr a plist with `:begin', `:end',
  3380. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3381. `:post-blank' as keywords. Otherwise, return nil.
  3382. Assume point is at the caret."
  3383. (save-excursion
  3384. (unless (bolp) (backward-char))
  3385. (when (looking-at org-match-substring-regexp)
  3386. (let ((bracketsp (match-beginning 4))
  3387. (begin (match-beginning 2))
  3388. (contents-begin (or (match-beginning 4)
  3389. (match-beginning 3)))
  3390. (contents-end (or (match-end 4) (match-end 3)))
  3391. (post-blank (progn (goto-char (match-end 0))
  3392. (skip-chars-forward " \t")))
  3393. (end (point)))
  3394. (list 'superscript
  3395. (list :begin begin
  3396. :end end
  3397. :use-brackets-p bracketsp
  3398. :contents-begin contents-begin
  3399. :contents-end contents-end
  3400. :post-blank post-blank))))))
  3401. (defun org-element-superscript-interpreter (superscript contents)
  3402. "Interpret SUPERSCRIPT object as Org syntax.
  3403. CONTENTS is the contents of the object."
  3404. (format
  3405. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3406. contents))
  3407. ;;;; Table Cell
  3408. (defun org-element-table-cell-parser ()
  3409. "Parse table cell at point.
  3410. Return a list whose car is `table-cell' and cdr is a plist
  3411. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3412. and `:post-blank' keywords."
  3413. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3414. (let* ((begin (match-beginning 0))
  3415. (end (match-end 0))
  3416. (contents-begin (match-beginning 1))
  3417. (contents-end (match-end 1)))
  3418. (list 'table-cell
  3419. (list :begin begin
  3420. :end end
  3421. :contents-begin contents-begin
  3422. :contents-end contents-end
  3423. :post-blank 0))))
  3424. (defun org-element-table-cell-interpreter (_ contents)
  3425. "Interpret table-cell element as Org syntax.
  3426. CONTENTS is the contents of the cell, or nil."
  3427. (concat " " contents " |"))
  3428. ;;;; Target
  3429. (defun org-element-target-parser ()
  3430. "Parse target at point, if any.
  3431. When at a target, return a list whose car is `target' and cdr
  3432. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3433. keywords. Otherwise, return nil.
  3434. Assume point is at the target."
  3435. (save-excursion
  3436. (when (looking-at org-target-regexp)
  3437. (let ((begin (point))
  3438. (value (match-string-no-properties 1))
  3439. (post-blank (progn (goto-char (match-end 0))
  3440. (skip-chars-forward " \t")))
  3441. (end (point)))
  3442. (list 'target
  3443. (list :begin begin
  3444. :end end
  3445. :value value
  3446. :post-blank post-blank))))))
  3447. (defun org-element-target-interpreter (target _)
  3448. "Interpret TARGET object as Org syntax."
  3449. (format "<<%s>>" (org-element-property :value target)))
  3450. ;;;; Timestamp
  3451. (defconst org-element--timestamp-regexp
  3452. (concat org-ts-regexp-both
  3453. "\\|"
  3454. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3455. "\\|"
  3456. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3457. "Regexp matching any timestamp type object.")
  3458. (defun org-element-timestamp-parser ()
  3459. "Parse time stamp at point, if any.
  3460. When at a time stamp, return a list whose car is `timestamp', and
  3461. cdr a plist with `:type', `:raw-value', `:year-start',
  3462. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3463. `:year-end', `:month-end', `:day-end', `:hour-end',
  3464. `:minute-end', `:repeater-type', `:repeater-value',
  3465. `:repeater-unit', `:warning-type', `:warning-value',
  3466. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3467. Otherwise, return nil.
  3468. Assume point is at the beginning of the timestamp."
  3469. (when (looking-at-p org-element--timestamp-regexp)
  3470. (save-excursion
  3471. (let* ((begin (point))
  3472. (activep (eq (char-after) ?<))
  3473. (raw-value
  3474. (progn
  3475. (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
  3476. (match-string-no-properties 0)))
  3477. (date-start (match-string-no-properties 1))
  3478. (date-end (match-string 3))
  3479. (diaryp (match-beginning 2))
  3480. (post-blank (progn (goto-char (match-end 0))
  3481. (skip-chars-forward " \t")))
  3482. (end (point))
  3483. (time-range
  3484. (and (not diaryp)
  3485. (string-match
  3486. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3487. date-start)
  3488. (cons (string-to-number (match-string 2 date-start))
  3489. (string-to-number (match-string 3 date-start)))))
  3490. (type (cond (diaryp 'diary)
  3491. ((and activep (or date-end time-range)) 'active-range)
  3492. (activep 'active)
  3493. ((or date-end time-range) 'inactive-range)
  3494. (t 'inactive)))
  3495. (repeater-props
  3496. (and (not diaryp)
  3497. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3498. raw-value)
  3499. (list
  3500. :repeater-type
  3501. (let ((type (match-string 1 raw-value)))
  3502. (cond ((equal "++" type) 'catch-up)
  3503. ((equal ".+" type) 'restart)
  3504. (t 'cumulate)))
  3505. :repeater-value (string-to-number (match-string 2 raw-value))
  3506. :repeater-unit
  3507. (pcase (string-to-char (match-string 3 raw-value))
  3508. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3509. (warning-props
  3510. (and (not diaryp)
  3511. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3512. (list
  3513. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3514. :warning-value (string-to-number (match-string 2 raw-value))
  3515. :warning-unit
  3516. (pcase (string-to-char (match-string 3 raw-value))
  3517. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3518. year-start month-start day-start hour-start minute-start year-end
  3519. month-end day-end hour-end minute-end)
  3520. ;; Parse date-start.
  3521. (unless diaryp
  3522. (let ((date (org-parse-time-string date-start t)))
  3523. (setq year-start (nth 5 date)
  3524. month-start (nth 4 date)
  3525. day-start (nth 3 date)
  3526. hour-start (nth 2 date)
  3527. minute-start (nth 1 date))))
  3528. ;; Compute date-end. It can be provided directly in time-stamp,
  3529. ;; or extracted from time range. Otherwise, it defaults to the
  3530. ;; same values as date-start.
  3531. (unless diaryp
  3532. (let ((date (and date-end (org-parse-time-string date-end t))))
  3533. (setq year-end (or (nth 5 date) year-start)
  3534. month-end (or (nth 4 date) month-start)
  3535. day-end (or (nth 3 date) day-start)
  3536. hour-end (or (nth 2 date) (car time-range) hour-start)
  3537. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3538. (list 'timestamp
  3539. (nconc (list :type type
  3540. :raw-value raw-value
  3541. :year-start year-start
  3542. :month-start month-start
  3543. :day-start day-start
  3544. :hour-start hour-start
  3545. :minute-start minute-start
  3546. :year-end year-end
  3547. :month-end month-end
  3548. :day-end day-end
  3549. :hour-end hour-end
  3550. :minute-end minute-end
  3551. :begin begin
  3552. :end end
  3553. :post-blank post-blank)
  3554. repeater-props
  3555. warning-props))))))
  3556. (defun org-element-timestamp-interpreter (timestamp _)
  3557. "Interpret TIMESTAMP object as Org syntax."
  3558. (let* ((repeat-string
  3559. (concat
  3560. (pcase (org-element-property :repeater-type timestamp)
  3561. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3562. (let ((val (org-element-property :repeater-value timestamp)))
  3563. (and val (number-to-string val)))
  3564. (pcase (org-element-property :repeater-unit timestamp)
  3565. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3566. (warning-string
  3567. (concat
  3568. (pcase (org-element-property :warning-type timestamp)
  3569. (`first "--") (`all "-"))
  3570. (let ((val (org-element-property :warning-value timestamp)))
  3571. (and val (number-to-string val)))
  3572. (pcase (org-element-property :warning-unit timestamp)
  3573. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3574. (build-ts-string
  3575. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3576. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3577. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3578. ;; specify a time range in the timestamp. REPEAT-STRING is
  3579. ;; the repeater string, if any.
  3580. (lambda (time activep &optional with-time-p hour-end minute-end)
  3581. (let ((ts (format-time-string
  3582. (funcall (if with-time-p #'cdr #'car)
  3583. org-time-stamp-formats)
  3584. time)))
  3585. (when (and hour-end minute-end)
  3586. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3587. (setq ts
  3588. (replace-match
  3589. (format "\\&-%02d:%02d" hour-end minute-end)
  3590. nil nil ts)))
  3591. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3592. (dolist (s (list repeat-string warning-string))
  3593. (when (org-string-nw-p s)
  3594. (setq ts (concat (substring ts 0 -1)
  3595. " "
  3596. s
  3597. (substring ts -1)))))
  3598. ;; Return value.
  3599. ts)))
  3600. (type (org-element-property :type timestamp)))
  3601. (pcase type
  3602. ((or `active `inactive)
  3603. (let* ((minute-start (org-element-property :minute-start timestamp))
  3604. (minute-end (org-element-property :minute-end timestamp))
  3605. (hour-start (org-element-property :hour-start timestamp))
  3606. (hour-end (org-element-property :hour-end timestamp))
  3607. (time-range-p (and hour-start hour-end minute-start minute-end
  3608. (or (/= hour-start hour-end)
  3609. (/= minute-start minute-end)))))
  3610. (funcall
  3611. build-ts-string
  3612. (encode-time 0
  3613. (or minute-start 0)
  3614. (or hour-start 0)
  3615. (org-element-property :day-start timestamp)
  3616. (org-element-property :month-start timestamp)
  3617. (org-element-property :year-start timestamp))
  3618. (eq type 'active)
  3619. (and hour-start minute-start)
  3620. (and time-range-p hour-end)
  3621. (and time-range-p minute-end))))
  3622. ((or `active-range `inactive-range)
  3623. (let ((minute-start (org-element-property :minute-start timestamp))
  3624. (minute-end (org-element-property :minute-end timestamp))
  3625. (hour-start (org-element-property :hour-start timestamp))
  3626. (hour-end (org-element-property :hour-end timestamp)))
  3627. (concat
  3628. (funcall
  3629. build-ts-string (encode-time
  3630. 0
  3631. (or minute-start 0)
  3632. (or hour-start 0)
  3633. (org-element-property :day-start timestamp)
  3634. (org-element-property :month-start timestamp)
  3635. (org-element-property :year-start timestamp))
  3636. (eq type 'active-range)
  3637. (and hour-start minute-start))
  3638. "--"
  3639. (funcall build-ts-string
  3640. (encode-time 0
  3641. (or minute-end 0)
  3642. (or hour-end 0)
  3643. (org-element-property :day-end timestamp)
  3644. (org-element-property :month-end timestamp)
  3645. (org-element-property :year-end timestamp))
  3646. (eq type 'active-range)
  3647. (and hour-end minute-end)))))
  3648. (_ (org-element-property :raw-value timestamp)))))
  3649. ;;;; Underline
  3650. (defun org-element-underline-parser ()
  3651. "Parse underline object at point, if any.
  3652. When at an underline object, return a list whose car is
  3653. `underline' and cdr is a plist with `:begin', `:end',
  3654. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3655. Otherwise, return nil.
  3656. Assume point is at the first underscore marker."
  3657. (org-element--parse-generic-emphasis "_" 'underline))
  3658. (defun org-element-underline-interpreter (_ contents)
  3659. "Interpret underline object as Org syntax.
  3660. CONTENTS is the contents of the object."
  3661. (format "_%s_" contents))
  3662. ;;;; Verbatim
  3663. (defun org-element-verbatim-parser ()
  3664. "Parse verbatim object at point, if any.
  3665. When at a verbatim object, return a list whose car is `verbatim'
  3666. and cdr is a plist with `:value', `:begin', `:end' and
  3667. `:post-blank' keywords. Otherwise, return nil.
  3668. Assume point is at the first equal sign marker."
  3669. (org-element--parse-generic-emphasis "=" 'verbatim))
  3670. (defun org-element-verbatim-interpreter (verbatim _)
  3671. "Interpret VERBATIM object as Org syntax."
  3672. (format "=%s=" (org-element-property :value verbatim)))
  3673. ;;; Parsing Element Starting At Point
  3674. ;;
  3675. ;; `org-element--current-element' is the core function of this section.
  3676. ;; It returns the Lisp representation of the element starting at
  3677. ;; point.
  3678. (defvar org-element--cache-sync-requests); Declared later
  3679. (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
  3680. "Parse the element starting at point.
  3681. Return value is a list like (TYPE PROPS) where TYPE is the type
  3682. of the element and PROPS a plist of properties associated to the
  3683. element.
  3684. Possible types are defined in `org-element-all-elements'.
  3685. LIMIT bounds the search.
  3686. Optional argument GRANULARITY determines the depth of the
  3687. recursion. Allowed values are `headline', `greater-element',
  3688. `element', `object' or nil. When it is broader than `object' (or
  3689. nil), secondary values will not be parsed, since they only
  3690. contain objects.
  3691. Optional argument MODE, when non-nil, can be either
  3692. `first-section', `item', `node-property', `planning',
  3693. `property-drawer', `section', `table-row', or `top-comment'.
  3694. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3695. computed.
  3696. Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
  3697. will also add current element to cache if it is not yet there. Use
  3698. this argument with care, as validity of the element in parse tree is
  3699. not checked.
  3700. This function assumes point is always at the beginning of the
  3701. element it has to parse."
  3702. (let* ((element (and (not (buffer-narrowed-p))
  3703. (org-element--cache-active-p)
  3704. (not org-element--cache-sync-requests)
  3705. (org-element--cache-find (point) t)))
  3706. (element (progn (while (and element
  3707. (not (and (eq (point) (org-element-property :begin element))
  3708. (eq mode (org-element-property :mode element)))))
  3709. (setq element (org-element-property :parent element)))
  3710. element))
  3711. (old-element element)
  3712. (element (when
  3713. (pcase (org-element-property :granularity element)
  3714. (`nil t)
  3715. (`object t)
  3716. (`element (not (memq granularity '(nil object))))
  3717. (`greater-element (not (memq granularity '(nil object element))))
  3718. (`headline (eq granularity 'headline)))
  3719. element)))
  3720. (if element
  3721. element
  3722. (save-excursion
  3723. (let ((case-fold-search t)
  3724. ;; Determine if parsing depth allows for secondary strings
  3725. ;; parsing. It only applies to elements referenced in
  3726. ;; `org-element-secondary-value-alist'.
  3727. (raw-secondary-p (and granularity (not (eq granularity 'object))))
  3728. result)
  3729. (setq
  3730. result
  3731. (cond
  3732. ;; Item.
  3733. ((eq mode 'item)
  3734. (org-element-item-parser limit structure raw-secondary-p))
  3735. ;; Table Row.
  3736. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3737. ;; Node Property.
  3738. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3739. ;; Headline.
  3740. ((org-with-limited-levels (looking-at-p org-outline-regexp-bol))
  3741. (org-element-headline-parser limit raw-secondary-p))
  3742. ;; Sections (must be checked after headline).
  3743. ((eq mode 'section) (org-element-section-parser limit))
  3744. ((eq mode 'first-section)
  3745. (org-element-section-parser
  3746. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3747. limit)))
  3748. ;; Comments.
  3749. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3750. (org-element-comment-parser limit))
  3751. ;; Planning.
  3752. ((and (eq mode 'planning)
  3753. (eq ?* (char-after (line-beginning-position 0)))
  3754. (looking-at org-element-planning-line-re))
  3755. (org-element-planning-parser limit))
  3756. ;; Property drawer.
  3757. ((and (pcase mode
  3758. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3759. ((or `property-drawer `top-comment)
  3760. (save-excursion
  3761. (beginning-of-line 0)
  3762. (not (looking-at "[[:blank:]]*$"))))
  3763. (_ nil))
  3764. (looking-at org-property-drawer-re))
  3765. (org-element-property-drawer-parser limit))
  3766. ;; When not at bol, point is at the beginning of an item or
  3767. ;; a footnote definition: next item is always a paragraph.
  3768. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3769. ;; Clock.
  3770. ((looking-at org-element-clock-line-re)
  3771. (org-element-clock-parser limit))
  3772. ;; Inlinetask.
  3773. ((looking-at "^\\*+ ")
  3774. (org-element-inlinetask-parser limit raw-secondary-p))
  3775. ;; From there, elements can have affiliated keywords.
  3776. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3777. limit (memq granularity '(nil object)))))
  3778. (cond
  3779. ;; Jumping over affiliated keywords put point off-limits.
  3780. ;; Parse them as regular keywords.
  3781. ((and (cdr affiliated) (>= (point) limit))
  3782. (goto-char (car affiliated))
  3783. (org-element-keyword-parser limit nil))
  3784. ;; LaTeX Environment.
  3785. ((looking-at org-element--latex-begin-environment)
  3786. (org-element-latex-environment-parser limit affiliated))
  3787. ;; Drawer.
  3788. ((looking-at org-element-drawer-re)
  3789. (org-element-drawer-parser limit affiliated))
  3790. ;; Fixed Width
  3791. ((looking-at "[ \t]*:\\( \\|$\\)")
  3792. (org-element-fixed-width-parser limit affiliated))
  3793. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3794. ;; Keywords.
  3795. ((looking-at "[ \t]*#\\+")
  3796. (goto-char (match-end 0))
  3797. (cond
  3798. ((looking-at "BEGIN_\\(\\S-+\\)")
  3799. (beginning-of-line)
  3800. (funcall (pcase (upcase (match-string 1))
  3801. ("CENTER" #'org-element-center-block-parser)
  3802. ("COMMENT" #'org-element-comment-block-parser)
  3803. ("EXAMPLE" #'org-element-example-block-parser)
  3804. ("EXPORT" #'org-element-export-block-parser)
  3805. ("QUOTE" #'org-element-quote-block-parser)
  3806. ("SRC" #'org-element-src-block-parser)
  3807. ("VERSE" #'org-element-verse-block-parser)
  3808. (_ #'org-element-special-block-parser))
  3809. limit
  3810. affiliated))
  3811. ((looking-at "CALL:")
  3812. (beginning-of-line)
  3813. (org-element-babel-call-parser limit affiliated))
  3814. ((save-excursion
  3815. (beginning-of-line)
  3816. (looking-at org-element-dynamic-block-open-re))
  3817. (beginning-of-line)
  3818. (org-element-dynamic-block-parser limit affiliated))
  3819. ((looking-at "\\S-+:")
  3820. (beginning-of-line)
  3821. (org-element-keyword-parser limit affiliated))
  3822. (t
  3823. (beginning-of-line)
  3824. (org-element-paragraph-parser limit affiliated))))
  3825. ;; Footnote Definition.
  3826. ((looking-at org-footnote-definition-re)
  3827. (org-element-footnote-definition-parser limit affiliated))
  3828. ;; Horizontal Rule.
  3829. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3830. (org-element-horizontal-rule-parser limit affiliated))
  3831. ;; Diary Sexp.
  3832. ((looking-at "%%(")
  3833. (org-element-diary-sexp-parser limit affiliated))
  3834. ;; Table.
  3835. ((or (looking-at "[ \t]*|")
  3836. ;; There is no strict definition of a table.el
  3837. ;; table. Try to prevent false positive while being
  3838. ;; quick.
  3839. (let ((rule-regexp
  3840. (rx (zero-or-more (any " \t"))
  3841. "+"
  3842. (one-or-more (one-or-more "-") "+")
  3843. (zero-or-more (any " \t"))
  3844. eol))
  3845. (non-table.el-line
  3846. (rx bol
  3847. (zero-or-more (any " \t"))
  3848. (or eol (not (any "+| \t")))))
  3849. (next (line-beginning-position 2)))
  3850. ;; Start with a full rule.
  3851. (and
  3852. (looking-at rule-regexp)
  3853. (< next limit) ;no room for a table.el table
  3854. (save-excursion
  3855. (end-of-line)
  3856. (cond
  3857. ;; Must end with a full rule.
  3858. ((not (re-search-forward non-table.el-line limit 'move))
  3859. (if (bolp) (forward-line -1) (beginning-of-line))
  3860. (looking-at rule-regexp))
  3861. ;; Ignore pseudo-tables with a single
  3862. ;; rule.
  3863. ((= next (line-beginning-position))
  3864. nil)
  3865. ;; Must end with a full rule.
  3866. (t
  3867. (forward-line -1)
  3868. (looking-at rule-regexp)))))))
  3869. (org-element-table-parser limit affiliated))
  3870. ;; List.
  3871. ((looking-at (org-item-re))
  3872. (org-element-plain-list-parser
  3873. limit affiliated
  3874. (or structure (org-element--list-struct limit))))
  3875. ;; Default element: Paragraph.
  3876. (t (org-element-paragraph-parser limit affiliated)))))))
  3877. (when result
  3878. (org-element-put-property result :mode mode)
  3879. (org-element-put-property result :granularity granularity))
  3880. (when (and (not (buffer-narrowed-p))
  3881. (org-element--cache-active-p)
  3882. (not org-element--cache-sync-requests)
  3883. add-to-cache)
  3884. (if (not old-element)
  3885. (setq result (org-element--cache-put result))
  3886. (org-element-set-element old-element result)
  3887. (setq result old-element)))
  3888. result)))))
  3889. ;; Most elements can have affiliated keywords. When looking for an
  3890. ;; element beginning, we want to move before them, as they belong to
  3891. ;; that element, and, in the meantime, collect information they give
  3892. ;; into appropriate properties. Hence the following function.
  3893. (defun org-element--collect-affiliated-keywords (limit parse)
  3894. "Collect affiliated keywords from point down to LIMIT.
  3895. Return a list whose CAR is the position at the first of them and
  3896. CDR a plist of keywords and values and move point to the
  3897. beginning of the first line after them.
  3898. As a special case, if element doesn't start at the beginning of
  3899. the line (e.g., a paragraph starting an item), CAR is current
  3900. position of point and CDR is nil.
  3901. When PARSE is non-nil, values from keywords belonging to
  3902. `org-element-parsed-keywords' are parsed as secondary strings."
  3903. (if (not (bolp)) (list (point))
  3904. (let ((case-fold-search t)
  3905. (origin (point))
  3906. ;; RESTRICT is the list of objects allowed in parsed
  3907. ;; keywords value. If PARSE is nil, no object is allowed.
  3908. (restrict (and parse (org-element-restriction 'keyword)))
  3909. output)
  3910. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3911. (let* ((raw-kwd (upcase (match-string 1)))
  3912. ;; Apply translation to RAW-KWD. From there, KWD is
  3913. ;; the official keyword.
  3914. (kwd (or (cdr (assoc raw-kwd
  3915. org-element-keyword-translation-alist))
  3916. raw-kwd))
  3917. ;; PARSED? is non-nil when keyword should have its
  3918. ;; value parsed.
  3919. (parsed? (member kwd org-element-parsed-keywords))
  3920. ;; Find main value for any keyword.
  3921. (value
  3922. (let ((beg (match-end 0))
  3923. (end (save-excursion
  3924. (end-of-line)
  3925. (skip-chars-backward " \t")
  3926. (point))))
  3927. (if parsed?
  3928. (save-match-data
  3929. (org-element--parse-objects beg end nil restrict))
  3930. (org-trim (buffer-substring-no-properties beg end)))))
  3931. ;; If KWD is a dual keyword, find its secondary value.
  3932. ;; Maybe parse it.
  3933. (dual? (member kwd org-element-dual-keywords))
  3934. (dual-value
  3935. (and dual?
  3936. (let ((sec (match-string-no-properties 2)))
  3937. (cond
  3938. ((and sec parsed?)
  3939. (save-match-data
  3940. (org-element--parse-objects
  3941. (match-beginning 2) (match-end 2) nil restrict)))
  3942. (sec sec)))))
  3943. ;; Attribute a property name to KWD.
  3944. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3945. ;; Now set final shape for VALUE.
  3946. (when dual?
  3947. (setq value (and (or value dual-value) (cons value dual-value))))
  3948. (when (or (member kwd org-element-multiple-keywords)
  3949. ;; Attributes can always appear on multiple lines.
  3950. (string-match "^ATTR_" kwd))
  3951. (setq value (cons value (plist-get output kwd-sym))))
  3952. ;; Eventually store the new value in OUTPUT.
  3953. (setq output (plist-put output kwd-sym value))
  3954. ;; Move to next keyword.
  3955. (forward-line)))
  3956. ;; If affiliated keywords are orphaned: move back to first one.
  3957. ;; They will be parsed as a paragraph.
  3958. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3959. ;; Return value.
  3960. (cons origin output))))
  3961. ;;; The Org Parser
  3962. ;;
  3963. ;; The two major functions here are `org-element-parse-buffer', which
  3964. ;; parses Org syntax inside the current buffer, taking into account
  3965. ;; region, narrowing, or even visibility if specified, and
  3966. ;; `org-element-parse-secondary-string', which parses objects within
  3967. ;; a given string.
  3968. ;;
  3969. ;; The (almost) almighty `org-element-map' allows applying a function
  3970. ;; on elements or objects matching some type, and accumulating the
  3971. ;; resulting values. In an export situation, it also skips unneeded
  3972. ;; parts of the parse tree.
  3973. (defun org-element-parse-buffer (&optional granularity visible-only)
  3974. "Recursively parse the buffer and return structure.
  3975. If narrowing is in effect, only parse the visible part of the
  3976. buffer.
  3977. Optional argument GRANULARITY determines the depth of the
  3978. recursion. It can be set to the following symbols:
  3979. `headline' Only parse headlines.
  3980. `greater-element' Don't recurse into greater elements except
  3981. headlines and sections. Thus, elements
  3982. parsed are the top-level ones.
  3983. `element' Parse everything but objects and plain text.
  3984. `object' Parse the complete buffer (default).
  3985. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3986. elements.
  3987. An element or object is represented as a list with the
  3988. pattern (TYPE PROPERTIES CONTENTS), where :
  3989. TYPE is a symbol describing the element or object. See
  3990. `org-element-all-elements' and `org-element-all-objects' for an
  3991. exhaustive list of such symbols. One can retrieve it with
  3992. `org-element-type' function.
  3993. PROPERTIES is the list of attributes attached to the element or
  3994. object, as a plist. Although most of them are specific to the
  3995. element or object type, all types share `:begin', `:end',
  3996. `:post-blank' and `:parent' properties, which respectively
  3997. refer to buffer position where the element or object starts,
  3998. ends, the number of white spaces or blank lines after it, and
  3999. the element or object containing it. Properties values can be
  4000. obtained by using `org-element-property' function.
  4001. CONTENTS is a list of elements, objects or raw strings
  4002. contained in the current element or object, when applicable.
  4003. One can access them with `org-element-contents' function.
  4004. The Org buffer has `org-data' as type and nil as properties.
  4005. `org-element-map' function can be used to find specific elements
  4006. or objects within the parse tree.
  4007. This function assumes that current major mode is `org-mode'."
  4008. (save-excursion
  4009. (goto-char (point-min))
  4010. (let ((org-data (org-element-org-data-parser))
  4011. (gc-cons-threshold #x40000000))
  4012. (org-skip-whitespace)
  4013. (org-element--parse-elements
  4014. (point-at-bol) (point-max)
  4015. ;; Start in `first-section' mode so text before the first
  4016. ;; headline belongs to a section.
  4017. 'first-section nil granularity visible-only org-data))))
  4018. (defun org-element-parse-secondary-string (string restriction &optional parent)
  4019. "Recursively parse objects in STRING and return structure.
  4020. RESTRICTION is a symbol limiting the object types that will be
  4021. looked after.
  4022. Optional argument PARENT, when non-nil, is the element or object
  4023. containing the secondary string. It is used to set correctly
  4024. `:parent' property within the string.
  4025. If STRING is the empty string or nil, return nil."
  4026. (cond
  4027. ((not string) nil)
  4028. ((equal string "") nil)
  4029. (t (let ((local-variables (buffer-local-variables)))
  4030. (with-temp-buffer
  4031. (dolist (v local-variables)
  4032. (ignore-errors
  4033. (if (symbolp v) (makunbound v)
  4034. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  4035. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  4036. (set (make-local-variable (car v)) (cdr v))))))
  4037. ;; Transferring local variables may put the temporary buffer
  4038. ;; into a read-only state. Make sure we can insert STRING.
  4039. (let ((inhibit-read-only t)) (insert string))
  4040. ;; Prevent "Buffer *temp* modified; kill anyway?".
  4041. (restore-buffer-modified-p nil)
  4042. (org-element--parse-objects
  4043. (point-min) (point-max) nil restriction parent))))))
  4044. (defun org-element-map
  4045. (data types fun &optional info first-match no-recursion with-affiliated)
  4046. "Map a function on selected elements or objects.
  4047. DATA is a parse tree (for example, returned by
  4048. `org-element-parse-buffer'), an element, an object, a string, or a
  4049. list of such constructs. TYPES is a symbol or list of symbols of
  4050. elements or object types (see `org-element-all-elements' and
  4051. `org-element-all-objects' for a complete list of types). FUN is the
  4052. function called on the matching element or object. It has to accept
  4053. one argument: the element or object itself.
  4054. When optional argument INFO is non-nil, it should be a plist
  4055. holding export options. In that case, parts of the parse tree
  4056. not exportable according to that property list will be skipped.
  4057. When optional argument FIRST-MATCH is non-nil, stop at the first
  4058. match for which FUN doesn't return nil, and return that value.
  4059. Optional argument NO-RECURSION is a symbol or a list of symbols
  4060. representing elements or objects types. `org-element-map' won't
  4061. enter any recursive element or object whose type belongs to that
  4062. list. Though, FUN can still be applied on them.
  4063. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  4064. apply to matching objects within parsed affiliated keywords (see
  4065. `org-element-parsed-keywords').
  4066. Nil values returned from FUN do not appear in the results.
  4067. Examples:
  4068. ---------
  4069. Assuming TREE is a variable containing an Org buffer parse tree,
  4070. the following example will return a flat list of all `src-block'
  4071. and `example-block' elements in it:
  4072. (setq tree (org-element-parse-buffer))
  4073. (org-element-map tree \\='(example-block src-block) #\\='identity)
  4074. The following snippet will find the first headline with a level
  4075. of 1 and a \"phone\" tag, and will return its beginning position:
  4076. (org-element-map tree \\='headline
  4077. (lambda (hl)
  4078. (and (= (org-element-property :level hl) 1)
  4079. (member \"phone\" (org-element-property :tags hl))
  4080. (org-element-property :begin hl)))
  4081. nil t)
  4082. The next example will return a flat list of all `plain-list' type
  4083. elements in TREE that are not a sub-list themselves:
  4084. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  4085. Eventually, this example will return a flat list of all `bold'
  4086. type objects containing a `latex-snippet' type object, even
  4087. looking into captions:
  4088. (org-element-map tree \\='bold
  4089. (lambda (b)
  4090. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  4091. nil nil nil t)"
  4092. (declare (indent 2))
  4093. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  4094. (let* ((types (if (listp types) types (list types)))
  4095. (no-recursion (if (listp no-recursion) no-recursion
  4096. (list no-recursion)))
  4097. ;; Recursion depth is determined by --CATEGORY.
  4098. (--category
  4099. (catch :--found
  4100. (let ((category 'greater-elements)
  4101. (all-objects (cons 'plain-text org-element-all-objects)))
  4102. (dolist (type types category)
  4103. (cond ((memq type all-objects)
  4104. ;; If one object is found, the function has
  4105. ;; to recurse into every object.
  4106. (throw :--found 'objects))
  4107. ((not (memq type org-element-greater-elements))
  4108. ;; If one regular element is found, the
  4109. ;; function has to recurse, at least, into
  4110. ;; every element it encounters.
  4111. (and (not (eq category 'elements))
  4112. (setq category 'elements))))))))
  4113. --acc)
  4114. (letrec ((--walk-tree
  4115. (lambda (--data)
  4116. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  4117. ;; holding contextual information.
  4118. (let ((--type (org-element-type --data)))
  4119. (cond
  4120. ((not --data))
  4121. ;; Ignored element in an export context.
  4122. ((and info (memq --data (plist-get info :ignore-list))))
  4123. ;; List of elements or objects.
  4124. ((not --type) (mapc --walk-tree --data))
  4125. ;; Unconditionally enter parse trees.
  4126. ((eq --type 'org-data)
  4127. (mapc --walk-tree (org-element-contents --data)))
  4128. (t
  4129. ;; Check if TYPE is matching among TYPES. If so,
  4130. ;; apply FUN to --DATA and accumulate return value
  4131. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  4132. (when (memq --type types)
  4133. (let ((result (funcall fun --data)))
  4134. (cond ((not result))
  4135. (first-match (throw :--map-first-match result))
  4136. (t (push result --acc)))))
  4137. ;; If --DATA has a secondary string that can contain
  4138. ;; objects with their type among TYPES, look inside.
  4139. (when (and (eq --category 'objects) (not (stringp --data)))
  4140. (dolist (p (cdr (assq --type
  4141. org-element-secondary-value-alist)))
  4142. (funcall --walk-tree (org-element-property p --data))))
  4143. ;; If --DATA has any parsed affiliated keywords and
  4144. ;; WITH-AFFILIATED is non-nil, look for objects in
  4145. ;; them.
  4146. (when (and with-affiliated
  4147. (eq --category 'objects)
  4148. (eq (org-element-class --data) 'element))
  4149. (dolist (kwd-pair org-element--parsed-properties-alist)
  4150. (let ((kwd (car kwd-pair))
  4151. (value (org-element-property (cdr kwd-pair) --data)))
  4152. ;; Pay attention to the type of parsed
  4153. ;; keyword. In particular, preserve order for
  4154. ;; multiple keywords.
  4155. (cond
  4156. ((not value))
  4157. ((member kwd org-element-dual-keywords)
  4158. (if (member kwd org-element-multiple-keywords)
  4159. (dolist (line (reverse value))
  4160. (funcall --walk-tree (cdr line))
  4161. (funcall --walk-tree (car line)))
  4162. (funcall --walk-tree (cdr value))
  4163. (funcall --walk-tree (car value))))
  4164. ((member kwd org-element-multiple-keywords)
  4165. (mapc --walk-tree (reverse value)))
  4166. (t (funcall --walk-tree value))))))
  4167. ;; Determine if a recursion into --DATA is possible.
  4168. (cond
  4169. ;; --TYPE is explicitly removed from recursion.
  4170. ((memq --type no-recursion))
  4171. ;; --DATA has no contents.
  4172. ((not (org-element-contents --data)))
  4173. ;; Looking for greater elements but --DATA is
  4174. ;; simply an element or an object.
  4175. ((and (eq --category 'greater-elements)
  4176. (not (memq --type org-element-greater-elements))))
  4177. ;; Looking for elements but --DATA is an object.
  4178. ((and (eq --category 'elements)
  4179. (eq (org-element-class --data) 'object)))
  4180. ;; In any other case, map contents.
  4181. (t (mapc --walk-tree (org-element-contents --data))))))))))
  4182. (catch :--map-first-match
  4183. (funcall --walk-tree data)
  4184. ;; Return value in a proper order.
  4185. (nreverse --acc)))))
  4186. ;; The following functions are internal parts of the parser.
  4187. ;;
  4188. ;; The first one, `org-element--parse-elements' acts at the element's
  4189. ;; level.
  4190. ;;
  4191. ;; The second one, `org-element--parse-objects' applies on all objects
  4192. ;; of a paragraph or a secondary string. It calls
  4193. ;; `org-element--object-lex' to find the next object in the current
  4194. ;; container.
  4195. (defsubst org-element--next-mode (mode type parent?)
  4196. "Return next mode according to current one.
  4197. MODE is a symbol representing the expectation about the next
  4198. element or object. Meaningful values are `first-section',
  4199. `item', `node-property', `planning', `property-drawer',
  4200. `section', `table-row', `top-comment', and nil.
  4201. TYPE is the type of the current element or object.
  4202. If PARENT? is non-nil, assume the next element or object will be
  4203. located inside the current one."
  4204. (if parent?
  4205. (pcase type
  4206. (`headline 'section)
  4207. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4208. ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
  4209. ((and (guard (not mode)) `org-data) 'first-section)
  4210. (`inlinetask 'planning)
  4211. (`plain-list 'item)
  4212. (`property-drawer 'node-property)
  4213. (`section 'planning)
  4214. (`table 'table-row))
  4215. (pcase mode
  4216. (`item 'item)
  4217. (`node-property 'node-property)
  4218. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4219. (`table-row 'table-row)
  4220. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4221. (defun org-element--parse-elements
  4222. (beg end mode structure granularity visible-only acc)
  4223. "Parse elements between BEG and END positions.
  4224. MODE prioritizes some elements over the others. It can be set to
  4225. `first-section', `item', `node-property', `planning',
  4226. `property-drawer', `section', `table-row', `top-comment', or nil.
  4227. When value is `item', STRUCTURE will be used as the current list
  4228. structure.
  4229. GRANULARITY determines the depth of the recursion. See
  4230. `org-element-parse-buffer' for more information.
  4231. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4232. elements.
  4233. Elements are accumulated into ACC."
  4234. (save-excursion
  4235. (goto-char beg)
  4236. ;; When parsing only headlines, skip any text before first one.
  4237. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4238. (org-with-limited-levels (outline-next-heading)))
  4239. (let (elements)
  4240. (while (< (point) end)
  4241. ;; Visible only: skip invisible parts due to folding.
  4242. (if (and visible-only (org-invisible-p nil t))
  4243. (progn
  4244. (goto-char (org-find-visible))
  4245. (when (and (eolp) (not (eobp))) (forward-char)))
  4246. ;; Find current element's type and parse it accordingly to
  4247. ;; its category.
  4248. (let* ((element (org-element-copy
  4249. ;; `org-element--current-element' may return cached
  4250. ;; elements. Below code reassigns
  4251. ;; `:parent' property of the element and
  4252. ;; may interfere with cache
  4253. ;; synchronisation if parent element is not
  4254. ;; yet in cache. Moreover, the returned
  4255. ;; structure may be altered by caller code
  4256. ;; arbitrarily. Hence, we return a copy of
  4257. ;; the potentially cached element to make
  4258. ;; potential modifications safe for element
  4259. ;; cache.
  4260. (org-element--current-element
  4261. end granularity mode structure)))
  4262. (type (org-element-type element))
  4263. (cbeg (org-element-property :contents-begin element)))
  4264. (goto-char (org-element-property :end element))
  4265. ;; Fill ELEMENT contents by side-effect.
  4266. (cond
  4267. ;; If element has no contents, don't modify it.
  4268. ((not cbeg))
  4269. ;; Greater element: parse it between `contents-begin' and
  4270. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4271. ;; or ELEMENT is a headline, in which case going inside
  4272. ;; is mandatory, in order to get sub-level headings.
  4273. ((and (memq type org-element-greater-elements)
  4274. (or (memq granularity '(element object nil))
  4275. (and (eq granularity 'greater-element)
  4276. (eq type 'section))
  4277. (eq type 'headline)))
  4278. (org-element--parse-elements
  4279. cbeg (org-element-property :contents-end element)
  4280. ;; Possibly switch to a special mode.
  4281. (org-element--next-mode mode type t)
  4282. (and (memq type '(item plain-list))
  4283. (org-element-property :structure element))
  4284. granularity visible-only element))
  4285. ;; ELEMENT has contents. Parse objects inside, if
  4286. ;; GRANULARITY allows it.
  4287. ((memq granularity '(object nil))
  4288. (org-element--parse-objects
  4289. cbeg (org-element-property :contents-end element) element
  4290. (org-element-restriction type))))
  4291. (push (org-element-put-property element :parent acc) elements)
  4292. ;; Update mode.
  4293. (setq mode (org-element--next-mode mode type nil)))))
  4294. ;; Return result.
  4295. (org-element-put-property acc :granularity granularity)
  4296. (apply #'org-element-set-contents acc (nreverse elements)))))
  4297. (defun org-element--object-lex (restriction)
  4298. "Return next object in current buffer or nil.
  4299. RESTRICTION is a list of object types, as symbols, that should be
  4300. looked after. This function assumes that the buffer is narrowed
  4301. to an appropriate container (e.g., a paragraph)."
  4302. (cond
  4303. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4304. ((memq 'citation-reference restriction)
  4305. (org-element-citation-reference-parser))
  4306. (t
  4307. (let* ((start (point))
  4308. (limit
  4309. ;; Object regexp sometimes needs to have a peek at
  4310. ;; a character ahead. Therefore, when there is a hard
  4311. ;; limit, make it one more than the true beginning of the
  4312. ;; radio target.
  4313. (save-excursion
  4314. (cond ((not org-target-link-regexp) nil)
  4315. ((not (memq 'link restriction)) nil)
  4316. ((progn
  4317. (unless (bolp) (forward-char -1))
  4318. (not (re-search-forward org-target-link-regexp nil t)))
  4319. nil)
  4320. ;; Since we moved backward, we do not want to
  4321. ;; match again an hypothetical 1-character long
  4322. ;; radio link before us. Realizing that this can
  4323. ;; only happen if such a radio link starts at
  4324. ;; beginning of line, we prevent this here.
  4325. ((and (= start (1+ (line-beginning-position)))
  4326. (= start (match-end 1)))
  4327. (and (re-search-forward org-target-link-regexp nil t)
  4328. (1+ (match-beginning 1))))
  4329. (t (1+ (match-beginning 1))))))
  4330. found)
  4331. (save-excursion
  4332. (while (and (not found)
  4333. (re-search-forward org-element--object-regexp limit 'move))
  4334. (goto-char (match-beginning 0))
  4335. (let ((result (match-string 0)))
  4336. (setq found
  4337. (cond
  4338. ((string-prefix-p "call_" result t)
  4339. (and (memq 'inline-babel-call restriction)
  4340. (org-element-inline-babel-call-parser)))
  4341. ((string-prefix-p "src_" result t)
  4342. (and (memq 'inline-src-block restriction)
  4343. (org-element-inline-src-block-parser)))
  4344. (t
  4345. (pcase (char-after)
  4346. (?^ (and (memq 'superscript restriction)
  4347. (org-element-superscript-parser)))
  4348. (?_ (or (and (memq 'subscript restriction)
  4349. (org-element-subscript-parser))
  4350. (and (memq 'underline restriction)
  4351. (org-element-underline-parser))))
  4352. (?* (and (memq 'bold restriction)
  4353. (org-element-bold-parser)))
  4354. (?/ (and (memq 'italic restriction)
  4355. (org-element-italic-parser)))
  4356. (?~ (and (memq 'code restriction)
  4357. (org-element-code-parser)))
  4358. (?= (and (memq 'verbatim restriction)
  4359. (org-element-verbatim-parser)))
  4360. (?+ (and (memq 'strike-through restriction)
  4361. (org-element-strike-through-parser)))
  4362. (?@ (and (memq 'export-snippet restriction)
  4363. (org-element-export-snippet-parser)))
  4364. (?{ (and (memq 'macro restriction)
  4365. (org-element-macro-parser)))
  4366. (?$ (and (memq 'latex-fragment restriction)
  4367. (org-element-latex-fragment-parser)))
  4368. (?<
  4369. (if (eq (aref result 1) ?<)
  4370. (or (and (memq 'radio-target restriction)
  4371. (org-element-radio-target-parser))
  4372. (and (memq 'target restriction)
  4373. (org-element-target-parser)))
  4374. (or (and (memq 'timestamp restriction)
  4375. (org-element-timestamp-parser))
  4376. (and (memq 'link restriction)
  4377. (org-element-link-parser)))))
  4378. (?\\
  4379. (if (eq (aref result 1) ?\\)
  4380. (and (memq 'line-break restriction)
  4381. (org-element-line-break-parser))
  4382. (or (and (memq 'entity restriction)
  4383. (org-element-entity-parser))
  4384. (and (memq 'latex-fragment restriction)
  4385. (org-element-latex-fragment-parser)))))
  4386. (?\[
  4387. (pcase (aref result 1)
  4388. ((and ?\[
  4389. (guard (memq 'link restriction)))
  4390. (org-element-link-parser))
  4391. ((and ?f
  4392. (guard (memq 'footnote-reference restriction)))
  4393. (org-element-footnote-reference-parser))
  4394. ((and ?c
  4395. (guard (memq 'citation restriction)))
  4396. (org-element-citation-parser))
  4397. ((and (or ?% ?/)
  4398. (guard (memq 'statistics-cookie restriction)))
  4399. (org-element-statistics-cookie-parser))
  4400. (_
  4401. (or (and (memq 'timestamp restriction)
  4402. (org-element-timestamp-parser))
  4403. (and (memq 'statistics-cookie restriction)
  4404. (org-element-statistics-cookie-parser))))))
  4405. ;; This is probably a plain link.
  4406. (_ (and (memq 'link restriction)
  4407. (org-element-link-parser)))))))
  4408. (or (eobp) (forward-char))))
  4409. (cond (found)
  4410. (limit (forward-char -1)
  4411. (org-element-link-parser)) ;radio link
  4412. (t nil)))))))
  4413. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4414. "Parse objects between BEG and END and return recursive structure.
  4415. Objects are accumulated in ACC. RESTRICTION is a list of object
  4416. successors which are allowed in the current object.
  4417. ACC becomes the parent for all parsed objects. However, if ACC
  4418. is nil (i.e., a secondary string is being parsed) and optional
  4419. argument PARENT is non-nil, use it as the parent for all objects.
  4420. Eventually, if both ACC and PARENT are nil, the common parent is
  4421. the list of objects itself."
  4422. (save-excursion
  4423. (save-restriction
  4424. (narrow-to-region beg end)
  4425. (goto-char (point-min))
  4426. (let (next-object contents)
  4427. (while (and (not (eobp))
  4428. (setq next-object (org-element--object-lex restriction)))
  4429. ;; Text before any object.
  4430. (let ((obj-beg (org-element-property :begin next-object)))
  4431. (unless (= (point) obj-beg)
  4432. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4433. (push (if acc (org-element-put-property text :parent acc) text)
  4434. contents))))
  4435. ;; Object...
  4436. (let ((obj-end (org-element-property :end next-object))
  4437. (cont-beg (org-element-property :contents-begin next-object)))
  4438. (when acc (org-element-put-property next-object :parent acc))
  4439. (push (if cont-beg
  4440. ;; Fill contents of NEXT-OBJECT if possible.
  4441. (org-element--parse-objects
  4442. cont-beg
  4443. (org-element-property :contents-end next-object)
  4444. next-object
  4445. (org-element-restriction next-object))
  4446. next-object)
  4447. contents)
  4448. (goto-char obj-end)))
  4449. ;; Text after last object.
  4450. (unless (eobp)
  4451. (let ((text (buffer-substring-no-properties (point) end)))
  4452. (push (if acc (org-element-put-property text :parent acc) text)
  4453. contents)))
  4454. ;; Result. Set appropriate parent.
  4455. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4456. (let* ((contents (nreverse contents))
  4457. (parent (or parent contents)))
  4458. (dolist (datum contents contents)
  4459. (org-element-put-property datum :parent parent))))))))
  4460. ;;; Towards A Bijective Process
  4461. ;;
  4462. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4463. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4464. ;; interpreted and expanded into a string with canonical Org syntax.
  4465. ;; Hence `org-element-interpret-data'.
  4466. ;;
  4467. ;; The function relies internally on
  4468. ;; `org-element--interpret-affiliated-keywords'.
  4469. ;;;###autoload
  4470. (defun org-element-interpret-data (data)
  4471. "Interpret DATA as Org syntax.
  4472. DATA is a parse tree, an element, an object or a secondary string
  4473. to interpret. Return Org syntax as a string."
  4474. (letrec ((fun
  4475. (lambda (data parent)
  4476. (let* ((type (org-element-type data))
  4477. ;; Find interpreter for current object or
  4478. ;; element. If it doesn't exist (e.g. this is
  4479. ;; a pseudo object or element), return contents,
  4480. ;; if any.
  4481. (interpret
  4482. (let ((fun (intern
  4483. (format "org-element-%s-interpreter" type))))
  4484. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4485. (results
  4486. (cond
  4487. ;; Secondary string.
  4488. ((not type)
  4489. (mapconcat (lambda (obj) (funcall fun obj parent))
  4490. data
  4491. ""))
  4492. ;; Full Org document.
  4493. ((eq type 'org-data)
  4494. (mapconcat (lambda (obj) (funcall fun obj parent))
  4495. (org-element-contents data)
  4496. ""))
  4497. ;; Plain text: return it.
  4498. ((stringp data) data)
  4499. ;; Element or object without contents.
  4500. ((not (org-element-contents data))
  4501. (funcall interpret data nil))
  4502. ;; Element or object with contents.
  4503. (t
  4504. (funcall
  4505. interpret
  4506. data
  4507. ;; Recursively interpret contents.
  4508. (mapconcat
  4509. (lambda (datum) (funcall fun datum data))
  4510. (org-element-contents
  4511. (if (not (memq type '(paragraph verse-block)))
  4512. data
  4513. ;; Fix indentation of elements containing
  4514. ;; objects. We ignore `table-row'
  4515. ;; elements as they are one line long
  4516. ;; anyway.
  4517. (org-element-normalize-contents
  4518. data
  4519. ;; When normalizing first paragraph of
  4520. ;; an item or a footnote-definition,
  4521. ;; ignore first line's indentation.
  4522. (and (eq type 'paragraph)
  4523. (memq (org-element-type parent)
  4524. '(footnote-definition item))
  4525. (eq data (car (org-element-contents parent)))
  4526. (eq (org-element-property :pre-blank parent)
  4527. 0)))))
  4528. ""))))))
  4529. (if (memq type '(org-data nil)) results
  4530. ;; Build white spaces. If no `:post-blank' property
  4531. ;; is specified, assume its value is 0.
  4532. (let ((blank (or (org-element-property :post-blank data) 0)))
  4533. (if (eq (org-element-class data parent) 'object)
  4534. (concat results (make-string blank ?\s))
  4535. (concat (org-element--interpret-affiliated-keywords data)
  4536. (org-element-normalize-string results)
  4537. (make-string blank ?\n)))))))))
  4538. (funcall fun data nil)))
  4539. (defun org-element--interpret-affiliated-keywords (element)
  4540. "Return ELEMENT's affiliated keywords as Org syntax.
  4541. If there is no affiliated keyword, return the empty string."
  4542. (let ((keyword-to-org
  4543. (lambda (key value)
  4544. (let (dual)
  4545. (when (member key org-element-dual-keywords)
  4546. (setq dual (cdr value) value (car value)))
  4547. (concat "#+" (downcase key)
  4548. (and dual
  4549. (format "[%s]" (org-element-interpret-data dual)))
  4550. ": "
  4551. (if (member key org-element-parsed-keywords)
  4552. (org-element-interpret-data value)
  4553. value)
  4554. "\n")))))
  4555. (mapconcat
  4556. (lambda (prop)
  4557. (let ((value (org-element-property prop element))
  4558. (keyword (upcase (substring (symbol-name prop) 1))))
  4559. (when value
  4560. (if (or (member keyword org-element-multiple-keywords)
  4561. ;; All attribute keywords can have multiple lines.
  4562. (string-match "^ATTR_" keyword))
  4563. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4564. (reverse value)
  4565. "")
  4566. (funcall keyword-to-org keyword value)))))
  4567. ;; List all ELEMENT's properties matching an attribute line or an
  4568. ;; affiliated keyword, but ignore translated keywords since they
  4569. ;; cannot belong to the property list.
  4570. (cl-loop for prop in (nth 1 element) by 'cddr
  4571. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4572. (or (string-match "^ATTR_" keyword)
  4573. (and
  4574. (member keyword org-element-affiliated-keywords)
  4575. (not (assoc keyword
  4576. org-element-keyword-translation-alist)))))
  4577. collect prop)
  4578. "")))
  4579. ;; Because interpretation of the parse tree must return the same
  4580. ;; number of blank lines between elements and the same number of white
  4581. ;; space after objects, some special care must be given to white
  4582. ;; spaces.
  4583. ;;
  4584. ;; The first function, `org-element-normalize-string', ensures any
  4585. ;; string different from the empty string will end with a single
  4586. ;; newline character.
  4587. ;;
  4588. ;; The second function, `org-element-normalize-contents', removes
  4589. ;; global indentation from the contents of the current element.
  4590. (defun org-element-normalize-string (s)
  4591. "Ensure string S ends with a single newline character.
  4592. If S isn't a string return it unchanged. If S is the empty
  4593. string, return it. Otherwise, return a new string with a single
  4594. newline character at its end."
  4595. (cond
  4596. ((not (stringp s)) s)
  4597. ((string= "" s) "")
  4598. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4599. (replace-match "\n" nil nil s)))))
  4600. (defun org-element-normalize-contents (element &optional ignore-first)
  4601. "Normalize plain text in ELEMENT's contents.
  4602. ELEMENT must only contain plain text and objects.
  4603. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4604. indentation to compute maximal common indentation.
  4605. Return the normalized element that is element with global
  4606. indentation removed from its contents."
  4607. (letrec ((find-min-ind
  4608. ;; Return minimal common indentation within BLOB. This is
  4609. ;; done by walking recursively BLOB and updating MIN-IND
  4610. ;; along the way. FIRST-FLAG is non-nil when the next
  4611. ;; object is expected to be a string that doesn't start
  4612. ;; with a newline character. It happens for strings at
  4613. ;; the beginnings of the contents or right after a line
  4614. ;; break.
  4615. (lambda (blob first-flag min-ind)
  4616. (dolist (datum (org-element-contents blob) min-ind)
  4617. (when first-flag
  4618. (setq first-flag nil)
  4619. (cond
  4620. ;; Objects cannot start with spaces: in this
  4621. ;; case, indentation is 0.
  4622. ((not (stringp datum)) (throw :zero 0))
  4623. ((not (string-match
  4624. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4625. (throw :zero 0))
  4626. ((equal (match-string 2 datum) "\n")
  4627. (put-text-property
  4628. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4629. (t
  4630. (let ((i (string-width (match-string 1 datum))))
  4631. (put-text-property
  4632. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4633. (setq min-ind (min i min-ind))))))
  4634. (cond
  4635. ((stringp datum)
  4636. (let ((s 0))
  4637. (while (string-match
  4638. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4639. (setq s (match-end 1))
  4640. (cond
  4641. ((equal (match-string 1 datum) "")
  4642. (unless (member (match-string 2 datum) '("" "\n"))
  4643. (throw :zero 0)))
  4644. ((equal (match-string 2 datum) "\n")
  4645. (put-text-property (match-beginning 1) (match-end 1)
  4646. 'org-ind 'empty datum))
  4647. (t
  4648. (let ((i (string-width (match-string 1 datum))))
  4649. (put-text-property (match-beginning 1) (match-end 1)
  4650. 'org-ind i datum)
  4651. (setq min-ind (min i min-ind))))))))
  4652. ((eq (org-element-type datum) 'line-break)
  4653. (setq first-flag t))
  4654. ((memq (org-element-type datum) org-element-recursive-objects)
  4655. (setq min-ind
  4656. (funcall find-min-ind datum first-flag min-ind)))))))
  4657. (min-ind
  4658. (catch :zero
  4659. (funcall find-min-ind
  4660. element (not ignore-first) most-positive-fixnum))))
  4661. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4662. ;; Build ELEMENT back, replacing each string with the same
  4663. ;; string minus common indentation.
  4664. (letrec ((build
  4665. (lambda (datum)
  4666. ;; Return DATUM with all its strings indentation
  4667. ;; shortened from MIN-IND white spaces.
  4668. (setcdr
  4669. (cdr datum)
  4670. (mapcar
  4671. (lambda (object)
  4672. (cond
  4673. ((stringp object)
  4674. (with-temp-buffer
  4675. (insert object)
  4676. (let ((s (point-min)))
  4677. (while (setq s (text-property-not-all
  4678. s (point-max) 'org-ind nil))
  4679. (goto-char s)
  4680. (let ((i (get-text-property s 'org-ind)))
  4681. (delete-region s (progn
  4682. (skip-chars-forward " \t")
  4683. (point)))
  4684. (when (integerp i) (indent-to (- i min-ind))))))
  4685. (buffer-string)))
  4686. ((memq (org-element-type object)
  4687. org-element-recursive-objects)
  4688. (funcall build object))
  4689. (t object)))
  4690. (org-element-contents datum)))
  4691. datum)))
  4692. (funcall build element)))))
  4693. ;;; Cache
  4694. ;;
  4695. ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
  4696. ;; fast mapping across Org elements in `org-element-cache-map', which see.
  4697. ;;
  4698. ;; When cache is enabled, the elements returned by `org-element-at-point' and
  4699. ;; `org-element-context' are returned by reference. Altering these elements will
  4700. ;; also alter their cache representation. The same is true for
  4701. ;; elements passed to mapping function in `org-element-cache-map'.
  4702. ;;
  4703. ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
  4704. ;; `org-element-cache-map'.
  4705. ;;
  4706. ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
  4707. ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
  4708. ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
  4709. ;;
  4710. ;; Internally, parsed elements are stored in an AVL tree,
  4711. ;; `org-element--cache'. This tree is updated lazily: whenever
  4712. ;; a change happens to the buffer, a synchronization request is
  4713. ;; registered in `org-element--cache-sync-requests' (see
  4714. ;; `org-element--cache-submit-request'). During idle time, requests
  4715. ;; are processed by `org-element--cache-sync'. Synchronization also
  4716. ;; happens when an element is required from the cache. In this case,
  4717. ;; the process stops as soon as the needed element is up-to-date.
  4718. ;;
  4719. ;; A synchronization request can only apply on a synchronized part of
  4720. ;; the cache. Therefore, the cache is updated at least to the
  4721. ;; location where the new request applies. Thus, requests are ordered
  4722. ;; from left to right and all elements starting before the first
  4723. ;; request are correct. This property is used by functions like
  4724. ;; `org-element--cache-find' to retrieve elements in the part of the
  4725. ;; cache that can be trusted.
  4726. ;;
  4727. ;; A request applies to every element, starting from its original
  4728. ;; location (or key, see below). When a request is processed, it
  4729. ;; moves forward and may collide the next one. In this case, both
  4730. ;; requests are merged into a new one that starts from that element.
  4731. ;; As a consequence, the whole synchronization complexity does not
  4732. ;; depend on the number of pending requests, but on the number of
  4733. ;; elements the very first request will be applied on.
  4734. ;;
  4735. ;; Elements cannot be accessed through their beginning position, which
  4736. ;; may or may not be up-to-date. Instead, each element in the tree is
  4737. ;; associated to a key, obtained with `org-element--cache-key'. This
  4738. ;; mechanism is robust enough to preserve total order among elements
  4739. ;; even when the tree is only partially synchronized.
  4740. ;;
  4741. ;; The cache code debuggin is fairly complex because cache request
  4742. ;; state is often hard to reproduce. An extensive diagnostics
  4743. ;; functionality is built into the cache code to assist hunting bugs.
  4744. ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
  4745. ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
  4746. ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
  4747. ;; `org-element--cache-map-statistics-threshold'.
  4748. (defvar org-element-use-cache t
  4749. "Non-nil when Org parser should cache its results.")
  4750. (defvar org-element-cache-persistent t
  4751. "Non-nil when cache should persist between Emacs sessions.")
  4752. (defvar org-element-cache-sync-idle-time 0.6
  4753. "Length, in seconds, of idle time before syncing cache.")
  4754. (defvar org-element-cache-sync-duration 0.04
  4755. "Maximum duration, as a time value, for a cache synchronization.
  4756. If the synchronization is not over after this delay, the process
  4757. pauses and resumes after `org-element-cache-sync-break'
  4758. seconds.")
  4759. (defvar org-element-cache-sync-break 0.3
  4760. "Duration, as a time value, of the pause between synchronizations.
  4761. See `org-element-cache-sync-duration' for more information.")
  4762. (defvar org-element--cache-self-verify t
  4763. "Activate extra consistency checks for the cache.
  4764. This may cause serious performance degradation depending on the value
  4765. of `org-element--cache-self-verify-frequency'.
  4766. When set to symbol `backtrace', record and display backtrace log if
  4767. any inconsistency is detected.")
  4768. (defvar org-element--cache-self-verify-frequency 0.03
  4769. "Frequency of cache element verification.
  4770. This number is a probability to check an element requested from cache
  4771. to be correct. Setting this to a value less than 0.0001 is useless.")
  4772. (defvar org-element--cache-diagnostics nil
  4773. "Print detailed diagnostics of cache processing.")
  4774. (defvar org-element--cache-map-statistics nil
  4775. "Print statistics for `org-element-cache-map'.")
  4776. (defvar org-element--cache-map-statistics-threshold 0.1
  4777. "Time threshold in seconds to log statistics for `org-element-cache-map'.")
  4778. (defvar org-element--cache-diagnostics-modifications t
  4779. "Non-nil enables cache warnings when for silent modifications.
  4780. Silent modifications are the modifications in Org buffers that are not
  4781. registered by `org-element--cache-before-change' and
  4782. `org-element--cache-after-change'.
  4783. This variable may cause false-positives because some Emacs versions
  4784. can change `buffer-chars-modified-tick' internally even though no
  4785. visible changes in buffer are being made. Some of such expected cases
  4786. are covered by heuristics, but not all.")
  4787. (defvar org-element--cache-silent-modification-check t
  4788. "Detect changes in buffer made inside `with-silent-modifications'.
  4789. Note that some internal Emacs functions may also trigger a warning and
  4790. cache reset. The warning can be suppressed by setting
  4791. `org-element--cache-diagnostics-modifications' to nil, but the cache
  4792. will still be refreshed to be safe.
  4793. WARNING: Setting this variable to nil may cause cache corruption is some
  4794. third-party packages make undetected changes in buffers.")
  4795. (defvar org-element--cache-diagnostics-level 2
  4796. "Detail level of the diagnostics.")
  4797. (defvar-local org-element--cache-diagnostics-ring nil
  4798. "Ring containing last `org-element--cache-diagnostics-ring-size'
  4799. cache process log entries.")
  4800. (defvar org-element--cache-diagnostics-ring-size 5000
  4801. "Size of `org-element--cache-diagnostics-ring'.")
  4802. ;;;; Data Structure
  4803. (defvar-local org-element--cache nil
  4804. "AVL tree used to cache elements.
  4805. Each node of the tree contains an element. Comparison is done
  4806. with `org-element--cache-compare'. This cache is used in
  4807. `org-element-at-point'.")
  4808. (defvar-local org-element--headline-cache nil
  4809. "AVL tree used to cache headline and inlinetask elements.
  4810. Each node of the tree contains an element. Comparison is done
  4811. with `org-element--cache-compare'. This cache is used in
  4812. `org-element-cache-map'.")
  4813. (defvar-local org-element--cache-size 0
  4814. "Size of the `org-element--cache'.
  4815. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4816. (defvar-local org-element--headline-cache-size 0
  4817. "Size of the `org-element--headline-cache'.
  4818. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4819. (defvar-local org-element--cache-sync-requests nil
  4820. "List of pending synchronization requests.
  4821. A request is a vector with the following pattern:
  4822. [NEXT BEG END OFFSET PARENT PHASE]
  4823. Processing a synchronization request consists of three phases:
  4824. 0. Delete modified elements,
  4825. 1. Fill missing area in cache,
  4826. 2. Shift positions and re-parent elements after the changes.
  4827. During phase 0, NEXT is the key of the first element to be
  4828. removed, BEG and END is buffer position delimiting the
  4829. modifications. Elements starting between them (inclusive) are
  4830. removed. So are elements whose parent is removed. PARENT, when
  4831. non-nil, is the common parent of all the elements between BEG and END.
  4832. It is guaranteed that only a single phase 0 request exists at any
  4833. moment of time. If it does, it must be the first request in the list.
  4834. During phase 1, NEXT is the key of the next known element in
  4835. cache and BEG its beginning position. Parse buffer between that
  4836. element and the one before it in order to determine the parent of
  4837. the next element. Set PARENT to the element containing NEXT.
  4838. During phase 2, NEXT is the key of the next element to shift in
  4839. the parse tree. All elements starting from this one have their
  4840. properties relative to buffer positions shifted by integer
  4841. OFFSET and, if they belong to element PARENT, are adopted by it.
  4842. PHASE specifies the phase number, as an integer.
  4843. For any synchronisation request, all the later requests in the cache
  4844. must not start at or before END. See `org-element--cache-submit-request'.")
  4845. (defvar-local org-element--cache-sync-timer nil
  4846. "Timer used for cache synchronization.")
  4847. (defvar-local org-element--cache-sync-keys-value nil
  4848. "Id value used to identify keys during synchronisation.
  4849. See `org-element--cache-key' for more information.")
  4850. (defvar-local org-element--cache-change-tic nil
  4851. "Last `buffer-chars-modified-tick' for registered changes.")
  4852. (defvar org-element--cache-non-modifying-commands
  4853. '(org-agenda
  4854. org-agenda-redo
  4855. org-sparse-tree
  4856. org-occur
  4857. org-columns
  4858. org-columns-redo
  4859. org-columns-new
  4860. org-columns-delete
  4861. org-columns-compute
  4862. org-columns-insert-dblock
  4863. org-agenda-columns
  4864. org-ctrl-c-ctrl-c)
  4865. "List of commands that are not expected to change the cache state.
  4866. This variable is used to determine when re-parsing buffer is not going
  4867. to slow down the command.
  4868. If the commends end up modifying the cache, the worst case scenario is
  4869. performance drop. So, advicing these commands is safe. Yet, it is
  4870. better to remove the commands adviced in such way from this list.")
  4871. (defmacro org-element--request-key (request)
  4872. "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
  4873. `(aref ,request 0))
  4874. (defmacro org-element--request-beg (request)
  4875. "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
  4876. `(aref ,request 1))
  4877. (defmacro org-element--request-end (request)
  4878. "Get END part of a `org-element--cache-sync-requests' REQUEST."
  4879. `(aref ,request 2))
  4880. (defmacro org-element--request-offset (request)
  4881. "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
  4882. `(aref ,request 3))
  4883. (defmacro org-element--request-parent (request)
  4884. "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
  4885. `(aref ,request 4))
  4886. (defmacro org-element--request-phase (request)
  4887. "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
  4888. `(aref ,request 5))
  4889. (defmacro org-element--format-element (element)
  4890. "Format ELEMENT for printing in diagnostics."
  4891. `(let ((print-length 50)
  4892. (print-level 5))
  4893. (prin1-to-string ,element)))
  4894. (defmacro org-element--cache-log-message (format-string &rest args)
  4895. "Add a new log message for org-element-cache."
  4896. `(when (or org-element--cache-diagnostics
  4897. (eq org-element--cache-self-verify 'backtrace))
  4898. (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
  4899. (buffer-name (current-buffer)))
  4900. ,format-string))
  4901. (format-string (funcall #'format format-string ,@args)))
  4902. (if org-element--cache-diagnostics
  4903. (display-warning 'org-element-cache format-string)
  4904. (unless org-element--cache-diagnostics-ring
  4905. (setq org-element--cache-diagnostics-ring
  4906. (make-ring org-element--cache-diagnostics-ring-size)))
  4907. (ring-insert org-element--cache-diagnostics-ring format-string)))))
  4908. (defmacro org-element--cache-warn (format-string &rest args)
  4909. "Raise warning for org-element-cache."
  4910. `(let* ((format-string (funcall #'format ,format-string ,@args))
  4911. (format-string
  4912. (if (or (not org-element--cache-diagnostics-ring)
  4913. (not (eq 'backtrace org-element--cache-self-verify)))
  4914. format-string
  4915. (prog1
  4916. (concat (format "Warning(%s): "
  4917. (buffer-name (current-buffer)))
  4918. format-string
  4919. "\nBacktrace:\n "
  4920. (mapconcat #'identity
  4921. (ring-elements org-element--cache-diagnostics-ring)
  4922. "\n "))
  4923. (setq org-element--cache-diagnostics-ring nil)))))
  4924. (if (and (boundp 'org-batch-test) org-batch-test)
  4925. (error "%s" (concat "org-element--cache: " format-string))
  4926. (display-warning 'org-element-cache
  4927. (concat "org-element--cache: " format-string)))))
  4928. (defsubst org-element--cache-key (element)
  4929. "Return a unique key for ELEMENT in cache tree.
  4930. Keys are used to keep a total order among elements in the cache.
  4931. Comparison is done with `org-element--cache-key-less-p'.
  4932. When no synchronization is taking place, a key is simply the
  4933. beginning position of the element, or that position plus one in
  4934. the case of an first item (respectively row) in
  4935. a list (respectively a table). They key of a section is its beginning
  4936. position minus one.
  4937. During a synchronization, the key is the one the element had when
  4938. the cache was synchronized for the last time. Elements added to
  4939. cache during the synchronization get a new key generated with
  4940. `org-element--cache-generate-key'.
  4941. Such keys are stored inside the element property
  4942. `:org-element--cache-sync-key'. The property is a cons containing
  4943. current `org-element--cache-sync-keys-value' and the element key."
  4944. (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
  4945. (cdr (org-element-property :org-element--cache-sync-key element)))
  4946. (let* ((begin (org-element-property :begin element))
  4947. ;; Increase beginning position of items (respectively
  4948. ;; table rows) by one, so the first item can get
  4949. ;; a different key from its parent list (respectively
  4950. ;; table).
  4951. (key (if (memq (org-element-type element) '(item table-row))
  4952. (1+ begin)
  4953. ;; Decrease beginning position of sections by one,
  4954. ;; so that the first element of the section get
  4955. ;; different key from the parent section.
  4956. (if (eq (org-element-type element) 'section)
  4957. (1- begin)
  4958. (if (eq (org-element-type element) 'org-data)
  4959. (- begin 2)
  4960. begin)))))
  4961. (when org-element--cache-sync-requests
  4962. (org-element-put-property
  4963. element
  4964. :org-element--cache-sync-key
  4965. (cons org-element--cache-sync-keys-value key)))
  4966. key)))
  4967. (defun org-element--cache-generate-key (lower upper)
  4968. "Generate a key between LOWER and UPPER.
  4969. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4970. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4971. a unique key, as an integer or a list of integers, according to
  4972. the following rules:
  4973. - LOWER and UPPER are compared level-wise until values differ.
  4974. - If, at a given level, LOWER and UPPER differ from more than
  4975. 2, the new key shares all the levels above with LOWER and
  4976. gets a new level. Its value is the mean between LOWER and
  4977. UPPER:
  4978. (1 2) + (1 4) --> (1 3)
  4979. - If LOWER has no value to compare with, it is assumed that its
  4980. value is `most-negative-fixnum'. E.g.,
  4981. (1 1) + (1 1 2)
  4982. is equivalent to
  4983. (1 1 m) + (1 1 2)
  4984. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4985. short of levels, the current value is `most-positive-fixnum'.
  4986. - If they differ from only one, the new key inherits from
  4987. current LOWER level and fork it at the next level. E.g.,
  4988. (2 1) + (3 3)
  4989. is equivalent to
  4990. (2 1) + (2 M)
  4991. where M is `most-positive-fixnum'.
  4992. - If the key is only one level long, it is returned as an
  4993. integer:
  4994. (1 2) + (3 2) --> 2
  4995. When they are not equals, the function assumes that LOWER is
  4996. lesser than UPPER, per `org-element--cache-key-less-p'."
  4997. (if (equal lower upper) lower
  4998. (let ((lower (if (integerp lower) (list lower) lower))
  4999. (upper (if (integerp upper) (list upper) upper))
  5000. skip-upper key)
  5001. (catch 'exit
  5002. (while t
  5003. (let ((min (or (car lower) most-negative-fixnum))
  5004. (max (cond (skip-upper most-positive-fixnum)
  5005. ((car upper))
  5006. (t most-positive-fixnum))))
  5007. (if (< (1+ min) max)
  5008. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  5009. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  5010. (when (and (< min max) (not skip-upper))
  5011. ;; When at a given level, LOWER and UPPER differ from
  5012. ;; 1, ignore UPPER altogether. Instead create a key
  5013. ;; between LOWER and the greatest key with the same
  5014. ;; prefix as LOWER so far.
  5015. (setq skip-upper t))
  5016. (push min key)
  5017. (setq lower (cdr lower) upper (cdr upper)))))))))
  5018. (defsubst org-element--cache-key-less-p (a b)
  5019. "Non-nil if key A is less than key B.
  5020. A and B are either integers or lists of integers, as returned by
  5021. `org-element--cache-key'."
  5022. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  5023. (if (integerp b) (< (car a) b)
  5024. (catch 'exit
  5025. (while (and a b)
  5026. (cond ((car-less-than-car a b) (throw 'exit t))
  5027. ((car-less-than-car b a) (throw 'exit nil))
  5028. (t (setq a (cdr a) b (cdr b)))))
  5029. ;; If A is empty, either keys are equal (B is also empty) and
  5030. ;; we return nil, or A is lesser than B (B is longer) and we
  5031. ;; return a non-nil value.
  5032. ;;
  5033. ;; If A is not empty, B is necessarily empty and A is greater
  5034. ;; than B (A is longer). Therefore, return nil.
  5035. (and (null a) b)))))
  5036. (defun org-element--cache-compare (a b)
  5037. "Non-nil when element A is located before element B."
  5038. (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
  5039. (defsubst org-element--cache-root ()
  5040. "Return root value in `org-element--cache' .
  5041. This function assumes `org-element--cache' is a valid AVL tree."
  5042. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  5043. (defsubst org-element--headline-cache-root ()
  5044. "Return root value in `org-element--headline-cache' .
  5045. This function assumes `org-element--headline-cache' is a valid AVL tree."
  5046. (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
  5047. ;;;; Tools
  5048. (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
  5049. "Non-nil when cache is active in current buffer."
  5050. (and org-element-use-cache
  5051. org-element--cache
  5052. (derived-mode-p 'org-mode)
  5053. (or called-from-cache-change-func-p
  5054. (and
  5055. ;; org-num-mode calls some Org structure analysis functions
  5056. ;; that can trigger cache update in the middle of changes. See
  5057. ;; `org-num--verify' calling `org-num--skip-value' calling
  5058. ;; `org-entry-get' that uses cache.
  5059. ;; Forcefully disable cache when called from inside a
  5060. ;; modification hook, where `inhibit-modification-hooks' is set
  5061. ;; to t.
  5062. (not inhibit-modification-hooks)
  5063. ;; `combine-change-calls' sets `after-change-functions' to
  5064. ;; nil. We need not to use cache inside
  5065. ;; `combine-change-calls' because the buffer is potentially
  5066. ;; changed without notice (the change will be registered
  5067. ;; after exiting the `combine-change-calls' body though).
  5068. (memq #'org-element--cache-after-change after-change-functions))
  5069. (eq org-element--cache-change-tic (buffer-chars-modified-tick)))))
  5070. (defun org-element--cache-find (pos &optional side)
  5071. "Find element in cache starting at POS or before.
  5072. POS refers to a buffer position.
  5073. When optional argument SIDE is non-nil, the function checks for
  5074. elements starting at or past POS instead. If SIDE is `both', the
  5075. function returns a cons cell where car is the first element
  5076. starting at or before POS and cdr the first element starting
  5077. after POS.
  5078. The function can only find elements in the synchronized part of
  5079. the cache."
  5080. (with-current-buffer (or (buffer-base-buffer) (current-buffer))
  5081. (let ((limit (and org-element--cache-sync-requests
  5082. (org-element--request-key (car org-element--cache-sync-requests))))
  5083. (node (org-element--cache-root))
  5084. lower upper)
  5085. (while node
  5086. (let* ((element (avl-tree--node-data node))
  5087. (begin (org-element-property :begin element)))
  5088. (cond
  5089. ((and limit
  5090. (not (org-element--cache-key-less-p
  5091. (org-element--cache-key element) limit)))
  5092. (setq node (avl-tree--node-left node)))
  5093. ((> begin pos)
  5094. (setq upper element
  5095. node (avl-tree--node-left node)))
  5096. ((or (< begin pos)
  5097. ;; If the element is section or org-data, we also need
  5098. ;; to check the following element.
  5099. (memq (org-element-type element) '(section org-data)))
  5100. (setq lower element
  5101. node (avl-tree--node-right node)))
  5102. ;; We found an element in cache starting at POS. If `side'
  5103. ;; is `both' we also want the next one in order to generate
  5104. ;; a key in-between.
  5105. ;;
  5106. ;; If the element is the first row or item in a table or
  5107. ;; a plain list, we always return the table or the plain
  5108. ;; list.
  5109. ;;
  5110. ;; In any other case, we return the element found.
  5111. ((eq side 'both)
  5112. (setq lower element)
  5113. (setq node (avl-tree--node-right node)))
  5114. ((and (memq (org-element-type element) '(item table-row))
  5115. (let ((parent (org-element-property :parent element)))
  5116. (and (= (org-element-property :begin element)
  5117. (org-element-property :contents-begin parent))
  5118. (setq node nil
  5119. lower parent
  5120. upper parent)))))
  5121. (t
  5122. (setq node nil
  5123. lower element
  5124. upper element)))))
  5125. (pcase side
  5126. (`both (cons lower upper))
  5127. (`nil lower)
  5128. (_ upper)))))
  5129. (defun org-element--cache-put (element)
  5130. "Store ELEMENT in current buffer's cache, if allowed."
  5131. (when (org-element--cache-active-p)
  5132. (when org-element--cache-sync-requests
  5133. ;; During synchronization, first build an appropriate key for
  5134. ;; the new element so `avl-tree-enter' can insert it at the
  5135. ;; right spot in the cache.
  5136. (let* ((keys (org-element--cache-find
  5137. (org-element-property :begin element) 'both))
  5138. (new-key (org-element--cache-generate-key
  5139. (and (car keys) (org-element--cache-key (car keys)))
  5140. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  5141. (org-element--cache-sync-requests
  5142. (org-element--request-key (car org-element--cache-sync-requests)))))))
  5143. (org-element-put-property
  5144. element
  5145. :org-element--cache-sync-key
  5146. (cons org-element--cache-sync-keys-value new-key))))
  5147. (when (>= org-element--cache-diagnostics-level 2)
  5148. (org-element--cache-log-message
  5149. "Added new element with %S key: %S"
  5150. (org-element-property :org-element--cache-sync-key element)
  5151. (org-element--format-element element)))
  5152. (org-element-put-property element :cached t)
  5153. (when (memq (org-element-type element) '(headline inlinetask))
  5154. (cl-incf org-element--headline-cache-size)
  5155. (avl-tree-enter org-element--headline-cache element))
  5156. (cl-incf org-element--cache-size)
  5157. (avl-tree-enter org-element--cache element)))
  5158. (defsubst org-element--cache-remove (element)
  5159. "Remove ELEMENT from cache.
  5160. Assume ELEMENT belongs to cache and that a cache is active."
  5161. (org-element-put-property element :cached nil)
  5162. (cl-decf org-element--cache-size)
  5163. ;; Invalidate contents of parent.
  5164. (when (and (org-element-property :parent element)
  5165. (org-element-contents (org-element-property :parent element)))
  5166. (org-element-set-contents (org-element-property :parent element) nil))
  5167. (when (memq (org-element-type element) '(headline inlinetask))
  5168. (cl-decf org-element--headline-cache-size)
  5169. (avl-tree-delete org-element--headline-cache element))
  5170. (or (avl-tree-delete org-element--cache element)
  5171. (progn
  5172. ;; This should not happen, but if it is, would be better to know
  5173. ;; where it happens.
  5174. (org-element--cache-warn
  5175. "Failed to delete %S element in %S at %S. The element cache key was %S.
  5176. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5177. (org-element-type element)
  5178. (current-buffer)
  5179. (org-element-property :begin element)
  5180. (org-element-property :org-element--cache-sync-key element))
  5181. (org-element-cache-reset)
  5182. (throw 'quit nil))))
  5183. ;;;; Synchronization
  5184. (defsubst org-element--cache-set-timer (buffer)
  5185. "Set idle timer for cache synchronization in BUFFER."
  5186. (when org-element--cache-sync-timer
  5187. (cancel-timer org-element--cache-sync-timer))
  5188. (setq org-element--cache-sync-timer
  5189. (run-with-idle-timer
  5190. (let ((idle (current-idle-time)))
  5191. (if idle (time-add idle org-element-cache-sync-break)
  5192. org-element-cache-sync-idle-time))
  5193. nil
  5194. #'org-element--cache-sync
  5195. buffer)))
  5196. (defsubst org-element--cache-interrupt-p (time-limit)
  5197. "Non-nil when synchronization process should be interrupted.
  5198. TIME-LIMIT is a time value or nil."
  5199. (and time-limit
  5200. (or (input-pending-p)
  5201. (time-less-p time-limit nil))))
  5202. (defsubst org-element--cache-shift-positions (element offset &optional props)
  5203. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  5204. Properties containing buffer positions are `:begin', `:end',
  5205. `:contents-begin', `:contents-end' and `:structure'. When
  5206. optional argument PROPS is a list of keywords, only shift
  5207. properties provided in that list.
  5208. Properties are modified by side-effect."
  5209. (let ((properties (nth 1 element)))
  5210. ;; Shift `:structure' property for the first plain list only: it
  5211. ;; is the only one that really matters and it prevents from
  5212. ;; shifting it more than once.
  5213. (when (and (or (not props) (memq :structure props))
  5214. (eq (org-element-type element) 'plain-list)
  5215. (not (eq (org-element-type (plist-get properties :parent)) 'item)))
  5216. (dolist (item (plist-get properties :structure))
  5217. (cl-incf (car item) offset)
  5218. (cl-incf (nth 6 item) offset)))
  5219. (dolist (key '( :begin :contents-begin :contents-end :end
  5220. :post-affiliated :robust-begin :robust-end))
  5221. (let ((value (and (or (not props) (memq key props))
  5222. (plist-get properties key))))
  5223. (and value (plist-put properties key (+ offset value)))))))
  5224. (defvar org-element--cache-interrupt-C-g t
  5225. "When non-nil, allow the user to abort `org-element--cache-sync'.
  5226. The execution is aborted upon pressing `\\[keyboard-quit]'
  5227. `org-element--cache-interrupt-C-g-max-count' times.")
  5228. (defvar org-element--cache-interrupt-C-g-max-count 5
  5229. "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
  5230. See `org-element--cache-interrupt-C-g'.")
  5231. (defvar org-element--cache-interrupt-C-g-count 0
  5232. "Current number of `org-element--cache-sync' calls.
  5233. See `org-element--cache-interrupt-C-g'.")
  5234. (defvar org-element--cache-change-warning nil
  5235. "Non-nil when a sensitive line is about to be changed.
  5236. It is a symbol among nil, t, or a number representing smallest level of
  5237. modified headline. The level considers headline levels both before
  5238. and after the modification.")
  5239. (defun org-element--cache-sync (buffer &optional threshold future-change offset)
  5240. "Synchronize cache with recent modification in BUFFER.
  5241. When optional argument THRESHOLD is non-nil, do the
  5242. synchronization for all elements starting before or at threshold,
  5243. then exit. Otherwise, synchronize cache for as long as
  5244. `org-element-cache-sync-duration' or until Emacs leaves idle
  5245. state.
  5246. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  5247. not registered yet in the cache are going to happen. OFFSET is the
  5248. change offset. It is used in `org-element--cache-submit-request',
  5249. where cache is partially updated before current modification are
  5250. actually submitted."
  5251. (when (buffer-live-p buffer)
  5252. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  5253. ;; Check if the buffer have been changed outside visibility of
  5254. ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
  5255. (if (and (/= org-element--cache-change-tic
  5256. (buffer-chars-modified-tick))
  5257. org-element--cache-silent-modification-check
  5258. ;; FIXME: Below is a heuristics noticed by observation.
  5259. ;; quail.el with non-latin input does silent
  5260. ;; modifications in buffer increasing the tick counter
  5261. ;; but not actually changing the buffer text:
  5262. ;; https://list.orgmode.org/87sfw2luhj.fsf@localhost/T/#you
  5263. ;; https://lists.gnu.org/archive/html/bug-gnu-emacs/2021-11/msg00894.html
  5264. ;; However, the values of `buffer-chars-modified-tick'
  5265. ;; and `buffer-modified-tick' appear to be same after
  5266. ;; the quail.el's changes in buffer. We do not
  5267. ;; consider these exact changes as a dangerous silent
  5268. ;; edit.
  5269. (/= (buffer-chars-modified-tick)
  5270. (buffer-modified-tick)))
  5271. (progn
  5272. (when (or (and org-element--cache-diagnostics-modifications
  5273. ;; A number of Emacs internal operations in
  5274. ;; Emacs 26 and 27 alter
  5275. ;; `buffer-chars-modified-tick' (see
  5276. ;; https://list.orgmode.org/87ee7jdv70.fsf@localhost/T/#t
  5277. ;; https://list.orgmode.org/2022-01-06T12-13-17@devnull.Karl-Voit.at/T/#mb3771758f81b31721ba2f420878a4d16081dc483).
  5278. ;; We have no way to distinguish them from
  5279. ;; dangerious silent edits. So, we can
  5280. ;; only reset the cache, but do not show
  5281. ;; warning to not irritate the users.)
  5282. (not (version< emacs-version "28")))
  5283. (and (boundp 'org-batch-test) org-batch-test))
  5284. (org-element--cache-warn
  5285. "Unregistered buffer modifications detected. Resetting.
  5286. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  5287. The buffer is: %s\n Current command: %S\n Chars modified: %S\n Buffer modified: %S\n Backtrace:\n%S"
  5288. (buffer-name (current-buffer))
  5289. (list this-command (buffer-chars-modified-tick) (buffer-modified-tick))
  5290. (buffer-chars-modified-tick)
  5291. (buffer-modified-tick)
  5292. (when (and (fboundp 'backtrace-get-frames)
  5293. (fboundp 'backtrace-to-string))
  5294. (backtrace-to-string (backtrace-get-frames 'backtrace)))))
  5295. (org-element-cache-reset))
  5296. (let ((inhibit-quit t) request next)
  5297. (setq org-element--cache-interrupt-C-g-count 0)
  5298. (when org-element--cache-sync-timer
  5299. (cancel-timer org-element--cache-sync-timer))
  5300. (let ((time-limit (time-add nil org-element-cache-sync-duration)))
  5301. (catch 'org-element--cache-interrupt
  5302. (when org-element--cache-sync-requests
  5303. (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
  5304. (while org-element--cache-sync-requests
  5305. (setq request (car org-element--cache-sync-requests)
  5306. next (nth 1 org-element--cache-sync-requests))
  5307. (org-element--cache-process-request
  5308. request
  5309. (when next (org-element--request-key next))
  5310. threshold
  5311. (unless threshold time-limit)
  5312. future-change
  5313. offset)
  5314. ;; Re-assign current and next requests. It could have
  5315. ;; been altered during phase 1.
  5316. (setq request (car org-element--cache-sync-requests)
  5317. next (nth 1 org-element--cache-sync-requests))
  5318. ;; Request processed. Merge current and next offsets and
  5319. ;; transfer ending position.
  5320. (when next
  5321. ;; The following requests can only be either phase 1
  5322. ;; or phase 2 requests. We need to let them know
  5323. ;; that additional shifting happened ahead of them.
  5324. (cl-incf (org-element--request-offset next) (org-element--request-offset request))
  5325. (org-element--cache-log-message
  5326. "Updating next request offset to %S: %s"
  5327. (org-element--request-offset next)
  5328. (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
  5329. ;; FIXME: END part of the request only matters for
  5330. ;; phase 0 requests. However, the only possible
  5331. ;; phase 0 request must be the first request in the
  5332. ;; list all the time. END position should be
  5333. ;; unused.
  5334. (setf (org-element--request-end next) (org-element--request-end request)))
  5335. (setq org-element--cache-sync-requests
  5336. (cdr org-element--cache-sync-requests)))))
  5337. ;; If more requests are awaiting, set idle timer accordingly.
  5338. ;; Otherwise, reset keys.
  5339. (if org-element--cache-sync-requests
  5340. (org-element--cache-set-timer buffer)
  5341. (setq org-element--cache-change-warning nil)
  5342. (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value))))))))
  5343. (defun org-element--cache-process-request
  5344. (request next-request-key threshold time-limit future-change offset)
  5345. "Process synchronization REQUEST for all entries before NEXT.
  5346. REQUEST is a vector, built by `org-element--cache-submit-request'.
  5347. NEXT-REQUEST-KEY is a cache key of the next request, as returned by
  5348. `org-element--cache-key'.
  5349. When non-nil, THRESHOLD is a buffer position. Synchronization
  5350. stops as soon as a shifted element begins after it.
  5351. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  5352. after this time or when Emacs exits idle state.
  5353. When non-nil, FUTURE-CHANGE is a buffer position where changes not
  5354. registered yet in the cache are going to happen. OFFSET is the
  5355. changed text length. See `org-element--cache-submit-request' for more
  5356. information.
  5357. Throw `org-element--cache-interrupt' if the process stops before
  5358. completing the request."
  5359. (org-element--cache-log-message
  5360. "org-element-cache: Processing request %s up to %S-%S, next: %S"
  5361. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5362. future-change
  5363. threshold
  5364. next-request-key)
  5365. (catch 'org-element--cache-quit
  5366. (when (= (org-element--request-phase request) 0)
  5367. ;; Phase 0.
  5368. ;;
  5369. ;; Delete all elements starting after beginning of the element
  5370. ;; with request key NEXT, but not after buffer position END.
  5371. ;;
  5372. ;; At each iteration, we start again at tree root since
  5373. ;; a deletion modifies structure of the balanced tree.
  5374. (org-element--cache-log-message "Phase 0")
  5375. (catch 'org-element--cache-end-phase
  5376. (let ((deletion-count 0))
  5377. (while t
  5378. (when (org-element--cache-interrupt-p time-limit)
  5379. (org-element--cache-log-message "Interrupt: time limit")
  5380. (throw 'org-element--cache-interrupt nil))
  5381. (let ((request-key (org-element--request-key request))
  5382. (end (org-element--request-end request))
  5383. (node (org-element--cache-root))
  5384. data data-key)
  5385. ;; Find first element in cache with key REQUEST-KEY or
  5386. ;; after it.
  5387. (while node
  5388. (let* ((element (avl-tree--node-data node))
  5389. (key (org-element--cache-key element)))
  5390. (cond
  5391. ((org-element--cache-key-less-p key request-key)
  5392. (setq node (avl-tree--node-right node)))
  5393. ((org-element--cache-key-less-p request-key key)
  5394. (setq data element
  5395. data-key key
  5396. node (avl-tree--node-left node)))
  5397. (t (setq data element
  5398. data-key key
  5399. node nil)))))
  5400. (if data
  5401. ;; We found first element in cache starting at or
  5402. ;; after REQUEST-KEY.
  5403. (let ((pos (org-element-property :begin data)))
  5404. ;; FIXME: Maybe simply (< pos end)?
  5405. (if (<= pos end)
  5406. (progn
  5407. (org-element--cache-log-message "removing %S::%S"
  5408. (org-element-property :org-element--cache-sync-key data)
  5409. (org-element--format-element data))
  5410. (cl-incf deletion-count)
  5411. (org-element--cache-remove data)
  5412. (when (and (> (log org-element--cache-size 2) 10)
  5413. (> deletion-count
  5414. (/ org-element--cache-size (log org-element--cache-size 2))))
  5415. (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
  5416. deletion-count
  5417. org-element--cache-size
  5418. (log org-element--cache-size 2))
  5419. (org-element-cache-reset)
  5420. (throw 'org-element--cache-quit t)))
  5421. ;; Done deleting everthing starting before END.
  5422. ;; DATA-KEY is the first known element after END.
  5423. ;; Move on to phase 1.
  5424. (org-element--cache-log-message
  5425. "found element after %S: %S::%S"
  5426. end
  5427. (org-element-property :org-element--cache-sync-key data)
  5428. (org-element--format-element data))
  5429. (setf (org-element--request-key request) data-key)
  5430. (setf (org-element--request-beg request) pos)
  5431. (setf (org-element--request-phase request) 1)
  5432. (throw 'org-element--cache-end-phase nil)))
  5433. ;; No element starting after modifications left in
  5434. ;; cache: further processing is futile.
  5435. (org-element--cache-log-message
  5436. "Phase 0 deleted all elements in cache after %S!"
  5437. request-key)
  5438. (throw 'org-element--cache-quit t)))))))
  5439. (when (= (org-element--request-phase request) 1)
  5440. ;; Phase 1.
  5441. ;;
  5442. ;; Phase 0 left a hole in the cache. Some elements after it
  5443. ;; could have parents within. For example, in the following
  5444. ;; buffer:
  5445. ;;
  5446. ;; - item
  5447. ;;
  5448. ;;
  5449. ;; Paragraph1
  5450. ;;
  5451. ;; Paragraph2
  5452. ;;
  5453. ;; if we remove a blank line between "item" and "Paragraph1",
  5454. ;; everything down to "Paragraph2" is removed from cache. But
  5455. ;; the paragraph now belongs to the list, and its `:parent'
  5456. ;; property no longer is accurate.
  5457. ;;
  5458. ;; Therefore we need to parse again elements in the hole, or at
  5459. ;; least in its last section, so that we can re-parent
  5460. ;; subsequent elements, during phase 2.
  5461. ;;
  5462. ;; Note that we only need to get the parent from the first
  5463. ;; element in cache after the hole.
  5464. ;;
  5465. ;; When next key is lesser or equal to the current one, current
  5466. ;; request is inside a to-be-shifted part of the cache. It is
  5467. ;; fine because the order of elements will not be altered by
  5468. ;; shifting. However, we cannot know the real position of the
  5469. ;; unshifted NEXT element in the current request. So, we need
  5470. ;; to sort the request list according to keys and re-start
  5471. ;; processing from the new leftmost request.
  5472. (org-element--cache-log-message "Phase 1")
  5473. (let ((key (org-element--request-key request)))
  5474. (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
  5475. ;; In theory, the only case when requests are not
  5476. ;; ordered is when key of the next request is either the
  5477. ;; same with current key or it is a key for a removed
  5478. ;; element. Either way, we can simply merge the two
  5479. ;; requests.
  5480. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5481. (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
  5482. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5483. (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
  5484. (setf (org-element--request-key next-request) key)
  5485. (setf (org-element--request-beg next-request) (org-element--request-beg request))
  5486. (setf (org-element--request-phase next-request) 1)
  5487. (throw 'org-element--cache-quit t))))
  5488. ;; Next element will start at its beginning position plus
  5489. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  5490. ;; contains the real beginning position of the first element to
  5491. ;; shift and re-parent.
  5492. (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request)))
  5493. cached-before)
  5494. (cond ((and threshold (> limit threshold))
  5495. (org-element--cache-log-message "Interrupt: position %S after threshold %S" limit threshold)
  5496. (throw 'org-element--cache-interrupt nil))
  5497. ((and future-change (>= limit future-change))
  5498. ;; Changes happened around this element and they will
  5499. ;; trigger another phase 1 request. Skip re-parenting
  5500. ;; and simply proceed with shifting (phase 2) to make
  5501. ;; sure that followup phase 0 request for the recent
  5502. ;; changes can operate on the correctly shifted cache.
  5503. (org-element--cache-log-message "position %S after future change %S" limit future-change)
  5504. (setf (org-element--request-parent request) nil)
  5505. (setf (org-element--request-phase request) 2))
  5506. (t
  5507. (when future-change
  5508. ;; Changes happened, but not yet registered after
  5509. ;; this element. However, we a not yet safe to look
  5510. ;; at the buffer and parse elements in the cache gap.
  5511. ;; Some of the parents to be added to cache may end
  5512. ;; after the changes. Parsing this parents will
  5513. ;; assign the :end correct value for cache state
  5514. ;; after future-change. Then, when the future change
  5515. ;; is going to be processed, such parent boundary
  5516. ;; will be altered unnecessarily. To avoid this,
  5517. ;; we alter the new parents by -OFFSET.
  5518. ;; For now, just save last known cached element and
  5519. ;; then check all the parents below.
  5520. (setq cached-before (org-element--cache-find (1- limit) nil)))
  5521. ;; No relevant changes happened after submitting this
  5522. ;; request. We are safe to look at the actual Org
  5523. ;; buffer and calculate the new parent.
  5524. (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
  5525. (when future-change
  5526. ;; Check all the newly added parents to not
  5527. ;; intersect with future change.
  5528. (let ((up parent))
  5529. (while (and up
  5530. (or (not cached-before)
  5531. (> (org-element-property :begin up)
  5532. (org-element-property :begin cached-before))))
  5533. (when (> (org-element-property :end up) future-change)
  5534. ;; Offset future cache request.
  5535. (org-element--cache-shift-positions
  5536. up (- offset)
  5537. (if (and (org-element-property :robust-begin up)
  5538. (org-element-property :robust-end up))
  5539. '(:contents-end :end :robust-end)
  5540. '(:contents-end :end))))
  5541. (setq up (org-element-property :parent up)))))
  5542. (org-element--cache-log-message
  5543. "New parent at %S: %S::%S"
  5544. limit
  5545. (org-element-property :org-element--cache-sync-key parent)
  5546. (org-element--format-element parent))
  5547. (setf (org-element--request-parent request) parent)
  5548. (setf (org-element--request-phase request) 2))))))
  5549. ;; Phase 2.
  5550. ;;
  5551. ;; Shift all elements starting from key START, but before NEXT, by
  5552. ;; OFFSET, and re-parent them when appropriate.
  5553. ;;
  5554. ;; Elements are modified by side-effect so the tree structure
  5555. ;; remains intact.
  5556. ;;
  5557. ;; Once THRESHOLD, if any, is reached, or once there is an input
  5558. ;; pending, exit. Before leaving, the current synchronization
  5559. ;; request is updated.
  5560. (org-element--cache-log-message "Phase 2")
  5561. (let ((start (org-element--request-key request))
  5562. (offset (org-element--request-offset request))
  5563. (parent (org-element--request-parent request))
  5564. (node (org-element--cache-root))
  5565. (stack (list nil))
  5566. (leftp t)
  5567. exit-flag continue-flag)
  5568. ;; No re-parenting nor shifting planned: request is over.
  5569. (when (and (not parent) (zerop offset))
  5570. (org-element--cache-log-message "Empty offset. Request completed.")
  5571. (throw 'org-element--cache-quit t))
  5572. (while node
  5573. (let* ((data (avl-tree--node-data node))
  5574. (key (org-element--cache-key data)))
  5575. ;; Traverse the cache tree. Ignore all the elements before
  5576. ;; START. Note that `avl-tree-stack' would not bypass the
  5577. ;; elements before START and thus would have beeen less
  5578. ;; efficient.
  5579. (if (and leftp (avl-tree--node-left node)
  5580. (not (org-element--cache-key-less-p key start)))
  5581. (progn (push node stack)
  5582. (setq node (avl-tree--node-left node)))
  5583. ;; Shift and re-parent when current node starts at or
  5584. ;; after START, but before NEXT.
  5585. (unless (org-element--cache-key-less-p key start)
  5586. ;; We reached NEXT. Request is complete.
  5587. (when (and next-request-key
  5588. (not (org-element--cache-key-less-p key next-request-key)))
  5589. (org-element--cache-log-message "Reached next request.")
  5590. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5591. (unless (and (org-element-property :cached (org-element--request-parent next-request))
  5592. (org-element-property :begin (org-element--request-parent next-request))
  5593. parent
  5594. (> (org-element-property :begin (org-element--request-parent next-request))
  5595. (org-element-property :begin parent)))
  5596. (setf (org-element--request-parent next-request) parent)))
  5597. (throw 'org-element--cache-quit t))
  5598. ;; Handle interruption request. Update current request.
  5599. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  5600. (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
  5601. (setf (org-element--request-key request) key)
  5602. (setf (org-element--request-parent request) parent)
  5603. (throw 'org-element--cache-interrupt nil))
  5604. ;; Shift element.
  5605. (unless (zerop offset)
  5606. (when (>= org-element--cache-diagnostics-level 3)
  5607. (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
  5608. offset
  5609. (org-element-property :org-element--cache-sync-key data)
  5610. (org-element--format-element data)))
  5611. (org-element--cache-shift-positions data offset))
  5612. (let ((begin (org-element-property :begin data)))
  5613. ;; Update PARENT and re-parent DATA, only when
  5614. ;; necessary. Propagate new structures for lists.
  5615. (while (and parent
  5616. (<= (org-element-property :end parent) begin))
  5617. (setq parent (org-element-property :parent parent)))
  5618. (cond ((and (not parent) (zerop offset)) (throw 'org-element--cache-quit nil))
  5619. ;; Consider scenario when DATA lays within
  5620. ;; sensitive lines of PARENT that was found
  5621. ;; during phase 2. For example:
  5622. ;;
  5623. ;; #+ begin_quote
  5624. ;; Paragraph
  5625. ;; #+end_quote
  5626. ;;
  5627. ;; In the above source block, remove space in
  5628. ;; the first line will trigger re-parenting of
  5629. ;; the paragraph and "#+end_quote" that is also
  5630. ;; considered paragraph before the modification.
  5631. ;; However, the paragraph element stored in
  5632. ;; cache must be deleted instead.
  5633. ((and parent
  5634. (or (not (memq (org-element-type parent) org-element-greater-elements))
  5635. (and (org-element-property :contents-begin parent)
  5636. (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
  5637. (and (org-element-property :contents-end parent)
  5638. (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
  5639. (> (org-element-property :end data) (org-element-property :end parent))
  5640. (and (org-element-property :contents-end data)
  5641. (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
  5642. (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
  5643. (org-element-property :org-element--cache-sync-key data)
  5644. (org-element--format-element data))
  5645. (org-element--cache-remove data)
  5646. ;; We altered the tree structure. The tree
  5647. ;; traversal needs to be restarted.
  5648. (setf (org-element--request-key request) key)
  5649. (setf (org-element--request-parent request) parent)
  5650. ;; Restart tree traversal.
  5651. (setq node (org-element--cache-root)
  5652. stack (list nil)
  5653. leftp t
  5654. begin -1
  5655. continue-flag t))
  5656. ((and parent
  5657. (not (eq parent data))
  5658. (let ((p (org-element-property :parent data)))
  5659. (or (not p)
  5660. (< (org-element-property :begin p)
  5661. (org-element-property :begin parent))
  5662. (unless (eq p parent)
  5663. (not (org-element-property :cached p))
  5664. ;; (not (avl-tree-member-p org-element--cache p))
  5665. ))))
  5666. (org-element--cache-log-message
  5667. "Updating parent in %S\n Old parent: %S\n New parent: %S"
  5668. (org-element--format-element data)
  5669. (org-element--format-element (org-element-property :parent data))
  5670. (org-element--format-element parent))
  5671. (when (and (eq 'org-data (org-element-type parent))
  5672. (not (eq 'headline (org-element-type data))))
  5673. ;; FIXME: This check is here to see whether
  5674. ;; such error happens within
  5675. ;; `org-element--cache-process-request' or somewhere
  5676. ;; else.
  5677. (org-element--cache-warn
  5678. "Added org-data parent to non-headline element: %S
  5679. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5680. data)
  5681. (org-element-cache-reset)
  5682. (throw 'org-element--cache-quit t))
  5683. (org-element-put-property data :parent parent)
  5684. (let ((s (org-element-property :structure parent)))
  5685. (when (and s (org-element-property :structure data))
  5686. (org-element-put-property data :structure s)))))
  5687. ;; Cache is up-to-date past THRESHOLD. Request
  5688. ;; interruption.
  5689. (when (and threshold (> begin threshold))
  5690. (org-element--cache-log-message "Reached threshold %S: %S"
  5691. threshold
  5692. (org-element--format-element data))
  5693. (setq exit-flag t))))
  5694. (if continue-flag
  5695. (setq continue-flag nil)
  5696. (setq node (if (setq leftp (avl-tree--node-right node))
  5697. (avl-tree--node-right node)
  5698. (pop stack)))))))
  5699. ;; We reached end of tree: synchronization complete.
  5700. t))
  5701. (org-element--cache-log-message
  5702. "org-element-cache: Finished process. The cache size is %S. The remaining sync requests: %S"
  5703. org-element--cache-size
  5704. (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests))))
  5705. (defsubst org-element--open-end-p (element)
  5706. "Check if ELEMENT in current buffer contains extra blank lines after
  5707. it and does not have closing term.
  5708. Examples of such elements are: section, headline, org-data,
  5709. and footnote-definition."
  5710. (and (org-element-property :contents-end element)
  5711. (= (org-element-property :contents-end element)
  5712. (save-excursion
  5713. (goto-char (org-element-property :end element))
  5714. (skip-chars-backward " \r\n\t")
  5715. (line-beginning-position 2)))))
  5716. (defun org-element--parse-to (pos &optional syncp time-limit)
  5717. "Parse elements in current section, down to POS.
  5718. Start parsing from the closest between the last known element in
  5719. cache or headline above. Return the smallest element containing
  5720. POS.
  5721. When optional argument SYNCP is non-nil, return the parent of the
  5722. element containing POS instead. In that case, it is also
  5723. possible to provide TIME-LIMIT, which is a time value specifying
  5724. when the parsing should stop. The function throws
  5725. `org-element--cache-interrupt' if the process stopped before finding
  5726. the expected result."
  5727. (catch 'exit
  5728. (save-match-data
  5729. (org-with-wide-buffer
  5730. (goto-char pos)
  5731. (save-excursion
  5732. (end-of-line)
  5733. (skip-chars-backward " \r\t\n")
  5734. ;; Within blank lines at the beginning of buffer, return nil.
  5735. (when (bobp) (throw 'exit nil)))
  5736. (let* ((cached (and (org-element--cache-active-p)
  5737. (org-element--cache-find pos nil)))
  5738. (mode (org-element-property :mode cached))
  5739. element next)
  5740. (cond
  5741. ;; Nothing in cache before point: start parsing from first
  5742. ;; element in buffer down to POS or from the beginning of the
  5743. ;; file.
  5744. ((and (not cached) (org-element--cache-active-p))
  5745. (setq element (org-element-org-data-parser))
  5746. (unless (org-element-property :begin element)
  5747. (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
  5748. (org-element--cache-log-message
  5749. "Nothing in cache. Adding org-data: %S"
  5750. (org-element--format-element element))
  5751. (org-element--cache-put element)
  5752. (goto-char (org-element-property :contents-begin element))
  5753. (setq mode 'org-data))
  5754. ;; Nothing in cache before point because cache is not active.
  5755. ;; Parse from previous heading to avoid re-parsing the whole
  5756. ;; buffer above. This comes at the cost of not calculating
  5757. ;; `:parent' property for headings.
  5758. ((not cached)
  5759. (if (org-with-limited-levels (outline-previous-heading))
  5760. (progn
  5761. (setq element (org-element-headline-parser nil 'fast))
  5762. (setq mode 'planning)
  5763. (forward-line))
  5764. (setq element (org-element-org-data-parser))
  5765. (setq mode 'org-data))
  5766. (org-skip-whitespace)
  5767. (beginning-of-line))
  5768. ;; Check if CACHED or any of its ancestors contain point.
  5769. ;;
  5770. ;; If there is such an element, we inspect it in order to know
  5771. ;; if we return it or if we need to parse its contents.
  5772. ;; Otherwise, we just start parsing from location, which is
  5773. ;; right after the top-most element containing CACHED but
  5774. ;; still before POS.
  5775. ;;
  5776. ;; As a special case, if POS is at the end of the buffer, we
  5777. ;; want to return the innermost element ending there.
  5778. ;;
  5779. ;; Also, if we find an ancestor and discover that we need to
  5780. ;; parse its contents, make sure we don't start from
  5781. ;; `:contents-begin', as we would otherwise go past CACHED
  5782. ;; again. Instead, in that situation, we will resume parsing
  5783. ;; from NEXT, which is located after CACHED or its higher
  5784. ;; ancestor not containing point.
  5785. (t
  5786. (let ((up cached)
  5787. (pos (if (= (point-max) pos) (1- pos) pos)))
  5788. (while (and up (<= (org-element-property :end up) pos))
  5789. (goto-char (org-element-property :end up))
  5790. (setq element up
  5791. mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
  5792. up (org-element-property :parent up)
  5793. next (point)))
  5794. (when up (setq element up)))))
  5795. ;; Parse successively each element until we reach POS.
  5796. (let ((end (or (org-element-property :end element) (point-max)))
  5797. (parent (org-element-property :parent element)))
  5798. (while t
  5799. (when (org-element--cache-interrupt-p time-limit)
  5800. (throw 'org-element--cache-interrupt nil))
  5801. (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
  5802. (when quit-flag
  5803. (cl-incf org-element--cache-interrupt-C-g-count)
  5804. (setq quit-flag nil))
  5805. (when (>= org-element--cache-interrupt-C-g-count
  5806. org-element--cache-interrupt-C-g-max-count)
  5807. (setq quit-flag t)
  5808. (setq org-element--cache-interrupt-C-g-count 0)
  5809. (org-element-cache-reset)
  5810. (error "org-element: Parsing aborted by user. Cache has been cleared.
  5811. If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
  5812. (message (substitute-command-keys
  5813. "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
  5814. (- org-element--cache-interrupt-C-g-max-count
  5815. org-element--cache-interrupt-C-g-count)))
  5816. (unless element
  5817. ;; Do not try to parse within blank at EOB.
  5818. (unless (save-excursion
  5819. (org-skip-whitespace)
  5820. (eobp))
  5821. (org-element-with-disabled-cache
  5822. (setq element (org-element--current-element
  5823. end 'element mode
  5824. (org-element-property :structure parent)))))
  5825. ;; Make sure that we return referenced element in cache
  5826. ;; that can be altered directly.
  5827. (if element
  5828. (setq element (or (org-element--cache-put element) element))
  5829. ;; Nothing to parse (i.e. empty file).
  5830. (throw 'exit parent))
  5831. (unless (or (not (org-element--cache-active-p)) parent)
  5832. (org-element--cache-warn
  5833. "Got empty parent while parsing. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n Backtrace:\n%S"
  5834. (when (and (fboundp 'backtrace-get-frames)
  5835. (fboundp 'backtrace-to-string))
  5836. (backtrace-to-string (backtrace-get-frames 'backtrace))
  5837. (org-element-cache-reset)
  5838. (error "org-element--cache: Emergency exit"))))
  5839. (org-element-put-property element :parent parent))
  5840. (let ((elem-end (org-element-property :end element))
  5841. (type (org-element-type element)))
  5842. (cond
  5843. ;; Skip any element ending before point. Also skip
  5844. ;; element ending at point (unless it is also the end of
  5845. ;; buffer) since we're sure that another element begins
  5846. ;; after it.
  5847. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5848. ;; Avoid parsing headline siblings above.
  5849. (goto-char elem-end)
  5850. (when (eq type 'headline)
  5851. (save-match-data
  5852. (unless (when (and (/= 1 (org-element-property :level element))
  5853. (re-search-forward
  5854. (rx-to-string
  5855. `(and bol (repeat 1 ,(1- (let ((level (org-element-property :level element)))
  5856. (if org-odd-levels-only (1- (* level 2)) level)))
  5857. "*")
  5858. " "))
  5859. pos t))
  5860. (beginning-of-line)
  5861. t)
  5862. ;; There are headings with lower level than
  5863. ;; ELEMENT between ELEM-END and POS. Siblings
  5864. ;; may exist though. Parse starting from the
  5865. ;; last sibling or from ELEM-END if there are
  5866. ;; no other siblings.
  5867. (goto-char pos)
  5868. (unless
  5869. (re-search-backward
  5870. (rx-to-string
  5871. `(and bol (repeat ,(let ((level (org-element-property :level element)))
  5872. (if org-odd-levels-only (1- (* level 2)) level))
  5873. "*")
  5874. " "))
  5875. elem-end t)
  5876. ;; Roll-back to normal parsing.
  5877. (goto-char elem-end)))))
  5878. (setq mode (org-element--next-mode mode type nil)))
  5879. ;; A non-greater element contains point: return it.
  5880. ((not (memq type org-element-greater-elements))
  5881. (throw 'exit (if syncp parent element)))
  5882. ;; Otherwise, we have to decide if ELEMENT really
  5883. ;; contains POS. In that case we start parsing from
  5884. ;; contents' beginning.
  5885. ;;
  5886. ;; If POS is at contents' beginning but it is also at
  5887. ;; the beginning of the first item in a list or a table.
  5888. ;; In that case, we need to create an anchor for that
  5889. ;; list or table, so return it.
  5890. ;;
  5891. ;; Also, if POS is at the end of the buffer, no element
  5892. ;; can start after it, but more than one may end there.
  5893. ;; Arbitrarily, we choose to return the innermost of
  5894. ;; such elements.
  5895. ((let ((cbeg (org-element-property :contents-begin element))
  5896. (cend (org-element-property :contents-end element)))
  5897. (when (and cbeg cend
  5898. (or (< cbeg pos)
  5899. (and (= cbeg pos)
  5900. (not (memq type '(plain-list table)))))
  5901. (or (> cend pos)
  5902. ;; When we are at cend or within blank
  5903. ;; lines after, it is a special case:
  5904. ;; 1. At the end of buffer we return
  5905. ;; the innermost element.
  5906. ;; 2. At cend of element with return
  5907. ;; that element.
  5908. ;; 3. At the end of element, we would
  5909. ;; return in the earlier cond form.
  5910. ;; 4. Within blank lines after cend,
  5911. ;; when element does not have a
  5912. ;; closing keyword, we return that
  5913. ;; outermost element, unless the
  5914. ;; outermost element is a non-empty
  5915. ;; headline. In the latter case, we
  5916. ;; return the outermost element inside
  5917. ;; the headline section.
  5918. (and (org-element--open-end-p element)
  5919. (or (= (org-element-property :end element) (point-max))
  5920. (and (>= pos (org-element-property :contents-end element))
  5921. (memq (org-element-type element) '(org-data section headline)))))))
  5922. (goto-char (or next cbeg))
  5923. (setq mode (if next mode (org-element--next-mode mode type t))
  5924. next nil
  5925. parent element
  5926. end (if (org-element--open-end-p element)
  5927. (org-element-property :end element)
  5928. (org-element-property :contents-end element))))))
  5929. ;; Otherwise, return ELEMENT as it is the smallest
  5930. ;; element containing POS.
  5931. (t (throw 'exit (if syncp parent element)))))
  5932. (setq element nil))))))))
  5933. ;;;; Staging Buffer Changes
  5934. (defconst org-element--cache-sensitive-re
  5935. (concat
  5936. "^\\*+ " "\\|"
  5937. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5938. "^[ \t]*\\(?:"
  5939. "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
  5940. org-list-full-item-re "\\|"
  5941. ":\\(?: \\|$\\)" "\\|"
  5942. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  5943. "\\)")
  5944. "Regexp matching a sensitive line, structure wise.
  5945. A sensitive line is a headline, inlinetask, block, drawer, or
  5946. latex-environment boundary. When such a line is modified,
  5947. structure changes in the document may propagate in the whole
  5948. section, possibly making cache invalid.")
  5949. (defun org-element--cache-before-change (beg end)
  5950. "Detect modifications in sensitive parts of Org buffer.
  5951. BEG and END are the beginning and end of the range of changed
  5952. text. See `before-change-functions' for more information.
  5953. The function returns the new value of `org-element--cache-change-warning'."
  5954. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  5955. (current-buffer))
  5956. (when (org-element--cache-active-p t)
  5957. (org-with-wide-buffer
  5958. (setq org-element--cache-change-tic (buffer-chars-modified-tick))
  5959. (goto-char beg)
  5960. (beginning-of-line)
  5961. (let ((bottom (save-excursion
  5962. (goto-char end)
  5963. (if (and (bolp)
  5964. ;; When beg == end, still extent to eol.
  5965. (> (point) beg))
  5966. ;; FIXME: Potential pitfall.
  5967. ;; We are appending to an element end.
  5968. ;; Unless the last inserted char is not
  5969. ;; newline, the next element is not broken
  5970. ;; and does not need to be purged from the
  5971. ;; cache.
  5972. end
  5973. (line-end-position)))))
  5974. (prog1
  5975. ;; Use the worst change warning to not miss important edits.
  5976. ;; This function is called before edit and after edit by
  5977. ;; `org-element--cache-after-change'. Before the edit, we still
  5978. ;; want to use the old value if it comes from previous
  5979. ;; not yet processed edit (they may be merged by
  5980. ;; `org-element--cache-submit-request'). After the edit, we want to
  5981. ;; look if there was a sensitive removed during edit.
  5982. ;; FIXME: This is not the most efficient way and we now
  5983. ;; have to delete more elemetns than needed in some
  5984. ;; cases. A better approach may be storing the warning
  5985. ;; in the modification request itself.
  5986. (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
  5987. (org-element--cache-change-warning-after))
  5988. (setq org-element--cache-change-warning-after
  5989. (save-match-data
  5990. (let ((case-fold-search t))
  5991. (when (re-search-forward
  5992. org-element--cache-sensitive-re bottom t)
  5993. (goto-char beg)
  5994. (beginning-of-line)
  5995. (let (min-level)
  5996. (cl-loop while (re-search-forward
  5997. (rx-to-string
  5998. (if (and min-level
  5999. (> min-level 1))
  6000. `(and bol (repeat 1 ,(1- min-level) "*") " ")
  6001. `(and bol (+ "*") " ")))
  6002. bottom t)
  6003. do (setq min-level (1- (length (match-string 0))))
  6004. until (= min-level 1))
  6005. (goto-char beg)
  6006. (beginning-of-line)
  6007. (or (and min-level (org-reduced-level min-level))
  6008. (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
  6009. 'org-data)
  6010. t))))))
  6011. (setq org-element--cache-change-warning
  6012. (cond
  6013. ((and (numberp org-element--cache-change-warning-before)
  6014. (numberp org-element--cache-change-warning-after))
  6015. (min org-element--cache-change-warning-after
  6016. org-element--cache-change-warning-before))
  6017. ((numberp org-element--cache-change-warning-before)
  6018. org-element--cache-change-warning-before)
  6019. ((numberp org-element--cache-change-warning-after)
  6020. org-element--cache-change-warning-after)
  6021. (t (or org-element--cache-change-warning-after
  6022. org-element--cache-change-warning-before)))))
  6023. (org-element--cache-log-message
  6024. "%S is about to modify text: warning %S"
  6025. this-command
  6026. org-element--cache-change-warning)))))))
  6027. (defun org-element--cache-after-change (beg end pre)
  6028. "Update buffer modifications for current buffer.
  6029. BEG and END are the beginning and end of the range of changed
  6030. text, and the length in bytes of the pre-change text replaced by
  6031. that range. See `after-change-functions' for more information."
  6032. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6033. (current-buffer))
  6034. (when (org-element--cache-active-p t)
  6035. (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
  6036. (org-element--cache-log-message "After change")
  6037. (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
  6038. ;; If beg is right after spaces in front of an element, we
  6039. ;; risk affecting previous element, so move beg to bol, making
  6040. ;; sure that we capture preceding element.
  6041. (setq beg (save-excursion
  6042. (goto-char beg)
  6043. (cl-incf pre (- beg (line-beginning-position)))
  6044. (line-beginning-position)))
  6045. ;; Store synchronization request.
  6046. (let ((offset (- end beg pre)))
  6047. (save-match-data
  6048. (org-element--cache-submit-request beg (- end offset) offset)))
  6049. ;; Activate a timer to process the request during idle time.
  6050. (org-element--cache-set-timer (current-buffer))))))
  6051. (defvar org-element--cache-avoid-synchronous-headline-re-parsing nil
  6052. "This variable controls how buffer changes are handled by the cache.
  6053. By default (when this variable is nil), cache re-parses modified
  6054. headlines immidiately after modification preserving all the unaffected
  6055. elements inside the headline.
  6056. The default behaviour works best when users types inside Org buffer of
  6057. when buffer modifications are mixed with cache requests. However,
  6058. large automated edits inserting/deleting many headlines are somewhat
  6059. slower by default (as in `org-archive-subtree'). Let-binding this
  6060. variable to non-nil will reduce cache latency after every singular edit
  6061. (`after-change-functions') at the cost of slower cache queries.")
  6062. (defun org-element--cache-for-removal (beg end offset)
  6063. "Return first element to remove from cache.
  6064. BEG and END are buffer positions delimiting buffer modifications.
  6065. OFFSET is the size of the changes.
  6066. Returned element is usually the first element in cache containing
  6067. any position between BEG and END. As an exception, greater
  6068. elements around the changes that are robust to contents
  6069. modifications are preserved and updated according to the
  6070. changes. In the latter case, the returned element is the outermost
  6071. non-robust element affected by the changes. Note that the returned
  6072. element may end before END position in which case some cached element
  6073. starting after the returned may still be affected by the changes.
  6074. Also, when there are no elements in cache before BEG, return first
  6075. known element in cache (it may start after END)."
  6076. (let* ((elements (org-element--cache-find (1- beg) 'both))
  6077. (before (car elements))
  6078. (after (cdr elements)))
  6079. (if (not before) after
  6080. ;; If BEFORE is a keyword, it may need to be removed to become
  6081. ;; an affiliated keyword.
  6082. (when (eq 'keyword (org-element-type before))
  6083. (let ((prev before))
  6084. (while (eq 'keyword (org-element-type prev))
  6085. (setq before prev
  6086. beg (org-element-property :begin prev))
  6087. (setq prev (org-element--cache-find (1- (org-element-property :begin before)))))))
  6088. (let ((up before)
  6089. (robust-flag t))
  6090. (while up
  6091. (if (let ((type (org-element-type up)))
  6092. (or (and (memq type '( center-block dynamic-block
  6093. quote-block special-block
  6094. drawer))
  6095. (or (not (eq type 'drawer))
  6096. (not (string= "PROPERTIES" (org-element-property :drawer-name up))))
  6097. ;; Sensitive change. This is
  6098. ;; unconditionally non-robust change.
  6099. (not org-element--cache-change-warning)
  6100. (let ((cbeg (org-element-property :contents-begin up))
  6101. (cend (org-element-property :contents-end up)))
  6102. (and cbeg
  6103. (<= cbeg beg)
  6104. (or (> cend end)
  6105. (and (= cend end)
  6106. (= (+ end offset) (point-max)))))))
  6107. (and (memq type '(headline section org-data))
  6108. (let ((rbeg (org-element-property :robust-begin up))
  6109. (rend (org-element-property :robust-end up)))
  6110. (and rbeg rend
  6111. (<= rbeg beg)
  6112. (or (> rend end)
  6113. (and (= rend end)
  6114. (= (+ end offset) (point-max))))))
  6115. (pcase type
  6116. ;; Sensitive change in section. Need to
  6117. ;; re-parse.
  6118. (`section (not org-element--cache-change-warning))
  6119. ;; Headline might be inserted. This is non-robust
  6120. ;; change when `up' is a `headline' or `section'
  6121. ;; with `>' level compared to the inserted headline.
  6122. ;;
  6123. ;; Also, planning info/property drawer
  6124. ;; could have been inserted. It is not
  6125. ;; robust change then.
  6126. (`headline
  6127. (and
  6128. (or (not (numberp org-element--cache-change-warning))
  6129. (> org-element--cache-change-warning
  6130. (org-element-property :level up)))
  6131. (org-with-point-at (org-element-property :contents-begin up)
  6132. (unless
  6133. (save-match-data
  6134. (when (looking-at-p org-element-planning-line-re)
  6135. (forward-line))
  6136. (when (looking-at org-property-drawer-re)
  6137. (< beg (match-end 0))))
  6138. 'robust))))
  6139. (`org-data (and (not (eq org-element--cache-change-warning 'org-data))
  6140. ;; Property drawer could
  6141. ;; have been inserted. It
  6142. ;; is not robust change
  6143. ;; then.
  6144. (org-with-wide-buffer
  6145. (goto-char (point-min))
  6146. (while (and (org-at-comment-p) (bolp)) (forward-line))
  6147. ;; Should not see property
  6148. ;; drawer within changed
  6149. ;; region.
  6150. (save-match-data
  6151. (or (not (looking-at org-property-drawer-re))
  6152. (> beg (match-end 0)))))))
  6153. (_ 'robust)))))
  6154. ;; UP is a robust greater element containing changes.
  6155. ;; We only need to extend its ending boundaries.
  6156. (progn
  6157. (org-element--cache-shift-positions
  6158. up offset
  6159. (if (and (org-element-property :robust-begin up)
  6160. (org-element-property :robust-end up))
  6161. '(:contents-end :end :robust-end)
  6162. '(:contents-end :end)))
  6163. (org-element--cache-log-message
  6164. "Shifting end positions of robust parent: %S"
  6165. (org-element--format-element up)))
  6166. (unless (or
  6167. ;; UP is non-robust. Yet, if UP is headline, flagging
  6168. ;; everything inside for removal may be to
  6169. ;; costly. Instead, we should better re-parse only the
  6170. ;; headline itself when possible. If a headline is still
  6171. ;; starting from old :begin position, we do not care that
  6172. ;; its boundaries could have extended to shrinked - we
  6173. ;; will re-parent and shift them anyway.
  6174. (and (eq 'headline (org-element-type up))
  6175. (not org-element--cache-avoid-synchronous-headline-re-parsing)
  6176. ;; The change is not inside headline. Not
  6177. ;; updating here.
  6178. (not (<= beg (org-element-property :begin up)))
  6179. (not (> end (org-element-property :end up)))
  6180. (let ((current (org-with-point-at (org-element-property :begin up)
  6181. (org-element-with-disabled-cache
  6182. (org-element--current-element (point-max))))))
  6183. (when (eq 'headline (org-element-type current))
  6184. (org-element--cache-log-message
  6185. "Found non-robust headline that can be updated individually: %S"
  6186. (org-element--format-element current))
  6187. (org-element-set-element up current)
  6188. t)))
  6189. ;; If UP is org-data, the situation is similar to
  6190. ;; headline case. We just need to re-parse the
  6191. ;; org-data itself, unless the change is made
  6192. ;; within blank lines at BOB (that could
  6193. ;; potentially alter first-section).
  6194. (when (and (eq 'org-data (org-element-type up))
  6195. (>= beg (org-element-property :contents-begin up)))
  6196. (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
  6197. (org-element--cache-log-message
  6198. "Found non-robust change invalidating org-data. Re-parsing: %S"
  6199. (org-element--format-element up))
  6200. t))
  6201. (org-element--cache-log-message
  6202. "Found non-robust element: %S"
  6203. (org-element--format-element up))
  6204. (setq before up)
  6205. (when robust-flag (setq robust-flag nil))))
  6206. (unless (or (org-element-property :parent up)
  6207. (eq 'org-data (org-element-type up)))
  6208. (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)
  6209. (org-element-cache-reset)
  6210. (error "org-element--cache: Emergency exit"))
  6211. (setq up (org-element-property :parent up)))
  6212. ;; We're at top level element containing ELEMENT: if it's
  6213. ;; altered by buffer modifications, it is first element in
  6214. ;; cache to be removed. Otherwise, that first element is the
  6215. ;; following one.
  6216. ;;
  6217. ;; As a special case, do not remove BEFORE if it is a robust
  6218. ;; container for current changes.
  6219. (if (or (< (org-element-property :end before) beg) robust-flag) after
  6220. before)))))
  6221. (defun org-element--cache-submit-request (beg end offset)
  6222. "Submit a new cache synchronization request for current buffer.
  6223. BEG and END are buffer positions delimiting the minimal area
  6224. where cache data should be removed. OFFSET is the size of the
  6225. change, as an integer."
  6226. (org-element--cache-log-message
  6227. "Submitting new synchronization request for [%S..%S]𝝙%S"
  6228. beg end offset)
  6229. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6230. (current-buffer))
  6231. (let ((next (car org-element--cache-sync-requests))
  6232. delete-to delete-from)
  6233. (if (and next
  6234. ;; First existing sync request is in phase 0.
  6235. (= 0 (org-element--request-phase next))
  6236. ;; Current changes intersect with the first sync request.
  6237. (> (setq delete-to (+ (org-element--request-end next)
  6238. (org-element--request-offset next)))
  6239. end)
  6240. (<= (setq delete-from (org-element--request-beg next))
  6241. end))
  6242. ;; Current changes can be merged with first sync request: we
  6243. ;; can save a partial cache synchronization.
  6244. (progn
  6245. (org-element--cache-log-message "Found another phase 0 request intersecting with current")
  6246. ;; Update OFFSET of the existing request.
  6247. (cl-incf (org-element--request-offset next) offset)
  6248. ;; If last change happened within area to be removed, extend
  6249. ;; boundaries of robust parents, if any. Otherwise, find
  6250. ;; first element to remove and update request accordingly.
  6251. (if (> beg delete-from)
  6252. ;; The current modification is completely inside NEXT.
  6253. ;; We already added the current OFFSET to the NEXT
  6254. ;; request. However, the robust elements around
  6255. ;; modifications also need to be shifted. Moreover, the
  6256. ;; new modification may also have non-nil
  6257. ;; `org-element--cache-change-warning'. In the latter case, we
  6258. ;; also need to update the request.
  6259. (let ((first (org-element--cache-for-removal delete-from end offset) ; Shift as needed.
  6260. ))
  6261. (org-element--cache-log-message
  6262. "Current request is inside next. Candidate parent: %S"
  6263. (org-element--format-element first))
  6264. (when
  6265. ;; Non-robust element is now before NEXT. Need to
  6266. ;; update.
  6267. (and first
  6268. (org-element--cache-key-less-p
  6269. (org-element--cache-key first)
  6270. (org-element--request-key next)))
  6271. (org-element--cache-log-message
  6272. "Current request is inside next. New parent: %S"
  6273. (org-element--format-element first))
  6274. (setf (org-element--request-key next)
  6275. (org-element--cache-key first))
  6276. (setf (org-element--request-beg next)
  6277. (org-element-property :begin first))
  6278. (setf (org-element--request-end next)
  6279. (max (org-element-property :end first)
  6280. (org-element--request-end next)))
  6281. (setf (org-element--request-parent next)
  6282. (org-element-property :parent first))))
  6283. ;; The current and NEXT modifications are intersecting
  6284. ;; with current modification starting before NEXT and NEXT
  6285. ;; ending after current. We need to update the common
  6286. ;; non-robust parent for the new extended modification
  6287. ;; region.
  6288. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  6289. (org-element--cache-log-message
  6290. "Current request intersects with next. Candidate parent: %S"
  6291. (org-element--format-element first))
  6292. (when (and first
  6293. (org-element--cache-key-less-p
  6294. (org-element--cache-key first)
  6295. (org-element--request-key next)))
  6296. (org-element--cache-log-message
  6297. "Current request intersects with next. Updating. New parent: %S"
  6298. (org-element--format-element first))
  6299. (setf (org-element--request-key next) (org-element--cache-key first))
  6300. (setf (org-element--request-beg next) (org-element-property :begin first))
  6301. (setf (org-element--request-end next)
  6302. (max (org-element-property :end first)
  6303. (org-element--request-end next)))
  6304. (setf (org-element--request-parent next) (org-element-property :parent first))))))
  6305. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  6306. ;; if any, is no longer a 0-phase request, thus ensuring that
  6307. ;; phases are properly ordered. We need to provide OFFSET as
  6308. ;; optional parameter since current modifications are not known
  6309. ;; yet to the otherwise correct part of the cache (i.e, before
  6310. ;; the first request).
  6311. (org-element--cache-log-message "Adding new phase 0 request")
  6312. (when next (org-element--cache-sync (current-buffer) end beg offset))
  6313. (let ((first (org-element--cache-for-removal beg end offset)))
  6314. (if first
  6315. (push (let ((first-beg (org-element-property :begin first))
  6316. (key (org-element--cache-key first)))
  6317. (cond
  6318. ;; When changes happen before the first known
  6319. ;; element, re-parent and shift the rest of the
  6320. ;; cache.
  6321. ((> first-beg end)
  6322. (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
  6323. (vector key first-beg nil offset nil 1))
  6324. ;; Otherwise, we find the first non robust
  6325. ;; element containing END. All elements between
  6326. ;; FIRST and this one are to be removed.
  6327. ;;
  6328. ;; The current modification is completely inside
  6329. ;; FIRST. Clear and update cached elements in
  6330. ;; region containing FIRST.
  6331. ((let ((first-end (org-element-property :end first)))
  6332. (when (> first-end end)
  6333. (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
  6334. (vector key first-beg first-end offset (org-element-property :parent first) 0))))
  6335. (t
  6336. ;; Now, FIRST is the first element after BEG or
  6337. ;; non-robust element containing BEG. However,
  6338. ;; FIRST ends before END and there might be
  6339. ;; another ELEMENT before END that spans beyond
  6340. ;; END. If there is such element, we need to
  6341. ;; extend the region down to end of the common
  6342. ;; parent of FIRST and everything inside
  6343. ;; BEG..END.
  6344. (let* ((element (org-element--cache-find end))
  6345. (element-end (org-element-property :end element))
  6346. (up element))
  6347. (while (and (not (eq up first))
  6348. (setq up (org-element-property :parent up))
  6349. (>= (org-element-property :begin up) first-beg))
  6350. ;; Note that UP might have been already
  6351. ;; shifted if it is a robust element. After
  6352. ;; deletion, it can put it's end before yet
  6353. ;; unprocessed ELEMENT.
  6354. (setq element-end (max (org-element-property :end up) element-end)
  6355. element up))
  6356. ;; Extend region to remove elements between
  6357. ;; beginning of first and the end of outermost
  6358. ;; element starting before END but after
  6359. ;; beginning of first.
  6360. ;; of the FIRST.
  6361. (org-element--cache-log-message
  6362. "Extending to all elements between:\n 1: %S\n 2: %S"
  6363. (org-element--format-element first)
  6364. (org-element--format-element element))
  6365. (vector key first-beg element-end offset up 0)))))
  6366. org-element--cache-sync-requests)
  6367. ;; No element to remove. No need to re-parent either.
  6368. ;; Simply shift additional elements, if any, by OFFSET.
  6369. (if org-element--cache-sync-requests
  6370. (progn
  6371. (org-element--cache-log-message
  6372. "Nothing to remove. Updating offset of the next request by 𝝙%S: %S"
  6373. offset
  6374. (let ((print-level 3))
  6375. (car org-element--cache-sync-requests)))
  6376. (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
  6377. offset))
  6378. (org-element--cache-log-message
  6379. "Nothing to remove. No elements in cache after %S. Terminating."
  6380. end))))))
  6381. (setq org-element--cache-change-warning nil)))
  6382. (defun org-element--cache-verify-element (element)
  6383. "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
  6384. Return non-nil when verification failed."
  6385. ;; Verify correct parent for the element.
  6386. (unless (or (org-element-property :parent element)
  6387. (eq 'org-data (org-element-type element)))
  6388. (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)
  6389. (org-element-cache-reset))
  6390. (let ((org-element--cache-self-verify
  6391. (or org-element--cache-self-verify
  6392. (and (boundp 'org-batch-test) org-batch-test)))
  6393. (org-element--cache-self-verify-frequency
  6394. (if (and (boundp 'org-batch-test) org-batch-test)
  6395. 1
  6396. org-element--cache-self-verify-frequency)))
  6397. (when (and org-element--cache-self-verify
  6398. (org-element--cache-active-p)
  6399. (derived-mode-p 'org-mode)
  6400. (org-element-property :parent element)
  6401. (eq 'headline (org-element-type element))
  6402. ;; Avoid too much slowdown
  6403. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6404. (org-with-point-at (org-element-property :begin element)
  6405. (org-element-with-disabled-cache (org-up-heading-or-point-min))
  6406. (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
  6407. (eq (point) (point-min)))
  6408. (org-element--cache-warn
  6409. "Cached element has wrong parent in %s. Resetting.
  6410. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6411. The element is: %S\n The parent is: %S\n The real parent is: %S"
  6412. (buffer-name (current-buffer))
  6413. (org-element--format-element element)
  6414. (org-element--format-element (org-element-property :parent element))
  6415. (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
  6416. (org-element-cache-reset))
  6417. (org-element--cache-verify-element (org-element-property :parent element))))
  6418. ;; Verify the element itself.
  6419. (when (and org-element--cache-self-verify
  6420. (org-element--cache-active-p)
  6421. element
  6422. (not (memq (org-element-type element) '(section org-data)))
  6423. ;; Avoid too much slowdown
  6424. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6425. (let ((real-element (let (org-element-use-cache)
  6426. (org-element--parse-to
  6427. (if (memq (org-element-type element) '(table-row item))
  6428. (1+ (org-element-property :begin element))
  6429. (org-element-property :begin element))))))
  6430. (unless (and (eq (org-element-type real-element) (org-element-type element))
  6431. (eq (org-element-property :begin real-element) (org-element-property :begin element))
  6432. (eq (org-element-property :end real-element) (org-element-property :end element))
  6433. (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
  6434. (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
  6435. (or (not (org-element-property :ID real-element))
  6436. (string= (org-element-property :ID real-element) (org-element-property :ID element))))
  6437. (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
  6438. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6439. The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
  6440. this-command
  6441. (buffer-name (current-buffer))
  6442. (if (/= org-element--cache-change-tic
  6443. (buffer-chars-modified-tick))
  6444. "no" "yes")
  6445. (org-element--format-element element)
  6446. (org-element--format-element real-element)
  6447. (org-element--cache-find (1- (org-element-property :begin real-element)))
  6448. (car (org-element--cache-find (org-element-property :begin real-element) 'both))
  6449. (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
  6450. (org-element-cache-reset))))))
  6451. ;;; Cache persistance
  6452. (defun org-element--cache-persist-before-write (container &optional associated)
  6453. "Sync cache before saving."
  6454. (when (equal container '(elisp org-element--cache))
  6455. (if (and org-element-use-cache
  6456. (plist-get associated :file)
  6457. (get-file-buffer (plist-get associated :file))
  6458. org-element-cache-persistent)
  6459. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6460. (if (and (derived-mode-p 'org-mode)
  6461. org-element--cache)
  6462. (progn
  6463. ;; Cleanup cache request keys to avoid collisions during next
  6464. ;; Emacs session.
  6465. (avl-tree-mapc
  6466. (lambda (el)
  6467. (org-element-put-property el :org-element--cache-sync-key nil))
  6468. org-element--cache)
  6469. (org-with-wide-buffer
  6470. (org-element-at-point (point-max)))
  6471. nil)
  6472. 'forbid))
  6473. 'forbid)))
  6474. (defun org-element--cache-persist-before-read (container &optional associated)
  6475. "Avoid reading cache before Org mode is loaded."
  6476. (when (equal container '(elisp org-element--cache))
  6477. (if (not (and (plist-get associated :file)
  6478. (get-file-buffer (plist-get associated :file))))
  6479. 'forbid
  6480. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6481. (unless (and org-element-use-cache
  6482. org-element-cache-persistent
  6483. (derived-mode-p 'org-mode)
  6484. (equal (secure-hash 'md5 (current-buffer))
  6485. (plist-get associated :hash)))
  6486. 'forbid)))))
  6487. (defun org-element--cache-persist-after-read (container &optional associated)
  6488. "Setup restored cache."
  6489. (when (and (plist-get associated :file)
  6490. (get-file-buffer (plist-get associated :file)))
  6491. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6492. (when (and org-element-use-cache org-element-cache-persistent)
  6493. (when (and (equal container '(elisp org-element--cache)) org-element--cache)
  6494. (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
  6495. (when (and (equal container '(elisp org-element--headline-cache)) org-element--headline-cache)
  6496. (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache)))))))
  6497. (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
  6498. (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
  6499. (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
  6500. ;;;; Public Functions
  6501. (defvar-local org-element--cache-gapless nil
  6502. "An alist containing (granularity . `org-element--cache-change-tic') elements.
  6503. Each element indicates the latest `org-element--cache-change-tic' when
  6504. change did not contain gaps.")
  6505. ;;;###autoload
  6506. (defun org-element-cache-reset (&optional all)
  6507. "Reset cache in current buffer.
  6508. When optional argument ALL is non-nil, reset cache in all Org
  6509. buffers."
  6510. (interactive "P")
  6511. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  6512. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  6513. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  6514. (when (not org-element-cache-persistent)
  6515. (org-persist-unregister 'org-element--headline-cache (current-buffer))
  6516. (org-persist-unregister 'org-element--cache (current-buffer)))
  6517. (when (and org-element-cache-persistent
  6518. (buffer-file-name (current-buffer)))
  6519. (org-persist-register 'org-element--cache (current-buffer))
  6520. (org-persist-register 'org-element--headline-cache
  6521. (current-buffer)
  6522. :inherit 'org-element--cache))
  6523. (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
  6524. (setq-local org-element--cache-gapless nil)
  6525. (setq-local org-element--cache
  6526. (avl-tree-create #'org-element--cache-compare))
  6527. (setq-local org-element--headline-cache
  6528. (avl-tree-create #'org-element--cache-compare))
  6529. (setq-local org-element--cache-size 0)
  6530. (setq-local org-element--headline-cache-size 0)
  6531. (setq-local org-element--cache-sync-keys-value 0)
  6532. (setq-local org-element--cache-change-warning nil)
  6533. (setq-local org-element--cache-sync-requests nil)
  6534. (setq-local org-element--cache-sync-timer nil)
  6535. (add-hook 'before-change-functions
  6536. #'org-element--cache-before-change nil t)
  6537. (add-hook 'after-change-functions
  6538. #'org-element--cache-after-change nil t)))))
  6539. ;;;###autoload
  6540. (defun org-element-cache-refresh (pos)
  6541. "Refresh cache at position POS."
  6542. (when (org-element--cache-active-p)
  6543. (org-element--cache-sync (current-buffer) pos)
  6544. (org-element--cache-submit-request pos pos 0)
  6545. (org-element--cache-set-timer (current-buffer))))
  6546. (defvar warning-minimum-log-level) ; Defined in warning.el
  6547. (defvar org-element-cache-map--recurse nil)
  6548. (defvar org-element-cache-map-continue-from nil
  6549. "Position from where mapping should continue.
  6550. This variable can be set by called function, especially when the
  6551. function modified the buffer.")
  6552. ;;;###autoload
  6553. (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
  6554. next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
  6555. narrow)
  6556. "Map all elements in current buffer with FUNC according to
  6557. GRANULARITY. Collect non-nil return values into result list.
  6558. FUNC should accept a single argument - the element.
  6559. FUNC can modify the buffer, but doing so may reduce performance. If
  6560. buffer is modified, the mapping will continue from an element starting
  6561. after the last mapped element. If the last mapped element is deleted,
  6562. the subsequent element will be skipped as it cannot be distinguished
  6563. deterministically from a changed element. If FUNC is expected to
  6564. delete the element, it should directly set the value of
  6565. `org-element-cache-map-continue-from' to force `org-element-cache-map'
  6566. continue from the right point in buffer.
  6567. If some elements are not yet in cache, they will be added.
  6568. GRANULARITY can be `headline', `headline+inlinetask'
  6569. `greater-element', or `element'. The default is
  6570. `headline+inlinetask'. `object' granularity is not supported.
  6571. RESTRICT-ELEMENTS is a list of element types to be mapped over.
  6572. NEXT-RE is a regexp used to search next candidate match when FUNC
  6573. returns non-nil and to search the first candidate match. FAIL-RE is a
  6574. regexp used to search next candidate match when FUNC returns nil. The
  6575. mapping will continue starting from headline at the RE match.
  6576. FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
  6577. mapped elements to elements starting at of after FROM-POS but before
  6578. TO-POS.
  6579. AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
  6580. after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
  6581. map all the elements starting from first element inside section, but
  6582. not including the section).
  6583. LIMIT-COUNT limits mapping to that many first matches where FUNC
  6584. returns non-nil.
  6585. NARROW controls whether current buffer narrowing should be preserved.
  6586. This function does a subset of what `org-element-map' does, but with
  6587. much better performance. Cached elements are supplied as the single
  6588. argument of FUNC. Changes to elements made in FUNC will also alter
  6589. the cache."
  6590. (unless (org-element--cache-active-p)
  6591. (error "Cache must be active."))
  6592. (unless (memq granularity '( headline headline+inlinetask
  6593. greater-element element))
  6594. (error "Unsupported granularity: %S" granularity))
  6595. ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
  6596. ;; process.
  6597. (unless (markerp to-pos)
  6598. (let ((mk (make-marker)))
  6599. (set-marker mk to-pos)
  6600. (setq to-pos mk)))
  6601. ;; Make sure that garbage collector does not stand on the way to
  6602. ;; maximum performance.
  6603. (let ((gc-cons-threshold #x40000000)
  6604. ;; Bind variables used inside loop to avoid memory
  6605. ;; re-allocation on every iteration.
  6606. ;; See https://emacsconf.org/2021/talks/faster/
  6607. tmpnext-start tmpparent tmpelement)
  6608. (save-excursion
  6609. (save-restriction
  6610. (unless narrow (widen))
  6611. ;; Synchronise cache up to the end of mapped region.
  6612. (org-element-at-point to-pos)
  6613. (cl-macrolet ((cache-root
  6614. ;; Use the most optimal version of cache available.
  6615. () `(if (memq granularity '(headline headline+inlinetask))
  6616. (org-element--headline-cache-root)
  6617. (org-element--cache-root)))
  6618. (cache-size
  6619. ;; Use the most optimal version of cache available.
  6620. () `(if (memq granularity '(headline headline+inlinetask))
  6621. org-element--headline-cache-size
  6622. org-element--cache-size))
  6623. (cache-walk-restart
  6624. ;; Restart tree traversal after AVL tree re-balance.
  6625. () `(when node
  6626. (org-element-at-point (point-max))
  6627. (setq node (cache-root)
  6628. stack (list nil)
  6629. leftp t
  6630. continue-flag t)))
  6631. (cache-walk-abort
  6632. ;; Abort tree traversal.
  6633. () `(setq continue-flag t
  6634. node nil))
  6635. (element-match-at-point
  6636. ;; Returning the first element to match around point.
  6637. ;; For example, if point is inside headline and
  6638. ;; granularity is restricted to headlines only, skip
  6639. ;; over all the child elements inside the headline
  6640. ;; and return the first parent headline.
  6641. ;; When we are inside a cache gap, calling
  6642. ;; `org-element-at-point' also fills the cache gap down to
  6643. ;; point.
  6644. () `(progn
  6645. ;; Parsing is one of the performance
  6646. ;; bottlenecks. Make sure to optimise it as
  6647. ;; much as possible.
  6648. ;;
  6649. ;; Avoid extra staff like timer cancels et al
  6650. ;; and only call `org-element--cache-sync-requests' when
  6651. ;; there are pending requests.
  6652. (when org-element--cache-sync-requests
  6653. (org-element--cache-sync (current-buffer)))
  6654. ;; Call `org-element--parse-to' directly avoiding any
  6655. ;; kind of `org-element-at-point' overheads.
  6656. (if restrict-elements
  6657. ;; Search directly instead of calling
  6658. ;; `org-element-lineage' to avoid funcall overheads
  6659. ;; and making sure that we do not go all
  6660. ;; the way to `org-data' as `org-element-lineage'
  6661. ;; does.
  6662. (progn
  6663. (setq tmpelement (org-element--parse-to (point)))
  6664. (while (and tmpelement (not (memq (org-element-type tmpelement) restrict-elements)))
  6665. (setq tmpelement (org-element-property :parent tmpelement)))
  6666. tmpelement)
  6667. (org-element--parse-to (point)))))
  6668. ;; Starting from (point), search RE and move START to
  6669. ;; the next valid element to be matched according to
  6670. ;; restriction. Abort cache walk if no next element
  6671. ;; can be found. When RE is nil, just find element at
  6672. ;; point.
  6673. (move-start-to-next-match
  6674. (re) `(save-match-data
  6675. (if (or (not ,re)
  6676. (if org-element--cache-map-statistics
  6677. (progn
  6678. (setq before-time (float-time))
  6679. (re-search-forward (or (car-safe ,re) ,re) nil 'move)
  6680. (cl-incf re-search-time
  6681. (- (float-time)
  6682. before-time)))
  6683. (re-search-forward (or (car-safe ,re) ,re) nil 'move)))
  6684. (unless (or (< (point) (or start -1))
  6685. (and data
  6686. (< (point) (org-element-property :begin data))))
  6687. (if (cdr-safe ,re)
  6688. ;; Avoid parsing when we are 100%
  6689. ;; sure that regexp is good enough
  6690. ;; to find new START.
  6691. (setq start (match-beginning 0))
  6692. (setq start (max (or start -1)
  6693. (or (org-element-property :begin data) -1)
  6694. (or (org-element-property :begin (element-match-at-point)) -1))))
  6695. (when (>= start to-pos) (cache-walk-abort))
  6696. (when (eq start -1) (setq start nil)))
  6697. (cache-walk-abort))))
  6698. ;; Find expected begin position of an element after
  6699. ;; DATA.
  6700. (next-element-start
  6701. () `(progn
  6702. (setq tmpnext-start nil)
  6703. (if (memq granularity '(headline headline+inlinetask))
  6704. (setq tmpnext-start (or (when (memq (org-element-type data) '(headline org-data))
  6705. (org-element-property :contents-begin data))
  6706. (org-element-property :end data)))
  6707. (setq tmpnext-start (or (when (memq (org-element-type data) org-element-greater-elements)
  6708. (org-element-property :contents-begin data))
  6709. (org-element-property :end data))))
  6710. ;; DATA end may be the last element inside
  6711. ;; i.e. source block. Skip up to the end
  6712. ;; of parent in such case.
  6713. (setq tmpparent data)
  6714. (catch :exit
  6715. (when (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6716. (setq tmpnext-start (org-element-property :end tmpparent)))
  6717. (while (setq tmpparent (org-element-property :parent tmpparent))
  6718. (if (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6719. (setq tmpnext-start (org-element-property :end tmpparent))
  6720. (throw :exit t))))
  6721. tmpnext-start))
  6722. ;; Check if cache does not have gaps.
  6723. (cache-gapless-p
  6724. () `(eq org-element--cache-change-tic
  6725. (alist-get granularity org-element--cache-gapless))))
  6726. ;; The core algorithm is simple walk along binary tree. However,
  6727. ;; instead of checking all the tree elements from first to last
  6728. ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
  6729. ;; the elements before FROM-POS efficiently: O(logN) instead of
  6730. ;; O(Nbefore).
  6731. ;;
  6732. ;; Later, we may also not check every single element in the
  6733. ;; binary tree after FROM-POS. Instead, we can find position of
  6734. ;; next candidate elements by means of regexp search and skip the
  6735. ;; binary tree branches that are before the next candidate:
  6736. ;; again, O(logN) instead of O(Nbetween).
  6737. ;;
  6738. ;; Some elements might not yet be in the tree. So, we also parse
  6739. ;; the empty gaps in cache as needed making sure that we do not
  6740. ;; miss anything.
  6741. (let* (;; START is always beginning of an element. When there is
  6742. ;; no element in cache at START, we are inside cache gap
  6743. ;; and need to fill it.
  6744. (start (and from-pos
  6745. (progn
  6746. (goto-char from-pos)
  6747. (org-element-property :begin (element-match-at-point)))))
  6748. ;; Some elements may start at the same position, so we
  6749. ;; also keep track of the last processed element and make
  6750. ;; sure that we do not try to search it again.
  6751. (prev after-element)
  6752. (node (cache-root))
  6753. data
  6754. (stack (list nil))
  6755. (leftp t)
  6756. result
  6757. ;; Whether previous element matched FUNC (FUNC
  6758. ;; returned non-nil).
  6759. (last-match t)
  6760. continue-flag
  6761. ;; Generic regexp to search next potential match. If it
  6762. ;; is a cons of (regexp . 'match-beg), we are 100% sure
  6763. ;; that the match beginning is the existing element
  6764. ;; beginning.
  6765. (next-element-re (pcase granularity
  6766. ((or `headline
  6767. (guard (eq '(headline)
  6768. restrict-elements)))
  6769. (cons
  6770. (org-with-limited-levels
  6771. org-element-headline-re)
  6772. 'match-beg))
  6773. (`headline+inlinetask
  6774. (cons
  6775. (if (eq '(inlinetask) restrict-elements)
  6776. (org-inlinetask-outline-regexp)
  6777. org-element-headline-re)
  6778. 'match-beg))
  6779. ;; TODO: May add other commonly
  6780. ;; searched elements as needed.
  6781. (_)))
  6782. ;; Make sure that we are not checking the same regexp twice.
  6783. (next-re (unless (and next-re
  6784. (string= next-re
  6785. (or (car-safe next-element-re)
  6786. next-element-re)))
  6787. next-re))
  6788. (fail-re (unless (and fail-re
  6789. (string= fail-re
  6790. (or (car-safe next-element-re)
  6791. next-element-re)))
  6792. fail-re))
  6793. (restrict-elements (or restrict-elements
  6794. (pcase granularity
  6795. (`headline
  6796. '(headline))
  6797. (`headline+inlinetask
  6798. '(headline inlinetask))
  6799. (`greater-element
  6800. org-element-greater-elements)
  6801. (_ nil))))
  6802. ;; Statistics
  6803. (time (float-time))
  6804. (predicate-time 0)
  6805. (pre-process-time 0)
  6806. (re-search-time 0)
  6807. (count-predicate-calls-match 0)
  6808. (count-predicate-calls-fail 0)
  6809. ;; Bind variables used inside loop to avoid memory
  6810. ;; re-allocation on every iteration.
  6811. ;; See https://emacsconf.org/2021/talks/faster/
  6812. cache-size before-time modified-tic)
  6813. ;; Skip to first element within region.
  6814. (goto-char (or start (point-min)))
  6815. (move-start-to-next-match next-element-re)
  6816. (unless (and start (>= start to-pos))
  6817. ;; Pre-process cache filling all the gaps.
  6818. (unless (or org-element-cache-map--recurse
  6819. (cache-gapless-p)
  6820. ;; Pre-processing all the elements in large
  6821. ;; buffers when NEXT-RE/FAIL-RE are provided
  6822. ;; may be much slower compared to using
  6823. ;; regexp.
  6824. (and (eq granularity 'element)
  6825. (or next-re fail-re)))
  6826. (let ((org-element-cache-map--recurse t))
  6827. (setq before-time (float-time))
  6828. (org-element-cache-map
  6829. #'ignore
  6830. :granularity granularity)
  6831. (cl-incf pre-process-time
  6832. (- (float-time)
  6833. before-time))
  6834. ;; Re-assign the cache root after filling the cache
  6835. ;; gaps.
  6836. (setq node (cache-root)))
  6837. (setf (alist-get granularity org-element--cache-gapless)
  6838. org-element--cache-change-tic))
  6839. (while node
  6840. (setq data (avl-tree--node-data node))
  6841. (if (and leftp (avl-tree--node-left node) ; Left branch.
  6842. ;; Do not move to left branch when we are before
  6843. ;; PREV.
  6844. (or (not prev)
  6845. (not (org-element--cache-key-less-p
  6846. (org-element--cache-key data)
  6847. (org-element--cache-key prev))))
  6848. ;; ... or when we are before START.
  6849. (or (not start)
  6850. (not (> start (org-element-property :begin data)))))
  6851. (progn (push node stack)
  6852. (setq node (avl-tree--node-left node)))
  6853. ;; The whole tree left to DATA is before START and
  6854. ;; PREV. DATA may still be before START (i.e. when
  6855. ;; DATA is the root or when START moved), at START, or
  6856. ;; after START.
  6857. ;;
  6858. ;; If DATA is before start, skip it over and move to
  6859. ;; subsequent elements.
  6860. ;; If DATA is at start, run FUNC if necessary and
  6861. ;; update START according and NEXT-RE, FAIL-RE,
  6862. ;; NEXT-ELEMENT-RE.
  6863. ;; If DATA is after start, we have found a cache gap
  6864. ;; and need to fill it.
  6865. (unless (or (and start (< (org-element-property :begin data) start))
  6866. (and prev (not (org-element--cache-key-less-p
  6867. (org-element--cache-key prev)
  6868. (org-element--cache-key data)))))
  6869. ;; DATA is at of after START and PREV.
  6870. (if (or (not start) (= (org-element-property :begin data) start))
  6871. ;; DATA is at START. Match it.
  6872. ;; In the process, we may alter the buffer,
  6873. ;; so also keep track of the cache state.
  6874. (progn
  6875. (setq modified-tic org-element--cache-change-tic)
  6876. (setq cache-size (cache-size))
  6877. ;; When NEXT-RE/FAIL-RE is provided, skip to
  6878. ;; next regexp match after :begin of the current
  6879. ;; element.
  6880. (when (if last-match next-re fail-re)
  6881. (goto-char (org-element-property :begin data))
  6882. (move-start-to-next-match
  6883. (if last-match next-re fail-re)))
  6884. (when (and (or (not start) (eq (org-element-property :begin data) start))
  6885. (< (org-element-property :begin data) to-pos))
  6886. ;; Calculate where next possible element
  6887. ;; starts and update START if needed.
  6888. (setq start (next-element-start))
  6889. (goto-char start)
  6890. ;; Move START further if possible.
  6891. (when (and next-element-re
  6892. ;; Do not move if we know for
  6893. ;; sure that cache does not
  6894. ;; contain gaps. Regexp
  6895. ;; searches are not cheap.
  6896. (not (cache-gapless-p)))
  6897. (move-start-to-next-match next-element-re)
  6898. ;; Make sure that point is at START
  6899. ;; before running FUNC.
  6900. (goto-char start))
  6901. ;; Try FUNC if DATA matches all the
  6902. ;; restrictions. Calculate new START.
  6903. (when (or (not restrict-elements)
  6904. (memq (org-element-type data) restrict-elements))
  6905. ;; DATA matches restriction. FUNC may
  6906. ;;
  6907. ;; Call FUNC. FUNC may move point.
  6908. (setq org-element-cache-map-continue-from nil)
  6909. (if org-element--cache-map-statistics
  6910. (progn
  6911. (setq before-time (float-time))
  6912. (push (funcall func data) result)
  6913. (cl-incf predicate-time
  6914. (- (float-time)
  6915. before-time))
  6916. (if (car result)
  6917. (cl-incf count-predicate-calls-match)
  6918. (cl-incf count-predicate-calls-fail)))
  6919. (push (funcall func data) result)
  6920. (when (car result) (cl-incf count-predicate-calls-match)))
  6921. ;; Set `last-match'.
  6922. (setq last-match (car result))
  6923. ;; If FUNC moved point forward, update
  6924. ;; START.
  6925. (when org-element-cache-map-continue-from
  6926. (goto-char org-element-cache-map-continue-from))
  6927. (when (> (point) start)
  6928. (move-start-to-next-match nil))
  6929. ;; Drop nil.
  6930. (unless (car result) (pop result)))
  6931. ;; If FUNC did not move the point and we
  6932. ;; know for sure that cache does not contain
  6933. ;; gaps, do not try to calculate START in
  6934. ;; advance but simply loop to the next cache
  6935. ;; element.
  6936. (when (and (cache-gapless-p)
  6937. (eq (next-element-start)
  6938. start))
  6939. (setq start nil))
  6940. ;; Check if the buffer has been modified.
  6941. (unless (and (eq modified-tic org-element--cache-change-tic)
  6942. (eq cache-size (cache-size)))
  6943. ;; START may no longer be valid, update
  6944. ;; it to beginning of real element.
  6945. ;; Upon modification, START may lay
  6946. ;; inside an element. We want to move
  6947. ;; it to real beginning then despite
  6948. ;; START being larger.
  6949. (setq start nil)
  6950. (move-start-to-next-match nil)
  6951. ;; The new element may now start before
  6952. ;; or at already processed position.
  6953. ;; Make sure that we continue from an
  6954. ;; element past already processed
  6955. ;; place.
  6956. (when (and start
  6957. (<= start (org-element-property :begin data))
  6958. (not org-element-cache-map-continue-from))
  6959. (goto-char start)
  6960. (setq data (element-match-at-point))
  6961. ;; If DATA is nil, buffer is
  6962. ;; empty. Abort.
  6963. (when data
  6964. (goto-char (next-element-start))
  6965. (move-start-to-next-match next-element-re)))
  6966. (org-element-at-point to-pos)
  6967. (cache-walk-restart))
  6968. ;; Reached LIMIT-COUNT. Abort.
  6969. (when (and limit-count
  6970. (>= count-predicate-calls-match
  6971. limit-count))
  6972. (cache-walk-abort))
  6973. (if (org-element-property :cached data)
  6974. (setq prev data)
  6975. (setq prev nil))))
  6976. ;; DATA is after START. Fill the gap.
  6977. (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
  6978. ;; Tables and lists are special, we need a
  6979. ;; trickery to make items/rows be populated
  6980. ;; into cache.
  6981. (org-element--parse-to (1+ start)))
  6982. ;; Restart tree traversal as AVL tree is
  6983. ;; re-balanced upon adding elements. We can no
  6984. ;; longer trust STACK.
  6985. (cache-walk-restart)))
  6986. ;; Second, move to the right branch of the tree or skip
  6987. ;; it alltogether.
  6988. (if continue-flag
  6989. (setq continue-flag nil)
  6990. (setq node (if (and (car stack)
  6991. ;; If START advanced beyond stack parent, skip the right branch.
  6992. (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
  6993. (and prev (org-element--cache-key-less-p
  6994. (org-element--cache-key (avl-tree--node-data (car stack)))
  6995. (org-element--cache-key prev)))))
  6996. (progn
  6997. (setq leftp nil)
  6998. (pop stack))
  6999. ;; Otherwise, move ahead into the right
  7000. ;; branch when it exists.
  7001. (if (setq leftp (avl-tree--node-right node))
  7002. (avl-tree--node-right node)
  7003. (pop stack))))))))
  7004. (when (and org-element--cache-map-statistics
  7005. (or (not org-element--cache-map-statistics-threshold)
  7006. (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
  7007. (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.
  7008. 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"
  7009. (current-buffer)
  7010. count-predicate-calls-match
  7011. (+ count-predicate-calls-match
  7012. count-predicate-calls-fail)
  7013. (- (float-time) time)
  7014. pre-process-time
  7015. predicate-time
  7016. re-search-time
  7017. granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
  7018. ;; Return result.
  7019. (nreverse result)))))))
  7020. ;;; The Toolbox
  7021. ;;
  7022. ;; The first move is to implement a way to obtain the smallest element
  7023. ;; containing point. This is the job of `org-element-at-point'. It
  7024. ;; basically jumps back to the beginning of section containing point
  7025. ;; and proceed, one element after the other, with
  7026. ;; `org-element--current-element' until the container is found. Note:
  7027. ;; When using `org-element-at-point', secondary values are never
  7028. ;; parsed since the function focuses on elements, not on objects.
  7029. ;;
  7030. ;; At a deeper level, `org-element-context' lists all elements and
  7031. ;; objects containing point.
  7032. ;;
  7033. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  7034. ;; internally by navigation and manipulation tools.
  7035. ;;;###autoload
  7036. (defun org-element-at-point (&optional pom cached-only)
  7037. "Determine closest element around point or POM.
  7038. Only check cached element when CACHED-ONLY is non-nil and return nil
  7039. unconditionally when element at POM is not in cache.
  7040. Return value is a list like (TYPE PROPS) where TYPE is the type
  7041. of the element and PROPS a plist of properties associated to the
  7042. element.
  7043. Possible types are defined in `org-element-all-elements'.
  7044. Properties depend on element or object type, but always include
  7045. `:begin', `:end', and `:post-blank' properties.
  7046. As a special case, if point is at the very beginning of the first
  7047. item in a list or sub-list, returned element will be that list
  7048. instead of the item. Likewise, if point is at the beginning of
  7049. the first row of a table, returned element will be the table
  7050. instead of the first row.
  7051. When point is at the end of the buffer, return the innermost
  7052. element ending there."
  7053. (setq pom (or pom (point)))
  7054. ;; Allow re-parsing when the command can benefit from it.
  7055. (when (and cached-only
  7056. (memq this-command org-element--cache-non-modifying-commands))
  7057. (setq cached-only nil))
  7058. (let (element)
  7059. (when (org-element--cache-active-p)
  7060. (if (not org-element--cache) (org-element-cache-reset)
  7061. (unless cached-only (org-element--cache-sync (current-buffer) pom))))
  7062. (setq element (if cached-only
  7063. (and (org-element--cache-active-p)
  7064. (or (not org-element--cache-sync-requests)
  7065. (org-element--cache-key-less-p pom (org-element--request-key (car org-element--cache-sync-requests))))
  7066. (org-element--cache-find pom))
  7067. (condition-case err
  7068. (org-element--parse-to pom)
  7069. (error
  7070. (org-element--cache-warn
  7071. "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)."
  7072. (buffer-name (current-buffer))
  7073. pom
  7074. err
  7075. (when (and (fboundp 'backtrace-get-frames)
  7076. (fboundp 'backtrace-to-string))
  7077. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  7078. (org-element-cache-reset)
  7079. (org-element--parse-to pom)))))
  7080. (when (and (org-element--cache-active-p)
  7081. element
  7082. (org-element--cache-verify-element element))
  7083. (setq element (org-element--parse-to pom)))
  7084. (unless (eq 'org-data (org-element-type element))
  7085. (unless (and cached-only
  7086. (not (and element
  7087. (or (= pom (org-element-property :begin element))
  7088. (and (not (memq (org-element-type element) org-element-greater-elements))
  7089. (>= pom (org-element-property :begin element))
  7090. (< pom (org-element-property :end element)))
  7091. (and (org-element-property :contents-begin element)
  7092. (>= pom (org-element-property :begin element))
  7093. (< pom (org-element-property :contents-begin element)))
  7094. (and (not (org-element-property :contents-end element))
  7095. (>= pom (org-element-property :begin element))
  7096. (< pom (org-element-property :end element)))))))
  7097. (if (not (eq (org-element-type element) 'section))
  7098. element
  7099. (org-element-at-point (1+ pom) cached-only))))))
  7100. ;;;###autoload
  7101. (defsubst org-element-at-point-no-context (&optional pom)
  7102. "Quickly find element at point or POM.
  7103. It is a faster version of `org-element-at-point' that is not
  7104. guaranteed to return correct `:parent' properties even when cache is
  7105. enabled."
  7106. (or (org-element-at-point pom 'cached-only)
  7107. (let (org-element-use-cache) (org-element-at-point pom))))
  7108. ;;;###autoload
  7109. (defun org-element-context (&optional element)
  7110. "Return smallest element or object around point.
  7111. Return value is a list like (TYPE PROPS) where TYPE is the type
  7112. of the element or object and PROPS a plist of properties
  7113. associated to it.
  7114. Possible types are defined in `org-element-all-elements' and
  7115. `org-element-all-objects'. Properties depend on element or
  7116. object type, but always include `:begin', `:end', `:parent' and
  7117. `:post-blank'.
  7118. As a special case, if point is right after an object and not at
  7119. the beginning of any other object, return that object.
  7120. Optional argument ELEMENT, when non-nil, is the closest element
  7121. containing point, as returned by `org-element-at-point'.
  7122. Providing it allows for quicker computation."
  7123. (catch 'objects-forbidden
  7124. (org-with-wide-buffer
  7125. (let* ((pos (point))
  7126. (element (or element (org-element-at-point)))
  7127. (type (org-element-type element))
  7128. (post (org-element-property :post-affiliated element)))
  7129. ;; If point is inside an element containing objects or
  7130. ;; a secondary string, narrow buffer to the container and
  7131. ;; proceed with parsing. Otherwise, return ELEMENT.
  7132. (cond
  7133. ;; At a parsed affiliated keyword, check if we're inside main
  7134. ;; or dual value.
  7135. ((and post (< pos post))
  7136. (beginning-of-line)
  7137. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  7138. (cond
  7139. ((not (member-ignore-case (match-string 1)
  7140. org-element-parsed-keywords))
  7141. (throw 'objects-forbidden element))
  7142. ((< (match-end 0) pos)
  7143. (narrow-to-region (match-end 0) (line-end-position)))
  7144. ((and (match-beginning 2)
  7145. (>= pos (match-beginning 2))
  7146. (< pos (match-end 2)))
  7147. (narrow-to-region (match-beginning 2) (match-end 2)))
  7148. (t (throw 'objects-forbidden element)))
  7149. ;; Also change type to retrieve correct restrictions.
  7150. (setq type 'keyword))
  7151. ;; At an item, objects can only be located within tag, if any.
  7152. ((eq type 'item)
  7153. (let ((tag (org-element-property :tag element)))
  7154. (if (or (not tag) (/= (line-beginning-position) post))
  7155. (throw 'objects-forbidden element)
  7156. (beginning-of-line)
  7157. (search-forward tag (line-end-position))
  7158. (goto-char (match-beginning 0))
  7159. (if (and (>= pos (point)) (< pos (match-end 0)))
  7160. (narrow-to-region (point) (match-end 0))
  7161. (throw 'objects-forbidden element)))))
  7162. ;; At an headline or inlinetask, objects are in title.
  7163. ((memq type '(headline inlinetask))
  7164. (let ((case-fold-search nil))
  7165. (goto-char (org-element-property :begin element))
  7166. (looking-at org-complex-heading-regexp)
  7167. (let ((end (match-end 4)))
  7168. (if (not end) (throw 'objects-forbidden element)
  7169. (goto-char (match-beginning 4))
  7170. (when (looking-at org-element-comment-string)
  7171. (goto-char (match-end 0)))
  7172. (if (>= (point) end) (throw 'objects-forbidden element)
  7173. (narrow-to-region (point) end))))))
  7174. ;; At a paragraph, a table-row or a verse block, objects are
  7175. ;; located within their contents.
  7176. ((memq type '(paragraph table-row verse-block))
  7177. (let ((cbeg (org-element-property :contents-begin element))
  7178. (cend (org-element-property :contents-end element)))
  7179. ;; CBEG is nil for table rules.
  7180. (if (and cbeg cend (>= pos cbeg)
  7181. (or (< pos cend) (and (= pos cend) (eobp))))
  7182. (narrow-to-region cbeg cend)
  7183. (throw 'objects-forbidden element))))
  7184. (t (throw 'objects-forbidden element)))
  7185. (goto-char (point-min))
  7186. (let ((restriction (org-element-restriction type))
  7187. (parent element)
  7188. last)
  7189. (catch 'exit
  7190. (while t
  7191. (let ((next (org-element--object-lex restriction)))
  7192. (when next (org-element-put-property next :parent parent))
  7193. ;; Process NEXT, if any, in order to know if we need to
  7194. ;; skip it, return it or move into it.
  7195. (if (or (not next) (> (org-element-property :begin next) pos))
  7196. (throw 'exit (or last parent))
  7197. (let ((end (org-element-property :end next))
  7198. (cbeg (org-element-property :contents-begin next))
  7199. (cend (org-element-property :contents-end next)))
  7200. (cond
  7201. ;; Skip objects ending before point. Also skip
  7202. ;; objects ending at point unless it is also the
  7203. ;; end of buffer, since we want to return the
  7204. ;; innermost object.
  7205. ((and (<= end pos) (/= (point-max) end))
  7206. (goto-char end)
  7207. ;; For convenience, when object ends at POS,
  7208. ;; without any space, store it in LAST, as we
  7209. ;; will return it if no object starts here.
  7210. (when (and (= end pos)
  7211. (not (memq (char-before) '(?\s ?\t))))
  7212. (setq last next)))
  7213. ;; If POS is within a container object, move into
  7214. ;; that object.
  7215. ((and cbeg cend
  7216. (>= pos cbeg)
  7217. (or (< pos cend)
  7218. ;; At contents' end, if there is no
  7219. ;; space before point, also move into
  7220. ;; object, for consistency with
  7221. ;; convenience feature above.
  7222. (and (= pos cend)
  7223. (or (= (point-max) pos)
  7224. (not (memq (char-before pos)
  7225. '(?\s ?\t)))))))
  7226. (goto-char cbeg)
  7227. (narrow-to-region (point) cend)
  7228. (setq parent next)
  7229. (setq restriction (org-element-restriction next)))
  7230. ;; Otherwise, return NEXT.
  7231. (t (throw 'exit next)))))))))))))
  7232. (defun org-element-lineage (datum &optional types with-self)
  7233. "List all ancestors of a given element or object.
  7234. DATUM is an object or element.
  7235. Return ancestors from the closest to the farthest. When optional
  7236. argument TYPES is a list of symbols, return the first element or
  7237. object in the lineage whose type belongs to that list instead.
  7238. When optional argument WITH-SELF is non-nil, lineage includes
  7239. DATUM itself as the first element, and TYPES, if provided, also
  7240. apply to it.
  7241. When DATUM is obtained through `org-element-context' or
  7242. `org-element-at-point', only ancestors from its section can be
  7243. found. There is no such limitation when DATUM belongs to a full
  7244. parse tree."
  7245. (let ((up (if with-self datum (org-element-property :parent datum)))
  7246. ancestors)
  7247. (while (and up (not (memq (org-element-type up) types)))
  7248. (unless types (push up ancestors))
  7249. (setq up (org-element-property :parent up)))
  7250. (if types up (nreverse ancestors))))
  7251. (defun org-element-nested-p (elem-A elem-B)
  7252. "Non-nil when elements ELEM-A and ELEM-B are nested."
  7253. (let ((beg-A (org-element-property :begin elem-A))
  7254. (beg-B (org-element-property :begin elem-B))
  7255. (end-A (org-element-property :end elem-A))
  7256. (end-B (org-element-property :end elem-B)))
  7257. (or (and (>= beg-A beg-B) (<= end-A end-B))
  7258. (and (>= beg-B beg-A) (<= end-B end-A)))))
  7259. (defun org-element-swap-A-B--overlays (elem-A elem-B)
  7260. "Swap elements ELEM-A and ELEM-B.
  7261. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7262. end of ELEM-A."
  7263. (goto-char (org-element-property :begin elem-A))
  7264. ;; There are two special cases when an element doesn't start at bol:
  7265. ;; the first paragraph in an item or in a footnote definition.
  7266. (let ((specialp (not (bolp))))
  7267. ;; Only a paragraph without any affiliated keyword can be moved at
  7268. ;; ELEM-A position in such a situation. Note that the case of
  7269. ;; a footnote definition is impossible: it cannot contain two
  7270. ;; paragraphs in a row because it cannot contain a blank line.
  7271. (when (and specialp
  7272. (or (not (eq (org-element-type elem-B) 'paragraph))
  7273. (/= (org-element-property :begin elem-B)
  7274. (org-element-property :contents-begin elem-B))))
  7275. (error "Cannot swap elements"))
  7276. ;; In a special situation, ELEM-A will have no indentation. We'll
  7277. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7278. (let* ((ind-B (when specialp
  7279. (goto-char (org-element-property :begin elem-B))
  7280. (current-indentation)))
  7281. (beg-A (org-element-property :begin elem-A))
  7282. (end-A (save-excursion
  7283. (goto-char (org-element-property :end elem-A))
  7284. (skip-chars-backward " \r\t\n")
  7285. (point-at-eol)))
  7286. (beg-B (org-element-property :begin elem-B))
  7287. (end-B (save-excursion
  7288. (goto-char (org-element-property :end elem-B))
  7289. (skip-chars-backward " \r\t\n")
  7290. (point-at-eol)))
  7291. ;; Store inner overlays responsible for visibility status.
  7292. ;; We also need to store their boundaries as they will be
  7293. ;; removed from buffer.
  7294. (overlays
  7295. (cons
  7296. (delq nil
  7297. (mapcar (lambda (o)
  7298. (and (>= (overlay-start o) beg-A)
  7299. (<= (overlay-end o) end-A)
  7300. (list o (overlay-start o) (overlay-end o))))
  7301. (overlays-in beg-A end-A)))
  7302. (delq nil
  7303. (mapcar (lambda (o)
  7304. (and (>= (overlay-start o) beg-B)
  7305. (<= (overlay-end o) end-B)
  7306. (list o (overlay-start o) (overlay-end o))))
  7307. (overlays-in beg-B end-B)))))
  7308. ;; Get contents.
  7309. (body-A (buffer-substring beg-A end-A))
  7310. (body-B (delete-and-extract-region beg-B end-B)))
  7311. (goto-char beg-B)
  7312. (when specialp
  7313. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7314. (indent-to-column ind-B))
  7315. (insert body-A)
  7316. ;; Restore ex ELEM-A overlays.
  7317. (let ((offset (- beg-B beg-A)))
  7318. (dolist (o (car overlays))
  7319. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  7320. (goto-char beg-A)
  7321. (delete-region beg-A end-A)
  7322. (insert body-B)
  7323. ;; Restore ex ELEM-B overlays.
  7324. (dolist (o (cdr overlays))
  7325. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  7326. (goto-char (org-element-property :end elem-B)))))
  7327. (defun org-element-swap-A-B--text-properties (elem-A elem-B)
  7328. "Swap elements ELEM-A and ELEM-B.
  7329. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7330. end of ELEM-A."
  7331. (goto-char (org-element-property :begin elem-A))
  7332. ;; There are two special cases when an element doesn't start at bol:
  7333. ;; the first paragraph in an item or in a footnote definition.
  7334. (let ((specialp (not (bolp))))
  7335. ;; Only a paragraph without any affiliated keyword can be moved at
  7336. ;; ELEM-A position in such a situation. Note that the case of
  7337. ;; a footnote definition is impossible: it cannot contain two
  7338. ;; paragraphs in a row because it cannot contain a blank line.
  7339. (when (and specialp
  7340. (or (not (eq (org-element-type elem-B) 'paragraph))
  7341. (/= (org-element-property :begin elem-B)
  7342. (org-element-property :contents-begin elem-B))))
  7343. (error "Cannot swap elements"))
  7344. ;; In a special situation, ELEM-A will have no indentation. We'll
  7345. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7346. (org-fold-core-ignore-modifications ;; Preserve folding state
  7347. (let* ((ind-B (when specialp
  7348. (goto-char (org-element-property :begin elem-B))
  7349. (current-indentation)))
  7350. (beg-A (org-element-property :begin elem-A))
  7351. (end-A (save-excursion
  7352. (goto-char (org-element-property :end elem-A))
  7353. (skip-chars-backward " \r\t\n")
  7354. (point-at-eol)))
  7355. (beg-B (org-element-property :begin elem-B))
  7356. (end-B (save-excursion
  7357. (goto-char (org-element-property :end elem-B))
  7358. (skip-chars-backward " \r\t\n")
  7359. (point-at-eol)))
  7360. ;; Get contents.
  7361. (body-A (buffer-substring beg-A end-A))
  7362. (body-B (delete-and-extract-region beg-B end-B)))
  7363. (goto-char beg-B)
  7364. (when specialp
  7365. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7366. (indent-to-column ind-B))
  7367. (insert body-A)
  7368. (goto-char beg-A)
  7369. (delete-region beg-A end-A)
  7370. (insert body-B)
  7371. (goto-char (org-element-property :end elem-B))))))
  7372. (defsubst org-element-swap-A-B (elem-A elem-B)
  7373. "Swap elements ELEM-A and ELEM-B.
  7374. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7375. end of ELEM-A."
  7376. (if (eq org-fold-core-style 'text-properties)
  7377. (org-element-swap-A-B--text-properties elem-A elem-B)
  7378. (org-element-swap-A-B--overlays elem-A elem-B)))
  7379. (provide 'org-element)
  7380. ;; Local variables:
  7381. ;; generated-autoload-file: "org-loaddefs.el"
  7382. ;; End:
  7383. ;;; org-element.el ends here