org-element.el 327 KB

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