org-element.el 334 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
  19. ;; Org syntax.
  20. ;;
  21. ;; Lisp-wise, a syntax object can be represented as a list.
  22. ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
  23. ;; TYPE is a symbol describing the object.
  24. ;; PROPERTIES is the property list attached to it. See docstring of
  25. ;; appropriate parsing function to get an exhaustive list.
  26. ;; CONTENTS is a list of syntax objects or raw strings contained
  27. ;; in the current object, when applicable.
  28. ;;
  29. ;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
  30. ;;
  31. ;; The first part of this file defines constants for the Org syntax,
  32. ;; while the second one provide accessors and setters functions.
  33. ;;
  34. ;; The next part implements a parser and an interpreter for each
  35. ;; element and object type in Org syntax.
  36. ;;
  37. ;; The following part creates a fully recursive buffer parser. It
  38. ;; also provides a tool to map a function to elements or objects
  39. ;; matching some criteria in the parse tree. Functions of interest
  40. ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
  41. ;; extent, `org-element-parse-secondary-string'.
  42. ;;
  43. ;; The penultimate part is the cradle of an interpreter for the
  44. ;; obtained parse tree: `org-element-interpret-data'.
  45. ;;
  46. ;; The library ends by furnishing `org-element-at-point' function, and
  47. ;; a way to give information about document structure around point
  48. ;; with `org-element-context'. A cache mechanism is also provided for
  49. ;; these functions.
  50. ;;; Code:
  51. (require 'avl-tree)
  52. (require 'ring)
  53. (require 'cl-lib)
  54. (require 'ol)
  55. (require 'org)
  56. (require 'org-persist)
  57. (require 'org-compat)
  58. (require 'org-entities)
  59. (require 'org-footnote)
  60. (require 'org-list)
  61. (require 'org-macs)
  62. (require 'org-table)
  63. (require 'org-fold-core)
  64. (declare-function org-at-heading-p "org" (&optional _))
  65. (declare-function org-escape-code-in-string "org-src" (s))
  66. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  67. (declare-function org-macro-extract-arguments "org-macro" (s))
  68. (declare-function org-reduced-level "org" (l))
  69. (declare-function org-unescape-code-in-string "org-src" (s))
  70. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  71. (declare-function outline-next-heading "outline" ())
  72. (declare-function outline-previous-heading "outline" ())
  73. (defvar org-complex-heading-regexp)
  74. (defvar org-done-keywords)
  75. (defvar org-edit-src-content-indentation)
  76. (defvar org-match-substring-regexp)
  77. (defvar org-odd-levels-only)
  78. (defvar org-property-drawer-re)
  79. (defvar org-property-format)
  80. (defvar org-property-re)
  81. (defvar org-src-preserve-indentation)
  82. (defvar org-tags-column)
  83. (defvar org-time-stamp-formats)
  84. (defvar org-todo-regexp)
  85. (defvar org-ts-regexp-both)
  86. ;;; Definitions And Rules
  87. ;;
  88. ;; Define elements, greater elements and specify recursive objects,
  89. ;; along with the affiliated keywords recognized. Also set up
  90. ;; restrictions on recursive objects combinations.
  91. ;;
  92. ;; `org-element-update-syntax' builds proper syntax regexps according
  93. ;; to current setup.
  94. (defconst org-element-archive-tag "ARCHIVE"
  95. "Tag marking a substree as archived.")
  96. (defconst org-element-citation-key-re
  97. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  98. "Regexp matching a citation key.
  99. Key is located in match group 1.")
  100. (defconst org-element-citation-prefix-re
  101. (rx "[cite"
  102. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  103. ":"
  104. (zero-or-more (any "\t\n ")))
  105. "Regexp matching a citation prefix.
  106. Style, if any, is located in match group 1.")
  107. (defconst org-element-clock-line-re
  108. (rx line-start (0+ (or ?\t ?\s)) "CLOCK:")
  109. "Regexp matching a clock line.")
  110. (defconst org-element-comment-string "COMMENT"
  111. "String marker for commented headlines.")
  112. (defconst org-element-closed-keyword "CLOSED:"
  113. "Keyword used to close TODO entries.")
  114. (defconst org-element-deadline-keyword "DEADLINE:"
  115. "Keyword used to mark deadline entries.")
  116. (defconst org-element-scheduled-keyword "SCHEDULED:"
  117. "Keyword used to mark scheduled entries.")
  118. (defconst org-element-planning-keywords-re
  119. (regexp-opt (list org-element-closed-keyword
  120. org-element-deadline-keyword
  121. org-element-scheduled-keyword))
  122. "Regexp matching any planning line keyword.")
  123. (defconst org-element-planning-line-re
  124. (rx-to-string
  125. `(seq line-start (0+ (any ?\s ?\t))
  126. (group (regexp ,org-element-planning-keywords-re))))
  127. "Regexp matching a planning line.")
  128. (defconst org-element-drawer-re
  129. (rx line-start (0+ (any ?\s ?\t))
  130. ":" (group (1+ (any ?- ?_ word))) ":"
  131. (0+ (any ?\s ?\t)) line-end)
  132. "Regexp matching opening or closing line of a drawer.
  133. Drawer's name is located in match group 1.")
  134. (defconst org-element-dynamic-block-open-re
  135. (rx line-start (0+ (any ?\s ?\t))
  136. "#+BEGIN:" (0+ (any ?\s ?\t))
  137. (group (1+ word))
  138. (opt
  139. (1+ (any ?\s ?\t))
  140. (group (1+ nonl))))
  141. "Regexp matching the opening line of a dynamic block.
  142. Dynamic block's name is located in match group 1.
  143. Parameters are in match group 2.")
  144. (defconst org-element-headline-re
  145. (rx line-start (1+ "*") " ")
  146. "Regexp matching a headline.")
  147. (defvar org-element-paragraph-separate nil
  148. "Regexp to separate paragraphs in an Org buffer.
  149. In the case of lines starting with \"#\" and \":\", this regexp
  150. is not sufficient to know if point is at a paragraph ending. See
  151. `org-element-paragraph-parser' for more information.")
  152. (defvar org-element--object-regexp nil
  153. "Regexp possibly matching the beginning of an object.
  154. This regexp allows false positives. Dedicated parser (e.g.,
  155. `org-export-bold-parser') will take care of further filtering.
  156. Radio links are not matched by this regexp, as they are treated
  157. specially in `org-element--object-lex'.")
  158. (defun org-element--set-regexps ()
  159. "Build variable syntax regexps."
  160. (setq org-element-paragraph-separate
  161. (concat "^\\(?:"
  162. ;; Headlines, inlinetasks.
  163. "\\*+ " "\\|"
  164. ;; Footnote definitions.
  165. "\\[fn:[-_[:word:]]+\\]" "\\|"
  166. ;; Diary sexps.
  167. "%%(" "\\|"
  168. "[ \t]*\\(?:"
  169. ;; Empty lines.
  170. "$" "\\|"
  171. ;; Tables (any type).
  172. "|" "\\|"
  173. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  174. ;; Comments, keyword-like or block-like constructs.
  175. ;; Blocks and keywords with dual values need to be
  176. ;; double-checked.
  177. "#\\(?: \\|$\\|\\+\\(?:"
  178. "BEGIN_\\S-+" "\\|"
  179. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  180. "\\|"
  181. ;; Drawers (any type) and fixed-width areas. Drawers
  182. ;; need to be double-checked.
  183. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  184. ;; Horizontal rules.
  185. "-\\{5,\\}[ \t]*$" "\\|"
  186. ;; LaTeX environments.
  187. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  188. ;; Clock lines.
  189. "CLOCK:" "\\|"
  190. ;; Lists.
  191. (let ((term (pcase org-plain-list-ordered-item-terminator
  192. (?\) ")") (?. "\\.") (_ "[.)]")))
  193. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  194. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  195. "\\(?:[ \t]\\|$\\)"))
  196. "\\)\\)")
  197. org-element--object-regexp
  198. (mapconcat #'identity
  199. (let ((link-types (regexp-opt (org-link-types))))
  200. (list
  201. ;; Sub/superscript.
  202. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  203. ;; Bold, code, italic, strike-through, underline
  204. ;; and verbatim.
  205. (rx (or "*" "~" "=" "+" "_" "/") (not space))
  206. ;; Plain links.
  207. (concat "\\<" link-types ":")
  208. ;; Objects starting with "[": citations,
  209. ;; footnote reference, statistics cookie,
  210. ;; timestamp (inactive) and regular link.
  211. (format "\\[\\(?:%s\\)"
  212. (mapconcat
  213. #'identity
  214. (list "cite[:/]"
  215. "fn:"
  216. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  217. "\\[")
  218. "\\|"))
  219. ;; Objects starting with "@": export snippets.
  220. "@@"
  221. ;; Objects starting with "{": macro.
  222. "{{{"
  223. ;; Objects starting with "<" : timestamp
  224. ;; (active, diary), target, radio target and
  225. ;; angular links.
  226. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  227. ;; Objects starting with "$": latex fragment.
  228. "\\$"
  229. ;; Objects starting with "\": line break,
  230. ;; entity, latex fragment.
  231. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  232. ;; Objects starting with raw text: inline Babel
  233. ;; source block, inline Babel call.
  234. "\\(?:call\\|src\\)_"))
  235. "\\|")))
  236. (org-element--set-regexps)
  237. ;;;###autoload
  238. (defun org-element-update-syntax ()
  239. "Update parser internals."
  240. (interactive)
  241. (org-element--set-regexps)
  242. (org-element-cache-reset 'all))
  243. (defconst org-element-all-elements
  244. '(babel-call center-block clock comment comment-block diary-sexp drawer
  245. dynamic-block example-block export-block fixed-width
  246. footnote-definition headline horizontal-rule inlinetask item
  247. keyword latex-environment node-property paragraph plain-list
  248. planning property-drawer quote-block section
  249. special-block src-block table table-row verse-block)
  250. "Complete list of element types.")
  251. (defconst org-element-greater-elements
  252. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  253. item plain-list property-drawer quote-block section
  254. special-block table org-data)
  255. "List of recursive element types aka Greater Elements.")
  256. (defconst org-element-all-objects
  257. '(bold citation citation-reference code entity export-snippet
  258. footnote-reference inline-babel-call inline-src-block italic line-break
  259. latex-fragment link macro radio-target statistics-cookie strike-through
  260. subscript superscript table-cell target timestamp underline verbatim)
  261. "Complete list of object types.")
  262. (defconst org-element-recursive-objects
  263. '(bold citation footnote-reference italic link subscript radio-target
  264. strike-through superscript table-cell underline)
  265. "List of recursive object types.")
  266. (defconst org-element-object-containers
  267. (append org-element-recursive-objects '(paragraph table-row verse-block))
  268. "List of object or element types that can directly contain objects.")
  269. (defconst org-element-affiliated-keywords
  270. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  271. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  272. "List of affiliated keywords as strings.
  273. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  274. are affiliated keywords and need not to be in this list.")
  275. (defconst org-element-keyword-translation-alist
  276. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  277. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  278. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  279. "Alist of usual translations for keywords.
  280. The key is the old name and the value the new one. The property
  281. holding their value will be named after the translated name.")
  282. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  283. "List of affiliated keywords that can occur more than once in an element.
  284. Their value will be consed into a list of strings, which will be
  285. returned as the value of the property.
  286. This list is checked after translations have been applied. See
  287. `org-element-keyword-translation-alist'.
  288. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  289. allow multiple occurrences and need not to be in this list.")
  290. (defconst org-element-parsed-keywords '("CAPTION")
  291. "List of affiliated keywords whose value can be parsed.
  292. Their value will be stored as a secondary string: a list of
  293. strings and objects.
  294. This list is checked after translations have been applied. See
  295. `org-element-keyword-translation-alist'.")
  296. (defconst org-element--parsed-properties-alist
  297. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  298. org-element-parsed-keywords)
  299. "Alist of parsed keywords and associated properties.
  300. This is generated from `org-element-parsed-keywords', which
  301. see.")
  302. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  303. "List of affiliated keywords which can have a secondary value.
  304. In Org syntax, they can be written with optional square brackets
  305. before the colons. For example, RESULTS keyword can be
  306. associated to a hash value with the following:
  307. #+RESULTS[hash-string]: some-source
  308. This list is checked after translations have been applied. See
  309. `org-element-keyword-translation-alist'.")
  310. (defconst org-element--affiliated-re
  311. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  312. (concat
  313. ;; Dual affiliated keywords.
  314. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  315. (regexp-opt org-element-dual-keywords))
  316. "\\|"
  317. ;; Regular affiliated keywords.
  318. (format "\\(?1:%s\\)"
  319. (regexp-opt
  320. (cl-remove-if
  321. (lambda (k) (member k org-element-dual-keywords))
  322. org-element-affiliated-keywords)))
  323. "\\|"
  324. ;; Export attributes.
  325. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  326. "Regexp matching any affiliated keyword.
  327. Keyword name is put in match group 1. Moreover, if keyword
  328. belongs to `org-element-dual-keywords', put the dual value in
  329. match group 2.
  330. Don't modify it, set `org-element-affiliated-keywords' instead.")
  331. (defconst org-element-object-restrictions
  332. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  333. subscript superscript underline verbatim))
  334. (standard-set
  335. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  336. (standard-set-no-line-break (remq 'line-break standard-set)))
  337. `((bold ,@standard-set)
  338. (citation citation-reference)
  339. (citation-reference ,@minimal-set)
  340. (footnote-reference ,@standard-set)
  341. (headline ,@standard-set-no-line-break)
  342. (inlinetask ,@standard-set-no-line-break)
  343. (italic ,@standard-set)
  344. (item ,@standard-set-no-line-break)
  345. (keyword ,@(remq 'footnote-reference standard-set))
  346. ;; Ignore all links in a link description. Also ignore
  347. ;; radio-targets and line breaks.
  348. (link export-snippet inline-babel-call inline-src-block macro
  349. statistics-cookie ,@minimal-set)
  350. (paragraph ,@standard-set)
  351. ;; Remove any variable object from radio target as it would
  352. ;; prevent it from being properly recognized.
  353. (radio-target ,@minimal-set)
  354. (strike-through ,@standard-set)
  355. (subscript ,@standard-set)
  356. (superscript ,@standard-set)
  357. ;; Ignore inline babel call and inline source block as formulas
  358. ;; are possible. Also ignore line breaks and statistics
  359. ;; cookies.
  360. (table-cell citation export-snippet footnote-reference link macro
  361. radio-target target timestamp ,@minimal-set)
  362. (table-row table-cell)
  363. (underline ,@standard-set)
  364. (verse-block ,@standard-set)))
  365. "Alist of objects restrictions.
  366. key is an element or object type containing objects and value is
  367. a list of types that can be contained within an element or object
  368. of such type.
  369. This alist also applies to secondary string. For example, an
  370. `headline' type element doesn't directly contain objects, but
  371. still has an entry since one of its properties (`:title') does.")
  372. (defconst org-element-secondary-value-alist
  373. '((citation :prefix :suffix)
  374. (headline :title)
  375. (inlinetask :title)
  376. (item :tag)
  377. (citation-reference :prefix :suffix))
  378. "Alist between element types and locations of secondary values.")
  379. (defconst org-element--pair-round-table
  380. (let ((table (make-char-table 'syntax-table '(2))))
  381. (modify-syntax-entry ?\( "()" table)
  382. (modify-syntax-entry ?\) ")(" table)
  383. table)
  384. "Table used internally to pair only round brackets.")
  385. (defconst org-element--pair-square-table
  386. (let ((table (make-char-table 'syntax-table '(2))))
  387. (modify-syntax-entry ?\[ "(]" table)
  388. (modify-syntax-entry ?\] ")[" table)
  389. table)
  390. "Table used internally to pair only square brackets.")
  391. (defconst org-element--pair-curly-table
  392. (let ((table (make-char-table 'syntax-table '(2))))
  393. (modify-syntax-entry ?\{ "(}" table)
  394. (modify-syntax-entry ?\} "){" table)
  395. table)
  396. "Table used internally to pair only curly brackets.")
  397. (defun org-element--parse-paired-brackets (char)
  398. "Parse paired brackets at point.
  399. CHAR is the opening bracket to consider, as a character. Return
  400. contents between brackets, as a string, or nil. Also move point
  401. past the brackets."
  402. (when (eq char (char-after))
  403. (let ((syntax-table (pcase char
  404. (?\{ org-element--pair-curly-table)
  405. (?\[ org-element--pair-square-table)
  406. (?\( org-element--pair-round-table)
  407. (_ nil)))
  408. (pos (point)))
  409. (when syntax-table
  410. (with-syntax-table syntax-table
  411. (let ((end (ignore-errors (scan-lists pos 1 0))))
  412. (when end
  413. (goto-char end)
  414. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  415. ;;; Accessors and Setters
  416. ;;
  417. ;; Provide four accessors: `org-element-type', `org-element-property'
  418. ;; `org-element-contents' and `org-element-restriction'.
  419. ;;
  420. ;; Setter functions allow modification of elements by side effect.
  421. ;; There is `org-element-put-property', `org-element-set-contents'.
  422. ;; These low-level functions are useful to build a parse tree.
  423. ;;
  424. ;; `org-element-adopt-elements', `org-element-set-element',
  425. ;; `org-element-extract-element' and `org-element-insert-before' are
  426. ;; high-level functions useful to modify a parse tree.
  427. ;;
  428. ;; `org-element-secondary-p' is a predicate used to know if a given
  429. ;; object belongs to a secondary string. `org-element-class' tells if
  430. ;; some parsed data is an element or an object, handling pseudo
  431. ;; elements and objects. `org-element-copy' returns an element or
  432. ;; object, stripping its parent property in the process.
  433. (defsubst org-element-type (element)
  434. "Return type of ELEMENT.
  435. The function returns the type of the element or object provided.
  436. It can also return the following special value:
  437. `plain-text' for a string
  438. `org-data' for a complete document
  439. nil in any other case."
  440. (cond
  441. ((not (consp element)) (and (stringp element) 'plain-text))
  442. ((symbolp (car element)) (car element))))
  443. (defsubst org-element-property (property element)
  444. "Extract the value from the PROPERTY of an ELEMENT."
  445. (if (stringp element) (get-text-property 0 property element)
  446. (plist-get (nth 1 element) property)))
  447. (defsubst org-element-contents (element)
  448. "Extract contents from an ELEMENT."
  449. (cond ((not (consp element)) nil)
  450. ((symbolp (car element)) (nthcdr 2 element))
  451. (t element)))
  452. (defsubst org-element-restriction (element)
  453. "Return restriction associated to ELEMENT.
  454. ELEMENT can be an element, an object or a symbol representing an
  455. element or object type."
  456. (cdr (assq (if (symbolp element) element (org-element-type element))
  457. org-element-object-restrictions)))
  458. (defsubst org-element-put-property (element property value)
  459. "In ELEMENT set PROPERTY to VALUE.
  460. Return modified element."
  461. (if (stringp element) (org-add-props element nil property value)
  462. (setcar (cdr element) (plist-put (nth 1 element) property value))
  463. element))
  464. (defsubst org-element-set-contents (element &rest contents)
  465. "Set ELEMENT's contents to CONTENTS.
  466. Return ELEMENT."
  467. (cond ((null element) contents)
  468. ((not (symbolp (car element))) contents)
  469. ((cdr element) (setcdr (cdr element) contents) element)
  470. (t (nconc element contents))))
  471. (defun org-element-secondary-p (object)
  472. "Non-nil when OBJECT directly belongs to a secondary string.
  473. Return value is the property name, as a keyword, or nil."
  474. (let* ((parent (org-element-property :parent object))
  475. (properties (cdr (assq (org-element-type parent)
  476. org-element-secondary-value-alist))))
  477. (catch 'exit
  478. (dolist (p properties)
  479. (and (memq object (org-element-property p parent))
  480. (throw 'exit p))))))
  481. (defsubst org-element-class (datum &optional parent)
  482. "Return class for ELEMENT, as a symbol.
  483. Class is either `element' or `object'. Optional argument PARENT
  484. is the element or object containing DATUM. It defaults to the
  485. value of DATUM `:parent' property."
  486. (let ((type (org-element-type datum))
  487. (parent (or parent (org-element-property :parent datum))))
  488. (cond
  489. ;; Trivial cases.
  490. ((memq type org-element-all-objects) 'object)
  491. ((memq type org-element-all-elements) 'element)
  492. ;; Special cases.
  493. ((eq type 'org-data) 'element)
  494. ((eq type 'plain-text) 'object)
  495. ((not type) 'object)
  496. ;; Pseudo object or elements. Make a guess about its class.
  497. ;; Basically a pseudo object is contained within another object,
  498. ;; a secondary string or a container element.
  499. ((not parent) 'element)
  500. (t
  501. (let ((parent-type (org-element-type parent)))
  502. (cond ((not parent-type) 'object)
  503. ((memq parent-type org-element-object-containers) 'object)
  504. ((org-element-secondary-p datum) 'object)
  505. (t 'element)))))))
  506. (defsubst org-element-adopt-elements (parent &rest children)
  507. "Append elements to the contents of another element.
  508. PARENT is an element or object. CHILDREN can be elements,
  509. objects, or a strings.
  510. The function takes care of setting `:parent' property for CHILD.
  511. Return parent element."
  512. (declare (indent 1))
  513. (if (not children) parent
  514. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  515. ;; string: parent is the list itself.
  516. (dolist (child children)
  517. (org-element-put-property child :parent (or parent children)))
  518. ;; Add CHILDREN at the end of PARENT contents.
  519. (when parent
  520. (apply #'org-element-set-contents
  521. parent
  522. (nconc (org-element-contents parent) children)))
  523. ;; Return modified PARENT element.
  524. (or parent children)))
  525. (defun org-element-extract-element (element)
  526. "Extract ELEMENT from parse tree.
  527. Remove element from the parse tree by side-effect, and return it
  528. with its `:parent' property stripped out."
  529. (let ((parent (org-element-property :parent element))
  530. (secondary (org-element-secondary-p element)))
  531. (if secondary
  532. (org-element-put-property
  533. parent secondary
  534. (delq element (org-element-property secondary parent)))
  535. (apply #'org-element-set-contents
  536. parent
  537. (delq element (org-element-contents parent))))
  538. ;; Return ELEMENT with its :parent removed.
  539. (org-element-put-property element :parent nil)))
  540. (defun org-element-insert-before (element location)
  541. "Insert ELEMENT before LOCATION in parse tree.
  542. LOCATION is an element, object or string within the parse tree.
  543. Parse tree is modified by side effect."
  544. (let* ((parent (org-element-property :parent location))
  545. (property (org-element-secondary-p location))
  546. (siblings (if property (org-element-property property parent)
  547. (org-element-contents parent)))
  548. ;; Special case: LOCATION is the first element of an
  549. ;; independent secondary string (e.g. :title property). Add
  550. ;; ELEMENT in-place.
  551. (specialp (and (not property)
  552. (eq siblings parent)
  553. (eq (car parent) location))))
  554. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  555. (cond (specialp)
  556. ((or (null siblings) (eq (car siblings) location))
  557. (push element siblings))
  558. ((null location) (nconc siblings (list element)))
  559. (t
  560. (let ((index (cl-position location siblings)))
  561. (unless index (error "No location found to insert element"))
  562. (push element (cdr (nthcdr (1- index) siblings))))))
  563. ;; Store SIBLINGS at appropriate place in parse tree.
  564. (cond
  565. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  566. (property (org-element-put-property parent property siblings))
  567. (t (apply #'org-element-set-contents parent siblings)))
  568. ;; Set appropriate :parent property.
  569. (org-element-put-property element :parent parent)))
  570. (defconst org-element--cache-element-properties
  571. '(:cached
  572. :org-element--cache-sync-key)
  573. "List of element properties used internally by cache.")
  574. (defun org-element-set-element (old new)
  575. "Replace element or object OLD with element or object NEW.
  576. The function takes care of setting `:parent' property for NEW."
  577. ;; Ensure OLD and NEW have the same parent.
  578. (org-element-put-property new :parent (org-element-property :parent old))
  579. (dolist (p org-element--cache-element-properties)
  580. (when (org-element-property p old)
  581. (org-element-put-property new p (org-element-property p old))))
  582. (if (or (memq (org-element-type old) '(plain-text nil))
  583. (memq (org-element-type new) '(plain-text nil)))
  584. ;; We cannot replace OLD with NEW since one of them is not an
  585. ;; object or element. We take the long path.
  586. (progn (org-element-insert-before new old)
  587. (org-element-extract-element old))
  588. ;; Since OLD is going to be changed into NEW by side-effect, first
  589. ;; make sure that every element or object within NEW has OLD as
  590. ;; parent.
  591. (dolist (blob (org-element-contents new))
  592. (org-element-put-property blob :parent old))
  593. ;; Transfer contents.
  594. (apply #'org-element-set-contents old (org-element-contents new))
  595. ;; Overwrite OLD's properties with NEW's.
  596. (setcar (cdr old) (nth 1 new))
  597. ;; Transfer type.
  598. (setcar old (car new))))
  599. (defun org-element-create (type &optional props &rest children)
  600. "Create a new element of type TYPE.
  601. Optional argument PROPS, when non-nil, is a plist defining the
  602. properties of the element. CHILDREN can be elements, objects or
  603. strings."
  604. (apply #'org-element-adopt-elements (list type props) children))
  605. (defun org-element-copy (datum)
  606. "Return a copy of DATUM.
  607. DATUM is an element, object, string or nil. `:parent' property
  608. is cleared and contents are removed in the process."
  609. (when datum
  610. (let ((type (org-element-type datum)))
  611. (pcase type
  612. (`org-data (list 'org-data nil))
  613. (`plain-text (substring-no-properties datum))
  614. (`nil (copy-sequence datum))
  615. (_
  616. (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
  617. ;; We cannot simply return the copies property list. When
  618. ;; DATUM is i.e. a headline, it's property list (`:title'
  619. ;; in case of headline) can contain parsed objects. The
  620. ;; objects will contain `:parent' property set to the DATUM
  621. ;; iteself. When copied, these inner `:parent' propery
  622. ;; values will contain incorrect object decoupled from
  623. ;; DATUM. Changes to the DATUM copy will not longer be
  624. ;; reflected in the `:parent' properties. So, we need to
  625. ;; reassign inner `:parent' propreties to the DATUM copy
  626. ;; explicitly.
  627. (org-element-map element-copy (cons 'plain-text org-element-all-objects)
  628. (lambda (obj) (when (equal datum (org-element-property :parent obj))
  629. (org-element-put-property obj :parent element-copy))))
  630. element-copy))))))
  631. ;;; Greater elements
  632. ;;
  633. ;; For each greater element type, we define a parser and an
  634. ;; interpreter.
  635. ;;
  636. ;; A parser returns the element or object as the list described above.
  637. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  638. ;; every element containing a secondary string (see
  639. ;; `org-element-secondary-value-alist') will accept an optional
  640. ;; argument to toggle parsing of these secondary strings. Moreover,
  641. ;; `item' parser requires current list's structure as its first
  642. ;; element.
  643. ;;
  644. ;; An interpreter accepts two arguments: the list representation of
  645. ;; the element or object, and its contents. The latter may be nil,
  646. ;; depending on the element or object considered. It returns the
  647. ;; appropriate Org syntax, as a string.
  648. ;;
  649. ;; Parsing functions must follow the naming convention:
  650. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  651. ;; defined in `org-element-greater-elements'.
  652. ;;
  653. ;; Similarly, interpreting functions must follow the naming
  654. ;; convention: org-element-TYPE-interpreter.
  655. ;;
  656. ;; With the exception of `headline' and `item' types, greater elements
  657. ;; cannot contain other greater elements of their own type.
  658. ;;
  659. ;; Beside implementing a parser and an interpreter, adding a new
  660. ;; greater element requires tweaking `org-element--current-element'.
  661. ;; Moreover, the newly defined type must be added to both
  662. ;; `org-element-all-elements' and `org-element-greater-elements'.
  663. ;;;; Center Block
  664. (defun org-element-center-block-parser (limit affiliated)
  665. "Parse a center block.
  666. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  667. the buffer position at the beginning of the first affiliated
  668. keyword and CDR is a plist of affiliated keywords along with
  669. their value.
  670. Return a list whose CAR is `center-block' and CDR is a plist
  671. containing `:begin', `:end', `:contents-begin', `:contents-end',
  672. `:post-blank' and `:post-affiliated' keywords.
  673. Assume point is at the beginning of the block."
  674. (let ((case-fold-search t))
  675. (if (not (save-excursion
  676. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  677. ;; Incomplete block: parse it as a paragraph.
  678. (org-element-paragraph-parser limit affiliated)
  679. (let ((block-end-line (match-beginning 0)))
  680. (let* ((begin (car affiliated))
  681. (post-affiliated (point))
  682. ;; Empty blocks have no contents.
  683. (contents-begin (progn (forward-line)
  684. (and (< (point) block-end-line)
  685. (point))))
  686. (contents-end (and contents-begin block-end-line))
  687. (pos-before-blank (progn (goto-char block-end-line)
  688. (forward-line)
  689. (point)))
  690. (end (save-excursion
  691. (skip-chars-forward " \r\t\n" limit)
  692. (if (eobp) (point) (line-beginning-position)))))
  693. (list 'center-block
  694. (nconc
  695. (list :begin begin
  696. :end end
  697. :contents-begin contents-begin
  698. :contents-end contents-end
  699. :post-blank (count-lines pos-before-blank end)
  700. :post-affiliated post-affiliated)
  701. (cdr affiliated))))))))
  702. (defun org-element-center-block-interpreter (_ contents)
  703. "Interpret a center-block element as Org syntax.
  704. CONTENTS is the contents of the element."
  705. (format "#+begin_center\n%s#+end_center" contents))
  706. ;;;; Drawer
  707. (defun org-element-drawer-parser (limit affiliated)
  708. "Parse a drawer.
  709. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  710. the buffer position at the beginning of the first affiliated
  711. keyword and CDR is a plist of affiliated keywords along with
  712. their value.
  713. Return a list whose CAR is `drawer' and CDR is a plist containing
  714. `:drawer-name', `:begin', `:end', `:contents-begin',
  715. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  716. Assume point is at beginning of drawer."
  717. (let ((case-fold-search t))
  718. (if (not (save-excursion
  719. (goto-char (min limit (line-end-position)))
  720. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  721. ;; Incomplete drawer: parse it as a paragraph.
  722. (org-element-paragraph-parser limit affiliated)
  723. (save-excursion
  724. (let* ((drawer-end-line (match-beginning 0))
  725. (name
  726. (progn
  727. (looking-at org-element-drawer-re)
  728. (match-string-no-properties 1)))
  729. (begin (car affiliated))
  730. (post-affiliated (point))
  731. ;; Empty drawers have no contents.
  732. (contents-begin (progn (forward-line)
  733. (and (< (point) drawer-end-line)
  734. (point))))
  735. (contents-end (and contents-begin drawer-end-line))
  736. (pos-before-blank (progn (goto-char drawer-end-line)
  737. (forward-line)
  738. (point)))
  739. (end (progn (skip-chars-forward " \r\t\n" limit)
  740. (if (eobp) (point) (line-beginning-position)))))
  741. (list 'drawer
  742. (nconc
  743. (list :begin begin
  744. :end end
  745. :drawer-name name
  746. :contents-begin contents-begin
  747. :contents-end contents-end
  748. :post-blank (count-lines pos-before-blank end)
  749. :post-affiliated post-affiliated)
  750. (cdr affiliated))))))))
  751. (defun org-element-drawer-interpreter (drawer contents)
  752. "Interpret DRAWER element as Org syntax.
  753. CONTENTS is the contents of the element."
  754. (format ":%s:\n%s:END:"
  755. (org-element-property :drawer-name drawer)
  756. contents))
  757. ;;;; Dynamic Block
  758. (defun org-element-dynamic-block-parser (limit affiliated)
  759. "Parse a dynamic block.
  760. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  761. the buffer position at the beginning of the first affiliated
  762. keyword and CDR is a plist of affiliated keywords along with
  763. their value.
  764. Return a list whose CAR is `dynamic-block' and CDR is a plist
  765. containing `:block-name', `:begin', `:end', `:contents-begin',
  766. `:contents-end', `:arguments', `:post-blank' and
  767. `:post-affiliated' keywords.
  768. Assume point is at beginning of dynamic block."
  769. (let ((case-fold-search t))
  770. (if (not (save-excursion
  771. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  772. ;; Incomplete block: parse it as a paragraph.
  773. (org-element-paragraph-parser limit affiliated)
  774. (let ((block-end-line (match-beginning 0)))
  775. (save-excursion
  776. (let* ((name (progn
  777. (looking-at org-element-dynamic-block-open-re)
  778. (match-string-no-properties 1)))
  779. (arguments (match-string-no-properties 2))
  780. (begin (car affiliated))
  781. (post-affiliated (point))
  782. ;; Empty blocks have no contents.
  783. (contents-begin (progn (forward-line)
  784. (and (< (point) block-end-line)
  785. (point))))
  786. (contents-end (and contents-begin block-end-line))
  787. (pos-before-blank (progn (goto-char block-end-line)
  788. (forward-line)
  789. (point)))
  790. (end (progn (skip-chars-forward " \r\t\n" limit)
  791. (if (eobp) (point) (line-beginning-position)))))
  792. (list 'dynamic-block
  793. (nconc
  794. (list :begin begin
  795. :end end
  796. :block-name name
  797. :arguments arguments
  798. :contents-begin contents-begin
  799. :contents-end contents-end
  800. :post-blank (count-lines pos-before-blank end)
  801. :post-affiliated post-affiliated)
  802. (cdr affiliated)))))))))
  803. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  804. "Interpret DYNAMIC-BLOCK element as Org syntax.
  805. CONTENTS is the contents of the element."
  806. (format "#+begin: %s%s\n%s#+end:"
  807. (org-element-property :block-name dynamic-block)
  808. (let ((args (org-element-property :arguments dynamic-block)))
  809. (if args (concat " " args) ""))
  810. contents))
  811. ;;;; Footnote Definition
  812. (defconst org-element--footnote-separator
  813. (concat org-element-headline-re "\\|"
  814. org-footnote-definition-re "\\|"
  815. "^\\([ \t]*\n\\)\\{2,\\}")
  816. "Regexp used as a footnote definition separator.")
  817. (defun org-element-footnote-definition-parser (limit affiliated)
  818. "Parse a footnote definition.
  819. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  820. the buffer position at the beginning of the first affiliated
  821. keyword and CDR is a plist of affiliated keywords along with
  822. their value.
  823. Return a list whose CAR is `footnote-definition' and CDR is
  824. a plist containing `:label', `:begin' `:end', `:contents-begin',
  825. `:contents-end', `:pre-blank',`:post-blank' and
  826. `:post-affiliated' keywords.
  827. Assume point is at the beginning of the footnote definition."
  828. (save-excursion
  829. (let* ((label (progn (looking-at org-footnote-definition-re)
  830. (match-string-no-properties 1)))
  831. (begin (car affiliated))
  832. (post-affiliated (point))
  833. (end
  834. (save-excursion
  835. (end-of-line)
  836. (cond
  837. ((not
  838. (re-search-forward org-element--footnote-separator limit t))
  839. limit)
  840. ((eq ?\[ (char-after (match-beginning 0)))
  841. ;; At a new footnote definition, make sure we end
  842. ;; before any affiliated keyword above.
  843. (forward-line -1)
  844. (while (and (> (point) post-affiliated)
  845. (looking-at-p org-element--affiliated-re))
  846. (forward-line -1))
  847. (line-beginning-position 2))
  848. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  849. (t (skip-chars-forward " \r\t\n" limit)
  850. (if (= limit (point)) limit (line-beginning-position))))))
  851. (pre-blank 0)
  852. (contents-begin
  853. (progn (search-forward "]")
  854. (skip-chars-forward " \r\t\n" end)
  855. (cond ((= (point) end) nil)
  856. ((= (line-beginning-position) post-affiliated) (point))
  857. (t
  858. (setq pre-blank
  859. (count-lines (line-beginning-position) begin))
  860. (line-beginning-position)))))
  861. (contents-end
  862. (progn (goto-char end)
  863. (skip-chars-backward " \r\t\n")
  864. (line-beginning-position 2))))
  865. (list 'footnote-definition
  866. (nconc
  867. (list :label label
  868. :begin begin
  869. :end end
  870. :contents-begin contents-begin
  871. :contents-end (and contents-begin contents-end)
  872. :pre-blank pre-blank
  873. :post-blank (count-lines contents-end end)
  874. :post-affiliated post-affiliated)
  875. (cdr affiliated))))))
  876. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  877. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  878. CONTENTS is the contents of the footnote-definition."
  879. (let ((pre-blank
  880. (min (or (org-element-property :pre-blank footnote-definition)
  881. ;; 0 is specific to paragraphs at the beginning of
  882. ;; the footnote definition, so we use 1 as
  883. ;; a fall-back value, which is more universal.
  884. 1)
  885. ;; Footnote ends after more than two consecutive empty
  886. ;; lines: limit ourselves to 2 newline characters.
  887. 2)))
  888. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  889. (if (= pre-blank 0) (concat " " (org-trim contents))
  890. (concat (make-string pre-blank ?\n) contents)))))
  891. ;;;; Headline
  892. (defun org-element--get-node-properties (&optional at-point-p?)
  893. "Return node properties for headline or property drawer at point.
  894. Upcase property names. It avoids confusion between properties
  895. obtained through property drawer and default properties from the
  896. parser (e.g. `:end' and :END:). Return value is a plist.
  897. When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
  898. parse properties for property drawer at point."
  899. (save-excursion
  900. (unless at-point-p?
  901. (forward-line)
  902. (when (looking-at-p org-element-planning-line-re) (forward-line)))
  903. (when (looking-at org-property-drawer-re)
  904. (forward-line)
  905. (let ((end (match-end 0)) properties)
  906. (while (< (line-end-position) end)
  907. (looking-at org-property-re)
  908. (let* ((property-name (concat ":" (upcase (match-string 2))))
  909. (property-name-symbol (intern property-name))
  910. (property-value (match-string-no-properties 3)))
  911. (cond
  912. ((and (plist-member properties property-name-symbol)
  913. (string-match-p "+$" property-name))
  914. (let ((val (plist-get properties property-name-symbol)))
  915. (if (listp val)
  916. (setq properties
  917. (plist-put properties
  918. property-name-symbol
  919. (append (plist-get properties property-name-symbol)
  920. (list property-value))))
  921. (plist-put properties property-name-symbol (list val property-value)))))
  922. (t (setq properties (plist-put properties property-name-symbol property-value)))))
  923. (forward-line))
  924. properties))))
  925. (defun org-element--get-time-properties ()
  926. "Return time properties associated to headline at point.
  927. Return value is a plist."
  928. (save-excursion
  929. (when (progn (forward-line) (looking-at org-element-planning-line-re))
  930. (let ((end (line-end-position))
  931. plist)
  932. (while (re-search-forward org-element-planning-keywords-re end t)
  933. (skip-chars-forward " \t")
  934. (let ((keyword (match-string 0))
  935. (time (org-element-timestamp-parser)))
  936. (cond ((equal keyword org-element-scheduled-keyword)
  937. (setq plist (plist-put plist :scheduled time)))
  938. ((equal keyword org-element-deadline-keyword)
  939. (setq plist (plist-put plist :deadline time)))
  940. (t (setq plist (plist-put plist :closed time))))))
  941. plist))))
  942. (defun org-element-headline-parser (&optional _ raw-secondary-p)
  943. "Parse a headline.
  944. Return a list whose CAR is `headline' and CDR is a plist
  945. containing `:raw-value', `:title', `:begin', `:end',
  946. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  947. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  948. `:deadline', `:closed', `:archivedp', `:commentedp'
  949. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  950. keywords.
  951. The plist also contains any property set in the property drawer,
  952. with its name in upper cases and colons added at the
  953. beginning (e.g., `:CUSTOM_ID').
  954. When RAW-SECONDARY-P is non-nil, headline's title will not be
  955. parsed as a secondary string, but as a plain string instead.
  956. Assume point is at beginning of the headline."
  957. (save-excursion
  958. (let* ((begin (point))
  959. (true-level (prog1 (skip-chars-forward "*")
  960. (skip-chars-forward " \t")))
  961. (level (org-reduced-level true-level))
  962. (todo (and org-todo-regexp
  963. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  964. (progn (goto-char (match-end 0))
  965. (skip-chars-forward " \t")
  966. (match-string 1))))
  967. (todo-type
  968. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  969. (priority (and (looking-at "\\[#.\\][ \t]*")
  970. (progn (goto-char (match-end 0))
  971. (aref (match-string 0) 2))))
  972. (commentedp
  973. (and (let ((case-fold-search nil))
  974. (looking-at org-element-comment-string))
  975. (goto-char (match-end 0))))
  976. (title-start (prog1 (point)
  977. (unless (or todo priority commentedp)
  978. ;; Headline like "* :tag:"
  979. (skip-chars-backward " \t"))))
  980. (tags (when (re-search-forward
  981. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  982. (line-end-position)
  983. 'move)
  984. (goto-char (match-beginning 0))
  985. (org-split-string (match-string 1) ":")))
  986. (title-end (point))
  987. (raw-value (org-trim
  988. (buffer-substring-no-properties title-start title-end)))
  989. (archivedp (member org-element-archive-tag tags))
  990. (footnote-section-p (and org-footnote-section
  991. (string= org-footnote-section raw-value)))
  992. (standard-props (org-element--get-node-properties))
  993. (time-props (org-element--get-time-properties))
  994. (end
  995. (save-excursion
  996. (let ((re (rx-to-string
  997. `(seq line-start (** 1 ,true-level "*") " "))))
  998. (if (re-search-forward re nil t)
  999. (line-beginning-position)
  1000. (point-max)))))
  1001. (contents-begin (save-excursion
  1002. (forward-line)
  1003. (skip-chars-forward " \r\t\n" end)
  1004. (and (/= (point) end) (line-beginning-position))))
  1005. (contents-end (and contents-begin
  1006. (progn (goto-char end)
  1007. (skip-chars-backward " \r\t\n")
  1008. (line-beginning-position 2))))
  1009. (robust-begin (and contents-begin
  1010. (progn (goto-char contents-begin)
  1011. (when (looking-at-p org-element-planning-line-re)
  1012. (forward-line))
  1013. (when (looking-at org-property-drawer-re)
  1014. (goto-char (match-end 0)))
  1015. ;; If there is :pre-blank, we
  1016. ;; need to be careful about
  1017. ;; robust beginning.
  1018. (max (if (< (+ 2 contents-begin) contents-end)
  1019. (+ 2 contents-begin)
  1020. 0)
  1021. (point)))))
  1022. (robust-end (and robust-begin
  1023. (when (> (- contents-end 2) robust-begin)
  1024. (- contents-end 2)))))
  1025. (unless robust-end (setq robust-begin nil))
  1026. (let ((headline
  1027. (list 'headline
  1028. (nconc
  1029. (list :raw-value raw-value
  1030. :begin begin
  1031. :end end
  1032. :pre-blank
  1033. (if (not contents-begin) 0
  1034. (1- (count-lines begin contents-begin)))
  1035. :contents-begin contents-begin
  1036. :contents-end contents-end
  1037. :robust-begin robust-begin
  1038. :robust-end robust-end
  1039. :level level
  1040. :priority priority
  1041. :tags tags
  1042. :todo-keyword todo
  1043. :todo-type todo-type
  1044. :post-blank
  1045. (if contents-end
  1046. (count-lines contents-end end)
  1047. (1- (count-lines begin end)))
  1048. :footnote-section-p footnote-section-p
  1049. :archivedp archivedp
  1050. :commentedp commentedp
  1051. :post-affiliated begin)
  1052. time-props
  1053. standard-props))))
  1054. (org-element-put-property
  1055. headline :title
  1056. (if raw-secondary-p raw-value
  1057. (org-element--parse-objects
  1058. (progn (goto-char title-start)
  1059. (skip-chars-forward " \t")
  1060. (point))
  1061. (progn (goto-char title-end)
  1062. (skip-chars-backward " \t")
  1063. (point))
  1064. nil
  1065. (org-element-restriction 'headline)
  1066. headline)))))))
  1067. (defun org-element-headline-interpreter (headline contents)
  1068. "Interpret HEADLINE element as Org syntax.
  1069. CONTENTS is the contents of the element."
  1070. (let* ((level (org-element-property :level headline))
  1071. (todo (org-element-property :todo-keyword headline))
  1072. (priority (org-element-property :priority headline))
  1073. (title (org-element-interpret-data
  1074. (org-element-property :title headline)))
  1075. (tags (let ((tag-list (org-element-property :tags headline)))
  1076. (and tag-list
  1077. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  1078. (commentedp (org-element-property :commentedp headline))
  1079. (pre-blank (or (org-element-property :pre-blank headline) 0))
  1080. (heading
  1081. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  1082. ?*)
  1083. (and todo (concat " " todo))
  1084. (and commentedp (concat " " org-element-comment-string))
  1085. (and priority (format " [#%c]" priority))
  1086. " "
  1087. (if (and org-footnote-section
  1088. (org-element-property :footnote-section-p headline))
  1089. org-footnote-section
  1090. title))))
  1091. (concat
  1092. heading
  1093. ;; Align tags.
  1094. (when tags
  1095. (cond
  1096. ((zerop org-tags-column) (format " %s" tags))
  1097. ((< org-tags-column 0)
  1098. (concat
  1099. (make-string
  1100. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1101. ?\s)
  1102. tags))
  1103. (t
  1104. (concat
  1105. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1106. tags))))
  1107. (make-string (1+ pre-blank) ?\n)
  1108. contents)))
  1109. ;;;; org-data
  1110. (defun org-element--get-global-node-properties ()
  1111. "Return node properties associated with the whole Org buffer.
  1112. Upcase property names. It avoids confusion between properties
  1113. obtained through property drawer and default properties from the
  1114. parser (e.g. `:end' and :END:). Return value is a plist."
  1115. (org-with-wide-buffer
  1116. (goto-char (point-min))
  1117. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1118. (org-element--get-node-properties t)))
  1119. (defvar org-element-org-data-parser--recurse nil)
  1120. (defun org-element-org-data-parser (&optional _)
  1121. "Parse org-data."
  1122. (org-with-wide-buffer
  1123. (let* ((begin 1)
  1124. (contents-begin (progn
  1125. (goto-char 1)
  1126. (org-skip-whitespace)
  1127. (beginning-of-line)
  1128. (point)))
  1129. (end (point-max))
  1130. (pos-before-blank (progn (goto-char (point-max))
  1131. (skip-chars-backward " \r\t\n")
  1132. (line-beginning-position 2)))
  1133. (robust-end (when (> (- pos-before-blank 2) contents-begin)
  1134. (- pos-before-blank 2)))
  1135. (robust-begin (when (and robust-end
  1136. (< (+ 2 contents-begin) pos-before-blank))
  1137. (or
  1138. (org-with-wide-buffer
  1139. (goto-char (point-min))
  1140. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1141. (when (looking-at org-property-drawer-re)
  1142. (goto-char (match-end 0))
  1143. (skip-chars-backward " \t")
  1144. (min robust-end (point))))
  1145. (+ 2 contents-begin))))
  1146. (category (cond ((null org-category)
  1147. (when (with-current-buffer
  1148. (or (buffer-base-buffer)
  1149. (current-buffer))
  1150. buffer-file-name)
  1151. (file-name-sans-extension
  1152. (file-name-nondirectory
  1153. (with-current-buffer
  1154. (or (buffer-base-buffer)
  1155. (current-buffer))
  1156. buffer-file-name)))))
  1157. ((symbolp org-category) (symbol-name org-category))
  1158. (t org-category)))
  1159. (category (catch 'buffer-category
  1160. (unless org-element-org-data-parser--recurse
  1161. (org-with-point-at end
  1162. ;; Avoid recusrive calls from
  1163. ;; `org-element-at-point-no-context'.
  1164. (let ((org-element-org-data-parser--recurse t))
  1165. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  1166. (org-element-with-disabled-cache
  1167. (let ((element (org-element-at-point-no-context)))
  1168. (when (eq (org-element-type element) 'keyword)
  1169. (throw 'buffer-category
  1170. (org-element-property :value element)))))))))
  1171. category))
  1172. (properties (org-element--get-global-node-properties)))
  1173. (unless (plist-get properties :CATEGORY)
  1174. (setq properties (plist-put properties :CATEGORY category)))
  1175. (list 'org-data
  1176. (nconc
  1177. (list :begin begin
  1178. :contents-begin contents-begin
  1179. :contents-end pos-before-blank
  1180. :end end
  1181. :robust-begin robust-begin
  1182. :robust-end robust-end
  1183. :post-blank (count-lines pos-before-blank end)
  1184. :post-affiliated begin
  1185. :path (buffer-file-name)
  1186. :mode 'org-data)
  1187. properties)))))
  1188. (defun org-element-org-data-interpreter (_ contents)
  1189. "Interpret ORG-DATA element as Org syntax.
  1190. CONTENTS is the contents of the element."
  1191. contents)
  1192. ;;;; Inlinetask
  1193. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1194. "Parse an inline task.
  1195. Return a list whose CAR is `inlinetask' and CDR is a plist
  1196. containing `:title', `:begin', `:end', `:pre-blank',
  1197. `:contents-begin' and `:contents-end', `:level', `:priority',
  1198. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1199. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1200. `:post-affiliated' keywords.
  1201. The plist also contains any property set in the property drawer,
  1202. with its name in upper cases and colons added at the
  1203. beginning (e.g., `:CUSTOM_ID').
  1204. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1205. title will not be parsed as a secondary string, but as a plain
  1206. string instead.
  1207. Assume point is at beginning of the inline task."
  1208. (save-excursion
  1209. (let* ((begin (point))
  1210. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1211. (skip-chars-forward " \t")))
  1212. (todo (and org-todo-regexp
  1213. (let (case-fold-search) (looking-at org-todo-regexp))
  1214. (progn (goto-char (match-end 0))
  1215. (skip-chars-forward " \t")
  1216. (match-string 0))))
  1217. (todo-type (and todo
  1218. (if (member todo org-done-keywords) 'done 'todo)))
  1219. (priority (and (looking-at "\\[#.\\][ \t]*")
  1220. (progn (goto-char (match-end 0))
  1221. (aref (match-string 0) 2))))
  1222. (title-start (point))
  1223. (tags (when (re-search-forward
  1224. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1225. (line-end-position)
  1226. 'move)
  1227. (goto-char (match-beginning 0))
  1228. (org-split-string (match-string 1) ":")))
  1229. (title-end (point))
  1230. (raw-value (org-trim
  1231. (buffer-substring-no-properties title-start title-end)))
  1232. (task-end (save-excursion
  1233. (end-of-line)
  1234. (and (re-search-forward org-element-headline-re limit t)
  1235. (looking-at-p "[ \t]*END[ \t]*$")
  1236. (line-beginning-position))))
  1237. (standard-props (and task-end (org-element--get-node-properties)))
  1238. (time-props (and task-end (org-element--get-time-properties)))
  1239. (contents-begin (and task-end
  1240. (< (point) task-end)
  1241. (progn
  1242. (forward-line)
  1243. (skip-chars-forward " \t\n")
  1244. (line-beginning-position))))
  1245. (contents-end (and contents-begin task-end))
  1246. (end (progn (when task-end (goto-char task-end))
  1247. (forward-line)
  1248. (skip-chars-forward " \r\t\n" limit)
  1249. (if (eobp) (point) (line-beginning-position))))
  1250. (inlinetask
  1251. (list 'inlinetask
  1252. (nconc
  1253. (list :raw-value raw-value
  1254. :begin begin
  1255. :end end
  1256. :pre-blank
  1257. (if (not contents-begin) 0
  1258. (1- (count-lines begin contents-begin)))
  1259. :contents-begin contents-begin
  1260. :contents-end contents-end
  1261. :level level
  1262. :priority priority
  1263. :tags tags
  1264. :todo-keyword todo
  1265. :todo-type todo-type
  1266. :post-blank (1- (count-lines (or task-end begin) end))
  1267. :post-affiliated begin)
  1268. time-props
  1269. standard-props))))
  1270. (org-element-put-property
  1271. inlinetask :title
  1272. (if raw-secondary-p raw-value
  1273. (org-element--parse-objects
  1274. (progn (goto-char title-start)
  1275. (skip-chars-forward " \t")
  1276. (point))
  1277. (progn (goto-char title-end)
  1278. (skip-chars-backward " \t")
  1279. (point))
  1280. nil
  1281. (org-element-restriction 'inlinetask)
  1282. inlinetask))))))
  1283. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1284. "Interpret INLINETASK element as Org syntax.
  1285. CONTENTS is the contents of inlinetask."
  1286. (let* ((level (org-element-property :level inlinetask))
  1287. (todo (org-element-property :todo-keyword inlinetask))
  1288. (priority (org-element-property :priority inlinetask))
  1289. (title (org-element-interpret-data
  1290. (org-element-property :title inlinetask)))
  1291. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1292. (and tag-list
  1293. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1294. (task (concat (make-string level ?*)
  1295. (and todo (concat " " todo))
  1296. (and priority (format " [#%c]" priority))
  1297. (and title (concat " " title)))))
  1298. (concat task
  1299. ;; Align tags.
  1300. (when tags
  1301. (cond
  1302. ((zerop org-tags-column) (format " %s" tags))
  1303. ((< org-tags-column 0)
  1304. (concat
  1305. (make-string
  1306. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1307. ?\s)
  1308. tags))
  1309. (t
  1310. (concat
  1311. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1312. tags))))
  1313. ;; Prefer degenerate inlinetasks when there are no
  1314. ;; contents.
  1315. (when contents
  1316. (concat "\n"
  1317. contents
  1318. (make-string level ?*) " end")))))
  1319. ;;;; Item
  1320. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1321. "Parse an item.
  1322. STRUCT is the structure of the plain list.
  1323. Return a list whose CAR is `item' and CDR is a plist containing
  1324. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1325. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1326. `:post-blank' and `:post-affiliated' keywords.
  1327. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1328. any, will not be parsed as a secondary string, but as a plain
  1329. string instead.
  1330. Assume point is at the beginning of the item."
  1331. (save-excursion
  1332. (beginning-of-line)
  1333. (looking-at org-list-full-item-re)
  1334. (let* ((begin (point))
  1335. (bullet (match-string-no-properties 1))
  1336. (checkbox (let ((box (match-string 3)))
  1337. (cond ((equal "[ ]" box) 'off)
  1338. ((equal "[X]" box) 'on)
  1339. ((equal "[-]" box) 'trans))))
  1340. (counter (let ((c (match-string 2)))
  1341. (save-match-data
  1342. (cond
  1343. ((not c) nil)
  1344. ((string-match "[A-Za-z]" c)
  1345. (- (string-to-char (upcase (match-string 0 c)))
  1346. 64))
  1347. ((string-match "[0-9]+" c)
  1348. (string-to-number (match-string 0 c)))))))
  1349. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1350. (if (bolp) (point) (line-beginning-position 2))))
  1351. (pre-blank 0)
  1352. (contents-begin
  1353. (progn
  1354. (goto-char
  1355. ;; Ignore tags in un-ordered lists: they are just
  1356. ;; a part of item's body.
  1357. (if (and (match-beginning 4)
  1358. (save-match-data (string-match "[.)]" bullet)))
  1359. (match-beginning 4)
  1360. (match-end 0)))
  1361. (skip-chars-forward " \r\t\n" end)
  1362. (cond ((= (point) end) nil)
  1363. ;; If first line isn't empty, contents really
  1364. ;; start at the text after item's meta-data.
  1365. ((= (line-beginning-position) begin) (point))
  1366. (t
  1367. (setq pre-blank
  1368. (count-lines (line-beginning-position) begin))
  1369. (line-beginning-position)))))
  1370. (contents-end (and contents-begin
  1371. (progn (goto-char end)
  1372. (skip-chars-backward " \r\t\n")
  1373. (line-beginning-position 2))))
  1374. (item
  1375. (list 'item
  1376. (list :bullet bullet
  1377. :begin begin
  1378. :end end
  1379. :contents-begin contents-begin
  1380. :contents-end contents-end
  1381. :checkbox checkbox
  1382. :counter counter
  1383. :structure struct
  1384. :pre-blank pre-blank
  1385. :post-blank (count-lines (or contents-end begin) end)
  1386. :post-affiliated begin))))
  1387. (org-element-put-property
  1388. item :tag
  1389. (let ((raw (org-list-get-tag begin struct)))
  1390. (when raw
  1391. (if raw-secondary-p raw
  1392. (org-element--parse-objects
  1393. (match-beginning 4) (match-end 4) nil
  1394. (org-element-restriction 'item)
  1395. item))))))))
  1396. (defun org-element-item-interpreter (item contents)
  1397. "Interpret ITEM element as Org syntax.
  1398. CONTENTS is the contents of the element."
  1399. (let ((tag (pcase (org-element-property :tag item)
  1400. (`nil nil)
  1401. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1402. (bullet
  1403. (org-list-bullet-string
  1404. (cond
  1405. ((not (string-match-p "[0-9a-zA-Z]"
  1406. (org-element-property :bullet item))) "- ")
  1407. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1408. (t "1.")))))
  1409. (concat
  1410. bullet
  1411. (pcase (org-element-property :counter item)
  1412. (`nil nil)
  1413. (counter (format "[@%d] " counter)))
  1414. (pcase (org-element-property :checkbox item)
  1415. (`on "[X] ")
  1416. (`off "[ ] ")
  1417. (`trans "[-] ")
  1418. (_ nil))
  1419. tag
  1420. (when contents
  1421. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1422. (pre-blank
  1423. (min (or (org-element-property :pre-blank item)
  1424. ;; 0 is specific to paragraphs at the
  1425. ;; beginning of the item, so we use 1 as
  1426. ;; a fall-back value, which is more universal.
  1427. 1)
  1428. ;; Lists ends after more than two consecutive
  1429. ;; empty lines: limit ourselves to 2 newline
  1430. ;; characters.
  1431. 2))
  1432. (contents (replace-regexp-in-string
  1433. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1434. (if (= pre-blank 0) (org-trim contents)
  1435. (concat (make-string pre-blank ?\n) contents)))))))
  1436. ;;;; Plain List
  1437. (defun org-element--list-struct (limit)
  1438. ;; Return structure of list at point. Internal function. See
  1439. ;; `org-list-struct' for details.
  1440. (let ((case-fold-search t)
  1441. (top-ind limit)
  1442. (item-re (org-item-re))
  1443. (inlinetask-re (and (featurep 'org-inlinetask)
  1444. (boundp 'org-inlinetask-min-level)
  1445. (boundp 'org-inlinetask-max-level)
  1446. (format "^\\*\\{%d,%d\\}+ "
  1447. org-inlinetask-min-level
  1448. org-inlinetask-max-level)))
  1449. items struct)
  1450. (save-excursion
  1451. (catch :exit
  1452. (while t
  1453. (cond
  1454. ;; At limit: end all items.
  1455. ((>= (point) limit)
  1456. (let ((end (progn (skip-chars-backward " \r\t\n")
  1457. (line-beginning-position 2))))
  1458. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1459. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1460. ;; At list end: end all items.
  1461. ((looking-at org-list-end-re)
  1462. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1463. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1464. ;; At a new item: end previous sibling.
  1465. ((looking-at item-re)
  1466. (let ((ind (save-excursion (skip-chars-forward " \t")
  1467. (current-column))))
  1468. (setq top-ind (min top-ind ind))
  1469. (while (and items (<= ind (nth 1 (car items))))
  1470. (let ((item (pop items)))
  1471. (setcar (nthcdr 6 item) (point))
  1472. (push item struct)))
  1473. (push (progn (looking-at org-list-full-item-re)
  1474. (let ((bullet (match-string-no-properties 1)))
  1475. (list (point)
  1476. ind
  1477. bullet
  1478. (match-string-no-properties 2) ; counter
  1479. (match-string-no-properties 3) ; checkbox
  1480. ;; Description tag.
  1481. (and (save-match-data
  1482. (string-match "[-+*]" bullet))
  1483. (match-string-no-properties 4))
  1484. ;; Ending position, unknown so far.
  1485. nil)))
  1486. items))
  1487. (forward-line))
  1488. ;; Skip empty lines.
  1489. ((looking-at "^[ \t]*$") (forward-line))
  1490. ;; Skip inline tasks and blank lines along the way.
  1491. ((and inlinetask-re (looking-at inlinetask-re))
  1492. (forward-line)
  1493. (let ((origin (point)))
  1494. (when (re-search-forward inlinetask-re limit t)
  1495. (if (looking-at-p "END[ \t]*$") (forward-line)
  1496. (goto-char origin)))))
  1497. ;; At some text line. Check if it ends any previous item.
  1498. (t
  1499. (let ((ind (save-excursion
  1500. (skip-chars-forward " \t")
  1501. (current-column)))
  1502. (end (save-excursion
  1503. (skip-chars-backward " \r\t\n")
  1504. (line-beginning-position 2))))
  1505. (while (<= ind (nth 1 (car items)))
  1506. (let ((item (pop items)))
  1507. (setcar (nthcdr 6 item) end)
  1508. (push item struct)
  1509. (unless items
  1510. (throw :exit (sort struct #'car-less-than-car))))))
  1511. ;; Skip blocks (any type) and drawers contents.
  1512. (cond
  1513. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1514. (re-search-forward
  1515. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1516. limit t)))
  1517. ((and (looking-at org-element-drawer-re)
  1518. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1519. (forward-line))))))))
  1520. (defun org-element-plain-list-parser (limit affiliated structure)
  1521. "Parse a plain list.
  1522. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1523. the buffer position at the beginning of the first affiliated
  1524. keyword and CDR is a plist of affiliated keywords along with
  1525. their value. STRUCTURE is the structure of the plain list being
  1526. parsed.
  1527. Return a list whose CAR is `plain-list' and CDR is a plist
  1528. containing `:type', `:begin', `:end', `:contents-begin' and
  1529. `:contents-end', `:structure', `:post-blank' and
  1530. `:post-affiliated' keywords.
  1531. Assume point is at the beginning of the list."
  1532. (save-excursion
  1533. (let* ((struct (or structure (org-element--list-struct limit)))
  1534. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1535. ((nth 5 (assq (point) struct)) 'descriptive)
  1536. (t 'unordered)))
  1537. (contents-begin (point))
  1538. (begin (car affiliated))
  1539. (contents-end (let* ((item (assq contents-begin struct))
  1540. (ind (nth 1 item))
  1541. (pos (nth 6 item)))
  1542. (while (and (setq item (assq pos struct))
  1543. (= (nth 1 item) ind))
  1544. (setq pos (nth 6 item)))
  1545. pos))
  1546. (end (progn (goto-char contents-end)
  1547. (skip-chars-forward " \r\t\n" limit)
  1548. (if (= (point) limit) limit (line-beginning-position)))))
  1549. ;; Return value.
  1550. (list 'plain-list
  1551. (nconc
  1552. (list :type type
  1553. :begin begin
  1554. :end end
  1555. :contents-begin contents-begin
  1556. :contents-end contents-end
  1557. :structure struct
  1558. :post-blank (count-lines contents-end end)
  1559. :post-affiliated contents-begin)
  1560. (cdr affiliated))))))
  1561. (defun org-element-plain-list-interpreter (_ contents)
  1562. "Interpret plain-list element as Org syntax.
  1563. CONTENTS is the contents of the element."
  1564. (with-temp-buffer
  1565. (insert contents)
  1566. (goto-char (point-min))
  1567. (org-list-repair)
  1568. (buffer-string)))
  1569. ;;;; Property Drawer
  1570. (defun org-element-property-drawer-parser (limit)
  1571. "Parse a property drawer.
  1572. LIMIT bounds the search.
  1573. Return a list whose car is `property-drawer' and cdr is a plist
  1574. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1575. `:post-blank' and `:post-affiliated' keywords.
  1576. Assume point is at the beginning of the property drawer."
  1577. (save-excursion
  1578. (let ((case-fold-search t)
  1579. (begin (point))
  1580. (contents-begin (line-beginning-position 2)))
  1581. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1582. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1583. (match-beginning 0)))
  1584. (before-blank (progn (forward-line) (point)))
  1585. (end (progn (skip-chars-forward " \r\t\n" limit)
  1586. (if (eobp) (point) (line-beginning-position)))))
  1587. (list 'property-drawer
  1588. (list :begin begin
  1589. :end end
  1590. :contents-begin (and contents-end contents-begin)
  1591. :contents-end contents-end
  1592. :post-blank (count-lines before-blank end)
  1593. :post-affiliated begin))))))
  1594. (defun org-element-property-drawer-interpreter (_ contents)
  1595. "Interpret property-drawer element as Org syntax.
  1596. CONTENTS is the properties within the drawer."
  1597. (format ":PROPERTIES:\n%s:END:" contents))
  1598. ;;;; Quote Block
  1599. (defun org-element-quote-block-parser (limit affiliated)
  1600. "Parse a quote block.
  1601. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1602. the buffer position at the beginning of the first affiliated
  1603. keyword and CDR is a plist of affiliated keywords along with
  1604. their value.
  1605. Return a list whose CAR is `quote-block' and CDR is a plist
  1606. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1607. `:post-blank' and `:post-affiliated' keywords.
  1608. Assume point is at the beginning of the block."
  1609. (let ((case-fold-search t))
  1610. (if (not (save-excursion
  1611. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1612. ;; Incomplete block: parse it as a paragraph.
  1613. (org-element-paragraph-parser limit affiliated)
  1614. (let ((block-end-line (match-beginning 0)))
  1615. (save-excursion
  1616. (let* ((begin (car affiliated))
  1617. (post-affiliated (point))
  1618. ;; Empty blocks have no contents.
  1619. (contents-begin (progn (forward-line)
  1620. (and (< (point) block-end-line)
  1621. (point))))
  1622. (contents-end (and contents-begin block-end-line))
  1623. (pos-before-blank (progn (goto-char block-end-line)
  1624. (forward-line)
  1625. (point)))
  1626. (end (progn (skip-chars-forward " \r\t\n" limit)
  1627. (if (eobp) (point) (line-beginning-position)))))
  1628. (list 'quote-block
  1629. (nconc
  1630. (list :begin begin
  1631. :end end
  1632. :contents-begin contents-begin
  1633. :contents-end contents-end
  1634. :post-blank (count-lines pos-before-blank end)
  1635. :post-affiliated post-affiliated)
  1636. (cdr affiliated)))))))))
  1637. (defun org-element-quote-block-interpreter (_ contents)
  1638. "Interpret quote-block element as Org syntax.
  1639. CONTENTS is the contents of the element."
  1640. (format "#+begin_quote\n%s#+end_quote" contents))
  1641. ;;;; Section
  1642. (defun org-element-section-parser (_)
  1643. "Parse a section.
  1644. Return a list whose CAR is `section' and CDR is a plist
  1645. containing `:begin', `:end', `:contents-begin', `contents-end',
  1646. `:post-blank' and `:post-affiliated' keywords."
  1647. (save-excursion
  1648. ;; Beginning of section is the beginning of the first non-blank
  1649. ;; line after previous headline.
  1650. (let* ((begin (point))
  1651. (end (progn (org-with-limited-levels (outline-next-heading))
  1652. (point)))
  1653. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1654. (line-beginning-position 2)))
  1655. (robust-end (when (> (- pos-before-blank 2) begin)
  1656. (- pos-before-blank 2)))
  1657. (robust-begin (when robust-end begin))
  1658. )
  1659. (list 'section
  1660. (list :begin begin
  1661. :end end
  1662. :contents-begin begin
  1663. :contents-end pos-before-blank
  1664. :robust-begin robust-begin
  1665. :robust-end robust-end
  1666. :post-blank (count-lines pos-before-blank end)
  1667. :post-affiliated begin)))))
  1668. (defun org-element-section-interpreter (_ contents)
  1669. "Interpret section element as Org syntax.
  1670. CONTENTS is the contents of the element."
  1671. contents)
  1672. ;;;; Special Block
  1673. (defun org-element-special-block-parser (limit affiliated)
  1674. "Parse a special block.
  1675. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1676. the buffer position at the beginning of the first affiliated
  1677. keyword and CDR is a plist of affiliated keywords along with
  1678. their value.
  1679. Return a list whose CAR is `special-block' and CDR is a plist
  1680. containing `:type', `:begin', `:end', `:contents-begin',
  1681. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1682. Assume point is at the beginning of the block."
  1683. (let* ((case-fold-search t)
  1684. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1685. (match-string-no-properties 1))))
  1686. (if (not (save-excursion
  1687. (re-search-forward
  1688. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1689. limit t)))
  1690. ;; Incomplete block: parse it as a paragraph.
  1691. (org-element-paragraph-parser limit affiliated)
  1692. (let ((block-end-line (match-beginning 0)))
  1693. (save-excursion
  1694. (let* ((begin (car affiliated))
  1695. (post-affiliated (point))
  1696. ;; Empty blocks have no contents.
  1697. (contents-begin (progn (forward-line)
  1698. (and (< (point) block-end-line)
  1699. (point))))
  1700. (contents-end (and contents-begin block-end-line))
  1701. (pos-before-blank (progn (goto-char block-end-line)
  1702. (forward-line)
  1703. (point)))
  1704. (end (progn (skip-chars-forward " \r\t\n" limit)
  1705. (if (eobp) (point) (line-beginning-position)))))
  1706. (list 'special-block
  1707. (nconc
  1708. (list :type type
  1709. :begin begin
  1710. :end end
  1711. :contents-begin contents-begin
  1712. :contents-end contents-end
  1713. :post-blank (count-lines pos-before-blank end)
  1714. :post-affiliated post-affiliated)
  1715. (cdr affiliated)))))))))
  1716. (defun org-element-special-block-interpreter (special-block contents)
  1717. "Interpret SPECIAL-BLOCK element as Org syntax.
  1718. CONTENTS is the contents of the element."
  1719. (let ((block-type (org-element-property :type special-block)))
  1720. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1721. ;;; Elements
  1722. ;;
  1723. ;; For each element, a parser and an interpreter are also defined.
  1724. ;; Both follow the same naming convention used for greater elements.
  1725. ;;
  1726. ;; Also, as for greater elements, adding a new element type is done
  1727. ;; through the following steps: implement a parser and an interpreter,
  1728. ;; tweak `org-element--current-element' so that it recognizes the new
  1729. ;; type and add that new type to `org-element-all-elements'.
  1730. ;;;; Babel Call
  1731. (defun org-element-babel-call-parser (limit affiliated)
  1732. "Parse a babel call.
  1733. LIMIT bounds the search. AFFILIATED is a list of which car is
  1734. the buffer position at the beginning of the first affiliated
  1735. keyword and cdr is a plist of affiliated keywords along with
  1736. their value.
  1737. Return a list whose car is `babel-call' and cdr is a plist
  1738. containing `:call', `:inside-header', `:arguments',
  1739. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1740. `:post-affiliated' as keywords."
  1741. (save-excursion
  1742. (let* ((begin (car affiliated))
  1743. (post-affiliated (point))
  1744. (before-blank (line-beginning-position 2))
  1745. (value (progn (search-forward ":" before-blank t)
  1746. (skip-chars-forward " \t")
  1747. (org-trim
  1748. (buffer-substring-no-properties
  1749. (point) (line-end-position)))))
  1750. (call
  1751. (or (org-string-nw-p
  1752. (buffer-substring-no-properties
  1753. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1754. (point))))))
  1755. (inside-header (org-element--parse-paired-brackets ?\[))
  1756. (arguments (org-string-nw-p
  1757. (org-element--parse-paired-brackets ?\()))
  1758. (end-header
  1759. (org-string-nw-p
  1760. (org-trim
  1761. (buffer-substring-no-properties (point) (line-end-position)))))
  1762. (end (progn (forward-line)
  1763. (skip-chars-forward " \r\t\n" limit)
  1764. (if (eobp) (point) (line-beginning-position)))))
  1765. (list 'babel-call
  1766. (nconc
  1767. (list :call call
  1768. :inside-header inside-header
  1769. :arguments arguments
  1770. :end-header end-header
  1771. :begin begin
  1772. :end end
  1773. :value value
  1774. :post-blank (count-lines before-blank end)
  1775. :post-affiliated post-affiliated)
  1776. (cdr affiliated))))))
  1777. (defun org-element-babel-call-interpreter (babel-call _)
  1778. "Interpret BABEL-CALL element as Org syntax."
  1779. (concat "#+call: "
  1780. (org-element-property :call babel-call)
  1781. (let ((h (org-element-property :inside-header babel-call)))
  1782. (and h (format "[%s]" h)))
  1783. (concat "(" (org-element-property :arguments babel-call) ")")
  1784. (let ((h (org-element-property :end-header babel-call)))
  1785. (and h (concat " " h)))))
  1786. ;;;; Clock
  1787. (defun org-element-clock-parser (limit)
  1788. "Parse a clock.
  1789. LIMIT bounds the search.
  1790. Return a list whose CAR is `clock' and CDR is a plist containing
  1791. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1792. `:post-affiliated' as keywords."
  1793. (save-excursion
  1794. (let* ((case-fold-search nil)
  1795. (begin (point))
  1796. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1797. (skip-chars-forward " \t")
  1798. (org-element-timestamp-parser)))
  1799. (duration (and (search-forward " => " (line-end-position) t)
  1800. (progn (skip-chars-forward " \t")
  1801. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1802. (match-string-no-properties 1)))
  1803. (status (if duration 'closed 'running))
  1804. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1805. (skip-chars-forward " \r\t\n" limit)
  1806. (skip-chars-backward " \t")
  1807. (unless (bolp) (end-of-line))
  1808. (count-lines before-blank (point))))
  1809. (end (point)))
  1810. (list 'clock
  1811. (list :status status
  1812. :value value
  1813. :duration duration
  1814. :begin begin
  1815. :end end
  1816. :post-blank post-blank
  1817. :post-affiliated begin)))))
  1818. (defun org-element-clock-interpreter (clock _)
  1819. "Interpret CLOCK element as Org syntax."
  1820. (concat "CLOCK: "
  1821. (org-element-timestamp-interpreter
  1822. (org-element-property :value clock) nil)
  1823. (let ((duration (org-element-property :duration clock)))
  1824. (and duration
  1825. (concat " => "
  1826. (apply 'format
  1827. "%2s:%02s"
  1828. (org-split-string duration ":")))))))
  1829. ;;;; Comment
  1830. (defun org-element-comment-parser (limit)
  1831. "Parse a comment.
  1832. LIMIT bounds the search.
  1833. Return a list whose CAR is `comment' and CDR is a plist
  1834. containing `:begin', `:end', `:value', `:post-blank',
  1835. `:post-affiliated' keywords.
  1836. Assume point is at comment beginning."
  1837. (save-excursion
  1838. (let* ((begin (point))
  1839. (value (prog2 (looking-at "[ \t]*# ?")
  1840. (buffer-substring-no-properties
  1841. (match-end 0) (line-end-position))
  1842. (forward-line)))
  1843. (com-end
  1844. ;; Get comments ending.
  1845. (progn
  1846. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1847. ;; Accumulate lines without leading hash and first
  1848. ;; whitespace.
  1849. (setq value
  1850. (concat value
  1851. "\n"
  1852. (buffer-substring-no-properties
  1853. (match-end 0) (line-end-position))))
  1854. (forward-line))
  1855. (point)))
  1856. (end (progn (goto-char com-end)
  1857. (skip-chars-forward " \r\t\n" limit)
  1858. (if (eobp) (point) (line-beginning-position)))))
  1859. (list 'comment
  1860. (list :begin begin
  1861. :end end
  1862. :value value
  1863. :post-blank (count-lines com-end end)
  1864. :post-affiliated begin)))))
  1865. (defun org-element-comment-interpreter (comment _)
  1866. "Interpret COMMENT element as Org syntax.
  1867. CONTENTS is nil."
  1868. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1869. ;;;; Comment Block
  1870. (defun org-element-comment-block-parser (limit affiliated)
  1871. "Parse an export block.
  1872. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1873. the buffer position at the beginning of the first affiliated
  1874. keyword and CDR is a plist of affiliated keywords along with
  1875. their value.
  1876. Return a list whose CAR is `comment-block' and CDR is a plist
  1877. containing `:begin', `:end', `:value', `:post-blank' and
  1878. `:post-affiliated' keywords.
  1879. Assume point is at comment block beginning."
  1880. (let ((case-fold-search t))
  1881. (if (not (save-excursion
  1882. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1883. ;; Incomplete block: parse it as a paragraph.
  1884. (org-element-paragraph-parser limit affiliated)
  1885. (let ((contents-end (match-beginning 0)))
  1886. (save-excursion
  1887. (let* ((begin (car affiliated))
  1888. (post-affiliated (point))
  1889. (contents-begin (progn (forward-line) (point)))
  1890. (pos-before-blank (progn (goto-char contents-end)
  1891. (forward-line)
  1892. (point)))
  1893. (end (progn (skip-chars-forward " \r\t\n" limit)
  1894. (if (eobp) (point) (line-beginning-position))))
  1895. (value (buffer-substring-no-properties
  1896. contents-begin contents-end)))
  1897. (list 'comment-block
  1898. (nconc
  1899. (list :begin begin
  1900. :end end
  1901. :value value
  1902. :post-blank (count-lines pos-before-blank end)
  1903. :post-affiliated post-affiliated)
  1904. (cdr affiliated)))))))))
  1905. (defun org-element-comment-block-interpreter (comment-block _)
  1906. "Interpret COMMENT-BLOCK element as Org syntax."
  1907. (format "#+begin_comment\n%s#+end_comment"
  1908. (org-element-normalize-string
  1909. (org-remove-indentation
  1910. (org-element-property :value comment-block)))))
  1911. ;;;; Diary Sexp
  1912. (defun org-element-diary-sexp-parser (limit affiliated)
  1913. "Parse a diary sexp.
  1914. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1915. the buffer position at the beginning of the first affiliated
  1916. keyword and CDR is a plist of affiliated keywords along with
  1917. their value.
  1918. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1919. containing `:begin', `:end', `:value', `:post-blank' and
  1920. `:post-affiliated' keywords."
  1921. (save-excursion
  1922. (let ((begin (car affiliated))
  1923. (post-affiliated (point))
  1924. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1925. (match-string-no-properties 1)))
  1926. (pos-before-blank (progn (forward-line) (point)))
  1927. (end (progn (skip-chars-forward " \r\t\n" limit)
  1928. (if (eobp) (point) (line-beginning-position)))))
  1929. (list 'diary-sexp
  1930. (nconc
  1931. (list :value value
  1932. :begin begin
  1933. :end end
  1934. :post-blank (count-lines pos-before-blank end)
  1935. :post-affiliated post-affiliated)
  1936. (cdr affiliated))))))
  1937. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1938. "Interpret DIARY-SEXP as Org syntax."
  1939. (org-element-property :value diary-sexp))
  1940. ;;;; Example Block
  1941. (defun org-element-example-block-parser (limit affiliated)
  1942. "Parse an example block.
  1943. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1944. the buffer position at the beginning of the first affiliated
  1945. keyword and CDR is a plist of affiliated keywords along with
  1946. their value.
  1947. Return a list whose CAR is `example-block' and CDR is a plist
  1948. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1949. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1950. `:value', `:post-blank' and `:post-affiliated' keywords."
  1951. (let ((case-fold-search t))
  1952. (if (not (save-excursion
  1953. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1954. ;; Incomplete block: parse it as a paragraph.
  1955. (org-element-paragraph-parser limit affiliated)
  1956. (let ((contents-end (match-beginning 0)))
  1957. (save-excursion
  1958. (let* ((switches
  1959. (progn
  1960. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1961. (match-string-no-properties 1)))
  1962. ;; Switches analysis.
  1963. (number-lines
  1964. (and switches
  1965. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1966. switches)
  1967. (cons
  1968. (if (equal (match-string 1 switches) "-")
  1969. 'new
  1970. 'continued)
  1971. (if (not (match-end 2)) 0
  1972. ;; Subtract 1 to give number of lines before
  1973. ;; first line.
  1974. (1- (string-to-number (match-string 2 switches)))))))
  1975. (preserve-indent
  1976. (and switches (string-match "-i\\>" switches)))
  1977. ;; Should labels be retained in (or stripped from) example
  1978. ;; blocks?
  1979. (retain-labels
  1980. (or (not switches)
  1981. (not (string-match "-r\\>" switches))
  1982. (and number-lines (string-match "-k\\>" switches))))
  1983. ;; What should code-references use - labels or
  1984. ;; line-numbers?
  1985. (use-labels
  1986. (or (not switches)
  1987. (and retain-labels
  1988. (not (string-match "-k\\>" switches)))))
  1989. (label-fmt
  1990. (and switches
  1991. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1992. (match-string 1 switches)))
  1993. ;; Standard block parsing.
  1994. (begin (car affiliated))
  1995. (post-affiliated (point))
  1996. (contents-begin (line-beginning-position 2))
  1997. (value (org-unescape-code-in-string
  1998. (buffer-substring-no-properties
  1999. contents-begin contents-end)))
  2000. (pos-before-blank (progn (goto-char contents-end)
  2001. (forward-line)
  2002. (point)))
  2003. (end (progn (skip-chars-forward " \r\t\n" limit)
  2004. (if (eobp) (point) (line-beginning-position)))))
  2005. (list 'example-block
  2006. (nconc
  2007. (list :begin begin
  2008. :end end
  2009. :value value
  2010. :switches switches
  2011. :number-lines number-lines
  2012. :preserve-indent preserve-indent
  2013. :retain-labels retain-labels
  2014. :use-labels use-labels
  2015. :label-fmt label-fmt
  2016. :post-blank (count-lines pos-before-blank end)
  2017. :post-affiliated post-affiliated)
  2018. (cdr affiliated)))))))))
  2019. (defun org-element-example-block-interpreter (example-block _)
  2020. "Interpret EXAMPLE-BLOCK element as Org syntax."
  2021. (let ((switches (org-element-property :switches example-block))
  2022. (value
  2023. (let ((val (org-element-property :value example-block)))
  2024. (cond
  2025. ((or org-src-preserve-indentation
  2026. (org-element-property :preserve-indent example-block))
  2027. val)
  2028. ((= 0 org-edit-src-content-indentation)
  2029. (org-remove-indentation val))
  2030. (t
  2031. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2032. (replace-regexp-in-string "^[ \t]*\\S-"
  2033. (concat ind "\\&")
  2034. (org-remove-indentation val))))))))
  2035. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  2036. (org-element-normalize-string (org-escape-code-in-string value))
  2037. "#+end_example")))
  2038. ;;;; Export Block
  2039. (defun org-element-export-block-parser (limit affiliated)
  2040. "Parse an export block.
  2041. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2042. the buffer position at the beginning of the first affiliated
  2043. keyword and CDR is a plist of affiliated keywords along with
  2044. their value.
  2045. Return a list whose CAR is `export-block' and CDR is a plist
  2046. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  2047. `:post-affiliated' keywords.
  2048. Assume point is at export-block beginning."
  2049. (let* ((case-fold-search t))
  2050. (if (not (save-excursion
  2051. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  2052. ;; Incomplete block: parse it as a paragraph.
  2053. (org-element-paragraph-parser limit affiliated)
  2054. (save-excursion
  2055. (let* ((contents-end (match-beginning 0))
  2056. (backend
  2057. (progn
  2058. (looking-at
  2059. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  2060. (match-string-no-properties 1)))
  2061. (begin (car affiliated))
  2062. (post-affiliated (point))
  2063. (contents-begin (progn (forward-line) (point)))
  2064. (pos-before-blank (progn (goto-char contents-end)
  2065. (forward-line)
  2066. (point)))
  2067. (end (progn (skip-chars-forward " \r\t\n" limit)
  2068. (if (eobp) (point) (line-beginning-position))))
  2069. (value (org-unescape-code-in-string
  2070. (buffer-substring-no-properties contents-begin
  2071. contents-end))))
  2072. (list 'export-block
  2073. (nconc
  2074. (list :type (and backend (upcase backend))
  2075. :begin begin
  2076. :end end
  2077. :value value
  2078. :post-blank (count-lines pos-before-blank end)
  2079. :post-affiliated post-affiliated)
  2080. (cdr affiliated))))))))
  2081. (defun org-element-export-block-interpreter (export-block _)
  2082. "Interpret EXPORT-BLOCK element as Org syntax."
  2083. (format "#+begin_export %s\n%s#+end_export"
  2084. (org-element-property :type export-block)
  2085. (org-element-property :value export-block)))
  2086. ;;;; Fixed-width
  2087. (defun org-element-fixed-width-parser (limit affiliated)
  2088. "Parse a fixed-width section.
  2089. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2090. the buffer position at the beginning of the first affiliated
  2091. keyword and CDR is a plist of affiliated keywords along with
  2092. their value.
  2093. Return a list whose CAR is `fixed-width' and CDR is a plist
  2094. containing `:begin', `:end', `:value', `:post-blank' and
  2095. `:post-affiliated' keywords.
  2096. Assume point is at the beginning of the fixed-width area."
  2097. (save-excursion
  2098. (let* ((begin (car affiliated))
  2099. (post-affiliated (point))
  2100. (end-area
  2101. (progn
  2102. (while (and (< (point) limit)
  2103. (looking-at "[ \t]*:\\( \\|$\\)"))
  2104. (forward-line))
  2105. (if (bolp) (line-end-position 0) (point))))
  2106. (end (progn (skip-chars-forward " \r\t\n" limit)
  2107. (if (eobp) (point) (line-beginning-position)))))
  2108. (list 'fixed-width
  2109. (nconc
  2110. (list :begin begin
  2111. :end end
  2112. :value (replace-regexp-in-string
  2113. "^[ \t]*: ?" ""
  2114. (buffer-substring-no-properties post-affiliated
  2115. end-area))
  2116. :post-blank (count-lines end-area end)
  2117. :post-affiliated post-affiliated)
  2118. (cdr affiliated))))))
  2119. (defun org-element-fixed-width-interpreter (fixed-width _)
  2120. "Interpret FIXED-WIDTH element as Org syntax."
  2121. (let ((value (org-element-property :value fixed-width)))
  2122. (and value (replace-regexp-in-string "^" ": " value))))
  2123. ;;;; Horizontal Rule
  2124. (defun org-element-horizontal-rule-parser (limit affiliated)
  2125. "Parse an horizontal rule.
  2126. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2127. the buffer position at the beginning of the first affiliated
  2128. keyword and CDR is a plist of affiliated keywords along with
  2129. their value.
  2130. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  2131. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  2132. keywords."
  2133. (save-excursion
  2134. (let ((begin (car affiliated))
  2135. (post-affiliated (point))
  2136. (post-hr (progn (forward-line) (point)))
  2137. (end (progn (skip-chars-forward " \r\t\n" limit)
  2138. (if (eobp) (point) (line-beginning-position)))))
  2139. (list 'horizontal-rule
  2140. (nconc
  2141. (list :begin begin
  2142. :end end
  2143. :post-blank (count-lines post-hr end)
  2144. :post-affiliated post-affiliated)
  2145. (cdr affiliated))))))
  2146. (defun org-element-horizontal-rule-interpreter (&rest _)
  2147. "Interpret HORIZONTAL-RULE element as Org syntax."
  2148. "-----")
  2149. ;;;; Keyword
  2150. (defun org-element-keyword-parser (limit affiliated)
  2151. "Parse a keyword at point.
  2152. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2153. the buffer position at the beginning of the first affiliated
  2154. keyword and CDR is a plist of affiliated keywords along with
  2155. their value.
  2156. Return a list whose CAR is a normalized `keyword' (uppercase) and
  2157. CDR is a plist containing `:key', `:value', `:begin', `:end',
  2158. `:post-blank' and `:post-affiliated' keywords."
  2159. (save-excursion
  2160. ;; An orphaned affiliated keyword is considered as a regular
  2161. ;; keyword. In this case AFFILIATED is nil, so we take care of
  2162. ;; this corner case.
  2163. (let ((begin (or (car affiliated) (point)))
  2164. (post-affiliated (point))
  2165. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  2166. (upcase (match-string-no-properties 1))))
  2167. (value (org-trim (buffer-substring-no-properties
  2168. (match-end 0) (point-at-eol))))
  2169. (pos-before-blank (progn (forward-line) (point)))
  2170. (end (progn (skip-chars-forward " \r\t\n" limit)
  2171. (if (eobp) (point) (line-beginning-position)))))
  2172. (list 'keyword
  2173. (nconc
  2174. (list :key key
  2175. :value value
  2176. :begin begin
  2177. :end end
  2178. :post-blank (count-lines pos-before-blank end)
  2179. :post-affiliated post-affiliated)
  2180. (cdr affiliated))))))
  2181. (defun org-element-keyword-interpreter (keyword _)
  2182. "Interpret KEYWORD element as Org syntax."
  2183. (format "#+%s: %s"
  2184. (downcase (org-element-property :key keyword))
  2185. (org-element-property :value keyword)))
  2186. ;;;; Latex Environment
  2187. (defconst org-element--latex-begin-environment
  2188. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2189. "Regexp matching the beginning of a LaTeX environment.
  2190. The environment is captured by the first group.
  2191. See also `org-element--latex-end-environment'.")
  2192. (defconst org-element--latex-end-environment
  2193. "\\\\end{%s}[ \t]*$"
  2194. "Format string matching the ending of a LaTeX environment.
  2195. See also `org-element--latex-begin-environment'.")
  2196. (defun org-element-latex-environment-parser (limit affiliated)
  2197. "Parse a LaTeX environment.
  2198. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2199. the buffer position at the beginning of the first affiliated
  2200. keyword and CDR is a plist of affiliated keywords along with
  2201. their value.
  2202. Return a list whose CAR is `latex-environment' and CDR is a plist
  2203. containing `:begin', `:end', `:value', `:post-blank' and
  2204. `:post-affiliated' keywords.
  2205. Assume point is at the beginning of the latex environment."
  2206. (save-excursion
  2207. (let ((case-fold-search t)
  2208. (code-begin (point)))
  2209. (looking-at org-element--latex-begin-environment)
  2210. (if (not (re-search-forward (format org-element--latex-end-environment
  2211. (regexp-quote (match-string 1)))
  2212. limit t))
  2213. ;; Incomplete latex environment: parse it as a paragraph.
  2214. (org-element-paragraph-parser limit affiliated)
  2215. (let* ((code-end (progn (forward-line) (point)))
  2216. (begin (car affiliated))
  2217. (value (buffer-substring-no-properties code-begin code-end))
  2218. (end (progn (skip-chars-forward " \r\t\n" limit)
  2219. (if (eobp) (point) (line-beginning-position)))))
  2220. (list 'latex-environment
  2221. (nconc
  2222. (list :begin begin
  2223. :end end
  2224. :value value
  2225. :post-blank (count-lines code-end end)
  2226. :post-affiliated code-begin)
  2227. (cdr affiliated))))))))
  2228. (defun org-element-latex-environment-interpreter (latex-environment _)
  2229. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2230. (org-element-property :value latex-environment))
  2231. ;;;; Node Property
  2232. (defun org-element-node-property-parser (limit)
  2233. "Parse a node-property at point.
  2234. LIMIT bounds the search.
  2235. Return a list whose CAR is `node-property' and CDR is a plist
  2236. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2237. `:post-affiliated' keywords."
  2238. (looking-at org-property-re)
  2239. (let ((case-fold-search t)
  2240. (begin (point))
  2241. (key (match-string-no-properties 2))
  2242. (value (match-string-no-properties 3))
  2243. (end (save-excursion
  2244. (end-of-line)
  2245. (if (re-search-forward org-property-re limit t)
  2246. (line-beginning-position)
  2247. limit))))
  2248. (list 'node-property
  2249. (list :key key
  2250. :value value
  2251. :begin begin
  2252. :end end
  2253. :post-blank 0
  2254. :post-affiliated begin))))
  2255. (defun org-element-node-property-interpreter (node-property _)
  2256. "Interpret NODE-PROPERTY element as Org syntax."
  2257. (format org-property-format
  2258. (format ":%s:" (org-element-property :key node-property))
  2259. (or (org-element-property :value node-property) "")))
  2260. ;;;; Paragraph
  2261. (defun org-element-paragraph-parser (limit affiliated)
  2262. "Parse a paragraph.
  2263. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2264. the buffer position at the beginning of the first affiliated
  2265. keyword and CDR is a plist of affiliated keywords along with
  2266. their value.
  2267. Return a list whose CAR is `paragraph' and CDR is a plist
  2268. containing `:begin', `:end', `:contents-begin' and
  2269. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2270. Assume point is at the beginning of the paragraph."
  2271. (save-excursion
  2272. (let* ((begin (car affiliated))
  2273. (contents-begin (point))
  2274. (before-blank
  2275. (let ((case-fold-search t))
  2276. (end-of-line)
  2277. ;; A matching `org-element-paragraph-separate' is not
  2278. ;; necessarily the end of the paragraph. In particular,
  2279. ;; drawers, blocks or LaTeX environments opening lines
  2280. ;; must be closed. Moreover keywords with a secondary
  2281. ;; value must belong to "dual keywords".
  2282. (while (not
  2283. (cond
  2284. ((not (and (re-search-forward
  2285. org-element-paragraph-separate limit 'move)
  2286. (progn (beginning-of-line) t))))
  2287. ((looking-at org-element-drawer-re)
  2288. (save-excursion
  2289. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2290. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2291. (save-excursion
  2292. (re-search-forward
  2293. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2294. (regexp-quote (match-string 1)))
  2295. limit t)))
  2296. ((looking-at org-element--latex-begin-environment)
  2297. (save-excursion
  2298. (re-search-forward
  2299. (format org-element--latex-end-environment
  2300. (regexp-quote (match-string 1)))
  2301. limit t)))
  2302. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2303. (member-ignore-case (match-string 1)
  2304. org-element-dual-keywords))
  2305. ;; Everything else is unambiguous.
  2306. (t)))
  2307. (end-of-line))
  2308. (if (= (point) limit) limit
  2309. (goto-char (line-beginning-position)))))
  2310. (contents-end (save-excursion
  2311. (skip-chars-backward " \r\t\n" contents-begin)
  2312. (line-beginning-position 2)))
  2313. (end (progn (skip-chars-forward " \r\t\n" limit)
  2314. (if (eobp) (point) (line-beginning-position)))))
  2315. (list 'paragraph
  2316. (nconc
  2317. (list :begin begin
  2318. :end end
  2319. :contents-begin contents-begin
  2320. :contents-end contents-end
  2321. :post-blank (count-lines before-blank end)
  2322. :post-affiliated contents-begin)
  2323. (cdr affiliated))))))
  2324. (defun org-element-paragraph-interpreter (_ contents)
  2325. "Interpret paragraph element as Org syntax.
  2326. CONTENTS is the contents of the element."
  2327. contents)
  2328. ;;;; Planning
  2329. (defun org-element-planning-parser (limit)
  2330. "Parse a planning.
  2331. LIMIT bounds the search.
  2332. Return a list whose CAR is `planning' and CDR is a plist
  2333. containing `:closed', `:deadline', `:scheduled', `:begin',
  2334. `:end', `:post-blank' and `:post-affiliated' keywords."
  2335. (save-excursion
  2336. (let* ((case-fold-search nil)
  2337. (begin (point))
  2338. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2339. (skip-chars-forward " \r\t\n" limit)
  2340. (skip-chars-backward " \t")
  2341. (unless (bolp) (end-of-line))
  2342. (count-lines before-blank (point))))
  2343. (end (point))
  2344. closed deadline scheduled)
  2345. (goto-char begin)
  2346. (while (re-search-forward org-element-planning-keywords-re end t)
  2347. (skip-chars-forward " \t" end)
  2348. (let ((keyword (match-string 0))
  2349. (time (org-element-timestamp-parser)))
  2350. (cond
  2351. ((equal keyword org-element-closed-keyword) (setq closed time))
  2352. ((equal keyword org-element-deadline-keyword) (setq deadline time))
  2353. (t (setq scheduled time)))))
  2354. (list 'planning
  2355. (list :closed closed
  2356. :deadline deadline
  2357. :scheduled scheduled
  2358. :begin begin
  2359. :end end
  2360. :post-blank post-blank
  2361. :post-affiliated begin)))))
  2362. (defun org-element-planning-interpreter (planning _)
  2363. "Interpret PLANNING element as Org syntax."
  2364. (mapconcat
  2365. #'identity
  2366. (delq nil
  2367. (list (let ((deadline (org-element-property :deadline planning)))
  2368. (when deadline
  2369. (concat org-element-deadline-keyword " "
  2370. (org-element-timestamp-interpreter deadline nil))))
  2371. (let ((scheduled (org-element-property :scheduled planning)))
  2372. (when scheduled
  2373. (concat org-element-scheduled-keyword " "
  2374. (org-element-timestamp-interpreter scheduled nil))))
  2375. (let ((closed (org-element-property :closed planning)))
  2376. (when closed
  2377. (concat org-element-closed-keyword " "
  2378. (org-element-timestamp-interpreter closed nil))))))
  2379. " "))
  2380. ;;;; Src Block
  2381. (defun org-element-src-block-parser (limit affiliated)
  2382. "Parse a source block.
  2383. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2384. the buffer position at the beginning of the first affiliated
  2385. keyword and CDR is a plist of affiliated keywords along with
  2386. their value.
  2387. Return a list whose CAR is `src-block' and CDR is a plist
  2388. containing `:language', `:switches', `:parameters', `:begin',
  2389. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2390. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2391. `:post-affiliated' keywords.
  2392. Assume point is at the beginning of the block."
  2393. (let ((case-fold-search t))
  2394. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2395. limit t)))
  2396. ;; Incomplete block: parse it as a paragraph.
  2397. (org-element-paragraph-parser limit affiliated)
  2398. (let ((contents-end (match-beginning 0)))
  2399. (save-excursion
  2400. (let* ((begin (car affiliated))
  2401. (post-affiliated (point))
  2402. ;; Get language as a string.
  2403. (language
  2404. (progn
  2405. (looking-at
  2406. "^[ \t]*#\\+BEGIN_SRC\
  2407. \\(?: +\\(\\S-+\\)\\)?\
  2408. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2409. \\(.*\\)[ \t]*$")
  2410. (match-string-no-properties 1)))
  2411. ;; Get switches.
  2412. (switches (match-string-no-properties 2))
  2413. ;; Get parameters.
  2414. (parameters (match-string-no-properties 3))
  2415. ;; Switches analysis.
  2416. (number-lines
  2417. (and switches
  2418. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2419. switches)
  2420. (cons
  2421. (if (equal (match-string 1 switches) "-")
  2422. 'new
  2423. 'continued)
  2424. (if (not (match-end 2)) 0
  2425. ;; Subtract 1 to give number of lines before
  2426. ;; first line.
  2427. (1- (string-to-number (match-string 2 switches)))))))
  2428. (preserve-indent (and switches
  2429. (string-match "-i\\>" switches)))
  2430. (label-fmt
  2431. (and switches
  2432. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2433. (match-string 1 switches)))
  2434. ;; Should labels be retained in (or stripped from)
  2435. ;; source blocks?
  2436. (retain-labels
  2437. (or (not switches)
  2438. (not (string-match "-r\\>" switches))
  2439. (and number-lines (string-match "-k\\>" switches))))
  2440. ;; What should code-references use - labels or
  2441. ;; line-numbers?
  2442. (use-labels
  2443. (or (not switches)
  2444. (and retain-labels
  2445. (not (string-match "-k\\>" switches)))))
  2446. ;; Retrieve code.
  2447. (value (org-unescape-code-in-string
  2448. (buffer-substring-no-properties
  2449. (line-beginning-position 2) contents-end)))
  2450. (pos-before-blank (progn (goto-char contents-end)
  2451. (forward-line)
  2452. (point)))
  2453. ;; Get position after ending blank lines.
  2454. (end (progn (skip-chars-forward " \r\t\n" limit)
  2455. (if (eobp) (point) (line-beginning-position)))))
  2456. (list 'src-block
  2457. (nconc
  2458. (list :language language
  2459. :switches (and (org-string-nw-p switches)
  2460. (org-trim switches))
  2461. :parameters (and (org-string-nw-p parameters)
  2462. (org-trim parameters))
  2463. :begin begin
  2464. :end end
  2465. :number-lines number-lines
  2466. :preserve-indent preserve-indent
  2467. :retain-labels retain-labels
  2468. :use-labels use-labels
  2469. :label-fmt label-fmt
  2470. :value value
  2471. :post-blank (count-lines pos-before-blank end)
  2472. :post-affiliated post-affiliated)
  2473. (cdr affiliated)))))))))
  2474. (defun org-element-src-block-interpreter (src-block _)
  2475. "Interpret SRC-BLOCK element as Org syntax."
  2476. (let ((lang (org-element-property :language src-block))
  2477. (switches (org-element-property :switches src-block))
  2478. (params (org-element-property :parameters src-block))
  2479. (value
  2480. (let ((val (org-element-property :value src-block)))
  2481. (cond
  2482. ((or org-src-preserve-indentation
  2483. (org-element-property :preserve-indent src-block))
  2484. val)
  2485. ((zerop org-edit-src-content-indentation)
  2486. (org-remove-indentation val))
  2487. (t
  2488. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2489. (replace-regexp-in-string "^[ \t]*\\S-"
  2490. (concat ind "\\&")
  2491. (org-remove-indentation val))))))))
  2492. (format "#+begin_src%s\n%s#+end_src"
  2493. (concat (and lang (concat " " lang))
  2494. (and switches (concat " " switches))
  2495. (and params (concat " " params)))
  2496. (org-element-normalize-string (org-escape-code-in-string value)))))
  2497. ;;;; Table
  2498. (defun org-element-table-parser (limit affiliated)
  2499. "Parse a table at point.
  2500. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2501. the buffer position at the beginning of the first affiliated
  2502. keyword and CDR is a plist of affiliated keywords along with
  2503. their value.
  2504. Return a list whose CAR is `table' and CDR is a plist containing
  2505. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2506. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2507. keywords.
  2508. Assume point is at the beginning of the table."
  2509. (save-excursion
  2510. (let* ((case-fold-search t)
  2511. (table-begin (point))
  2512. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2513. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2514. (if (eq type 'org) "" "+")))
  2515. (begin (car affiliated))
  2516. (table-end
  2517. (if (re-search-forward end-re limit 'move)
  2518. (goto-char (match-beginning 0))
  2519. (point)))
  2520. (tblfm (let (acc)
  2521. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2522. (push (match-string-no-properties 1) acc)
  2523. (forward-line))
  2524. acc))
  2525. (pos-before-blank (point))
  2526. (end (progn (skip-chars-forward " \r\t\n" limit)
  2527. (if (eobp) (point) (line-beginning-position)))))
  2528. (list 'table
  2529. (nconc
  2530. (list :begin begin
  2531. :end end
  2532. :type type
  2533. :tblfm tblfm
  2534. ;; Only `org' tables have contents. `table.el' tables
  2535. ;; use a `:value' property to store raw table as
  2536. ;; a string.
  2537. :contents-begin (and (eq type 'org) table-begin)
  2538. :contents-end (and (eq type 'org) table-end)
  2539. :value (and (eq type 'table.el)
  2540. (buffer-substring-no-properties
  2541. table-begin table-end))
  2542. :post-blank (count-lines pos-before-blank end)
  2543. :post-affiliated table-begin)
  2544. (cdr affiliated))))))
  2545. (defun org-element-table-interpreter (table contents)
  2546. "Interpret TABLE element as Org syntax.
  2547. CONTENTS is a string, if table's type is `org', or nil."
  2548. (if (eq (org-element-property :type table) 'table.el)
  2549. (org-remove-indentation (org-element-property :value table))
  2550. (concat (with-temp-buffer (insert contents)
  2551. (org-table-align)
  2552. (buffer-string))
  2553. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2554. (reverse (org-element-property :tblfm table))
  2555. "\n"))))
  2556. ;;;; Table Row
  2557. (defun org-element-table-row-parser (_)
  2558. "Parse table row at point.
  2559. Return a list whose CAR is `table-row' and CDR is a plist
  2560. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2561. `:type', `:post-blank' and `:post-affiliated' keywords."
  2562. (save-excursion
  2563. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2564. (begin (point))
  2565. ;; A table rule has no contents. In that case, ensure
  2566. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2567. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2568. (contents-end (and (eq type 'standard)
  2569. (progn
  2570. (end-of-line)
  2571. (skip-chars-backward " \t")
  2572. (point))))
  2573. (end (line-beginning-position 2)))
  2574. (list 'table-row
  2575. (list :type type
  2576. :begin begin
  2577. :end end
  2578. :contents-begin contents-begin
  2579. :contents-end contents-end
  2580. :post-blank 0
  2581. :post-affiliated begin)))))
  2582. (defun org-element-table-row-interpreter (table-row contents)
  2583. "Interpret TABLE-ROW element as Org syntax.
  2584. CONTENTS is the contents of the table row."
  2585. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2586. (concat "|" contents)))
  2587. ;;;; Verse Block
  2588. (defun org-element-verse-block-parser (limit affiliated)
  2589. "Parse a verse block.
  2590. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2591. the buffer position at the beginning of the first affiliated
  2592. keyword and CDR is a plist of affiliated keywords along with
  2593. their value.
  2594. Return a list whose CAR is `verse-block' and CDR is a plist
  2595. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2596. `:post-blank' and `:post-affiliated' keywords.
  2597. Assume point is at beginning of the block."
  2598. (let ((case-fold-search t))
  2599. (if (not (save-excursion
  2600. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2601. ;; Incomplete block: parse it as a paragraph.
  2602. (org-element-paragraph-parser limit affiliated)
  2603. (let ((contents-end (match-beginning 0)))
  2604. (save-excursion
  2605. (let* ((begin (car affiliated))
  2606. (post-affiliated (point))
  2607. (contents-begin (progn (forward-line) (point)))
  2608. (pos-before-blank (progn (goto-char contents-end)
  2609. (forward-line)
  2610. (point)))
  2611. (end (progn (skip-chars-forward " \r\t\n" limit)
  2612. (if (eobp) (point) (line-beginning-position)))))
  2613. (list 'verse-block
  2614. (nconc
  2615. (list :begin begin
  2616. :end end
  2617. :contents-begin contents-begin
  2618. :contents-end contents-end
  2619. :post-blank (count-lines pos-before-blank end)
  2620. :post-affiliated post-affiliated)
  2621. (cdr affiliated)))))))))
  2622. (defun org-element-verse-block-interpreter (_ contents)
  2623. "Interpret verse-block element as Org syntax.
  2624. CONTENTS is verse block contents."
  2625. (format "#+begin_verse\n%s#+end_verse" contents))
  2626. ;;; Objects
  2627. ;;
  2628. ;; Unlike to elements, raw text can be found between objects. Hence,
  2629. ;; `org-element--object-lex' is provided to find the next object in
  2630. ;; buffer.
  2631. ;;
  2632. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2633. ;; object types they can contain will be specified in
  2634. ;; `org-element-object-restrictions'.
  2635. ;;
  2636. ;; Creating a new type of object requires to alter
  2637. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2638. ;; new type in `org-element-all-objects', and possibly add
  2639. ;; restrictions in `org-element-object-restrictions'.
  2640. ;;;; Bold
  2641. (defun org-element--parse-generic-emphasis (mark type)
  2642. "Parse emphasis object at point, if any.
  2643. MARK is the delimiter string used. TYPE is a symbol among
  2644. ‘bold’, ‘code’, ‘italic’, ‘strike-through’, ‘underline’, and
  2645. ‘verbatim’.
  2646. Assume point is at first MARK."
  2647. (save-excursion
  2648. (let ((origin (point)))
  2649. (unless (bolp) (forward-char -1))
  2650. (let ((opening-re
  2651. (rx-to-string
  2652. `(seq (or line-start (any space ?- ?\( ?' ?\" ?\{))
  2653. ,mark
  2654. (not space)))))
  2655. (when (looking-at opening-re)
  2656. (goto-char (1+ origin))
  2657. (let ((closing-re
  2658. (rx-to-string
  2659. `(seq
  2660. (not space)
  2661. (group ,mark)
  2662. (or (any space ?- ?. ?, ?\; ?: ?! ?? ?' ?\" ?\) ?\} ?\\ ?\[)
  2663. line-end)))))
  2664. (when (re-search-forward closing-re nil t)
  2665. (let ((closing (match-end 1)))
  2666. (goto-char closing)
  2667. (let* ((post-blank (skip-chars-forward " \t"))
  2668. (contents-begin (1+ origin))
  2669. (contents-end (1- closing)))
  2670. (list type
  2671. (append
  2672. (list :begin origin
  2673. :end (point)
  2674. :post-blank post-blank)
  2675. (if (memq type '(code verbatim))
  2676. (list :value
  2677. (and (memq type '(code verbatim))
  2678. (buffer-substring
  2679. contents-begin contents-end)))
  2680. (list :contents-begin contents-begin
  2681. :contents-end contents-end)))))))))))))
  2682. (defun org-element-bold-parser ()
  2683. "Parse bold object at point, if any.
  2684. When at a bold object, return a list whose car is `bold' and cdr
  2685. is a plist with `:begin', `:end', `:contents-begin' and
  2686. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2687. nil.
  2688. Assume point is at the first star marker."
  2689. (org-element--parse-generic-emphasis "*" 'bold))
  2690. (defun org-element-bold-interpreter (_ contents)
  2691. "Interpret bold object as Org syntax.
  2692. CONTENTS is the contents of the object."
  2693. (format "*%s*" contents))
  2694. ;;;; Citation
  2695. (defun org-element-citation-parser ()
  2696. "Parse citation object at point, if any.
  2697. When at a citation object, return a list whose car is `citation'
  2698. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2699. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2700. keywords. Otherwise, return nil.
  2701. Assume point is at the beginning of the citation."
  2702. (when (looking-at org-element-citation-prefix-re)
  2703. (let* ((begin (point))
  2704. (style (and (match-end 1)
  2705. (match-string-no-properties 1)))
  2706. ;; Ignore blanks between cite type and prefix or key.
  2707. (start (match-end 0))
  2708. (closing (with-syntax-table org-element--pair-square-table
  2709. (ignore-errors (scan-lists begin 1 0)))))
  2710. (save-excursion
  2711. (when (and closing
  2712. (re-search-forward org-element-citation-key-re closing t))
  2713. ;; Find prefix, if any.
  2714. (let ((first-key-end (match-end 0))
  2715. (types (org-element-restriction 'citation-reference))
  2716. (cite
  2717. (list 'citation
  2718. (list :style style
  2719. :begin begin
  2720. :post-blank (progn
  2721. (goto-char closing)
  2722. (skip-chars-forward " \t"))
  2723. :end (point)))))
  2724. ;; `:contents-begin' depends on the presence of
  2725. ;; a non-empty common prefix.
  2726. (goto-char first-key-end)
  2727. (if (not (search-backward ";" start t))
  2728. (org-element-put-property cite :contents-begin start)
  2729. (when (< start (point))
  2730. (org-element-put-property
  2731. cite :prefix
  2732. (org-element--parse-objects start (point) nil types cite)))
  2733. (forward-char)
  2734. (org-element-put-property cite :contents-begin (point)))
  2735. ;; `:contents-end' depends on the presence of a non-empty
  2736. ;; common suffix.
  2737. (goto-char (1- closing))
  2738. (skip-chars-backward " \r\t\n")
  2739. (let ((end (point)))
  2740. (if (or (not (search-backward ";" first-key-end t))
  2741. (re-search-forward org-element-citation-key-re end t))
  2742. (org-element-put-property cite :contents-end end)
  2743. (forward-char)
  2744. (when (< (point) end)
  2745. (org-element-put-property
  2746. cite :suffix
  2747. (org-element--parse-objects (point) end nil types cite)))
  2748. (org-element-put-property cite :contents-end (point))))
  2749. cite))))))
  2750. (defun org-element-citation-interpreter (citation contents)
  2751. "Interpret CITATION object as Org syntax.
  2752. CONTENTS is the contents of the object, as a string."
  2753. (let ((prefix (org-element-property :prefix citation))
  2754. (suffix (org-element-property :suffix citation))
  2755. (style (org-element-property :style citation)))
  2756. (concat "[cite"
  2757. (and style (concat "/" style))
  2758. ":"
  2759. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2760. (if suffix
  2761. (concat contents (org-element-interpret-data suffix))
  2762. ;; Remove spurious semicolon.
  2763. (substring contents nil -1))
  2764. "]")))
  2765. ;;;; Citation Reference
  2766. (defun org-element-citation-reference-parser ()
  2767. "Parse citation reference object at point, if any.
  2768. When at a reference, return a list whose car is
  2769. `citation-reference', and cdr is a plist with `:key',
  2770. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2771. Assume point is at the beginning of the reference."
  2772. (save-excursion
  2773. (let ((begin (point)))
  2774. (when (re-search-forward org-element-citation-key-re nil t)
  2775. (let* ((key (match-string-no-properties 1))
  2776. (key-start (match-beginning 0))
  2777. (key-end (match-end 0))
  2778. (separator (search-forward ";" nil t))
  2779. (end (or separator (point-max)))
  2780. (suffix-end (if separator (1- end) end))
  2781. (types (org-element-restriction 'citation-reference))
  2782. (reference
  2783. (list 'citation-reference
  2784. (list :key key
  2785. :begin begin
  2786. :end end
  2787. :post-blank 0))))
  2788. (when (< begin key-start)
  2789. (org-element-put-property
  2790. reference :prefix
  2791. (org-element--parse-objects begin key-start nil types reference)))
  2792. (when (< key-end suffix-end)
  2793. (org-element-put-property
  2794. reference :suffix
  2795. (org-element--parse-objects key-end suffix-end nil types reference)))
  2796. reference)))))
  2797. (defun org-element-citation-reference-interpreter (citation-reference _)
  2798. "Interpret CITATION-REFERENCE object as Org syntax."
  2799. (concat (org-element-interpret-data
  2800. (org-element-property :prefix citation-reference))
  2801. "@" (org-element-property :key citation-reference)
  2802. (org-element-interpret-data
  2803. (org-element-property :suffix citation-reference))
  2804. ";"))
  2805. ;;;; Code
  2806. (defun org-element-code-parser ()
  2807. "Parse code object at point, if any.
  2808. When at a code object, return a list whose car is `code' and cdr
  2809. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2810. keywords. Otherwise, return nil.
  2811. Assume point is at the first tilde marker."
  2812. (org-element--parse-generic-emphasis "~" 'code))
  2813. (defun org-element-code-interpreter (code _)
  2814. "Interpret CODE object as Org syntax."
  2815. (format "~%s~" (org-element-property :value code)))
  2816. ;;;; Entity
  2817. (defun org-element-entity-parser ()
  2818. "Parse entity at point, if any.
  2819. When at an entity, return a list whose car is `entity' and cdr
  2820. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2821. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2822. `:post-blank' as keywords. Otherwise, return nil.
  2823. Assume point is at the beginning of the entity."
  2824. (catch 'no-object
  2825. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2826. (save-excursion
  2827. (let* ((value (or (org-entity-get (match-string 1))
  2828. (throw 'no-object nil)))
  2829. (begin (match-beginning 0))
  2830. (bracketsp (string= (match-string 2) "{}"))
  2831. (post-blank (progn (goto-char (match-end 1))
  2832. (when bracketsp (forward-char 2))
  2833. (skip-chars-forward " \t")))
  2834. (end (point)))
  2835. (list 'entity
  2836. (list :name (car value)
  2837. :latex (nth 1 value)
  2838. :latex-math-p (nth 2 value)
  2839. :html (nth 3 value)
  2840. :ascii (nth 4 value)
  2841. :latin1 (nth 5 value)
  2842. :utf-8 (nth 6 value)
  2843. :begin begin
  2844. :end end
  2845. :use-brackets-p bracketsp
  2846. :post-blank post-blank)))))))
  2847. (defun org-element-entity-interpreter (entity _)
  2848. "Interpret ENTITY object as Org syntax."
  2849. (concat "\\"
  2850. (org-element-property :name entity)
  2851. (when (org-element-property :use-brackets-p entity) "{}")))
  2852. ;;;; Export Snippet
  2853. (defun org-element-export-snippet-parser ()
  2854. "Parse export snippet at point.
  2855. When at an export snippet, return a list whose car is
  2856. `export-snippet' and cdr a plist with `:begin', `:end',
  2857. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2858. return nil.
  2859. Assume point is at the beginning of the snippet."
  2860. (save-excursion
  2861. (let (contents-end)
  2862. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2863. (setq contents-end
  2864. (save-match-data (goto-char (match-end 0))
  2865. (when
  2866. (re-search-forward "@@" nil t)
  2867. (match-beginning 0)))))
  2868. (let* ((begin (match-beginning 0))
  2869. (back-end (match-string-no-properties 1))
  2870. (value (buffer-substring-no-properties
  2871. (match-end 0) contents-end))
  2872. (post-blank (skip-chars-forward " \t"))
  2873. (end (point)))
  2874. (list 'export-snippet
  2875. (list :back-end back-end
  2876. :value value
  2877. :begin begin
  2878. :end end
  2879. :post-blank post-blank)))))))
  2880. (defun org-element-export-snippet-interpreter (export-snippet _)
  2881. "Interpret EXPORT-SNIPPET object as Org syntax."
  2882. (format "@@%s:%s@@"
  2883. (org-element-property :back-end export-snippet)
  2884. (org-element-property :value export-snippet)))
  2885. ;;;; Footnote Reference
  2886. (defun org-element-footnote-reference-parser ()
  2887. "Parse footnote reference at point, if any.
  2888. When at a footnote reference, return a list whose car is
  2889. `footnote-reference' and cdr a plist with `:label', `:type',
  2890. `:begin', `:end', `:contents-begin', `:contents-end' and
  2891. `:post-blank' as keywords. Otherwise, return nil."
  2892. (when (looking-at org-footnote-re)
  2893. (let ((closing (with-syntax-table org-element--pair-square-table
  2894. (ignore-errors (scan-lists (point) 1 0)))))
  2895. (when closing
  2896. (save-excursion
  2897. (let* ((begin (point))
  2898. (label (match-string-no-properties 1))
  2899. (inner-begin (match-end 0))
  2900. (inner-end (1- closing))
  2901. (type (if (match-end 2) 'inline 'standard))
  2902. (post-blank (progn (goto-char closing)
  2903. (skip-chars-forward " \t")))
  2904. (end (point)))
  2905. (list 'footnote-reference
  2906. (list :label label
  2907. :type type
  2908. :begin begin
  2909. :end end
  2910. :contents-begin (and (eq type 'inline) inner-begin)
  2911. :contents-end (and (eq type 'inline) inner-end)
  2912. :post-blank post-blank))))))))
  2913. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2914. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2915. CONTENTS is its definition, when inline, or nil."
  2916. (format "[fn:%s%s]"
  2917. (or (org-element-property :label footnote-reference) "")
  2918. (if contents (concat ":" contents) "")))
  2919. ;;;; Inline Babel Call
  2920. (defun org-element-inline-babel-call-parser ()
  2921. "Parse inline babel call at point, if any.
  2922. When at an inline babel call, return a list whose car is
  2923. `inline-babel-call' and cdr a plist with `:call',
  2924. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2925. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2926. Assume point is at the beginning of the babel call."
  2927. (save-excursion
  2928. (catch :no-object
  2929. (when (let ((case-fold-search nil))
  2930. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2931. (goto-char (match-end 1))
  2932. (let* ((begin (match-beginning 0))
  2933. (call (match-string-no-properties 1))
  2934. (inside-header
  2935. (let ((p (org-element--parse-paired-brackets ?\[)))
  2936. (and (org-string-nw-p p)
  2937. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2938. (arguments (org-string-nw-p
  2939. (or (org-element--parse-paired-brackets ?\()
  2940. ;; Parenthesis are mandatory.
  2941. (throw :no-object nil))))
  2942. (end-header
  2943. (let ((p (org-element--parse-paired-brackets ?\[)))
  2944. (and (org-string-nw-p p)
  2945. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2946. (value (buffer-substring-no-properties begin (point)))
  2947. (post-blank (skip-chars-forward " \t"))
  2948. (end (point)))
  2949. (list 'inline-babel-call
  2950. (list :call call
  2951. :inside-header inside-header
  2952. :arguments arguments
  2953. :end-header end-header
  2954. :begin begin
  2955. :end end
  2956. :value value
  2957. :post-blank post-blank)))))))
  2958. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2959. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2960. (concat "call_"
  2961. (org-element-property :call inline-babel-call)
  2962. (let ((h (org-element-property :inside-header inline-babel-call)))
  2963. (and h (format "[%s]" h)))
  2964. "(" (org-element-property :arguments inline-babel-call) ")"
  2965. (let ((h (org-element-property :end-header inline-babel-call)))
  2966. (and h (format "[%s]" h)))))
  2967. ;;;; Inline Src Block
  2968. (defun org-element-inline-src-block-parser ()
  2969. "Parse inline source block at point, if any.
  2970. When at an inline source block, return a list whose car is
  2971. `inline-src-block' and cdr a plist with `:begin', `:end',
  2972. `:language', `:value', `:parameters' and `:post-blank' as
  2973. keywords. Otherwise, return nil.
  2974. Assume point is at the beginning of the inline source block."
  2975. (save-excursion
  2976. (catch :no-object
  2977. (when (let ((case-fold-search nil))
  2978. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2979. (goto-char (match-end 1))
  2980. (let ((begin (match-beginning 0))
  2981. (language (match-string-no-properties 1))
  2982. (parameters
  2983. (let ((p (org-element--parse-paired-brackets ?\[)))
  2984. (and (org-string-nw-p p)
  2985. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2986. (value (or (org-element--parse-paired-brackets ?\{)
  2987. (throw :no-object nil)))
  2988. (post-blank (skip-chars-forward " \t")))
  2989. (list 'inline-src-block
  2990. (list :language language
  2991. :value value
  2992. :parameters parameters
  2993. :begin begin
  2994. :end (point)
  2995. :post-blank post-blank)))))))
  2996. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2997. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2998. (let ((language (org-element-property :language inline-src-block))
  2999. (arguments (org-element-property :parameters inline-src-block))
  3000. (body (org-element-property :value inline-src-block)))
  3001. (format "src_%s%s{%s}"
  3002. language
  3003. (if arguments (format "[%s]" arguments) "")
  3004. body)))
  3005. ;;;; Italic
  3006. (defun org-element-italic-parser ()
  3007. "Parse italic object at point, if any.
  3008. When at an italic object, return a list whose car is `italic' and
  3009. cdr is a plist with `:begin', `:end', `:contents-begin' and
  3010. `:contents-end' and `:post-blank' keywords. Otherwise, return
  3011. nil.
  3012. Assume point is at the first slash marker."
  3013. (org-element--parse-generic-emphasis "/" 'italic))
  3014. (defun org-element-italic-interpreter (_ contents)
  3015. "Interpret italic object as Org syntax.
  3016. CONTENTS is the contents of the object."
  3017. (format "/%s/" contents))
  3018. ;;;; Latex Fragment
  3019. (defun org-element-latex-fragment-parser ()
  3020. "Parse LaTeX fragment at point, if any.
  3021. When at a LaTeX fragment, return a list whose car is
  3022. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  3023. and `:post-blank' as keywords. Otherwise, return nil.
  3024. Assume point is at the beginning of the LaTeX fragment."
  3025. (catch 'no-object
  3026. (save-excursion
  3027. (let* ((begin (point))
  3028. (after-fragment
  3029. (cond
  3030. ((not (eq ?$ (char-after)))
  3031. (pcase (char-after (1+ (point)))
  3032. (?\( (search-forward "\\)" nil t))
  3033. (?\[ (search-forward "\\]" nil t))
  3034. (_
  3035. ;; Macro.
  3036. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  3037. \\|\\({[^{}\n]*}\\)\\)*")
  3038. (match-end 0)))))
  3039. ((eq ?$ (char-after (1+ (point))))
  3040. (search-forward "$$" nil t 2))
  3041. (t
  3042. (and (not (eq ?$ (char-before)))
  3043. (not (memq (char-after (1+ (point)))
  3044. '(?\s ?\t ?\n ?, ?. ?\;)))
  3045. (search-forward "$" nil t 2)
  3046. (not (memq (char-before (match-beginning 0))
  3047. '(?\s ?\t ?\n ?, ?.)))
  3048. (looking-at-p
  3049. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  3050. (point)))))
  3051. (post-blank
  3052. (if (not after-fragment) (throw 'no-object nil)
  3053. (goto-char after-fragment)
  3054. (skip-chars-forward " \t")))
  3055. (end (point)))
  3056. (list 'latex-fragment
  3057. (list :value (buffer-substring-no-properties begin after-fragment)
  3058. :begin begin
  3059. :end end
  3060. :post-blank post-blank))))))
  3061. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  3062. "Interpret LATEX-FRAGMENT object as Org syntax."
  3063. (org-element-property :value latex-fragment))
  3064. ;;;; Line Break
  3065. (defun org-element-line-break-parser ()
  3066. "Parse line break at point, if any.
  3067. When at a line break, return a list whose car is `line-break',
  3068. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  3069. Otherwise, return nil.
  3070. Assume point is at the beginning of the line break."
  3071. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  3072. (not (eq (char-before) ?\\)))
  3073. (list 'line-break
  3074. (list :begin (point)
  3075. :end (line-beginning-position 2)
  3076. :post-blank 0))))
  3077. (defun org-element-line-break-interpreter (&rest _)
  3078. "Interpret LINE-BREAK object as Org syntax."
  3079. "\\\\\n")
  3080. ;;;; Link
  3081. (defun org-element-link-parser ()
  3082. "Parse link at point, if any.
  3083. When at a link, return a list whose car is `link' and cdr a plist
  3084. with `:type', `:path', `:format', `:raw-link', `:application',
  3085. `:search-option', `:begin', `:end', `:contents-begin',
  3086. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  3087. nil.
  3088. Assume point is at the beginning of the link."
  3089. (catch 'no-object
  3090. (let ((begin (point))
  3091. end contents-begin contents-end link-end post-blank path type format
  3092. raw-link search-option application)
  3093. (cond
  3094. ;; Type 1: Text targeted from a radio target.
  3095. ((and org-target-link-regexp
  3096. (save-excursion (or (bolp) (backward-char))
  3097. (looking-at org-target-link-regexp)))
  3098. (setq type "radio")
  3099. (setq format 'plain)
  3100. (setq link-end (match-end 1))
  3101. (setq path (match-string-no-properties 1))
  3102. (setq contents-begin (match-beginning 1))
  3103. (setq contents-end (match-end 1)))
  3104. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  3105. ((looking-at org-link-bracket-re)
  3106. (setq format 'bracket)
  3107. (setq contents-begin (match-beginning 2))
  3108. (setq contents-end (match-end 2))
  3109. (setq link-end (match-end 0))
  3110. ;; RAW-LINK is the original link. Decode any encoding.
  3111. ;; Expand any abbreviation in it.
  3112. ;;
  3113. ;; Also treat any newline character and associated
  3114. ;; indentation as a single space character. This is not
  3115. ;; compatible with RFC 3986, which requires to ignore
  3116. ;; them altogether. However, doing so would require
  3117. ;; users to encode spaces on the fly when writing links
  3118. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  3119. ;; [[shell:ls *.org]], which defeats Org's focus on
  3120. ;; simplicity.
  3121. (setq raw-link (org-link-expand-abbrev
  3122. (org-link-unescape
  3123. (replace-regexp-in-string
  3124. "[ \t]*\n[ \t]*" " "
  3125. (match-string-no-properties 1)))))
  3126. ;; Determine TYPE of link and set PATH accordingly. According
  3127. ;; to RFC 3986, remove whitespaces from URI in external links.
  3128. ;; In internal ones, treat indentation as a single space.
  3129. (cond
  3130. ;; File type.
  3131. ((or (file-name-absolute-p raw-link)
  3132. (string-match "\\`\\.\\.?/" raw-link))
  3133. (setq type "file")
  3134. (setq path raw-link))
  3135. ;; Explicit type (http, irc, bbdb...).
  3136. ((string-match org-link-types-re raw-link)
  3137. (setq type (match-string 1 raw-link))
  3138. (setq path (substring raw-link (match-end 0))))
  3139. ;; Code-ref type: PATH is the name of the reference.
  3140. ((and (string-match-p "\\`(" raw-link)
  3141. (string-match-p ")\\'" raw-link))
  3142. (setq type "coderef")
  3143. (setq path (substring raw-link 1 -1)))
  3144. ;; Custom-id type: PATH is the name of the custom id.
  3145. ((= (string-to-char raw-link) ?#)
  3146. (setq type "custom-id")
  3147. (setq path (substring raw-link 1)))
  3148. ;; Fuzzy type: Internal link either matches a target, an
  3149. ;; headline name or nothing. PATH is the target or
  3150. ;; headline's name.
  3151. (t
  3152. (setq type "fuzzy")
  3153. (setq path raw-link))))
  3154. ;; Type 3: Plain link, e.g., https://orgmode.org
  3155. ((looking-at org-link-plain-re)
  3156. (setq format 'plain)
  3157. (setq raw-link (match-string-no-properties 0))
  3158. (setq type (match-string-no-properties 1))
  3159. (setq link-end (match-end 0))
  3160. (setq path (match-string-no-properties 2)))
  3161. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  3162. ;; bracket links, follow RFC 3986 and remove any extra
  3163. ;; whitespace in URI.
  3164. ((looking-at org-link-angle-re)
  3165. (setq format 'angle)
  3166. (setq type (match-string-no-properties 1))
  3167. (setq link-end (match-end 0))
  3168. (setq raw-link
  3169. (buffer-substring-no-properties
  3170. (match-beginning 1) (match-end 2)))
  3171. (setq path (replace-regexp-in-string
  3172. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  3173. (t (throw 'no-object nil)))
  3174. ;; In any case, deduce end point after trailing white space from
  3175. ;; LINK-END variable.
  3176. (save-excursion
  3177. (setq post-blank
  3178. (progn (goto-char link-end) (skip-chars-forward " \t")))
  3179. (setq end (point)))
  3180. ;; Special "file"-type link processing. Extract opening
  3181. ;; application and search option, if any. Also normalize URI.
  3182. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  3183. (setq application (match-string 1 type))
  3184. (setq type "file")
  3185. (when (string-match "::\\(.*\\)\\'" path)
  3186. (setq search-option (match-string 1 path))
  3187. (setq path (replace-match "" nil nil path)))
  3188. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3189. ;; Translate link, if `org-link-translation-function' is set.
  3190. (let ((trans (and (functionp org-link-translation-function)
  3191. (funcall org-link-translation-function type path))))
  3192. (when trans
  3193. (setq type (car trans))
  3194. (setq path (cdr trans))))
  3195. (list 'link
  3196. (list :type type
  3197. :path path
  3198. :format format
  3199. :raw-link (or raw-link path)
  3200. :application application
  3201. :search-option search-option
  3202. :begin begin
  3203. :end end
  3204. :contents-begin contents-begin
  3205. :contents-end contents-end
  3206. :post-blank post-blank)))))
  3207. (defun org-element-link-interpreter (link contents)
  3208. "Interpret LINK object as Org syntax.
  3209. CONTENTS is the contents of the object, or nil."
  3210. (let ((type (org-element-property :type link))
  3211. (path (org-element-property :path link)))
  3212. (if (string= type "radio") path
  3213. (let ((fmt (pcase (org-element-property :format link)
  3214. ;; Links with contents and internal links have to
  3215. ;; use bracket syntax. Ignore `:format' in these
  3216. ;; cases. This is also the default syntax when the
  3217. ;; property is not defined, e.g., when the object
  3218. ;; was crafted by the user.
  3219. ((guard contents)
  3220. (format "[[%%s][%s]]"
  3221. ;; Since this is going to be used as
  3222. ;; a format string, escape percent signs
  3223. ;; in description.
  3224. (replace-regexp-in-string "%" "%%" contents)))
  3225. ((or `bracket
  3226. `nil
  3227. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3228. "[[%s]]")
  3229. ;; Otherwise, just obey to `:format'.
  3230. (`angle "<%s>")
  3231. (`plain "%s")
  3232. (f (error "Wrong `:format' value: %s" f)))))
  3233. (format fmt
  3234. (pcase type
  3235. ("coderef" (format "(%s)" path))
  3236. ("custom-id" (concat "#" path))
  3237. ("file"
  3238. (let ((app (org-element-property :application link))
  3239. (opt (org-element-property :search-option link)))
  3240. (concat type (and app (concat "+" app)) ":"
  3241. path
  3242. (and opt (concat "::" opt)))))
  3243. ("fuzzy" path)
  3244. (_ (concat type ":" path))))))))
  3245. ;;;; Macro
  3246. (defun org-element-macro-parser ()
  3247. "Parse macro at point, if any.
  3248. When at a macro, return a list whose car is `macro' and cdr
  3249. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3250. `:post-blank' as keywords. Otherwise, return nil.
  3251. Assume point is at the macro."
  3252. (save-excursion
  3253. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3254. (let ((begin (point))
  3255. (key (downcase (match-string-no-properties 1)))
  3256. (value (match-string-no-properties 0))
  3257. (post-blank (progn (goto-char (match-end 0))
  3258. (skip-chars-forward " \t")))
  3259. (end (point))
  3260. (args (pcase (match-string-no-properties 3)
  3261. (`nil nil)
  3262. (a (org-macro-extract-arguments
  3263. (replace-regexp-in-string
  3264. "[ \t\r\n]+" " " (org-trim a)))))))
  3265. (list 'macro
  3266. (list :key key
  3267. :value value
  3268. :args args
  3269. :begin begin
  3270. :end end
  3271. :post-blank post-blank))))))
  3272. (defun org-element-macro-interpreter (macro _)
  3273. "Interpret MACRO object as Org syntax."
  3274. (format "{{{%s%s}}}"
  3275. (org-element-property :key macro)
  3276. (pcase (org-element-property :args macro)
  3277. (`nil "")
  3278. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3279. ;;;; Radio-target
  3280. (defun org-element-radio-target-parser ()
  3281. "Parse radio target at point, if any.
  3282. When at a radio target, return a list whose car is `radio-target'
  3283. and cdr a plist with `:begin', `:end', `:contents-begin',
  3284. `:contents-end', `:value' and `:post-blank' as keywords.
  3285. Otherwise, return nil.
  3286. Assume point is at the radio target."
  3287. (save-excursion
  3288. (when (looking-at org-radio-target-regexp)
  3289. (let ((begin (point))
  3290. (contents-begin (match-beginning 1))
  3291. (contents-end (match-end 1))
  3292. (value (match-string-no-properties 1))
  3293. (post-blank (progn (goto-char (match-end 0))
  3294. (skip-chars-forward " \t")))
  3295. (end (point)))
  3296. (list 'radio-target
  3297. (list :begin begin
  3298. :end end
  3299. :contents-begin contents-begin
  3300. :contents-end contents-end
  3301. :post-blank post-blank
  3302. :value value))))))
  3303. (defun org-element-radio-target-interpreter (_ contents)
  3304. "Interpret target object as Org syntax.
  3305. CONTENTS is the contents of the object."
  3306. (concat "<<<" contents ">>>"))
  3307. ;;;; Statistics Cookie
  3308. (defun org-element-statistics-cookie-parser ()
  3309. "Parse statistics cookie at point, if any.
  3310. When at a statistics cookie, return a list whose car is
  3311. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3312. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3313. Assume point is at the beginning of the statistics-cookie."
  3314. (save-excursion
  3315. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3316. (let* ((begin (point))
  3317. (value (buffer-substring-no-properties
  3318. (match-beginning 0) (match-end 0)))
  3319. (post-blank (progn (goto-char (match-end 0))
  3320. (skip-chars-forward " \t")))
  3321. (end (point)))
  3322. (list 'statistics-cookie
  3323. (list :begin begin
  3324. :end end
  3325. :value value
  3326. :post-blank post-blank))))))
  3327. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3328. "Interpret STATISTICS-COOKIE object as Org syntax."
  3329. (org-element-property :value statistics-cookie))
  3330. ;;;; Strike-Through
  3331. (defun org-element-strike-through-parser ()
  3332. "Parse strike-through object at point, if any.
  3333. When at a strike-through object, return a list whose car is
  3334. `strike-through' and cdr is a plist with `:begin', `:end',
  3335. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3336. Otherwise, return nil.
  3337. Assume point is at the first plus sign marker."
  3338. (org-element--parse-generic-emphasis "+" 'strike-through))
  3339. (defun org-element-strike-through-interpreter (_ contents)
  3340. "Interpret strike-through object as Org syntax.
  3341. CONTENTS is the contents of the object."
  3342. (format "+%s+" contents))
  3343. ;;;; Subscript
  3344. (defun org-element-subscript-parser ()
  3345. "Parse subscript at point, if any.
  3346. When at a subscript object, return a list whose car is
  3347. `subscript' and cdr a plist with `:begin', `:end',
  3348. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3349. `:post-blank' as keywords. Otherwise, return nil.
  3350. Assume point is at the underscore."
  3351. (save-excursion
  3352. (unless (bolp) (backward-char))
  3353. (when (looking-at org-match-substring-regexp)
  3354. (let ((bracketsp (match-beginning 4))
  3355. (begin (match-beginning 2))
  3356. (contents-begin (or (match-beginning 4)
  3357. (match-beginning 3)))
  3358. (contents-end (or (match-end 4) (match-end 3)))
  3359. (post-blank (progn (goto-char (match-end 0))
  3360. (skip-chars-forward " \t")))
  3361. (end (point)))
  3362. (list 'subscript
  3363. (list :begin begin
  3364. :end end
  3365. :use-brackets-p bracketsp
  3366. :contents-begin contents-begin
  3367. :contents-end contents-end
  3368. :post-blank post-blank))))))
  3369. (defun org-element-subscript-interpreter (subscript contents)
  3370. "Interpret SUBSCRIPT object as Org syntax.
  3371. CONTENTS is the contents of the object."
  3372. (format
  3373. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3374. contents))
  3375. ;;;; Superscript
  3376. (defun org-element-superscript-parser ()
  3377. "Parse superscript at point, if any.
  3378. When at a superscript object, return a list whose car is
  3379. `superscript' and cdr a plist with `:begin', `:end',
  3380. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3381. `:post-blank' as keywords. Otherwise, return nil.
  3382. Assume point is at the caret."
  3383. (save-excursion
  3384. (unless (bolp) (backward-char))
  3385. (when (looking-at org-match-substring-regexp)
  3386. (let ((bracketsp (match-beginning 4))
  3387. (begin (match-beginning 2))
  3388. (contents-begin (or (match-beginning 4)
  3389. (match-beginning 3)))
  3390. (contents-end (or (match-end 4) (match-end 3)))
  3391. (post-blank (progn (goto-char (match-end 0))
  3392. (skip-chars-forward " \t")))
  3393. (end (point)))
  3394. (list 'superscript
  3395. (list :begin begin
  3396. :end end
  3397. :use-brackets-p bracketsp
  3398. :contents-begin contents-begin
  3399. :contents-end contents-end
  3400. :post-blank post-blank))))))
  3401. (defun org-element-superscript-interpreter (superscript contents)
  3402. "Interpret SUPERSCRIPT object as Org syntax.
  3403. CONTENTS is the contents of the object."
  3404. (format
  3405. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3406. contents))
  3407. ;;;; Table Cell
  3408. (defun org-element-table-cell-parser ()
  3409. "Parse table cell at point.
  3410. Return a list whose car is `table-cell' and cdr is a plist
  3411. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3412. and `:post-blank' keywords."
  3413. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3414. (let* ((begin (match-beginning 0))
  3415. (end (match-end 0))
  3416. (contents-begin (match-beginning 1))
  3417. (contents-end (match-end 1)))
  3418. (list 'table-cell
  3419. (list :begin begin
  3420. :end end
  3421. :contents-begin contents-begin
  3422. :contents-end contents-end
  3423. :post-blank 0))))
  3424. (defun org-element-table-cell-interpreter (_ contents)
  3425. "Interpret table-cell element as Org syntax.
  3426. CONTENTS is the contents of the cell, or nil."
  3427. (concat " " contents " |"))
  3428. ;;;; Target
  3429. (defun org-element-target-parser ()
  3430. "Parse target at point, if any.
  3431. When at a target, return a list whose car is `target' and cdr
  3432. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3433. keywords. Otherwise, return nil.
  3434. Assume point is at the target."
  3435. (save-excursion
  3436. (when (looking-at org-target-regexp)
  3437. (let ((begin (point))
  3438. (value (match-string-no-properties 1))
  3439. (post-blank (progn (goto-char (match-end 0))
  3440. (skip-chars-forward " \t")))
  3441. (end (point)))
  3442. (list 'target
  3443. (list :begin begin
  3444. :end end
  3445. :value value
  3446. :post-blank post-blank))))))
  3447. (defun org-element-target-interpreter (target _)
  3448. "Interpret TARGET object as Org syntax."
  3449. (format "<<%s>>" (org-element-property :value target)))
  3450. ;;;; Timestamp
  3451. (defconst org-element--timestamp-regexp
  3452. (concat org-ts-regexp-both
  3453. "\\|"
  3454. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3455. "\\|"
  3456. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3457. "Regexp matching any timestamp type object.")
  3458. (defun org-element-timestamp-parser ()
  3459. "Parse time stamp at point, if any.
  3460. When at a time stamp, return a list whose car is `timestamp', and
  3461. cdr a plist with `:type', `:raw-value', `:year-start',
  3462. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3463. `:year-end', `:month-end', `:day-end', `:hour-end',
  3464. `:minute-end', `:repeater-type', `:repeater-value',
  3465. `:repeater-unit', `:warning-type', `:warning-value',
  3466. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3467. Otherwise, return nil.
  3468. Assume point is at the beginning of the timestamp."
  3469. (when (looking-at-p org-element--timestamp-regexp)
  3470. (save-excursion
  3471. (let* ((begin (point))
  3472. (activep (eq (char-after) ?<))
  3473. (raw-value
  3474. (progn
  3475. (looking-at (concat "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\("
  3476. org-ts-regexp-both
  3477. "\\)\\)?"))
  3478. (match-string-no-properties 0)))
  3479. (date-start (match-string-no-properties 1))
  3480. (date-end (match-string 3))
  3481. (diaryp (match-beginning 2))
  3482. (post-blank (progn (goto-char (match-end 0))
  3483. (skip-chars-forward " \t")))
  3484. (end (point))
  3485. (time-range
  3486. (and (not diaryp)
  3487. (string-match
  3488. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3489. date-start)
  3490. (cons (string-to-number (match-string 2 date-start))
  3491. (string-to-number (match-string 3 date-start)))))
  3492. (type (cond (diaryp 'diary)
  3493. ((and activep (or date-end time-range)) 'active-range)
  3494. (activep 'active)
  3495. ((or date-end time-range) 'inactive-range)
  3496. (t 'inactive)))
  3497. (repeater-props
  3498. (and (not diaryp)
  3499. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3500. raw-value)
  3501. (list
  3502. :repeater-type
  3503. (let ((type (match-string 1 raw-value)))
  3504. (cond ((equal "++" type) 'catch-up)
  3505. ((equal ".+" type) 'restart)
  3506. (t 'cumulate)))
  3507. :repeater-value (string-to-number (match-string 2 raw-value))
  3508. :repeater-unit
  3509. (pcase (string-to-char (match-string 3 raw-value))
  3510. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3511. (warning-props
  3512. (and (not diaryp)
  3513. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3514. (list
  3515. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3516. :warning-value (string-to-number (match-string 2 raw-value))
  3517. :warning-unit
  3518. (pcase (string-to-char (match-string 3 raw-value))
  3519. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3520. year-start month-start day-start hour-start minute-start year-end
  3521. month-end day-end hour-end minute-end)
  3522. ;; Parse date-start.
  3523. (unless diaryp
  3524. (let ((date (org-parse-time-string date-start t)))
  3525. (setq year-start (nth 5 date)
  3526. month-start (nth 4 date)
  3527. day-start (nth 3 date)
  3528. hour-start (nth 2 date)
  3529. minute-start (nth 1 date))))
  3530. ;; Compute date-end. It can be provided directly in time-stamp,
  3531. ;; or extracted from time range. Otherwise, it defaults to the
  3532. ;; same values as date-start.
  3533. (unless diaryp
  3534. (let ((date (and date-end (org-parse-time-string date-end t))))
  3535. (setq year-end (or (nth 5 date) year-start)
  3536. month-end (or (nth 4 date) month-start)
  3537. day-end (or (nth 3 date) day-start)
  3538. hour-end (or (nth 2 date) (car time-range) hour-start)
  3539. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3540. (list 'timestamp
  3541. (nconc (list :type type
  3542. :raw-value raw-value
  3543. :year-start year-start
  3544. :month-start month-start
  3545. :day-start day-start
  3546. :hour-start hour-start
  3547. :minute-start minute-start
  3548. :year-end year-end
  3549. :month-end month-end
  3550. :day-end day-end
  3551. :hour-end hour-end
  3552. :minute-end minute-end
  3553. :begin begin
  3554. :end end
  3555. :post-blank post-blank)
  3556. repeater-props
  3557. warning-props))))))
  3558. (defun org-element-timestamp-interpreter (timestamp _)
  3559. "Interpret TIMESTAMP object as Org syntax."
  3560. (let* ((repeat-string
  3561. (concat
  3562. (pcase (org-element-property :repeater-type timestamp)
  3563. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3564. (let ((val (org-element-property :repeater-value timestamp)))
  3565. (and val (number-to-string val)))
  3566. (pcase (org-element-property :repeater-unit timestamp)
  3567. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3568. (warning-string
  3569. (concat
  3570. (pcase (org-element-property :warning-type timestamp)
  3571. (`first "--") (`all "-"))
  3572. (let ((val (org-element-property :warning-value timestamp)))
  3573. (and val (number-to-string val)))
  3574. (pcase (org-element-property :warning-unit timestamp)
  3575. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3576. (build-ts-string
  3577. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3578. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3579. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3580. ;; specify a time range in the timestamp. REPEAT-STRING is
  3581. ;; the repeater string, if any.
  3582. (lambda (time activep &optional with-time-p hour-end minute-end)
  3583. (let ((ts (format-time-string
  3584. (funcall (if with-time-p #'cdr #'car)
  3585. org-time-stamp-formats)
  3586. time)))
  3587. (when (and hour-end minute-end)
  3588. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3589. (setq ts
  3590. (replace-match
  3591. (format "\\&-%02d:%02d" hour-end minute-end)
  3592. nil nil ts)))
  3593. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3594. (dolist (s (list repeat-string warning-string))
  3595. (when (org-string-nw-p s)
  3596. (setq ts (concat (substring ts 0 -1)
  3597. " "
  3598. s
  3599. (substring ts -1)))))
  3600. ;; Return value.
  3601. ts)))
  3602. (type (org-element-property :type timestamp)))
  3603. (pcase type
  3604. ((or `active `inactive)
  3605. (let* ((minute-start (org-element-property :minute-start timestamp))
  3606. (minute-end (org-element-property :minute-end timestamp))
  3607. (hour-start (org-element-property :hour-start timestamp))
  3608. (hour-end (org-element-property :hour-end timestamp))
  3609. (time-range-p (and hour-start hour-end minute-start minute-end
  3610. (or (/= hour-start hour-end)
  3611. (/= minute-start minute-end)))))
  3612. (funcall
  3613. build-ts-string
  3614. (encode-time 0
  3615. (or minute-start 0)
  3616. (or hour-start 0)
  3617. (org-element-property :day-start timestamp)
  3618. (org-element-property :month-start timestamp)
  3619. (org-element-property :year-start timestamp))
  3620. (eq type 'active)
  3621. (and hour-start minute-start)
  3622. (and time-range-p hour-end)
  3623. (and time-range-p minute-end))))
  3624. ((or `active-range `inactive-range)
  3625. (let ((minute-start (org-element-property :minute-start timestamp))
  3626. (minute-end (org-element-property :minute-end timestamp))
  3627. (hour-start (org-element-property :hour-start timestamp))
  3628. (hour-end (org-element-property :hour-end timestamp)))
  3629. (concat
  3630. (funcall
  3631. build-ts-string (encode-time
  3632. 0
  3633. (or minute-start 0)
  3634. (or hour-start 0)
  3635. (org-element-property :day-start timestamp)
  3636. (org-element-property :month-start timestamp)
  3637. (org-element-property :year-start timestamp))
  3638. (eq type 'active-range)
  3639. (and hour-start minute-start))
  3640. "--"
  3641. (funcall build-ts-string
  3642. (encode-time 0
  3643. (or minute-end 0)
  3644. (or hour-end 0)
  3645. (org-element-property :day-end timestamp)
  3646. (org-element-property :month-end timestamp)
  3647. (org-element-property :year-end timestamp))
  3648. (eq type 'active-range)
  3649. (and hour-end minute-end)))))
  3650. (_ (org-element-property :raw-value timestamp)))))
  3651. ;;;; Underline
  3652. (defun org-element-underline-parser ()
  3653. "Parse underline object at point, if any.
  3654. When at an underline object, return a list whose car is
  3655. `underline' and cdr is a plist with `:begin', `:end',
  3656. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3657. Otherwise, return nil.
  3658. Assume point is at the first underscore marker."
  3659. (org-element--parse-generic-emphasis "_" 'underline))
  3660. (defun org-element-underline-interpreter (_ contents)
  3661. "Interpret underline object as Org syntax.
  3662. CONTENTS is the contents of the object."
  3663. (format "_%s_" contents))
  3664. ;;;; Verbatim
  3665. (defun org-element-verbatim-parser ()
  3666. "Parse verbatim object at point, if any.
  3667. When at a verbatim object, return a list whose car is `verbatim'
  3668. and cdr is a plist with `:value', `:begin', `:end' and
  3669. `:post-blank' keywords. Otherwise, return nil.
  3670. Assume point is at the first equal sign marker."
  3671. (org-element--parse-generic-emphasis "=" 'verbatim))
  3672. (defun org-element-verbatim-interpreter (verbatim _)
  3673. "Interpret VERBATIM object as Org syntax."
  3674. (format "=%s=" (org-element-property :value verbatim)))
  3675. ;;; Parsing Element Starting At Point
  3676. ;;
  3677. ;; `org-element--current-element' is the core function of this section.
  3678. ;; It returns the Lisp representation of the element starting at
  3679. ;; point.
  3680. (defvar org-element--cache-sync-requests); Declared later
  3681. (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
  3682. "Parse the element starting at point.
  3683. Return value is a list like (TYPE PROPS) where TYPE is the type
  3684. of the element and PROPS a plist of properties associated to the
  3685. element.
  3686. Possible types are defined in `org-element-all-elements'.
  3687. LIMIT bounds the search.
  3688. Optional argument GRANULARITY determines the depth of the
  3689. recursion. Allowed values are `headline', `greater-element',
  3690. `element', `object' or nil. When it is broader than `object' (or
  3691. nil), secondary values will not be parsed, since they only
  3692. contain objects.
  3693. Optional argument MODE, when non-nil, can be either
  3694. `first-section', `item', `node-property', `planning',
  3695. `property-drawer', `section', `table-row', or `top-comment'.
  3696. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3697. computed.
  3698. Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
  3699. will also add current element to cache if it is not yet there. Use
  3700. this argument with care, as validity of the element in parse tree is
  3701. not checked.
  3702. This function assumes point is always at the beginning of the
  3703. element it has to parse."
  3704. (let* ((element (and (not (buffer-narrowed-p))
  3705. (org-element--cache-active-p)
  3706. (not org-element--cache-sync-requests)
  3707. (org-element--cache-find (point) t)))
  3708. (element (progn (while (and element
  3709. (not (and (eq (point) (org-element-property :begin element))
  3710. (eq mode (org-element-property :mode element)))))
  3711. (setq element (org-element-property :parent element)))
  3712. element))
  3713. (old-element element)
  3714. (element (when
  3715. (pcase (org-element-property :granularity element)
  3716. (`nil t)
  3717. (`object t)
  3718. (`element (not (memq granularity '(nil object))))
  3719. (`greater-element (not (memq granularity '(nil object element))))
  3720. (`headline (eq granularity 'headline)))
  3721. element)))
  3722. (if element
  3723. element
  3724. (save-excursion
  3725. (let ((case-fold-search t)
  3726. ;; Determine if parsing depth allows for secondary strings
  3727. ;; parsing. It only applies to elements referenced in
  3728. ;; `org-element-secondary-value-alist'.
  3729. (raw-secondary-p (and granularity (not (eq granularity 'object))))
  3730. result)
  3731. (setq
  3732. result
  3733. (cond
  3734. ;; Item.
  3735. ((eq mode 'item)
  3736. (org-element-item-parser limit structure raw-secondary-p))
  3737. ;; Table Row.
  3738. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3739. ;; Node Property.
  3740. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3741. ;; Headline.
  3742. ((org-with-limited-levels (looking-at-p org-outline-regexp-bol))
  3743. (org-element-headline-parser limit raw-secondary-p))
  3744. ;; Sections (must be checked after headline).
  3745. ((eq mode 'section) (org-element-section-parser limit))
  3746. ((eq mode 'first-section)
  3747. (org-element-section-parser
  3748. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3749. limit)))
  3750. ;; Comments.
  3751. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3752. (org-element-comment-parser limit))
  3753. ;; Planning.
  3754. ((and (eq mode 'planning)
  3755. (eq ?* (char-after (line-beginning-position 0)))
  3756. (looking-at org-element-planning-line-re))
  3757. (org-element-planning-parser limit))
  3758. ;; Property drawer.
  3759. ((and (pcase mode
  3760. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3761. ((or `property-drawer `top-comment)
  3762. (save-excursion
  3763. (beginning-of-line 0)
  3764. (not (looking-at "[[:blank:]]*$"))))
  3765. (_ nil))
  3766. (looking-at org-property-drawer-re))
  3767. (org-element-property-drawer-parser limit))
  3768. ;; When not at bol, point is at the beginning of an item or
  3769. ;; a footnote definition: next item is always a paragraph.
  3770. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3771. ;; Clock.
  3772. ((looking-at org-element-clock-line-re)
  3773. (org-element-clock-parser limit))
  3774. ;; Inlinetask.
  3775. ((looking-at "^\\*+ ")
  3776. (org-element-inlinetask-parser limit raw-secondary-p))
  3777. ;; From there, elements can have affiliated keywords.
  3778. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3779. limit (memq granularity '(nil object)))))
  3780. (cond
  3781. ;; Jumping over affiliated keywords put point off-limits.
  3782. ;; Parse them as regular keywords.
  3783. ((and (cdr affiliated) (>= (point) limit))
  3784. (goto-char (car affiliated))
  3785. (org-element-keyword-parser limit nil))
  3786. ;; LaTeX Environment.
  3787. ((looking-at org-element--latex-begin-environment)
  3788. (org-element-latex-environment-parser limit affiliated))
  3789. ;; Drawer.
  3790. ((looking-at org-element-drawer-re)
  3791. (org-element-drawer-parser limit affiliated))
  3792. ;; Fixed Width
  3793. ((looking-at "[ \t]*:\\( \\|$\\)")
  3794. (org-element-fixed-width-parser limit affiliated))
  3795. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3796. ;; Keywords.
  3797. ((looking-at "[ \t]*#\\+")
  3798. (goto-char (match-end 0))
  3799. (cond
  3800. ((looking-at "BEGIN_\\(\\S-+\\)")
  3801. (beginning-of-line)
  3802. (funcall (pcase (upcase (match-string 1))
  3803. ("CENTER" #'org-element-center-block-parser)
  3804. ("COMMENT" #'org-element-comment-block-parser)
  3805. ("EXAMPLE" #'org-element-example-block-parser)
  3806. ("EXPORT" #'org-element-export-block-parser)
  3807. ("QUOTE" #'org-element-quote-block-parser)
  3808. ("SRC" #'org-element-src-block-parser)
  3809. ("VERSE" #'org-element-verse-block-parser)
  3810. (_ #'org-element-special-block-parser))
  3811. limit
  3812. affiliated))
  3813. ((looking-at "CALL:")
  3814. (beginning-of-line)
  3815. (org-element-babel-call-parser limit affiliated))
  3816. ((save-excursion
  3817. (beginning-of-line)
  3818. (looking-at org-element-dynamic-block-open-re))
  3819. (beginning-of-line)
  3820. (org-element-dynamic-block-parser limit affiliated))
  3821. ((looking-at "\\S-+:")
  3822. (beginning-of-line)
  3823. (org-element-keyword-parser limit affiliated))
  3824. (t
  3825. (beginning-of-line)
  3826. (org-element-paragraph-parser limit affiliated))))
  3827. ;; Footnote Definition.
  3828. ((looking-at org-footnote-definition-re)
  3829. (org-element-footnote-definition-parser limit affiliated))
  3830. ;; Horizontal Rule.
  3831. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3832. (org-element-horizontal-rule-parser limit affiliated))
  3833. ;; Diary Sexp.
  3834. ((looking-at "%%(")
  3835. (org-element-diary-sexp-parser limit affiliated))
  3836. ;; Table.
  3837. ((or (looking-at "[ \t]*|")
  3838. ;; There is no strict definition of a table.el
  3839. ;; table. Try to prevent false positive while being
  3840. ;; quick.
  3841. (let ((rule-regexp
  3842. (rx (zero-or-more (any " \t"))
  3843. "+"
  3844. (one-or-more (one-or-more "-") "+")
  3845. (zero-or-more (any " \t"))
  3846. eol))
  3847. (non-table.el-line
  3848. (rx bol
  3849. (zero-or-more (any " \t"))
  3850. (or eol (not (any "+| \t")))))
  3851. (next (line-beginning-position 2)))
  3852. ;; Start with a full rule.
  3853. (and
  3854. (looking-at rule-regexp)
  3855. (< next limit) ;no room for a table.el table
  3856. (save-excursion
  3857. (end-of-line)
  3858. (cond
  3859. ;; Must end with a full rule.
  3860. ((not (re-search-forward non-table.el-line limit 'move))
  3861. (if (bolp) (forward-line -1) (beginning-of-line))
  3862. (looking-at rule-regexp))
  3863. ;; Ignore pseudo-tables with a single
  3864. ;; rule.
  3865. ((= next (line-beginning-position))
  3866. nil)
  3867. ;; Must end with a full rule.
  3868. (t
  3869. (forward-line -1)
  3870. (looking-at rule-regexp)))))))
  3871. (org-element-table-parser limit affiliated))
  3872. ;; List.
  3873. ((looking-at (org-item-re))
  3874. (org-element-plain-list-parser
  3875. limit affiliated
  3876. (or structure (org-element--list-struct limit))))
  3877. ;; Default element: Paragraph.
  3878. (t (org-element-paragraph-parser limit affiliated)))))))
  3879. (when result
  3880. (org-element-put-property result :mode mode)
  3881. (org-element-put-property result :granularity granularity))
  3882. (when (and (not (buffer-narrowed-p))
  3883. (org-element--cache-active-p)
  3884. (not org-element--cache-sync-requests)
  3885. add-to-cache)
  3886. (if (not old-element)
  3887. (setq result (org-element--cache-put result))
  3888. (org-element-set-element old-element result)
  3889. (setq result old-element)))
  3890. result)))))
  3891. ;; Most elements can have affiliated keywords. When looking for an
  3892. ;; element beginning, we want to move before them, as they belong to
  3893. ;; that element, and, in the meantime, collect information they give
  3894. ;; into appropriate properties. Hence the following function.
  3895. (defun org-element--collect-affiliated-keywords (limit parse)
  3896. "Collect affiliated keywords from point down to LIMIT.
  3897. Return a list whose CAR is the position at the first of them and
  3898. CDR a plist of keywords and values and move point to the
  3899. beginning of the first line after them.
  3900. As a special case, if element doesn't start at the beginning of
  3901. the line (e.g., a paragraph starting an item), CAR is current
  3902. position of point and CDR is nil.
  3903. When PARSE is non-nil, values from keywords belonging to
  3904. `org-element-parsed-keywords' are parsed as secondary strings."
  3905. (if (not (bolp)) (list (point))
  3906. (let ((case-fold-search t)
  3907. (origin (point))
  3908. ;; RESTRICT is the list of objects allowed in parsed
  3909. ;; keywords value. If PARSE is nil, no object is allowed.
  3910. (restrict (and parse (org-element-restriction 'keyword)))
  3911. output)
  3912. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3913. (let* ((raw-kwd (upcase (match-string 1)))
  3914. ;; Apply translation to RAW-KWD. From there, KWD is
  3915. ;; the official keyword.
  3916. (kwd (or (cdr (assoc raw-kwd
  3917. org-element-keyword-translation-alist))
  3918. raw-kwd))
  3919. ;; PARSED? is non-nil when keyword should have its
  3920. ;; value parsed.
  3921. (parsed? (member kwd org-element-parsed-keywords))
  3922. ;; Find main value for any keyword.
  3923. (value
  3924. (let ((beg (match-end 0))
  3925. (end (save-excursion
  3926. (end-of-line)
  3927. (skip-chars-backward " \t")
  3928. (point))))
  3929. (if parsed?
  3930. (save-match-data
  3931. (org-element--parse-objects beg end nil restrict))
  3932. (org-trim (buffer-substring-no-properties beg end)))))
  3933. ;; If KWD is a dual keyword, find its secondary value.
  3934. ;; Maybe parse it.
  3935. (dual? (member kwd org-element-dual-keywords))
  3936. (dual-value
  3937. (and dual?
  3938. (let ((sec (match-string-no-properties 2)))
  3939. (cond
  3940. ((and sec parsed?)
  3941. (save-match-data
  3942. (org-element--parse-objects
  3943. (match-beginning 2) (match-end 2) nil restrict)))
  3944. (sec sec)))))
  3945. ;; Attribute a property name to KWD.
  3946. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3947. ;; Now set final shape for VALUE.
  3948. (when dual?
  3949. (setq value (and (or value dual-value) (cons value dual-value))))
  3950. (when (or (member kwd org-element-multiple-keywords)
  3951. ;; Attributes can always appear on multiple lines.
  3952. (string-match "^ATTR_" kwd))
  3953. (setq value (cons value (plist-get output kwd-sym))))
  3954. ;; Eventually store the new value in OUTPUT.
  3955. (setq output (plist-put output kwd-sym value))
  3956. ;; Move to next keyword.
  3957. (forward-line)))
  3958. ;; If affiliated keywords are orphaned: move back to first one.
  3959. ;; They will be parsed as a paragraph.
  3960. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3961. ;; Return value.
  3962. (cons origin output))))
  3963. ;;; The Org Parser
  3964. ;;
  3965. ;; The two major functions here are `org-element-parse-buffer', which
  3966. ;; parses Org syntax inside the current buffer, taking into account
  3967. ;; region, narrowing, or even visibility if specified, and
  3968. ;; `org-element-parse-secondary-string', which parses objects within
  3969. ;; a given string.
  3970. ;;
  3971. ;; The (almost) almighty `org-element-map' allows applying a function
  3972. ;; on elements or objects matching some type, and accumulating the
  3973. ;; resulting values. In an export situation, it also skips unneeded
  3974. ;; parts of the parse tree.
  3975. (defun org-element-parse-buffer (&optional granularity visible-only)
  3976. "Recursively parse the buffer and return structure.
  3977. If narrowing is in effect, only parse the visible part of the
  3978. buffer.
  3979. Optional argument GRANULARITY determines the depth of the
  3980. recursion. It can be set to the following symbols:
  3981. `headline' Only parse headlines.
  3982. `greater-element' Don't recurse into greater elements except
  3983. headlines and sections. Thus, elements
  3984. parsed are the top-level ones.
  3985. `element' Parse everything but objects and plain text.
  3986. `object' Parse the complete buffer (default).
  3987. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3988. elements.
  3989. An element or object is represented as a list with the
  3990. pattern (TYPE PROPERTIES CONTENTS), where :
  3991. TYPE is a symbol describing the element or object. See
  3992. `org-element-all-elements' and `org-element-all-objects' for an
  3993. exhaustive list of such symbols. One can retrieve it with
  3994. `org-element-type' function.
  3995. PROPERTIES is the list of attributes attached to the element or
  3996. object, as a plist. Although most of them are specific to the
  3997. element or object type, all types share `:begin', `:end',
  3998. `:post-blank' and `:parent' properties, which respectively
  3999. refer to buffer position where the element or object starts,
  4000. ends, the number of white spaces or blank lines after it, and
  4001. the element or object containing it. Properties values can be
  4002. obtained by using `org-element-property' function.
  4003. CONTENTS is a list of elements, objects or raw strings
  4004. contained in the current element or object, when applicable.
  4005. One can access them with `org-element-contents' function.
  4006. The Org buffer has `org-data' as type and nil as properties.
  4007. `org-element-map' function can be used to find specific elements
  4008. or objects within the parse tree.
  4009. This function assumes that current major mode is `org-mode'."
  4010. (save-excursion
  4011. (goto-char (point-min))
  4012. (let ((org-data (org-element-org-data-parser))
  4013. (gc-cons-threshold #x40000000))
  4014. (org-skip-whitespace)
  4015. (org-element--parse-elements
  4016. (point-at-bol) (point-max)
  4017. ;; Start in `first-section' mode so text before the first
  4018. ;; headline belongs to a section.
  4019. 'first-section nil granularity visible-only org-data))))
  4020. (defun org-element-parse-secondary-string (string restriction &optional parent)
  4021. "Recursively parse objects in STRING and return structure.
  4022. RESTRICTION is a symbol limiting the object types that will be
  4023. looked after.
  4024. Optional argument PARENT, when non-nil, is the element or object
  4025. containing the secondary string. It is used to set correctly
  4026. `:parent' property within the string.
  4027. If STRING is the empty string or nil, return nil."
  4028. (cond
  4029. ((not string) nil)
  4030. ((equal string "") nil)
  4031. (t (let ((local-variables (buffer-local-variables)))
  4032. (with-temp-buffer
  4033. (dolist (v local-variables)
  4034. (ignore-errors
  4035. (if (symbolp v) (makunbound v)
  4036. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  4037. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  4038. (set (make-local-variable (car v)) (cdr v))))))
  4039. ;; Transferring local variables may put the temporary buffer
  4040. ;; into a read-only state. Make sure we can insert STRING.
  4041. (let ((inhibit-read-only t)) (insert string))
  4042. ;; Prevent "Buffer *temp* modified; kill anyway?".
  4043. (restore-buffer-modified-p nil)
  4044. (org-element--parse-objects
  4045. (point-min) (point-max) nil restriction parent))))))
  4046. (defun org-element-map
  4047. (data types fun &optional info first-match no-recursion with-affiliated)
  4048. "Map a function on selected elements or objects.
  4049. DATA is a parse tree (for example, returned by
  4050. `org-element-parse-buffer'), an element, an object, a string, or a
  4051. list of such constructs. TYPES is a symbol or list of symbols of
  4052. elements or object types (see `org-element-all-elements' and
  4053. `org-element-all-objects' for a complete list of types). FUN is the
  4054. function called on the matching element or object. It has to accept
  4055. one argument: the element or object itself.
  4056. When optional argument INFO is non-nil, it should be a plist
  4057. holding export options. In that case, parts of the parse tree
  4058. not exportable according to that property list will be skipped.
  4059. When optional argument FIRST-MATCH is non-nil, stop at the first
  4060. match for which FUN doesn't return nil, and return that value.
  4061. Optional argument NO-RECURSION is a symbol or a list of symbols
  4062. representing elements or objects types. `org-element-map' won't
  4063. enter any recursive element or object whose type belongs to that
  4064. list. Though, FUN can still be applied on them.
  4065. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  4066. apply to matching objects within parsed affiliated keywords (see
  4067. `org-element-parsed-keywords').
  4068. Nil values returned from FUN do not appear in the results.
  4069. Examples:
  4070. ---------
  4071. Assuming TREE is a variable containing an Org buffer parse tree,
  4072. the following example will return a flat list of all `src-block'
  4073. and `example-block' elements in it:
  4074. (setq tree (org-element-parse-buffer))
  4075. (org-element-map tree \\='(example-block src-block) #\\='identity)
  4076. The following snippet will find the first headline with a level
  4077. of 1 and a \"phone\" tag, and will return its beginning position:
  4078. (org-element-map tree \\='headline
  4079. (lambda (hl)
  4080. (and (= (org-element-property :level hl) 1)
  4081. (member \"phone\" (org-element-property :tags hl))
  4082. (org-element-property :begin hl)))
  4083. nil t)
  4084. The next example will return a flat list of all `plain-list' type
  4085. elements in TREE that are not a sub-list themselves:
  4086. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  4087. Eventually, this example will return a flat list of all `bold'
  4088. type objects containing a `latex-snippet' type object, even
  4089. looking into captions:
  4090. (org-element-map tree \\='bold
  4091. (lambda (b)
  4092. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  4093. nil nil nil t)"
  4094. (declare (indent 2))
  4095. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  4096. (let* ((types (if (listp types) types (list types)))
  4097. (no-recursion (if (listp no-recursion) no-recursion
  4098. (list no-recursion)))
  4099. ;; Recursion depth is determined by --CATEGORY.
  4100. (--category
  4101. (catch :--found
  4102. (let ((category 'greater-elements)
  4103. (all-objects (cons 'plain-text org-element-all-objects)))
  4104. (dolist (type types category)
  4105. (cond ((memq type all-objects)
  4106. ;; If one object is found, the function has
  4107. ;; to recurse into every object.
  4108. (throw :--found 'objects))
  4109. ((not (memq type org-element-greater-elements))
  4110. ;; If one regular element is found, the
  4111. ;; function has to recurse, at least, into
  4112. ;; every element it encounters.
  4113. (and (not (eq category 'elements))
  4114. (setq category 'elements))))))))
  4115. --acc)
  4116. (letrec ((--walk-tree
  4117. (lambda (--data)
  4118. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  4119. ;; holding contextual information.
  4120. (let ((--type (org-element-type --data)))
  4121. (cond
  4122. ((not --data))
  4123. ;; Ignored element in an export context.
  4124. ((and info (memq --data (plist-get info :ignore-list))))
  4125. ;; List of elements or objects.
  4126. ((not --type) (mapc --walk-tree --data))
  4127. ;; Unconditionally enter parse trees.
  4128. ((eq --type 'org-data)
  4129. (mapc --walk-tree (org-element-contents --data)))
  4130. (t
  4131. ;; Check if TYPE is matching among TYPES. If so,
  4132. ;; apply FUN to --DATA and accumulate return value
  4133. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  4134. (when (memq --type types)
  4135. (let ((result (funcall fun --data)))
  4136. (cond ((not result))
  4137. (first-match (throw :--map-first-match result))
  4138. (t (push result --acc)))))
  4139. ;; If --DATA has a secondary string that can contain
  4140. ;; objects with their type among TYPES, look inside.
  4141. (when (and (eq --category 'objects) (not (stringp --data)))
  4142. (dolist (p (cdr (assq --type
  4143. org-element-secondary-value-alist)))
  4144. (funcall --walk-tree (org-element-property p --data))))
  4145. ;; If --DATA has any parsed affiliated keywords and
  4146. ;; WITH-AFFILIATED is non-nil, look for objects in
  4147. ;; them.
  4148. (when (and with-affiliated
  4149. (eq --category 'objects)
  4150. (eq (org-element-class --data) 'element))
  4151. (dolist (kwd-pair org-element--parsed-properties-alist)
  4152. (let ((kwd (car kwd-pair))
  4153. (value (org-element-property (cdr kwd-pair) --data)))
  4154. ;; Pay attention to the type of parsed
  4155. ;; keyword. In particular, preserve order for
  4156. ;; multiple keywords.
  4157. (cond
  4158. ((not value))
  4159. ((member kwd org-element-dual-keywords)
  4160. (if (member kwd org-element-multiple-keywords)
  4161. (dolist (line (reverse value))
  4162. (funcall --walk-tree (cdr line))
  4163. (funcall --walk-tree (car line)))
  4164. (funcall --walk-tree (cdr value))
  4165. (funcall --walk-tree (car value))))
  4166. ((member kwd org-element-multiple-keywords)
  4167. (mapc --walk-tree (reverse value)))
  4168. (t (funcall --walk-tree value))))))
  4169. ;; Determine if a recursion into --DATA is possible.
  4170. (cond
  4171. ;; --TYPE is explicitly removed from recursion.
  4172. ((memq --type no-recursion))
  4173. ;; --DATA has no contents.
  4174. ((not (org-element-contents --data)))
  4175. ;; Looking for greater elements but --DATA is
  4176. ;; simply an element or an object.
  4177. ((and (eq --category 'greater-elements)
  4178. (not (memq --type org-element-greater-elements))))
  4179. ;; Looking for elements but --DATA is an object.
  4180. ((and (eq --category 'elements)
  4181. (eq (org-element-class --data) 'object)))
  4182. ;; In any other case, map contents.
  4183. (t (mapc --walk-tree (org-element-contents --data))))))))))
  4184. (catch :--map-first-match
  4185. (funcall --walk-tree data)
  4186. ;; Return value in a proper order.
  4187. (nreverse --acc)))))
  4188. ;; The following functions are internal parts of the parser.
  4189. ;;
  4190. ;; The first one, `org-element--parse-elements' acts at the element's
  4191. ;; level.
  4192. ;;
  4193. ;; The second one, `org-element--parse-objects' applies on all objects
  4194. ;; of a paragraph or a secondary string. It calls
  4195. ;; `org-element--object-lex' to find the next object in the current
  4196. ;; container.
  4197. (defsubst org-element--next-mode (mode type parent?)
  4198. "Return next mode according to current one.
  4199. MODE is a symbol representing the expectation about the next
  4200. element or object. Meaningful values are `first-section',
  4201. `item', `node-property', `planning', `property-drawer',
  4202. `section', `table-row', `top-comment', and nil.
  4203. TYPE is the type of the current element or object.
  4204. If PARENT? is non-nil, assume the next element or object will be
  4205. located inside the current one."
  4206. (if parent?
  4207. (pcase type
  4208. (`headline 'section)
  4209. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4210. ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
  4211. ((and (guard (not mode)) `org-data) 'first-section)
  4212. (`inlinetask 'planning)
  4213. (`plain-list 'item)
  4214. (`property-drawer 'node-property)
  4215. (`section 'planning)
  4216. (`table 'table-row))
  4217. (pcase mode
  4218. (`item 'item)
  4219. (`node-property 'node-property)
  4220. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4221. (`table-row 'table-row)
  4222. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4223. (defun org-element--parse-elements
  4224. (beg end mode structure granularity visible-only acc)
  4225. "Parse elements between BEG and END positions.
  4226. MODE prioritizes some elements over the others. It can be set to
  4227. `first-section', `item', `node-property', `planning',
  4228. `property-drawer', `section', `table-row', `top-comment', or nil.
  4229. When value is `item', STRUCTURE will be used as the current list
  4230. structure.
  4231. GRANULARITY determines the depth of the recursion. See
  4232. `org-element-parse-buffer' for more information.
  4233. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4234. elements.
  4235. Elements are accumulated into ACC."
  4236. (save-excursion
  4237. (goto-char beg)
  4238. ;; When parsing only headlines, skip any text before first one.
  4239. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4240. (org-with-limited-levels (outline-next-heading)))
  4241. (let (elements)
  4242. (while (< (point) end)
  4243. ;; Visible only: skip invisible parts due to folding.
  4244. (if (and visible-only (org-invisible-p nil t))
  4245. (progn
  4246. (goto-char (org-find-visible))
  4247. (when (and (eolp) (not (eobp))) (forward-char)))
  4248. ;; Find current element's type and parse it accordingly to
  4249. ;; its category.
  4250. (let* ((element (org-element-copy
  4251. ;; `org-element--current-element' may return cached
  4252. ;; elements. Below code reassigns
  4253. ;; `:parent' property of the element and
  4254. ;; may interfere with cache
  4255. ;; synchronisation if parent element is not
  4256. ;; yet in cache. Moreover, the returned
  4257. ;; structure may be altered by caller code
  4258. ;; arbitrarily. Hence, we return a copy of
  4259. ;; the potentially cached element to make
  4260. ;; potential modifications safe for element
  4261. ;; cache.
  4262. (org-element--current-element
  4263. end granularity mode structure)))
  4264. (type (org-element-type element))
  4265. (cbeg (org-element-property :contents-begin element)))
  4266. (goto-char (org-element-property :end element))
  4267. ;; Fill ELEMENT contents by side-effect.
  4268. (cond
  4269. ;; If element has no contents, don't modify it.
  4270. ((not cbeg))
  4271. ;; Greater element: parse it between `contents-begin' and
  4272. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4273. ;; or ELEMENT is a headline, in which case going inside
  4274. ;; is mandatory, in order to get sub-level headings.
  4275. ((and (memq type org-element-greater-elements)
  4276. (or (memq granularity '(element object nil))
  4277. (and (eq granularity 'greater-element)
  4278. (eq type 'section))
  4279. (eq type 'headline)))
  4280. (org-element--parse-elements
  4281. cbeg (org-element-property :contents-end element)
  4282. ;; Possibly switch to a special mode.
  4283. (org-element--next-mode mode type t)
  4284. (and (memq type '(item plain-list))
  4285. (org-element-property :structure element))
  4286. granularity visible-only element))
  4287. ;; ELEMENT has contents. Parse objects inside, if
  4288. ;; GRANULARITY allows it.
  4289. ((memq granularity '(object nil))
  4290. (org-element--parse-objects
  4291. cbeg (org-element-property :contents-end element) element
  4292. (org-element-restriction type))))
  4293. (push (org-element-put-property element :parent acc) elements)
  4294. ;; Update mode.
  4295. (setq mode (org-element--next-mode mode type nil)))))
  4296. ;; Return result.
  4297. (org-element-put-property acc :granularity granularity)
  4298. (apply #'org-element-set-contents acc (nreverse elements)))))
  4299. (defun org-element--object-lex (restriction)
  4300. "Return next object in current buffer or nil.
  4301. RESTRICTION is a list of object types, as symbols, that should be
  4302. looked after. This function assumes that the buffer is narrowed
  4303. to an appropriate container (e.g., a paragraph)."
  4304. (cond
  4305. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4306. ((memq 'citation-reference restriction)
  4307. (org-element-citation-reference-parser))
  4308. (t
  4309. (let* ((start (point))
  4310. (limit
  4311. ;; Object regexp sometimes needs to have a peek at
  4312. ;; a character ahead. Therefore, when there is a hard
  4313. ;; limit, make it one more than the true beginning of the
  4314. ;; radio target.
  4315. (save-excursion
  4316. (cond ((not org-target-link-regexp) nil)
  4317. ((not (memq 'link restriction)) nil)
  4318. ((progn
  4319. (unless (bolp) (forward-char -1))
  4320. (not (re-search-forward org-target-link-regexp nil t)))
  4321. nil)
  4322. ;; Since we moved backward, we do not want to
  4323. ;; match again an hypothetical 1-character long
  4324. ;; radio link before us. Realizing that this can
  4325. ;; only happen if such a radio link starts at
  4326. ;; beginning of line, we prevent this here.
  4327. ((and (= start (1+ (line-beginning-position)))
  4328. (= start (match-end 1)))
  4329. (and (re-search-forward org-target-link-regexp nil t)
  4330. (1+ (match-beginning 1))))
  4331. (t (1+ (match-beginning 1))))))
  4332. found)
  4333. (save-excursion
  4334. (while (and (not found)
  4335. (re-search-forward org-element--object-regexp limit 'move))
  4336. (goto-char (match-beginning 0))
  4337. (let ((result (match-string 0)))
  4338. (setq found
  4339. (cond
  4340. ((string-prefix-p "call_" result t)
  4341. (and (memq 'inline-babel-call restriction)
  4342. (org-element-inline-babel-call-parser)))
  4343. ((string-prefix-p "src_" result t)
  4344. (and (memq 'inline-src-block restriction)
  4345. (org-element-inline-src-block-parser)))
  4346. (t
  4347. (pcase (char-after)
  4348. (?^ (and (memq 'superscript restriction)
  4349. (org-element-superscript-parser)))
  4350. (?_ (or (and (memq 'subscript restriction)
  4351. (org-element-subscript-parser))
  4352. (and (memq 'underline restriction)
  4353. (org-element-underline-parser))))
  4354. (?* (and (memq 'bold restriction)
  4355. (org-element-bold-parser)))
  4356. (?/ (and (memq 'italic restriction)
  4357. (org-element-italic-parser)))
  4358. (?~ (and (memq 'code restriction)
  4359. (org-element-code-parser)))
  4360. (?= (and (memq 'verbatim restriction)
  4361. (org-element-verbatim-parser)))
  4362. (?+ (and (memq 'strike-through restriction)
  4363. (org-element-strike-through-parser)))
  4364. (?@ (and (memq 'export-snippet restriction)
  4365. (org-element-export-snippet-parser)))
  4366. (?{ (and (memq 'macro restriction)
  4367. (org-element-macro-parser)))
  4368. (?$ (and (memq 'latex-fragment restriction)
  4369. (org-element-latex-fragment-parser)))
  4370. (?<
  4371. (if (eq (aref result 1) ?<)
  4372. (or (and (memq 'radio-target restriction)
  4373. (org-element-radio-target-parser))
  4374. (and (memq 'target restriction)
  4375. (org-element-target-parser)))
  4376. (or (and (memq 'timestamp restriction)
  4377. (org-element-timestamp-parser))
  4378. (and (memq 'link restriction)
  4379. (org-element-link-parser)))))
  4380. (?\\
  4381. (if (eq (aref result 1) ?\\)
  4382. (and (memq 'line-break restriction)
  4383. (org-element-line-break-parser))
  4384. (or (and (memq 'entity restriction)
  4385. (org-element-entity-parser))
  4386. (and (memq 'latex-fragment restriction)
  4387. (org-element-latex-fragment-parser)))))
  4388. (?\[
  4389. (pcase (aref result 1)
  4390. ((and ?\[
  4391. (guard (memq 'link restriction)))
  4392. (org-element-link-parser))
  4393. ((and ?f
  4394. (guard (memq 'footnote-reference restriction)))
  4395. (org-element-footnote-reference-parser))
  4396. ((and ?c
  4397. (guard (memq 'citation restriction)))
  4398. (org-element-citation-parser))
  4399. ((and (or ?% ?/)
  4400. (guard (memq 'statistics-cookie restriction)))
  4401. (org-element-statistics-cookie-parser))
  4402. (_
  4403. (or (and (memq 'timestamp restriction)
  4404. (org-element-timestamp-parser))
  4405. (and (memq 'statistics-cookie restriction)
  4406. (org-element-statistics-cookie-parser))))))
  4407. ;; This is probably a plain link.
  4408. (_ (and (memq 'link restriction)
  4409. (org-element-link-parser)))))))
  4410. (or (eobp) (forward-char))))
  4411. (cond (found)
  4412. (limit (forward-char -1)
  4413. (org-element-link-parser)) ;radio link
  4414. (t nil)))))))
  4415. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4416. "Parse objects between BEG and END and return recursive structure.
  4417. Objects are accumulated in ACC. RESTRICTION is a list of object
  4418. successors which are allowed in the current object.
  4419. ACC becomes the parent for all parsed objects. However, if ACC
  4420. is nil (i.e., a secondary string is being parsed) and optional
  4421. argument PARENT is non-nil, use it as the parent for all objects.
  4422. Eventually, if both ACC and PARENT are nil, the common parent is
  4423. the list of objects itself."
  4424. (save-excursion
  4425. (save-restriction
  4426. (narrow-to-region beg end)
  4427. (goto-char (point-min))
  4428. (let (next-object contents)
  4429. (while (and (not (eobp))
  4430. (setq next-object (org-element--object-lex restriction)))
  4431. ;; Text before any object.
  4432. (let ((obj-beg (org-element-property :begin next-object)))
  4433. (unless (= (point) obj-beg)
  4434. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4435. (push (if acc (org-element-put-property text :parent acc) text)
  4436. contents))))
  4437. ;; Object...
  4438. (let ((obj-end (org-element-property :end next-object))
  4439. (cont-beg (org-element-property :contents-begin next-object)))
  4440. (when acc (org-element-put-property next-object :parent acc))
  4441. (push (if cont-beg
  4442. ;; Fill contents of NEXT-OBJECT if possible.
  4443. (org-element--parse-objects
  4444. cont-beg
  4445. (org-element-property :contents-end next-object)
  4446. next-object
  4447. (org-element-restriction next-object))
  4448. next-object)
  4449. contents)
  4450. (goto-char obj-end)))
  4451. ;; Text after last object.
  4452. (unless (eobp)
  4453. (let ((text (buffer-substring-no-properties (point) end)))
  4454. (push (if acc (org-element-put-property text :parent acc) text)
  4455. contents)))
  4456. ;; Result. Set appropriate parent.
  4457. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4458. (let* ((contents (nreverse contents))
  4459. (parent (or parent contents)))
  4460. (dolist (datum contents contents)
  4461. (org-element-put-property datum :parent parent))))))))
  4462. ;;; Towards A Bijective Process
  4463. ;;
  4464. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4465. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4466. ;; interpreted and expanded into a string with canonical Org syntax.
  4467. ;; Hence `org-element-interpret-data'.
  4468. ;;
  4469. ;; The function relies internally on
  4470. ;; `org-element--interpret-affiliated-keywords'.
  4471. ;;;###autoload
  4472. (defun org-element-interpret-data (data)
  4473. "Interpret DATA as Org syntax.
  4474. DATA is a parse tree, an element, an object or a secondary string
  4475. to interpret. Return Org syntax as a string."
  4476. (letrec ((fun
  4477. (lambda (data parent)
  4478. (let* ((type (org-element-type data))
  4479. ;; Find interpreter for current object or
  4480. ;; element. If it doesn't exist (e.g. this is
  4481. ;; a pseudo object or element), return contents,
  4482. ;; if any.
  4483. (interpret
  4484. (let ((fun (intern
  4485. (format "org-element-%s-interpreter" type))))
  4486. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4487. (results
  4488. (cond
  4489. ;; Secondary string.
  4490. ((not type)
  4491. (mapconcat (lambda (obj) (funcall fun obj parent))
  4492. data
  4493. ""))
  4494. ;; Full Org document.
  4495. ((eq type 'org-data)
  4496. (mapconcat (lambda (obj) (funcall fun obj parent))
  4497. (org-element-contents data)
  4498. ""))
  4499. ;; Plain text: return it.
  4500. ((stringp data) data)
  4501. ;; Element or object without contents.
  4502. ((not (org-element-contents data))
  4503. (funcall interpret data nil))
  4504. ;; Element or object with contents.
  4505. (t
  4506. (funcall
  4507. interpret
  4508. data
  4509. ;; Recursively interpret contents.
  4510. (mapconcat
  4511. (lambda (datum) (funcall fun datum data))
  4512. (org-element-contents
  4513. (if (not (memq type '(paragraph verse-block)))
  4514. data
  4515. ;; Fix indentation of elements containing
  4516. ;; objects. We ignore `table-row'
  4517. ;; elements as they are one line long
  4518. ;; anyway.
  4519. (org-element-normalize-contents
  4520. data
  4521. ;; When normalizing first paragraph of
  4522. ;; an item or a footnote-definition,
  4523. ;; ignore first line's indentation.
  4524. (and (eq type 'paragraph)
  4525. (memq (org-element-type parent)
  4526. '(footnote-definition item))
  4527. (eq data (car (org-element-contents parent)))
  4528. (eq (org-element-property :pre-blank parent)
  4529. 0)))))
  4530. ""))))))
  4531. (if (memq type '(org-data nil)) results
  4532. ;; Build white spaces. If no `:post-blank' property
  4533. ;; is specified, assume its value is 0.
  4534. (let ((blank (or (org-element-property :post-blank data) 0)))
  4535. (if (eq (org-element-class data parent) 'object)
  4536. (concat results (make-string blank ?\s))
  4537. (concat (org-element--interpret-affiliated-keywords data)
  4538. (org-element-normalize-string results)
  4539. (make-string blank ?\n)))))))))
  4540. (funcall fun data nil)))
  4541. (defun org-element--interpret-affiliated-keywords (element)
  4542. "Return ELEMENT's affiliated keywords as Org syntax.
  4543. If there is no affiliated keyword, return the empty string."
  4544. (let ((keyword-to-org
  4545. (lambda (key value)
  4546. (let (dual)
  4547. (when (member key org-element-dual-keywords)
  4548. (setq dual (cdr value) value (car value)))
  4549. (concat "#+" (downcase key)
  4550. (and dual
  4551. (format "[%s]" (org-element-interpret-data dual)))
  4552. ": "
  4553. (if (member key org-element-parsed-keywords)
  4554. (org-element-interpret-data value)
  4555. value)
  4556. "\n")))))
  4557. (mapconcat
  4558. (lambda (prop)
  4559. (let ((value (org-element-property prop element))
  4560. (keyword (upcase (substring (symbol-name prop) 1))))
  4561. (when value
  4562. (if (or (member keyword org-element-multiple-keywords)
  4563. ;; All attribute keywords can have multiple lines.
  4564. (string-match "^ATTR_" keyword))
  4565. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4566. (reverse value)
  4567. "")
  4568. (funcall keyword-to-org keyword value)))))
  4569. ;; List all ELEMENT's properties matching an attribute line or an
  4570. ;; affiliated keyword, but ignore translated keywords since they
  4571. ;; cannot belong to the property list.
  4572. (cl-loop for prop in (nth 1 element) by 'cddr
  4573. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4574. (or (string-match "^ATTR_" keyword)
  4575. (and
  4576. (member keyword org-element-affiliated-keywords)
  4577. (not (assoc keyword
  4578. org-element-keyword-translation-alist)))))
  4579. collect prop)
  4580. "")))
  4581. ;; Because interpretation of the parse tree must return the same
  4582. ;; number of blank lines between elements and the same number of white
  4583. ;; space after objects, some special care must be given to white
  4584. ;; spaces.
  4585. ;;
  4586. ;; The first function, `org-element-normalize-string', ensures any
  4587. ;; string different from the empty string will end with a single
  4588. ;; newline character.
  4589. ;;
  4590. ;; The second function, `org-element-normalize-contents', removes
  4591. ;; global indentation from the contents of the current element.
  4592. (defun org-element-normalize-string (s)
  4593. "Ensure string S ends with a single newline character.
  4594. If S isn't a string return it unchanged. If S is the empty
  4595. string, return it. Otherwise, return a new string with a single
  4596. newline character at its end."
  4597. (cond
  4598. ((not (stringp s)) s)
  4599. ((string= "" s) "")
  4600. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4601. (replace-match "\n" nil nil s)))))
  4602. (defun org-element-normalize-contents (element &optional ignore-first)
  4603. "Normalize plain text in ELEMENT's contents.
  4604. ELEMENT must only contain plain text and objects.
  4605. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4606. indentation to compute maximal common indentation.
  4607. Return the normalized element that is element with global
  4608. indentation removed from its contents."
  4609. (letrec ((find-min-ind
  4610. ;; Return minimal common indentation within BLOB. This is
  4611. ;; done by walking recursively BLOB and updating MIN-IND
  4612. ;; along the way. FIRST-FLAG is non-nil when the next
  4613. ;; object is expected to be a string that doesn't start
  4614. ;; with a newline character. It happens for strings at
  4615. ;; the beginnings of the contents or right after a line
  4616. ;; break.
  4617. (lambda (blob first-flag min-ind)
  4618. (dolist (datum (org-element-contents blob) min-ind)
  4619. (when first-flag
  4620. (setq first-flag nil)
  4621. (cond
  4622. ;; Objects cannot start with spaces: in this
  4623. ;; case, indentation is 0.
  4624. ((not (stringp datum)) (throw :zero 0))
  4625. ((not (string-match
  4626. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4627. (throw :zero 0))
  4628. ((equal (match-string 2 datum) "\n")
  4629. (put-text-property
  4630. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4631. (t
  4632. (let ((i (string-width (match-string 1 datum))))
  4633. (put-text-property
  4634. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4635. (setq min-ind (min i min-ind))))))
  4636. (cond
  4637. ((stringp datum)
  4638. (let ((s 0))
  4639. (while (string-match
  4640. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4641. (setq s (match-end 1))
  4642. (cond
  4643. ((equal (match-string 1 datum) "")
  4644. (unless (member (match-string 2 datum) '("" "\n"))
  4645. (throw :zero 0)))
  4646. ((equal (match-string 2 datum) "\n")
  4647. (put-text-property (match-beginning 1) (match-end 1)
  4648. 'org-ind 'empty datum))
  4649. (t
  4650. (let ((i (string-width (match-string 1 datum))))
  4651. (put-text-property (match-beginning 1) (match-end 1)
  4652. 'org-ind i datum)
  4653. (setq min-ind (min i min-ind))))))))
  4654. ((eq (org-element-type datum) 'line-break)
  4655. (setq first-flag t))
  4656. ((memq (org-element-type datum) org-element-recursive-objects)
  4657. (setq min-ind
  4658. (funcall find-min-ind datum first-flag min-ind)))))))
  4659. (min-ind
  4660. (catch :zero
  4661. (funcall find-min-ind
  4662. element (not ignore-first) most-positive-fixnum))))
  4663. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4664. ;; Build ELEMENT back, replacing each string with the same
  4665. ;; string minus common indentation.
  4666. (letrec ((build
  4667. (lambda (datum)
  4668. ;; Return DATUM with all its strings indentation
  4669. ;; shortened from MIN-IND white spaces.
  4670. (setcdr
  4671. (cdr datum)
  4672. (mapcar
  4673. (lambda (object)
  4674. (cond
  4675. ((stringp object)
  4676. (with-temp-buffer
  4677. (insert object)
  4678. (let ((s (point-min)))
  4679. (while (setq s (text-property-not-all
  4680. s (point-max) 'org-ind nil))
  4681. (goto-char s)
  4682. (let ((i (get-text-property s 'org-ind)))
  4683. (delete-region s (progn
  4684. (skip-chars-forward " \t")
  4685. (point)))
  4686. (when (integerp i) (indent-to (- i min-ind))))))
  4687. (buffer-string)))
  4688. ((memq (org-element-type object)
  4689. org-element-recursive-objects)
  4690. (funcall build object))
  4691. (t object)))
  4692. (org-element-contents datum)))
  4693. datum)))
  4694. (funcall build element)))))
  4695. ;;; Cache
  4696. ;;
  4697. ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
  4698. ;; fast mapping across Org elements in `org-element-cache-map', which see.
  4699. ;;
  4700. ;; When cache is enabled, the elements returned by `org-element-at-point' and
  4701. ;; `org-element-context' are returned by reference. Altering these elements will
  4702. ;; also alter their cache representation. The same is true for
  4703. ;; elements passed to mapping function in `org-element-cache-map'.
  4704. ;;
  4705. ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
  4706. ;; `org-element-cache-map'.
  4707. ;;
  4708. ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
  4709. ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
  4710. ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
  4711. ;;
  4712. ;; Internally, parsed elements are stored in an AVL tree,
  4713. ;; `org-element--cache'. This tree is updated lazily: whenever
  4714. ;; a change happens to the buffer, a synchronization request is
  4715. ;; registered in `org-element--cache-sync-requests' (see
  4716. ;; `org-element--cache-submit-request'). During idle time, requests
  4717. ;; are processed by `org-element--cache-sync'. Synchronization also
  4718. ;; happens when an element is required from the cache. In this case,
  4719. ;; the process stops as soon as the needed element is up-to-date.
  4720. ;;
  4721. ;; A synchronization request can only apply on a synchronized part of
  4722. ;; the cache. Therefore, the cache is updated at least to the
  4723. ;; location where the new request applies. Thus, requests are ordered
  4724. ;; from left to right and all elements starting before the first
  4725. ;; request are correct. This property is used by functions like
  4726. ;; `org-element--cache-find' to retrieve elements in the part of the
  4727. ;; cache that can be trusted.
  4728. ;;
  4729. ;; A request applies to every element, starting from its original
  4730. ;; location (or key, see below). When a request is processed, it
  4731. ;; moves forward and may collide the next one. In this case, both
  4732. ;; requests are merged into a new one that starts from that element.
  4733. ;; As a consequence, the whole synchronization complexity does not
  4734. ;; depend on the number of pending requests, but on the number of
  4735. ;; elements the very first request will be applied on.
  4736. ;;
  4737. ;; Elements cannot be accessed through their beginning position, which
  4738. ;; may or may not be up-to-date. Instead, each element in the tree is
  4739. ;; associated to a key, obtained with `org-element--cache-key'. This
  4740. ;; mechanism is robust enough to preserve total order among elements
  4741. ;; even when the tree is only partially synchronized.
  4742. ;;
  4743. ;; The cache code debuggin is fairly complex because cache request
  4744. ;; state is often hard to reproduce. An extensive diagnostics
  4745. ;; functionality is built into the cache code to assist hunting bugs.
  4746. ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
  4747. ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
  4748. ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
  4749. ;; `org-element--cache-map-statistics-threshold'.
  4750. (defvar org-element-use-cache t
  4751. "Non-nil when Org parser should cache its results.")
  4752. (defvar org-element-cache-persistent t
  4753. "Non-nil when cache should persist between Emacs sessions.")
  4754. (defvar org-element-cache-sync-idle-time 0.6
  4755. "Length, in seconds, of idle time before syncing cache.")
  4756. (defvar org-element-cache-sync-duration 0.04
  4757. "Maximum duration, as a time value, for a cache synchronization.
  4758. If the synchronization is not over after this delay, the process
  4759. pauses and resumes after `org-element-cache-sync-break'
  4760. seconds.")
  4761. (defvar org-element-cache-sync-break 0.3
  4762. "Duration, as a time value, of the pause between synchronizations.
  4763. See `org-element-cache-sync-duration' for more information.")
  4764. (defvar org-element--cache-self-verify t
  4765. "Activate extra consistency checks for the cache.
  4766. This may cause serious performance degradation depending on the value
  4767. of `org-element--cache-self-verify-frequency'.
  4768. When set to symbol `backtrace', record and display backtrace log if
  4769. any inconsistency is detected.")
  4770. (defvar org-element--cache-self-verify-frequency 0.03
  4771. "Frequency of cache element verification.
  4772. This number is a probability to check an element requested from cache
  4773. to be correct. Setting this to a value less than 0.0001 is useless.")
  4774. (defvar org-element--cache-diagnostics nil
  4775. "Print detailed diagnostics of cache processing.")
  4776. (defvar org-element--cache-map-statistics nil
  4777. "Print statistics for `org-element-cache-map'.")
  4778. (defvar org-element--cache-map-statistics-threshold 0.1
  4779. "Time threshold in seconds to log statistics for `org-element-cache-map'.")
  4780. (defvar org-element--cache-diagnostics-modifications t
  4781. "Non-nil enables cache warnings when for silent modifications.
  4782. Silent modifications are the modifications in Org buffers that are not
  4783. registered by `org-element--cache-before-change' and
  4784. `org-element--cache-after-change'.
  4785. This variable may cause false-positives because some Emacs versions
  4786. can change `buffer-chars-modified-tick' internally even though no
  4787. visible changes in buffer are being made. Some of such expected cases
  4788. are covered by heuristics, but not all.")
  4789. (defvar org-element--cache-silent-modification-check t
  4790. "Detect changes in buffer made inside `with-silent-modifications'.
  4791. Note that some internal Emacs functions may also trigger a warning and
  4792. cache reset. The warning can be suppressed by setting
  4793. `org-element--cache-diagnostics-modifications' to nil, but the cache
  4794. will still be refreshed to be safe.
  4795. WARNING: Setting this variable to nil may cause cache corruption is some
  4796. third-party packages make undetected changes in buffers.")
  4797. (defvar org-element--cache-diagnostics-level 2
  4798. "Detail level of the diagnostics.")
  4799. (defvar-local org-element--cache-diagnostics-ring nil
  4800. "Ring containing last `org-element--cache-diagnostics-ring-size'
  4801. cache process log entries.")
  4802. (defvar org-element--cache-diagnostics-ring-size 5000
  4803. "Size of `org-element--cache-diagnostics-ring'.")
  4804. ;;;; Data Structure
  4805. (defvar-local org-element--cache nil
  4806. "AVL tree used to cache elements.
  4807. Each node of the tree contains an element. Comparison is done
  4808. with `org-element--cache-compare'. This cache is used in
  4809. `org-element-at-point'.")
  4810. (defvar-local org-element--headline-cache nil
  4811. "AVL tree used to cache headline and inlinetask elements.
  4812. Each node of the tree contains an element. Comparison is done
  4813. with `org-element--cache-compare'. This cache is used in
  4814. `org-element-cache-map'.")
  4815. (defconst org-element--cache-hash-size 16
  4816. "Cache size for recent cached calls to `org-element--cache-find'.
  4817. This extra caching is based on the following paper:
  4818. Pugh [Information Processing Letters] (1990) Slow optimally balanced
  4819. search strategies vs. cached fast uniformly balanced search
  4820. strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
  4821. Also, see `org-element--cache-hash-left' and `org-element--cache-hash-right'.")
  4822. (defvar-local org-element--cache-hash-left nil
  4823. "Cached elements from `org-element--cache' for fast O(1) lookup.
  4824. When non-nil, it should be a vector representing POS arguments of
  4825. `org-element--cache-find' called with nil SIDE argument.
  4826. Also, see `org-element--cache-hash-size'.")
  4827. (defvar-local org-element--cache-hash-right nil
  4828. "Cached elements from `org-element--cache' for fast O(1) lookup.
  4829. When non-nil, it should be a vector representing POS arguments of
  4830. `org-element--cache-find' called with non-nil, non-`both' SIDE argument.
  4831. Also, see `org-element--cache-hash-size'.")
  4832. (defvar org-element--cache-hash-statistics '(0 . 0)
  4833. "Cons cell storing how Org makes use of `org-element--cache-find' caching.
  4834. The car is the number of successful uses and cdr is the total calls to
  4835. `org-element--cache-find'.")
  4836. (defvar org-element--cache-hash-nocache 0
  4837. "Number of calls to `org-element--cache-has' with `both' SIDE argument.
  4838. These calls are not cached by hash. See `org-element--cache-hash-size'.")
  4839. (defvar-local org-element--cache-size 0
  4840. "Size of the `org-element--cache'.
  4841. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4842. (defvar-local org-element--headline-cache-size 0
  4843. "Size of the `org-element--headline-cache'.
  4844. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4845. (defvar-local org-element--cache-sync-requests nil
  4846. "List of pending synchronization requests.
  4847. A request is a vector with the following pattern:
  4848. [NEXT BEG END OFFSET PARENT PHASE]
  4849. Processing a synchronization request consists of three phases:
  4850. 0. Delete modified elements,
  4851. 1. Fill missing area in cache,
  4852. 2. Shift positions and re-parent elements after the changes.
  4853. During phase 0, NEXT is the key of the first element to be
  4854. removed, BEG and END is buffer position delimiting the
  4855. modifications. Elements starting between them (inclusive) are
  4856. removed. So are elements whose parent is removed. PARENT, when
  4857. non-nil, is the common parent of all the elements between BEG and END.
  4858. It is guaranteed that only a single phase 0 request exists at any
  4859. moment of time. If it does, it must be the first request in the list.
  4860. During phase 1, NEXT is the key of the next known element in
  4861. cache and BEG its beginning position. Parse buffer between that
  4862. element and the one before it in order to determine the parent of
  4863. the next element. Set PARENT to the element containing NEXT.
  4864. During phase 2, NEXT is the key of the next element to shift in
  4865. the parse tree. All elements starting from this one have their
  4866. properties relative to buffer positions shifted by integer
  4867. OFFSET and, if they belong to element PARENT, are adopted by it.
  4868. PHASE specifies the phase number, as an integer.
  4869. For any synchronisation request, all the later requests in the cache
  4870. must not start at or before END. See `org-element--cache-submit-request'.")
  4871. (defvar-local org-element--cache-sync-timer nil
  4872. "Timer used for cache synchronization.")
  4873. (defvar-local org-element--cache-sync-keys-value nil
  4874. "Id value used to identify keys during synchronisation.
  4875. See `org-element--cache-key' for more information.")
  4876. (defvar-local org-element--cache-change-tic nil
  4877. "Last `buffer-chars-modified-tick' for registered changes.")
  4878. (defvar org-element--cache-non-modifying-commands
  4879. '(org-agenda
  4880. org-agenda-redo
  4881. org-sparse-tree
  4882. org-occur
  4883. org-columns
  4884. org-columns-redo
  4885. org-columns-new
  4886. org-columns-delete
  4887. org-columns-compute
  4888. org-columns-insert-dblock
  4889. org-agenda-columns
  4890. org-ctrl-c-ctrl-c)
  4891. "List of commands that are not expected to change the cache state.
  4892. This variable is used to determine when re-parsing buffer is not going
  4893. to slow down the command.
  4894. If the commends end up modifying the cache, the worst case scenario is
  4895. performance drop. So, advicing these commands is safe. Yet, it is
  4896. better to remove the commands adviced in such way from this list.")
  4897. (defmacro org-element--request-key (request)
  4898. "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
  4899. `(aref ,request 0))
  4900. (defmacro org-element--request-beg (request)
  4901. "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
  4902. `(aref ,request 1))
  4903. (defmacro org-element--request-end (request)
  4904. "Get END part of a `org-element--cache-sync-requests' REQUEST."
  4905. `(aref ,request 2))
  4906. (defmacro org-element--request-offset (request)
  4907. "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
  4908. `(aref ,request 3))
  4909. (defmacro org-element--request-parent (request)
  4910. "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
  4911. `(aref ,request 4))
  4912. (defmacro org-element--request-phase (request)
  4913. "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
  4914. `(aref ,request 5))
  4915. (defmacro org-element--format-element (element)
  4916. "Format ELEMENT for printing in diagnostics."
  4917. `(let ((print-length 50)
  4918. (print-level 5))
  4919. (prin1-to-string ,element)))
  4920. (defmacro org-element--cache-log-message (format-string &rest args)
  4921. "Add a new log message for org-element-cache."
  4922. `(when (or org-element--cache-diagnostics
  4923. (eq org-element--cache-self-verify 'backtrace))
  4924. (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
  4925. (buffer-name (current-buffer)))
  4926. ,format-string))
  4927. (format-string (funcall #'format format-string ,@args)))
  4928. (if org-element--cache-diagnostics
  4929. (display-warning 'org-element-cache format-string)
  4930. (unless org-element--cache-diagnostics-ring
  4931. (setq org-element--cache-diagnostics-ring
  4932. (make-ring org-element--cache-diagnostics-ring-size)))
  4933. (ring-insert org-element--cache-diagnostics-ring format-string)))))
  4934. (defmacro org-element--cache-warn (format-string &rest args)
  4935. "Raise warning for org-element-cache."
  4936. `(let* ((format-string (funcall #'format ,format-string ,@args))
  4937. (format-string
  4938. (if (or (not org-element--cache-diagnostics-ring)
  4939. (not (eq 'backtrace org-element--cache-self-verify)))
  4940. format-string
  4941. (prog1
  4942. (concat (format "Warning(%s): "
  4943. (buffer-name (current-buffer)))
  4944. format-string
  4945. "\nBacktrace:\n "
  4946. (mapconcat #'identity
  4947. (ring-elements org-element--cache-diagnostics-ring)
  4948. "\n "))
  4949. (setq org-element--cache-diagnostics-ring nil)))))
  4950. (if (and (boundp 'org-batch-test) org-batch-test)
  4951. (error "%s" (concat "org-element--cache: " format-string))
  4952. (display-warning 'org-element-cache
  4953. (concat "org-element--cache: " format-string)))))
  4954. (defsubst org-element--cache-key (element)
  4955. "Return a unique key for ELEMENT in cache tree.
  4956. Keys are used to keep a total order among elements in the cache.
  4957. Comparison is done with `org-element--cache-key-less-p'.
  4958. When no synchronization is taking place, a key is simply the
  4959. beginning position of the element, or that position plus one in
  4960. the case of an first item (respectively row) in
  4961. a list (respectively a table). They key of a section is its beginning
  4962. position minus one.
  4963. During a synchronization, the key is the one the element had when
  4964. the cache was synchronized for the last time. Elements added to
  4965. cache during the synchronization get a new key generated with
  4966. `org-element--cache-generate-key'.
  4967. Such keys are stored inside the element property
  4968. `:org-element--cache-sync-key'. The property is a cons containing
  4969. current `org-element--cache-sync-keys-value' and the element key."
  4970. (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
  4971. (cdr (org-element-property :org-element--cache-sync-key element)))
  4972. (let* ((begin (org-element-property :begin element))
  4973. ;; Increase beginning position of items (respectively
  4974. ;; table rows) by one, so the first item can get
  4975. ;; a different key from its parent list (respectively
  4976. ;; table).
  4977. (key (if (memq (org-element-type element) '(item table-row))
  4978. (1+ begin)
  4979. ;; Decrease beginning position of sections by one,
  4980. ;; so that the first element of the section get
  4981. ;; different key from the parent section.
  4982. (if (eq (org-element-type element) 'section)
  4983. (1- begin)
  4984. (if (eq (org-element-type element) 'org-data)
  4985. (- begin 2)
  4986. begin)))))
  4987. (when org-element--cache-sync-requests
  4988. (org-element-put-property
  4989. element
  4990. :org-element--cache-sync-key
  4991. (cons org-element--cache-sync-keys-value key)))
  4992. key)))
  4993. (defun org-element--cache-generate-key (lower upper)
  4994. "Generate a key between LOWER and UPPER.
  4995. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4996. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4997. a unique key, as an integer or a list of integers, according to
  4998. the following rules:
  4999. - LOWER and UPPER are compared level-wise until values differ.
  5000. - If, at a given level, LOWER and UPPER differ from more than
  5001. 2, the new key shares all the levels above with LOWER and
  5002. gets a new level. Its value is the mean between LOWER and
  5003. UPPER:
  5004. (1 2) + (1 4) --> (1 3)
  5005. - If LOWER has no value to compare with, it is assumed that its
  5006. value is `most-negative-fixnum'. E.g.,
  5007. (1 1) + (1 1 2)
  5008. is equivalent to
  5009. (1 1 m) + (1 1 2)
  5010. where m is `most-negative-fixnum'. Likewise, if UPPER is
  5011. short of levels, the current value is `most-positive-fixnum'.
  5012. - If they differ from only one, the new key inherits from
  5013. current LOWER level and fork it at the next level. E.g.,
  5014. (2 1) + (3 3)
  5015. is equivalent to
  5016. (2 1) + (2 M)
  5017. where M is `most-positive-fixnum'.
  5018. - If the key is only one level long, it is returned as an
  5019. integer:
  5020. (1 2) + (3 2) --> 2
  5021. When they are not equals, the function assumes that LOWER is
  5022. lesser than UPPER, per `org-element--cache-key-less-p'."
  5023. (if (equal lower upper) lower
  5024. (let ((lower (if (integerp lower) (list lower) lower))
  5025. (upper (if (integerp upper) (list upper) upper))
  5026. skip-upper key)
  5027. (catch 'exit
  5028. (while t
  5029. (let ((min (or (car lower) most-negative-fixnum))
  5030. (max (cond (skip-upper most-positive-fixnum)
  5031. ((car upper))
  5032. (t most-positive-fixnum))))
  5033. (if (< (1+ min) max)
  5034. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  5035. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  5036. (when (and (< min max) (not skip-upper))
  5037. ;; When at a given level, LOWER and UPPER differ from
  5038. ;; 1, ignore UPPER altogether. Instead create a key
  5039. ;; between LOWER and the greatest key with the same
  5040. ;; prefix as LOWER so far.
  5041. (setq skip-upper t))
  5042. (push min key)
  5043. (setq lower (cdr lower) upper (cdr upper)))))))))
  5044. (defsubst org-element--cache-key-less-p (a b)
  5045. "Non-nil if key A is less than key B.
  5046. A and B are either integers or lists of integers, as returned by
  5047. `org-element--cache-key'.
  5048. Note that it is not reliable to compare buffer position with the cache
  5049. keys. They keys may be larger compared to actual element :begin
  5050. position."
  5051. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  5052. (if (integerp b) (< (car a) b)
  5053. (catch 'exit
  5054. (while (and a b)
  5055. (cond ((car-less-than-car a b) (throw 'exit t))
  5056. ((car-less-than-car b a) (throw 'exit nil))
  5057. (t (setq a (cdr a) b (cdr b)))))
  5058. ;; If A is empty, either keys are equal (B is also empty) and
  5059. ;; we return nil, or A is lesser than B (B is longer) and we
  5060. ;; return a non-nil value.
  5061. ;;
  5062. ;; If A is not empty, B is necessarily empty and A is greater
  5063. ;; than B (A is longer). Therefore, return nil.
  5064. (and (null a) b)))))
  5065. (defun org-element--cache-compare (a b)
  5066. "Non-nil when element A is located before element B."
  5067. (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
  5068. (defsubst org-element--cache-root ()
  5069. "Return root value in `org-element--cache' .
  5070. This function assumes `org-element--cache' is a valid AVL tree."
  5071. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  5072. (defsubst org-element--headline-cache-root ()
  5073. "Return root value in `org-element--headline-cache' .
  5074. This function assumes `org-element--headline-cache' is a valid AVL tree."
  5075. (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
  5076. ;;;; Tools
  5077. (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
  5078. "Non-nil when cache is active in current buffer."
  5079. (and org-element-use-cache
  5080. org-element--cache
  5081. (derived-mode-p 'org-mode)
  5082. (or called-from-cache-change-func-p
  5083. (and
  5084. ;; org-num-mode calls some Org structure analysis functions
  5085. ;; that can trigger cache update in the middle of changes. See
  5086. ;; `org-num--verify' calling `org-num--skip-value' calling
  5087. ;; `org-entry-get' that uses cache.
  5088. ;; Forcefully disable cache when called from inside a
  5089. ;; modification hook, where `inhibit-modification-hooks' is set
  5090. ;; to t.
  5091. (not inhibit-modification-hooks)
  5092. ;; `combine-change-calls' sets `after-change-functions' to
  5093. ;; nil. We need not to use cache inside
  5094. ;; `combine-change-calls' because the buffer is potentially
  5095. ;; changed without notice (the change will be registered
  5096. ;; after exiting the `combine-change-calls' body though).
  5097. (memq #'org-element--cache-after-change after-change-functions))
  5098. (eq org-element--cache-change-tic (buffer-chars-modified-tick)))))
  5099. ;; FIXME: Remove after we establish that hashing is effective.
  5100. (defun org-element-cache-hash-show-statistics ()
  5101. "Display efficiency of O(1) query cache for `org-element--cache-find'.
  5102. This extra caching is based on the following paper:
  5103. Pugh [Information Processing Letters] (1990) Slow optimally balanced
  5104. search strategies vs. cached fast uniformly balanced search
  5105. strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
  5106. Also, see `org-element--cache-size'."
  5107. (interactive)
  5108. (message "%.2f%% of cache searches hashed, %.2f%% non-hashable."
  5109. (* 100
  5110. (/ (float (car org-element--cache-hash-statistics))
  5111. (cdr org-element--cache-hash-statistics)))
  5112. (* 100
  5113. (/ (float org-element--cache-hash-nocache)
  5114. (cdr org-element--cache-hash-statistics)))))
  5115. (defun org-element--cache-find (pos &optional side)
  5116. "Find element in cache starting at POS or before.
  5117. POS refers to a buffer position.
  5118. When optional argument SIDE is non-nil, the function checks for
  5119. elements starting at or past POS instead. If SIDE is `both', the
  5120. function returns a cons cell where car is the first element
  5121. starting at or before POS and cdr the first element starting
  5122. after POS.
  5123. The function can only find elements in the synchronized part of
  5124. the cache."
  5125. (with-current-buffer (or (buffer-base-buffer) (current-buffer))
  5126. (let* ((limit (and org-element--cache-sync-requests
  5127. (org-element--request-key (car org-element--cache-sync-requests))))
  5128. (node (org-element--cache-root))
  5129. (hash-pos (unless (eq side 'both)
  5130. (mod (org-knuth-hash pos)
  5131. org-element--cache-hash-size)))
  5132. (hashed (if (not side)
  5133. (aref org-element--cache-hash-left hash-pos)
  5134. (unless (eq side 'both)
  5135. (aref org-element--cache-hash-right hash-pos))))
  5136. lower upper)
  5137. ;; `org-element--cache-key-less-p' does not accept markers.
  5138. (when (markerp pos) (setq pos (marker-position pos)))
  5139. (cl-incf (cdr org-element--cache-hash-statistics))
  5140. (when (eq side 'both) (cl-incf org-element--cache-hash-nocache))
  5141. (if (and hashed (not (eq side 'both))
  5142. (or (not limit)
  5143. ;; Limit can be a list key.
  5144. (org-element--cache-key-less-p
  5145. (org-element--cache-key hashed)
  5146. limit))
  5147. (= pos (org-element-property :begin hashed))
  5148. ;; We cannot rely on element :begin for elements with
  5149. ;; children starting at the same pos.
  5150. (not (memq (org-element-type hashed)
  5151. '(section org-data table)))
  5152. (org-element-property :cached hashed))
  5153. (progn
  5154. (cl-incf (car org-element--cache-hash-statistics))
  5155. hashed)
  5156. (while node
  5157. (let* ((element (avl-tree--node-data node))
  5158. (begin (org-element-property :begin element)))
  5159. (cond
  5160. ((and limit
  5161. (not (org-element--cache-key-less-p
  5162. (org-element--cache-key element) limit)))
  5163. (setq node (avl-tree--node-left node)))
  5164. ((> begin pos)
  5165. (setq upper element
  5166. node (avl-tree--node-left node)))
  5167. ((or (< begin pos)
  5168. ;; If the element is section or org-data, we also need
  5169. ;; to check the following element.
  5170. (memq (org-element-type element) '(section org-data)))
  5171. (setq lower element
  5172. node (avl-tree--node-right node)))
  5173. ;; We found an element in cache starting at POS. If `side'
  5174. ;; is `both' we also want the next one in order to generate
  5175. ;; a key in-between.
  5176. ;;
  5177. ;; If the element is the first row or item in a table or
  5178. ;; a plain list, we always return the table or the plain
  5179. ;; list.
  5180. ;;
  5181. ;; In any other case, we return the element found.
  5182. ((eq side 'both)
  5183. (setq lower element)
  5184. (setq node (avl-tree--node-right node)))
  5185. ((and (memq (org-element-type element) '(item table-row))
  5186. (let ((parent (org-element-property :parent element)))
  5187. (and (= (org-element-property :begin element)
  5188. (org-element-property :contents-begin parent))
  5189. (setq node nil
  5190. lower parent
  5191. upper parent)))))
  5192. (t
  5193. (setq node nil
  5194. lower element
  5195. upper element)))))
  5196. (if (not side)
  5197. (aset org-element--cache-hash-left hash-pos lower)
  5198. (unless (eq side 'both)
  5199. (aset org-element--cache-hash-right hash-pos lower)))
  5200. (pcase side
  5201. (`both (cons lower upper))
  5202. (`nil lower)
  5203. (_ upper))))))
  5204. (defun org-element--cache-put (element)
  5205. "Store ELEMENT in current buffer's cache, if allowed."
  5206. (when (org-element--cache-active-p)
  5207. (when org-element--cache-sync-requests
  5208. ;; During synchronization, first build an appropriate key for
  5209. ;; the new element so `avl-tree-enter' can insert it at the
  5210. ;; right spot in the cache.
  5211. (let* ((keys (org-element--cache-find
  5212. (org-element-property :begin element) 'both))
  5213. (new-key (org-element--cache-generate-key
  5214. (and (car keys) (org-element--cache-key (car keys)))
  5215. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  5216. (org-element--cache-sync-requests
  5217. (org-element--request-key (car org-element--cache-sync-requests)))))))
  5218. (org-element-put-property
  5219. element
  5220. :org-element--cache-sync-key
  5221. (cons org-element--cache-sync-keys-value new-key))))
  5222. (when (>= org-element--cache-diagnostics-level 2)
  5223. (org-element--cache-log-message
  5224. "Added new element with %S key: %S"
  5225. (org-element-property :org-element--cache-sync-key element)
  5226. (org-element--format-element element)))
  5227. (org-element-put-property element :cached t)
  5228. (when (memq (org-element-type element) '(headline inlinetask))
  5229. (cl-incf org-element--headline-cache-size)
  5230. (avl-tree-enter org-element--headline-cache element))
  5231. (cl-incf org-element--cache-size)
  5232. (avl-tree-enter org-element--cache element)))
  5233. (defsubst org-element--cache-remove (element)
  5234. "Remove ELEMENT from cache.
  5235. Assume ELEMENT belongs to cache and that a cache is active."
  5236. (org-element-put-property element :cached nil)
  5237. (cl-decf org-element--cache-size)
  5238. ;; Invalidate contents of parent.
  5239. (when (and (org-element-property :parent element)
  5240. (org-element-contents (org-element-property :parent element)))
  5241. (org-element-set-contents (org-element-property :parent element) nil))
  5242. (when (memq (org-element-type element) '(headline inlinetask))
  5243. (cl-decf org-element--headline-cache-size)
  5244. (avl-tree-delete org-element--headline-cache element))
  5245. (or (avl-tree-delete org-element--cache element)
  5246. (progn
  5247. ;; This should not happen, but if it is, would be better to know
  5248. ;; where it happens.
  5249. (org-element--cache-warn
  5250. "Failed to delete %S element in %S at %S. The element cache key was %S.
  5251. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5252. (org-element-type element)
  5253. (current-buffer)
  5254. (org-element-property :begin element)
  5255. (org-element-property :org-element--cache-sync-key element))
  5256. (org-element-cache-reset)
  5257. (throw 'quit nil))))
  5258. ;;;; Synchronization
  5259. (defsubst org-element--cache-set-timer (buffer)
  5260. "Set idle timer for cache synchronization in BUFFER."
  5261. (when org-element--cache-sync-timer
  5262. (cancel-timer org-element--cache-sync-timer))
  5263. (setq org-element--cache-sync-timer
  5264. (run-with-idle-timer
  5265. (let ((idle (current-idle-time)))
  5266. (if idle (time-add idle org-element-cache-sync-break)
  5267. org-element-cache-sync-idle-time))
  5268. nil
  5269. #'org-element--cache-sync
  5270. buffer)))
  5271. (defsubst org-element--cache-interrupt-p (time-limit)
  5272. "Non-nil when synchronization process should be interrupted.
  5273. TIME-LIMIT is a time value or nil."
  5274. (and time-limit
  5275. (or (input-pending-p)
  5276. (time-less-p time-limit nil))))
  5277. (defsubst org-element--cache-shift-positions (element offset &optional props)
  5278. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  5279. Properties containing buffer positions are `:begin', `:end',
  5280. `:contents-begin', `:contents-end' and `:structure'. When
  5281. optional argument PROPS is a list of keywords, only shift
  5282. properties provided in that list.
  5283. Properties are modified by side-effect."
  5284. (let ((properties (nth 1 element)))
  5285. ;; Shift `:structure' property for the first plain list only: it
  5286. ;; is the only one that really matters and it prevents from
  5287. ;; shifting it more than once.
  5288. (when (and (or (not props) (memq :structure props))
  5289. (eq (org-element-type element) 'plain-list)
  5290. (not (eq (org-element-type (plist-get properties :parent)) 'item)))
  5291. (dolist (item (plist-get properties :structure))
  5292. (cl-incf (car item) offset)
  5293. (cl-incf (nth 6 item) offset)))
  5294. (dolist (key '( :begin :contents-begin :contents-end :end
  5295. :post-affiliated :robust-begin :robust-end))
  5296. (let ((value (and (or (not props) (memq key props))
  5297. (plist-get properties key))))
  5298. (and value (plist-put properties key (+ offset value)))))))
  5299. (defvar org-element--cache-interrupt-C-g t
  5300. "When non-nil, allow the user to abort `org-element--cache-sync'.
  5301. The execution is aborted upon pressing `\\[keyboard-quit]'
  5302. `org-element--cache-interrupt-C-g-max-count' times.")
  5303. (defvar org-element--cache-interrupt-C-g-max-count 5
  5304. "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
  5305. See `org-element--cache-interrupt-C-g'.")
  5306. (defvar org-element--cache-interrupt-C-g-count 0
  5307. "Current number of `org-element--cache-sync' calls.
  5308. See `org-element--cache-interrupt-C-g'.")
  5309. (defvar org-element--cache-change-warning nil
  5310. "Non-nil when a sensitive line is about to be changed.
  5311. It is a symbol among nil, t, or a number representing smallest level of
  5312. modified headline. The level considers headline levels both before
  5313. and after the modification.")
  5314. (defun org-element--cache-sync (buffer &optional threshold future-change offset)
  5315. "Synchronize cache with recent modification in BUFFER.
  5316. When optional argument THRESHOLD is non-nil, do the
  5317. synchronization for all elements starting before or at threshold,
  5318. then exit. Otherwise, synchronize cache for as long as
  5319. `org-element-cache-sync-duration' or until Emacs leaves idle
  5320. state.
  5321. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  5322. not registered yet in the cache are going to happen. OFFSET is the
  5323. change offset. It is used in `org-element--cache-submit-request',
  5324. where cache is partially updated before current modification are
  5325. actually submitted."
  5326. (when (buffer-live-p buffer)
  5327. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  5328. ;; Check if the buffer have been changed outside visibility of
  5329. ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
  5330. (if (and (/= org-element--cache-change-tic
  5331. (buffer-chars-modified-tick))
  5332. org-element--cache-silent-modification-check
  5333. ;; FIXME: Below is a heuristics noticed by observation.
  5334. ;; quail.el with non-latin input does silent
  5335. ;; modifications in buffer increasing the tick counter
  5336. ;; but not actually changing the buffer text:
  5337. ;; https://list.orgmode.org/87sfw2luhj.fsf@localhost/T/#you
  5338. ;; https://lists.gnu.org/archive/html/bug-gnu-emacs/2021-11/msg00894.html
  5339. ;; However, the values of `buffer-chars-modified-tick'
  5340. ;; and `buffer-modified-tick' appear to be same after
  5341. ;; the quail.el's changes in buffer. We do not
  5342. ;; consider these exact changes as a dangerous silent
  5343. ;; edit.
  5344. (/= (buffer-chars-modified-tick)
  5345. (buffer-modified-tick)))
  5346. (progn
  5347. (when (or (and org-element--cache-diagnostics-modifications
  5348. ;; A number of Emacs internal operations in
  5349. ;; Emacs 26 and 27 alter
  5350. ;; `buffer-chars-modified-tick' (see
  5351. ;; https://list.orgmode.org/87ee7jdv70.fsf@localhost/T/#t
  5352. ;; https://list.orgmode.org/2022-01-06T12-13-17@devnull.Karl-Voit.at/T/#mb3771758f81b31721ba2f420878a4d16081dc483).
  5353. ;; We have no way to distinguish them from
  5354. ;; dangerious silent edits. So, we can
  5355. ;; only reset the cache, but do not show
  5356. ;; warning to not irritate the users.)
  5357. (not (version< emacs-version "28")))
  5358. (and (boundp 'org-batch-test) org-batch-test))
  5359. (org-element--cache-warn
  5360. "Unregistered buffer modifications detected. Resetting.
  5361. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  5362. The buffer is: %s\n Current command: %S\n Chars modified: %S\n Buffer modified: %S\n Backtrace:\n%S"
  5363. (buffer-name (current-buffer))
  5364. (list this-command (buffer-chars-modified-tick) (buffer-modified-tick))
  5365. (buffer-chars-modified-tick)
  5366. (buffer-modified-tick)
  5367. (when (and (fboundp 'backtrace-get-frames)
  5368. (fboundp 'backtrace-to-string))
  5369. (backtrace-to-string (backtrace-get-frames 'backtrace)))))
  5370. (org-element-cache-reset))
  5371. (let ((inhibit-quit t) request next)
  5372. (setq org-element--cache-interrupt-C-g-count 0)
  5373. (when org-element--cache-sync-timer
  5374. (cancel-timer org-element--cache-sync-timer))
  5375. (let ((time-limit (time-add nil org-element-cache-sync-duration)))
  5376. (catch 'org-element--cache-interrupt
  5377. (when org-element--cache-sync-requests
  5378. (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
  5379. (while org-element--cache-sync-requests
  5380. (setq request (car org-element--cache-sync-requests)
  5381. next (nth 1 org-element--cache-sync-requests))
  5382. (org-element--cache-process-request
  5383. request
  5384. (when next (org-element--request-key next))
  5385. threshold
  5386. (unless threshold time-limit)
  5387. future-change
  5388. offset)
  5389. ;; Re-assign current and next requests. It could have
  5390. ;; been altered during phase 1.
  5391. (setq request (car org-element--cache-sync-requests)
  5392. next (nth 1 org-element--cache-sync-requests))
  5393. ;; Request processed. Merge current and next offsets and
  5394. ;; transfer ending position.
  5395. (when next
  5396. ;; The following requests can only be either phase 1
  5397. ;; or phase 2 requests. We need to let them know
  5398. ;; that additional shifting happened ahead of them.
  5399. (cl-incf (org-element--request-offset next) (org-element--request-offset request))
  5400. (org-element--cache-log-message
  5401. "Updating next request offset to %S: %s"
  5402. (org-element--request-offset next)
  5403. (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
  5404. ;; FIXME: END part of the request only matters for
  5405. ;; phase 0 requests. However, the only possible
  5406. ;; phase 0 request must be the first request in the
  5407. ;; list all the time. END position should be
  5408. ;; unused.
  5409. (setf (org-element--request-end next) (org-element--request-end request)))
  5410. (setq org-element--cache-sync-requests
  5411. (cdr org-element--cache-sync-requests)))))
  5412. ;; If more requests are awaiting, set idle timer accordingly.
  5413. ;; Otherwise, reset keys.
  5414. (if org-element--cache-sync-requests
  5415. (org-element--cache-set-timer buffer)
  5416. (setq org-element--cache-change-warning nil)
  5417. (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value))))))))
  5418. (defun org-element--cache-process-request
  5419. (request next-request-key threshold time-limit future-change offset)
  5420. "Process synchronization REQUEST for all entries before NEXT.
  5421. REQUEST is a vector, built by `org-element--cache-submit-request'.
  5422. NEXT-REQUEST-KEY is a cache key of the next request, as returned by
  5423. `org-element--cache-key'.
  5424. When non-nil, THRESHOLD is a buffer position. Synchronization
  5425. stops as soon as a shifted element begins after it.
  5426. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  5427. after this time or when Emacs exits idle state.
  5428. When non-nil, FUTURE-CHANGE is a buffer position where changes not
  5429. registered yet in the cache are going to happen. OFFSET is the
  5430. changed text length. See `org-element--cache-submit-request' for more
  5431. information.
  5432. Throw `org-element--cache-interrupt' if the process stops before
  5433. completing the request."
  5434. (org-element--cache-log-message
  5435. "org-element-cache: Processing request %s up to %S-%S, next: %S"
  5436. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5437. future-change
  5438. threshold
  5439. next-request-key)
  5440. (catch 'org-element--cache-quit
  5441. (when (= (org-element--request-phase request) 0)
  5442. ;; Phase 0.
  5443. ;;
  5444. ;; Delete all elements starting after beginning of the element
  5445. ;; with request key NEXT, but not after buffer position END.
  5446. ;;
  5447. ;; At each iteration, we start again at tree root since
  5448. ;; a deletion modifies structure of the balanced tree.
  5449. (org-element--cache-log-message "Phase 0")
  5450. (catch 'org-element--cache-end-phase
  5451. (let ((deletion-count 0))
  5452. (while t
  5453. (when (org-element--cache-interrupt-p time-limit)
  5454. (org-element--cache-log-message "Interrupt: time limit")
  5455. (throw 'org-element--cache-interrupt nil))
  5456. (let ((request-key (org-element--request-key request))
  5457. (end (org-element--request-end request))
  5458. (node (org-element--cache-root))
  5459. data data-key)
  5460. ;; Find first element in cache with key REQUEST-KEY or
  5461. ;; after it.
  5462. (while node
  5463. (let* ((element (avl-tree--node-data node))
  5464. (key (org-element--cache-key element)))
  5465. (cond
  5466. ((org-element--cache-key-less-p key request-key)
  5467. (setq node (avl-tree--node-right node)))
  5468. ((org-element--cache-key-less-p request-key key)
  5469. (setq data element
  5470. data-key key
  5471. node (avl-tree--node-left node)))
  5472. (t (setq data element
  5473. data-key key
  5474. node nil)))))
  5475. (if data
  5476. ;; We found first element in cache starting at or
  5477. ;; after REQUEST-KEY.
  5478. (let ((pos (org-element-property :begin data)))
  5479. ;; FIXME: Maybe simply (< pos end)?
  5480. (if (<= pos end)
  5481. (progn
  5482. (org-element--cache-log-message "removing %S::%S"
  5483. (org-element-property :org-element--cache-sync-key data)
  5484. (org-element--format-element data))
  5485. (cl-incf deletion-count)
  5486. (org-element--cache-remove data)
  5487. (when (and (> (log org-element--cache-size 2) 10)
  5488. (> deletion-count
  5489. (/ org-element--cache-size (log org-element--cache-size 2))))
  5490. (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
  5491. deletion-count
  5492. org-element--cache-size
  5493. (log org-element--cache-size 2))
  5494. (org-element-cache-reset)
  5495. (throw 'org-element--cache-quit t)))
  5496. ;; Done deleting everthing starting before END.
  5497. ;; DATA-KEY is the first known element after END.
  5498. ;; Move on to phase 1.
  5499. (org-element--cache-log-message
  5500. "found element after %S: %S::%S"
  5501. end
  5502. (org-element-property :org-element--cache-sync-key data)
  5503. (org-element--format-element data))
  5504. (setf (org-element--request-key request) data-key)
  5505. (setf (org-element--request-beg request) pos)
  5506. (setf (org-element--request-phase request) 1)
  5507. (throw 'org-element--cache-end-phase nil)))
  5508. ;; No element starting after modifications left in
  5509. ;; cache: further processing is futile.
  5510. (org-element--cache-log-message
  5511. "Phase 0 deleted all elements in cache after %S!"
  5512. request-key)
  5513. (throw 'org-element--cache-quit t)))))))
  5514. (when (= (org-element--request-phase request) 1)
  5515. ;; Phase 1.
  5516. ;;
  5517. ;; Phase 0 left a hole in the cache. Some elements after it
  5518. ;; could have parents within. For example, in the following
  5519. ;; buffer:
  5520. ;;
  5521. ;; - item
  5522. ;;
  5523. ;;
  5524. ;; Paragraph1
  5525. ;;
  5526. ;; Paragraph2
  5527. ;;
  5528. ;; if we remove a blank line between "item" and "Paragraph1",
  5529. ;; everything down to "Paragraph2" is removed from cache. But
  5530. ;; the paragraph now belongs to the list, and its `:parent'
  5531. ;; property no longer is accurate.
  5532. ;;
  5533. ;; Therefore we need to parse again elements in the hole, or at
  5534. ;; least in its last section, so that we can re-parent
  5535. ;; subsequent elements, during phase 2.
  5536. ;;
  5537. ;; Note that we only need to get the parent from the first
  5538. ;; element in cache after the hole.
  5539. ;;
  5540. ;; When next key is lesser or equal to the current one, current
  5541. ;; request is inside a to-be-shifted part of the cache. It is
  5542. ;; fine because the order of elements will not be altered by
  5543. ;; shifting. However, we cannot know the real position of the
  5544. ;; unshifted NEXT element in the current request. So, we need
  5545. ;; to sort the request list according to keys and re-start
  5546. ;; processing from the new leftmost request.
  5547. (org-element--cache-log-message "Phase 1")
  5548. (let ((key (org-element--request-key request)))
  5549. (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
  5550. ;; In theory, the only case when requests are not
  5551. ;; ordered is when key of the next request is either the
  5552. ;; same with current key or it is a key for a removed
  5553. ;; element. Either way, we can simply merge the two
  5554. ;; requests.
  5555. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5556. (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
  5557. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5558. (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
  5559. (setf (org-element--request-key next-request) key)
  5560. (setf (org-element--request-beg next-request) (org-element--request-beg request))
  5561. (setf (org-element--request-phase next-request) 1)
  5562. (throw 'org-element--cache-quit t))))
  5563. ;; Next element will start at its beginning position plus
  5564. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  5565. ;; contains the real beginning position of the first element to
  5566. ;; shift and re-parent.
  5567. (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request)))
  5568. cached-before)
  5569. (cond ((and threshold (> limit threshold))
  5570. (org-element--cache-log-message "Interrupt: position %S after threshold %S" limit threshold)
  5571. (throw 'org-element--cache-interrupt nil))
  5572. ((and future-change (>= limit future-change))
  5573. ;; Changes happened around this element and they will
  5574. ;; trigger another phase 1 request. Skip re-parenting
  5575. ;; and simply proceed with shifting (phase 2) to make
  5576. ;; sure that followup phase 0 request for the recent
  5577. ;; changes can operate on the correctly shifted cache.
  5578. (org-element--cache-log-message "position %S after future change %S" limit future-change)
  5579. (setf (org-element--request-parent request) nil)
  5580. (setf (org-element--request-phase request) 2))
  5581. (t
  5582. (when future-change
  5583. ;; Changes happened, but not yet registered after
  5584. ;; this element. However, we a not yet safe to look
  5585. ;; at the buffer and parse elements in the cache gap.
  5586. ;; Some of the parents to be added to cache may end
  5587. ;; after the changes. Parsing this parents will
  5588. ;; assign the :end correct value for cache state
  5589. ;; after future-change. Then, when the future change
  5590. ;; is going to be processed, such parent boundary
  5591. ;; will be altered unnecessarily. To avoid this,
  5592. ;; we alter the new parents by -OFFSET.
  5593. ;; For now, just save last known cached element and
  5594. ;; then check all the parents below.
  5595. (setq cached-before (org-element--cache-find (1- limit) nil)))
  5596. ;; No relevant changes happened after submitting this
  5597. ;; request. We are safe to look at the actual Org
  5598. ;; buffer and calculate the new parent.
  5599. (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
  5600. (when future-change
  5601. ;; Check all the newly added parents to not
  5602. ;; intersect with future change.
  5603. (let ((up parent))
  5604. (while (and up
  5605. (or (not cached-before)
  5606. (> (org-element-property :begin up)
  5607. (org-element-property :begin cached-before))))
  5608. (when (> (org-element-property :end up) future-change)
  5609. ;; Offset future cache request.
  5610. (org-element--cache-shift-positions
  5611. up (- offset)
  5612. (if (and (org-element-property :robust-begin up)
  5613. (org-element-property :robust-end up))
  5614. '(:contents-end :end :robust-end)
  5615. '(:contents-end :end))))
  5616. (setq up (org-element-property :parent up)))))
  5617. (org-element--cache-log-message
  5618. "New parent at %S: %S::%S"
  5619. limit
  5620. (org-element-property :org-element--cache-sync-key parent)
  5621. (org-element--format-element parent))
  5622. (setf (org-element--request-parent request) parent)
  5623. (setf (org-element--request-phase request) 2))))))
  5624. ;; Phase 2.
  5625. ;;
  5626. ;; Shift all elements starting from key START, but before NEXT, by
  5627. ;; OFFSET, and re-parent them when appropriate.
  5628. ;;
  5629. ;; Elements are modified by side-effect so the tree structure
  5630. ;; remains intact.
  5631. ;;
  5632. ;; Once THRESHOLD, if any, is reached, or once there is an input
  5633. ;; pending, exit. Before leaving, the current synchronization
  5634. ;; request is updated.
  5635. (org-element--cache-log-message "Phase 2")
  5636. (let ((start (org-element--request-key request))
  5637. (offset (org-element--request-offset request))
  5638. (parent (org-element--request-parent request))
  5639. (node (org-element--cache-root))
  5640. (stack (list nil))
  5641. (leftp t)
  5642. exit-flag continue-flag)
  5643. ;; No re-parenting nor shifting planned: request is over.
  5644. (when (and (not parent) (zerop offset))
  5645. (org-element--cache-log-message "Empty offset. Request completed.")
  5646. (throw 'org-element--cache-quit t))
  5647. (while node
  5648. (let* ((data (avl-tree--node-data node))
  5649. (key (org-element--cache-key data)))
  5650. ;; Traverse the cache tree. Ignore all the elements before
  5651. ;; START. Note that `avl-tree-stack' would not bypass the
  5652. ;; elements before START and thus would have beeen less
  5653. ;; efficient.
  5654. (if (and leftp (avl-tree--node-left node)
  5655. (not (org-element--cache-key-less-p key start)))
  5656. (progn (push node stack)
  5657. (setq node (avl-tree--node-left node)))
  5658. ;; Shift and re-parent when current node starts at or
  5659. ;; after START, but before NEXT.
  5660. (unless (org-element--cache-key-less-p key start)
  5661. ;; We reached NEXT. Request is complete.
  5662. (when (and next-request-key
  5663. (not (org-element--cache-key-less-p key next-request-key)))
  5664. (org-element--cache-log-message "Reached next request.")
  5665. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5666. (unless (and (org-element-property :cached (org-element--request-parent next-request))
  5667. (org-element-property :begin (org-element--request-parent next-request))
  5668. parent
  5669. (> (org-element-property :begin (org-element--request-parent next-request))
  5670. (org-element-property :begin parent)))
  5671. (setf (org-element--request-parent next-request) parent)))
  5672. (throw 'org-element--cache-quit t))
  5673. ;; Handle interruption request. Update current request.
  5674. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  5675. (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
  5676. (setf (org-element--request-key request) key)
  5677. (setf (org-element--request-parent request) parent)
  5678. (throw 'org-element--cache-interrupt nil))
  5679. ;; Shift element.
  5680. (unless (zerop offset)
  5681. (when (>= org-element--cache-diagnostics-level 3)
  5682. (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
  5683. offset
  5684. (org-element-property :org-element--cache-sync-key data)
  5685. (org-element--format-element data)))
  5686. (org-element--cache-shift-positions data offset))
  5687. (let ((begin (org-element-property :begin data)))
  5688. ;; Update PARENT and re-parent DATA, only when
  5689. ;; necessary. Propagate new structures for lists.
  5690. (while (and parent
  5691. (<= (org-element-property :end parent) begin))
  5692. (setq parent (org-element-property :parent parent)))
  5693. (cond ((and (not parent) (zerop offset)) (throw 'org-element--cache-quit nil))
  5694. ;; Consider scenario when DATA lays within
  5695. ;; sensitive lines of PARENT that was found
  5696. ;; during phase 2. For example:
  5697. ;;
  5698. ;; #+ begin_quote
  5699. ;; Paragraph
  5700. ;; #+end_quote
  5701. ;;
  5702. ;; In the above source block, remove space in
  5703. ;; the first line will trigger re-parenting of
  5704. ;; the paragraph and "#+end_quote" that is also
  5705. ;; considered paragraph before the modification.
  5706. ;; However, the paragraph element stored in
  5707. ;; cache must be deleted instead.
  5708. ((and parent
  5709. (or (not (memq (org-element-type parent) org-element-greater-elements))
  5710. (and (org-element-property :contents-begin parent)
  5711. (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
  5712. (and (org-element-property :contents-end parent)
  5713. (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
  5714. (> (org-element-property :end data) (org-element-property :end parent))
  5715. (and (org-element-property :contents-end data)
  5716. (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
  5717. (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
  5718. (org-element-property :org-element--cache-sync-key data)
  5719. (org-element--format-element data))
  5720. (org-element--cache-remove data)
  5721. ;; We altered the tree structure. The tree
  5722. ;; traversal needs to be restarted.
  5723. (setf (org-element--request-key request) key)
  5724. (setf (org-element--request-parent request) parent)
  5725. ;; Restart tree traversal.
  5726. (setq node (org-element--cache-root)
  5727. stack (list nil)
  5728. leftp t
  5729. begin -1
  5730. continue-flag t))
  5731. ((and parent
  5732. (not (eq parent data))
  5733. (let ((p (org-element-property :parent data)))
  5734. (or (not p)
  5735. (< (org-element-property :begin p)
  5736. (org-element-property :begin parent))
  5737. (unless (eq p parent)
  5738. (not (org-element-property :cached p))
  5739. ;; (not (avl-tree-member-p org-element--cache p))
  5740. ))))
  5741. (org-element--cache-log-message
  5742. "Updating parent in %S\n Old parent: %S\n New parent: %S"
  5743. (org-element--format-element data)
  5744. (org-element--format-element (org-element-property :parent data))
  5745. (org-element--format-element parent))
  5746. (when (and (eq 'org-data (org-element-type parent))
  5747. (not (eq 'headline (org-element-type data))))
  5748. ;; FIXME: This check is here to see whether
  5749. ;; such error happens within
  5750. ;; `org-element--cache-process-request' or somewhere
  5751. ;; else.
  5752. (org-element--cache-warn
  5753. "Added org-data parent to non-headline element: %S
  5754. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5755. data)
  5756. (org-element-cache-reset)
  5757. (throw 'org-element--cache-quit t))
  5758. (org-element-put-property data :parent parent)
  5759. (let ((s (org-element-property :structure parent)))
  5760. (when (and s (org-element-property :structure data))
  5761. (org-element-put-property data :structure s)))))
  5762. ;; Cache is up-to-date past THRESHOLD. Request
  5763. ;; interruption.
  5764. (when (and threshold (> begin threshold))
  5765. (org-element--cache-log-message "Reached threshold %S: %S"
  5766. threshold
  5767. (org-element--format-element data))
  5768. (setq exit-flag t))))
  5769. (if continue-flag
  5770. (setq continue-flag nil)
  5771. (setq node (if (setq leftp (avl-tree--node-right node))
  5772. (avl-tree--node-right node)
  5773. (pop stack)))))))
  5774. ;; We reached end of tree: synchronization complete.
  5775. t))
  5776. (org-element--cache-log-message
  5777. "org-element-cache: Finished process. The cache size is %S. The remaining sync requests: %S"
  5778. org-element--cache-size
  5779. (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests))))
  5780. (defsubst org-element--open-end-p (element)
  5781. "Check if ELEMENT in current buffer contains extra blank lines after
  5782. it and does not have closing term.
  5783. Examples of such elements are: section, headline, org-data,
  5784. and footnote-definition."
  5785. (and (org-element-property :contents-end element)
  5786. (= (org-element-property :contents-end element)
  5787. (save-excursion
  5788. (goto-char (org-element-property :end element))
  5789. (skip-chars-backward " \r\n\t")
  5790. (line-beginning-position 2)))))
  5791. (defun org-element--parse-to (pos &optional syncp time-limit)
  5792. "Parse elements in current section, down to POS.
  5793. Start parsing from the closest between the last known element in
  5794. cache or headline above. Return the smallest element containing
  5795. POS.
  5796. When optional argument SYNCP is non-nil, return the parent of the
  5797. element containing POS instead. In that case, it is also
  5798. possible to provide TIME-LIMIT, which is a time value specifying
  5799. when the parsing should stop. The function throws
  5800. `org-element--cache-interrupt' if the process stopped before finding
  5801. the expected result."
  5802. (catch 'exit
  5803. (save-match-data
  5804. (org-with-wide-buffer
  5805. (goto-char pos)
  5806. (save-excursion
  5807. (end-of-line)
  5808. (skip-chars-backward " \r\t\n")
  5809. ;; Within blank lines at the beginning of buffer, return nil.
  5810. (when (bobp) (throw 'exit nil)))
  5811. (let* ((cached (and (org-element--cache-active-p)
  5812. (org-element--cache-find pos nil)))
  5813. (mode (org-element-property :mode cached))
  5814. element next)
  5815. (cond
  5816. ;; Nothing in cache before point: start parsing from first
  5817. ;; element in buffer down to POS or from the beginning of the
  5818. ;; file.
  5819. ((and (not cached) (org-element--cache-active-p))
  5820. (setq element (org-element-org-data-parser))
  5821. (unless (org-element-property :begin element)
  5822. (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
  5823. (org-element--cache-log-message
  5824. "Nothing in cache. Adding org-data: %S"
  5825. (org-element--format-element element))
  5826. (org-element--cache-put element)
  5827. (goto-char (org-element-property :contents-begin element))
  5828. (setq mode 'org-data))
  5829. ;; Nothing in cache before point because cache is not active.
  5830. ;; Parse from previous heading to avoid re-parsing the whole
  5831. ;; buffer above. This comes at the cost of not calculating
  5832. ;; `:parent' property for headings.
  5833. ((not cached)
  5834. (if (org-with-limited-levels (outline-previous-heading))
  5835. (progn
  5836. (setq element (org-element-headline-parser nil 'fast))
  5837. (setq mode 'planning)
  5838. (forward-line))
  5839. (setq element (org-element-org-data-parser))
  5840. (setq mode 'org-data))
  5841. (org-skip-whitespace)
  5842. (beginning-of-line))
  5843. ;; Check if CACHED or any of its ancestors contain point.
  5844. ;;
  5845. ;; If there is such an element, we inspect it in order to know
  5846. ;; if we return it or if we need to parse its contents.
  5847. ;; Otherwise, we just start parsing from location, which is
  5848. ;; right after the top-most element containing CACHED but
  5849. ;; still before POS.
  5850. ;;
  5851. ;; As a special case, if POS is at the end of the buffer, we
  5852. ;; want to return the innermost element ending there.
  5853. ;;
  5854. ;; Also, if we find an ancestor and discover that we need to
  5855. ;; parse its contents, make sure we don't start from
  5856. ;; `:contents-begin', as we would otherwise go past CACHED
  5857. ;; again. Instead, in that situation, we will resume parsing
  5858. ;; from NEXT, which is located after CACHED or its higher
  5859. ;; ancestor not containing point.
  5860. (t
  5861. (let ((up cached)
  5862. (pos (if (= (point-max) pos) (1- pos) pos)))
  5863. (while (and up (<= (org-element-property :end up) pos))
  5864. (goto-char (org-element-property :end up))
  5865. (setq element up
  5866. mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
  5867. up (org-element-property :parent up)
  5868. next (point)))
  5869. (when up (setq element up)))))
  5870. ;; Parse successively each element until we reach POS.
  5871. (let ((end (or (org-element-property :end element) (point-max)))
  5872. (parent (org-element-property :parent element)))
  5873. (while t
  5874. (when (org-element--cache-interrupt-p time-limit)
  5875. (throw 'org-element--cache-interrupt nil))
  5876. (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
  5877. (when quit-flag
  5878. (cl-incf org-element--cache-interrupt-C-g-count)
  5879. (setq quit-flag nil))
  5880. (when (>= org-element--cache-interrupt-C-g-count
  5881. org-element--cache-interrupt-C-g-max-count)
  5882. (setq quit-flag t)
  5883. (setq org-element--cache-interrupt-C-g-count 0)
  5884. (org-element-cache-reset)
  5885. (error "org-element: Parsing aborted by user. Cache has been cleared.
  5886. If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
  5887. (message (substitute-command-keys
  5888. "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
  5889. (- org-element--cache-interrupt-C-g-max-count
  5890. org-element--cache-interrupt-C-g-count)))
  5891. (unless element
  5892. ;; Do not try to parse within blank at EOB.
  5893. (unless (save-excursion
  5894. (org-skip-whitespace)
  5895. (eobp))
  5896. (org-element-with-disabled-cache
  5897. (setq element (org-element--current-element
  5898. end 'element mode
  5899. (org-element-property :structure parent)))))
  5900. ;; Make sure that we return referenced element in cache
  5901. ;; that can be altered directly.
  5902. (if element
  5903. (setq element (or (org-element--cache-put element) element))
  5904. ;; Nothing to parse (i.e. empty file).
  5905. (throw 'exit parent))
  5906. (unless (or (not (org-element--cache-active-p)) parent)
  5907. (org-element--cache-warn
  5908. "Got empty parent while parsing. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n Backtrace:\n%S"
  5909. (when (and (fboundp 'backtrace-get-frames)
  5910. (fboundp 'backtrace-to-string))
  5911. (backtrace-to-string (backtrace-get-frames 'backtrace))
  5912. (org-element-cache-reset)
  5913. (error "org-element--cache: Emergency exit"))))
  5914. (org-element-put-property element :parent parent))
  5915. (let ((elem-end (org-element-property :end element))
  5916. (type (org-element-type element)))
  5917. (cond
  5918. ;; Skip any element ending before point. Also skip
  5919. ;; element ending at point (unless it is also the end of
  5920. ;; buffer) since we're sure that another element begins
  5921. ;; after it.
  5922. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5923. ;; Avoid parsing headline siblings above.
  5924. (goto-char elem-end)
  5925. (when (eq type 'headline)
  5926. (save-match-data
  5927. (unless (when (and (/= 1 (org-element-property :level element))
  5928. (re-search-forward
  5929. (rx-to-string
  5930. `(and bol (repeat 1 ,(1- (let ((level (org-element-property :level element)))
  5931. (if org-odd-levels-only (1- (* level 2)) level)))
  5932. "*")
  5933. " "))
  5934. pos t))
  5935. (beginning-of-line)
  5936. t)
  5937. ;; There are headings with lower level than
  5938. ;; ELEMENT between ELEM-END and POS. Siblings
  5939. ;; may exist though. Parse starting from the
  5940. ;; last sibling or from ELEM-END if there are
  5941. ;; no other siblings.
  5942. (goto-char pos)
  5943. (unless
  5944. (re-search-backward
  5945. (rx-to-string
  5946. `(and bol (repeat ,(let ((level (org-element-property :level element)))
  5947. (if org-odd-levels-only (1- (* level 2)) level))
  5948. "*")
  5949. " "))
  5950. elem-end t)
  5951. ;; Roll-back to normal parsing.
  5952. (goto-char elem-end)))))
  5953. (setq mode (org-element--next-mode mode type nil)))
  5954. ;; A non-greater element contains point: return it.
  5955. ((not (memq type org-element-greater-elements))
  5956. (throw 'exit (if syncp parent element)))
  5957. ;; Otherwise, we have to decide if ELEMENT really
  5958. ;; contains POS. In that case we start parsing from
  5959. ;; contents' beginning.
  5960. ;;
  5961. ;; If POS is at contents' beginning but it is also at
  5962. ;; the beginning of the first item in a list or a table.
  5963. ;; In that case, we need to create an anchor for that
  5964. ;; list or table, so return it.
  5965. ;;
  5966. ;; Also, if POS is at the end of the buffer, no element
  5967. ;; can start after it, but more than one may end there.
  5968. ;; Arbitrarily, we choose to return the innermost of
  5969. ;; such elements.
  5970. ((let ((cbeg (org-element-property :contents-begin element))
  5971. (cend (org-element-property :contents-end element)))
  5972. (when (and cbeg cend
  5973. (or (< cbeg pos)
  5974. (and (= cbeg pos)
  5975. (not (memq type '(plain-list table)))))
  5976. (or (> cend pos)
  5977. ;; When we are at cend or within blank
  5978. ;; lines after, it is a special case:
  5979. ;; 1. At the end of buffer we return
  5980. ;; the innermost element.
  5981. ;; 2. At cend of element with return
  5982. ;; that element.
  5983. ;; 3. At the end of element, we would
  5984. ;; return in the earlier cond form.
  5985. ;; 4. Within blank lines after cend,
  5986. ;; when element does not have a
  5987. ;; closing keyword, we return that
  5988. ;; outermost element, unless the
  5989. ;; outermost element is a non-empty
  5990. ;; headline. In the latter case, we
  5991. ;; return the outermost element inside
  5992. ;; the headline section.
  5993. (and (org-element--open-end-p element)
  5994. (or (= (org-element-property :end element) (point-max))
  5995. (and (>= pos (org-element-property :contents-end element))
  5996. (memq (org-element-type element) '(org-data section headline)))))))
  5997. (goto-char (or next cbeg))
  5998. (setq mode (if next mode (org-element--next-mode mode type t))
  5999. next nil
  6000. parent element
  6001. end (if (org-element--open-end-p element)
  6002. (org-element-property :end element)
  6003. (org-element-property :contents-end element))))))
  6004. ;; Otherwise, return ELEMENT as it is the smallest
  6005. ;; element containing POS.
  6006. (t (throw 'exit (if syncp parent element)))))
  6007. (setq element nil))))))))
  6008. ;;;; Staging Buffer Changes
  6009. (defconst org-element--cache-sensitive-re
  6010. (concat
  6011. "^\\*+ " "\\|"
  6012. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  6013. "^[ \t]*\\(?:"
  6014. "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
  6015. org-list-full-item-re "\\|"
  6016. ":\\(?: \\|$\\)" "\\|"
  6017. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  6018. "\\)")
  6019. "Regexp matching a sensitive line, structure wise.
  6020. A sensitive line is a headline, inlinetask, block, drawer, or
  6021. latex-environment boundary. When such a line is modified,
  6022. structure changes in the document may propagate in the whole
  6023. section, possibly making cache invalid.")
  6024. (defun org-element--cache-before-change (beg end)
  6025. "Detect modifications in sensitive parts of Org buffer.
  6026. BEG and END are the beginning and end of the range of changed
  6027. text. See `before-change-functions' for more information.
  6028. The function returns the new value of `org-element--cache-change-warning'."
  6029. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6030. (current-buffer))
  6031. (when (org-element--cache-active-p t)
  6032. (org-with-wide-buffer
  6033. (setq org-element--cache-change-tic (buffer-chars-modified-tick))
  6034. (goto-char beg)
  6035. (beginning-of-line)
  6036. (let ((bottom (save-excursion
  6037. (goto-char end)
  6038. (if (and (bolp)
  6039. ;; When beg == end, still extent to eol.
  6040. (> (point) beg))
  6041. ;; FIXME: Potential pitfall.
  6042. ;; We are appending to an element end.
  6043. ;; Unless the last inserted char is not
  6044. ;; newline, the next element is not broken
  6045. ;; and does not need to be purged from the
  6046. ;; cache.
  6047. end
  6048. (line-end-position)))))
  6049. (prog1
  6050. ;; Use the worst change warning to not miss important edits.
  6051. ;; This function is called before edit and after edit by
  6052. ;; `org-element--cache-after-change'. Before the edit, we still
  6053. ;; want to use the old value if it comes from previous
  6054. ;; not yet processed edit (they may be merged by
  6055. ;; `org-element--cache-submit-request'). After the edit, we want to
  6056. ;; look if there was a sensitive removed during edit.
  6057. ;; FIXME: This is not the most efficient way and we now
  6058. ;; have to delete more elemetns than needed in some
  6059. ;; cases. A better approach may be storing the warning
  6060. ;; in the modification request itself.
  6061. (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
  6062. (org-element--cache-change-warning-after))
  6063. (setq org-element--cache-change-warning-after
  6064. (save-match-data
  6065. (let ((case-fold-search t))
  6066. (when (re-search-forward
  6067. org-element--cache-sensitive-re bottom t)
  6068. (goto-char beg)
  6069. (beginning-of-line)
  6070. (let (min-level)
  6071. (cl-loop while (re-search-forward
  6072. (rx-to-string
  6073. (if (and min-level
  6074. (> min-level 1))
  6075. `(and bol (repeat 1 ,(1- min-level) "*") " ")
  6076. `(and bol (+ "*") " ")))
  6077. bottom t)
  6078. do (setq min-level (1- (length (match-string 0))))
  6079. until (= min-level 1))
  6080. (goto-char beg)
  6081. (beginning-of-line)
  6082. (or (and min-level (org-reduced-level min-level))
  6083. (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
  6084. 'org-data)
  6085. t))))))
  6086. (setq org-element--cache-change-warning
  6087. (cond
  6088. ((and (numberp org-element--cache-change-warning-before)
  6089. (numberp org-element--cache-change-warning-after))
  6090. (min org-element--cache-change-warning-after
  6091. org-element--cache-change-warning-before))
  6092. ((numberp org-element--cache-change-warning-before)
  6093. org-element--cache-change-warning-before)
  6094. ((numberp org-element--cache-change-warning-after)
  6095. org-element--cache-change-warning-after)
  6096. (t (or org-element--cache-change-warning-after
  6097. org-element--cache-change-warning-before)))))
  6098. (org-element--cache-log-message
  6099. "%S is about to modify text: warning %S"
  6100. this-command
  6101. org-element--cache-change-warning)))))))
  6102. (defun org-element--cache-after-change (beg end pre)
  6103. "Update buffer modifications for current buffer.
  6104. BEG and END are the beginning and end of the range of changed
  6105. text, and the length in bytes of the pre-change text replaced by
  6106. that range. See `after-change-functions' for more information."
  6107. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6108. (current-buffer))
  6109. (when (org-element--cache-active-p t)
  6110. (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
  6111. (org-element--cache-log-message "After change")
  6112. (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
  6113. ;; If beg is right after spaces in front of an element, we
  6114. ;; risk affecting previous element, so move beg to bol, making
  6115. ;; sure that we capture preceding element.
  6116. (setq beg (save-excursion
  6117. (goto-char beg)
  6118. (cl-incf pre (- beg (line-beginning-position)))
  6119. (line-beginning-position)))
  6120. ;; Store synchronization request.
  6121. (let ((offset (- end beg pre)))
  6122. (save-match-data
  6123. (org-element--cache-submit-request beg (- end offset) offset)))
  6124. ;; Activate a timer to process the request during idle time.
  6125. (org-element--cache-set-timer (current-buffer))))))
  6126. (defvar org-element--cache-avoid-synchronous-headline-re-parsing nil
  6127. "This variable controls how buffer changes are handled by the cache.
  6128. By default (when this variable is nil), cache re-parses modified
  6129. headlines immidiately after modification preserving all the unaffected
  6130. elements inside the headline.
  6131. The default behaviour works best when users types inside Org buffer of
  6132. when buffer modifications are mixed with cache requests. However,
  6133. large automated edits inserting/deleting many headlines are somewhat
  6134. slower by default (as in `org-archive-subtree'). Let-binding this
  6135. variable to non-nil will reduce cache latency after every singular edit
  6136. (`after-change-functions') at the cost of slower cache queries.")
  6137. (defun org-element--cache-for-removal (beg end offset)
  6138. "Return first element to remove from cache.
  6139. BEG and END are buffer positions delimiting buffer modifications.
  6140. OFFSET is the size of the changes.
  6141. Returned element is usually the first element in cache containing
  6142. any position between BEG and END. As an exception, greater
  6143. elements around the changes that are robust to contents
  6144. modifications are preserved and updated according to the
  6145. changes. In the latter case, the returned element is the outermost
  6146. non-robust element affected by the changes. Note that the returned
  6147. element may end before END position in which case some cached element
  6148. starting after the returned may still be affected by the changes.
  6149. Also, when there are no elements in cache before BEG, return first
  6150. known element in cache (it may start after END)."
  6151. (let* ((elements (org-element--cache-find (1- beg) 'both))
  6152. (before (car elements))
  6153. (after (cdr elements)))
  6154. (if (not before) after
  6155. ;; If BEFORE is a keyword, it may need to be removed to become
  6156. ;; an affiliated keyword.
  6157. (when (eq 'keyword (org-element-type before))
  6158. (let ((prev before))
  6159. (while (eq 'keyword (org-element-type prev))
  6160. (setq before prev
  6161. beg (org-element-property :begin prev))
  6162. (setq prev (org-element--cache-find (1- (org-element-property :begin before)))))))
  6163. (let ((up before)
  6164. (robust-flag t))
  6165. (while up
  6166. (if (let ((type (org-element-type up)))
  6167. (or (and (memq type '( center-block dynamic-block
  6168. quote-block special-block
  6169. drawer))
  6170. (or (not (eq type 'drawer))
  6171. (not (string= "PROPERTIES" (org-element-property :drawer-name up))))
  6172. ;; Sensitive change. This is
  6173. ;; unconditionally non-robust change.
  6174. (not org-element--cache-change-warning)
  6175. (let ((cbeg (org-element-property :contents-begin up))
  6176. (cend (org-element-property :contents-end up)))
  6177. (and cbeg
  6178. (<= cbeg beg)
  6179. (or (> cend end)
  6180. (and (= cend end)
  6181. (= (+ end offset) (point-max)))))))
  6182. (and (memq type '(headline section org-data))
  6183. (let ((rbeg (org-element-property :robust-begin up))
  6184. (rend (org-element-property :robust-end up)))
  6185. (and rbeg rend
  6186. (<= rbeg beg)
  6187. (or (> rend end)
  6188. (and (= rend end)
  6189. (= (+ end offset) (point-max))))))
  6190. (pcase type
  6191. ;; Sensitive change in section. Need to
  6192. ;; re-parse.
  6193. (`section (not org-element--cache-change-warning))
  6194. ;; Headline might be inserted. This is non-robust
  6195. ;; change when `up' is a `headline' or `section'
  6196. ;; with `>' level compared to the inserted headline.
  6197. ;;
  6198. ;; Also, planning info/property drawer
  6199. ;; could have been inserted. It is not
  6200. ;; robust change then.
  6201. (`headline
  6202. (and
  6203. (or (not (numberp org-element--cache-change-warning))
  6204. (> org-element--cache-change-warning
  6205. (org-element-property :level up)))
  6206. (org-with-point-at (org-element-property :contents-begin up)
  6207. (unless
  6208. (save-match-data
  6209. (when (looking-at-p org-element-planning-line-re)
  6210. (forward-line))
  6211. (when (looking-at org-property-drawer-re)
  6212. (< beg (match-end 0))))
  6213. 'robust))))
  6214. (`org-data (and (not (eq org-element--cache-change-warning 'org-data))
  6215. ;; Property drawer could
  6216. ;; have been inserted. It
  6217. ;; is not robust change
  6218. ;; then.
  6219. (org-with-wide-buffer
  6220. (goto-char (point-min))
  6221. (while (and (org-at-comment-p) (bolp)) (forward-line))
  6222. ;; Should not see property
  6223. ;; drawer within changed
  6224. ;; region.
  6225. (save-match-data
  6226. (or (not (looking-at org-property-drawer-re))
  6227. (> beg (match-end 0)))))))
  6228. (_ 'robust)))))
  6229. ;; UP is a robust greater element containing changes.
  6230. ;; We only need to extend its ending boundaries.
  6231. (progn
  6232. (org-element--cache-shift-positions
  6233. up offset
  6234. (if (and (org-element-property :robust-begin up)
  6235. (org-element-property :robust-end up))
  6236. '(:contents-end :end :robust-end)
  6237. '(:contents-end :end)))
  6238. (org-element--cache-log-message
  6239. "Shifting end positions of robust parent: %S"
  6240. (org-element--format-element up)))
  6241. (unless (or
  6242. ;; UP is non-robust. Yet, if UP is headline, flagging
  6243. ;; everything inside for removal may be to
  6244. ;; costly. Instead, we should better re-parse only the
  6245. ;; headline itself when possible. If a headline is still
  6246. ;; starting from old :begin position, we do not care that
  6247. ;; its boundaries could have extended to shrinked - we
  6248. ;; will re-parent and shift them anyway.
  6249. (and (eq 'headline (org-element-type up))
  6250. (not org-element--cache-avoid-synchronous-headline-re-parsing)
  6251. ;; The change is not inside headline. Not
  6252. ;; updating here.
  6253. (not (<= beg (org-element-property :begin up)))
  6254. (not (> end (org-element-property :end up)))
  6255. (let ((current (org-with-point-at (org-element-property :begin up)
  6256. (org-element-with-disabled-cache
  6257. (and (looking-at-p org-element-headline-re)
  6258. (org-element-headline-parser nil t))))))
  6259. (when (eq 'headline (org-element-type current))
  6260. (org-element--cache-log-message
  6261. "Found non-robust headline that can be updated individually: %S"
  6262. (org-element--format-element current))
  6263. (org-element-set-element up current)
  6264. t)))
  6265. ;; If UP is org-data, the situation is similar to
  6266. ;; headline case. We just need to re-parse the
  6267. ;; org-data itself, unless the change is made
  6268. ;; within blank lines at BOB (that could
  6269. ;; potentially alter first-section).
  6270. (when (and (eq 'org-data (org-element-type up))
  6271. (>= beg (org-element-property :contents-begin up)))
  6272. (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
  6273. (org-element--cache-log-message
  6274. "Found non-robust change invalidating org-data. Re-parsing: %S"
  6275. (org-element--format-element up))
  6276. t))
  6277. (org-element--cache-log-message
  6278. "Found non-robust element: %S"
  6279. (org-element--format-element up))
  6280. (setq before up)
  6281. (when robust-flag (setq robust-flag nil))))
  6282. (unless (or (org-element-property :parent up)
  6283. (eq 'org-data (org-element-type up)))
  6284. (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)
  6285. (org-element-cache-reset)
  6286. (error "org-element--cache: Emergency exit"))
  6287. (setq up (org-element-property :parent up)))
  6288. ;; We're at top level element containing ELEMENT: if it's
  6289. ;; altered by buffer modifications, it is first element in
  6290. ;; cache to be removed. Otherwise, that first element is the
  6291. ;; following one.
  6292. ;;
  6293. ;; As a special case, do not remove BEFORE if it is a robust
  6294. ;; container for current changes.
  6295. (if (or (< (org-element-property :end before) beg) robust-flag) after
  6296. before)))))
  6297. (defun org-element--cache-submit-request (beg end offset)
  6298. "Submit a new cache synchronization request for current buffer.
  6299. BEG and END are buffer positions delimiting the minimal area
  6300. where cache data should be removed. OFFSET is the size of the
  6301. change, as an integer."
  6302. (org-element--cache-log-message
  6303. "Submitting new synchronization request for [%S..%S]𝝙%S"
  6304. beg end offset)
  6305. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6306. (current-buffer))
  6307. (let ((next (car org-element--cache-sync-requests))
  6308. delete-to delete-from)
  6309. (if (and next
  6310. ;; First existing sync request is in phase 0.
  6311. (= 0 (org-element--request-phase next))
  6312. ;; Current changes intersect with the first sync request.
  6313. (> (setq delete-to (+ (org-element--request-end next)
  6314. (org-element--request-offset next)))
  6315. end)
  6316. (<= (setq delete-from (org-element--request-beg next))
  6317. end))
  6318. ;; Current changes can be merged with first sync request: we
  6319. ;; can save a partial cache synchronization.
  6320. (progn
  6321. (org-element--cache-log-message "Found another phase 0 request intersecting with current")
  6322. ;; Update OFFSET of the existing request.
  6323. (cl-incf (org-element--request-offset next) offset)
  6324. ;; If last change happened within area to be removed, extend
  6325. ;; boundaries of robust parents, if any. Otherwise, find
  6326. ;; first element to remove and update request accordingly.
  6327. (if (> beg delete-from)
  6328. ;; The current modification is completely inside NEXT.
  6329. ;; We already added the current OFFSET to the NEXT
  6330. ;; request. However, the robust elements around
  6331. ;; modifications also need to be shifted. Moreover, the
  6332. ;; new modification may also have non-nil
  6333. ;; `org-element--cache-change-warning'. In the latter case, we
  6334. ;; also need to update the request.
  6335. (let ((first (org-element--cache-for-removal delete-from end offset) ; Shift as needed.
  6336. ))
  6337. (org-element--cache-log-message
  6338. "Current request is inside next. Candidate parent: %S"
  6339. (org-element--format-element first))
  6340. (when
  6341. ;; Non-robust element is now before NEXT. Need to
  6342. ;; update.
  6343. (and first
  6344. (org-element--cache-key-less-p
  6345. (org-element--cache-key first)
  6346. (org-element--request-key next)))
  6347. (org-element--cache-log-message
  6348. "Current request is inside next. New parent: %S"
  6349. (org-element--format-element first))
  6350. (setf (org-element--request-key next)
  6351. (org-element--cache-key first))
  6352. (setf (org-element--request-beg next)
  6353. (org-element-property :begin first))
  6354. (setf (org-element--request-end next)
  6355. (max (org-element-property :end first)
  6356. (org-element--request-end next)))
  6357. (setf (org-element--request-parent next)
  6358. (org-element-property :parent first))))
  6359. ;; The current and NEXT modifications are intersecting
  6360. ;; with current modification starting before NEXT and NEXT
  6361. ;; ending after current. We need to update the common
  6362. ;; non-robust parent for the new extended modification
  6363. ;; region.
  6364. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  6365. (org-element--cache-log-message
  6366. "Current request intersects with next. Candidate parent: %S"
  6367. (org-element--format-element first))
  6368. (when (and first
  6369. (org-element--cache-key-less-p
  6370. (org-element--cache-key first)
  6371. (org-element--request-key next)))
  6372. (org-element--cache-log-message
  6373. "Current request intersects with next. Updating. New parent: %S"
  6374. (org-element--format-element first))
  6375. (setf (org-element--request-key next) (org-element--cache-key first))
  6376. (setf (org-element--request-beg next) (org-element-property :begin first))
  6377. (setf (org-element--request-end next)
  6378. (max (org-element-property :end first)
  6379. (org-element--request-end next)))
  6380. (setf (org-element--request-parent next) (org-element-property :parent first))))))
  6381. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  6382. ;; if any, is no longer a 0-phase request, thus ensuring that
  6383. ;; phases are properly ordered. We need to provide OFFSET as
  6384. ;; optional parameter since current modifications are not known
  6385. ;; yet to the otherwise correct part of the cache (i.e, before
  6386. ;; the first request).
  6387. (org-element--cache-log-message "Adding new phase 0 request")
  6388. (when next (org-element--cache-sync (current-buffer) end beg offset))
  6389. (let ((first (org-element--cache-for-removal beg end offset)))
  6390. (if first
  6391. (push (let ((first-beg (org-element-property :begin first))
  6392. (key (org-element--cache-key first)))
  6393. (cond
  6394. ;; When changes happen before the first known
  6395. ;; element, re-parent and shift the rest of the
  6396. ;; cache.
  6397. ((> first-beg end)
  6398. (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
  6399. (vector key first-beg nil offset nil 1))
  6400. ;; Otherwise, we find the first non robust
  6401. ;; element containing END. All elements between
  6402. ;; FIRST and this one are to be removed.
  6403. ;;
  6404. ;; The current modification is completely inside
  6405. ;; FIRST. Clear and update cached elements in
  6406. ;; region containing FIRST.
  6407. ((let ((first-end (org-element-property :end first)))
  6408. (when (> first-end end)
  6409. (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
  6410. (vector key first-beg first-end offset (org-element-property :parent first) 0))))
  6411. (t
  6412. ;; Now, FIRST is the first element after BEG or
  6413. ;; non-robust element containing BEG. However,
  6414. ;; FIRST ends before END and there might be
  6415. ;; another ELEMENT before END that spans beyond
  6416. ;; END. If there is such element, we need to
  6417. ;; extend the region down to end of the common
  6418. ;; parent of FIRST and everything inside
  6419. ;; BEG..END.
  6420. (let* ((element (org-element--cache-find end))
  6421. (element-end (org-element-property :end element))
  6422. (up element))
  6423. (while (and (not (eq up first))
  6424. (setq up (org-element-property :parent up))
  6425. (>= (org-element-property :begin up) first-beg))
  6426. ;; Note that UP might have been already
  6427. ;; shifted if it is a robust element. After
  6428. ;; deletion, it can put it's end before yet
  6429. ;; unprocessed ELEMENT.
  6430. (setq element-end (max (org-element-property :end up) element-end)
  6431. element up))
  6432. ;; Extend region to remove elements between
  6433. ;; beginning of first and the end of outermost
  6434. ;; element starting before END but after
  6435. ;; beginning of first.
  6436. ;; of the FIRST.
  6437. (org-element--cache-log-message
  6438. "Extending to all elements between:\n 1: %S\n 2: %S"
  6439. (org-element--format-element first)
  6440. (org-element--format-element element))
  6441. (vector key first-beg element-end offset up 0)))))
  6442. org-element--cache-sync-requests)
  6443. ;; No element to remove. No need to re-parent either.
  6444. ;; Simply shift additional elements, if any, by OFFSET.
  6445. (if org-element--cache-sync-requests
  6446. (progn
  6447. (org-element--cache-log-message
  6448. "Nothing to remove. Updating offset of the next request by 𝝙%S: %S"
  6449. offset
  6450. (let ((print-level 3))
  6451. (car org-element--cache-sync-requests)))
  6452. (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
  6453. offset))
  6454. (org-element--cache-log-message
  6455. "Nothing to remove. No elements in cache after %S. Terminating."
  6456. end))))))
  6457. (setq org-element--cache-change-warning nil)))
  6458. (defun org-element--cache-verify-element (element)
  6459. "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
  6460. Return non-nil when verification failed."
  6461. ;; Verify correct parent for the element.
  6462. (unless (or (org-element-property :parent element)
  6463. (eq 'org-data (org-element-type element)))
  6464. (org-element--cache-warn "Got element without parent (cache active?: %S). Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" (org-element--cache-active-p) element)
  6465. (org-element-cache-reset))
  6466. (let ((org-element--cache-self-verify
  6467. (or org-element--cache-self-verify
  6468. (and (boundp 'org-batch-test) org-batch-test)))
  6469. (org-element--cache-self-verify-frequency
  6470. (if (and (boundp 'org-batch-test) org-batch-test)
  6471. 1
  6472. org-element--cache-self-verify-frequency)))
  6473. (when (and org-element--cache-self-verify
  6474. (org-element--cache-active-p)
  6475. (derived-mode-p 'org-mode)
  6476. (org-element-property :parent element)
  6477. (eq 'headline (org-element-type element))
  6478. ;; Avoid too much slowdown
  6479. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6480. (org-with-point-at (org-element-property :begin element)
  6481. (org-element-with-disabled-cache (org-up-heading-or-point-min))
  6482. (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
  6483. (eq (point) (point-min)))
  6484. (org-element--cache-warn
  6485. "Cached element has wrong parent in %s. Resetting.
  6486. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6487. The element is: %S\n The parent is: %S\n The real parent is: %S"
  6488. (buffer-name (current-buffer))
  6489. (org-element--format-element element)
  6490. (org-element--format-element (org-element-property :parent element))
  6491. (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
  6492. (org-element-cache-reset))
  6493. (org-element--cache-verify-element (org-element-property :parent element))))
  6494. ;; Verify the element itself.
  6495. (when (and org-element--cache-self-verify
  6496. (org-element--cache-active-p)
  6497. element
  6498. (not (memq (org-element-type element) '(section org-data)))
  6499. ;; Avoid too much slowdown
  6500. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6501. (let ((real-element (let (org-element-use-cache)
  6502. (org-element--parse-to
  6503. (if (memq (org-element-type element) '(table-row item))
  6504. (1+ (org-element-property :begin element))
  6505. (org-element-property :begin element))))))
  6506. (unless (and (eq (org-element-type real-element) (org-element-type element))
  6507. (eq (org-element-property :begin real-element) (org-element-property :begin element))
  6508. (eq (org-element-property :end real-element) (org-element-property :end element))
  6509. (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
  6510. (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
  6511. (or (not (org-element-property :ID real-element))
  6512. (string= (org-element-property :ID real-element) (org-element-property :ID element))))
  6513. (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
  6514. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6515. The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
  6516. this-command
  6517. (buffer-name (current-buffer))
  6518. (if (/= org-element--cache-change-tic
  6519. (buffer-chars-modified-tick))
  6520. "no" "yes")
  6521. (org-element--format-element element)
  6522. (org-element--format-element real-element)
  6523. (org-element--cache-find (1- (org-element-property :begin real-element)))
  6524. (car (org-element--cache-find (org-element-property :begin real-element) 'both))
  6525. (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
  6526. (org-element-cache-reset))))))
  6527. ;;; Cache persistance
  6528. (defun org-element--cache-persist-before-write (container &optional associated)
  6529. "Sync cache before saving."
  6530. (when (equal container '(elisp org-element--cache))
  6531. (if (and org-element-use-cache
  6532. (plist-get associated :file)
  6533. (get-file-buffer (plist-get associated :file))
  6534. org-element-cache-persistent)
  6535. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6536. (if (and (derived-mode-p 'org-mode)
  6537. org-element--cache)
  6538. (progn
  6539. ;; Cleanup cache request keys to avoid collisions during next
  6540. ;; Emacs session.
  6541. (avl-tree-mapc
  6542. (lambda (el)
  6543. (org-element-put-property el :org-element--cache-sync-key nil))
  6544. org-element--cache)
  6545. (org-with-wide-buffer
  6546. (org-element-at-point (point-max)))
  6547. nil)
  6548. 'forbid))
  6549. 'forbid)))
  6550. (defun org-element--cache-persist-before-read (container &optional associated)
  6551. "Avoid reading cache before Org mode is loaded."
  6552. (when (equal container '(elisp org-element--cache))
  6553. (if (not (and (plist-get associated :file)
  6554. (get-file-buffer (plist-get associated :file))))
  6555. 'forbid
  6556. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6557. (unless (and org-element-use-cache
  6558. org-element-cache-persistent
  6559. (derived-mode-p 'org-mode)
  6560. (equal (secure-hash 'md5 (current-buffer))
  6561. (plist-get associated :hash)))
  6562. 'forbid)))))
  6563. (defun org-element--cache-persist-after-read (container &optional associated)
  6564. "Setup restored cache."
  6565. (when (and (plist-get associated :file)
  6566. (get-file-buffer (plist-get associated :file)))
  6567. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6568. (when (and org-element-use-cache org-element-cache-persistent)
  6569. (when (and (equal container '(elisp org-element--cache)) org-element--cache)
  6570. (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
  6571. (when (and (equal container '(elisp org-element--headline-cache)) org-element--headline-cache)
  6572. (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache)))))))
  6573. (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
  6574. (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
  6575. (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
  6576. ;;;; Public Functions
  6577. (defvar-local org-element--cache-gapless nil
  6578. "An alist containing (granularity . `org-element--cache-change-tic') elements.
  6579. Each element indicates the latest `org-element--cache-change-tic' when
  6580. change did not contain gaps.")
  6581. ;;;###autoload
  6582. (defun org-element-cache-reset (&optional all)
  6583. "Reset cache in current buffer.
  6584. When optional argument ALL is non-nil, reset cache in all Org
  6585. buffers."
  6586. (interactive "P")
  6587. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  6588. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  6589. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  6590. (when (not org-element-cache-persistent)
  6591. (org-persist-unregister 'org-element--headline-cache (current-buffer))
  6592. (org-persist-unregister 'org-element--cache (current-buffer)))
  6593. (when (and org-element-cache-persistent
  6594. (buffer-file-name (current-buffer)))
  6595. (org-persist-register 'org-element--cache (current-buffer))
  6596. (org-persist-register 'org-element--headline-cache
  6597. (current-buffer)
  6598. :inherit 'org-element--cache))
  6599. (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
  6600. (setq-local org-element--cache-gapless nil)
  6601. (setq-local org-element--cache
  6602. (avl-tree-create #'org-element--cache-compare))
  6603. (setq-local org-element--headline-cache
  6604. (avl-tree-create #'org-element--cache-compare))
  6605. (setq-local org-element--cache-hash-left (make-vector org-element--cache-hash-size nil))
  6606. (setq-local org-element--cache-hash-right (make-vector org-element--cache-hash-size nil))
  6607. (setq-local org-element--cache-size 0)
  6608. (setq-local org-element--headline-cache-size 0)
  6609. (setq-local org-element--cache-sync-keys-value 0)
  6610. (setq-local org-element--cache-change-warning nil)
  6611. (setq-local org-element--cache-sync-requests nil)
  6612. (setq-local org-element--cache-sync-timer nil)
  6613. (add-hook 'before-change-functions
  6614. #'org-element--cache-before-change nil t)
  6615. (add-hook 'after-change-functions
  6616. #'org-element--cache-after-change nil t)))))
  6617. ;;;###autoload
  6618. (defun org-element-cache-refresh (pos)
  6619. "Refresh cache at position POS."
  6620. (when (org-element--cache-active-p)
  6621. (org-element--cache-sync (current-buffer) pos)
  6622. (org-element--cache-submit-request pos pos 0)
  6623. (org-element--cache-set-timer (current-buffer))))
  6624. (defvar warning-minimum-log-level) ; Defined in warning.el
  6625. (defvar org-element-cache-map--recurse nil)
  6626. (defvar org-element-cache-map-continue-from nil
  6627. "Position from where mapping should continue.
  6628. This variable can be set by called function, especially when the
  6629. function modified the buffer.")
  6630. ;;;###autoload
  6631. (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
  6632. next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
  6633. narrow)
  6634. "Map all elements in current buffer with FUNC according to
  6635. GRANULARITY. Collect non-nil return values into result list.
  6636. FUNC should accept a single argument - the element.
  6637. FUNC can modify the buffer, but doing so may reduce performance. If
  6638. buffer is modified, the mapping will continue from an element starting
  6639. after the last mapped element. If the last mapped element is deleted,
  6640. the subsequent element will be skipped as it cannot be distinguished
  6641. deterministically from a changed element. If FUNC is expected to
  6642. delete the element, it should directly set the value of
  6643. `org-element-cache-map-continue-from' to force `org-element-cache-map'
  6644. continue from the right point in buffer.
  6645. If some elements are not yet in cache, they will be added.
  6646. GRANULARITY can be `headline', `headline+inlinetask'
  6647. `greater-element', or `element'. The default is
  6648. `headline+inlinetask'. `object' granularity is not supported.
  6649. RESTRICT-ELEMENTS is a list of element types to be mapped over.
  6650. NEXT-RE is a regexp used to search next candidate match when FUNC
  6651. returns non-nil and to search the first candidate match. FAIL-RE is a
  6652. regexp used to search next candidate match when FUNC returns nil. The
  6653. mapping will continue starting from headline at the RE match.
  6654. FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
  6655. mapped elements to elements starting at of after FROM-POS but before
  6656. TO-POS.
  6657. AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
  6658. after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
  6659. map all the elements starting from first element inside section, but
  6660. not including the section).
  6661. LIMIT-COUNT limits mapping to that many first matches where FUNC
  6662. returns non-nil.
  6663. NARROW controls whether current buffer narrowing should be preserved.
  6664. This function does a subset of what `org-element-map' does, but with
  6665. much better performance. Cached elements are supplied as the single
  6666. argument of FUNC. Changes to elements made in FUNC will also alter
  6667. the cache."
  6668. (unless (org-element--cache-active-p)
  6669. (error "Cache must be active."))
  6670. (unless (memq granularity '( headline headline+inlinetask
  6671. greater-element element))
  6672. (error "Unsupported granularity: %S" granularity))
  6673. ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
  6674. ;; process.
  6675. (unless (markerp to-pos)
  6676. (let ((mk (make-marker)))
  6677. (set-marker mk to-pos)
  6678. (setq to-pos mk)))
  6679. ;; Make sure that garbage collector does not stand on the way to
  6680. ;; maximum performance.
  6681. (let ((gc-cons-threshold #x40000000)
  6682. ;; Bind variables used inside loop to avoid memory
  6683. ;; re-allocation on every iteration.
  6684. ;; See https://emacsconf.org/2021/talks/faster/
  6685. tmpnext-start tmpparent tmpelement)
  6686. (save-excursion
  6687. (save-restriction
  6688. (unless narrow (widen))
  6689. ;; Synchronise cache up to the end of mapped region.
  6690. (org-element-at-point to-pos)
  6691. (cl-macrolet ((cache-root
  6692. ;; Use the most optimal version of cache available.
  6693. () `(if (memq granularity '(headline headline+inlinetask))
  6694. (org-element--headline-cache-root)
  6695. (org-element--cache-root)))
  6696. (cache-size
  6697. ;; Use the most optimal version of cache available.
  6698. () `(if (memq granularity '(headline headline+inlinetask))
  6699. org-element--headline-cache-size
  6700. org-element--cache-size))
  6701. (cache-walk-restart
  6702. ;; Restart tree traversal after AVL tree re-balance.
  6703. () `(when node
  6704. (org-element-at-point (point-max))
  6705. (setq node (cache-root)
  6706. stack (list nil)
  6707. leftp t
  6708. continue-flag t)))
  6709. (cache-walk-abort
  6710. ;; Abort tree traversal.
  6711. () `(setq continue-flag t
  6712. node nil))
  6713. (element-match-at-point
  6714. ;; Returning the first element to match around point.
  6715. ;; For example, if point is inside headline and
  6716. ;; granularity is restricted to headlines only, skip
  6717. ;; over all the child elements inside the headline
  6718. ;; and return the first parent headline.
  6719. ;; When we are inside a cache gap, calling
  6720. ;; `org-element-at-point' also fills the cache gap down to
  6721. ;; point.
  6722. () `(progn
  6723. ;; Parsing is one of the performance
  6724. ;; bottlenecks. Make sure to optimise it as
  6725. ;; much as possible.
  6726. ;;
  6727. ;; Avoid extra staff like timer cancels et al
  6728. ;; and only call `org-element--cache-sync-requests' when
  6729. ;; there are pending requests.
  6730. (when org-element--cache-sync-requests
  6731. (org-element--cache-sync (current-buffer)))
  6732. ;; Call `org-element--parse-to' directly avoiding any
  6733. ;; kind of `org-element-at-point' overheads.
  6734. (if restrict-elements
  6735. ;; Search directly instead of calling
  6736. ;; `org-element-lineage' to avoid funcall overheads
  6737. ;; and making sure that we do not go all
  6738. ;; the way to `org-data' as `org-element-lineage'
  6739. ;; does.
  6740. (progn
  6741. (setq tmpelement (org-element--parse-to (point)))
  6742. (while (and tmpelement (not (memq (org-element-type tmpelement) restrict-elements)))
  6743. (setq tmpelement (org-element-property :parent tmpelement)))
  6744. tmpelement)
  6745. (org-element--parse-to (point)))))
  6746. ;; Starting from (point), search RE and move START to
  6747. ;; the next valid element to be matched according to
  6748. ;; restriction. Abort cache walk if no next element
  6749. ;; can be found. When RE is nil, just find element at
  6750. ;; point.
  6751. (move-start-to-next-match
  6752. (re) `(save-match-data
  6753. (if (or (not ,re)
  6754. (if org-element--cache-map-statistics
  6755. (progn
  6756. (setq before-time (float-time))
  6757. (re-search-forward (or (car-safe ,re) ,re) nil 'move)
  6758. (cl-incf re-search-time
  6759. (- (float-time)
  6760. before-time)))
  6761. (re-search-forward (or (car-safe ,re) ,re) nil 'move)))
  6762. (unless (or (< (point) (or start -1))
  6763. (and data
  6764. (< (point) (org-element-property :begin data))))
  6765. (if (cdr-safe ,re)
  6766. ;; Avoid parsing when we are 100%
  6767. ;; sure that regexp is good enough
  6768. ;; to find new START.
  6769. (setq start (match-beginning 0))
  6770. (setq start (max (or start -1)
  6771. (or (org-element-property :begin data) -1)
  6772. (or (org-element-property :begin (element-match-at-point)) -1))))
  6773. (when (>= start to-pos) (cache-walk-abort))
  6774. (when (eq start -1) (setq start nil)))
  6775. (cache-walk-abort))))
  6776. ;; Find expected begin position of an element after
  6777. ;; DATA.
  6778. (next-element-start
  6779. () `(progn
  6780. (setq tmpnext-start nil)
  6781. (if (memq granularity '(headline headline+inlinetask))
  6782. (setq tmpnext-start (or (when (memq (org-element-type data) '(headline org-data))
  6783. (org-element-property :contents-begin data))
  6784. (org-element-property :end data)))
  6785. (setq tmpnext-start (or (when (memq (org-element-type data) org-element-greater-elements)
  6786. (org-element-property :contents-begin data))
  6787. (org-element-property :end data))))
  6788. ;; DATA end may be the last element inside
  6789. ;; i.e. source block. Skip up to the end
  6790. ;; of parent in such case.
  6791. (setq tmpparent data)
  6792. (catch :exit
  6793. (when (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6794. (setq tmpnext-start (org-element-property :end tmpparent)))
  6795. (while (setq tmpparent (org-element-property :parent tmpparent))
  6796. (if (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6797. (setq tmpnext-start (org-element-property :end tmpparent))
  6798. (throw :exit t))))
  6799. tmpnext-start))
  6800. ;; Check if cache does not have gaps.
  6801. (cache-gapless-p
  6802. () `(eq org-element--cache-change-tic
  6803. (alist-get granularity org-element--cache-gapless))))
  6804. ;; The core algorithm is simple walk along binary tree. However,
  6805. ;; instead of checking all the tree elements from first to last
  6806. ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
  6807. ;; the elements before FROM-POS efficiently: O(logN) instead of
  6808. ;; O(Nbefore).
  6809. ;;
  6810. ;; Later, we may also not check every single element in the
  6811. ;; binary tree after FROM-POS. Instead, we can find position of
  6812. ;; next candidate elements by means of regexp search and skip the
  6813. ;; binary tree branches that are before the next candidate:
  6814. ;; again, O(logN) instead of O(Nbetween).
  6815. ;;
  6816. ;; Some elements might not yet be in the tree. So, we also parse
  6817. ;; the empty gaps in cache as needed making sure that we do not
  6818. ;; miss anything.
  6819. (let* (;; START is always beginning of an element. When there is
  6820. ;; no element in cache at START, we are inside cache gap
  6821. ;; and need to fill it.
  6822. (start (and from-pos
  6823. (progn
  6824. (goto-char from-pos)
  6825. (org-element-property :begin (element-match-at-point)))))
  6826. ;; Some elements may start at the same position, so we
  6827. ;; also keep track of the last processed element and make
  6828. ;; sure that we do not try to search it again.
  6829. (prev after-element)
  6830. (node (cache-root))
  6831. data
  6832. (stack (list nil))
  6833. (leftp t)
  6834. result
  6835. ;; Whether previous element matched FUNC (FUNC
  6836. ;; returned non-nil).
  6837. (last-match t)
  6838. continue-flag
  6839. ;; Generic regexp to search next potential match. If it
  6840. ;; is a cons of (regexp . 'match-beg), we are 100% sure
  6841. ;; that the match beginning is the existing element
  6842. ;; beginning.
  6843. (next-element-re (pcase granularity
  6844. ((or `headline
  6845. (guard (eq '(headline)
  6846. restrict-elements)))
  6847. (cons
  6848. (org-with-limited-levels
  6849. org-element-headline-re)
  6850. 'match-beg))
  6851. (`headline+inlinetask
  6852. (cons
  6853. (if (eq '(inlinetask) restrict-elements)
  6854. (org-inlinetask-outline-regexp)
  6855. org-element-headline-re)
  6856. 'match-beg))
  6857. ;; TODO: May add other commonly
  6858. ;; searched elements as needed.
  6859. (_)))
  6860. ;; Make sure that we are not checking the same regexp twice.
  6861. (next-re (unless (and next-re
  6862. (string= next-re
  6863. (or (car-safe next-element-re)
  6864. next-element-re)))
  6865. next-re))
  6866. (fail-re (unless (and fail-re
  6867. (string= fail-re
  6868. (or (car-safe next-element-re)
  6869. next-element-re)))
  6870. fail-re))
  6871. (restrict-elements (or restrict-elements
  6872. (pcase granularity
  6873. (`headline
  6874. '(headline))
  6875. (`headline+inlinetask
  6876. '(headline inlinetask))
  6877. (`greater-element
  6878. org-element-greater-elements)
  6879. (_ nil))))
  6880. ;; Statistics
  6881. (time (float-time))
  6882. (predicate-time 0)
  6883. (pre-process-time 0)
  6884. (re-search-time 0)
  6885. (count-predicate-calls-match 0)
  6886. (count-predicate-calls-fail 0)
  6887. ;; Bind variables used inside loop to avoid memory
  6888. ;; re-allocation on every iteration.
  6889. ;; See https://emacsconf.org/2021/talks/faster/
  6890. cache-size before-time modified-tic)
  6891. ;; Skip to first element within region.
  6892. (goto-char (or start (point-min)))
  6893. (move-start-to-next-match next-element-re)
  6894. (unless (and start (>= start to-pos))
  6895. ;; Pre-process cache filling all the gaps.
  6896. (unless (or org-element-cache-map--recurse
  6897. (cache-gapless-p)
  6898. ;; Pre-processing all the elements in large
  6899. ;; buffers when NEXT-RE/FAIL-RE are provided
  6900. ;; may be much slower compared to using
  6901. ;; regexp.
  6902. (and (eq granularity 'element)
  6903. (or next-re fail-re)))
  6904. (let ((org-element-cache-map--recurse t))
  6905. (setq before-time (float-time))
  6906. (org-element-cache-map
  6907. #'ignore
  6908. :granularity granularity)
  6909. (cl-incf pre-process-time
  6910. (- (float-time)
  6911. before-time))
  6912. ;; Re-assign the cache root after filling the cache
  6913. ;; gaps.
  6914. (setq node (cache-root)))
  6915. (setf (alist-get granularity org-element--cache-gapless)
  6916. org-element--cache-change-tic))
  6917. (while node
  6918. (setq data (avl-tree--node-data node))
  6919. (if (and leftp (avl-tree--node-left node) ; Left branch.
  6920. ;; Do not move to left branch when we are before
  6921. ;; PREV.
  6922. (or (not prev)
  6923. (not (org-element--cache-key-less-p
  6924. (org-element--cache-key data)
  6925. (org-element--cache-key prev))))
  6926. ;; ... or when we are before START.
  6927. (or (not start)
  6928. (not (> start (org-element-property :begin data)))))
  6929. (progn (push node stack)
  6930. (setq node (avl-tree--node-left node)))
  6931. ;; The whole tree left to DATA is before START and
  6932. ;; PREV. DATA may still be before START (i.e. when
  6933. ;; DATA is the root or when START moved), at START, or
  6934. ;; after START.
  6935. ;;
  6936. ;; If DATA is before start, skip it over and move to
  6937. ;; subsequent elements.
  6938. ;; If DATA is at start, run FUNC if necessary and
  6939. ;; update START according and NEXT-RE, FAIL-RE,
  6940. ;; NEXT-ELEMENT-RE.
  6941. ;; If DATA is after start, we have found a cache gap
  6942. ;; and need to fill it.
  6943. (unless (or (and start (< (org-element-property :begin data) start))
  6944. (and prev (not (org-element--cache-key-less-p
  6945. (org-element--cache-key prev)
  6946. (org-element--cache-key data)))))
  6947. ;; DATA is at of after START and PREV.
  6948. (if (or (not start) (= (org-element-property :begin data) start))
  6949. ;; DATA is at START. Match it.
  6950. ;; In the process, we may alter the buffer,
  6951. ;; so also keep track of the cache state.
  6952. (progn
  6953. (setq modified-tic org-element--cache-change-tic)
  6954. (setq cache-size (cache-size))
  6955. ;; When NEXT-RE/FAIL-RE is provided, skip to
  6956. ;; next regexp match after :begin of the current
  6957. ;; element.
  6958. (when (if last-match next-re fail-re)
  6959. (goto-char (org-element-property :begin data))
  6960. (move-start-to-next-match
  6961. (if last-match next-re fail-re)))
  6962. (when (and (or (not start) (eq (org-element-property :begin data) start))
  6963. (< (org-element-property :begin data) to-pos))
  6964. ;; Calculate where next possible element
  6965. ;; starts and update START if needed.
  6966. (setq start (next-element-start))
  6967. (goto-char start)
  6968. ;; Move START further if possible.
  6969. (when (and next-element-re
  6970. ;; Do not move if we know for
  6971. ;; sure that cache does not
  6972. ;; contain gaps. Regexp
  6973. ;; searches are not cheap.
  6974. (not (cache-gapless-p)))
  6975. (move-start-to-next-match next-element-re)
  6976. ;; Make sure that point is at START
  6977. ;; before running FUNC.
  6978. (goto-char start))
  6979. ;; Try FUNC if DATA matches all the
  6980. ;; restrictions. Calculate new START.
  6981. (when (or (not restrict-elements)
  6982. (memq (org-element-type data) restrict-elements))
  6983. ;; DATA matches restriction. FUNC may
  6984. ;;
  6985. ;; Call FUNC. FUNC may move point.
  6986. (setq org-element-cache-map-continue-from nil)
  6987. (if org-element--cache-map-statistics
  6988. (progn
  6989. (setq before-time (float-time))
  6990. (push (funcall func data) result)
  6991. (cl-incf predicate-time
  6992. (- (float-time)
  6993. before-time))
  6994. (if (car result)
  6995. (cl-incf count-predicate-calls-match)
  6996. (cl-incf count-predicate-calls-fail)))
  6997. (push (funcall func data) result)
  6998. (when (car result) (cl-incf count-predicate-calls-match)))
  6999. ;; Set `last-match'.
  7000. (setq last-match (car result))
  7001. ;; If FUNC moved point forward, update
  7002. ;; START.
  7003. (when org-element-cache-map-continue-from
  7004. (goto-char org-element-cache-map-continue-from))
  7005. (when (> (point) start)
  7006. (move-start-to-next-match nil))
  7007. ;; Drop nil.
  7008. (unless (car result) (pop result)))
  7009. ;; If FUNC did not move the point and we
  7010. ;; know for sure that cache does not contain
  7011. ;; gaps, do not try to calculate START in
  7012. ;; advance but simply loop to the next cache
  7013. ;; element.
  7014. (when (and (cache-gapless-p)
  7015. (eq (next-element-start)
  7016. start))
  7017. (setq start nil))
  7018. ;; Check if the buffer has been modified.
  7019. (unless (and (eq modified-tic org-element--cache-change-tic)
  7020. (eq cache-size (cache-size)))
  7021. ;; START may no longer be valid, update
  7022. ;; it to beginning of real element.
  7023. ;; Upon modification, START may lay
  7024. ;; inside an element. We want to move
  7025. ;; it to real beginning then despite
  7026. ;; START being larger.
  7027. (setq start nil)
  7028. (move-start-to-next-match nil)
  7029. ;; The new element may now start before
  7030. ;; or at already processed position.
  7031. ;; Make sure that we continue from an
  7032. ;; element past already processed
  7033. ;; place.
  7034. (when (and start
  7035. (<= start (org-element-property :begin data))
  7036. (not org-element-cache-map-continue-from))
  7037. (goto-char start)
  7038. (setq data (element-match-at-point))
  7039. ;; If DATA is nil, buffer is
  7040. ;; empty. Abort.
  7041. (when data
  7042. (goto-char (next-element-start))
  7043. (move-start-to-next-match next-element-re)))
  7044. (org-element-at-point to-pos)
  7045. (cache-walk-restart))
  7046. ;; Reached LIMIT-COUNT. Abort.
  7047. (when (and limit-count
  7048. (>= count-predicate-calls-match
  7049. limit-count))
  7050. (cache-walk-abort))
  7051. (if (org-element-property :cached data)
  7052. (setq prev data)
  7053. (setq prev nil))))
  7054. ;; DATA is after START. Fill the gap.
  7055. (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
  7056. ;; Tables and lists are special, we need a
  7057. ;; trickery to make items/rows be populated
  7058. ;; into cache.
  7059. (org-element--parse-to (1+ start)))
  7060. ;; Restart tree traversal as AVL tree is
  7061. ;; re-balanced upon adding elements. We can no
  7062. ;; longer trust STACK.
  7063. (cache-walk-restart)))
  7064. ;; Second, move to the right branch of the tree or skip
  7065. ;; it alltogether.
  7066. (if continue-flag
  7067. (setq continue-flag nil)
  7068. (setq node (if (and (car stack)
  7069. ;; If START advanced beyond stack parent, skip the right branch.
  7070. (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
  7071. (and prev (org-element--cache-key-less-p
  7072. (org-element--cache-key (avl-tree--node-data (car stack)))
  7073. (org-element--cache-key prev)))))
  7074. (progn
  7075. (setq leftp nil)
  7076. (pop stack))
  7077. ;; Otherwise, move ahead into the right
  7078. ;; branch when it exists.
  7079. (if (setq leftp (avl-tree--node-right node))
  7080. (avl-tree--node-right node)
  7081. (pop stack))))))))
  7082. (when (and org-element--cache-map-statistics
  7083. (or (not org-element--cache-map-statistics-threshold)
  7084. (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
  7085. (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.
  7086. 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"
  7087. (current-buffer)
  7088. count-predicate-calls-match
  7089. (+ count-predicate-calls-match
  7090. count-predicate-calls-fail)
  7091. (- (float-time) time)
  7092. pre-process-time
  7093. predicate-time
  7094. re-search-time
  7095. granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
  7096. ;; Return result.
  7097. (nreverse result)))))))
  7098. ;;; The Toolbox
  7099. ;;
  7100. ;; The first move is to implement a way to obtain the smallest element
  7101. ;; containing point. This is the job of `org-element-at-point'. It
  7102. ;; basically jumps back to the beginning of section containing point
  7103. ;; and proceed, one element after the other, with
  7104. ;; `org-element--current-element' until the container is found. Note:
  7105. ;; When using `org-element-at-point', secondary values are never
  7106. ;; parsed since the function focuses on elements, not on objects.
  7107. ;;
  7108. ;; At a deeper level, `org-element-context' lists all elements and
  7109. ;; objects containing point.
  7110. ;;
  7111. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  7112. ;; internally by navigation and manipulation tools.
  7113. ;;;###autoload
  7114. (defun org-element-at-point (&optional pom cached-only)
  7115. "Determine closest element around point or POM.
  7116. Only check cached element when CACHED-ONLY is non-nil and return nil
  7117. unconditionally when element at POM is not in cache.
  7118. Return value is a list like (TYPE PROPS) where TYPE is the type
  7119. of the element and PROPS a plist of properties associated to the
  7120. element.
  7121. Possible types are defined in `org-element-all-elements'.
  7122. Properties depend on element or object type, but always include
  7123. `:begin', `:end', and `:post-blank' properties.
  7124. As a special case, if point is at the very beginning of the first
  7125. item in a list or sub-list, returned element will be that list
  7126. instead of the item. Likewise, if point is at the beginning of
  7127. the first row of a table, returned element will be the table
  7128. instead of the first row.
  7129. When point is at the end of the buffer, return the innermost
  7130. element ending there."
  7131. (setq pom (or pom (point)))
  7132. ;; Allow re-parsing when the command can benefit from it.
  7133. (when (and cached-only
  7134. (memq this-command org-element--cache-non-modifying-commands))
  7135. (setq cached-only nil))
  7136. (let (element)
  7137. (when (org-element--cache-active-p)
  7138. (if (not org-element--cache) (org-element-cache-reset)
  7139. (unless cached-only (org-element--cache-sync (current-buffer) pom))))
  7140. (setq element (if cached-only
  7141. (when (and (org-element--cache-active-p)
  7142. (or (not org-element--cache-sync-requests)
  7143. (< pom
  7144. (org-element--request-beg
  7145. (car org-element--cache-sync-requests)))))
  7146. (org-element--cache-find pom))
  7147. (condition-case err
  7148. (org-element--parse-to pom)
  7149. (error
  7150. (org-element--cache-warn
  7151. "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)."
  7152. (buffer-name (current-buffer))
  7153. pom
  7154. err
  7155. (when (and (fboundp 'backtrace-get-frames)
  7156. (fboundp 'backtrace-to-string))
  7157. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  7158. (org-element-cache-reset)
  7159. (org-element--parse-to pom)))))
  7160. (when (and (org-element--cache-active-p)
  7161. element
  7162. (org-element--cache-verify-element element))
  7163. (setq element (org-element--parse-to pom)))
  7164. (unless (eq 'org-data (org-element-type element))
  7165. (unless (and cached-only
  7166. (not (and element
  7167. (or (= pom (org-element-property :begin element))
  7168. (and (not (memq (org-element-type element) org-element-greater-elements))
  7169. (>= pom (org-element-property :begin element))
  7170. (< pom (org-element-property :end element)))
  7171. (and (org-element-property :contents-begin element)
  7172. (>= pom (org-element-property :begin element))
  7173. (< pom (org-element-property :contents-begin element)))
  7174. (and (not (org-element-property :contents-end element))
  7175. (>= pom (org-element-property :begin element))
  7176. (< pom (org-element-property :end element)))))))
  7177. (if (not (eq (org-element-type element) 'section))
  7178. element
  7179. (org-element-at-point (1+ pom) cached-only))))))
  7180. ;;;###autoload
  7181. (defsubst org-element-at-point-no-context (&optional pom)
  7182. "Quickly find element at point or POM.
  7183. It is a faster version of `org-element-at-point' that is not
  7184. guaranteed to return correct `:parent' properties even when cache is
  7185. enabled."
  7186. (or (org-element-at-point pom 'cached-only)
  7187. (let (org-element-use-cache) (org-element-at-point pom))))
  7188. ;;;###autoload
  7189. (defun org-element-context (&optional element)
  7190. "Return smallest element or object around point.
  7191. Return value is a list like (TYPE PROPS) where TYPE is the type
  7192. of the element or object and PROPS a plist of properties
  7193. associated to it.
  7194. Possible types are defined in `org-element-all-elements' and
  7195. `org-element-all-objects'. Properties depend on element or
  7196. object type, but always include `:begin', `:end', `:parent' and
  7197. `:post-blank'.
  7198. As a special case, if point is right after an object and not at
  7199. the beginning of any other object, return that object.
  7200. Optional argument ELEMENT, when non-nil, is the closest element
  7201. containing point, as returned by `org-element-at-point'.
  7202. Providing it allows for quicker computation."
  7203. (catch 'objects-forbidden
  7204. (org-with-wide-buffer
  7205. (let* ((pos (point))
  7206. (element (or element (org-element-at-point)))
  7207. (type (org-element-type element))
  7208. (post (org-element-property :post-affiliated element)))
  7209. ;; If point is inside an element containing objects or
  7210. ;; a secondary string, narrow buffer to the container and
  7211. ;; proceed with parsing. Otherwise, return ELEMENT.
  7212. (cond
  7213. ;; At a parsed affiliated keyword, check if we're inside main
  7214. ;; or dual value.
  7215. ((and post (< pos post))
  7216. (beginning-of-line)
  7217. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  7218. (cond
  7219. ((not (member-ignore-case (match-string 1)
  7220. org-element-parsed-keywords))
  7221. (throw 'objects-forbidden element))
  7222. ((< (match-end 0) pos)
  7223. (narrow-to-region (match-end 0) (line-end-position)))
  7224. ((and (match-beginning 2)
  7225. (>= pos (match-beginning 2))
  7226. (< pos (match-end 2)))
  7227. (narrow-to-region (match-beginning 2) (match-end 2)))
  7228. (t (throw 'objects-forbidden element)))
  7229. ;; Also change type to retrieve correct restrictions.
  7230. (setq type 'keyword))
  7231. ;; At an item, objects can only be located within tag, if any.
  7232. ((eq type 'item)
  7233. (let ((tag (org-element-property :tag element)))
  7234. (if (or (not tag) (/= (line-beginning-position) post))
  7235. (throw 'objects-forbidden element)
  7236. (beginning-of-line)
  7237. (search-forward tag (line-end-position))
  7238. (goto-char (match-beginning 0))
  7239. (if (and (>= pos (point)) (< pos (match-end 0)))
  7240. (narrow-to-region (point) (match-end 0))
  7241. (throw 'objects-forbidden element)))))
  7242. ;; At an headline or inlinetask, objects are in title.
  7243. ((memq type '(headline inlinetask))
  7244. (let ((case-fold-search nil))
  7245. (goto-char (org-element-property :begin element))
  7246. (looking-at org-complex-heading-regexp)
  7247. (let ((end (match-end 4)))
  7248. (if (not end) (throw 'objects-forbidden element)
  7249. (goto-char (match-beginning 4))
  7250. (when (looking-at org-element-comment-string)
  7251. (goto-char (match-end 0)))
  7252. (if (>= (point) end) (throw 'objects-forbidden element)
  7253. (narrow-to-region (point) end))))))
  7254. ;; At a paragraph, a table-row or a verse block, objects are
  7255. ;; located within their contents.
  7256. ((memq type '(paragraph table-row verse-block))
  7257. (let ((cbeg (org-element-property :contents-begin element))
  7258. (cend (org-element-property :contents-end element)))
  7259. ;; CBEG is nil for table rules.
  7260. (if (and cbeg cend (>= pos cbeg)
  7261. (or (< pos cend) (and (= pos cend) (eobp))))
  7262. (narrow-to-region cbeg cend)
  7263. (throw 'objects-forbidden element))))
  7264. (t (throw 'objects-forbidden element)))
  7265. (goto-char (point-min))
  7266. (let ((restriction (org-element-restriction type))
  7267. (parent element)
  7268. last)
  7269. (catch 'exit
  7270. (while t
  7271. (let ((next (org-element--object-lex restriction)))
  7272. (when next (org-element-put-property next :parent parent))
  7273. ;; Process NEXT, if any, in order to know if we need to
  7274. ;; skip it, return it or move into it.
  7275. (if (or (not next) (> (org-element-property :begin next) pos))
  7276. (throw 'exit (or last parent))
  7277. (let ((end (org-element-property :end next))
  7278. (cbeg (org-element-property :contents-begin next))
  7279. (cend (org-element-property :contents-end next)))
  7280. (cond
  7281. ;; Skip objects ending before point. Also skip
  7282. ;; objects ending at point unless it is also the
  7283. ;; end of buffer, since we want to return the
  7284. ;; innermost object.
  7285. ((and (<= end pos) (/= (point-max) end))
  7286. (goto-char end)
  7287. ;; For convenience, when object ends at POS,
  7288. ;; without any space, store it in LAST, as we
  7289. ;; will return it if no object starts here.
  7290. (when (and (= end pos)
  7291. (not (memq (char-before) '(?\s ?\t))))
  7292. (setq last next)))
  7293. ;; If POS is within a container object, move into
  7294. ;; that object.
  7295. ((and cbeg cend
  7296. (>= pos cbeg)
  7297. (or (< pos cend)
  7298. ;; At contents' end, if there is no
  7299. ;; space before point, also move into
  7300. ;; object, for consistency with
  7301. ;; convenience feature above.
  7302. (and (= pos cend)
  7303. (or (= (point-max) pos)
  7304. (not (memq (char-before pos)
  7305. '(?\s ?\t)))))))
  7306. (goto-char cbeg)
  7307. (narrow-to-region (point) cend)
  7308. (setq parent next)
  7309. (setq restriction (org-element-restriction next)))
  7310. ;; Otherwise, return NEXT.
  7311. (t (throw 'exit next)))))))))))))
  7312. (defun org-element-lineage (datum &optional types with-self)
  7313. "List all ancestors of a given element or object.
  7314. DATUM is an object or element.
  7315. Return ancestors from the closest to the farthest. When optional
  7316. argument TYPES is a list of symbols, return the first element or
  7317. object in the lineage whose type belongs to that list instead.
  7318. When optional argument WITH-SELF is non-nil, lineage includes
  7319. DATUM itself as the first element, and TYPES, if provided, also
  7320. apply to it.
  7321. When DATUM is obtained through `org-element-context' or
  7322. `org-element-at-point', only ancestors from its section can be
  7323. found. There is no such limitation when DATUM belongs to a full
  7324. parse tree."
  7325. (let ((up (if with-self datum (org-element-property :parent datum)))
  7326. ancestors)
  7327. (while (and up (not (memq (org-element-type up) types)))
  7328. (unless types (push up ancestors))
  7329. (setq up (org-element-property :parent up)))
  7330. (if types up (nreverse ancestors))))
  7331. (defun org-element-nested-p (elem-A elem-B)
  7332. "Non-nil when elements ELEM-A and ELEM-B are nested."
  7333. (let ((beg-A (org-element-property :begin elem-A))
  7334. (beg-B (org-element-property :begin elem-B))
  7335. (end-A (org-element-property :end elem-A))
  7336. (end-B (org-element-property :end elem-B)))
  7337. (or (and (>= beg-A beg-B) (<= end-A end-B))
  7338. (and (>= beg-B beg-A) (<= end-B end-A)))))
  7339. (defun org-element-swap-A-B--overlays (elem-A elem-B)
  7340. "Swap elements ELEM-A and ELEM-B.
  7341. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7342. end of ELEM-A."
  7343. (goto-char (org-element-property :begin elem-A))
  7344. ;; There are two special cases when an element doesn't start at bol:
  7345. ;; the first paragraph in an item or in a footnote definition.
  7346. (let ((specialp (not (bolp))))
  7347. ;; Only a paragraph without any affiliated keyword can be moved at
  7348. ;; ELEM-A position in such a situation. Note that the case of
  7349. ;; a footnote definition is impossible: it cannot contain two
  7350. ;; paragraphs in a row because it cannot contain a blank line.
  7351. (when (and specialp
  7352. (or (not (eq (org-element-type elem-B) 'paragraph))
  7353. (/= (org-element-property :begin elem-B)
  7354. (org-element-property :contents-begin elem-B))))
  7355. (error "Cannot swap elements"))
  7356. ;; In a special situation, ELEM-A will have no indentation. We'll
  7357. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7358. (let* ((ind-B (when specialp
  7359. (goto-char (org-element-property :begin elem-B))
  7360. (current-indentation)))
  7361. (beg-A (org-element-property :begin elem-A))
  7362. (end-A (save-excursion
  7363. (goto-char (org-element-property :end elem-A))
  7364. (skip-chars-backward " \r\t\n")
  7365. (point-at-eol)))
  7366. (beg-B (org-element-property :begin elem-B))
  7367. (end-B (save-excursion
  7368. (goto-char (org-element-property :end elem-B))
  7369. (skip-chars-backward " \r\t\n")
  7370. (point-at-eol)))
  7371. ;; Store inner overlays responsible for visibility status.
  7372. ;; We also need to store their boundaries as they will be
  7373. ;; removed from buffer.
  7374. (overlays
  7375. (cons
  7376. (delq nil
  7377. (mapcar (lambda (o)
  7378. (and (>= (overlay-start o) beg-A)
  7379. (<= (overlay-end o) end-A)
  7380. (list o (overlay-start o) (overlay-end o))))
  7381. (overlays-in beg-A end-A)))
  7382. (delq nil
  7383. (mapcar (lambda (o)
  7384. (and (>= (overlay-start o) beg-B)
  7385. (<= (overlay-end o) end-B)
  7386. (list o (overlay-start o) (overlay-end o))))
  7387. (overlays-in beg-B end-B)))))
  7388. ;; Get contents.
  7389. (body-A (buffer-substring beg-A end-A))
  7390. (body-B (delete-and-extract-region beg-B end-B)))
  7391. (goto-char beg-B)
  7392. (when specialp
  7393. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7394. (indent-to-column ind-B))
  7395. (insert body-A)
  7396. ;; Restore ex ELEM-A overlays.
  7397. (let ((offset (- beg-B beg-A)))
  7398. (dolist (o (car overlays))
  7399. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  7400. (goto-char beg-A)
  7401. (delete-region beg-A end-A)
  7402. (insert body-B)
  7403. ;; Restore ex ELEM-B overlays.
  7404. (dolist (o (cdr overlays))
  7405. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  7406. (goto-char (org-element-property :end elem-B)))))
  7407. (defun org-element-swap-A-B--text-properties (elem-A elem-B)
  7408. "Swap elements ELEM-A and ELEM-B.
  7409. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7410. end of ELEM-A."
  7411. (goto-char (org-element-property :begin elem-A))
  7412. ;; There are two special cases when an element doesn't start at bol:
  7413. ;; the first paragraph in an item or in a footnote definition.
  7414. (let ((specialp (not (bolp))))
  7415. ;; Only a paragraph without any affiliated keyword can be moved at
  7416. ;; ELEM-A position in such a situation. Note that the case of
  7417. ;; a footnote definition is impossible: it cannot contain two
  7418. ;; paragraphs in a row because it cannot contain a blank line.
  7419. (when (and specialp
  7420. (or (not (eq (org-element-type elem-B) 'paragraph))
  7421. (/= (org-element-property :begin elem-B)
  7422. (org-element-property :contents-begin elem-B))))
  7423. (error "Cannot swap elements"))
  7424. ;; In a special situation, ELEM-A will have no indentation. We'll
  7425. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7426. (org-fold-core-ignore-modifications ;; Preserve folding state
  7427. (let* ((ind-B (when specialp
  7428. (goto-char (org-element-property :begin elem-B))
  7429. (current-indentation)))
  7430. (beg-A (org-element-property :begin elem-A))
  7431. (end-A (save-excursion
  7432. (goto-char (org-element-property :end elem-A))
  7433. (skip-chars-backward " \r\t\n")
  7434. (point-at-eol)))
  7435. (beg-B (org-element-property :begin elem-B))
  7436. (end-B (save-excursion
  7437. (goto-char (org-element-property :end elem-B))
  7438. (skip-chars-backward " \r\t\n")
  7439. (point-at-eol)))
  7440. ;; Get contents.
  7441. (body-A (buffer-substring beg-A end-A))
  7442. (body-B (delete-and-extract-region beg-B end-B)))
  7443. (goto-char beg-B)
  7444. (when specialp
  7445. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7446. (indent-to-column ind-B))
  7447. (insert body-A)
  7448. (goto-char beg-A)
  7449. (delete-region beg-A end-A)
  7450. (insert body-B)
  7451. (goto-char (org-element-property :end elem-B))))))
  7452. (defsubst org-element-swap-A-B (elem-A elem-B)
  7453. "Swap elements ELEM-A and ELEM-B.
  7454. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7455. end of ELEM-A."
  7456. (if (eq org-fold-core-style 'text-properties)
  7457. (org-element-swap-A-B--text-properties elem-A elem-B)
  7458. (org-element-swap-A-B--overlays elem-A elem-B)))
  7459. (provide 'org-element)
  7460. ;; Local variables:
  7461. ;; generated-autoload-file: "org-loaddefs.el"
  7462. ;; End:
  7463. ;;; org-element.el ends here