org-element.el 318 KB

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