org-element.el 327 KB

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