org-element.el 318 KB

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