org-element.el 329 KB

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