org-element.el 330 KB

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