org-element.el 330 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
  19. ;; Org syntax.
  20. ;;
  21. ;; Lisp-wise, a syntax object can be represented as a list.
  22. ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
  23. ;; TYPE is a symbol describing the object.
  24. ;; PROPERTIES is the property list attached to it. See docstring of
  25. ;; appropriate parsing function to get an exhaustive list.
  26. ;; CONTENTS is a list of syntax objects or raw strings contained
  27. ;; in the current object, when applicable.
  28. ;;
  29. ;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
  30. ;;
  31. ;; The first part of this file defines constants for the Org syntax,
  32. ;; while the second one provide accessors and setters functions.
  33. ;;
  34. ;; The next part implements a parser and an interpreter for each
  35. ;; element and object type in Org syntax.
  36. ;;
  37. ;; The following part creates a fully recursive buffer parser. It
  38. ;; also provides a tool to map a function to elements or objects
  39. ;; matching some criteria in the parse tree. Functions of interest
  40. ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
  41. ;; extent, `org-element-parse-secondary-string'.
  42. ;;
  43. ;; The penultimate part is the cradle of an interpreter for the
  44. ;; obtained parse tree: `org-element-interpret-data'.
  45. ;;
  46. ;; The library ends by furnishing `org-element-at-point' function, and
  47. ;; a way to give information about document structure around point
  48. ;; with `org-element-context'. A cache mechanism is also provided for
  49. ;; these functions.
  50. ;;; Code:
  51. (require 'org-macs)
  52. (org-assert-version)
  53. (require 'avl-tree)
  54. (require 'ring)
  55. (require 'cl-lib)
  56. (require 'ol)
  57. (require 'org)
  58. (require 'org-persist)
  59. (require 'org-compat)
  60. (require 'org-entities)
  61. (require 'org-footnote)
  62. (require 'org-list)
  63. (require 'org-macs)
  64. (require 'org-table)
  65. (require 'org-fold-core)
  66. (declare-function org-at-heading-p "org" (&optional _))
  67. (declare-function org-escape-code-in-string "org-src" (s))
  68. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  69. (declare-function org-macro-extract-arguments "org-macro" (s))
  70. (declare-function org-reduced-level "org" (l))
  71. (declare-function org-unescape-code-in-string "org-src" (s))
  72. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  73. (declare-function outline-next-heading "outline" ())
  74. (declare-function outline-previous-heading "outline" ())
  75. (defvar org-complex-heading-regexp)
  76. (defvar org-done-keywords)
  77. (defvar org-edit-src-content-indentation)
  78. (defvar org-match-substring-regexp)
  79. (defvar org-odd-levels-only)
  80. (defvar org-property-drawer-re)
  81. (defvar org-property-format)
  82. (defvar org-property-re)
  83. (defvar org-src-preserve-indentation)
  84. (defvar org-tags-column)
  85. (defvar org-time-stamp-formats)
  86. (defvar org-todo-regexp)
  87. (defvar org-ts-regexp-both)
  88. ;;; Definitions And Rules
  89. ;;
  90. ;; Define elements, greater elements and specify recursive objects,
  91. ;; along with the affiliated keywords recognized. Also set up
  92. ;; restrictions on recursive objects combinations.
  93. ;;
  94. ;; `org-element-update-syntax' builds proper syntax regexps according
  95. ;; to current setup.
  96. (defconst org-element-archive-tag "ARCHIVE"
  97. "Tag marking a substree as archived.")
  98. (defconst org-element-citation-key-re
  99. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  100. "Regexp matching a citation key.
  101. Key is located in match group 1.")
  102. (defconst org-element-citation-prefix-re
  103. (rx "[cite"
  104. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  105. ":"
  106. (zero-or-more (any "\t\n ")))
  107. "Regexp matching a citation prefix.
  108. Style, if any, is located in match group 1.")
  109. (defconst org-element-clock-line-re
  110. (rx-to-string
  111. `(seq
  112. line-start (0+ (or ?\t ?\s))
  113. "CLOCK: "
  114. (regexp ,org-ts-regexp-inactive)
  115. (opt "--"
  116. (regexp ,org-ts-regexp-inactive)
  117. (1+ (or ?\t ?\s)) "=>" (1+ (or ?\t ?\s))
  118. (1+ digit) ":" digit digit)
  119. (0+ (or ?\t ?\s))
  120. line-end))
  121. "Regexp matching a clock line.")
  122. (defconst org-element-comment-string "COMMENT"
  123. "String marker for commented headlines.")
  124. (defconst org-element-closed-keyword "CLOSED:"
  125. "Keyword used to close TODO entries.")
  126. (defconst org-element-deadline-keyword "DEADLINE:"
  127. "Keyword used to mark deadline entries.")
  128. (defconst org-element-scheduled-keyword "SCHEDULED:"
  129. "Keyword used to mark scheduled entries.")
  130. (defconst org-element-planning-keywords-re
  131. (regexp-opt (list org-element-closed-keyword
  132. org-element-deadline-keyword
  133. org-element-scheduled-keyword))
  134. "Regexp matching any planning line keyword.")
  135. (defconst org-element-planning-line-re
  136. (rx-to-string
  137. `(seq line-start (0+ (any ?\s ?\t))
  138. (group (regexp ,org-element-planning-keywords-re))))
  139. "Regexp matching a planning line.")
  140. (defconst org-element-drawer-re
  141. (rx line-start (0+ (any ?\s ?\t))
  142. ":" (group (1+ (any ?- ?_ word))) ":"
  143. (0+ (any ?\s ?\t)) line-end)
  144. "Regexp matching opening or closing line of a drawer.
  145. Drawer's name is located in match group 1.")
  146. (defconst org-element-dynamic-block-open-re
  147. (rx line-start (0+ (any ?\s ?\t))
  148. "#+BEGIN:" (0+ (any ?\s ?\t))
  149. (group (1+ word))
  150. (opt
  151. (1+ (any ?\s ?\t))
  152. (group (1+ nonl))))
  153. "Regexp matching the opening line of a dynamic block.
  154. Dynamic block's name is located in match group 1.
  155. Parameters are in match group 2.")
  156. (defconst org-element-headline-re
  157. (rx line-start (1+ "*") " ")
  158. "Regexp matching a headline.")
  159. (defvar org-element-paragraph-separate nil
  160. "Regexp to separate paragraphs in an Org buffer.
  161. In the case of lines starting with \"#\" and \":\", this regexp
  162. is not sufficient to know if point is at a paragraph ending. See
  163. `org-element-paragraph-parser' for more information.")
  164. (defvar org-element--object-regexp nil
  165. "Regexp possibly matching the beginning of an object.
  166. This regexp allows false positives. Dedicated parser (e.g.,
  167. `org-export-bold-parser') will take care of further filtering.
  168. Radio links are not matched by this regexp, as they are treated
  169. specially in `org-element--object-lex'.")
  170. (defun org-element--set-regexps ()
  171. "Build variable syntax regexps."
  172. (setq org-element-paragraph-separate
  173. (concat "^\\(?:"
  174. ;; Headlines, inlinetasks.
  175. "\\*+ " "\\|"
  176. ;; Footnote definitions.
  177. "\\[fn:[-_[:word:]]+\\]" "\\|"
  178. ;; Diary sexps.
  179. "%%(" "\\|"
  180. "[ \t]*\\(?:"
  181. ;; Empty lines.
  182. "$" "\\|"
  183. ;; Tables (any type).
  184. "|" "\\|"
  185. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  186. ;; Comments, keyword-like or block-like constructs.
  187. ;; Blocks and keywords with dual values need to be
  188. ;; double-checked.
  189. "#\\(?: \\|$\\|\\+\\(?:"
  190. "BEGIN_\\S-+" "\\|"
  191. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  192. "\\|"
  193. ;; Drawers (any type) and fixed-width areas. Drawers
  194. ;; need to be double-checked.
  195. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  196. ;; Horizontal rules.
  197. "-\\{5,\\}[ \t]*$" "\\|"
  198. ;; LaTeX environments.
  199. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  200. ;; Clock lines.
  201. org-element-clock-line-re "\\|"
  202. ;; Lists.
  203. (let ((term (pcase org-plain-list-ordered-item-terminator
  204. (?\) ")") (?. "\\.") (_ "[.)]")))
  205. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  206. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  207. "\\(?:[ \t]\\|$\\)"))
  208. "\\)\\)")
  209. org-element--object-regexp
  210. (mapconcat #'identity
  211. (let ((link-types (regexp-opt (org-link-types))))
  212. (list
  213. ;; Sub/superscript.
  214. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  215. ;; Bold, code, italic, strike-through, underline
  216. ;; and verbatim.
  217. (rx (or "*" "~" "=" "+" "_" "/") (not space))
  218. ;; Plain links.
  219. (concat "\\<" link-types ":")
  220. ;; Objects starting with "[": citations,
  221. ;; footnote reference, statistics cookie,
  222. ;; timestamp (inactive) and regular link.
  223. (format "\\[\\(?:%s\\)"
  224. (mapconcat
  225. #'identity
  226. (list "cite[:/]"
  227. "fn:"
  228. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  229. "\\[")
  230. "\\|"))
  231. ;; Objects starting with "@": export snippets.
  232. "@@"
  233. ;; Objects starting with "{": macro.
  234. "{{{"
  235. ;; Objects starting with "<" : timestamp
  236. ;; (active, diary), target, radio target and
  237. ;; angular links.
  238. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  239. ;; Objects starting with "$": latex fragment.
  240. "\\$"
  241. ;; Objects starting with "\": line break,
  242. ;; entity, latex fragment.
  243. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  244. ;; Objects starting with raw text: inline Babel
  245. ;; source block, inline Babel call.
  246. "\\(?:call\\|src\\)_"))
  247. "\\|")))
  248. (org-element--set-regexps)
  249. ;;;###autoload
  250. (defun org-element-update-syntax ()
  251. "Update parser internals."
  252. (interactive)
  253. (org-element--set-regexps)
  254. (org-element-cache-reset 'all))
  255. (defconst org-element-all-elements
  256. '(babel-call center-block clock comment comment-block diary-sexp drawer
  257. dynamic-block example-block export-block fixed-width
  258. footnote-definition headline horizontal-rule inlinetask item
  259. keyword latex-environment node-property paragraph plain-list
  260. planning property-drawer quote-block section
  261. special-block src-block table table-row verse-block)
  262. "Complete list of element types.")
  263. (defconst org-element-greater-elements
  264. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  265. item plain-list property-drawer quote-block section
  266. special-block table org-data)
  267. "List of recursive element types aka Greater Elements.")
  268. (defconst org-element-all-objects
  269. '(bold citation citation-reference code entity export-snippet
  270. footnote-reference inline-babel-call inline-src-block italic line-break
  271. latex-fragment link macro radio-target statistics-cookie strike-through
  272. subscript superscript table-cell target timestamp underline verbatim)
  273. "Complete list of object types.")
  274. (defconst org-element-recursive-objects
  275. '(bold citation footnote-reference italic link subscript radio-target
  276. strike-through superscript table-cell underline)
  277. "List of recursive object types.")
  278. (defconst org-element-object-containers
  279. (append org-element-recursive-objects '(paragraph table-row verse-block))
  280. "List of object or element types that can directly contain objects.")
  281. (defconst org-element-affiliated-keywords
  282. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  283. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  284. "List of affiliated keywords as strings.
  285. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  286. are affiliated keywords and need not to be in this list.")
  287. (defconst org-element-keyword-translation-alist
  288. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  289. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  290. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  291. "Alist of usual translations for keywords.
  292. The key is the old name and the value the new one. The property
  293. holding their value will be named after the translated name.")
  294. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  295. "List of affiliated keywords that can occur more than once in an element.
  296. Their value will be consed into a list of strings, which will be
  297. returned as the value of the property.
  298. This list is checked after translations have been applied. See
  299. `org-element-keyword-translation-alist'.
  300. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  301. allow multiple occurrences and need not to be in this list.")
  302. (defconst org-element-parsed-keywords '("CAPTION")
  303. "List of affiliated keywords whose value can be parsed.
  304. Their value will be stored as a secondary string: a list of
  305. strings and objects.
  306. This list is checked after translations have been applied. See
  307. `org-element-keyword-translation-alist'.")
  308. (defconst org-element--parsed-properties-alist
  309. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  310. org-element-parsed-keywords)
  311. "Alist of parsed keywords and associated properties.
  312. This is generated from `org-element-parsed-keywords', which
  313. see.")
  314. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  315. "List of affiliated keywords which can have a secondary value.
  316. In Org syntax, they can be written with optional square brackets
  317. before the colons. For example, RESULTS keyword can be
  318. associated to a hash value with the following:
  319. #+RESULTS[hash-string]: some-source
  320. This list is checked after translations have been applied. See
  321. `org-element-keyword-translation-alist'.")
  322. (defconst org-element--affiliated-re
  323. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  324. (concat
  325. ;; Dual affiliated keywords.
  326. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  327. (regexp-opt org-element-dual-keywords))
  328. "\\|"
  329. ;; Regular affiliated keywords.
  330. (format "\\(?1:%s\\)"
  331. (regexp-opt
  332. (cl-remove-if
  333. (lambda (k) (member k org-element-dual-keywords))
  334. org-element-affiliated-keywords)))
  335. "\\|"
  336. ;; Export attributes.
  337. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  338. "Regexp matching any affiliated keyword.
  339. Keyword name is put in match group 1. Moreover, if keyword
  340. belongs to `org-element-dual-keywords', put the dual value in
  341. match group 2.
  342. Don't modify it, set `org-element-affiliated-keywords' instead.")
  343. (defconst org-element-object-restrictions
  344. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  345. subscript superscript underline verbatim))
  346. (standard-set
  347. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  348. (standard-set-no-line-break (remq 'line-break standard-set)))
  349. `((bold ,@standard-set)
  350. (citation citation-reference)
  351. (citation-reference ,@minimal-set)
  352. (footnote-reference ,@standard-set)
  353. (headline ,@standard-set-no-line-break)
  354. (inlinetask ,@standard-set-no-line-break)
  355. (italic ,@standard-set)
  356. (item ,@standard-set-no-line-break)
  357. (keyword ,@(remq 'footnote-reference standard-set))
  358. ;; Ignore all links in a link description. Also ignore
  359. ;; radio-targets and line breaks.
  360. (link export-snippet inline-babel-call inline-src-block macro
  361. statistics-cookie ,@minimal-set)
  362. (paragraph ,@standard-set)
  363. ;; Remove any variable object from radio target as it would
  364. ;; prevent it from being properly recognized.
  365. (radio-target ,@minimal-set)
  366. (strike-through ,@standard-set)
  367. (subscript ,@standard-set)
  368. (superscript ,@standard-set)
  369. ;; Ignore inline babel call and inline source block as formulas
  370. ;; are possible. Also ignore line breaks and statistics
  371. ;; cookies.
  372. (table-cell citation export-snippet footnote-reference link macro
  373. radio-target target timestamp ,@minimal-set)
  374. (table-row table-cell)
  375. (underline ,@standard-set)
  376. (verse-block ,@standard-set)))
  377. "Alist of objects restrictions.
  378. key is an element or object type containing objects and value is
  379. a list of types that can be contained within an element or object
  380. of such type.
  381. This alist also applies to secondary string. For example, an
  382. `headline' type element doesn't directly contain objects, but
  383. still has an entry since one of its properties (`:title') does.")
  384. (defconst org-element-secondary-value-alist
  385. '((citation :prefix :suffix)
  386. (headline :title)
  387. (inlinetask :title)
  388. (item :tag)
  389. (citation-reference :prefix :suffix))
  390. "Alist between element types and locations of secondary values.")
  391. (defconst org-element--pair-round-table
  392. (let ((table (make-char-table 'syntax-table '(2))))
  393. (modify-syntax-entry ?\( "()" table)
  394. (modify-syntax-entry ?\) ")(" table)
  395. table)
  396. "Table used internally to pair only round brackets.")
  397. (defconst org-element--pair-square-table
  398. (let ((table (make-char-table 'syntax-table '(2))))
  399. (modify-syntax-entry ?\[ "(]" table)
  400. (modify-syntax-entry ?\] ")[" table)
  401. table)
  402. "Table used internally to pair only square brackets.")
  403. (defconst org-element--pair-curly-table
  404. (let ((table (make-char-table 'syntax-table '(2))))
  405. (modify-syntax-entry ?\{ "(}" table)
  406. (modify-syntax-entry ?\} "){" table)
  407. table)
  408. "Table used internally to pair only curly brackets.")
  409. (defun org-element--parse-paired-brackets (char)
  410. "Parse paired brackets at point.
  411. CHAR is the opening bracket to consider, as a character. Return
  412. contents between brackets, as a string, or nil. Also move point
  413. past the brackets."
  414. (when (eq char (char-after))
  415. (let ((syntax-table (pcase char
  416. (?\{ org-element--pair-curly-table)
  417. (?\[ org-element--pair-square-table)
  418. (?\( org-element--pair-round-table)
  419. (_ nil)))
  420. (pos (point)))
  421. (when syntax-table
  422. (with-syntax-table syntax-table
  423. (let ((end (ignore-errors (scan-lists pos 1 0))))
  424. (when end
  425. (goto-char end)
  426. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  427. ;;; Accessors and Setters
  428. ;;
  429. ;; Provide four accessors: `org-element-type', `org-element-property'
  430. ;; `org-element-contents' and `org-element-restriction'.
  431. ;;
  432. ;; Setter functions allow modification of elements by side effect.
  433. ;; There is `org-element-put-property', `org-element-set-contents'.
  434. ;; These low-level functions are useful to build a parse tree.
  435. ;;
  436. ;; `org-element-adopt-elements', `org-element-set-element',
  437. ;; `org-element-extract-element' and `org-element-insert-before' are
  438. ;; high-level functions useful to modify a parse tree.
  439. ;;
  440. ;; `org-element-secondary-p' is a predicate used to know if a given
  441. ;; object belongs to a secondary string. `org-element-class' tells if
  442. ;; some parsed data is an element or an object, handling pseudo
  443. ;; elements and objects. `org-element-copy' returns an element or
  444. ;; object, stripping its parent property in the process.
  445. (defsubst org-element-type (element)
  446. "Return type of ELEMENT.
  447. The function returns the type of the element or object provided.
  448. It can also return the following special value:
  449. `plain-text' for a string
  450. `org-data' for a complete document
  451. nil in any other case."
  452. (cond
  453. ((not (consp element)) (and (stringp element) 'plain-text))
  454. ((symbolp (car element)) (car element))))
  455. (defsubst org-element-property (property element)
  456. "Extract the value from the PROPERTY of an ELEMENT."
  457. (if (stringp element) (get-text-property 0 property element)
  458. (plist-get (nth 1 element) property)))
  459. (defsubst org-element-contents (element)
  460. "Extract contents from an ELEMENT."
  461. (cond ((not (consp element)) nil)
  462. ((symbolp (car element)) (nthcdr 2 element))
  463. (t element)))
  464. (defsubst org-element-restriction (element)
  465. "Return restriction associated to ELEMENT.
  466. ELEMENT can be an element, an object or a symbol representing an
  467. element or object type."
  468. (cdr (assq (if (symbolp element) element (org-element-type element))
  469. org-element-object-restrictions)))
  470. (defsubst org-element-put-property (element property value)
  471. "In ELEMENT set PROPERTY to VALUE.
  472. Return modified element."
  473. (if (stringp element) (org-add-props element nil property value)
  474. (setcar (cdr element) (plist-put (nth 1 element) property value))
  475. element))
  476. (defsubst org-element-set-contents (element &rest contents)
  477. "Set ELEMENT's contents to CONTENTS.
  478. Return ELEMENT."
  479. (cond ((null element) contents)
  480. ((not (symbolp (car element))) contents)
  481. ((cdr element) (setcdr (cdr element) contents) element)
  482. (t (nconc element contents))))
  483. (defun org-element-secondary-p (object)
  484. "Non-nil when OBJECT directly belongs to a secondary string.
  485. Return value is the property name, as a keyword, or nil."
  486. (let* ((parent (org-element-property :parent object))
  487. (properties (cdr (assq (org-element-type parent)
  488. org-element-secondary-value-alist))))
  489. (catch 'exit
  490. (dolist (p properties)
  491. (and (memq object (org-element-property p parent))
  492. (throw 'exit p))))))
  493. (defsubst org-element-class (datum &optional parent)
  494. "Return class for ELEMENT, as a symbol.
  495. Class is either `element' or `object'. Optional argument PARENT
  496. is the element or object containing DATUM. It defaults to the
  497. value of DATUM `:parent' property."
  498. (let ((type (org-element-type datum))
  499. (parent (or parent (org-element-property :parent datum))))
  500. (cond
  501. ;; Trivial cases.
  502. ((memq type org-element-all-objects) 'object)
  503. ((memq type org-element-all-elements) 'element)
  504. ;; Special cases.
  505. ((eq type 'org-data) 'element)
  506. ((eq type 'plain-text) 'object)
  507. ((not type) 'object)
  508. ;; Pseudo object or elements. Make a guess about its class.
  509. ;; Basically a pseudo object is contained within another object,
  510. ;; a secondary string or a container element.
  511. ((not parent) 'element)
  512. (t
  513. (let ((parent-type (org-element-type parent)))
  514. (cond ((not parent-type) 'object)
  515. ((memq parent-type org-element-object-containers) 'object)
  516. ((org-element-secondary-p datum) 'object)
  517. (t 'element)))))))
  518. (defsubst org-element-adopt-elements (parent &rest children)
  519. "Append elements to the contents of another element.
  520. PARENT is an element or object. CHILDREN can be elements,
  521. objects, or a strings.
  522. The function takes care of setting `:parent' property for CHILD.
  523. Return parent element."
  524. (declare (indent 1))
  525. (if (not children) parent
  526. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  527. ;; string: parent is the list itself.
  528. (dolist (child children)
  529. (org-element-put-property child :parent (or parent children)))
  530. ;; Add CHILDREN at the end of PARENT contents.
  531. (when parent
  532. (apply #'org-element-set-contents
  533. parent
  534. (nconc (org-element-contents parent) children)))
  535. ;; Return modified PARENT element.
  536. (or parent children)))
  537. (defun org-element-extract-element (element)
  538. "Extract ELEMENT from parse tree.
  539. Remove element from the parse tree by side-effect, and return it
  540. with its `:parent' property stripped out."
  541. (let ((parent (org-element-property :parent element))
  542. (secondary (org-element-secondary-p element)))
  543. (if secondary
  544. (org-element-put-property
  545. parent secondary
  546. (delq element (org-element-property secondary parent)))
  547. (apply #'org-element-set-contents
  548. parent
  549. (delq element (org-element-contents parent))))
  550. ;; Return ELEMENT with its :parent removed.
  551. (org-element-put-property element :parent nil)))
  552. (defun org-element-insert-before (element location)
  553. "Insert ELEMENT before LOCATION in parse tree.
  554. LOCATION is an element, object or string within the parse tree.
  555. Parse tree is modified by side effect."
  556. (let* ((parent (org-element-property :parent location))
  557. (property (org-element-secondary-p location))
  558. (siblings (if property (org-element-property property parent)
  559. (org-element-contents parent)))
  560. ;; Special case: LOCATION is the first element of an
  561. ;; independent secondary string (e.g. :title property). Add
  562. ;; ELEMENT in-place.
  563. (specialp (and (not property)
  564. (eq siblings parent)
  565. (eq (car parent) location))))
  566. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  567. (cond (specialp)
  568. ((or (null siblings) (eq (car siblings) location))
  569. (push element siblings))
  570. ((null location) (nconc siblings (list element)))
  571. (t
  572. (let ((index (cl-position location siblings)))
  573. (unless index (error "No location found to insert element"))
  574. (push element (cdr (nthcdr (1- index) siblings))))))
  575. ;; Store SIBLINGS at appropriate place in parse tree.
  576. (cond
  577. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  578. (property (org-element-put-property parent property siblings))
  579. (t (apply #'org-element-set-contents parent siblings)))
  580. ;; Set appropriate :parent property.
  581. (org-element-put-property element :parent parent)))
  582. (defconst org-element--cache-element-properties
  583. '(:cached
  584. :org-element--cache-sync-key)
  585. "List of element properties used internally by cache.")
  586. (defun org-element-set-element (old new)
  587. "Replace element or object OLD with element or object NEW.
  588. The function takes care of setting `:parent' property for NEW."
  589. ;; Ensure OLD and NEW have the same parent.
  590. (org-element-put-property new :parent (org-element-property :parent old))
  591. (dolist (p org-element--cache-element-properties)
  592. (when (org-element-property p old)
  593. (org-element-put-property new p (org-element-property p old))))
  594. (if (or (memq (org-element-type old) '(plain-text nil))
  595. (memq (org-element-type new) '(plain-text nil)))
  596. ;; We cannot replace OLD with NEW since one of them is not an
  597. ;; object or element. We take the long path.
  598. (progn (org-element-insert-before new old)
  599. (org-element-extract-element old))
  600. ;; Since OLD is going to be changed into NEW by side-effect, first
  601. ;; make sure that every element or object within NEW has OLD as
  602. ;; parent.
  603. (dolist (blob (org-element-contents new))
  604. (org-element-put-property blob :parent old))
  605. ;; Transfer contents.
  606. (apply #'org-element-set-contents old (org-element-contents new))
  607. ;; Overwrite OLD's properties with NEW's.
  608. (setcar (cdr old) (nth 1 new))
  609. ;; Transfer type.
  610. (setcar old (car new))))
  611. (defun org-element-create (type &optional props &rest children)
  612. "Create a new element of type TYPE.
  613. Optional argument PROPS, when non-nil, is a plist defining the
  614. properties of the element. CHILDREN can be elements, objects or
  615. strings."
  616. (apply #'org-element-adopt-elements (list type props) children))
  617. (defun org-element-copy (datum)
  618. "Return a copy of DATUM.
  619. DATUM is an element, object, string or nil. `:parent' property
  620. is cleared and contents are removed in the process."
  621. (when datum
  622. (let ((type (org-element-type datum)))
  623. (pcase type
  624. (`org-data (list 'org-data nil))
  625. (`plain-text (substring-no-properties datum))
  626. (`nil (copy-sequence datum))
  627. (_
  628. (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
  629. ;; We cannot simply return the copies property list. When
  630. ;; DATUM is i.e. a headline, it's property list (`:title'
  631. ;; in case of headline) can contain parsed objects. The
  632. ;; objects will contain `:parent' property set to the DATUM
  633. ;; itself. When copied, these inner `:parent' propery
  634. ;; values will contain incorrect object decoupled from
  635. ;; DATUM. Changes to the DATUM copy will not longer be
  636. ;; reflected in the `:parent' properties. So, we need to
  637. ;; reassign inner `:parent' propreties to the DATUM copy
  638. ;; explicitly.
  639. (org-element-map element-copy (cons 'plain-text org-element-all-objects)
  640. (lambda (obj) (when (equal datum (org-element-property :parent obj))
  641. (org-element-put-property obj :parent element-copy))))
  642. element-copy))))))
  643. ;;; Greater elements
  644. ;;
  645. ;; For each greater element type, we define a parser and an
  646. ;; interpreter.
  647. ;;
  648. ;; A parser returns the element or object as the list described above.
  649. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  650. ;; every element containing a secondary string (see
  651. ;; `org-element-secondary-value-alist') will accept an optional
  652. ;; argument to toggle parsing of these secondary strings. Moreover,
  653. ;; `item' parser requires current list's structure as its first
  654. ;; element.
  655. ;;
  656. ;; An interpreter accepts two arguments: the list representation of
  657. ;; the element or object, and its contents. The latter may be nil,
  658. ;; depending on the element or object considered. It returns the
  659. ;; appropriate Org syntax, as a string.
  660. ;;
  661. ;; Parsing functions must follow the naming convention:
  662. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  663. ;; defined in `org-element-greater-elements'.
  664. ;;
  665. ;; Similarly, interpreting functions must follow the naming
  666. ;; convention: org-element-TYPE-interpreter.
  667. ;;
  668. ;; With the exception of `headline' and `item' types, greater elements
  669. ;; cannot contain other greater elements of their own type.
  670. ;;
  671. ;; Beside implementing a parser and an interpreter, adding a new
  672. ;; greater element requires tweaking `org-element--current-element'.
  673. ;; Moreover, the newly defined type must be added to both
  674. ;; `org-element-all-elements' and `org-element-greater-elements'.
  675. ;;;; Center Block
  676. (defun org-element-center-block-parser (limit affiliated)
  677. "Parse a center block.
  678. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  679. the buffer position at the beginning of the first affiliated
  680. keyword and CDR is a plist of affiliated keywords along with
  681. their value.
  682. Return a list whose CAR is `center-block' and CDR is a plist
  683. containing `:begin', `:end', `:contents-begin', `:contents-end',
  684. `:post-blank' and `:post-affiliated' keywords.
  685. Assume point is at the beginning of the block."
  686. (let ((case-fold-search t))
  687. (if (not (save-excursion
  688. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  689. ;; Incomplete block: parse it as a paragraph.
  690. (org-element-paragraph-parser limit affiliated)
  691. (let ((block-end-line (match-beginning 0)))
  692. (let* ((begin (car affiliated))
  693. (post-affiliated (point))
  694. ;; Empty blocks have no contents.
  695. (contents-begin (progn (forward-line)
  696. (and (< (point) block-end-line)
  697. (point))))
  698. (contents-end (and contents-begin block-end-line))
  699. (pos-before-blank (progn (goto-char block-end-line)
  700. (forward-line)
  701. (point)))
  702. (end (save-excursion
  703. (skip-chars-forward " \r\t\n" limit)
  704. (if (eobp) (point) (line-beginning-position)))))
  705. (list 'center-block
  706. (nconc
  707. (list :begin begin
  708. :end end
  709. :contents-begin contents-begin
  710. :contents-end contents-end
  711. :post-blank (count-lines pos-before-blank end)
  712. :post-affiliated post-affiliated)
  713. (cdr affiliated))))))))
  714. (defun org-element-center-block-interpreter (_ contents)
  715. "Interpret a center-block element as Org syntax.
  716. CONTENTS is the contents of the element."
  717. (format "#+begin_center\n%s#+end_center" contents))
  718. ;;;; Drawer
  719. (defun org-element-drawer-parser (limit affiliated)
  720. "Parse a drawer.
  721. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  722. the buffer position at the beginning of the first affiliated
  723. keyword and CDR is a plist of affiliated keywords along with
  724. their value.
  725. Return a list whose CAR is `drawer' and CDR is a plist containing
  726. `:drawer-name', `:begin', `:end', `:contents-begin',
  727. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  728. Assume point is at beginning of drawer."
  729. (let ((case-fold-search t))
  730. (if (not (save-excursion
  731. (goto-char (min limit (line-end-position)))
  732. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  733. ;; Incomplete drawer: parse it as a paragraph.
  734. (org-element-paragraph-parser limit affiliated)
  735. (save-excursion
  736. (let* ((drawer-end-line (match-beginning 0))
  737. (name
  738. (progn
  739. (looking-at org-element-drawer-re)
  740. (match-string-no-properties 1)))
  741. (begin (car affiliated))
  742. (post-affiliated (point))
  743. ;; Empty drawers have no contents.
  744. (contents-begin (progn (forward-line)
  745. (and (< (point) drawer-end-line)
  746. (point))))
  747. (contents-end (and contents-begin drawer-end-line))
  748. (pos-before-blank (progn (goto-char drawer-end-line)
  749. (forward-line)
  750. (point)))
  751. (end (progn (skip-chars-forward " \r\t\n" limit)
  752. (if (eobp) (point) (line-beginning-position)))))
  753. (list 'drawer
  754. (nconc
  755. (list :begin begin
  756. :end end
  757. :drawer-name name
  758. :contents-begin contents-begin
  759. :contents-end contents-end
  760. :post-blank (count-lines pos-before-blank end)
  761. :post-affiliated post-affiliated)
  762. (cdr affiliated))))))))
  763. (defun org-element-drawer-interpreter (drawer contents)
  764. "Interpret DRAWER element as Org syntax.
  765. CONTENTS is the contents of the element."
  766. (format ":%s:\n%s:END:"
  767. (org-element-property :drawer-name drawer)
  768. contents))
  769. ;;;; Dynamic Block
  770. (defun org-element-dynamic-block-parser (limit affiliated)
  771. "Parse a dynamic block.
  772. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  773. the buffer position at the beginning of the first affiliated
  774. keyword and CDR is a plist of affiliated keywords along with
  775. their value.
  776. Return a list whose CAR is `dynamic-block' and CDR is a plist
  777. containing `:block-name', `:begin', `:end', `:contents-begin',
  778. `:contents-end', `:arguments', `:post-blank' and
  779. `:post-affiliated' keywords.
  780. Assume point is at beginning of dynamic block."
  781. (let ((case-fold-search t))
  782. (if (not (save-excursion
  783. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  784. ;; Incomplete block: parse it as a paragraph.
  785. (org-element-paragraph-parser limit affiliated)
  786. (let ((block-end-line (match-beginning 0)))
  787. (save-excursion
  788. (let* ((name (progn
  789. (looking-at org-element-dynamic-block-open-re)
  790. (match-string-no-properties 1)))
  791. (arguments (match-string-no-properties 2))
  792. (begin (car affiliated))
  793. (post-affiliated (point))
  794. ;; Empty blocks have no contents.
  795. (contents-begin (progn (forward-line)
  796. (and (< (point) block-end-line)
  797. (point))))
  798. (contents-end (and contents-begin block-end-line))
  799. (pos-before-blank (progn (goto-char block-end-line)
  800. (forward-line)
  801. (point)))
  802. (end (progn (skip-chars-forward " \r\t\n" limit)
  803. (if (eobp) (point) (line-beginning-position)))))
  804. (list 'dynamic-block
  805. (nconc
  806. (list :begin begin
  807. :end end
  808. :block-name name
  809. :arguments arguments
  810. :contents-begin contents-begin
  811. :contents-end contents-end
  812. :post-blank (count-lines pos-before-blank end)
  813. :post-affiliated post-affiliated)
  814. (cdr affiliated)))))))))
  815. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  816. "Interpret DYNAMIC-BLOCK element as Org syntax.
  817. CONTENTS is the contents of the element."
  818. (format "#+begin: %s%s\n%s#+end:"
  819. (org-element-property :block-name dynamic-block)
  820. (let ((args (org-element-property :arguments dynamic-block)))
  821. (if args (concat " " args) ""))
  822. contents))
  823. ;;;; Footnote Definition
  824. (defconst org-element--footnote-separator
  825. (concat org-element-headline-re "\\|"
  826. org-footnote-definition-re "\\|"
  827. "^\\([ \t]*\n\\)\\{2,\\}")
  828. "Regexp used as a footnote definition separator.")
  829. (defun org-element-footnote-definition-parser (limit affiliated)
  830. "Parse a footnote definition.
  831. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  832. the buffer position at the beginning of the first affiliated
  833. keyword and CDR is a plist of affiliated keywords along with
  834. their value.
  835. Return a list whose CAR is `footnote-definition' and CDR is
  836. a plist containing `:label', `:begin' `:end', `:contents-begin',
  837. `:contents-end', `:pre-blank',`:post-blank' and
  838. `:post-affiliated' keywords.
  839. Assume point is at the beginning of the footnote definition."
  840. (save-excursion
  841. (let* ((label (progn (looking-at org-footnote-definition-re)
  842. (match-string-no-properties 1)))
  843. (begin (car affiliated))
  844. (post-affiliated (point))
  845. (end
  846. (save-excursion
  847. (end-of-line)
  848. (cond
  849. ((not
  850. (re-search-forward org-element--footnote-separator limit t))
  851. limit)
  852. ((eq ?\[ (char-after (match-beginning 0)))
  853. ;; At a new footnote definition, make sure we end
  854. ;; before any affiliated keyword above.
  855. (forward-line -1)
  856. (while (and (> (point) post-affiliated)
  857. (looking-at-p org-element--affiliated-re))
  858. (forward-line -1))
  859. (line-beginning-position 2))
  860. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  861. (t (skip-chars-forward " \r\t\n" limit)
  862. (if (= limit (point)) limit (line-beginning-position))))))
  863. (pre-blank 0)
  864. (contents-begin
  865. (progn (search-forward "]")
  866. (skip-chars-forward " \r\t\n" end)
  867. (cond ((= (point) end) nil)
  868. ((= (line-beginning-position) post-affiliated) (point))
  869. (t
  870. (setq pre-blank
  871. (count-lines (line-beginning-position) begin))
  872. (line-beginning-position)))))
  873. (contents-end
  874. (progn (goto-char end)
  875. (skip-chars-backward " \r\t\n")
  876. (line-beginning-position 2))))
  877. (list 'footnote-definition
  878. (nconc
  879. (list :label label
  880. :begin begin
  881. :end end
  882. :contents-begin contents-begin
  883. :contents-end (and contents-begin contents-end)
  884. :pre-blank pre-blank
  885. :post-blank (count-lines contents-end end)
  886. :post-affiliated post-affiliated)
  887. (cdr affiliated))))))
  888. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  889. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  890. CONTENTS is the contents of the footnote-definition."
  891. (let ((pre-blank
  892. (min (or (org-element-property :pre-blank footnote-definition)
  893. ;; 0 is specific to paragraphs at the beginning of
  894. ;; the footnote definition, so we use 1 as
  895. ;; a fall-back value, which is more universal.
  896. 1)
  897. ;; Footnote ends after more than two consecutive empty
  898. ;; lines: limit ourselves to 2 newline characters.
  899. 2)))
  900. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  901. (if (= pre-blank 0) (concat " " (org-trim contents))
  902. (concat (make-string pre-blank ?\n) contents)))))
  903. ;;;; Headline
  904. (defun org-element--get-node-properties (&optional at-point-p?)
  905. "Return node properties for headline or property drawer at point.
  906. Upcase property names. It avoids confusion between properties
  907. obtained through property drawer and default properties from the
  908. parser (e.g. `:end' and :END:). Return value is a plist.
  909. When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
  910. parse properties for property drawer at point."
  911. (save-excursion
  912. (unless at-point-p?
  913. (forward-line)
  914. (when (looking-at-p org-element-planning-line-re) (forward-line)))
  915. (when (looking-at org-property-drawer-re)
  916. (forward-line)
  917. (let ((end (match-end 0)) properties)
  918. (while (< (line-end-position) end)
  919. (looking-at org-property-re)
  920. (let* ((property-name (concat ":" (upcase (match-string 2))))
  921. (property-name-symbol (intern property-name))
  922. (property-value (match-string-no-properties 3)))
  923. (cond
  924. ((and (plist-member properties property-name-symbol)
  925. (string-match-p "+$" property-name))
  926. (let ((val (plist-get properties property-name-symbol)))
  927. (if (listp val)
  928. (setq properties
  929. (plist-put properties
  930. property-name-symbol
  931. (append (plist-get properties property-name-symbol)
  932. (list property-value))))
  933. (plist-put properties property-name-symbol (list val property-value)))))
  934. (t (setq properties (plist-put properties property-name-symbol property-value)))))
  935. (forward-line))
  936. properties))))
  937. (defun org-element--get-time-properties ()
  938. "Return time properties associated to headline at point.
  939. Return value is a plist."
  940. (save-excursion
  941. (when (progn (forward-line) (looking-at org-element-planning-line-re))
  942. (let ((end (line-end-position))
  943. plist)
  944. (while (re-search-forward org-element-planning-keywords-re end t)
  945. (skip-chars-forward " \t")
  946. (let ((keyword (match-string 0))
  947. (time (org-element-timestamp-parser)))
  948. (cond ((equal keyword org-element-scheduled-keyword)
  949. (setq plist (plist-put plist :scheduled time)))
  950. ((equal keyword org-element-deadline-keyword)
  951. (setq plist (plist-put plist :deadline time)))
  952. (t (setq plist (plist-put plist :closed time))))))
  953. plist))))
  954. (defun org-element-headline-parser (&optional _ raw-secondary-p)
  955. "Parse a headline.
  956. Return a list whose CAR is `headline' and CDR is a plist
  957. containing `:raw-value', `:title', `:begin', `:end',
  958. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  959. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  960. `:deadline', `:closed', `:archivedp', `:commentedp'
  961. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  962. keywords.
  963. The plist also contains any property set in the property drawer,
  964. with its name in upper cases and colons added at the
  965. beginning (e.g., `:CUSTOM_ID').
  966. When RAW-SECONDARY-P is non-nil, headline's title will not be
  967. parsed as a secondary string, but as a plain string instead.
  968. Assume point is at beginning of the headline."
  969. (save-excursion
  970. (let* ((begin (point))
  971. (true-level (prog1 (skip-chars-forward "*")
  972. (skip-chars-forward " \t")))
  973. (level (org-reduced-level true-level))
  974. (todo (and org-todo-regexp
  975. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  976. (progn (goto-char (match-end 0))
  977. (skip-chars-forward " \t")
  978. (match-string 1))))
  979. (todo-type
  980. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  981. (priority (and (looking-at "\\[#.\\][ \t]*")
  982. (progn (goto-char (match-end 0))
  983. (aref (match-string 0) 2))))
  984. (commentedp
  985. (and (let ((case-fold-search nil))
  986. (looking-at org-element-comment-string))
  987. (goto-char (match-end 0))
  988. (when (looking-at-p "\\(?:[ \t]\\|$\\)")
  989. (point))))
  990. (title-start (prog1 (point)
  991. (unless (or todo priority commentedp)
  992. ;; Headline like "* :tag:"
  993. (skip-chars-backward " \t"))))
  994. (tags (when (re-search-forward
  995. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  996. (line-end-position)
  997. 'move)
  998. (goto-char (match-beginning 0))
  999. (org-split-string (match-string 1) ":")))
  1000. (title-end (point))
  1001. (raw-value (org-trim
  1002. (buffer-substring-no-properties title-start title-end)))
  1003. (archivedp (member org-element-archive-tag tags))
  1004. (footnote-section-p (and org-footnote-section
  1005. (string= org-footnote-section raw-value)))
  1006. (standard-props (org-element--get-node-properties))
  1007. (time-props (org-element--get-time-properties))
  1008. (end
  1009. (save-excursion
  1010. (let ((re (rx-to-string
  1011. `(seq line-start (** 1 ,true-level "*") " "))))
  1012. (if (re-search-forward re nil t)
  1013. (line-beginning-position)
  1014. (point-max)))))
  1015. (contents-begin (save-excursion
  1016. (forward-line)
  1017. (skip-chars-forward " \r\t\n" end)
  1018. (and (/= (point) end) (line-beginning-position))))
  1019. (contents-end (and contents-begin
  1020. (progn (goto-char end)
  1021. (skip-chars-backward " \r\t\n")
  1022. (line-beginning-position 2))))
  1023. (robust-begin (and contents-begin
  1024. (progn (goto-char contents-begin)
  1025. (when (looking-at-p org-element-planning-line-re)
  1026. (forward-line))
  1027. (when (looking-at org-property-drawer-re)
  1028. (goto-char (match-end 0)))
  1029. ;; If there is :pre-blank, we
  1030. ;; need to be careful about
  1031. ;; robust beginning.
  1032. (max (if (< (+ 2 contents-begin) contents-end)
  1033. (+ 2 contents-begin)
  1034. 0)
  1035. (point)))))
  1036. (robust-end (and robust-begin
  1037. (when (> (- contents-end 2) robust-begin)
  1038. (- contents-end 2)))))
  1039. (unless robust-end (setq robust-begin nil))
  1040. (let ((headline
  1041. (list 'headline
  1042. (nconc
  1043. (list :raw-value raw-value
  1044. :begin begin
  1045. :end end
  1046. :pre-blank
  1047. (if (not contents-begin) 0
  1048. (1- (count-lines begin contents-begin)))
  1049. :contents-begin contents-begin
  1050. :contents-end contents-end
  1051. :robust-begin robust-begin
  1052. :robust-end robust-end
  1053. :level level
  1054. :priority priority
  1055. :tags tags
  1056. :todo-keyword todo
  1057. :todo-type todo-type
  1058. :post-blank
  1059. (if contents-end
  1060. (count-lines contents-end end)
  1061. (1- (count-lines begin end)))
  1062. :footnote-section-p footnote-section-p
  1063. :archivedp archivedp
  1064. :commentedp commentedp
  1065. :post-affiliated begin)
  1066. time-props
  1067. standard-props))))
  1068. (org-element-put-property
  1069. headline :title
  1070. (if raw-secondary-p raw-value
  1071. (org-element--parse-objects
  1072. (progn (goto-char title-start)
  1073. (skip-chars-forward " \t")
  1074. (point))
  1075. (progn (goto-char title-end)
  1076. (skip-chars-backward " \t")
  1077. (point))
  1078. nil
  1079. (org-element-restriction 'headline)
  1080. headline)))))))
  1081. (defun org-element-headline-interpreter (headline contents)
  1082. "Interpret HEADLINE element as Org syntax.
  1083. CONTENTS is the contents of the element."
  1084. (let* ((level (org-element-property :level headline))
  1085. (todo (org-element-property :todo-keyword headline))
  1086. (priority (org-element-property :priority headline))
  1087. (title (org-element-interpret-data
  1088. (org-element-property :title headline)))
  1089. (tags (let ((tag-list (org-element-property :tags headline)))
  1090. (and tag-list
  1091. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  1092. (commentedp (org-element-property :commentedp headline))
  1093. (pre-blank (or (org-element-property :pre-blank headline) 0))
  1094. (heading
  1095. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  1096. ?*)
  1097. (and todo (concat " " todo))
  1098. (and commentedp (concat " " org-element-comment-string))
  1099. (and priority (format " [#%c]" priority))
  1100. " "
  1101. (if (and org-footnote-section
  1102. (org-element-property :footnote-section-p headline))
  1103. org-footnote-section
  1104. title))))
  1105. (concat
  1106. heading
  1107. ;; Align tags.
  1108. (when tags
  1109. (cond
  1110. ((zerop org-tags-column) (format " %s" tags))
  1111. ((< org-tags-column 0)
  1112. (concat
  1113. (make-string
  1114. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1115. ?\s)
  1116. tags))
  1117. (t
  1118. (concat
  1119. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1120. tags))))
  1121. (make-string (1+ pre-blank) ?\n)
  1122. contents)))
  1123. ;;;; org-data
  1124. (defun org-element--get-global-node-properties ()
  1125. "Return node properties associated with the whole Org buffer.
  1126. Upcase property names. It avoids confusion between properties
  1127. obtained through property drawer and default properties from the
  1128. parser (e.g. `:end' and :END:). Return value is a plist."
  1129. (org-with-wide-buffer
  1130. (goto-char (point-min))
  1131. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1132. (org-element--get-node-properties t)))
  1133. (defvar org-element-org-data-parser--recurse nil)
  1134. (defun org-element-org-data-parser (&optional _)
  1135. "Parse org-data."
  1136. (org-with-wide-buffer
  1137. (let* ((begin 1)
  1138. (contents-begin (progn
  1139. (goto-char 1)
  1140. (org-skip-whitespace)
  1141. (beginning-of-line)
  1142. (point)))
  1143. (end (point-max))
  1144. (pos-before-blank (progn (goto-char (point-max))
  1145. (skip-chars-backward " \r\t\n")
  1146. (line-beginning-position 2)))
  1147. (robust-end (when (> (- pos-before-blank 2) contents-begin)
  1148. (- pos-before-blank 2)))
  1149. (robust-begin (when (and robust-end
  1150. (< (+ 2 contents-begin) pos-before-blank))
  1151. (or
  1152. (org-with-wide-buffer
  1153. (goto-char (point-min))
  1154. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1155. (when (looking-at org-property-drawer-re)
  1156. (goto-char (match-end 0))
  1157. (skip-chars-backward " \t")
  1158. (min robust-end (point))))
  1159. (+ 2 contents-begin))))
  1160. (category (cond ((null org-category)
  1161. (when (with-current-buffer
  1162. (or (buffer-base-buffer)
  1163. (current-buffer))
  1164. buffer-file-name)
  1165. (file-name-sans-extension
  1166. (file-name-nondirectory
  1167. (with-current-buffer
  1168. (or (buffer-base-buffer)
  1169. (current-buffer))
  1170. buffer-file-name)))))
  1171. ((symbolp org-category) (symbol-name org-category))
  1172. (t org-category)))
  1173. (category (catch 'buffer-category
  1174. (unless org-element-org-data-parser--recurse
  1175. (org-with-point-at end
  1176. ;; Avoid recursive calls from
  1177. ;; `org-element-at-point-no-context'.
  1178. (let ((org-element-org-data-parser--recurse t))
  1179. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  1180. (org-element-with-disabled-cache
  1181. (let ((element (org-element-at-point-no-context)))
  1182. (when (eq (org-element-type element) 'keyword)
  1183. (throw 'buffer-category
  1184. (org-element-property :value element)))))))))
  1185. category))
  1186. (properties (org-element--get-global-node-properties)))
  1187. (unless (plist-get properties :CATEGORY)
  1188. (setq properties (plist-put properties :CATEGORY category)))
  1189. (list 'org-data
  1190. (nconc
  1191. (list :begin begin
  1192. :contents-begin contents-begin
  1193. :contents-end pos-before-blank
  1194. :end end
  1195. :robust-begin robust-begin
  1196. :robust-end robust-end
  1197. :post-blank (count-lines pos-before-blank end)
  1198. :post-affiliated begin
  1199. :path (buffer-file-name)
  1200. :mode 'org-data)
  1201. properties)))))
  1202. (defun org-element-org-data-interpreter (_ contents)
  1203. "Interpret ORG-DATA element as Org syntax.
  1204. CONTENTS is the contents of the element."
  1205. contents)
  1206. ;;;; Inlinetask
  1207. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1208. "Parse an inline task.
  1209. Return a list whose CAR is `inlinetask' and CDR is a plist
  1210. containing `:title', `:begin', `:end', `:pre-blank',
  1211. `:contents-begin' and `:contents-end', `:level', `:priority',
  1212. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1213. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1214. `:post-affiliated' keywords.
  1215. The plist also contains any property set in the property drawer,
  1216. with its name in upper cases and colons added at the
  1217. beginning (e.g., `:CUSTOM_ID').
  1218. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1219. title will not be parsed as a secondary string, but as a plain
  1220. string instead.
  1221. Assume point is at beginning of the inline task."
  1222. (save-excursion
  1223. (let* ((begin (point))
  1224. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1225. (skip-chars-forward " \t")))
  1226. (todo (and org-todo-regexp
  1227. (let (case-fold-search) (looking-at org-todo-regexp))
  1228. (progn (goto-char (match-end 0))
  1229. (skip-chars-forward " \t")
  1230. (match-string 0))))
  1231. (todo-type (and todo
  1232. (if (member todo org-done-keywords) 'done 'todo)))
  1233. (priority (and (looking-at "\\[#.\\][ \t]*")
  1234. (progn (goto-char (match-end 0))
  1235. (aref (match-string 0) 2))))
  1236. (title-start (point))
  1237. (tags (when (re-search-forward
  1238. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1239. (line-end-position)
  1240. 'move)
  1241. (goto-char (match-beginning 0))
  1242. (org-split-string (match-string 1) ":")))
  1243. (title-end (point))
  1244. (raw-value (org-trim
  1245. (buffer-substring-no-properties title-start title-end)))
  1246. (task-end (save-excursion
  1247. (end-of-line)
  1248. (and (re-search-forward org-element-headline-re limit t)
  1249. (looking-at-p "[ \t]*END[ \t]*$")
  1250. (line-beginning-position))))
  1251. (standard-props (and task-end (org-element--get-node-properties)))
  1252. (time-props (and task-end (org-element--get-time-properties)))
  1253. (contents-begin (and task-end
  1254. (< (point) task-end)
  1255. (progn
  1256. (forward-line)
  1257. (skip-chars-forward " \t\n")
  1258. (line-beginning-position))))
  1259. (contents-end (and contents-begin task-end))
  1260. (end (progn (when task-end (goto-char task-end))
  1261. (forward-line)
  1262. (skip-chars-forward " \r\t\n" limit)
  1263. (if (eobp) (point) (line-beginning-position))))
  1264. (inlinetask
  1265. (list 'inlinetask
  1266. (nconc
  1267. (list :raw-value raw-value
  1268. :begin begin
  1269. :end end
  1270. :pre-blank
  1271. (if (not contents-begin) 0
  1272. (1- (count-lines begin contents-begin)))
  1273. :contents-begin contents-begin
  1274. :contents-end contents-end
  1275. :level level
  1276. :priority priority
  1277. :tags tags
  1278. :todo-keyword todo
  1279. :todo-type todo-type
  1280. :post-blank (1- (count-lines (or task-end begin) end))
  1281. :post-affiliated begin)
  1282. time-props
  1283. standard-props))))
  1284. (org-element-put-property
  1285. inlinetask :title
  1286. (if raw-secondary-p raw-value
  1287. (org-element--parse-objects
  1288. (progn (goto-char title-start)
  1289. (skip-chars-forward " \t")
  1290. (point))
  1291. (progn (goto-char title-end)
  1292. (skip-chars-backward " \t")
  1293. (point))
  1294. nil
  1295. (org-element-restriction 'inlinetask)
  1296. inlinetask))))))
  1297. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1298. "Interpret INLINETASK element as Org syntax.
  1299. CONTENTS is the contents of inlinetask."
  1300. (let* ((level (org-element-property :level inlinetask))
  1301. (todo (org-element-property :todo-keyword inlinetask))
  1302. (priority (org-element-property :priority inlinetask))
  1303. (title (org-element-interpret-data
  1304. (org-element-property :title inlinetask)))
  1305. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1306. (and tag-list
  1307. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1308. (task (concat (make-string level ?*)
  1309. (and todo (concat " " todo))
  1310. (and priority (format " [#%c]" priority))
  1311. (and title (concat " " title)))))
  1312. (concat task
  1313. ;; Align tags.
  1314. (when tags
  1315. (cond
  1316. ((zerop org-tags-column) (format " %s" tags))
  1317. ((< org-tags-column 0)
  1318. (concat
  1319. (make-string
  1320. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1321. ?\s)
  1322. tags))
  1323. (t
  1324. (concat
  1325. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1326. tags))))
  1327. ;; Prefer degenerate inlinetasks when there are no
  1328. ;; contents.
  1329. (when contents
  1330. (concat "\n"
  1331. contents
  1332. (make-string level ?*) " end")))))
  1333. ;;;; Item
  1334. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1335. "Parse an item.
  1336. STRUCT is the structure of the plain list.
  1337. Return a list whose CAR is `item' and CDR is a plist containing
  1338. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1339. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1340. `:post-blank' and `:post-affiliated' keywords.
  1341. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1342. any, will not be parsed as a secondary string, but as a plain
  1343. string instead.
  1344. Assume point is at the beginning of the item."
  1345. (save-excursion
  1346. (beginning-of-line)
  1347. (looking-at org-list-full-item-re)
  1348. (let* ((begin (point))
  1349. (bullet (match-string-no-properties 1))
  1350. (checkbox (let ((box (match-string 3)))
  1351. (cond ((equal "[ ]" box) 'off)
  1352. ((equal "[X]" box) 'on)
  1353. ((equal "[-]" box) 'trans))))
  1354. (counter (let ((c (match-string 2)))
  1355. (save-match-data
  1356. (cond
  1357. ((not c) nil)
  1358. ((string-match "[A-Za-z]" c)
  1359. (- (string-to-char (upcase (match-string 0 c)))
  1360. 64))
  1361. ((string-match "[0-9]+" c)
  1362. (string-to-number (match-string 0 c)))))))
  1363. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1364. (if (bolp) (point) (line-beginning-position 2))))
  1365. (pre-blank 0)
  1366. (contents-begin
  1367. (progn
  1368. (goto-char
  1369. ;; Ignore tags in un-ordered lists: they are just
  1370. ;; a part of item's body.
  1371. (if (and (match-beginning 4)
  1372. (save-match-data (string-match "[.)]" bullet)))
  1373. (match-beginning 4)
  1374. (match-end 0)))
  1375. (skip-chars-forward " \r\t\n" end)
  1376. (cond ((= (point) end) nil)
  1377. ;; If first line isn't empty, contents really
  1378. ;; start at the text after item's meta-data.
  1379. ((= (line-beginning-position) begin) (point))
  1380. (t
  1381. (setq pre-blank
  1382. (count-lines (line-beginning-position) begin))
  1383. (line-beginning-position)))))
  1384. (contents-end (and contents-begin
  1385. (progn (goto-char end)
  1386. (skip-chars-backward " \r\t\n")
  1387. (line-beginning-position 2))))
  1388. (item
  1389. (list 'item
  1390. (list :bullet bullet
  1391. :begin begin
  1392. :end end
  1393. :contents-begin contents-begin
  1394. :contents-end contents-end
  1395. :checkbox checkbox
  1396. :counter counter
  1397. :structure struct
  1398. :pre-blank pre-blank
  1399. :post-blank (count-lines (or contents-end begin) end)
  1400. :post-affiliated begin))))
  1401. (org-element-put-property
  1402. item :tag
  1403. (let ((raw (org-list-get-tag begin struct)))
  1404. (when raw
  1405. (if raw-secondary-p raw
  1406. (org-element--parse-objects
  1407. (match-beginning 4) (match-end 4) nil
  1408. (org-element-restriction 'item)
  1409. item))))))))
  1410. (defun org-element-item-interpreter (item contents)
  1411. "Interpret ITEM element as Org syntax.
  1412. CONTENTS is the contents of the element."
  1413. (let ((tag (pcase (org-element-property :tag item)
  1414. (`nil nil)
  1415. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1416. (bullet
  1417. (org-list-bullet-string
  1418. (cond
  1419. ((not (string-match-p "[0-9a-zA-Z]"
  1420. (org-element-property :bullet item))) "- ")
  1421. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1422. (t "1.")))))
  1423. (concat
  1424. bullet
  1425. (pcase (org-element-property :counter item)
  1426. (`nil nil)
  1427. (counter (format "[@%d] " counter)))
  1428. (pcase (org-element-property :checkbox item)
  1429. (`on "[X] ")
  1430. (`off "[ ] ")
  1431. (`trans "[-] ")
  1432. (_ nil))
  1433. tag
  1434. (when contents
  1435. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1436. (pre-blank
  1437. (min (or (org-element-property :pre-blank item)
  1438. ;; 0 is specific to paragraphs at the
  1439. ;; beginning of the item, so we use 1 as
  1440. ;; a fall-back value, which is more universal.
  1441. 1)
  1442. ;; Lists ends after more than two consecutive
  1443. ;; empty lines: limit ourselves to 2 newline
  1444. ;; characters.
  1445. 2))
  1446. (contents (replace-regexp-in-string
  1447. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1448. (if (= pre-blank 0) (org-trim contents)
  1449. (concat (make-string pre-blank ?\n) contents)))))))
  1450. ;;;; Plain List
  1451. (defun org-element--list-struct (limit)
  1452. ;; Return structure of list at point. Internal function. See
  1453. ;; `org-list-struct' for details.
  1454. (let ((case-fold-search t)
  1455. (top-ind limit)
  1456. (item-re (org-item-re))
  1457. (inlinetask-re (and (featurep 'org-inlinetask)
  1458. (boundp 'org-inlinetask-min-level)
  1459. (boundp 'org-inlinetask-max-level)
  1460. (format "^\\*\\{%d,%d\\}+ "
  1461. org-inlinetask-min-level
  1462. org-inlinetask-max-level)))
  1463. items struct)
  1464. (save-excursion
  1465. (catch :exit
  1466. (while t
  1467. (cond
  1468. ;; At limit: end all items.
  1469. ((>= (point) limit)
  1470. (let ((end (progn (skip-chars-backward " \r\t\n")
  1471. (line-beginning-position 2))))
  1472. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1473. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1474. ;; At list end: end all items.
  1475. ((looking-at org-list-end-re)
  1476. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1477. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1478. ;; At a new item: end previous sibling.
  1479. ((looking-at item-re)
  1480. (let ((ind (save-excursion (skip-chars-forward " \t")
  1481. (org-current-text-column))))
  1482. (setq top-ind (min top-ind ind))
  1483. (while (and items (<= ind (nth 1 (car items))))
  1484. (let ((item (pop items)))
  1485. (setcar (nthcdr 6 item) (point))
  1486. (push item struct)))
  1487. (push (progn (looking-at org-list-full-item-re)
  1488. (let ((bullet (match-string-no-properties 1)))
  1489. (list (point)
  1490. ind
  1491. bullet
  1492. (match-string-no-properties 2) ; counter
  1493. (match-string-no-properties 3) ; checkbox
  1494. ;; Description tag.
  1495. (and (save-match-data
  1496. (string-match "[-+*]" bullet))
  1497. (match-string-no-properties 4))
  1498. ;; Ending position, unknown so far.
  1499. nil)))
  1500. items))
  1501. (forward-line))
  1502. ;; Skip empty lines.
  1503. ((looking-at "^[ \t]*$") (forward-line))
  1504. ;; Skip inline tasks and blank lines along the way.
  1505. ((and inlinetask-re (looking-at inlinetask-re))
  1506. (forward-line)
  1507. (let ((origin (point)))
  1508. (when (re-search-forward inlinetask-re limit t)
  1509. (if (looking-at-p "END[ \t]*$") (forward-line)
  1510. (goto-char origin)))))
  1511. ;; At some text line. Check if it ends any previous item.
  1512. (t
  1513. (let ((ind (save-excursion
  1514. (skip-chars-forward " \t")
  1515. (org-current-text-column)))
  1516. (end (save-excursion
  1517. (skip-chars-backward " \r\t\n")
  1518. (line-beginning-position 2))))
  1519. (while (<= ind (nth 1 (car items)))
  1520. (let ((item (pop items)))
  1521. (setcar (nthcdr 6 item) end)
  1522. (push item struct)
  1523. (unless items
  1524. (throw :exit (sort struct #'car-less-than-car))))))
  1525. ;; Skip blocks (any type) and drawers contents.
  1526. (cond
  1527. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1528. (re-search-forward
  1529. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1530. limit t)))
  1531. ((and (looking-at org-element-drawer-re)
  1532. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1533. (forward-line))))))))
  1534. (defun org-element-plain-list-parser (limit affiliated structure)
  1535. "Parse a plain list.
  1536. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1537. the buffer position at the beginning of the first affiliated
  1538. keyword and CDR is a plist of affiliated keywords along with
  1539. their value. STRUCTURE is the structure of the plain list being
  1540. parsed.
  1541. Return a list whose CAR is `plain-list' and CDR is a plist
  1542. containing `:type', `:begin', `:end', `:contents-begin' and
  1543. `:contents-end', `:structure', `:post-blank' and
  1544. `:post-affiliated' keywords.
  1545. Assume point is at the beginning of the list."
  1546. (save-excursion
  1547. (let* ((struct (or structure (org-element--list-struct limit)))
  1548. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1549. ((nth 5 (assq (point) struct)) 'descriptive)
  1550. (t 'unordered)))
  1551. (contents-begin (point))
  1552. (begin (car affiliated))
  1553. (contents-end (let* ((item (assq contents-begin struct))
  1554. (ind (nth 1 item))
  1555. (pos (nth 6 item)))
  1556. (while (and (setq item (assq pos struct))
  1557. (= (nth 1 item) ind))
  1558. (setq pos (nth 6 item)))
  1559. pos))
  1560. (end (progn (goto-char contents-end)
  1561. (skip-chars-forward " \r\t\n" limit)
  1562. (if (= (point) limit) limit (line-beginning-position)))))
  1563. ;; Return value.
  1564. (list 'plain-list
  1565. (nconc
  1566. (list :type type
  1567. :begin begin
  1568. :end end
  1569. :contents-begin contents-begin
  1570. :contents-end contents-end
  1571. :structure struct
  1572. :post-blank (count-lines contents-end end)
  1573. :post-affiliated contents-begin)
  1574. (cdr affiliated))))))
  1575. (defun org-element-plain-list-interpreter (_ contents)
  1576. "Interpret plain-list element as Org syntax.
  1577. CONTENTS is the contents of the element."
  1578. (with-temp-buffer
  1579. (insert contents)
  1580. (goto-char (point-min))
  1581. (org-list-repair)
  1582. (buffer-string)))
  1583. ;;;; Property Drawer
  1584. (defun org-element-property-drawer-parser (limit)
  1585. "Parse a property drawer.
  1586. LIMIT bounds the search.
  1587. Return a list whose car is `property-drawer' and cdr is a plist
  1588. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1589. `:post-blank' and `:post-affiliated' keywords.
  1590. Assume point is at the beginning of the property drawer."
  1591. (save-excursion
  1592. (let ((case-fold-search t)
  1593. (begin (point))
  1594. (contents-begin (line-beginning-position 2)))
  1595. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1596. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1597. (match-beginning 0)))
  1598. (before-blank (progn (forward-line) (point)))
  1599. (end (progn (skip-chars-forward " \r\t\n" limit)
  1600. (if (eobp) (point) (line-beginning-position)))))
  1601. (list 'property-drawer
  1602. (list :begin begin
  1603. :end end
  1604. :contents-begin (and contents-end contents-begin)
  1605. :contents-end contents-end
  1606. :post-blank (count-lines before-blank end)
  1607. :post-affiliated begin))))))
  1608. (defun org-element-property-drawer-interpreter (_ contents)
  1609. "Interpret property-drawer element as Org syntax.
  1610. CONTENTS is the properties within the drawer."
  1611. (format ":PROPERTIES:\n%s:END:" contents))
  1612. ;;;; Quote Block
  1613. (defun org-element-quote-block-parser (limit affiliated)
  1614. "Parse a quote block.
  1615. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1616. the buffer position at the beginning of the first affiliated
  1617. keyword and CDR is a plist of affiliated keywords along with
  1618. their value.
  1619. Return a list whose CAR is `quote-block' and CDR is a plist
  1620. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1621. `:post-blank' and `:post-affiliated' keywords.
  1622. Assume point is at the beginning of the block."
  1623. (let ((case-fold-search t))
  1624. (if (not (save-excursion
  1625. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1626. ;; Incomplete block: parse it as a paragraph.
  1627. (org-element-paragraph-parser limit affiliated)
  1628. (let ((block-end-line (match-beginning 0)))
  1629. (save-excursion
  1630. (let* ((begin (car affiliated))
  1631. (post-affiliated (point))
  1632. ;; Empty blocks have no contents.
  1633. (contents-begin (progn (forward-line)
  1634. (and (< (point) block-end-line)
  1635. (point))))
  1636. (contents-end (and contents-begin block-end-line))
  1637. (pos-before-blank (progn (goto-char block-end-line)
  1638. (forward-line)
  1639. (point)))
  1640. (end (progn (skip-chars-forward " \r\t\n" limit)
  1641. (if (eobp) (point) (line-beginning-position)))))
  1642. (list 'quote-block
  1643. (nconc
  1644. (list :begin begin
  1645. :end end
  1646. :contents-begin contents-begin
  1647. :contents-end contents-end
  1648. :post-blank (count-lines pos-before-blank end)
  1649. :post-affiliated post-affiliated)
  1650. (cdr affiliated)))))))))
  1651. (defun org-element-quote-block-interpreter (_ contents)
  1652. "Interpret quote-block element as Org syntax.
  1653. CONTENTS is the contents of the element."
  1654. (format "#+begin_quote\n%s#+end_quote" contents))
  1655. ;;;; Section
  1656. (defun org-element-section-parser (_)
  1657. "Parse a section.
  1658. Return a list whose CAR is `section' and CDR is a plist
  1659. containing `:begin', `:end', `:contents-begin', `contents-end',
  1660. `:post-blank' and `:post-affiliated' keywords."
  1661. (save-excursion
  1662. ;; Beginning of section is the beginning of the first non-blank
  1663. ;; line after previous headline.
  1664. (let* ((begin (point))
  1665. (end (progn (org-with-limited-levels (outline-next-heading))
  1666. (point)))
  1667. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1668. (line-beginning-position 2)))
  1669. (robust-end (when (> (- pos-before-blank 2) begin)
  1670. (- pos-before-blank 2)))
  1671. (robust-begin (when robust-end begin))
  1672. )
  1673. (list 'section
  1674. (list :begin begin
  1675. :end end
  1676. :contents-begin begin
  1677. :contents-end pos-before-blank
  1678. :robust-begin robust-begin
  1679. :robust-end robust-end
  1680. :post-blank (count-lines pos-before-blank end)
  1681. :post-affiliated begin)))))
  1682. (defun org-element-section-interpreter (_ contents)
  1683. "Interpret section element as Org syntax.
  1684. CONTENTS is the contents of the element."
  1685. contents)
  1686. ;;;; Special Block
  1687. (defun org-element-special-block-parser (limit affiliated)
  1688. "Parse a special block.
  1689. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1690. the buffer position at the beginning of the first affiliated
  1691. keyword and CDR is a plist of affiliated keywords along with
  1692. their value.
  1693. Return a list whose CAR is `special-block' and CDR is a plist
  1694. containing `:type', `:begin', `:end', `:contents-begin',
  1695. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1696. Assume point is at the beginning of the block."
  1697. (let* ((case-fold-search t)
  1698. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1699. (match-string-no-properties 1))))
  1700. (if (not (save-excursion
  1701. (re-search-forward
  1702. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1703. limit t)))
  1704. ;; Incomplete block: parse it as a paragraph.
  1705. (org-element-paragraph-parser limit affiliated)
  1706. (let ((block-end-line (match-beginning 0)))
  1707. (save-excursion
  1708. (let* ((begin (car affiliated))
  1709. (post-affiliated (point))
  1710. ;; Empty blocks have no contents.
  1711. (contents-begin (progn (forward-line)
  1712. (and (< (point) block-end-line)
  1713. (point))))
  1714. (contents-end (and contents-begin block-end-line))
  1715. (pos-before-blank (progn (goto-char block-end-line)
  1716. (forward-line)
  1717. (point)))
  1718. (end (progn (skip-chars-forward " \r\t\n" limit)
  1719. (if (eobp) (point) (line-beginning-position)))))
  1720. (list 'special-block
  1721. (nconc
  1722. (list :type type
  1723. :begin begin
  1724. :end end
  1725. :contents-begin contents-begin
  1726. :contents-end contents-end
  1727. :post-blank (count-lines pos-before-blank end)
  1728. :post-affiliated post-affiliated)
  1729. (cdr affiliated)))))))))
  1730. (defun org-element-special-block-interpreter (special-block contents)
  1731. "Interpret SPECIAL-BLOCK element as Org syntax.
  1732. CONTENTS is the contents of the element."
  1733. (let ((block-type (org-element-property :type special-block)))
  1734. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1735. ;;; Elements
  1736. ;;
  1737. ;; For each element, a parser and an interpreter are also defined.
  1738. ;; Both follow the same naming convention used for greater elements.
  1739. ;;
  1740. ;; Also, as for greater elements, adding a new element type is done
  1741. ;; through the following steps: implement a parser and an interpreter,
  1742. ;; tweak `org-element--current-element' so that it recognizes the new
  1743. ;; type and add that new type to `org-element-all-elements'.
  1744. ;;;; Babel Call
  1745. (defun org-element-babel-call-parser (limit affiliated)
  1746. "Parse a babel call.
  1747. LIMIT bounds the search. AFFILIATED is a list of which car is
  1748. the buffer position at the beginning of the first affiliated
  1749. keyword and cdr is a plist of affiliated keywords along with
  1750. their value.
  1751. Return a list whose car is `babel-call' and cdr is a plist
  1752. containing `:call', `:inside-header', `:arguments',
  1753. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1754. `:post-affiliated' as keywords."
  1755. (save-excursion
  1756. (let* ((begin (car affiliated))
  1757. (post-affiliated (point))
  1758. (before-blank (line-beginning-position 2))
  1759. (value (progn (search-forward ":" before-blank t)
  1760. (skip-chars-forward " \t")
  1761. (org-trim
  1762. (buffer-substring-no-properties
  1763. (point) (line-end-position)))))
  1764. (call
  1765. (or (org-string-nw-p
  1766. (buffer-substring-no-properties
  1767. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1768. (point))))))
  1769. (inside-header (org-element--parse-paired-brackets ?\[))
  1770. (arguments (org-string-nw-p
  1771. (org-element--parse-paired-brackets ?\()))
  1772. (end-header
  1773. (org-string-nw-p
  1774. (org-trim
  1775. (buffer-substring-no-properties (point) (line-end-position)))))
  1776. (end (progn (forward-line)
  1777. (skip-chars-forward " \r\t\n" limit)
  1778. (if (eobp) (point) (line-beginning-position)))))
  1779. (list 'babel-call
  1780. (nconc
  1781. (list :call call
  1782. :inside-header inside-header
  1783. :arguments arguments
  1784. :end-header end-header
  1785. :begin begin
  1786. :end end
  1787. :value value
  1788. :post-blank (count-lines before-blank end)
  1789. :post-affiliated post-affiliated)
  1790. (cdr affiliated))))))
  1791. (defun org-element-babel-call-interpreter (babel-call _)
  1792. "Interpret BABEL-CALL element as Org syntax."
  1793. (concat "#+call: "
  1794. (org-element-property :call babel-call)
  1795. (let ((h (org-element-property :inside-header babel-call)))
  1796. (and h (format "[%s]" h)))
  1797. (concat "(" (org-element-property :arguments babel-call) ")")
  1798. (let ((h (org-element-property :end-header babel-call)))
  1799. (and h (concat " " h)))))
  1800. ;;;; Clock
  1801. (defun org-element-clock-parser (limit)
  1802. "Parse a clock.
  1803. LIMIT bounds the search.
  1804. Return a list whose CAR is `clock' and CDR is a plist containing
  1805. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1806. `:post-affiliated' as keywords."
  1807. (save-excursion
  1808. (let* ((case-fold-search nil)
  1809. (begin (point))
  1810. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1811. (skip-chars-forward " \t")
  1812. (org-element-timestamp-parser)))
  1813. (duration (and (search-forward " => " (line-end-position) t)
  1814. (progn (skip-chars-forward " \t")
  1815. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1816. (match-string-no-properties 1)))
  1817. (status (if duration 'closed 'running))
  1818. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1819. (skip-chars-forward " \r\t\n" limit)
  1820. (skip-chars-backward " \t")
  1821. (unless (bolp) (end-of-line))
  1822. (count-lines before-blank (point))))
  1823. (end (point)))
  1824. (list 'clock
  1825. (list :status status
  1826. :value value
  1827. :duration duration
  1828. :begin begin
  1829. :end end
  1830. :post-blank post-blank
  1831. :post-affiliated begin)))))
  1832. (defun org-element-clock-interpreter (clock _)
  1833. "Interpret CLOCK element as Org syntax."
  1834. (concat "CLOCK: "
  1835. (org-element-timestamp-interpreter
  1836. (org-element-property :value clock) nil)
  1837. (let ((duration (org-element-property :duration clock)))
  1838. (and duration
  1839. (concat " => "
  1840. (apply 'format
  1841. "%2s:%02s"
  1842. (org-split-string duration ":")))))))
  1843. ;;;; Comment
  1844. (defun org-element-comment-parser (limit)
  1845. "Parse a comment.
  1846. LIMIT bounds the search.
  1847. Return a list whose CAR is `comment' and CDR is a plist
  1848. containing `:begin', `:end', `:value', `:post-blank',
  1849. `:post-affiliated' keywords.
  1850. Assume point is at comment beginning."
  1851. (save-excursion
  1852. (let* ((begin (point))
  1853. (value (prog2 (looking-at "[ \t]*# ?")
  1854. (buffer-substring-no-properties
  1855. (match-end 0) (line-end-position))
  1856. (forward-line)))
  1857. (com-end
  1858. ;; Get comments ending.
  1859. (progn
  1860. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1861. ;; Accumulate lines without leading hash and first
  1862. ;; whitespace.
  1863. (setq value
  1864. (concat value
  1865. "\n"
  1866. (buffer-substring-no-properties
  1867. (match-end 0) (line-end-position))))
  1868. (forward-line))
  1869. (point)))
  1870. (end (progn (goto-char com-end)
  1871. (skip-chars-forward " \r\t\n" limit)
  1872. (if (eobp) (point) (line-beginning-position)))))
  1873. (list 'comment
  1874. (list :begin begin
  1875. :end end
  1876. :value value
  1877. :post-blank (count-lines com-end end)
  1878. :post-affiliated begin)))))
  1879. (defun org-element-comment-interpreter (comment _)
  1880. "Interpret COMMENT element as Org syntax.
  1881. CONTENTS is nil."
  1882. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1883. ;;;; Comment Block
  1884. (defun org-element-comment-block-parser (limit affiliated)
  1885. "Parse an export block.
  1886. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1887. the buffer position at the beginning of the first affiliated
  1888. keyword and CDR is a plist of affiliated keywords along with
  1889. their value.
  1890. Return a list whose CAR is `comment-block' and CDR is a plist
  1891. containing `:begin', `:end', `:value', `:post-blank' and
  1892. `:post-affiliated' keywords.
  1893. Assume point is at comment block beginning."
  1894. (let ((case-fold-search t))
  1895. (if (not (save-excursion
  1896. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1897. ;; Incomplete block: parse it as a paragraph.
  1898. (org-element-paragraph-parser limit affiliated)
  1899. (let ((contents-end (match-beginning 0)))
  1900. (save-excursion
  1901. (let* ((begin (car affiliated))
  1902. (post-affiliated (point))
  1903. (contents-begin (progn (forward-line) (point)))
  1904. (pos-before-blank (progn (goto-char contents-end)
  1905. (forward-line)
  1906. (point)))
  1907. (end (progn (skip-chars-forward " \r\t\n" limit)
  1908. (if (eobp) (point) (line-beginning-position))))
  1909. (value (buffer-substring-no-properties
  1910. contents-begin contents-end)))
  1911. (list 'comment-block
  1912. (nconc
  1913. (list :begin begin
  1914. :end end
  1915. :value value
  1916. :post-blank (count-lines pos-before-blank end)
  1917. :post-affiliated post-affiliated)
  1918. (cdr affiliated)))))))))
  1919. (defun org-element-comment-block-interpreter (comment-block _)
  1920. "Interpret COMMENT-BLOCK element as Org syntax."
  1921. (format "#+begin_comment\n%s#+end_comment"
  1922. (org-element-normalize-string
  1923. (org-remove-indentation
  1924. (org-element-property :value comment-block)))))
  1925. ;;;; Diary Sexp
  1926. (defun org-element-diary-sexp-parser (limit affiliated)
  1927. "Parse a diary sexp.
  1928. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1929. the buffer position at the beginning of the first affiliated
  1930. keyword and CDR is a plist of affiliated keywords along with
  1931. their value.
  1932. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1933. containing `:begin', `:end', `:value', `:post-blank' and
  1934. `:post-affiliated' keywords."
  1935. (save-excursion
  1936. (let ((begin (car affiliated))
  1937. (post-affiliated (point))
  1938. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1939. (match-string-no-properties 1)))
  1940. (pos-before-blank (progn (forward-line) (point)))
  1941. (end (progn (skip-chars-forward " \r\t\n" limit)
  1942. (if (eobp) (point) (line-beginning-position)))))
  1943. (list 'diary-sexp
  1944. (nconc
  1945. (list :value value
  1946. :begin begin
  1947. :end end
  1948. :post-blank (count-lines pos-before-blank end)
  1949. :post-affiliated post-affiliated)
  1950. (cdr affiliated))))))
  1951. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1952. "Interpret DIARY-SEXP as Org syntax."
  1953. (org-element-property :value diary-sexp))
  1954. ;;;; Example Block
  1955. (defun org-element-example-block-parser (limit affiliated)
  1956. "Parse an example block.
  1957. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1958. the buffer position at the beginning of the first affiliated
  1959. keyword and CDR is a plist of affiliated keywords along with
  1960. their value.
  1961. Return a list whose CAR is `example-block' and CDR is a plist
  1962. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1963. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1964. `:value', `:post-blank' and `:post-affiliated' keywords."
  1965. (let ((case-fold-search t))
  1966. (if (not (save-excursion
  1967. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1968. ;; Incomplete block: parse it as a paragraph.
  1969. (org-element-paragraph-parser limit affiliated)
  1970. (let ((contents-end (match-beginning 0)))
  1971. (save-excursion
  1972. (let* ((switches
  1973. (progn
  1974. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1975. (match-string-no-properties 1)))
  1976. ;; Switches analysis.
  1977. (number-lines
  1978. (and switches
  1979. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1980. switches)
  1981. (cons
  1982. (if (equal (match-string 1 switches) "-")
  1983. 'new
  1984. 'continued)
  1985. (if (not (match-end 2)) 0
  1986. ;; Subtract 1 to give number of lines before
  1987. ;; first line.
  1988. (1- (string-to-number (match-string 2 switches)))))))
  1989. (preserve-indent
  1990. (and switches (string-match "-i\\>" switches)))
  1991. ;; Should labels be retained in (or stripped from) example
  1992. ;; blocks?
  1993. (retain-labels
  1994. (or (not switches)
  1995. (not (string-match "-r\\>" switches))
  1996. (and number-lines (string-match "-k\\>" switches))))
  1997. ;; What should code-references use - labels or
  1998. ;; line-numbers?
  1999. (use-labels
  2000. (or (not switches)
  2001. (and retain-labels
  2002. (not (string-match "-k\\>" switches)))))
  2003. (label-fmt
  2004. (and switches
  2005. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2006. (match-string 1 switches)))
  2007. ;; Standard block parsing.
  2008. (begin (car affiliated))
  2009. (post-affiliated (point))
  2010. (contents-begin (line-beginning-position 2))
  2011. (value (org-unescape-code-in-string
  2012. (buffer-substring-no-properties
  2013. contents-begin contents-end)))
  2014. (pos-before-blank (progn (goto-char contents-end)
  2015. (forward-line)
  2016. (point)))
  2017. (end (progn (skip-chars-forward " \r\t\n" limit)
  2018. (if (eobp) (point) (line-beginning-position)))))
  2019. (list 'example-block
  2020. (nconc
  2021. (list :begin begin
  2022. :end end
  2023. :value value
  2024. :switches switches
  2025. :number-lines number-lines
  2026. :preserve-indent preserve-indent
  2027. :retain-labels retain-labels
  2028. :use-labels use-labels
  2029. :label-fmt label-fmt
  2030. :post-blank (count-lines pos-before-blank end)
  2031. :post-affiliated post-affiliated)
  2032. (cdr affiliated)))))))))
  2033. (defun org-element-example-block-interpreter (example-block _)
  2034. "Interpret EXAMPLE-BLOCK element as Org syntax."
  2035. (let ((switches (org-element-property :switches example-block))
  2036. (value
  2037. (let ((val (org-element-property :value example-block)))
  2038. (cond
  2039. ((or org-src-preserve-indentation
  2040. (org-element-property :preserve-indent example-block))
  2041. val)
  2042. ((= 0 org-edit-src-content-indentation)
  2043. (org-remove-indentation val))
  2044. (t
  2045. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2046. (replace-regexp-in-string "^[ \t]*\\S-"
  2047. (concat ind "\\&")
  2048. (org-remove-indentation val))))))))
  2049. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  2050. (org-element-normalize-string (org-escape-code-in-string value))
  2051. "#+end_example")))
  2052. ;;;; Export Block
  2053. (defun org-element-export-block-parser (limit affiliated)
  2054. "Parse an export block.
  2055. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2056. the buffer position at the beginning of the first affiliated
  2057. keyword and CDR is a plist of affiliated keywords along with
  2058. their value.
  2059. Return a list whose CAR is `export-block' and CDR is a plist
  2060. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  2061. `:post-affiliated' keywords.
  2062. Assume point is at export-block beginning."
  2063. (let* ((case-fold-search t))
  2064. (if (not (save-excursion
  2065. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  2066. ;; Incomplete block: parse it as a paragraph.
  2067. (org-element-paragraph-parser limit affiliated)
  2068. (save-excursion
  2069. (let* ((contents-end (match-beginning 0))
  2070. (backend
  2071. (progn
  2072. (looking-at
  2073. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  2074. (match-string-no-properties 1)))
  2075. (begin (car affiliated))
  2076. (post-affiliated (point))
  2077. (contents-begin (progn (forward-line) (point)))
  2078. (pos-before-blank (progn (goto-char contents-end)
  2079. (forward-line)
  2080. (point)))
  2081. (end (progn (skip-chars-forward " \r\t\n" limit)
  2082. (if (eobp) (point) (line-beginning-position))))
  2083. (value (org-unescape-code-in-string
  2084. (buffer-substring-no-properties contents-begin
  2085. contents-end))))
  2086. (list 'export-block
  2087. (nconc
  2088. (list :type (and backend (upcase backend))
  2089. :begin begin
  2090. :end end
  2091. :value value
  2092. :post-blank (count-lines pos-before-blank end)
  2093. :post-affiliated post-affiliated)
  2094. (cdr affiliated))))))))
  2095. (defun org-element-export-block-interpreter (export-block _)
  2096. "Interpret EXPORT-BLOCK element as Org syntax."
  2097. (format "#+begin_export %s\n%s#+end_export"
  2098. (org-element-property :type export-block)
  2099. (org-element-property :value export-block)))
  2100. ;;;; Fixed-width
  2101. (defun org-element-fixed-width-parser (limit affiliated)
  2102. "Parse a fixed-width section.
  2103. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2104. the buffer position at the beginning of the first affiliated
  2105. keyword and CDR is a plist of affiliated keywords along with
  2106. their value.
  2107. Return a list whose CAR is `fixed-width' and CDR is a plist
  2108. containing `:begin', `:end', `:value', `:post-blank' and
  2109. `:post-affiliated' keywords.
  2110. Assume point is at the beginning of the fixed-width area."
  2111. (save-excursion
  2112. (let* ((begin (car affiliated))
  2113. (post-affiliated (point))
  2114. (end-area
  2115. (progn
  2116. (while (and (< (point) limit)
  2117. (looking-at "[ \t]*:\\( \\|$\\)"))
  2118. (forward-line))
  2119. (if (bolp) (line-end-position 0) (point))))
  2120. (end (progn (skip-chars-forward " \r\t\n" limit)
  2121. (if (eobp) (point) (line-beginning-position)))))
  2122. (list 'fixed-width
  2123. (nconc
  2124. (list :begin begin
  2125. :end end
  2126. :value (replace-regexp-in-string
  2127. "^[ \t]*: ?" ""
  2128. (buffer-substring-no-properties post-affiliated
  2129. end-area))
  2130. :post-blank (count-lines end-area end)
  2131. :post-affiliated post-affiliated)
  2132. (cdr affiliated))))))
  2133. (defun org-element-fixed-width-interpreter (fixed-width _)
  2134. "Interpret FIXED-WIDTH element as Org syntax."
  2135. (let ((value (org-element-property :value fixed-width)))
  2136. (and value (replace-regexp-in-string "^" ": " value))))
  2137. ;;;; Horizontal Rule
  2138. (defun org-element-horizontal-rule-parser (limit affiliated)
  2139. "Parse an horizontal rule.
  2140. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2141. the buffer position at the beginning of the first affiliated
  2142. keyword and CDR is a plist of affiliated keywords along with
  2143. their value.
  2144. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  2145. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  2146. keywords."
  2147. (save-excursion
  2148. (let ((begin (car affiliated))
  2149. (post-affiliated (point))
  2150. (post-hr (progn (forward-line) (point)))
  2151. (end (progn (skip-chars-forward " \r\t\n" limit)
  2152. (if (eobp) (point) (line-beginning-position)))))
  2153. (list 'horizontal-rule
  2154. (nconc
  2155. (list :begin begin
  2156. :end end
  2157. :post-blank (count-lines post-hr end)
  2158. :post-affiliated post-affiliated)
  2159. (cdr affiliated))))))
  2160. (defun org-element-horizontal-rule-interpreter (&rest _)
  2161. "Interpret HORIZONTAL-RULE element as Org syntax."
  2162. "-----")
  2163. ;;;; Keyword
  2164. (defun org-element-keyword-parser (limit affiliated)
  2165. "Parse a keyword at point.
  2166. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2167. the buffer position at the beginning of the first affiliated
  2168. keyword and CDR is a plist of affiliated keywords along with
  2169. their value.
  2170. Return a list whose CAR is a normalized `keyword' (uppercase) and
  2171. CDR is a plist containing `:key', `:value', `:begin', `:end',
  2172. `:post-blank' and `:post-affiliated' keywords."
  2173. (save-excursion
  2174. ;; An orphaned affiliated keyword is considered as a regular
  2175. ;; keyword. In this case AFFILIATED is nil, so we take care of
  2176. ;; this corner case.
  2177. (let ((begin (or (car affiliated) (point)))
  2178. (post-affiliated (point))
  2179. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  2180. (upcase (match-string-no-properties 1))))
  2181. (value (org-trim (buffer-substring-no-properties
  2182. (match-end 0) (line-end-position))))
  2183. (pos-before-blank (progn (forward-line) (point)))
  2184. (end (progn (skip-chars-forward " \r\t\n" limit)
  2185. (if (eobp) (point) (line-beginning-position)))))
  2186. (list 'keyword
  2187. (nconc
  2188. (list :key key
  2189. :value value
  2190. :begin begin
  2191. :end end
  2192. :post-blank (count-lines pos-before-blank end)
  2193. :post-affiliated post-affiliated)
  2194. (cdr affiliated))))))
  2195. (defun org-element-keyword-interpreter (keyword _)
  2196. "Interpret KEYWORD element as Org syntax."
  2197. (format "#+%s: %s"
  2198. (downcase (org-element-property :key keyword))
  2199. (org-element-property :value keyword)))
  2200. ;;;; Latex Environment
  2201. (defconst org-element--latex-begin-environment
  2202. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2203. "Regexp matching the beginning of a LaTeX environment.
  2204. The environment is captured by the first group.
  2205. See also `org-element--latex-end-environment'.")
  2206. (defconst org-element--latex-end-environment
  2207. "\\\\end{%s}[ \t]*$"
  2208. "Format string matching the ending of a LaTeX environment.
  2209. See also `org-element--latex-begin-environment'.")
  2210. (defun org-element-latex-environment-parser (limit affiliated)
  2211. "Parse a LaTeX environment.
  2212. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2213. the buffer position at the beginning of the first affiliated
  2214. keyword and CDR is a plist of affiliated keywords along with
  2215. their value.
  2216. Return a list whose CAR is `latex-environment' and CDR is a plist
  2217. containing `:begin', `:end', `:value', `:post-blank' and
  2218. `:post-affiliated' keywords.
  2219. Assume point is at the beginning of the latex environment."
  2220. (save-excursion
  2221. (let ((case-fold-search t)
  2222. (code-begin (point)))
  2223. (looking-at org-element--latex-begin-environment)
  2224. (if (not (re-search-forward (format org-element--latex-end-environment
  2225. (regexp-quote (match-string 1)))
  2226. limit t))
  2227. ;; Incomplete latex environment: parse it as a paragraph.
  2228. (org-element-paragraph-parser limit affiliated)
  2229. (let* ((code-end (progn (forward-line) (point)))
  2230. (begin (car affiliated))
  2231. (value (buffer-substring-no-properties code-begin code-end))
  2232. (end (progn (skip-chars-forward " \r\t\n" limit)
  2233. (if (eobp) (point) (line-beginning-position)))))
  2234. (list 'latex-environment
  2235. (nconc
  2236. (list :begin begin
  2237. :end end
  2238. :value value
  2239. :post-blank (count-lines code-end end)
  2240. :post-affiliated code-begin)
  2241. (cdr affiliated))))))))
  2242. (defun org-element-latex-environment-interpreter (latex-environment _)
  2243. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2244. (org-element-property :value latex-environment))
  2245. ;;;; Node Property
  2246. (defun org-element-node-property-parser (limit)
  2247. "Parse a node-property at point.
  2248. LIMIT bounds the search.
  2249. Return a list whose CAR is `node-property' and CDR is a plist
  2250. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2251. `:post-affiliated' keywords."
  2252. (looking-at org-property-re)
  2253. (let ((case-fold-search t)
  2254. (begin (point))
  2255. (key (match-string-no-properties 2))
  2256. (value (match-string-no-properties 3))
  2257. (end (save-excursion
  2258. (end-of-line)
  2259. (if (re-search-forward org-property-re limit t)
  2260. (line-beginning-position)
  2261. limit))))
  2262. (list 'node-property
  2263. (list :key key
  2264. :value value
  2265. :begin begin
  2266. :end end
  2267. :post-blank 0
  2268. :post-affiliated begin))))
  2269. (defun org-element-node-property-interpreter (node-property _)
  2270. "Interpret NODE-PROPERTY element as Org syntax."
  2271. (format org-property-format
  2272. (format ":%s:" (org-element-property :key node-property))
  2273. (or (org-element-property :value node-property) "")))
  2274. ;;;; Paragraph
  2275. (defun org-element-paragraph-parser (limit affiliated)
  2276. "Parse a paragraph.
  2277. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2278. the buffer position at the beginning of the first affiliated
  2279. keyword and CDR is a plist of affiliated keywords along with
  2280. their value.
  2281. Return a list whose CAR is `paragraph' and CDR is a plist
  2282. containing `:begin', `:end', `:contents-begin' and
  2283. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2284. Assume point is at the beginning of the paragraph."
  2285. (save-excursion
  2286. (let* ((begin (car affiliated))
  2287. (contents-begin (point))
  2288. (before-blank
  2289. (let ((case-fold-search t))
  2290. (end-of-line)
  2291. ;; A matching `org-element-paragraph-separate' is not
  2292. ;; necessarily the end of the paragraph. In particular,
  2293. ;; drawers, blocks or LaTeX environments opening lines
  2294. ;; must be closed. Moreover keywords with a secondary
  2295. ;; value must belong to "dual keywords".
  2296. (while (not
  2297. (cond
  2298. ((not (and (re-search-forward
  2299. org-element-paragraph-separate limit 'move)
  2300. (progn (beginning-of-line) t))))
  2301. ((looking-at org-element-drawer-re)
  2302. (save-excursion
  2303. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2304. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2305. (save-excursion
  2306. (re-search-forward
  2307. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2308. (regexp-quote (match-string 1)))
  2309. limit t)))
  2310. ((looking-at org-element--latex-begin-environment)
  2311. (save-excursion
  2312. (re-search-forward
  2313. (format org-element--latex-end-environment
  2314. (regexp-quote (match-string 1)))
  2315. limit t)))
  2316. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2317. (member-ignore-case (match-string 1)
  2318. org-element-dual-keywords))
  2319. ;; Everything else is unambiguous.
  2320. (t)))
  2321. (end-of-line))
  2322. (if (= (point) limit) limit
  2323. (goto-char (line-beginning-position)))))
  2324. (contents-end (save-excursion
  2325. (skip-chars-backward " \r\t\n" contents-begin)
  2326. (line-beginning-position 2)))
  2327. (end (progn (skip-chars-forward " \r\t\n" limit)
  2328. (if (eobp) (point) (line-beginning-position)))))
  2329. (list 'paragraph
  2330. (nconc
  2331. (list :begin begin
  2332. :end end
  2333. :contents-begin contents-begin
  2334. :contents-end contents-end
  2335. :post-blank (count-lines before-blank end)
  2336. :post-affiliated contents-begin)
  2337. (cdr affiliated))))))
  2338. (defun org-element-paragraph-interpreter (_ contents)
  2339. "Interpret paragraph element as Org syntax.
  2340. CONTENTS is the contents of the element."
  2341. contents)
  2342. ;;;; Planning
  2343. (defun org-element-planning-parser (limit)
  2344. "Parse a planning.
  2345. LIMIT bounds the search.
  2346. Return a list whose CAR is `planning' and CDR is a plist
  2347. containing `:closed', `:deadline', `:scheduled', `:begin',
  2348. `:end', `:post-blank' and `:post-affiliated' keywords."
  2349. (save-excursion
  2350. (let* ((case-fold-search nil)
  2351. (begin (point))
  2352. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2353. (skip-chars-forward " \r\t\n" limit)
  2354. (skip-chars-backward " \t")
  2355. (unless (bolp) (end-of-line))
  2356. (count-lines before-blank (point))))
  2357. (end (point))
  2358. closed deadline scheduled)
  2359. (goto-char begin)
  2360. (while (re-search-forward org-element-planning-keywords-re end t)
  2361. (skip-chars-forward " \t" end)
  2362. (let ((keyword (match-string 0))
  2363. (time (org-element-timestamp-parser)))
  2364. (cond
  2365. ((equal keyword org-element-closed-keyword) (setq closed time))
  2366. ((equal keyword org-element-deadline-keyword) (setq deadline time))
  2367. (t (setq scheduled time)))))
  2368. (list 'planning
  2369. (list :closed closed
  2370. :deadline deadline
  2371. :scheduled scheduled
  2372. :begin begin
  2373. :end end
  2374. :post-blank post-blank
  2375. :post-affiliated begin)))))
  2376. (defun org-element-planning-interpreter (planning _)
  2377. "Interpret PLANNING element as Org syntax."
  2378. (mapconcat
  2379. #'identity
  2380. (delq nil
  2381. (list (let ((deadline (org-element-property :deadline planning)))
  2382. (when deadline
  2383. (concat org-element-deadline-keyword " "
  2384. (org-element-timestamp-interpreter deadline nil))))
  2385. (let ((scheduled (org-element-property :scheduled planning)))
  2386. (when scheduled
  2387. (concat org-element-scheduled-keyword " "
  2388. (org-element-timestamp-interpreter scheduled nil))))
  2389. (let ((closed (org-element-property :closed planning)))
  2390. (when closed
  2391. (concat org-element-closed-keyword " "
  2392. (org-element-timestamp-interpreter closed nil))))))
  2393. " "))
  2394. ;;;; Src Block
  2395. (defun org-element-src-block-parser (limit affiliated)
  2396. "Parse a source block.
  2397. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2398. the buffer position at the beginning of the first affiliated
  2399. keyword and CDR is a plist of affiliated keywords along with
  2400. their value.
  2401. Return a list whose CAR is `src-block' and CDR is a plist
  2402. containing `:language', `:switches', `:parameters', `:begin',
  2403. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2404. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2405. `:post-affiliated' keywords.
  2406. Assume point is at the beginning of the block."
  2407. (let ((case-fold-search t))
  2408. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2409. limit t)))
  2410. ;; Incomplete block: parse it as a paragraph.
  2411. (org-element-paragraph-parser limit affiliated)
  2412. (let ((contents-end (match-beginning 0)))
  2413. (save-excursion
  2414. (let* ((begin (car affiliated))
  2415. (post-affiliated (point))
  2416. ;; Get language as a string.
  2417. (language
  2418. (progn
  2419. (looking-at
  2420. "^[ \t]*#\\+BEGIN_SRC\
  2421. \\(?: +\\(\\S-+\\)\\)?\
  2422. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2423. \\(.*\\)[ \t]*$")
  2424. (match-string-no-properties 1)))
  2425. ;; Get switches.
  2426. (switches (match-string-no-properties 2))
  2427. ;; Get parameters.
  2428. (parameters (match-string-no-properties 3))
  2429. ;; Switches analysis.
  2430. (number-lines
  2431. (and switches
  2432. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2433. switches)
  2434. (cons
  2435. (if (equal (match-string 1 switches) "-")
  2436. 'new
  2437. 'continued)
  2438. (if (not (match-end 2)) 0
  2439. ;; Subtract 1 to give number of lines before
  2440. ;; first line.
  2441. (1- (string-to-number (match-string 2 switches)))))))
  2442. (preserve-indent (and switches
  2443. (string-match "-i\\>" switches)))
  2444. (label-fmt
  2445. (and switches
  2446. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2447. (match-string 1 switches)))
  2448. ;; Should labels be retained in (or stripped from)
  2449. ;; source blocks?
  2450. (retain-labels
  2451. (or (not switches)
  2452. (not (string-match "-r\\>" switches))
  2453. (and number-lines (string-match "-k\\>" switches))))
  2454. ;; What should code-references use - labels or
  2455. ;; line-numbers?
  2456. (use-labels
  2457. (or (not switches)
  2458. (and retain-labels
  2459. (not (string-match "-k\\>" switches)))))
  2460. ;; Retrieve code.
  2461. (value (org-unescape-code-in-string
  2462. (buffer-substring-no-properties
  2463. (line-beginning-position 2) contents-end)))
  2464. (pos-before-blank (progn (goto-char contents-end)
  2465. (forward-line)
  2466. (point)))
  2467. ;; Get position after ending blank lines.
  2468. (end (progn (skip-chars-forward " \r\t\n" limit)
  2469. (if (eobp) (point) (line-beginning-position)))))
  2470. (list 'src-block
  2471. (nconc
  2472. (list :language language
  2473. :switches (and (org-string-nw-p switches)
  2474. (org-trim switches))
  2475. :parameters (and (org-string-nw-p parameters)
  2476. (org-trim parameters))
  2477. :begin begin
  2478. :end end
  2479. :number-lines number-lines
  2480. :preserve-indent preserve-indent
  2481. :retain-labels retain-labels
  2482. :use-labels use-labels
  2483. :label-fmt label-fmt
  2484. :value value
  2485. :post-blank (count-lines pos-before-blank end)
  2486. :post-affiliated post-affiliated)
  2487. (cdr affiliated)))))))))
  2488. (defun org-element-src-block-interpreter (src-block _)
  2489. "Interpret SRC-BLOCK element as Org syntax."
  2490. (let ((lang (org-element-property :language src-block))
  2491. (switches (org-element-property :switches src-block))
  2492. (params (org-element-property :parameters src-block))
  2493. (value
  2494. (let ((val (org-element-property :value src-block)))
  2495. (cond
  2496. ((or org-src-preserve-indentation
  2497. (org-element-property :preserve-indent src-block))
  2498. val)
  2499. ((zerop org-edit-src-content-indentation)
  2500. (org-remove-indentation val))
  2501. (t
  2502. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2503. (replace-regexp-in-string "^[ \t]*\\S-"
  2504. (concat ind "\\&")
  2505. (org-remove-indentation val))))))))
  2506. (format "#+begin_src%s\n%s#+end_src"
  2507. (concat (and lang (concat " " lang))
  2508. (and switches (concat " " switches))
  2509. (and params (concat " " params)))
  2510. (org-element-normalize-string (org-escape-code-in-string value)))))
  2511. ;;;; Table
  2512. (defun org-element-table-parser (limit affiliated)
  2513. "Parse a table at point.
  2514. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2515. the buffer position at the beginning of the first affiliated
  2516. keyword and CDR is a plist of affiliated keywords along with
  2517. their value.
  2518. Return a list whose CAR is `table' and CDR is a plist containing
  2519. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2520. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2521. keywords.
  2522. Assume point is at the beginning of the table."
  2523. (save-excursion
  2524. (let* ((case-fold-search t)
  2525. (table-begin (point))
  2526. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2527. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2528. (if (eq type 'org) "" "+")))
  2529. (begin (car affiliated))
  2530. (table-end
  2531. (if (re-search-forward end-re limit 'move)
  2532. (goto-char (match-beginning 0))
  2533. (point)))
  2534. (tblfm (let (acc)
  2535. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2536. (push (match-string-no-properties 1) acc)
  2537. (forward-line))
  2538. acc))
  2539. (pos-before-blank (point))
  2540. (end (progn (skip-chars-forward " \r\t\n" limit)
  2541. (if (eobp) (point) (line-beginning-position)))))
  2542. (list 'table
  2543. (nconc
  2544. (list :begin begin
  2545. :end end
  2546. :type type
  2547. :tblfm tblfm
  2548. ;; Only `org' tables have contents. `table.el' tables
  2549. ;; use a `:value' property to store raw table as
  2550. ;; a string.
  2551. :contents-begin (and (eq type 'org) table-begin)
  2552. :contents-end (and (eq type 'org) table-end)
  2553. :value (and (eq type 'table.el)
  2554. (buffer-substring-no-properties
  2555. table-begin table-end))
  2556. :post-blank (count-lines pos-before-blank end)
  2557. :post-affiliated table-begin)
  2558. (cdr affiliated))))))
  2559. (defun org-element-table-interpreter (table contents)
  2560. "Interpret TABLE element as Org syntax.
  2561. CONTENTS is a string, if table's type is `org', or nil."
  2562. (if (eq (org-element-property :type table) 'table.el)
  2563. (org-remove-indentation (org-element-property :value table))
  2564. (concat (with-temp-buffer (insert contents)
  2565. (org-table-align)
  2566. (buffer-string))
  2567. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2568. (reverse (org-element-property :tblfm table))
  2569. "\n"))))
  2570. ;;;; Table Row
  2571. (defun org-element-table-row-parser (_)
  2572. "Parse table row at point.
  2573. Return a list whose CAR is `table-row' and CDR is a plist
  2574. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2575. `:type', `:post-blank' and `:post-affiliated' keywords."
  2576. (save-excursion
  2577. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2578. (begin (point))
  2579. ;; A table rule has no contents. In that case, ensure
  2580. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2581. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2582. (contents-end (and (eq type 'standard)
  2583. (progn
  2584. (end-of-line)
  2585. (skip-chars-backward " \t")
  2586. (point))))
  2587. (end (line-beginning-position 2)))
  2588. (list 'table-row
  2589. (list :type type
  2590. :begin begin
  2591. :end end
  2592. :contents-begin contents-begin
  2593. :contents-end contents-end
  2594. :post-blank 0
  2595. :post-affiliated begin)))))
  2596. (defun org-element-table-row-interpreter (table-row contents)
  2597. "Interpret TABLE-ROW element as Org syntax.
  2598. CONTENTS is the contents of the table row."
  2599. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2600. (concat "|" contents)))
  2601. ;;;; Verse Block
  2602. (defun org-element-verse-block-parser (limit affiliated)
  2603. "Parse a verse block.
  2604. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2605. the buffer position at the beginning of the first affiliated
  2606. keyword and CDR is a plist of affiliated keywords along with
  2607. their value.
  2608. Return a list whose CAR is `verse-block' and CDR is a plist
  2609. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2610. `:post-blank' and `:post-affiliated' keywords.
  2611. Assume point is at beginning of the block."
  2612. (let ((case-fold-search t))
  2613. (if (not (save-excursion
  2614. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2615. ;; Incomplete block: parse it as a paragraph.
  2616. (org-element-paragraph-parser limit affiliated)
  2617. (let ((contents-end (match-beginning 0)))
  2618. (save-excursion
  2619. (let* ((begin (car affiliated))
  2620. (post-affiliated (point))
  2621. (contents-begin (progn (forward-line) (point)))
  2622. (pos-before-blank (progn (goto-char contents-end)
  2623. (forward-line)
  2624. (point)))
  2625. (end (progn (skip-chars-forward " \r\t\n" limit)
  2626. (if (eobp) (point) (line-beginning-position)))))
  2627. (list 'verse-block
  2628. (nconc
  2629. (list :begin begin
  2630. :end end
  2631. :contents-begin contents-begin
  2632. :contents-end contents-end
  2633. :post-blank (count-lines pos-before-blank end)
  2634. :post-affiliated post-affiliated)
  2635. (cdr affiliated)))))))))
  2636. (defun org-element-verse-block-interpreter (_ contents)
  2637. "Interpret verse-block element as Org syntax.
  2638. CONTENTS is verse block contents."
  2639. (format "#+begin_verse\n%s#+end_verse" contents))
  2640. ;;; Objects
  2641. ;;
  2642. ;; Unlike to elements, raw text can be found between objects. Hence,
  2643. ;; `org-element--object-lex' is provided to find the next object in
  2644. ;; buffer.
  2645. ;;
  2646. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2647. ;; object types they can contain will be specified in
  2648. ;; `org-element-object-restrictions'.
  2649. ;;
  2650. ;; Creating a new type of object requires to alter
  2651. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2652. ;; new type in `org-element-all-objects', and possibly add
  2653. ;; restrictions in `org-element-object-restrictions'.
  2654. ;;;; Bold
  2655. (defun org-element--parse-generic-emphasis (mark type)
  2656. "Parse emphasis object at point, if any.
  2657. MARK is the delimiter string used. TYPE is a symbol among
  2658. `bold', `code', `italic', `strike-through', `underline', and
  2659. `verbatim'.
  2660. Assume point is at first MARK."
  2661. (save-excursion
  2662. (let ((origin (point)))
  2663. (unless (bolp) (forward-char -1))
  2664. (let ((opening-re
  2665. (rx-to-string
  2666. `(seq (or line-start (any space ?- ?\( ?' ?\" ?\{))
  2667. ,mark
  2668. (not space)))))
  2669. (when (looking-at opening-re)
  2670. (goto-char (1+ origin))
  2671. (let ((closing-re
  2672. (rx-to-string
  2673. `(seq
  2674. (not space)
  2675. (group ,mark)
  2676. (or (any space ?- ?. ?, ?\; ?: ?! ?? ?' ?\" ?\) ?\} ?\\ ?\[)
  2677. line-end)))))
  2678. (when (re-search-forward closing-re nil t)
  2679. (let ((closing (match-end 1)))
  2680. (goto-char closing)
  2681. (let* ((post-blank (skip-chars-forward " \t"))
  2682. (contents-begin (1+ origin))
  2683. (contents-end (1- closing)))
  2684. (list type
  2685. (append
  2686. (list :begin origin
  2687. :end (point)
  2688. :post-blank post-blank)
  2689. (if (memq type '(code verbatim))
  2690. (list :value
  2691. (and (memq type '(code verbatim))
  2692. (buffer-substring
  2693. contents-begin contents-end)))
  2694. (list :contents-begin contents-begin
  2695. :contents-end contents-end)))))))))))))
  2696. (defun org-element-bold-parser ()
  2697. "Parse bold object at point, if any.
  2698. When at a bold object, return a list whose car is `bold' and cdr
  2699. is a plist with `:begin', `:end', `:contents-begin' and
  2700. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2701. nil.
  2702. Assume point is at the first star marker."
  2703. (org-element--parse-generic-emphasis "*" 'bold))
  2704. (defun org-element-bold-interpreter (_ contents)
  2705. "Interpret bold object as Org syntax.
  2706. CONTENTS is the contents of the object."
  2707. (format "*%s*" contents))
  2708. ;;;; Citation
  2709. (defun org-element-citation-parser ()
  2710. "Parse citation object at point, if any.
  2711. When at a citation object, return a list whose car is `citation'
  2712. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2713. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2714. keywords. Otherwise, return nil.
  2715. Assume point is at the beginning of the citation."
  2716. (when (looking-at org-element-citation-prefix-re)
  2717. (let* ((begin (point))
  2718. (style (and (match-end 1)
  2719. (match-string-no-properties 1)))
  2720. ;; Ignore blanks between cite type and prefix or key.
  2721. (start (match-end 0))
  2722. (closing (with-syntax-table org-element--pair-square-table
  2723. (ignore-errors (scan-lists begin 1 0)))))
  2724. (save-excursion
  2725. (when (and closing
  2726. (re-search-forward org-element-citation-key-re closing t))
  2727. ;; Find prefix, if any.
  2728. (let ((first-key-end (match-end 0))
  2729. (types (org-element-restriction 'citation-reference))
  2730. (cite
  2731. (list 'citation
  2732. (list :style style
  2733. :begin begin
  2734. :post-blank (progn
  2735. (goto-char closing)
  2736. (skip-chars-forward " \t"))
  2737. :end (point)))))
  2738. ;; `:contents-begin' depends on the presence of
  2739. ;; a non-empty common prefix.
  2740. (goto-char first-key-end)
  2741. (if (not (search-backward ";" start t))
  2742. (org-element-put-property cite :contents-begin start)
  2743. (when (< start (point))
  2744. (org-element-put-property
  2745. cite :prefix
  2746. (org-element--parse-objects start (point) nil types cite)))
  2747. (forward-char)
  2748. (org-element-put-property cite :contents-begin (point)))
  2749. ;; `:contents-end' depends on the presence of a non-empty
  2750. ;; common suffix.
  2751. (goto-char (1- closing))
  2752. (skip-chars-backward " \r\t\n")
  2753. (let ((end (point)))
  2754. (if (or (not (search-backward ";" first-key-end t))
  2755. (re-search-forward org-element-citation-key-re end t))
  2756. (org-element-put-property cite :contents-end end)
  2757. (forward-char)
  2758. (when (< (point) end)
  2759. (org-element-put-property
  2760. cite :suffix
  2761. (org-element--parse-objects (point) end nil types cite)))
  2762. (org-element-put-property cite :contents-end (point))))
  2763. cite))))))
  2764. (defun org-element-citation-interpreter (citation contents)
  2765. "Interpret CITATION object as Org syntax.
  2766. CONTENTS is the contents of the object, as a string."
  2767. (let ((prefix (org-element-property :prefix citation))
  2768. (suffix (org-element-property :suffix citation))
  2769. (style (org-element-property :style citation)))
  2770. (concat "[cite"
  2771. (and style (concat "/" style))
  2772. ":"
  2773. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2774. (if suffix
  2775. (concat contents (org-element-interpret-data suffix))
  2776. ;; Remove spurious semicolon.
  2777. (substring contents nil -1))
  2778. "]")))
  2779. ;;;; Citation Reference
  2780. (defun org-element-citation-reference-parser ()
  2781. "Parse citation reference object at point, if any.
  2782. When at a reference, return a list whose car is
  2783. `citation-reference', and cdr is a plist with `:key',
  2784. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2785. Assume point is at the beginning of the reference."
  2786. (save-excursion
  2787. (let ((begin (point)))
  2788. (when (re-search-forward org-element-citation-key-re nil t)
  2789. (let* ((key (match-string-no-properties 1))
  2790. (key-start (match-beginning 0))
  2791. (key-end (match-end 0))
  2792. (separator (search-forward ";" nil t))
  2793. (end (or separator (point-max)))
  2794. (suffix-end (if separator (1- end) end))
  2795. (types (org-element-restriction 'citation-reference))
  2796. (reference
  2797. (list 'citation-reference
  2798. (list :key key
  2799. :begin begin
  2800. :end end
  2801. :post-blank 0))))
  2802. (when (< begin key-start)
  2803. (org-element-put-property
  2804. reference :prefix
  2805. (org-element--parse-objects begin key-start nil types reference)))
  2806. (when (< key-end suffix-end)
  2807. (org-element-put-property
  2808. reference :suffix
  2809. (org-element--parse-objects key-end suffix-end nil types reference)))
  2810. reference)))))
  2811. (defun org-element-citation-reference-interpreter (citation-reference _)
  2812. "Interpret CITATION-REFERENCE object as Org syntax."
  2813. (concat (org-element-interpret-data
  2814. (org-element-property :prefix citation-reference))
  2815. "@" (org-element-property :key citation-reference)
  2816. (org-element-interpret-data
  2817. (org-element-property :suffix citation-reference))
  2818. ";"))
  2819. ;;;; Code
  2820. (defun org-element-code-parser ()
  2821. "Parse code object at point, if any.
  2822. When at a code object, return a list whose car is `code' and cdr
  2823. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2824. keywords. Otherwise, return nil.
  2825. Assume point is at the first tilde marker."
  2826. (org-element--parse-generic-emphasis "~" 'code))
  2827. (defun org-element-code-interpreter (code _)
  2828. "Interpret CODE object as Org syntax."
  2829. (format "~%s~" (org-element-property :value code)))
  2830. ;;;; Entity
  2831. (defun org-element-entity-parser ()
  2832. "Parse entity at point, if any.
  2833. When at an entity, return a list whose car is `entity' and cdr
  2834. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2835. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2836. `:post-blank' as keywords. Otherwise, return nil.
  2837. Assume point is at the beginning of the entity."
  2838. (catch 'no-object
  2839. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2840. (save-excursion
  2841. (let* ((value (or (org-entity-get (match-string 1))
  2842. (throw 'no-object nil)))
  2843. (begin (match-beginning 0))
  2844. (bracketsp (string= (match-string 2) "{}"))
  2845. (post-blank (progn (goto-char (match-end 1))
  2846. (when bracketsp (forward-char 2))
  2847. (skip-chars-forward " \t")))
  2848. (end (point)))
  2849. (list 'entity
  2850. (list :name (car value)
  2851. :latex (nth 1 value)
  2852. :latex-math-p (nth 2 value)
  2853. :html (nth 3 value)
  2854. :ascii (nth 4 value)
  2855. :latin1 (nth 5 value)
  2856. :utf-8 (nth 6 value)
  2857. :begin begin
  2858. :end end
  2859. :use-brackets-p bracketsp
  2860. :post-blank post-blank)))))))
  2861. (defun org-element-entity-interpreter (entity _)
  2862. "Interpret ENTITY object as Org syntax."
  2863. (concat "\\"
  2864. (org-element-property :name entity)
  2865. (when (org-element-property :use-brackets-p entity) "{}")))
  2866. ;;;; Export Snippet
  2867. (defun org-element-export-snippet-parser ()
  2868. "Parse export snippet at point.
  2869. When at an export snippet, return a list whose car is
  2870. `export-snippet' and cdr a plist with `:begin', `:end',
  2871. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2872. return nil.
  2873. Assume point is at the beginning of the snippet."
  2874. (save-excursion
  2875. (let (contents-end)
  2876. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2877. (setq contents-end
  2878. (save-match-data (goto-char (match-end 0))
  2879. (when
  2880. (re-search-forward "@@" nil t)
  2881. (match-beginning 0)))))
  2882. (let* ((begin (match-beginning 0))
  2883. (back-end (match-string-no-properties 1))
  2884. (value (buffer-substring-no-properties
  2885. (match-end 0) contents-end))
  2886. (post-blank (skip-chars-forward " \t"))
  2887. (end (point)))
  2888. (list 'export-snippet
  2889. (list :back-end back-end
  2890. :value value
  2891. :begin begin
  2892. :end end
  2893. :post-blank post-blank)))))))
  2894. (defun org-element-export-snippet-interpreter (export-snippet _)
  2895. "Interpret EXPORT-SNIPPET object as Org syntax."
  2896. (format "@@%s:%s@@"
  2897. (org-element-property :back-end export-snippet)
  2898. (org-element-property :value export-snippet)))
  2899. ;;;; Footnote Reference
  2900. (defun org-element-footnote-reference-parser ()
  2901. "Parse footnote reference at point, if any.
  2902. When at a footnote reference, return a list whose car is
  2903. `footnote-reference' and cdr a plist with `:label', `:type',
  2904. `:begin', `:end', `:contents-begin', `:contents-end' and
  2905. `:post-blank' as keywords. Otherwise, return nil."
  2906. (when (looking-at org-footnote-re)
  2907. (let ((closing (with-syntax-table org-element--pair-square-table
  2908. (ignore-errors (scan-lists (point) 1 0)))))
  2909. (when closing
  2910. (save-excursion
  2911. (let* ((begin (point))
  2912. (label (match-string-no-properties 1))
  2913. (inner-begin (match-end 0))
  2914. (inner-end (1- closing))
  2915. (type (if (match-end 2) 'inline 'standard))
  2916. (post-blank (progn (goto-char closing)
  2917. (skip-chars-forward " \t")))
  2918. (end (point)))
  2919. (list 'footnote-reference
  2920. (list :label label
  2921. :type type
  2922. :begin begin
  2923. :end end
  2924. :contents-begin (and (eq type 'inline) inner-begin)
  2925. :contents-end (and (eq type 'inline) inner-end)
  2926. :post-blank post-blank))))))))
  2927. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2928. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2929. CONTENTS is its definition, when inline, or nil."
  2930. (format "[fn:%s%s]"
  2931. (or (org-element-property :label footnote-reference) "")
  2932. (if contents (concat ":" contents) "")))
  2933. ;;;; Inline Babel Call
  2934. (defun org-element-inline-babel-call-parser ()
  2935. "Parse inline babel call at point, if any.
  2936. When at an inline babel call, return a list whose car is
  2937. `inline-babel-call' and cdr a plist with `:call',
  2938. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2939. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2940. Assume point is at the beginning of the babel call."
  2941. (save-excursion
  2942. (catch :no-object
  2943. (when (let ((case-fold-search nil))
  2944. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2945. (goto-char (match-end 1))
  2946. (let* ((begin (match-beginning 0))
  2947. (call (match-string-no-properties 1))
  2948. (inside-header
  2949. (let ((p (org-element--parse-paired-brackets ?\[)))
  2950. (and (org-string-nw-p p)
  2951. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2952. (arguments (org-string-nw-p
  2953. (or (org-element--parse-paired-brackets ?\()
  2954. ;; Parenthesis are mandatory.
  2955. (throw :no-object nil))))
  2956. (end-header
  2957. (let ((p (org-element--parse-paired-brackets ?\[)))
  2958. (and (org-string-nw-p p)
  2959. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2960. (value (buffer-substring-no-properties begin (point)))
  2961. (post-blank (skip-chars-forward " \t"))
  2962. (end (point)))
  2963. (list 'inline-babel-call
  2964. (list :call call
  2965. :inside-header inside-header
  2966. :arguments arguments
  2967. :end-header end-header
  2968. :begin begin
  2969. :end end
  2970. :value value
  2971. :post-blank post-blank)))))))
  2972. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2973. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2974. (concat "call_"
  2975. (org-element-property :call inline-babel-call)
  2976. (let ((h (org-element-property :inside-header inline-babel-call)))
  2977. (and h (format "[%s]" h)))
  2978. "(" (org-element-property :arguments inline-babel-call) ")"
  2979. (let ((h (org-element-property :end-header inline-babel-call)))
  2980. (and h (format "[%s]" h)))))
  2981. ;;;; Inline Src Block
  2982. (defun org-element-inline-src-block-parser ()
  2983. "Parse inline source block at point, if any.
  2984. When at an inline source block, return a list whose car is
  2985. `inline-src-block' and cdr a plist with `:begin', `:end',
  2986. `:language', `:value', `:parameters' and `:post-blank' as
  2987. keywords. Otherwise, return nil.
  2988. Assume point is at the beginning of the inline source block."
  2989. (save-excursion
  2990. (catch :no-object
  2991. (when (let ((case-fold-search nil))
  2992. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2993. (goto-char (match-end 1))
  2994. (let ((begin (match-beginning 0))
  2995. (language (match-string-no-properties 1))
  2996. (parameters
  2997. (let ((p (org-element--parse-paired-brackets ?\[)))
  2998. (and (org-string-nw-p p)
  2999. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  3000. (value (or (org-element--parse-paired-brackets ?\{)
  3001. (throw :no-object nil)))
  3002. (post-blank (skip-chars-forward " \t")))
  3003. (list 'inline-src-block
  3004. (list :language language
  3005. :value value
  3006. :parameters parameters
  3007. :begin begin
  3008. :end (point)
  3009. :post-blank post-blank)))))))
  3010. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  3011. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  3012. (let ((language (org-element-property :language inline-src-block))
  3013. (arguments (org-element-property :parameters inline-src-block))
  3014. (body (org-element-property :value inline-src-block)))
  3015. (format "src_%s%s{%s}"
  3016. language
  3017. (if arguments (format "[%s]" arguments) "")
  3018. body)))
  3019. ;;;; Italic
  3020. (defun org-element-italic-parser ()
  3021. "Parse italic object at point, if any.
  3022. When at an italic object, return a list whose car is `italic' and
  3023. cdr is a plist with `:begin', `:end', `:contents-begin' and
  3024. `:contents-end' and `:post-blank' keywords. Otherwise, return
  3025. nil.
  3026. Assume point is at the first slash marker."
  3027. (org-element--parse-generic-emphasis "/" 'italic))
  3028. (defun org-element-italic-interpreter (_ contents)
  3029. "Interpret italic object as Org syntax.
  3030. CONTENTS is the contents of the object."
  3031. (format "/%s/" contents))
  3032. ;;;; Latex Fragment
  3033. (defun org-element-latex-fragment-parser ()
  3034. "Parse LaTeX fragment at point, if any.
  3035. When at a LaTeX fragment, return a list whose car is
  3036. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  3037. and `:post-blank' as keywords. Otherwise, return nil.
  3038. Assume point is at the beginning of the LaTeX fragment."
  3039. (catch 'no-object
  3040. (save-excursion
  3041. (let* ((begin (point))
  3042. (after-fragment
  3043. (cond
  3044. ((not (eq ?$ (char-after)))
  3045. (pcase (char-after (1+ (point)))
  3046. (?\( (search-forward "\\)" nil t))
  3047. (?\[ (search-forward "\\]" nil t))
  3048. (_
  3049. ;; Macro.
  3050. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  3051. \\|\\({[^{}\n]*}\\)\\)*")
  3052. (match-end 0)))))
  3053. ((eq ?$ (char-after (1+ (point))))
  3054. (search-forward "$$" nil t 2))
  3055. (t
  3056. (and (not (eq ?$ (char-before)))
  3057. (not (memq (char-after (1+ (point)))
  3058. '(?\s ?\t ?\n ?, ?. ?\;)))
  3059. (search-forward "$" nil t 2)
  3060. (not (memq (char-before (match-beginning 0))
  3061. '(?\s ?\t ?\n ?, ?.)))
  3062. (looking-at-p
  3063. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  3064. (point)))))
  3065. (post-blank
  3066. (if (not after-fragment) (throw 'no-object nil)
  3067. (goto-char after-fragment)
  3068. (skip-chars-forward " \t")))
  3069. (end (point)))
  3070. (list 'latex-fragment
  3071. (list :value (buffer-substring-no-properties begin after-fragment)
  3072. :begin begin
  3073. :end end
  3074. :post-blank post-blank))))))
  3075. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  3076. "Interpret LATEX-FRAGMENT object as Org syntax."
  3077. (org-element-property :value latex-fragment))
  3078. ;;;; Line Break
  3079. (defun org-element-line-break-parser ()
  3080. "Parse line break at point, if any.
  3081. When at a line break, return a list whose car is `line-break',
  3082. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  3083. Otherwise, return nil.
  3084. Assume point is at the beginning of the line break."
  3085. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  3086. (not (eq (char-before) ?\\)))
  3087. (list 'line-break
  3088. (list :begin (point)
  3089. :end (line-beginning-position 2)
  3090. :post-blank 0))))
  3091. (defun org-element-line-break-interpreter (&rest _)
  3092. "Interpret LINE-BREAK object as Org syntax."
  3093. "\\\\\n")
  3094. ;;;; Link
  3095. (defun org-element-link-parser ()
  3096. "Parse link at point, if any.
  3097. When at a link, return a list whose car is `link' and cdr a plist
  3098. with `:type', `:path', `:format', `:raw-link', `:application',
  3099. `:search-option', `:begin', `:end', `:contents-begin',
  3100. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  3101. nil.
  3102. Assume point is at the beginning of the link."
  3103. (catch 'no-object
  3104. (let ((begin (point))
  3105. end contents-begin contents-end link-end post-blank path type format
  3106. raw-link search-option application)
  3107. (cond
  3108. ;; Type 1: Text targeted from a radio target.
  3109. ((and org-target-link-regexp
  3110. (save-excursion (or (bolp) (backward-char))
  3111. (looking-at org-target-link-regexp)))
  3112. (setq type "radio")
  3113. (setq format 'plain)
  3114. (setq link-end (match-end 1))
  3115. (setq path (match-string-no-properties 1))
  3116. (setq contents-begin (match-beginning 1))
  3117. (setq contents-end (match-end 1)))
  3118. ;; Type 2: Standard link, i.e. [[https://orgmode.org][website]]
  3119. ((looking-at org-link-bracket-re)
  3120. (setq format 'bracket)
  3121. (setq contents-begin (match-beginning 2))
  3122. (setq contents-end (match-end 2))
  3123. (setq link-end (match-end 0))
  3124. ;; RAW-LINK is the original link. Decode any encoding.
  3125. ;; Expand any abbreviation in it.
  3126. ;;
  3127. ;; Also treat any newline character and associated
  3128. ;; indentation as a single space character. This is not
  3129. ;; compatible with RFC 3986, which requires to ignore
  3130. ;; them altogether. However, doing so would require
  3131. ;; users to encode spaces on the fly when writing links
  3132. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  3133. ;; [[shell:ls *.org]], which defeats Org's focus on
  3134. ;; simplicity.
  3135. (setq raw-link (org-link-expand-abbrev
  3136. (org-link-unescape
  3137. (replace-regexp-in-string
  3138. "[ \t]*\n[ \t]*" " "
  3139. (match-string-no-properties 1)))))
  3140. ;; Determine TYPE of link and set PATH accordingly. According
  3141. ;; to RFC 3986, remove whitespaces from URI in external links.
  3142. ;; In internal ones, treat indentation as a single space.
  3143. (cond
  3144. ;; File type.
  3145. ((or (file-name-absolute-p raw-link)
  3146. (string-match "\\`\\.\\.?/" raw-link))
  3147. (setq type "file")
  3148. (setq path raw-link))
  3149. ;; Explicit type (http, irc, bbdb...).
  3150. ((string-match org-link-types-re raw-link)
  3151. (setq type (match-string 1 raw-link))
  3152. (setq path (substring raw-link (match-end 0))))
  3153. ;; Code-ref type: PATH is the name of the reference.
  3154. ((and (string-match-p "\\`(" raw-link)
  3155. (string-match-p ")\\'" raw-link))
  3156. (setq type "coderef")
  3157. (setq path (substring raw-link 1 -1)))
  3158. ;; Custom-id type: PATH is the name of the custom id.
  3159. ((= (string-to-char raw-link) ?#)
  3160. (setq type "custom-id")
  3161. (setq path (substring raw-link 1)))
  3162. ;; Fuzzy type: Internal link either matches a target, an
  3163. ;; headline name or nothing. PATH is the target or
  3164. ;; headline's name.
  3165. (t
  3166. (setq type "fuzzy")
  3167. (setq path raw-link))))
  3168. ;; Type 3: Plain link, e.g., https://orgmode.org
  3169. ((looking-at org-link-plain-re)
  3170. (setq format 'plain)
  3171. (setq raw-link (match-string-no-properties 0))
  3172. (setq type (match-string-no-properties 1))
  3173. (setq link-end (match-end 0))
  3174. (setq path (match-string-no-properties 2)))
  3175. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  3176. ;; bracket links, follow RFC 3986 and remove any extra
  3177. ;; whitespace in URI.
  3178. ((looking-at org-link-angle-re)
  3179. (setq format 'angle)
  3180. (setq type (match-string-no-properties 1))
  3181. (setq link-end (match-end 0))
  3182. (setq raw-link
  3183. (buffer-substring-no-properties
  3184. (match-beginning 1) (match-end 2)))
  3185. (setq path (replace-regexp-in-string
  3186. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  3187. (t (throw 'no-object nil)))
  3188. ;; In any case, deduce end point after trailing white space from
  3189. ;; LINK-END variable.
  3190. (save-excursion
  3191. (setq post-blank
  3192. (progn (goto-char link-end) (skip-chars-forward " \t")))
  3193. (setq end (point)))
  3194. ;; Special "file"-type link processing. Extract opening
  3195. ;; application and search option, if any. Also normalize URI.
  3196. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  3197. (setq application (match-string 1 type))
  3198. (setq type "file")
  3199. (when (string-match "::\\(.*\\)\\'" path)
  3200. (setq search-option (match-string 1 path))
  3201. (setq path (replace-match "" nil nil path)))
  3202. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3203. ;; Translate link, if `org-link-translation-function' is set.
  3204. (let ((trans (and (functionp org-link-translation-function)
  3205. (funcall org-link-translation-function type path))))
  3206. (when trans
  3207. (setq type (car trans))
  3208. (setq path (cdr trans))))
  3209. (list 'link
  3210. (list :type type
  3211. :path path
  3212. :format format
  3213. :raw-link (or raw-link path)
  3214. :application application
  3215. :search-option search-option
  3216. :begin begin
  3217. :end end
  3218. :contents-begin contents-begin
  3219. :contents-end contents-end
  3220. :post-blank post-blank)))))
  3221. (defun org-element-link-interpreter (link contents)
  3222. "Interpret LINK object as Org syntax.
  3223. CONTENTS is the contents of the object, or nil."
  3224. (let ((type (org-element-property :type link))
  3225. (path (org-element-property :path link)))
  3226. (if (string= type "radio") path
  3227. (let ((fmt (pcase (org-element-property :format link)
  3228. ;; Links with contents and internal links have to
  3229. ;; use bracket syntax. Ignore `:format' in these
  3230. ;; cases. This is also the default syntax when the
  3231. ;; property is not defined, e.g., when the object
  3232. ;; was crafted by the user.
  3233. ((guard contents)
  3234. (format "[[%%s][%s]]"
  3235. ;; Since this is going to be used as
  3236. ;; a format string, escape percent signs
  3237. ;; in description.
  3238. (replace-regexp-in-string "%" "%%" contents)))
  3239. ((or `bracket
  3240. `nil
  3241. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3242. "[[%s]]")
  3243. ;; Otherwise, just obey to `:format'.
  3244. (`angle "<%s>")
  3245. (`plain "%s")
  3246. (f (error "Wrong `:format' value: %s" f)))))
  3247. (format fmt
  3248. (pcase type
  3249. ("coderef" (format "(%s)" path))
  3250. ("custom-id" (concat "#" path))
  3251. ("file"
  3252. (let ((app (org-element-property :application link))
  3253. (opt (org-element-property :search-option link)))
  3254. (concat type (and app (concat "+" app)) ":"
  3255. path
  3256. (and opt (concat "::" opt)))))
  3257. ("fuzzy" path)
  3258. (_ (concat type ":" path))))))))
  3259. ;;;; Macro
  3260. (defun org-element-macro-parser ()
  3261. "Parse macro at point, if any.
  3262. When at a macro, return a list whose car is `macro' and cdr
  3263. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3264. `:post-blank' as keywords. Otherwise, return nil.
  3265. Assume point is at the macro."
  3266. (save-excursion
  3267. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3268. (let ((begin (point))
  3269. (key (downcase (match-string-no-properties 1)))
  3270. (value (match-string-no-properties 0))
  3271. (post-blank (progn (goto-char (match-end 0))
  3272. (skip-chars-forward " \t")))
  3273. (end (point))
  3274. (args (pcase (match-string-no-properties 3)
  3275. (`nil nil)
  3276. (a (org-macro-extract-arguments
  3277. (replace-regexp-in-string
  3278. "[ \t\r\n]+" " " (org-trim a)))))))
  3279. (list 'macro
  3280. (list :key key
  3281. :value value
  3282. :args args
  3283. :begin begin
  3284. :end end
  3285. :post-blank post-blank))))))
  3286. (defun org-element-macro-interpreter (macro _)
  3287. "Interpret MACRO object as Org syntax."
  3288. (format "{{{%s%s}}}"
  3289. (org-element-property :key macro)
  3290. (pcase (org-element-property :args macro)
  3291. (`nil "")
  3292. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3293. ;;;; Radio-target
  3294. (defun org-element-radio-target-parser ()
  3295. "Parse radio target at point, if any.
  3296. When at a radio target, return a list whose car is `radio-target'
  3297. and cdr a plist with `:begin', `:end', `:contents-begin',
  3298. `:contents-end', `:value' and `:post-blank' as keywords.
  3299. Otherwise, return nil.
  3300. Assume point is at the radio target."
  3301. (save-excursion
  3302. (when (looking-at org-radio-target-regexp)
  3303. (let ((begin (point))
  3304. (contents-begin (match-beginning 1))
  3305. (contents-end (match-end 1))
  3306. (value (match-string-no-properties 1))
  3307. (post-blank (progn (goto-char (match-end 0))
  3308. (skip-chars-forward " \t")))
  3309. (end (point)))
  3310. (list 'radio-target
  3311. (list :begin begin
  3312. :end end
  3313. :contents-begin contents-begin
  3314. :contents-end contents-end
  3315. :post-blank post-blank
  3316. :value value))))))
  3317. (defun org-element-radio-target-interpreter (_ contents)
  3318. "Interpret target object as Org syntax.
  3319. CONTENTS is the contents of the object."
  3320. (concat "<<<" contents ">>>"))
  3321. ;;;; Statistics Cookie
  3322. (defun org-element-statistics-cookie-parser ()
  3323. "Parse statistics cookie at point, if any.
  3324. When at a statistics cookie, return a list whose car is
  3325. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3326. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3327. Assume point is at the beginning of the statistics-cookie."
  3328. (save-excursion
  3329. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3330. (let* ((begin (point))
  3331. (value (buffer-substring-no-properties
  3332. (match-beginning 0) (match-end 0)))
  3333. (post-blank (progn (goto-char (match-end 0))
  3334. (skip-chars-forward " \t")))
  3335. (end (point)))
  3336. (list 'statistics-cookie
  3337. (list :begin begin
  3338. :end end
  3339. :value value
  3340. :post-blank post-blank))))))
  3341. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3342. "Interpret STATISTICS-COOKIE object as Org syntax."
  3343. (org-element-property :value statistics-cookie))
  3344. ;;;; Strike-Through
  3345. (defun org-element-strike-through-parser ()
  3346. "Parse strike-through object at point, if any.
  3347. When at a strike-through object, return a list whose car is
  3348. `strike-through' and cdr is a plist with `:begin', `:end',
  3349. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3350. Otherwise, return nil.
  3351. Assume point is at the first plus sign marker."
  3352. (org-element--parse-generic-emphasis "+" 'strike-through))
  3353. (defun org-element-strike-through-interpreter (_ contents)
  3354. "Interpret strike-through object as Org syntax.
  3355. CONTENTS is the contents of the object."
  3356. (format "+%s+" contents))
  3357. ;;;; Subscript
  3358. (defun org-element-subscript-parser ()
  3359. "Parse subscript at point, if any.
  3360. When at a subscript object, return a list whose car is
  3361. `subscript' and cdr a plist with `:begin', `:end',
  3362. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3363. `:post-blank' as keywords. Otherwise, return nil.
  3364. Assume point is at the underscore."
  3365. (save-excursion
  3366. (unless (bolp) (backward-char))
  3367. (when (looking-at org-match-substring-regexp)
  3368. (let ((bracketsp (match-beginning 4))
  3369. (begin (match-beginning 2))
  3370. (contents-begin (or (match-beginning 4)
  3371. (match-beginning 3)))
  3372. (contents-end (or (match-end 4) (match-end 3)))
  3373. (post-blank (progn (goto-char (match-end 0))
  3374. (skip-chars-forward " \t")))
  3375. (end (point)))
  3376. (list 'subscript
  3377. (list :begin begin
  3378. :end end
  3379. :use-brackets-p bracketsp
  3380. :contents-begin contents-begin
  3381. :contents-end contents-end
  3382. :post-blank post-blank))))))
  3383. (defun org-element-subscript-interpreter (subscript contents)
  3384. "Interpret SUBSCRIPT object as Org syntax.
  3385. CONTENTS is the contents of the object."
  3386. (format
  3387. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3388. contents))
  3389. ;;;; Superscript
  3390. (defun org-element-superscript-parser ()
  3391. "Parse superscript at point, if any.
  3392. When at a superscript object, return a list whose car is
  3393. `superscript' and cdr a plist with `:begin', `:end',
  3394. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3395. `:post-blank' as keywords. Otherwise, return nil.
  3396. Assume point is at the caret."
  3397. (save-excursion
  3398. (unless (bolp) (backward-char))
  3399. (when (looking-at org-match-substring-regexp)
  3400. (let ((bracketsp (match-beginning 4))
  3401. (begin (match-beginning 2))
  3402. (contents-begin (or (match-beginning 4)
  3403. (match-beginning 3)))
  3404. (contents-end (or (match-end 4) (match-end 3)))
  3405. (post-blank (progn (goto-char (match-end 0))
  3406. (skip-chars-forward " \t")))
  3407. (end (point)))
  3408. (list 'superscript
  3409. (list :begin begin
  3410. :end end
  3411. :use-brackets-p bracketsp
  3412. :contents-begin contents-begin
  3413. :contents-end contents-end
  3414. :post-blank post-blank))))))
  3415. (defun org-element-superscript-interpreter (superscript contents)
  3416. "Interpret SUPERSCRIPT object as Org syntax.
  3417. CONTENTS is the contents of the object."
  3418. (format
  3419. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3420. contents))
  3421. ;;;; Table Cell
  3422. (defun org-element-table-cell-parser ()
  3423. "Parse table cell at point.
  3424. Return a list whose car is `table-cell' and cdr is a plist
  3425. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3426. and `:post-blank' keywords."
  3427. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3428. (let* ((begin (match-beginning 0))
  3429. (end (match-end 0))
  3430. (contents-begin (match-beginning 1))
  3431. (contents-end (match-end 1)))
  3432. (list 'table-cell
  3433. (list :begin begin
  3434. :end end
  3435. :contents-begin contents-begin
  3436. :contents-end contents-end
  3437. :post-blank 0))))
  3438. (defun org-element-table-cell-interpreter (_ contents)
  3439. "Interpret table-cell element as Org syntax.
  3440. CONTENTS is the contents of the cell, or nil."
  3441. (concat " " contents " |"))
  3442. ;;;; Target
  3443. (defun org-element-target-parser ()
  3444. "Parse target at point, if any.
  3445. When at a target, return a list whose car is `target' and cdr
  3446. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3447. keywords. Otherwise, return nil.
  3448. Assume point is at the target."
  3449. (save-excursion
  3450. (when (looking-at org-target-regexp)
  3451. (let ((begin (point))
  3452. (value (match-string-no-properties 1))
  3453. (post-blank (progn (goto-char (match-end 0))
  3454. (skip-chars-forward " \t")))
  3455. (end (point)))
  3456. (list 'target
  3457. (list :begin begin
  3458. :end end
  3459. :value value
  3460. :post-blank post-blank))))))
  3461. (defun org-element-target-interpreter (target _)
  3462. "Interpret TARGET object as Org syntax."
  3463. (format "<<%s>>" (org-element-property :value target)))
  3464. ;;;; Timestamp
  3465. (defconst org-element--timestamp-regexp
  3466. (concat org-ts-regexp-both
  3467. "\\|"
  3468. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3469. "\\|"
  3470. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3471. "Regexp matching any timestamp type object.")
  3472. (defun org-element-timestamp-parser ()
  3473. "Parse time stamp at point, if any.
  3474. When at a time stamp, return a list whose car is `timestamp', and
  3475. cdr a plist with `:type', `:raw-value', `:year-start',
  3476. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3477. `:year-end', `:month-end', `:day-end', `:hour-end',
  3478. `:minute-end', `:repeater-type', `:repeater-value',
  3479. `:repeater-unit', `:warning-type', `:warning-value',
  3480. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3481. Otherwise, return nil.
  3482. Assume point is at the beginning of the timestamp."
  3483. (when (looking-at-p org-element--timestamp-regexp)
  3484. (save-excursion
  3485. (let* ((begin (point))
  3486. (activep (eq (char-after) ?<))
  3487. (raw-value
  3488. (progn
  3489. (looking-at (concat "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\("
  3490. org-ts-regexp-both
  3491. "\\)\\)?"))
  3492. (match-string-no-properties 0)))
  3493. (date-start (match-string-no-properties 1))
  3494. (date-end (match-string 3))
  3495. (diaryp (match-beginning 2))
  3496. (post-blank (progn (goto-char (match-end 0))
  3497. (skip-chars-forward " \t")))
  3498. (end (point))
  3499. (time-range
  3500. (and (not diaryp)
  3501. (string-match
  3502. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3503. date-start)
  3504. (cons (string-to-number (match-string 2 date-start))
  3505. (string-to-number (match-string 3 date-start)))))
  3506. (type (cond (diaryp 'diary)
  3507. ((and activep (or date-end time-range)) 'active-range)
  3508. (activep 'active)
  3509. ((or date-end time-range) 'inactive-range)
  3510. (t 'inactive)))
  3511. (repeater-props
  3512. (and (not diaryp)
  3513. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3514. raw-value)
  3515. (list
  3516. :repeater-type
  3517. (let ((type (match-string 1 raw-value)))
  3518. (cond ((equal "++" type) 'catch-up)
  3519. ((equal ".+" type) 'restart)
  3520. (t 'cumulate)))
  3521. :repeater-value (string-to-number (match-string 2 raw-value))
  3522. :repeater-unit
  3523. (pcase (string-to-char (match-string 3 raw-value))
  3524. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3525. (warning-props
  3526. (and (not diaryp)
  3527. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3528. (list
  3529. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3530. :warning-value (string-to-number (match-string 2 raw-value))
  3531. :warning-unit
  3532. (pcase (string-to-char (match-string 3 raw-value))
  3533. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3534. year-start month-start day-start hour-start minute-start year-end
  3535. month-end day-end hour-end minute-end)
  3536. ;; Parse date-start.
  3537. (unless diaryp
  3538. (let ((date (org-parse-time-string date-start t)))
  3539. (setq year-start (nth 5 date)
  3540. month-start (nth 4 date)
  3541. day-start (nth 3 date)
  3542. hour-start (nth 2 date)
  3543. minute-start (nth 1 date))))
  3544. ;; Compute date-end. It can be provided directly in time-stamp,
  3545. ;; or extracted from time range. Otherwise, it defaults to the
  3546. ;; same values as date-start.
  3547. (unless diaryp
  3548. (let ((date (and date-end (org-parse-time-string date-end t))))
  3549. (setq year-end (or (nth 5 date) year-start)
  3550. month-end (or (nth 4 date) month-start)
  3551. day-end (or (nth 3 date) day-start)
  3552. hour-end (or (nth 2 date) (car time-range) hour-start)
  3553. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3554. (list 'timestamp
  3555. (nconc (list :type type
  3556. :raw-value raw-value
  3557. :year-start year-start
  3558. :month-start month-start
  3559. :day-start day-start
  3560. :hour-start hour-start
  3561. :minute-start minute-start
  3562. :year-end year-end
  3563. :month-end month-end
  3564. :day-end day-end
  3565. :hour-end hour-end
  3566. :minute-end minute-end
  3567. :begin begin
  3568. :end end
  3569. :post-blank post-blank)
  3570. repeater-props
  3571. warning-props))))))
  3572. (defun org-element-timestamp-interpreter (timestamp _)
  3573. "Interpret TIMESTAMP object as Org syntax."
  3574. (let* ((repeat-string
  3575. (concat
  3576. (pcase (org-element-property :repeater-type timestamp)
  3577. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3578. (let ((val (org-element-property :repeater-value timestamp)))
  3579. (and val (number-to-string val)))
  3580. (pcase (org-element-property :repeater-unit timestamp)
  3581. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3582. (warning-string
  3583. (concat
  3584. (pcase (org-element-property :warning-type timestamp)
  3585. (`first "--") (`all "-"))
  3586. (let ((val (org-element-property :warning-value timestamp)))
  3587. (and val (number-to-string val)))
  3588. (pcase (org-element-property :warning-unit timestamp)
  3589. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3590. (build-ts-string
  3591. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3592. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3593. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3594. ;; specify a time range in the timestamp. REPEAT-STRING is
  3595. ;; the repeater string, if any.
  3596. (lambda (time activep &optional with-time-p hour-end minute-end)
  3597. (let ((ts (format-time-string
  3598. (funcall (if with-time-p #'cdr #'car)
  3599. org-time-stamp-formats)
  3600. time)))
  3601. (when (and hour-end minute-end)
  3602. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3603. (setq ts
  3604. (replace-match
  3605. (format "\\&-%02d:%02d" hour-end minute-end)
  3606. nil nil ts)))
  3607. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3608. (dolist (s (list repeat-string warning-string))
  3609. (when (org-string-nw-p s)
  3610. (setq ts (concat (substring ts 0 -1)
  3611. " "
  3612. s
  3613. (substring ts -1)))))
  3614. ;; Return value.
  3615. ts)))
  3616. (type (org-element-property :type timestamp)))
  3617. (pcase type
  3618. ((or `active `inactive)
  3619. (let* ((minute-start (org-element-property :minute-start timestamp))
  3620. (minute-end (org-element-property :minute-end timestamp))
  3621. (hour-start (org-element-property :hour-start timestamp))
  3622. (hour-end (org-element-property :hour-end timestamp))
  3623. (time-range-p (and hour-start hour-end minute-start minute-end
  3624. (or (/= hour-start hour-end)
  3625. (/= minute-start minute-end)))))
  3626. (funcall
  3627. build-ts-string
  3628. (org-encode-time 0
  3629. (or minute-start 0)
  3630. (or hour-start 0)
  3631. (org-element-property :day-start timestamp)
  3632. (org-element-property :month-start timestamp)
  3633. (org-element-property :year-start timestamp))
  3634. (eq type 'active)
  3635. (and hour-start minute-start)
  3636. (and time-range-p hour-end)
  3637. (and time-range-p minute-end))))
  3638. ((or `active-range `inactive-range)
  3639. (let ((minute-start (org-element-property :minute-start timestamp))
  3640. (minute-end (org-element-property :minute-end timestamp))
  3641. (hour-start (org-element-property :hour-start timestamp))
  3642. (hour-end (org-element-property :hour-end timestamp)))
  3643. (concat
  3644. (funcall
  3645. build-ts-string (org-encode-time
  3646. 0
  3647. (or minute-start 0)
  3648. (or hour-start 0)
  3649. (org-element-property :day-start timestamp)
  3650. (org-element-property :month-start timestamp)
  3651. (org-element-property :year-start timestamp))
  3652. (eq type 'active-range)
  3653. (and hour-start minute-start))
  3654. "--"
  3655. (funcall build-ts-string
  3656. (org-encode-time
  3657. 0
  3658. (or minute-end 0)
  3659. (or hour-end 0)
  3660. (org-element-property :day-end timestamp)
  3661. (org-element-property :month-end timestamp)
  3662. (org-element-property :year-end timestamp))
  3663. (eq type 'active-range)
  3664. (and hour-end minute-end)))))
  3665. (_ (org-element-property :raw-value timestamp)))))
  3666. ;;;; Underline
  3667. (defun org-element-underline-parser ()
  3668. "Parse underline object at point, if any.
  3669. When at an underline object, return a list whose car is
  3670. `underline' and cdr is a plist with `:begin', `:end',
  3671. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3672. Otherwise, return nil.
  3673. Assume point is at the first underscore marker."
  3674. (org-element--parse-generic-emphasis "_" 'underline))
  3675. (defun org-element-underline-interpreter (_ contents)
  3676. "Interpret underline object as Org syntax.
  3677. CONTENTS is the contents of the object."
  3678. (format "_%s_" contents))
  3679. ;;;; Verbatim
  3680. (defun org-element-verbatim-parser ()
  3681. "Parse verbatim object at point, if any.
  3682. When at a verbatim object, return a list whose car is `verbatim'
  3683. and cdr is a plist with `:value', `:begin', `:end' and
  3684. `:post-blank' keywords. Otherwise, return nil.
  3685. Assume point is at the first equal sign marker."
  3686. (org-element--parse-generic-emphasis "=" 'verbatim))
  3687. (defun org-element-verbatim-interpreter (verbatim _)
  3688. "Interpret VERBATIM object as Org syntax."
  3689. (format "=%s=" (org-element-property :value verbatim)))
  3690. ;;; Parsing Element Starting At Point
  3691. ;;
  3692. ;; `org-element--current-element' is the core function of this section.
  3693. ;; It returns the Lisp representation of the element starting at
  3694. ;; point.
  3695. (defvar org-element--cache-sync-requests); Declared later
  3696. (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
  3697. "Parse the element starting at point.
  3698. Return value is a list like (TYPE PROPS) where TYPE is the type
  3699. of the element and PROPS a plist of properties associated to the
  3700. element.
  3701. Possible types are defined in `org-element-all-elements'.
  3702. LIMIT bounds the search.
  3703. Optional argument GRANULARITY determines the depth of the
  3704. recursion. Allowed values are `headline', `greater-element',
  3705. `element', `object' or nil. When it is broader than `object' (or
  3706. nil), secondary values will not be parsed, since they only
  3707. contain objects.
  3708. Optional argument MODE, when non-nil, can be either
  3709. `first-section', `item', `node-property', `planning',
  3710. `property-drawer', `section', `table-row', or `top-comment'.
  3711. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3712. computed.
  3713. Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
  3714. will also add current element to cache if it is not yet there. Use
  3715. this argument with care, as validity of the element in parse tree is
  3716. not checked.
  3717. This function assumes point is always at the beginning of the
  3718. element it has to parse."
  3719. (let* ((element (and (not (buffer-narrowed-p))
  3720. (org-element--cache-active-p)
  3721. (not org-element--cache-sync-requests)
  3722. (org-element--cache-find (point) t)))
  3723. (element (progn (while (and element
  3724. (not (and (eq (point) (org-element-property :begin element))
  3725. (eq mode (org-element-property :mode element)))))
  3726. (setq element (org-element-property :parent element)))
  3727. element))
  3728. (old-element element)
  3729. (element (when
  3730. (pcase (org-element-property :granularity element)
  3731. (`nil t)
  3732. (`object t)
  3733. (`element (not (memq granularity '(nil object))))
  3734. (`greater-element (not (memq granularity '(nil object element))))
  3735. (`headline (eq granularity 'headline)))
  3736. element)))
  3737. (if element
  3738. element
  3739. (save-excursion
  3740. (let ((case-fold-search t)
  3741. ;; Determine if parsing depth allows for secondary strings
  3742. ;; parsing. It only applies to elements referenced in
  3743. ;; `org-element-secondary-value-alist'.
  3744. (raw-secondary-p (and granularity (not (eq granularity 'object))))
  3745. result)
  3746. (setq
  3747. result
  3748. (cond
  3749. ;; Item.
  3750. ((eq mode 'item)
  3751. (org-element-item-parser limit structure raw-secondary-p))
  3752. ;; Table Row.
  3753. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3754. ;; Node Property.
  3755. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3756. ;; Headline.
  3757. ((org-with-limited-levels (looking-at-p org-outline-regexp-bol))
  3758. (org-element-headline-parser limit raw-secondary-p))
  3759. ;; Sections (must be checked after headline).
  3760. ((eq mode 'section) (org-element-section-parser limit))
  3761. ((eq mode 'first-section)
  3762. (org-element-section-parser
  3763. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3764. limit)))
  3765. ;; Comments.
  3766. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3767. (org-element-comment-parser limit))
  3768. ;; Planning.
  3769. ((and (eq mode 'planning)
  3770. (eq ?* (char-after (line-beginning-position 0)))
  3771. (looking-at org-element-planning-line-re))
  3772. (org-element-planning-parser limit))
  3773. ;; Property drawer.
  3774. ((and (pcase mode
  3775. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3776. ((or `property-drawer `top-comment)
  3777. (save-excursion
  3778. (beginning-of-line 0)
  3779. (not (looking-at "[[:blank:]]*$"))))
  3780. (_ nil))
  3781. (looking-at org-property-drawer-re))
  3782. (org-element-property-drawer-parser limit))
  3783. ;; When not at bol, point is at the beginning of an item or
  3784. ;; a footnote definition: next item is always a paragraph.
  3785. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3786. ;; Clock.
  3787. ((looking-at org-element-clock-line-re)
  3788. (org-element-clock-parser limit))
  3789. ;; Inlinetask.
  3790. ((looking-at "^\\*+ ")
  3791. (org-element-inlinetask-parser limit raw-secondary-p))
  3792. ;; From there, elements can have affiliated keywords.
  3793. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3794. limit (memq granularity '(nil object)))))
  3795. (cond
  3796. ;; Jumping over affiliated keywords put point off-limits.
  3797. ;; Parse them as regular keywords.
  3798. ((and (cdr affiliated) (>= (point) limit))
  3799. (goto-char (car affiliated))
  3800. (org-element-keyword-parser limit nil))
  3801. ;; LaTeX Environment.
  3802. ((looking-at org-element--latex-begin-environment)
  3803. (org-element-latex-environment-parser limit affiliated))
  3804. ;; Drawer.
  3805. ((looking-at org-element-drawer-re)
  3806. (org-element-drawer-parser limit affiliated))
  3807. ;; Fixed Width
  3808. ((looking-at "[ \t]*:\\( \\|$\\)")
  3809. (org-element-fixed-width-parser limit affiliated))
  3810. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3811. ;; Keywords.
  3812. ((looking-at "[ \t]*#\\+")
  3813. (goto-char (match-end 0))
  3814. (cond
  3815. ((looking-at "BEGIN_\\(\\S-+\\)")
  3816. (beginning-of-line)
  3817. (funcall (pcase (upcase (match-string 1))
  3818. ("CENTER" #'org-element-center-block-parser)
  3819. ("COMMENT" #'org-element-comment-block-parser)
  3820. ("EXAMPLE" #'org-element-example-block-parser)
  3821. ("EXPORT" #'org-element-export-block-parser)
  3822. ("QUOTE" #'org-element-quote-block-parser)
  3823. ("SRC" #'org-element-src-block-parser)
  3824. ("VERSE" #'org-element-verse-block-parser)
  3825. (_ #'org-element-special-block-parser))
  3826. limit
  3827. affiliated))
  3828. ((looking-at "CALL:")
  3829. (beginning-of-line)
  3830. (org-element-babel-call-parser limit affiliated))
  3831. ((save-excursion
  3832. (beginning-of-line)
  3833. (looking-at org-element-dynamic-block-open-re))
  3834. (beginning-of-line)
  3835. (org-element-dynamic-block-parser limit affiliated))
  3836. ((looking-at "\\S-+:")
  3837. (beginning-of-line)
  3838. (org-element-keyword-parser limit affiliated))
  3839. (t
  3840. (beginning-of-line)
  3841. (org-element-paragraph-parser limit affiliated))))
  3842. ;; Footnote Definition.
  3843. ((looking-at org-footnote-definition-re)
  3844. (org-element-footnote-definition-parser limit affiliated))
  3845. ;; Horizontal Rule.
  3846. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3847. (org-element-horizontal-rule-parser limit affiliated))
  3848. ;; Diary Sexp.
  3849. ((looking-at "%%(")
  3850. (org-element-diary-sexp-parser limit affiliated))
  3851. ;; Table.
  3852. ((or (looking-at "[ \t]*|")
  3853. ;; There is no strict definition of a table.el
  3854. ;; table. Try to prevent false positive while being
  3855. ;; quick.
  3856. (let ((rule-regexp
  3857. (rx (zero-or-more (any " \t"))
  3858. "+"
  3859. (one-or-more (one-or-more "-") "+")
  3860. (zero-or-more (any " \t"))
  3861. eol))
  3862. (non-table.el-line
  3863. (rx bol
  3864. (zero-or-more (any " \t"))
  3865. (or eol (not (any "+| \t")))))
  3866. (next (line-beginning-position 2)))
  3867. ;; Start with a full rule.
  3868. (and
  3869. (looking-at rule-regexp)
  3870. (< next limit) ;no room for a table.el table
  3871. (save-excursion
  3872. (end-of-line)
  3873. (cond
  3874. ;; Must end with a full rule.
  3875. ((not (re-search-forward non-table.el-line limit 'move))
  3876. (if (bolp) (forward-line -1) (beginning-of-line))
  3877. (looking-at rule-regexp))
  3878. ;; Ignore pseudo-tables with a single
  3879. ;; rule.
  3880. ((= next (line-beginning-position))
  3881. nil)
  3882. ;; Must end with a full rule.
  3883. (t
  3884. (forward-line -1)
  3885. (looking-at rule-regexp)))))))
  3886. (org-element-table-parser limit affiliated))
  3887. ;; List.
  3888. ((looking-at (org-item-re))
  3889. (org-element-plain-list-parser
  3890. limit affiliated
  3891. (or structure (org-element--list-struct limit))))
  3892. ;; Default element: Paragraph.
  3893. (t (org-element-paragraph-parser limit affiliated)))))))
  3894. (when result
  3895. (org-element-put-property result :mode mode)
  3896. (org-element-put-property result :granularity granularity))
  3897. (when (and (not (buffer-narrowed-p))
  3898. (org-element--cache-active-p)
  3899. (not org-element--cache-sync-requests)
  3900. add-to-cache)
  3901. (if (not old-element)
  3902. (setq result (org-element--cache-put result))
  3903. (org-element-set-element old-element result)
  3904. (setq result old-element)))
  3905. result)))))
  3906. ;; Most elements can have affiliated keywords. When looking for an
  3907. ;; element beginning, we want to move before them, as they belong to
  3908. ;; that element, and, in the meantime, collect information they give
  3909. ;; into appropriate properties. Hence the following function.
  3910. (defun org-element--collect-affiliated-keywords (limit parse)
  3911. "Collect affiliated keywords from point down to LIMIT.
  3912. Return a list whose CAR is the position at the first of them and
  3913. CDR a plist of keywords and values and move point to the
  3914. beginning of the first line after them.
  3915. As a special case, if element doesn't start at the beginning of
  3916. the line (e.g., a paragraph starting an item), CAR is current
  3917. position of point and CDR is nil.
  3918. When PARSE is non-nil, values from keywords belonging to
  3919. `org-element-parsed-keywords' are parsed as secondary strings."
  3920. (if (not (bolp)) (list (point))
  3921. (let ((case-fold-search t)
  3922. (origin (point))
  3923. ;; RESTRICT is the list of objects allowed in parsed
  3924. ;; keywords value. If PARSE is nil, no object is allowed.
  3925. (restrict (and parse (org-element-restriction 'keyword)))
  3926. output)
  3927. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3928. (let* ((raw-kwd (upcase (match-string 1)))
  3929. ;; Apply translation to RAW-KWD. From there, KWD is
  3930. ;; the official keyword.
  3931. (kwd (or (cdr (assoc raw-kwd
  3932. org-element-keyword-translation-alist))
  3933. raw-kwd))
  3934. ;; PARSED? is non-nil when keyword should have its
  3935. ;; value parsed.
  3936. (parsed? (member kwd org-element-parsed-keywords))
  3937. ;; Find main value for any keyword.
  3938. (value
  3939. (let ((beg (match-end 0))
  3940. (end (save-excursion
  3941. (end-of-line)
  3942. (skip-chars-backward " \t")
  3943. (point))))
  3944. (if parsed?
  3945. (save-match-data
  3946. (org-element--parse-objects beg end nil restrict))
  3947. (org-trim (buffer-substring-no-properties beg end)))))
  3948. ;; If KWD is a dual keyword, find its secondary value.
  3949. ;; Maybe parse it.
  3950. (dual? (member kwd org-element-dual-keywords))
  3951. (dual-value
  3952. (and dual?
  3953. (let ((sec (match-string-no-properties 2)))
  3954. (cond
  3955. ((and sec parsed?)
  3956. (save-match-data
  3957. (org-element--parse-objects
  3958. (match-beginning 2) (match-end 2) nil restrict)))
  3959. (sec sec)))))
  3960. ;; Attribute a property name to KWD.
  3961. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3962. ;; Now set final shape for VALUE.
  3963. (when dual?
  3964. (setq value (and (or value dual-value) (cons value dual-value))))
  3965. (when (or (member kwd org-element-multiple-keywords)
  3966. ;; Attributes can always appear on multiple lines.
  3967. (string-match "^ATTR_" kwd))
  3968. (setq value (cons value (plist-get output kwd-sym))))
  3969. ;; Eventually store the new value in OUTPUT.
  3970. (setq output (plist-put output kwd-sym value))
  3971. ;; Move to next keyword.
  3972. (forward-line)))
  3973. ;; If affiliated keywords are orphaned: move back to first one.
  3974. ;; They will be parsed as a paragraph.
  3975. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3976. ;; Return value.
  3977. (cons origin output))))
  3978. ;;; The Org Parser
  3979. ;;
  3980. ;; The two major functions here are `org-element-parse-buffer', which
  3981. ;; parses Org syntax inside the current buffer, taking into account
  3982. ;; region, narrowing, or even visibility if specified, and
  3983. ;; `org-element-parse-secondary-string', which parses objects within
  3984. ;; a given string.
  3985. ;;
  3986. ;; The (almost) almighty `org-element-map' allows applying a function
  3987. ;; on elements or objects matching some type, and accumulating the
  3988. ;; resulting values. In an export situation, it also skips unneeded
  3989. ;; parts of the parse tree.
  3990. (defun org-element-parse-buffer (&optional granularity visible-only)
  3991. "Recursively parse the buffer and return structure.
  3992. If narrowing is in effect, only parse the visible part of the
  3993. buffer.
  3994. Optional argument GRANULARITY determines the depth of the
  3995. recursion. It can be set to the following symbols:
  3996. `headline' Only parse headlines.
  3997. `greater-element' Don't recurse into greater elements except
  3998. headlines and sections. Thus, elements
  3999. parsed are the top-level ones.
  4000. `element' Parse everything but objects and plain text.
  4001. `object' Parse the complete buffer (default).
  4002. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4003. elements.
  4004. An element or object is represented as a list with the
  4005. pattern (TYPE PROPERTIES CONTENTS), where :
  4006. TYPE is a symbol describing the element or object. See
  4007. `org-element-all-elements' and `org-element-all-objects' for an
  4008. exhaustive list of such symbols. One can retrieve it with
  4009. `org-element-type' function.
  4010. PROPERTIES is the list of attributes attached to the element or
  4011. object, as a plist. Although most of them are specific to the
  4012. element or object type, all types share `:begin', `:end',
  4013. `:post-blank' and `:parent' properties, which respectively
  4014. refer to buffer position where the element or object starts,
  4015. ends, the number of white spaces or blank lines after it, and
  4016. the element or object containing it. Properties values can be
  4017. obtained by using `org-element-property' function.
  4018. CONTENTS is a list of elements, objects or raw strings
  4019. contained in the current element or object, when applicable.
  4020. One can access them with `org-element-contents' function.
  4021. The Org buffer has `org-data' as type and nil as properties.
  4022. `org-element-map' function can be used to find specific elements
  4023. or objects within the parse tree.
  4024. This function assumes that current major mode is `org-mode'."
  4025. (save-excursion
  4026. (goto-char (point-min))
  4027. (let ((org-data (org-element-org-data-parser))
  4028. (gc-cons-threshold #x40000000))
  4029. (org-skip-whitespace)
  4030. (org-element--parse-elements
  4031. (line-beginning-position) (point-max)
  4032. ;; Start in `first-section' mode so text before the first
  4033. ;; headline belongs to a section.
  4034. 'first-section nil granularity visible-only org-data))))
  4035. (defun org-element-parse-secondary-string (string restriction &optional parent)
  4036. "Recursively parse objects in STRING and return structure.
  4037. RESTRICTION is a symbol limiting the object types that will be
  4038. looked after.
  4039. Optional argument PARENT, when non-nil, is the element or object
  4040. containing the secondary string. It is used to set correctly
  4041. `:parent' property within the string.
  4042. If STRING is the empty string or nil, return nil."
  4043. (cond
  4044. ((not string) nil)
  4045. ((equal string "") nil)
  4046. (t (let ((local-variables (buffer-local-variables)))
  4047. (with-temp-buffer
  4048. (dolist (v local-variables)
  4049. (ignore-errors
  4050. (if (symbolp v) (makunbound v)
  4051. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  4052. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  4053. (set (make-local-variable (car v)) (cdr v))))))
  4054. ;; Transferring local variables may put the temporary buffer
  4055. ;; into a read-only state. Make sure we can insert STRING.
  4056. (let ((inhibit-read-only t)) (insert string))
  4057. ;; Prevent "Buffer *temp* modified; kill anyway?".
  4058. (restore-buffer-modified-p nil)
  4059. (org-element--parse-objects
  4060. (point-min) (point-max) nil restriction parent))))))
  4061. (defun org-element-map
  4062. (data types fun &optional info first-match no-recursion with-affiliated)
  4063. "Map a function on selected elements or objects.
  4064. DATA is a parse tree (for example, returned by
  4065. `org-element-parse-buffer'), an element, an object, a string, or a
  4066. list of such constructs. TYPES is a symbol or list of symbols of
  4067. elements or object types (see `org-element-all-elements' and
  4068. `org-element-all-objects' for a complete list of types). FUN is the
  4069. function called on the matching element or object. It has to accept
  4070. one argument: the element or object itself.
  4071. When optional argument INFO is non-nil, it should be a plist
  4072. holding export options. In that case, parts of the parse tree
  4073. not exportable according to that property list will be skipped.
  4074. When optional argument FIRST-MATCH is non-nil, stop at the first
  4075. match for which FUN doesn't return nil, and return that value.
  4076. Optional argument NO-RECURSION is a symbol or a list of symbols
  4077. representing elements or objects types. `org-element-map' won't
  4078. enter any recursive element or object whose type belongs to that
  4079. list. Though, FUN can still be applied on them.
  4080. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  4081. apply to matching objects within parsed affiliated keywords (see
  4082. `org-element-parsed-keywords').
  4083. Nil values returned from FUN do not appear in the results.
  4084. Examples:
  4085. ---------
  4086. Assuming TREE is a variable containing an Org buffer parse tree,
  4087. the following example will return a flat list of all `src-block'
  4088. and `example-block' elements in it:
  4089. (setq tree (org-element-parse-buffer))
  4090. (org-element-map tree \\='(example-block src-block) #\\='identity)
  4091. The following snippet will find the first headline with a level
  4092. of 1 and a \"phone\" tag, and will return its beginning position:
  4093. (org-element-map tree \\='headline
  4094. (lambda (hl)
  4095. (and (= (org-element-property :level hl) 1)
  4096. (member \"phone\" (org-element-property :tags hl))
  4097. (org-element-property :begin hl)))
  4098. nil t)
  4099. The next example will return a flat list of all `plain-list' type
  4100. elements in TREE that are not a sub-list themselves:
  4101. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  4102. Eventually, this example will return a flat list of all `bold'
  4103. type objects containing a `latex-snippet' type object, even
  4104. looking into captions:
  4105. (org-element-map tree \\='bold
  4106. (lambda (b)
  4107. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  4108. nil nil nil t)"
  4109. (declare (indent 2))
  4110. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  4111. (let* ((types (if (listp types) types (list types)))
  4112. (no-recursion (if (listp no-recursion) no-recursion
  4113. (list no-recursion)))
  4114. ;; Recursion depth is determined by --CATEGORY.
  4115. (--category
  4116. (catch :--found
  4117. (let ((category 'greater-elements)
  4118. (all-objects (cons 'plain-text org-element-all-objects)))
  4119. (dolist (type types category)
  4120. (cond ((memq type all-objects)
  4121. ;; If one object is found, the function has
  4122. ;; to recurse into every object.
  4123. (throw :--found 'objects))
  4124. ((not (memq type org-element-greater-elements))
  4125. ;; If one regular element is found, the
  4126. ;; function has to recurse, at least, into
  4127. ;; every element it encounters.
  4128. (and (not (eq category 'elements))
  4129. (setq category 'elements))))))))
  4130. (--ignore-list (plist-get info :ignore-list))
  4131. --acc)
  4132. (letrec ((--walk-tree
  4133. (lambda (--data)
  4134. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  4135. ;; holding contextual information.
  4136. (let ((--type (org-element-type --data)))
  4137. (cond
  4138. ((not --data))
  4139. ;; Ignored element in an export context.
  4140. ((and info (memq --data --ignore-list)))
  4141. ;; List of elements or objects.
  4142. ((not --type) (mapc --walk-tree --data))
  4143. ;; Unconditionally enter parse trees.
  4144. ((eq --type 'org-data)
  4145. (mapc --walk-tree (org-element-contents --data)))
  4146. (t
  4147. ;; Check if TYPE is matching among TYPES. If so,
  4148. ;; apply FUN to --DATA and accumulate return value
  4149. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  4150. (when (memq --type types)
  4151. (let ((result (funcall fun --data)))
  4152. (cond ((not result))
  4153. (first-match (throw :--map-first-match result))
  4154. (t (push result --acc)))))
  4155. ;; If --DATA has a secondary string that can contain
  4156. ;; objects with their type among TYPES, look inside.
  4157. (when (and (eq --category 'objects) (not (stringp --data)))
  4158. (dolist (p (cdr (assq --type
  4159. org-element-secondary-value-alist)))
  4160. (funcall --walk-tree (org-element-property p --data))))
  4161. ;; If --DATA has any parsed affiliated keywords and
  4162. ;; WITH-AFFILIATED is non-nil, look for objects in
  4163. ;; them.
  4164. (when (and with-affiliated
  4165. (eq --category 'objects)
  4166. (eq (org-element-class --data) 'element))
  4167. (dolist (kwd-pair org-element--parsed-properties-alist)
  4168. (let ((kwd (car kwd-pair))
  4169. (value (org-element-property (cdr kwd-pair) --data)))
  4170. ;; Pay attention to the type of parsed
  4171. ;; keyword. In particular, preserve order for
  4172. ;; multiple keywords.
  4173. (cond
  4174. ((not value))
  4175. ((member kwd org-element-dual-keywords)
  4176. (if (member kwd org-element-multiple-keywords)
  4177. (dolist (line (reverse value))
  4178. (funcall --walk-tree (cdr line))
  4179. (funcall --walk-tree (car line)))
  4180. (funcall --walk-tree (cdr value))
  4181. (funcall --walk-tree (car value))))
  4182. ((member kwd org-element-multiple-keywords)
  4183. (mapc --walk-tree (reverse value)))
  4184. (t (funcall --walk-tree value))))))
  4185. ;; Determine if a recursion into --DATA is possible.
  4186. (cond
  4187. ;; --TYPE is explicitly removed from recursion.
  4188. ((memq --type no-recursion))
  4189. ;; --DATA has no contents.
  4190. ((not (org-element-contents --data)))
  4191. ;; Looking for greater elements but --DATA is
  4192. ;; simply an element or an object.
  4193. ((and (eq --category 'greater-elements)
  4194. (not (memq --type org-element-greater-elements))))
  4195. ;; Looking for elements but --DATA is an object.
  4196. ((and (eq --category 'elements)
  4197. (eq (org-element-class --data) 'object)))
  4198. ;; In any other case, map contents.
  4199. (t (mapc --walk-tree (org-element-contents --data))))))))))
  4200. (catch :--map-first-match
  4201. (funcall --walk-tree data)
  4202. ;; Return value in a proper order.
  4203. (nreverse --acc)))))
  4204. ;; The following functions are internal parts of the parser.
  4205. ;;
  4206. ;; The first one, `org-element--parse-elements' acts at the element's
  4207. ;; level.
  4208. ;;
  4209. ;; The second one, `org-element--parse-objects' applies on all objects
  4210. ;; of a paragraph or a secondary string. It calls
  4211. ;; `org-element--object-lex' to find the next object in the current
  4212. ;; container.
  4213. (defsubst org-element--next-mode (mode type parent?)
  4214. "Return next mode according to current one.
  4215. MODE is a symbol representing the expectation about the next
  4216. element or object. Meaningful values are `first-section',
  4217. `item', `node-property', `planning', `property-drawer',
  4218. `section', `table-row', `top-comment', and nil.
  4219. TYPE is the type of the current element or object.
  4220. If PARENT? is non-nil, assume the next element or object will be
  4221. located inside the current one."
  4222. (if parent?
  4223. (pcase type
  4224. (`headline 'section)
  4225. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4226. ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
  4227. ((and (guard (not mode)) `org-data) 'first-section)
  4228. (`inlinetask 'planning)
  4229. (`plain-list 'item)
  4230. (`property-drawer 'node-property)
  4231. (`section 'planning)
  4232. (`table 'table-row))
  4233. (pcase mode
  4234. (`item 'item)
  4235. (`node-property 'node-property)
  4236. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4237. (`table-row 'table-row)
  4238. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4239. (defun org-element--parse-elements
  4240. (beg end mode structure granularity visible-only acc)
  4241. "Parse elements between BEG and END positions.
  4242. MODE prioritizes some elements over the others. It can be set to
  4243. `first-section', `item', `node-property', `planning',
  4244. `property-drawer', `section', `table-row', `top-comment', or nil.
  4245. When value is `item', STRUCTURE will be used as the current list
  4246. structure.
  4247. GRANULARITY determines the depth of the recursion. See
  4248. `org-element-parse-buffer' for more information.
  4249. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4250. elements.
  4251. Elements are accumulated into ACC."
  4252. (save-excursion
  4253. (goto-char beg)
  4254. ;; When parsing only headlines, skip any text before first one.
  4255. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4256. (org-with-limited-levels (outline-next-heading)))
  4257. (let (elements)
  4258. (while (< (point) end)
  4259. ;; Visible only: skip invisible parts due to folding.
  4260. (if (and visible-only (org-invisible-p nil t))
  4261. (progn
  4262. (goto-char (org-find-visible))
  4263. (when (and (eolp) (not (eobp))) (forward-char)))
  4264. ;; Find current element's type and parse it accordingly to
  4265. ;; its category.
  4266. (let* ((element (org-element-copy
  4267. ;; `org-element--current-element' may return cached
  4268. ;; elements. Below code reassigns
  4269. ;; `:parent' property of the element and
  4270. ;; may interfere with cache
  4271. ;; synchronisation if parent element is not
  4272. ;; yet in cache. Moreover, the returned
  4273. ;; structure may be altered by caller code
  4274. ;; arbitrarily. Hence, we return a copy of
  4275. ;; the potentially cached element to make
  4276. ;; potential modifications safe for element
  4277. ;; cache.
  4278. (org-element--current-element
  4279. end granularity mode structure)))
  4280. (type (org-element-type element))
  4281. (cbeg (org-element-property :contents-begin element)))
  4282. (goto-char (org-element-property :end element))
  4283. ;; Fill ELEMENT contents by side-effect.
  4284. (cond
  4285. ;; If element has no contents, don't modify it.
  4286. ((not cbeg))
  4287. ;; Greater element: parse it between `contents-begin' and
  4288. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4289. ;; or ELEMENT is a headline, in which case going inside
  4290. ;; is mandatory, in order to get sub-level headings.
  4291. ((and (memq type org-element-greater-elements)
  4292. (or (memq granularity '(element object nil))
  4293. (and (eq granularity 'greater-element)
  4294. (eq type 'section))
  4295. (eq type 'headline)))
  4296. (org-element--parse-elements
  4297. cbeg (org-element-property :contents-end element)
  4298. ;; Possibly switch to a special mode.
  4299. (org-element--next-mode mode type t)
  4300. (and (memq type '(item plain-list))
  4301. (org-element-property :structure element))
  4302. granularity visible-only element))
  4303. ;; ELEMENT has contents. Parse objects inside, if
  4304. ;; GRANULARITY allows it.
  4305. ((memq granularity '(object nil))
  4306. (org-element--parse-objects
  4307. cbeg (org-element-property :contents-end element) element
  4308. (org-element-restriction type))))
  4309. (push (org-element-put-property element :parent acc) elements)
  4310. ;; Update mode.
  4311. (setq mode (org-element--next-mode mode type nil)))))
  4312. ;; Return result.
  4313. (org-element-put-property acc :granularity granularity)
  4314. (apply #'org-element-set-contents acc (nreverse elements)))))
  4315. (defun org-element--object-lex (restriction)
  4316. "Return next object in current buffer or nil.
  4317. RESTRICTION is a list of object types, as symbols, that should be
  4318. looked after. This function assumes that the buffer is narrowed
  4319. to an appropriate container (e.g., a paragraph)."
  4320. (cond
  4321. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4322. ((memq 'citation-reference restriction)
  4323. (org-element-citation-reference-parser))
  4324. (t
  4325. (let* ((start (point))
  4326. (limit
  4327. ;; Object regexp sometimes needs to have a peek at
  4328. ;; a character ahead. Therefore, when there is a hard
  4329. ;; limit, make it one more than the true beginning of the
  4330. ;; radio target.
  4331. (save-excursion
  4332. (cond ((not org-target-link-regexp) nil)
  4333. ((not (memq 'link restriction)) nil)
  4334. ((progn
  4335. (unless (bolp) (forward-char -1))
  4336. (not (re-search-forward org-target-link-regexp nil t)))
  4337. nil)
  4338. ;; Since we moved backward, we do not want to
  4339. ;; match again an hypothetical 1-character long
  4340. ;; radio link before us. Realizing that this can
  4341. ;; only happen if such a radio link starts at
  4342. ;; beginning of line, we prevent this here.
  4343. ((and (= start (1+ (line-beginning-position)))
  4344. (= start (match-end 1)))
  4345. (and (re-search-forward org-target-link-regexp nil t)
  4346. (1+ (match-beginning 1))))
  4347. (t (1+ (match-beginning 1))))))
  4348. found)
  4349. (save-excursion
  4350. (while (and (not found)
  4351. (re-search-forward org-element--object-regexp limit 'move))
  4352. (goto-char (match-beginning 0))
  4353. (let ((result (match-string 0)))
  4354. (setq found
  4355. (cond
  4356. ((string-prefix-p "call_" result t)
  4357. (and (memq 'inline-babel-call restriction)
  4358. (org-element-inline-babel-call-parser)))
  4359. ((string-prefix-p "src_" result t)
  4360. (and (memq 'inline-src-block restriction)
  4361. (org-element-inline-src-block-parser)))
  4362. (t
  4363. (pcase (char-after)
  4364. (?^ (and (memq 'superscript restriction)
  4365. (org-element-superscript-parser)))
  4366. (?_ (or (and (memq 'subscript restriction)
  4367. (org-element-subscript-parser))
  4368. (and (memq 'underline restriction)
  4369. (org-element-underline-parser))))
  4370. (?* (and (memq 'bold restriction)
  4371. (org-element-bold-parser)))
  4372. (?/ (and (memq 'italic restriction)
  4373. (org-element-italic-parser)))
  4374. (?~ (and (memq 'code restriction)
  4375. (org-element-code-parser)))
  4376. (?= (and (memq 'verbatim restriction)
  4377. (org-element-verbatim-parser)))
  4378. (?+ (and (memq 'strike-through restriction)
  4379. (org-element-strike-through-parser)))
  4380. (?@ (and (memq 'export-snippet restriction)
  4381. (org-element-export-snippet-parser)))
  4382. (?{ (and (memq 'macro restriction)
  4383. (org-element-macro-parser)))
  4384. (?$ (and (memq 'latex-fragment restriction)
  4385. (org-element-latex-fragment-parser)))
  4386. (?<
  4387. (if (eq (aref result 1) ?<)
  4388. (or (and (memq 'radio-target restriction)
  4389. (org-element-radio-target-parser))
  4390. (and (memq 'target restriction)
  4391. (org-element-target-parser)))
  4392. (or (and (memq 'timestamp restriction)
  4393. (org-element-timestamp-parser))
  4394. (and (memq 'link restriction)
  4395. (org-element-link-parser)))))
  4396. (?\\
  4397. (if (eq (aref result 1) ?\\)
  4398. (and (memq 'line-break restriction)
  4399. (org-element-line-break-parser))
  4400. (or (and (memq 'entity restriction)
  4401. (org-element-entity-parser))
  4402. (and (memq 'latex-fragment restriction)
  4403. (org-element-latex-fragment-parser)))))
  4404. (?\[
  4405. (pcase (aref result 1)
  4406. ((and ?\[
  4407. (guard (memq 'link restriction)))
  4408. (org-element-link-parser))
  4409. ((and ?f
  4410. (guard (memq 'footnote-reference restriction)))
  4411. (org-element-footnote-reference-parser))
  4412. ((and ?c
  4413. (guard (memq 'citation restriction)))
  4414. (org-element-citation-parser))
  4415. ((and (or ?% ?/)
  4416. (guard (memq 'statistics-cookie restriction)))
  4417. (org-element-statistics-cookie-parser))
  4418. (_
  4419. (or (and (memq 'timestamp restriction)
  4420. (org-element-timestamp-parser))
  4421. (and (memq 'statistics-cookie restriction)
  4422. (org-element-statistics-cookie-parser))))))
  4423. ;; This is probably a plain link.
  4424. (_ (and (memq 'link restriction)
  4425. (org-element-link-parser)))))))
  4426. (or (eobp) (forward-char))))
  4427. (cond (found)
  4428. (limit (forward-char -1)
  4429. (org-element-link-parser)) ;radio link
  4430. (t nil)))))))
  4431. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4432. "Parse objects between BEG and END and return recursive structure.
  4433. Objects are accumulated in ACC. RESTRICTION is a list of object
  4434. successors which are allowed in the current object.
  4435. ACC becomes the parent for all parsed objects. However, if ACC
  4436. is nil (i.e., a secondary string is being parsed) and optional
  4437. argument PARENT is non-nil, use it as the parent for all objects.
  4438. Eventually, if both ACC and PARENT are nil, the common parent is
  4439. the list of objects itself."
  4440. (save-excursion
  4441. (save-restriction
  4442. (narrow-to-region beg end)
  4443. (goto-char (point-min))
  4444. (let (next-object contents)
  4445. (while (and (not (eobp))
  4446. (setq next-object (org-element--object-lex restriction)))
  4447. ;; Text before any object.
  4448. (let ((obj-beg (org-element-property :begin next-object)))
  4449. (unless (= (point) obj-beg)
  4450. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4451. (push (if acc (org-element-put-property text :parent acc) text)
  4452. contents))))
  4453. ;; Object...
  4454. (let ((obj-end (org-element-property :end next-object))
  4455. (cont-beg (org-element-property :contents-begin next-object)))
  4456. (when acc (org-element-put-property next-object :parent acc))
  4457. (push (if cont-beg
  4458. ;; Fill contents of NEXT-OBJECT if possible.
  4459. (org-element--parse-objects
  4460. cont-beg
  4461. (org-element-property :contents-end next-object)
  4462. next-object
  4463. (org-element-restriction next-object))
  4464. next-object)
  4465. contents)
  4466. (goto-char obj-end)))
  4467. ;; Text after last object.
  4468. (unless (eobp)
  4469. (let ((text (buffer-substring-no-properties (point) end)))
  4470. (push (if acc (org-element-put-property text :parent acc) text)
  4471. contents)))
  4472. ;; Result. Set appropriate parent.
  4473. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4474. (let* ((contents (nreverse contents))
  4475. (parent (or parent contents)))
  4476. (dolist (datum contents contents)
  4477. (org-element-put-property datum :parent parent))))))))
  4478. ;;; Towards A Bijective Process
  4479. ;;
  4480. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4481. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4482. ;; interpreted and expanded into a string with canonical Org syntax.
  4483. ;; Hence `org-element-interpret-data'.
  4484. ;;
  4485. ;; The function relies internally on
  4486. ;; `org-element--interpret-affiliated-keywords'.
  4487. ;;;###autoload
  4488. (defun org-element-interpret-data (data)
  4489. "Interpret DATA as Org syntax.
  4490. DATA is a parse tree, an element, an object or a secondary string
  4491. to interpret. Return Org syntax as a string."
  4492. (letrec ((fun
  4493. (lambda (data parent)
  4494. (let* ((type (org-element-type data))
  4495. ;; Find interpreter for current object or
  4496. ;; element. If it doesn't exist (e.g. this is
  4497. ;; a pseudo object or element), return contents,
  4498. ;; if any.
  4499. (interpret
  4500. (let ((fun (intern
  4501. (format "org-element-%s-interpreter" type))))
  4502. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4503. (results
  4504. (cond
  4505. ;; Secondary string.
  4506. ((not type)
  4507. (mapconcat (lambda (obj) (funcall fun obj parent))
  4508. data
  4509. ""))
  4510. ;; Full Org document.
  4511. ((eq type 'org-data)
  4512. (mapconcat (lambda (obj) (funcall fun obj parent))
  4513. (org-element-contents data)
  4514. ""))
  4515. ;; Plain text: return it.
  4516. ((stringp data) data)
  4517. ;; Element or object without contents.
  4518. ((not (org-element-contents data))
  4519. (funcall interpret data nil))
  4520. ;; Element or object with contents.
  4521. (t
  4522. (funcall
  4523. interpret
  4524. data
  4525. ;; Recursively interpret contents.
  4526. (mapconcat
  4527. (lambda (datum) (funcall fun datum data))
  4528. (org-element-contents
  4529. (if (not (memq type '(paragraph verse-block)))
  4530. data
  4531. ;; Fix indentation of elements containing
  4532. ;; objects. We ignore `table-row'
  4533. ;; elements as they are one line long
  4534. ;; anyway.
  4535. (org-element-normalize-contents
  4536. data
  4537. ;; When normalizing first paragraph of
  4538. ;; an item or a footnote-definition,
  4539. ;; ignore first line's indentation.
  4540. (and (eq type 'paragraph)
  4541. (memq (org-element-type parent)
  4542. '(footnote-definition item))
  4543. (eq data (car (org-element-contents parent)))
  4544. (eq (org-element-property :pre-blank parent)
  4545. 0)))))
  4546. ""))))))
  4547. (if (memq type '(org-data nil)) results
  4548. ;; Build white spaces. If no `:post-blank' property
  4549. ;; is specified, assume its value is 0.
  4550. (let ((blank (or (org-element-property :post-blank data) 0)))
  4551. (if (eq (org-element-class data parent) 'object)
  4552. (concat results (make-string blank ?\s))
  4553. (concat (org-element--interpret-affiliated-keywords data)
  4554. (org-element-normalize-string results)
  4555. (make-string blank ?\n)))))))))
  4556. (funcall fun data nil)))
  4557. (defun org-element--interpret-affiliated-keywords (element)
  4558. "Return ELEMENT's affiliated keywords as Org syntax.
  4559. If there is no affiliated keyword, return the empty string."
  4560. (let ((keyword-to-org
  4561. (lambda (key value)
  4562. (let (dual)
  4563. (when (member key org-element-dual-keywords)
  4564. (setq dual (cdr value) value (car value)))
  4565. (concat "#+" (downcase key)
  4566. (and dual
  4567. (format "[%s]" (org-element-interpret-data dual)))
  4568. ": "
  4569. (if (member key org-element-parsed-keywords)
  4570. (org-element-interpret-data value)
  4571. value)
  4572. "\n")))))
  4573. (mapconcat
  4574. (lambda (prop)
  4575. (let ((value (org-element-property prop element))
  4576. (keyword (upcase (substring (symbol-name prop) 1))))
  4577. (when value
  4578. (if (or (member keyword org-element-multiple-keywords)
  4579. ;; All attribute keywords can have multiple lines.
  4580. (string-match "^ATTR_" keyword))
  4581. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4582. (reverse value)
  4583. "")
  4584. (funcall keyword-to-org keyword value)))))
  4585. ;; List all ELEMENT's properties matching an attribute line or an
  4586. ;; affiliated keyword, but ignore translated keywords since they
  4587. ;; cannot belong to the property list.
  4588. (cl-loop for prop in (nth 1 element) by 'cddr
  4589. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4590. (or (string-match "^ATTR_" keyword)
  4591. (and
  4592. (member keyword org-element-affiliated-keywords)
  4593. (not (assoc keyword
  4594. org-element-keyword-translation-alist)))))
  4595. collect prop)
  4596. "")))
  4597. ;; Because interpretation of the parse tree must return the same
  4598. ;; number of blank lines between elements and the same number of white
  4599. ;; space after objects, some special care must be given to white
  4600. ;; spaces.
  4601. ;;
  4602. ;; The first function, `org-element-normalize-string', ensures any
  4603. ;; string different from the empty string will end with a single
  4604. ;; newline character.
  4605. ;;
  4606. ;; The second function, `org-element-normalize-contents', removes
  4607. ;; global indentation from the contents of the current element.
  4608. (defun org-element-normalize-string (s)
  4609. "Ensure string S ends with a single newline character.
  4610. If S isn't a string return it unchanged. If S is the empty
  4611. string, return it. Otherwise, return a new string with a single
  4612. newline character at its end."
  4613. (cond
  4614. ((not (stringp s)) s)
  4615. ((string= "" s) "")
  4616. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4617. (replace-match "\n" nil nil s)))))
  4618. (defun org-element-normalize-contents (element &optional ignore-first)
  4619. "Normalize plain text in ELEMENT's contents.
  4620. ELEMENT must only contain plain text and objects.
  4621. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4622. indentation to compute maximal common indentation.
  4623. Return the normalized element that is element with global
  4624. indentation removed from its contents."
  4625. (letrec ((find-min-ind
  4626. ;; Return minimal common indentation within BLOB. This is
  4627. ;; done by walking recursively BLOB and updating MIN-IND
  4628. ;; along the way. FIRST-FLAG is non-nil when the next
  4629. ;; object is expected to be a string that doesn't start
  4630. ;; with a newline character. It happens for strings at
  4631. ;; the beginnings of the contents or right after a line
  4632. ;; break.
  4633. (lambda (blob first-flag min-ind)
  4634. (dolist (datum (org-element-contents blob) min-ind)
  4635. (when first-flag
  4636. (setq first-flag nil)
  4637. (cond
  4638. ;; Objects cannot start with spaces: in this
  4639. ;; case, indentation is 0.
  4640. ((not (stringp datum)) (throw :zero 0))
  4641. ((not (string-match
  4642. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4643. (throw :zero 0))
  4644. ((equal (match-string 2 datum) "\n")
  4645. (put-text-property
  4646. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4647. (t
  4648. (let ((i (string-width (match-string 1 datum))))
  4649. (put-text-property
  4650. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4651. (setq min-ind (min i min-ind))))))
  4652. (cond
  4653. ((stringp datum)
  4654. (let ((s 0))
  4655. (while (string-match
  4656. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4657. (setq s (match-end 1))
  4658. (cond
  4659. ((equal (match-string 1 datum) "")
  4660. (unless (member (match-string 2 datum) '("" "\n"))
  4661. (throw :zero 0)))
  4662. ((equal (match-string 2 datum) "\n")
  4663. (put-text-property (match-beginning 1) (match-end 1)
  4664. 'org-ind 'empty datum))
  4665. (t
  4666. (let ((i (string-width (match-string 1 datum))))
  4667. (put-text-property (match-beginning 1) (match-end 1)
  4668. 'org-ind i datum)
  4669. (setq min-ind (min i min-ind))))))))
  4670. ((eq (org-element-type datum) 'line-break)
  4671. (setq first-flag t))
  4672. ((memq (org-element-type datum) org-element-recursive-objects)
  4673. (setq min-ind
  4674. (funcall find-min-ind datum first-flag min-ind)))))))
  4675. (min-ind
  4676. (catch :zero
  4677. (funcall find-min-ind
  4678. element (not ignore-first) most-positive-fixnum))))
  4679. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4680. ;; Build ELEMENT back, replacing each string with the same
  4681. ;; string minus common indentation.
  4682. (letrec ((build
  4683. (lambda (datum)
  4684. ;; Return DATUM with all its strings indentation
  4685. ;; shortened from MIN-IND white spaces.
  4686. (setcdr
  4687. (cdr datum)
  4688. (mapcar
  4689. (lambda (object)
  4690. (cond
  4691. ((stringp object)
  4692. (with-temp-buffer
  4693. (insert object)
  4694. (let ((s (point-min)))
  4695. (while (setq s (text-property-not-all
  4696. s (point-max) 'org-ind nil))
  4697. (goto-char s)
  4698. (let ((i (get-text-property s 'org-ind)))
  4699. (delete-region s (progn
  4700. (skip-chars-forward " \t")
  4701. (point)))
  4702. (when (integerp i) (indent-to (- i min-ind))))))
  4703. (buffer-string)))
  4704. ((memq (org-element-type object)
  4705. org-element-recursive-objects)
  4706. (funcall build object))
  4707. (t object)))
  4708. (org-element-contents datum)))
  4709. datum)))
  4710. (funcall build element)))))
  4711. ;;; Cache
  4712. ;;
  4713. ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
  4714. ;; fast mapping across Org elements in `org-element-cache-map', which see.
  4715. ;;
  4716. ;; When cache is enabled, the elements returned by `org-element-at-point' and
  4717. ;; `org-element-context' are returned by reference. Altering these elements will
  4718. ;; also alter their cache representation. The same is true for
  4719. ;; elements passed to mapping function in `org-element-cache-map'.
  4720. ;;
  4721. ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
  4722. ;; `org-element-cache-map'.
  4723. ;;
  4724. ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
  4725. ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
  4726. ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
  4727. ;;
  4728. ;; Internally, parsed elements are stored in an AVL tree,
  4729. ;; `org-element--cache'. This tree is updated lazily: whenever
  4730. ;; a change happens to the buffer, a synchronization request is
  4731. ;; registered in `org-element--cache-sync-requests' (see
  4732. ;; `org-element--cache-submit-request'). During idle time, requests
  4733. ;; are processed by `org-element--cache-sync'. Synchronization also
  4734. ;; happens when an element is required from the cache. In this case,
  4735. ;; the process stops as soon as the needed element is up-to-date.
  4736. ;;
  4737. ;; A synchronization request can only apply on a synchronized part of
  4738. ;; the cache. Therefore, the cache is updated at least to the
  4739. ;; location where the new request applies. Thus, requests are ordered
  4740. ;; from left to right and all elements starting before the first
  4741. ;; request are correct. This property is used by functions like
  4742. ;; `org-element--cache-find' to retrieve elements in the part of the
  4743. ;; cache that can be trusted.
  4744. ;;
  4745. ;; A request applies to every element, starting from its original
  4746. ;; location (or key, see below). When a request is processed, it
  4747. ;; moves forward and may collide the next one. In this case, both
  4748. ;; requests are merged into a new one that starts from that element.
  4749. ;; As a consequence, the whole synchronization complexity does not
  4750. ;; depend on the number of pending requests, but on the number of
  4751. ;; elements the very first request will be applied on.
  4752. ;;
  4753. ;; Elements cannot be accessed through their beginning position, which
  4754. ;; may or may not be up-to-date. Instead, each element in the tree is
  4755. ;; associated to a key, obtained with `org-element--cache-key'. This
  4756. ;; mechanism is robust enough to preserve total order among elements
  4757. ;; even when the tree is only partially synchronized.
  4758. ;;
  4759. ;; The cache code debuggin is fairly complex because cache request
  4760. ;; state is often hard to reproduce. An extensive diagnostics
  4761. ;; functionality is built into the cache code to assist hunting bugs.
  4762. ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
  4763. ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
  4764. ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
  4765. ;; `org-element--cache-map-statistics-threshold'.
  4766. (defvar org-element-use-cache t
  4767. "Non-nil when Org parser should cache its results.")
  4768. (defvar org-element-cache-persistent t
  4769. "Non-nil when cache should persist between Emacs sessions.")
  4770. (defvar org-element-cache-sync-idle-time 0.6
  4771. "Length, in seconds, of idle time before syncing cache.")
  4772. (defvar org-element-cache-sync-duration 0.04
  4773. "Maximum duration, as a time value, for a cache synchronization.
  4774. If the synchronization is not over after this delay, the process
  4775. pauses and resumes after `org-element-cache-sync-break'
  4776. seconds.")
  4777. (defvar org-element-cache-sync-break 0.3
  4778. "Duration, as a time value, of the pause between synchronizations.
  4779. See `org-element-cache-sync-duration' for more information.")
  4780. (defvar org-element--cache-self-verify t
  4781. "Activate extra consistency checks for the cache.
  4782. This may cause serious performance degradation depending on the value
  4783. of `org-element--cache-self-verify-frequency'.
  4784. When set to symbol `backtrace', record and display backtrace log if
  4785. any inconsistency is detected.")
  4786. (defvar org-element--cache-self-verify-frequency 0.03
  4787. "Frequency of cache element verification.
  4788. This number is a probability to check an element requested from cache
  4789. to be correct. Setting this to a value less than 0.0001 is useless.")
  4790. (defvar org-element--cache-diagnostics nil
  4791. "Print detailed diagnostics of cache processing.")
  4792. (defvar org-element--cache-map-statistics nil
  4793. "Print statistics for `org-element-cache-map'.")
  4794. (defvar org-element--cache-map-statistics-threshold 0.1
  4795. "Time threshold in seconds to log statistics for `org-element-cache-map'.")
  4796. (defvar org-element--cache-diagnostics-level 2
  4797. "Detail level of the diagnostics.")
  4798. (defvar-local org-element--cache-diagnostics-ring nil
  4799. "Ring containing last `org-element--cache-diagnostics-ring-size'
  4800. cache process log entries.")
  4801. (defvar org-element--cache-diagnostics-ring-size 5000
  4802. "Size of `org-element--cache-diagnostics-ring'.")
  4803. ;;;; Data Structure
  4804. (defvar-local org-element--cache nil
  4805. "AVL tree used to cache elements.
  4806. Each node of the tree contains an element. Comparison is done
  4807. with `org-element--cache-compare'. This cache is used in
  4808. `org-element-at-point'.")
  4809. (defvar-local org-element--headline-cache nil
  4810. "AVL tree used to cache headline and inlinetask elements.
  4811. Each node of the tree contains an element. Comparison is done
  4812. with `org-element--cache-compare'. This cache is used in
  4813. `org-element-cache-map'.")
  4814. (defconst org-element--cache-hash-size 16
  4815. "Cache size for recent cached calls to `org-element--cache-find'.
  4816. This extra caching is based on the following paper:
  4817. Pugh [Information Processing Letters] (1990) Slow optimally balanced
  4818. search strategies vs. cached fast uniformly balanced search
  4819. strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
  4820. Also, see `org-element--cache-hash-left' and `org-element--cache-hash-right'.")
  4821. (defvar-local org-element--cache-hash-left nil
  4822. "Cached elements from `org-element--cache' for fast O(1) lookup.
  4823. When non-nil, it should be a vector representing POS arguments of
  4824. `org-element--cache-find' called with nil SIDE argument.
  4825. Also, see `org-element--cache-hash-size'.")
  4826. (defvar-local org-element--cache-hash-right nil
  4827. "Cached elements from `org-element--cache' for fast O(1) lookup.
  4828. When non-nil, it should be a vector representing POS arguments of
  4829. `org-element--cache-find' called with non-nil, non-`both' SIDE argument.
  4830. Also, see `org-element--cache-hash-size'.")
  4831. (defvar org-element--cache-hash-statistics '(0 . 0)
  4832. "Cons cell storing how Org makes use of `org-element--cache-find' caching.
  4833. The car is the number of successful uses and cdr is the total calls to
  4834. `org-element--cache-find'.")
  4835. (defvar org-element--cache-hash-nocache 0
  4836. "Number of calls to `org-element--cache-has' with `both' SIDE argument.
  4837. These calls are not cached by hash. See `org-element--cache-hash-size'.")
  4838. (defvar-local org-element--cache-size 0
  4839. "Size of the `org-element--cache'.
  4840. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4841. (defvar-local org-element--headline-cache-size 0
  4842. "Size of the `org-element--headline-cache'.
  4843. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4844. (defvar-local org-element--cache-sync-requests nil
  4845. "List of pending synchronization requests.
  4846. A request is a vector with the following pattern:
  4847. [NEXT BEG END OFFSET PARENT PHASE]
  4848. Processing a synchronization request consists of three phases:
  4849. 0. Delete modified elements,
  4850. 1. Fill missing area in cache,
  4851. 2. Shift positions and re-parent elements after the changes.
  4852. During phase 0, NEXT is the key of the first element to be
  4853. removed, BEG and END is buffer position delimiting the
  4854. modifications. Elements starting between them (inclusive) are
  4855. removed. So are elements whose parent is removed. PARENT, when
  4856. non-nil, is the common parent of all the elements between BEG and END.
  4857. It is guaranteed that only a single phase 0 request exists at any
  4858. moment of time. If it does, it must be the first request in the list.
  4859. During phase 1, NEXT is the key of the next known element in
  4860. cache and BEG its beginning position. Parse buffer between that
  4861. element and the one before it in order to determine the parent of
  4862. the next element. Set PARENT to the element containing NEXT.
  4863. During phase 2, NEXT is the key of the next element to shift in
  4864. the parse tree. All elements starting from this one have their
  4865. properties relative to buffer positions shifted by integer
  4866. OFFSET and, if they belong to element PARENT, are adopted by it.
  4867. PHASE specifies the phase number, as an integer.
  4868. For any synchronisation request, all the later requests in the cache
  4869. must not start at or before END. See `org-element--cache-submit-request'.")
  4870. (defvar-local org-element--cache-sync-timer nil
  4871. "Timer used for cache synchronization.")
  4872. (defvar-local org-element--cache-sync-keys-value nil
  4873. "Id value used to identify keys during synchronisation.
  4874. See `org-element--cache-key' for more information.")
  4875. (defvar-local org-element--cache-change-tic nil
  4876. "Last `buffer-chars-modified-tick' for registered changes.")
  4877. (defvar-local org-element--cache-last-buffer-size nil
  4878. "Last value of `buffer-size' for registered changes.")
  4879. (defvar org-element--cache-non-modifying-commands
  4880. '(org-agenda
  4881. org-agenda-redo
  4882. org-sparse-tree
  4883. org-occur
  4884. org-columns
  4885. org-columns-redo
  4886. org-columns-new
  4887. org-columns-delete
  4888. org-columns-compute
  4889. org-columns-insert-dblock
  4890. org-agenda-columns
  4891. org-ctrl-c-ctrl-c)
  4892. "List of commands that are not expected to change the cache state.
  4893. This variable is used to determine when re-parsing buffer is not going
  4894. to slow down the command.
  4895. If the commends end up modifying the cache, the worst case scenario is
  4896. performance drop. So, advicing these commands is safe. Yet, it is
  4897. better to remove the commands adviced in such way from this list.")
  4898. (defmacro org-element--request-key (request)
  4899. "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
  4900. `(aref ,request 0))
  4901. (defmacro org-element--request-beg (request)
  4902. "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
  4903. `(aref ,request 1))
  4904. (defmacro org-element--request-end (request)
  4905. "Get END part of a `org-element--cache-sync-requests' REQUEST."
  4906. `(aref ,request 2))
  4907. (defmacro org-element--request-offset (request)
  4908. "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
  4909. `(aref ,request 3))
  4910. (defmacro org-element--request-parent (request)
  4911. "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
  4912. `(aref ,request 4))
  4913. (defmacro org-element--request-phase (request)
  4914. "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
  4915. `(aref ,request 5))
  4916. (defmacro org-element--format-element (element)
  4917. "Format ELEMENT for printing in diagnostics."
  4918. `(let ((print-length 50)
  4919. (print-level 5))
  4920. (prin1-to-string ,element)))
  4921. (defmacro org-element--cache-log-message (format-string &rest args)
  4922. "Add a new log message for org-element-cache."
  4923. `(when (or org-element--cache-diagnostics
  4924. (eq org-element--cache-self-verify 'backtrace))
  4925. (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
  4926. (buffer-name (current-buffer)))
  4927. ,format-string))
  4928. (format-string (funcall #'format format-string ,@args)))
  4929. (if org-element--cache-diagnostics
  4930. (display-warning 'org-element-cache format-string)
  4931. (unless org-element--cache-diagnostics-ring
  4932. (setq org-element--cache-diagnostics-ring
  4933. (make-ring org-element--cache-diagnostics-ring-size)))
  4934. (ring-insert org-element--cache-diagnostics-ring format-string)))))
  4935. (defmacro org-element--cache-warn (format-string &rest args)
  4936. "Raise warning for org-element-cache."
  4937. `(let* ((format-string (funcall #'format ,format-string ,@args))
  4938. (format-string
  4939. (if (or (not org-element--cache-diagnostics-ring)
  4940. (not (eq 'backtrace org-element--cache-self-verify)))
  4941. format-string
  4942. (prog1
  4943. (concat (format "Warning(%s): "
  4944. (buffer-name (current-buffer)))
  4945. format-string
  4946. "\nBacktrace:\n "
  4947. (mapconcat #'identity
  4948. (ring-elements org-element--cache-diagnostics-ring)
  4949. "\n "))
  4950. (setq org-element--cache-diagnostics-ring nil)))))
  4951. (if (and (boundp 'org-batch-test) org-batch-test)
  4952. (error "%s" (concat "org-element--cache: " format-string))
  4953. (display-warning 'org-element-cache
  4954. (concat "org-element--cache: " format-string)))))
  4955. (defsubst org-element--cache-key (element)
  4956. "Return a unique key for ELEMENT in cache tree.
  4957. Keys are used to keep a total order among elements in the cache.
  4958. Comparison is done with `org-element--cache-key-less-p'.
  4959. When no synchronization is taking place, a key is simply the
  4960. beginning position of the element, or that position plus one in
  4961. the case of an first item (respectively row) in
  4962. a list (respectively a table). They key of a section is its beginning
  4963. position minus one.
  4964. During a synchronization, the key is the one the element had when
  4965. the cache was synchronized for the last time. Elements added to
  4966. cache during the synchronization get a new key generated with
  4967. `org-element--cache-generate-key'.
  4968. Such keys are stored inside the element property
  4969. `:org-element--cache-sync-key'. The property is a cons containing
  4970. current `org-element--cache-sync-keys-value' and the element key."
  4971. (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
  4972. (cdr (org-element-property :org-element--cache-sync-key element)))
  4973. (let* ((begin (org-element-property :begin element))
  4974. ;; Increase beginning position of items (respectively
  4975. ;; table rows) by one, so the first item can get
  4976. ;; a different key from its parent list (respectively
  4977. ;; table).
  4978. (key (if (memq (org-element-type element) '(item table-row))
  4979. (1+ begin)
  4980. ;; Decrease beginning position of sections by one,
  4981. ;; so that the first element of the section get
  4982. ;; different key from the parent section.
  4983. (if (eq (org-element-type element) 'section)
  4984. (1- begin)
  4985. (if (eq (org-element-type element) 'org-data)
  4986. (- begin 2)
  4987. begin)))))
  4988. (when org-element--cache-sync-requests
  4989. (org-element-put-property
  4990. element
  4991. :org-element--cache-sync-key
  4992. (cons org-element--cache-sync-keys-value key)))
  4993. key)))
  4994. (defun org-element--cache-generate-key (lower upper)
  4995. "Generate a key between LOWER and UPPER.
  4996. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4997. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4998. a unique key, as an integer or a list of integers, according to
  4999. the following rules:
  5000. - LOWER and UPPER are compared level-wise until values differ.
  5001. - If, at a given level, LOWER and UPPER differ from more than
  5002. 2, the new key shares all the levels above with LOWER and
  5003. gets a new level. Its value is the mean between LOWER and
  5004. UPPER:
  5005. (1 2) + (1 4) --> (1 3)
  5006. - If LOWER has no value to compare with, it is assumed that its
  5007. value is `most-negative-fixnum'. E.g.,
  5008. (1 1) + (1 1 2)
  5009. is equivalent to
  5010. (1 1 m) + (1 1 2)
  5011. where m is `most-negative-fixnum'. Likewise, if UPPER is
  5012. short of levels, the current value is `most-positive-fixnum'.
  5013. - If they differ from only one, the new key inherits from
  5014. current LOWER level and fork it at the next level. E.g.,
  5015. (2 1) + (3 3)
  5016. is equivalent to
  5017. (2 1) + (2 M)
  5018. where M is `most-positive-fixnum'.
  5019. - If the key is only one level long, it is returned as an
  5020. integer:
  5021. (1 2) + (3 2) --> 2
  5022. When they are not equals, the function assumes that LOWER is
  5023. lesser than UPPER, per `org-element--cache-key-less-p'."
  5024. (if (equal lower upper) lower
  5025. (let ((lower (if (integerp lower) (list lower) lower))
  5026. (upper (if (integerp upper) (list upper) upper))
  5027. skip-upper key)
  5028. (catch 'exit
  5029. (while t
  5030. (let ((min (or (car lower) most-negative-fixnum))
  5031. (max (cond (skip-upper most-positive-fixnum)
  5032. ((car upper))
  5033. (t most-positive-fixnum))))
  5034. (if (< (1+ min) max)
  5035. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  5036. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  5037. (when (and (< min max) (not skip-upper))
  5038. ;; When at a given level, LOWER and UPPER differ from
  5039. ;; 1, ignore UPPER altogether. Instead create a key
  5040. ;; between LOWER and the greatest key with the same
  5041. ;; prefix as LOWER so far.
  5042. (setq skip-upper t))
  5043. (push min key)
  5044. (setq lower (cdr lower) upper (cdr upper)))))))))
  5045. (defsubst org-element--cache-key-less-p (a b)
  5046. "Non-nil if key A is less than key B.
  5047. A and B are either integers or lists of integers, as returned by
  5048. `org-element--cache-key'.
  5049. Note that it is not reliable to compare buffer position with the cache
  5050. keys. They keys may be larger compared to actual element :begin
  5051. position."
  5052. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  5053. (if (integerp b) (< (car a) b)
  5054. (catch 'exit
  5055. (while (and a b)
  5056. (cond ((car-less-than-car a b) (throw 'exit t))
  5057. ((car-less-than-car b a) (throw 'exit nil))
  5058. (t (setq a (cdr a) b (cdr b)))))
  5059. ;; If A is empty, either keys are equal (B is also empty) and
  5060. ;; we return nil, or A is lesser than B (B is longer) and we
  5061. ;; return a non-nil value.
  5062. ;;
  5063. ;; If A is not empty, B is necessarily empty and A is greater
  5064. ;; than B (A is longer). Therefore, return nil.
  5065. (and (null a) b)))))
  5066. (defun org-element--cache-compare (a b)
  5067. "Non-nil when element A is located before element B."
  5068. (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
  5069. (defsubst org-element--cache-root ()
  5070. "Return root value in `org-element--cache' .
  5071. This function assumes `org-element--cache' is a valid AVL tree."
  5072. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  5073. (defsubst org-element--headline-cache-root ()
  5074. "Return root value in `org-element--headline-cache' .
  5075. This function assumes `org-element--headline-cache' is a valid AVL tree."
  5076. (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
  5077. ;;;; Tools
  5078. ;; FIXME: Ideally, this should be inlined to avoid overheads, but
  5079. ;; inlined functions should be declared before the code that uses them
  5080. ;; and some code above does use `org-element--cache-active-p'. Moving this
  5081. ;; declaration on top would require restructuring the whole cache
  5082. ;; section.
  5083. (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
  5084. "Non-nil when cache is active in current buffer."
  5085. (and org-element-use-cache
  5086. org-element--cache
  5087. (or called-from-cache-change-func-p
  5088. (eq org-element--cache-change-tic (buffer-chars-modified-tick))
  5089. (and
  5090. ;; org-num-mode calls some Org structure analysis functions
  5091. ;; that can trigger cache update in the middle of changes. See
  5092. ;; `org-num--verify' calling `org-num--skip-value' calling
  5093. ;; `org-entry-get' that uses cache.
  5094. ;; Forcefully disable cache when called from inside a
  5095. ;; modification hook, where `inhibit-modification-hooks' is set
  5096. ;; to t.
  5097. (not inhibit-modification-hooks)
  5098. ;; `combine-change-calls' sets `after-change-functions' to
  5099. ;; nil. We need not to use cache inside
  5100. ;; `combine-change-calls' because the buffer is potentially
  5101. ;; changed without notice (the change will be registered
  5102. ;; after exiting the `combine-change-calls' body though).
  5103. (memq #'org-element--cache-after-change after-change-functions)))))
  5104. ;; FIXME: Remove after we establish that hashing is effective.
  5105. (defun org-element-cache-hash-show-statistics ()
  5106. "Display efficiency of O(1) query cache for `org-element--cache-find'.
  5107. This extra caching is based on the following paper:
  5108. Pugh [Information Processing Letters] (1990) Slow optimally balanced
  5109. search strategies vs. cached fast uniformly balanced search
  5110. strategies. http://dx.doi.org/10.1016/0020-0190(90)90130-P
  5111. Also, see `org-element--cache-size'."
  5112. (interactive)
  5113. (message "%.2f%% of cache searches hashed, %.2f%% non-hashable."
  5114. (* 100
  5115. (/ (float (car org-element--cache-hash-statistics))
  5116. (cdr org-element--cache-hash-statistics)))
  5117. (* 100
  5118. (/ (float org-element--cache-hash-nocache)
  5119. (cdr org-element--cache-hash-statistics)))))
  5120. (defun org-element--cache-find (pos &optional side)
  5121. "Find element in cache starting at POS or before.
  5122. POS refers to a buffer position.
  5123. When optional argument SIDE is non-nil, the function checks for
  5124. elements starting at or past POS instead. If SIDE is `both', the
  5125. function returns a cons cell where car is the first element
  5126. starting at or before POS and cdr the first element starting
  5127. after POS.
  5128. The function can only find elements in the synchronized part of
  5129. the cache."
  5130. (with-current-buffer (or (buffer-base-buffer) (current-buffer))
  5131. (let* ((limit (and org-element--cache-sync-requests
  5132. (org-element--request-key (car org-element--cache-sync-requests))))
  5133. (node (org-element--cache-root))
  5134. (hash-pos (unless (eq side 'both)
  5135. (mod (org-knuth-hash pos)
  5136. org-element--cache-hash-size)))
  5137. (hashed (if (not side)
  5138. (aref org-element--cache-hash-left hash-pos)
  5139. (unless (eq side 'both)
  5140. (aref org-element--cache-hash-right hash-pos))))
  5141. lower upper)
  5142. ;; `org-element--cache-key-less-p' does not accept markers.
  5143. (when (markerp pos) (setq pos (marker-position pos)))
  5144. (cl-incf (cdr org-element--cache-hash-statistics))
  5145. (when (eq side 'both) (cl-incf org-element--cache-hash-nocache))
  5146. (if (and hashed (not (eq side 'both))
  5147. (or (not limit)
  5148. ;; Limit can be a list key.
  5149. (org-element--cache-key-less-p
  5150. (org-element--cache-key hashed)
  5151. limit))
  5152. (= pos (org-element-property :begin hashed))
  5153. ;; We cannot rely on element :begin for elements with
  5154. ;; children starting at the same pos.
  5155. (not (memq (org-element-type hashed)
  5156. '(section org-data table)))
  5157. (org-element-property :cached hashed))
  5158. (progn
  5159. (cl-incf (car org-element--cache-hash-statistics))
  5160. hashed)
  5161. (while node
  5162. (let* ((element (avl-tree--node-data node))
  5163. (begin (org-element-property :begin element)))
  5164. (cond
  5165. ((and limit
  5166. (not (org-element--cache-key-less-p
  5167. (org-element--cache-key element) limit)))
  5168. (setq node (avl-tree--node-left node)))
  5169. ((> begin pos)
  5170. (setq upper element
  5171. node (avl-tree--node-left node)))
  5172. ((or (< begin pos)
  5173. ;; If the element is section or org-data, we also need
  5174. ;; to check the following element.
  5175. (memq (org-element-type element) '(section org-data)))
  5176. (setq lower element
  5177. node (avl-tree--node-right node)))
  5178. ;; We found an element in cache starting at POS. If `side'
  5179. ;; is `both' we also want the next one in order to generate
  5180. ;; a key in-between.
  5181. ;;
  5182. ;; If the element is the first row or item in a table or
  5183. ;; a plain list, we always return the table or the plain
  5184. ;; list.
  5185. ;;
  5186. ;; In any other case, we return the element found.
  5187. ((eq side 'both)
  5188. (setq lower element)
  5189. (setq node (avl-tree--node-right node)))
  5190. ((and (memq (org-element-type element) '(item table-row))
  5191. (let ((parent (org-element-property :parent element)))
  5192. (and (= (org-element-property :begin element)
  5193. (org-element-property :contents-begin parent))
  5194. (setq node nil
  5195. lower parent
  5196. upper parent)))))
  5197. (t
  5198. (setq node nil
  5199. lower element
  5200. upper element)))))
  5201. (if (not side)
  5202. (aset org-element--cache-hash-left hash-pos lower)
  5203. (unless (eq side 'both)
  5204. (aset org-element--cache-hash-right hash-pos lower)))
  5205. (pcase side
  5206. (`both (cons lower upper))
  5207. (`nil lower)
  5208. (_ upper))))))
  5209. (defun org-element--cache-put (element)
  5210. "Store ELEMENT in current buffer's cache, if allowed."
  5211. (when (org-element--cache-active-p)
  5212. (when org-element--cache-sync-requests
  5213. ;; During synchronization, first build an appropriate key for
  5214. ;; the new element so `avl-tree-enter' can insert it at the
  5215. ;; right spot in the cache.
  5216. (let* ((keys (org-element--cache-find
  5217. (org-element-property :begin element) 'both))
  5218. (new-key (org-element--cache-generate-key
  5219. (and (car keys) (org-element--cache-key (car keys)))
  5220. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  5221. (org-element--cache-sync-requests
  5222. (org-element--request-key (car org-element--cache-sync-requests)))))))
  5223. (org-element-put-property
  5224. element
  5225. :org-element--cache-sync-key
  5226. (cons org-element--cache-sync-keys-value new-key))))
  5227. (when (>= org-element--cache-diagnostics-level 2)
  5228. (org-element--cache-log-message
  5229. "Added new element with %S key: %S"
  5230. (org-element-property :org-element--cache-sync-key element)
  5231. (org-element--format-element element)))
  5232. (org-element-put-property element :cached t)
  5233. (when (memq (org-element-type element) '(headline inlinetask))
  5234. (cl-incf org-element--headline-cache-size)
  5235. (avl-tree-enter org-element--headline-cache element))
  5236. (cl-incf org-element--cache-size)
  5237. (avl-tree-enter org-element--cache element)))
  5238. (defsubst org-element--cache-remove (element)
  5239. "Remove ELEMENT from cache.
  5240. Assume ELEMENT belongs to cache and that a cache is active."
  5241. (org-element-put-property element :cached nil)
  5242. (cl-decf org-element--cache-size)
  5243. ;; Invalidate contents of parent.
  5244. (when (and (org-element-property :parent element)
  5245. (org-element-contents (org-element-property :parent element)))
  5246. (org-element-set-contents (org-element-property :parent element) nil))
  5247. (when (memq (org-element-type element) '(headline inlinetask))
  5248. (cl-decf org-element--headline-cache-size)
  5249. (avl-tree-delete org-element--headline-cache element))
  5250. (or (avl-tree-delete org-element--cache element)
  5251. (progn
  5252. ;; This should not happen, but if it is, would be better to know
  5253. ;; where it happens.
  5254. (org-element--cache-warn
  5255. "Failed to delete %S element in %S at %S. The element cache key was %S.
  5256. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5257. (org-element-type element)
  5258. (current-buffer)
  5259. (org-element-property :begin element)
  5260. (org-element-property :org-element--cache-sync-key element))
  5261. (org-element-cache-reset)
  5262. (throw 'quit nil))))
  5263. ;;;; Synchronization
  5264. (defsubst org-element--cache-set-timer (buffer)
  5265. "Set idle timer for cache synchronization in BUFFER."
  5266. (when org-element--cache-sync-timer
  5267. (cancel-timer org-element--cache-sync-timer))
  5268. (setq org-element--cache-sync-timer
  5269. (run-with-idle-timer
  5270. (let ((idle (current-idle-time)))
  5271. (if idle (time-add idle org-element-cache-sync-break)
  5272. org-element-cache-sync-idle-time))
  5273. nil
  5274. #'org-element--cache-sync
  5275. buffer)))
  5276. (defsubst org-element--cache-interrupt-p (time-limit)
  5277. "Non-nil when synchronization process should be interrupted.
  5278. TIME-LIMIT is a time value or nil."
  5279. (and time-limit
  5280. (or (input-pending-p)
  5281. (time-less-p time-limit nil))))
  5282. (defsubst org-element--cache-shift-positions (element offset &optional props)
  5283. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  5284. Properties containing buffer positions are `:begin', `:end',
  5285. `:contents-begin', `:contents-end' and `:structure'. When
  5286. optional argument PROPS is a list of keywords, only shift
  5287. properties provided in that list.
  5288. Properties are modified by side-effect."
  5289. (let ((properties (nth 1 element)))
  5290. ;; Shift `:structure' property for the first plain list only: it
  5291. ;; is the only one that really matters and it prevents from
  5292. ;; shifting it more than once.
  5293. (when (and (or (not props) (memq :structure props))
  5294. (eq (org-element-type element) 'plain-list)
  5295. (not (eq (org-element-type (plist-get properties :parent)) 'item)))
  5296. (dolist (item (plist-get properties :structure))
  5297. (cl-incf (car item) offset)
  5298. (cl-incf (nth 6 item) offset)))
  5299. (dolist (key '( :begin :contents-begin :contents-end :end
  5300. :post-affiliated :robust-begin :robust-end))
  5301. (let ((value (and (or (not props) (memq key props))
  5302. (plist-get properties key))))
  5303. (and value (plist-put properties key (+ offset value)))))))
  5304. (defvar org-element--cache-interrupt-C-g t
  5305. "When non-nil, allow the user to abort `org-element--cache-sync'.
  5306. The execution is aborted upon pressing `\\[keyboard-quit]'
  5307. `org-element--cache-interrupt-C-g-max-count' times.")
  5308. (defvar org-element--cache-interrupt-C-g-max-count 5
  5309. "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
  5310. See `org-element--cache-interrupt-C-g'.")
  5311. (defvar org-element--cache-interrupt-C-g-count 0
  5312. "Current number of `org-element--cache-sync' calls.
  5313. See `org-element--cache-interrupt-C-g'.")
  5314. (defvar org-element--cache-change-warning nil
  5315. "Non-nil when a sensitive line is about to be changed.
  5316. It is a symbol among nil, t, or a number representing smallest level of
  5317. modified headline. The level considers headline levels both before
  5318. and after the modification.")
  5319. (defun org-element--cache-sync (buffer &optional threshold future-change offset)
  5320. "Synchronize cache with recent modification in BUFFER.
  5321. When optional argument THRESHOLD is non-nil, do the
  5322. synchronization for all elements starting before or at threshold,
  5323. then exit. Otherwise, synchronize cache for as long as
  5324. `org-element-cache-sync-duration' or until Emacs leaves idle
  5325. state.
  5326. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  5327. not registered yet in the cache are going to happen. OFFSET is the
  5328. change offset. It is used in `org-element--cache-submit-request',
  5329. where cache is partially updated before current modification are
  5330. actually submitted."
  5331. (when (buffer-live-p buffer)
  5332. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  5333. ;; Do not sync when, for example, in the middle of
  5334. ;; `combine-change-calls'. See the commentary inside
  5335. ;; `org-element--cache-active-p'.
  5336. (when (and org-element--cache-sync-requests (org-element--cache-active-p))
  5337. ;; Check if the buffer have been changed outside visibility of
  5338. ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
  5339. (if (/= org-element--cache-last-buffer-size (buffer-size))
  5340. (progn
  5341. (org-element--cache-warn
  5342. "Unregistered buffer modifications detected (%S != %S). Resetting.
  5343. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  5344. The buffer is: %s\n Current command: %S\n Backtrace:\n%S"
  5345. org-element--cache-last-buffer-size
  5346. (buffer-size)
  5347. (buffer-name (current-buffer))
  5348. this-command
  5349. (when (and (fboundp 'backtrace-get-frames)
  5350. (fboundp 'backtrace-to-string))
  5351. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  5352. (org-element-cache-reset))
  5353. (let ((inhibit-quit t) request next)
  5354. (setq org-element--cache-interrupt-C-g-count 0)
  5355. (when org-element--cache-sync-timer
  5356. (cancel-timer org-element--cache-sync-timer))
  5357. (let ((time-limit (time-add nil org-element-cache-sync-duration)))
  5358. (catch 'org-element--cache-interrupt
  5359. (when org-element--cache-sync-requests
  5360. (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
  5361. (while org-element--cache-sync-requests
  5362. (setq request (car org-element--cache-sync-requests)
  5363. next (nth 1 org-element--cache-sync-requests))
  5364. (org-element--cache-process-request
  5365. request
  5366. (when next (org-element--request-key next))
  5367. threshold
  5368. (unless threshold time-limit)
  5369. future-change
  5370. offset)
  5371. ;; Re-assign current and next requests. It could have
  5372. ;; been altered during phase 1.
  5373. (setq request (car org-element--cache-sync-requests)
  5374. next (nth 1 org-element--cache-sync-requests))
  5375. ;; Request processed. Merge current and next offsets and
  5376. ;; transfer ending position.
  5377. (when next
  5378. ;; The following requests can only be either phase 1
  5379. ;; or phase 2 requests. We need to let them know
  5380. ;; that additional shifting happened ahead of them.
  5381. (cl-incf (org-element--request-offset next) (org-element--request-offset request))
  5382. (org-element--cache-log-message
  5383. "Updating next request offset to %S: %s"
  5384. (org-element--request-offset next)
  5385. (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
  5386. ;; FIXME: END part of the request only matters for
  5387. ;; phase 0 requests. However, the only possible
  5388. ;; phase 0 request must be the first request in the
  5389. ;; list all the time. END position should be
  5390. ;; unused.
  5391. (setf (org-element--request-end next) (org-element--request-end request)))
  5392. (setq org-element--cache-sync-requests
  5393. (cdr org-element--cache-sync-requests)))))
  5394. ;; If more requests are awaiting, set idle timer accordingly.
  5395. ;; Otherwise, reset keys.
  5396. (if org-element--cache-sync-requests
  5397. (org-element--cache-set-timer buffer)
  5398. (setq org-element--cache-change-warning nil)
  5399. (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value)))))))))
  5400. (defun org-element--cache-process-request
  5401. (request next-request-key threshold time-limit future-change offset)
  5402. "Process synchronization REQUEST for all entries before NEXT.
  5403. REQUEST is a vector, built by `org-element--cache-submit-request'.
  5404. NEXT-REQUEST-KEY is a cache key of the next request, as returned by
  5405. `org-element--cache-key'.
  5406. When non-nil, THRESHOLD is a buffer position. Synchronization
  5407. stops as soon as a shifted element begins after it.
  5408. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  5409. after this time or when Emacs exits idle state.
  5410. When non-nil, FUTURE-CHANGE is a buffer position where changes not
  5411. registered yet in the cache are going to happen. OFFSET is the
  5412. changed text length. See `org-element--cache-submit-request' for more
  5413. information.
  5414. Throw `org-element--cache-interrupt' if the process stops before
  5415. completing the request."
  5416. (org-element--cache-log-message
  5417. "org-element-cache: Processing request %s up to %S-%S, next: %S"
  5418. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5419. future-change
  5420. threshold
  5421. next-request-key)
  5422. (catch 'org-element--cache-quit
  5423. (when (= (org-element--request-phase request) 0)
  5424. ;; Phase 0.
  5425. ;;
  5426. ;; Delete all elements starting after beginning of the element
  5427. ;; with request key NEXT, but not after buffer position END.
  5428. ;;
  5429. ;; At each iteration, we start again at tree root since
  5430. ;; a deletion modifies structure of the balanced tree.
  5431. (org-element--cache-log-message "Phase 0")
  5432. (catch 'org-element--cache-end-phase
  5433. (let ((deletion-count 0))
  5434. (while t
  5435. (when (org-element--cache-interrupt-p time-limit)
  5436. (org-element--cache-log-message "Interrupt: time limit")
  5437. (throw 'org-element--cache-interrupt nil))
  5438. (let ((request-key (org-element--request-key request))
  5439. (end (org-element--request-end request))
  5440. (node (org-element--cache-root))
  5441. data data-key)
  5442. ;; Find first element in cache with key REQUEST-KEY or
  5443. ;; after it.
  5444. (while node
  5445. (let* ((element (avl-tree--node-data node))
  5446. (key (org-element--cache-key element)))
  5447. (cond
  5448. ((org-element--cache-key-less-p key request-key)
  5449. (setq node (avl-tree--node-right node)))
  5450. ((org-element--cache-key-less-p request-key key)
  5451. (setq data element
  5452. data-key key
  5453. node (avl-tree--node-left node)))
  5454. (t (setq data element
  5455. data-key key
  5456. node nil)))))
  5457. (if data
  5458. ;; We found first element in cache starting at or
  5459. ;; after REQUEST-KEY.
  5460. (let ((pos (org-element-property :begin data)))
  5461. ;; FIXME: Maybe simply (< pos end)?
  5462. (if (<= pos end)
  5463. (progn
  5464. (org-element--cache-log-message "removing %S::%S"
  5465. (org-element-property :org-element--cache-sync-key data)
  5466. (org-element--format-element data))
  5467. (cl-incf deletion-count)
  5468. (org-element--cache-remove data)
  5469. (when (and (> (log org-element--cache-size 2) 10)
  5470. (> deletion-count
  5471. (/ org-element--cache-size (log org-element--cache-size 2))))
  5472. (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
  5473. deletion-count
  5474. org-element--cache-size
  5475. (log org-element--cache-size 2))
  5476. (org-element-cache-reset)
  5477. (throw 'org-element--cache-quit t)))
  5478. ;; Done deleting everything starting before END.
  5479. ;; DATA-KEY is the first known element after END.
  5480. ;; Move on to phase 1.
  5481. (org-element--cache-log-message
  5482. "found element after %S: %S::%S"
  5483. end
  5484. (org-element-property :org-element--cache-sync-key data)
  5485. (org-element--format-element data))
  5486. (setf (org-element--request-key request) data-key)
  5487. (setf (org-element--request-beg request) pos)
  5488. (setf (org-element--request-phase request) 1)
  5489. (throw 'org-element--cache-end-phase nil)))
  5490. ;; No element starting after modifications left in
  5491. ;; cache: further processing is futile.
  5492. (org-element--cache-log-message
  5493. "Phase 0 deleted all elements in cache after %S!"
  5494. request-key)
  5495. (throw 'org-element--cache-quit t)))))))
  5496. (when (= (org-element--request-phase request) 1)
  5497. ;; Phase 1.
  5498. ;;
  5499. ;; Phase 0 left a hole in the cache. Some elements after it
  5500. ;; could have parents within. For example, in the following
  5501. ;; buffer:
  5502. ;;
  5503. ;; - item
  5504. ;;
  5505. ;;
  5506. ;; Paragraph1
  5507. ;;
  5508. ;; Paragraph2
  5509. ;;
  5510. ;; if we remove a blank line between "item" and "Paragraph1",
  5511. ;; everything down to "Paragraph2" is removed from cache. But
  5512. ;; the paragraph now belongs to the list, and its `:parent'
  5513. ;; property no longer is accurate.
  5514. ;;
  5515. ;; Therefore we need to parse again elements in the hole, or at
  5516. ;; least in its last section, so that we can re-parent
  5517. ;; subsequent elements, during phase 2.
  5518. ;;
  5519. ;; Note that we only need to get the parent from the first
  5520. ;; element in cache after the hole.
  5521. ;;
  5522. ;; When next key is lesser or equal to the current one, current
  5523. ;; request is inside a to-be-shifted part of the cache. It is
  5524. ;; fine because the order of elements will not be altered by
  5525. ;; shifting. However, we cannot know the real position of the
  5526. ;; unshifted NEXT element in the current request. So, we need
  5527. ;; to sort the request list according to keys and re-start
  5528. ;; processing from the new leftmost request.
  5529. (org-element--cache-log-message "Phase 1")
  5530. (let ((key (org-element--request-key request)))
  5531. (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
  5532. ;; In theory, the only case when requests are not
  5533. ;; ordered is when key of the next request is either the
  5534. ;; same with current key or it is a key for a removed
  5535. ;; element. Either way, we can simply merge the two
  5536. ;; requests.
  5537. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5538. (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
  5539. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5540. (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
  5541. (setf (org-element--request-key next-request) key)
  5542. (setf (org-element--request-beg next-request) (org-element--request-beg request))
  5543. (setf (org-element--request-phase next-request) 1)
  5544. (throw 'org-element--cache-quit t))))
  5545. ;; Next element will start at its beginning position plus
  5546. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  5547. ;; contains the real beginning position of the first element to
  5548. ;; shift and re-parent.
  5549. (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request)))
  5550. cached-before)
  5551. (cond ((and threshold (> limit threshold))
  5552. (org-element--cache-log-message "Interrupt: position %S after threshold %S" limit threshold)
  5553. (throw 'org-element--cache-interrupt nil))
  5554. ((and future-change (>= limit future-change))
  5555. ;; Changes happened around this element and they will
  5556. ;; trigger another phase 1 request. Skip re-parenting
  5557. ;; and simply proceed with shifting (phase 2) to make
  5558. ;; sure that followup phase 0 request for the recent
  5559. ;; changes can operate on the correctly shifted cache.
  5560. (org-element--cache-log-message "position %S after future change %S" limit future-change)
  5561. (setf (org-element--request-parent request) nil)
  5562. (setf (org-element--request-phase request) 2))
  5563. (t
  5564. (when future-change
  5565. ;; Changes happened, but not yet registered after
  5566. ;; this element. However, we a not yet safe to look
  5567. ;; at the buffer and parse elements in the cache gap.
  5568. ;; Some of the parents to be added to cache may end
  5569. ;; after the changes. Parsing this parents will
  5570. ;; assign the :end correct value for cache state
  5571. ;; after future-change. Then, when the future change
  5572. ;; is going to be processed, such parent boundary
  5573. ;; will be altered unnecessarily. To avoid this,
  5574. ;; we alter the new parents by -OFFSET.
  5575. ;; For now, just save last known cached element and
  5576. ;; then check all the parents below.
  5577. (setq cached-before (org-element--cache-find (1- limit) nil)))
  5578. ;; No relevant changes happened after submitting this
  5579. ;; request. We are safe to look at the actual Org
  5580. ;; buffer and calculate the new parent.
  5581. (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
  5582. (when future-change
  5583. ;; Check all the newly added parents to not
  5584. ;; intersect with future change.
  5585. (let ((up parent))
  5586. (while (and up
  5587. (or (not cached-before)
  5588. (> (org-element-property :begin up)
  5589. (org-element-property :begin cached-before))))
  5590. (when (> (org-element-property :end up) future-change)
  5591. ;; Offset future cache request.
  5592. (org-element--cache-shift-positions
  5593. up (- offset)
  5594. (if (and (org-element-property :robust-begin up)
  5595. (org-element-property :robust-end up))
  5596. '(:contents-end :end :robust-end)
  5597. '(:contents-end :end))))
  5598. (setq up (org-element-property :parent up)))))
  5599. (org-element--cache-log-message
  5600. "New parent at %S: %S::%S"
  5601. limit
  5602. (org-element-property :org-element--cache-sync-key parent)
  5603. (org-element--format-element parent))
  5604. (setf (org-element--request-parent request) parent)
  5605. (setf (org-element--request-phase request) 2))))))
  5606. ;; Phase 2.
  5607. ;;
  5608. ;; Shift all elements starting from key START, but before NEXT, by
  5609. ;; OFFSET, and re-parent them when appropriate.
  5610. ;;
  5611. ;; Elements are modified by side-effect so the tree structure
  5612. ;; remains intact.
  5613. ;;
  5614. ;; Once THRESHOLD, if any, is reached, or once there is an input
  5615. ;; pending, exit. Before leaving, the current synchronization
  5616. ;; request is updated.
  5617. (org-element--cache-log-message "Phase 2")
  5618. (let ((start (org-element--request-key request))
  5619. (offset (org-element--request-offset request))
  5620. (parent (org-element--request-parent request))
  5621. (node (org-element--cache-root))
  5622. (stack (list nil))
  5623. (leftp t)
  5624. exit-flag continue-flag)
  5625. ;; No re-parenting nor shifting planned: request is over.
  5626. (when (and (not parent) (zerop offset))
  5627. (org-element--cache-log-message "Empty offset. Request completed.")
  5628. (throw 'org-element--cache-quit t))
  5629. (while node
  5630. (let* ((data (avl-tree--node-data node))
  5631. (key (org-element--cache-key data)))
  5632. ;; Traverse the cache tree. Ignore all the elements before
  5633. ;; START. Note that `avl-tree-stack' would not bypass the
  5634. ;; elements before START and thus would have beeen less
  5635. ;; efficient.
  5636. (if (and leftp (avl-tree--node-left node)
  5637. (not (org-element--cache-key-less-p key start)))
  5638. (progn (push node stack)
  5639. (setq node (avl-tree--node-left node)))
  5640. ;; Shift and re-parent when current node starts at or
  5641. ;; after START, but before NEXT.
  5642. (unless (org-element--cache-key-less-p key start)
  5643. ;; We reached NEXT. Request is complete.
  5644. (when (and next-request-key
  5645. (not (org-element--cache-key-less-p key next-request-key)))
  5646. (org-element--cache-log-message "Reached next request.")
  5647. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5648. (unless (and (org-element-property :cached (org-element--request-parent next-request))
  5649. (org-element-property :begin (org-element--request-parent next-request))
  5650. parent
  5651. (> (org-element-property :begin (org-element--request-parent next-request))
  5652. (org-element-property :begin parent)))
  5653. (setf (org-element--request-parent next-request) parent)))
  5654. (throw 'org-element--cache-quit t))
  5655. ;; Handle interruption request. Update current request.
  5656. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  5657. (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
  5658. (setf (org-element--request-key request) key)
  5659. (setf (org-element--request-parent request) parent)
  5660. (throw 'org-element--cache-interrupt nil))
  5661. ;; Shift element.
  5662. (unless (zerop offset)
  5663. (when (>= org-element--cache-diagnostics-level 3)
  5664. (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
  5665. offset
  5666. (org-element-property :org-element--cache-sync-key data)
  5667. (org-element--format-element data)))
  5668. (org-element--cache-shift-positions data offset))
  5669. (let ((begin (org-element-property :begin data)))
  5670. ;; Update PARENT and re-parent DATA, only when
  5671. ;; necessary. Propagate new structures for lists.
  5672. (while (and parent
  5673. (<= (org-element-property :end parent) begin))
  5674. (setq parent (org-element-property :parent parent)))
  5675. (cond ((and (not parent) (zerop offset)) (throw 'org-element--cache-quit nil))
  5676. ;; Consider scenario when DATA lays within
  5677. ;; sensitive lines of PARENT that was found
  5678. ;; during phase 2. For example:
  5679. ;;
  5680. ;; #+ begin_quote
  5681. ;; Paragraph
  5682. ;; #+end_quote
  5683. ;;
  5684. ;; In the above source block, remove space in
  5685. ;; the first line will trigger re-parenting of
  5686. ;; the paragraph and "#+end_quote" that is also
  5687. ;; considered paragraph before the modification.
  5688. ;; However, the paragraph element stored in
  5689. ;; cache must be deleted instead.
  5690. ((and parent
  5691. (or (not (memq (org-element-type parent) org-element-greater-elements))
  5692. (and (org-element-property :contents-begin parent)
  5693. (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
  5694. (and (org-element-property :contents-end parent)
  5695. (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
  5696. (> (org-element-property :end data) (org-element-property :end parent))
  5697. (and (org-element-property :contents-end data)
  5698. (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
  5699. (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
  5700. (org-element-property :org-element--cache-sync-key data)
  5701. (org-element--format-element data))
  5702. (org-element--cache-remove data)
  5703. ;; We altered the tree structure. The tree
  5704. ;; traversal needs to be restarted.
  5705. (setf (org-element--request-key request) key)
  5706. (setf (org-element--request-parent request) parent)
  5707. ;; Restart tree traversal.
  5708. (setq node (org-element--cache-root)
  5709. stack (list nil)
  5710. leftp t
  5711. begin -1
  5712. continue-flag t))
  5713. ((and parent
  5714. (not (eq parent data))
  5715. (let ((p (org-element-property :parent data)))
  5716. (or (not p)
  5717. (< (org-element-property :begin p)
  5718. (org-element-property :begin parent))
  5719. (unless (eq p parent)
  5720. (not (org-element-property :cached p))
  5721. ;; (not (avl-tree-member-p org-element--cache p))
  5722. ))))
  5723. (org-element--cache-log-message
  5724. "Updating parent in %S\n Old parent: %S\n New parent: %S"
  5725. (org-element--format-element data)
  5726. (org-element--format-element (org-element-property :parent data))
  5727. (org-element--format-element parent))
  5728. (when (and (eq 'org-data (org-element-type parent))
  5729. (not (eq 'headline (org-element-type data))))
  5730. ;; FIXME: This check is here to see whether
  5731. ;; such error happens within
  5732. ;; `org-element--cache-process-request' or somewhere
  5733. ;; else.
  5734. (org-element--cache-warn
  5735. "Added org-data parent to non-headline element: %S
  5736. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5737. data)
  5738. (org-element-cache-reset)
  5739. (throw 'org-element--cache-quit t))
  5740. (org-element-put-property data :parent parent)
  5741. (let ((s (org-element-property :structure parent)))
  5742. (when (and s (org-element-property :structure data))
  5743. (org-element-put-property data :structure s)))))
  5744. ;; Cache is up-to-date past THRESHOLD. Request
  5745. ;; interruption.
  5746. (when (and threshold (> begin threshold))
  5747. (org-element--cache-log-message "Reached threshold %S: %S"
  5748. threshold
  5749. (org-element--format-element data))
  5750. (setq exit-flag t))))
  5751. (if continue-flag
  5752. (setq continue-flag nil)
  5753. (setq node (if (setq leftp (avl-tree--node-right node))
  5754. (avl-tree--node-right node)
  5755. (pop stack)))))))
  5756. ;; We reached end of tree: synchronization complete.
  5757. t))
  5758. (org-element--cache-log-message
  5759. "org-element-cache: Finished process. The cache size is %S. The remaining sync requests: %S"
  5760. org-element--cache-size
  5761. (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests))))
  5762. (defsubst org-element--open-end-p (element)
  5763. "Check if ELEMENT in current buffer contains extra blank lines after
  5764. it and does not have closing term.
  5765. Examples of such elements are: section, headline, org-data,
  5766. and footnote-definition."
  5767. (and (org-element-property :contents-end element)
  5768. (= (org-element-property :contents-end element)
  5769. (save-excursion
  5770. (goto-char (org-element-property :end element))
  5771. (skip-chars-backward " \r\n\t")
  5772. (line-beginning-position 2)))))
  5773. (defun org-element--parse-to (pos &optional syncp time-limit)
  5774. "Parse elements in current section, down to POS.
  5775. Start parsing from the closest between the last known element in
  5776. cache or headline above. Return the smallest element containing
  5777. POS.
  5778. When optional argument SYNCP is non-nil, return the parent of the
  5779. element containing POS instead. In that case, it is also
  5780. possible to provide TIME-LIMIT, which is a time value specifying
  5781. when the parsing should stop. The function throws
  5782. `org-element--cache-interrupt' if the process stopped before finding
  5783. the expected result."
  5784. (catch 'exit
  5785. (save-match-data
  5786. (org-with-wide-buffer
  5787. (goto-char pos)
  5788. (save-excursion
  5789. (end-of-line)
  5790. (skip-chars-backward " \r\t\n")
  5791. ;; Within blank lines at the beginning of buffer, return nil.
  5792. (when (bobp) (throw 'exit nil)))
  5793. (let* ((cached (and (org-element--cache-active-p)
  5794. (org-element--cache-find pos nil)))
  5795. (mode (org-element-property :mode cached))
  5796. element next)
  5797. (cond
  5798. ;; Nothing in cache before point: start parsing from first
  5799. ;; element in buffer down to POS or from the beginning of the
  5800. ;; file.
  5801. ((and (not cached) (org-element--cache-active-p))
  5802. (setq element (org-element-org-data-parser))
  5803. (unless (org-element-property :begin element)
  5804. (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
  5805. (org-element--cache-log-message
  5806. "Nothing in cache. Adding org-data: %S"
  5807. (org-element--format-element element))
  5808. (org-element--cache-put element)
  5809. (goto-char (org-element-property :contents-begin element))
  5810. (setq mode 'org-data))
  5811. ;; Nothing in cache before point because cache is not active.
  5812. ;; Parse from previous heading to avoid re-parsing the whole
  5813. ;; buffer above. This comes at the cost of not calculating
  5814. ;; `:parent' property for headings.
  5815. ((not cached)
  5816. (if (org-with-limited-levels (outline-previous-heading))
  5817. (progn
  5818. (setq element (org-element-headline-parser nil 'fast))
  5819. (setq mode 'planning)
  5820. (forward-line))
  5821. (setq element (org-element-org-data-parser))
  5822. (setq mode 'org-data))
  5823. (org-skip-whitespace)
  5824. (beginning-of-line))
  5825. ;; Check if CACHED or any of its ancestors contain point.
  5826. ;;
  5827. ;; If there is such an element, we inspect it in order to know
  5828. ;; if we return it or if we need to parse its contents.
  5829. ;; Otherwise, we just start parsing from location, which is
  5830. ;; right after the top-most element containing CACHED but
  5831. ;; still before POS.
  5832. ;;
  5833. ;; As a special case, if POS is at the end of the buffer, we
  5834. ;; want to return the innermost element ending there.
  5835. ;;
  5836. ;; Also, if we find an ancestor and discover that we need to
  5837. ;; parse its contents, make sure we don't start from
  5838. ;; `:contents-begin', as we would otherwise go past CACHED
  5839. ;; again. Instead, in that situation, we will resume parsing
  5840. ;; from NEXT, which is located after CACHED or its higher
  5841. ;; ancestor not containing point.
  5842. (t
  5843. (let ((up cached)
  5844. (pos (if (= (point-max) pos) (1- pos) pos)))
  5845. (while (and up (<= (org-element-property :end up) pos))
  5846. (goto-char (org-element-property :end up))
  5847. (setq element up
  5848. mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
  5849. up (org-element-property :parent up)
  5850. next (point)))
  5851. (when up (setq element up)))))
  5852. ;; Parse successively each element until we reach POS.
  5853. (let ((end (or (org-element-property :end element) (point-max)))
  5854. (parent (org-element-property :parent element)))
  5855. (while t
  5856. (when (org-element--cache-interrupt-p time-limit)
  5857. (throw 'org-element--cache-interrupt nil))
  5858. (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
  5859. (when quit-flag
  5860. (cl-incf org-element--cache-interrupt-C-g-count)
  5861. (setq quit-flag nil))
  5862. (when (>= org-element--cache-interrupt-C-g-count
  5863. org-element--cache-interrupt-C-g-max-count)
  5864. (setq quit-flag t)
  5865. (setq org-element--cache-interrupt-C-g-count 0)
  5866. (org-element-cache-reset)
  5867. (error "org-element: Parsing aborted by user. Cache has been cleared.
  5868. If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
  5869. (message (substitute-command-keys
  5870. "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
  5871. (- org-element--cache-interrupt-C-g-max-count
  5872. org-element--cache-interrupt-C-g-count)))
  5873. (unless element
  5874. ;; Do not try to parse within blank at EOB.
  5875. (unless (save-excursion
  5876. (org-skip-whitespace)
  5877. (eobp))
  5878. (org-element-with-disabled-cache
  5879. (setq element (org-element--current-element
  5880. end 'element mode
  5881. (org-element-property :structure parent)))))
  5882. ;; Make sure that we return referenced element in cache
  5883. ;; that can be altered directly.
  5884. (if element
  5885. (setq element (or (org-element--cache-put element) element))
  5886. ;; Nothing to parse (i.e. empty file).
  5887. (throw 'exit parent))
  5888. (unless (or (not (org-element--cache-active-p)) parent)
  5889. (org-element--cache-warn
  5890. "Got empty parent while parsing. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n Backtrace:\n%S"
  5891. (when (and (fboundp 'backtrace-get-frames)
  5892. (fboundp 'backtrace-to-string))
  5893. (backtrace-to-string (backtrace-get-frames 'backtrace))
  5894. (org-element-cache-reset)
  5895. (error "org-element--cache: Emergency exit"))))
  5896. (org-element-put-property element :parent parent))
  5897. (let ((elem-end (org-element-property :end element))
  5898. (type (org-element-type element)))
  5899. (cond
  5900. ;; Skip any element ending before point. Also skip
  5901. ;; element ending at point (unless it is also the end of
  5902. ;; buffer) since we're sure that another element begins
  5903. ;; after it.
  5904. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5905. ;; Avoid parsing headline siblings above.
  5906. (goto-char elem-end)
  5907. (when (eq type 'headline)
  5908. (save-match-data
  5909. (unless (when (and (/= 1 (org-element-property :level element))
  5910. (re-search-forward
  5911. (rx-to-string
  5912. `(and bol (repeat 1 ,(1- (let ((level (org-element-property :level element)))
  5913. (if org-odd-levels-only (1- (* level 2)) level)))
  5914. "*")
  5915. " "))
  5916. pos t))
  5917. (beginning-of-line)
  5918. t)
  5919. ;; There are headings with lower level than
  5920. ;; ELEMENT between ELEM-END and POS. Siblings
  5921. ;; may exist though. Parse starting from the
  5922. ;; last sibling or from ELEM-END if there are
  5923. ;; no other siblings.
  5924. (goto-char pos)
  5925. (unless
  5926. (re-search-backward
  5927. (rx-to-string
  5928. `(and bol (repeat ,(let ((level (org-element-property :level element)))
  5929. (if org-odd-levels-only (1- (* level 2)) level))
  5930. "*")
  5931. " "))
  5932. elem-end t)
  5933. ;; Roll-back to normal parsing.
  5934. (goto-char elem-end)))))
  5935. (setq mode (org-element--next-mode mode type nil)))
  5936. ;; A non-greater element contains point: return it.
  5937. ((not (memq type org-element-greater-elements))
  5938. (throw 'exit (if syncp parent element)))
  5939. ;; Otherwise, we have to decide if ELEMENT really
  5940. ;; contains POS. In that case we start parsing from
  5941. ;; contents' beginning.
  5942. ;;
  5943. ;; If POS is at contents' beginning but it is also at
  5944. ;; the beginning of the first item in a list or a table.
  5945. ;; In that case, we need to create an anchor for that
  5946. ;; list or table, so return it.
  5947. ;;
  5948. ;; Also, if POS is at the end of the buffer, no element
  5949. ;; can start after it, but more than one may end there.
  5950. ;; Arbitrarily, we choose to return the innermost of
  5951. ;; such elements.
  5952. ((let ((cbeg (org-element-property :contents-begin element))
  5953. (cend (org-element-property :contents-end element)))
  5954. (when (and cbeg cend
  5955. (or (< cbeg pos)
  5956. (and (= cbeg pos)
  5957. (not (memq type '(plain-list table)))))
  5958. (or (> cend pos)
  5959. ;; When we are at cend or within blank
  5960. ;; lines after, it is a special case:
  5961. ;; 1. At the end of buffer we return
  5962. ;; the innermost element.
  5963. ;; 2. At cend of element with return
  5964. ;; that element.
  5965. ;; 3. At the end of element, we would
  5966. ;; return in the earlier cond form.
  5967. ;; 4. Within blank lines after cend,
  5968. ;; when element does not have a
  5969. ;; closing keyword, we return that
  5970. ;; outermost element, unless the
  5971. ;; outermost element is a non-empty
  5972. ;; headline. In the latter case, we
  5973. ;; return the outermost element inside
  5974. ;; the headline section.
  5975. (and (org-element--open-end-p element)
  5976. (or (= (org-element-property :end element) (point-max))
  5977. (and (>= pos (org-element-property :contents-end element))
  5978. (memq (org-element-type element) '(org-data section headline)))))))
  5979. (goto-char (or next cbeg))
  5980. (setq mode (if next mode (org-element--next-mode mode type t))
  5981. next nil
  5982. parent element
  5983. end (if (org-element--open-end-p element)
  5984. (org-element-property :end element)
  5985. (org-element-property :contents-end element))))))
  5986. ;; Otherwise, return ELEMENT as it is the smallest
  5987. ;; element containing POS.
  5988. (t (throw 'exit (if syncp parent element)))))
  5989. (setq element nil))))))))
  5990. ;;;; Staging Buffer Changes
  5991. (defconst org-element--cache-sensitive-re
  5992. (concat
  5993. "^\\*+ " "\\|"
  5994. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5995. "^[ \t]*\\(?:"
  5996. "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
  5997. org-list-full-item-re "\\|"
  5998. ":\\(?: \\|$\\)" "\\|"
  5999. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  6000. "\\)")
  6001. "Regexp matching a sensitive line, structure wise.
  6002. A sensitive line is a headline, inlinetask, block, drawer, or
  6003. latex-environment boundary. When such a line is modified,
  6004. structure changes in the document may propagate in the whole
  6005. section, possibly making cache invalid.")
  6006. (defun org-element--cache-before-change (beg end)
  6007. "Detect modifications in sensitive parts of Org buffer.
  6008. BEG and END are the beginning and end of the range of changed
  6009. text. See `before-change-functions' for more information.
  6010. The function returns the new value of `org-element--cache-change-warning'."
  6011. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6012. (current-buffer))
  6013. (when (org-element--cache-active-p t)
  6014. (org-with-wide-buffer
  6015. (setq org-element--cache-change-tic (buffer-chars-modified-tick))
  6016. (setq org-element--cache-last-buffer-size (buffer-size))
  6017. (goto-char beg)
  6018. (beginning-of-line)
  6019. (let ((bottom (save-excursion
  6020. (goto-char end)
  6021. (if (and (bolp)
  6022. ;; When beg == end, still extent to eol.
  6023. (> (point) beg))
  6024. ;; FIXME: Potential pitfall.
  6025. ;; We are appending to an element end.
  6026. ;; Unless the last inserted char is not
  6027. ;; newline, the next element is not broken
  6028. ;; and does not need to be purged from the
  6029. ;; cache.
  6030. end
  6031. (line-end-position)))))
  6032. (prog1
  6033. ;; Use the worst change warning to not miss important edits.
  6034. ;; This function is called before edit and after edit by
  6035. ;; `org-element--cache-after-change'. Before the edit, we still
  6036. ;; want to use the old value if it comes from previous
  6037. ;; not yet processed edit (they may be merged by
  6038. ;; `org-element--cache-submit-request'). After the edit, we want to
  6039. ;; look if there was a sensitive removed during edit.
  6040. ;; FIXME: This is not the most efficient way and we now
  6041. ;; have to delete more elements than needed in some
  6042. ;; cases. A better approach may be storing the warning
  6043. ;; in the modification request itself.
  6044. (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
  6045. (org-element--cache-change-warning-after))
  6046. (setq org-element--cache-change-warning-after
  6047. (save-match-data
  6048. (let ((case-fold-search t))
  6049. (when (re-search-forward
  6050. org-element--cache-sensitive-re bottom t)
  6051. (goto-char beg)
  6052. (beginning-of-line)
  6053. (let (min-level)
  6054. (cl-loop while (re-search-forward
  6055. (rx-to-string
  6056. (if (and min-level
  6057. (> min-level 1))
  6058. `(and bol (repeat 1 ,(1- min-level) "*") " ")
  6059. `(and bol (+ "*") " ")))
  6060. bottom t)
  6061. do (setq min-level (1- (length (match-string 0))))
  6062. until (= min-level 1))
  6063. (goto-char beg)
  6064. (beginning-of-line)
  6065. (or (and min-level (org-reduced-level min-level))
  6066. (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
  6067. 'org-data)
  6068. t))))))
  6069. (setq org-element--cache-change-warning
  6070. (cond
  6071. ((and (numberp org-element--cache-change-warning-before)
  6072. (numberp org-element--cache-change-warning-after))
  6073. (min org-element--cache-change-warning-after
  6074. org-element--cache-change-warning-before))
  6075. ((numberp org-element--cache-change-warning-before)
  6076. org-element--cache-change-warning-before)
  6077. ((numberp org-element--cache-change-warning-after)
  6078. org-element--cache-change-warning-after)
  6079. (t (or org-element--cache-change-warning-after
  6080. org-element--cache-change-warning-before)))))
  6081. (org-element--cache-log-message
  6082. "%S is about to modify text: warning %S"
  6083. this-command
  6084. org-element--cache-change-warning)))))))
  6085. (defun org-element--cache-after-change (beg end pre)
  6086. "Update buffer modifications for current buffer.
  6087. BEG and END are the beginning and end of the range of changed
  6088. text, and the length in bytes of the pre-change text replaced by
  6089. that range. See `after-change-functions' for more information."
  6090. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6091. (current-buffer))
  6092. (when (org-element--cache-active-p t)
  6093. (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
  6094. (org-element--cache-log-message "After change")
  6095. (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
  6096. ;; If beg is right after spaces in front of an element, we
  6097. ;; risk affecting previous element, so move beg to bol, making
  6098. ;; sure that we capture preceding element.
  6099. (setq beg (save-excursion
  6100. (goto-char beg)
  6101. (cl-incf pre (- beg (line-beginning-position)))
  6102. (line-beginning-position)))
  6103. ;; Store synchronization request.
  6104. (let ((offset (- end beg pre)))
  6105. (save-match-data
  6106. (org-element--cache-submit-request beg (- end offset) offset)))
  6107. ;; Activate a timer to process the request during idle time.
  6108. (org-element--cache-set-timer (current-buffer))))))
  6109. (defun org-element--cache-setup-change-functions ()
  6110. "Setup `before-change-functions' and `after-change-functions'."
  6111. (when (and (derived-mode-p 'org-mode) org-element-use-cache)
  6112. (add-hook 'before-change-functions
  6113. #'org-element--cache-before-change nil t)
  6114. ;; Run `org-element--cache-after-change' early to handle cases
  6115. ;; when other `after-change-functions' require element cache.
  6116. (add-hook 'after-change-functions
  6117. #'org-element--cache-after-change -1 t)))
  6118. (defvar org-element--cache-avoid-synchronous-headline-re-parsing nil
  6119. "This variable controls how buffer changes are handled by the cache.
  6120. By default (when this variable is nil), cache re-parses modified
  6121. headlines immediately after modification preserving all the unaffected
  6122. elements inside the headline.
  6123. The default behaviour works best when users types inside Org buffer of
  6124. when buffer modifications are mixed with cache requests. However,
  6125. large automated edits inserting/deleting many headlines are somewhat
  6126. slower by default (as in `org-archive-subtree'). Let-binding this
  6127. variable to non-nil will reduce cache latency after every singular edit
  6128. (`after-change-functions') at the cost of slower cache queries.")
  6129. (defun org-element--cache-for-removal (beg end offset)
  6130. "Return first element to remove from cache.
  6131. BEG and END are buffer positions delimiting buffer modifications.
  6132. OFFSET is the size of the changes.
  6133. Returned element is usually the first element in cache containing
  6134. any position between BEG and END. As an exception, greater
  6135. elements around the changes that are robust to contents
  6136. modifications are preserved and updated according to the
  6137. changes. In the latter case, the returned element is the outermost
  6138. non-robust element affected by the changes. Note that the returned
  6139. element may end before END position in which case some cached element
  6140. starting after the returned may still be affected by the changes.
  6141. Also, when there are no elements in cache before BEG, return first
  6142. known element in cache (it may start after END)."
  6143. (let* ((elements (org-element--cache-find (1- beg) 'both))
  6144. (before (car elements))
  6145. (after (cdr elements)))
  6146. (if (not before) after
  6147. ;; If BEFORE is a keyword, it may need to be removed to become
  6148. ;; an affiliated keyword.
  6149. (when (eq 'keyword (org-element-type before))
  6150. (let ((prev before))
  6151. (while (eq 'keyword (org-element-type prev))
  6152. (setq before prev
  6153. beg (org-element-property :begin prev))
  6154. (setq prev (org-element--cache-find (1- (org-element-property :begin before)))))))
  6155. (let ((up before)
  6156. (robust-flag t))
  6157. (while up
  6158. (if (let ((type (org-element-type up)))
  6159. (or (and (memq type '( center-block dynamic-block
  6160. quote-block special-block
  6161. drawer))
  6162. (or (not (eq type 'drawer))
  6163. (not (string= "PROPERTIES" (org-element-property :drawer-name up))))
  6164. ;; Sensitive change. This is
  6165. ;; unconditionally non-robust change.
  6166. (not org-element--cache-change-warning)
  6167. (let ((cbeg (org-element-property :contents-begin up))
  6168. (cend (org-element-property :contents-end up)))
  6169. (and cbeg
  6170. (<= cbeg beg)
  6171. (or (> cend end)
  6172. (and (= cend end)
  6173. (= (+ end offset) (point-max)))))))
  6174. (and (memq type '(headline section org-data))
  6175. (let ((rbeg (org-element-property :robust-begin up))
  6176. (rend (org-element-property :robust-end up)))
  6177. (and rbeg rend
  6178. (<= rbeg beg)
  6179. (or (> rend end)
  6180. (and (= rend end)
  6181. (= (+ end offset) (point-max))))))
  6182. (pcase type
  6183. ;; Sensitive change in section. Need to
  6184. ;; re-parse.
  6185. (`section (not org-element--cache-change-warning))
  6186. ;; Headline might be inserted. This is non-robust
  6187. ;; change when `up' is a `headline' or `section'
  6188. ;; with `>' level compared to the inserted headline.
  6189. ;;
  6190. ;; Also, planning info/property drawer
  6191. ;; could have been inserted. It is not
  6192. ;; robust change then.
  6193. (`headline
  6194. (and
  6195. (or (not (numberp org-element--cache-change-warning))
  6196. (> org-element--cache-change-warning
  6197. (org-element-property :level up)))
  6198. (org-with-point-at (org-element-property :contents-begin up)
  6199. (unless
  6200. (save-match-data
  6201. (when (looking-at-p org-element-planning-line-re)
  6202. (forward-line))
  6203. (when (looking-at org-property-drawer-re)
  6204. (< beg (match-end 0))))
  6205. 'robust))))
  6206. (`org-data (and (not (eq org-element--cache-change-warning 'org-data))
  6207. ;; Property drawer could
  6208. ;; have been inserted. It
  6209. ;; is not robust change
  6210. ;; then.
  6211. (org-with-wide-buffer
  6212. (goto-char (point-min))
  6213. (while (and (org-at-comment-p) (bolp)) (forward-line))
  6214. ;; Should not see property
  6215. ;; drawer within changed
  6216. ;; region.
  6217. (save-match-data
  6218. (or (not (looking-at org-property-drawer-re))
  6219. (> beg (match-end 0)))))))
  6220. (_ 'robust)))))
  6221. ;; UP is a robust greater element containing changes.
  6222. ;; We only need to extend its ending boundaries.
  6223. (progn
  6224. (org-element--cache-shift-positions
  6225. up offset
  6226. (if (and (org-element-property :robust-begin up)
  6227. (org-element-property :robust-end up))
  6228. '(:contents-end :end :robust-end)
  6229. '(:contents-end :end)))
  6230. (org-element--cache-log-message
  6231. "Shifting end positions of robust parent: %S"
  6232. (org-element--format-element up)))
  6233. (unless (or
  6234. ;; UP is non-robust. Yet, if UP is headline, flagging
  6235. ;; everything inside for removal may be to
  6236. ;; costly. Instead, we should better re-parse only the
  6237. ;; headline itself when possible. If a headline is still
  6238. ;; starting from old :begin position, we do not care that
  6239. ;; its boundaries could have extended to shrunk - we
  6240. ;; will re-parent and shift them anyway.
  6241. (and (eq 'headline (org-element-type up))
  6242. (not org-element--cache-avoid-synchronous-headline-re-parsing)
  6243. ;; The change is not inside headline. Not
  6244. ;; updating here.
  6245. (not (<= beg (org-element-property :begin up)))
  6246. (not (> end (org-element-property :end up)))
  6247. (let ((current (org-with-point-at (org-element-property :begin up)
  6248. (org-element-with-disabled-cache
  6249. (and (looking-at-p org-element-headline-re)
  6250. (org-element-headline-parser))))))
  6251. (when (eq 'headline (org-element-type current))
  6252. (org-element--cache-log-message
  6253. "Found non-robust headline that can be updated individually: %S"
  6254. (org-element--format-element current))
  6255. (org-element-set-element up current)
  6256. t)))
  6257. ;; If UP is org-data, the situation is similar to
  6258. ;; headline case. We just need to re-parse the
  6259. ;; org-data itself, unless the change is made
  6260. ;; within blank lines at BOB (that could
  6261. ;; potentially alter first-section).
  6262. (when (and (eq 'org-data (org-element-type up))
  6263. (>= beg (org-element-property :contents-begin up)))
  6264. (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
  6265. (org-element--cache-log-message
  6266. "Found non-robust change invalidating org-data. Re-parsing: %S"
  6267. (org-element--format-element up))
  6268. t))
  6269. (org-element--cache-log-message
  6270. "Found non-robust element: %S"
  6271. (org-element--format-element up))
  6272. (setq before up)
  6273. (when robust-flag (setq robust-flag nil))))
  6274. (unless (or (org-element-property :parent up)
  6275. (eq 'org-data (org-element-type up)))
  6276. (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)
  6277. (org-element-cache-reset)
  6278. (error "org-element--cache: Emergency exit"))
  6279. (setq up (org-element-property :parent up)))
  6280. ;; We're at top level element containing ELEMENT: if it's
  6281. ;; altered by buffer modifications, it is first element in
  6282. ;; cache to be removed. Otherwise, that first element is the
  6283. ;; following one.
  6284. ;;
  6285. ;; As a special case, do not remove BEFORE if it is a robust
  6286. ;; container for current changes.
  6287. (if (or (< (org-element-property :end before) beg) robust-flag) after
  6288. before)))))
  6289. (defun org-element--cache-submit-request (beg end offset)
  6290. "Submit a new cache synchronization request for current buffer.
  6291. BEG and END are buffer positions delimiting the minimal area
  6292. where cache data should be removed. OFFSET is the size of the
  6293. change, as an integer."
  6294. (org-element--cache-log-message
  6295. "Submitting new synchronization request for [%S..%S]𝝙%S"
  6296. beg end offset)
  6297. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6298. (current-buffer))
  6299. (let ((next (car org-element--cache-sync-requests))
  6300. delete-to delete-from)
  6301. (if (and next
  6302. ;; First existing sync request is in phase 0.
  6303. (= 0 (org-element--request-phase next))
  6304. ;; Current changes intersect with the first sync request.
  6305. (> (setq delete-to (+ (org-element--request-end next)
  6306. (org-element--request-offset next)))
  6307. end)
  6308. (<= (setq delete-from (org-element--request-beg next))
  6309. end))
  6310. ;; Current changes can be merged with first sync request: we
  6311. ;; can save a partial cache synchronization.
  6312. (progn
  6313. (org-element--cache-log-message "Found another phase 0 request intersecting with current")
  6314. ;; Update OFFSET of the existing request.
  6315. (cl-incf (org-element--request-offset next) offset)
  6316. ;; If last change happened within area to be removed, extend
  6317. ;; boundaries of robust parents, if any. Otherwise, find
  6318. ;; first element to remove and update request accordingly.
  6319. (if (> beg delete-from)
  6320. ;; The current modification is completely inside NEXT.
  6321. ;; We already added the current OFFSET to the NEXT
  6322. ;; request. However, the robust elements around
  6323. ;; modifications also need to be shifted. Moreover, the
  6324. ;; new modification may also have non-nil
  6325. ;; `org-element--cache-change-warning'. In the latter case, we
  6326. ;; also need to update the request.
  6327. (let ((first (org-element--cache-for-removal delete-from end offset) ; Shift as needed.
  6328. ))
  6329. (org-element--cache-log-message
  6330. "Current request is inside next. Candidate parent: %S"
  6331. (org-element--format-element first))
  6332. (when
  6333. ;; Non-robust element is now before NEXT. Need to
  6334. ;; update.
  6335. (and first
  6336. (org-element--cache-key-less-p
  6337. (org-element--cache-key first)
  6338. (org-element--request-key next)))
  6339. (org-element--cache-log-message
  6340. "Current request is inside next. New parent: %S"
  6341. (org-element--format-element first))
  6342. (setf (org-element--request-key next)
  6343. (org-element--cache-key first))
  6344. (setf (org-element--request-beg next)
  6345. (org-element-property :begin first))
  6346. (setf (org-element--request-end next)
  6347. (max (org-element-property :end first)
  6348. (org-element--request-end next)))
  6349. (setf (org-element--request-parent next)
  6350. (org-element-property :parent first))))
  6351. ;; The current and NEXT modifications are intersecting
  6352. ;; with current modification starting before NEXT and NEXT
  6353. ;; ending after current. We need to update the common
  6354. ;; non-robust parent for the new extended modification
  6355. ;; region.
  6356. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  6357. (org-element--cache-log-message
  6358. "Current request intersects with next. Candidate parent: %S"
  6359. (org-element--format-element first))
  6360. (when (and first
  6361. (org-element--cache-key-less-p
  6362. (org-element--cache-key first)
  6363. (org-element--request-key next)))
  6364. (org-element--cache-log-message
  6365. "Current request intersects with next. Updating. New parent: %S"
  6366. (org-element--format-element first))
  6367. (setf (org-element--request-key next) (org-element--cache-key first))
  6368. (setf (org-element--request-beg next) (org-element-property :begin first))
  6369. (setf (org-element--request-end next)
  6370. (max (org-element-property :end first)
  6371. (org-element--request-end next)))
  6372. (setf (org-element--request-parent next) (org-element-property :parent first))))))
  6373. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  6374. ;; if any, is no longer a 0-phase request, thus ensuring that
  6375. ;; phases are properly ordered. We need to provide OFFSET as
  6376. ;; optional parameter since current modifications are not known
  6377. ;; yet to the otherwise correct part of the cache (i.e, before
  6378. ;; the first request).
  6379. (org-element--cache-log-message "Adding new phase 0 request")
  6380. (when next (org-element--cache-sync (current-buffer) end beg offset))
  6381. (let ((first (org-element--cache-for-removal beg end offset)))
  6382. (if first
  6383. (push (let ((first-beg (org-element-property :begin first))
  6384. (key (org-element--cache-key first)))
  6385. (cond
  6386. ;; When changes happen before the first known
  6387. ;; element, re-parent and shift the rest of the
  6388. ;; cache.
  6389. ((> first-beg end)
  6390. (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
  6391. (vector key first-beg nil offset nil 1))
  6392. ;; Otherwise, we find the first non robust
  6393. ;; element containing END. All elements between
  6394. ;; FIRST and this one are to be removed.
  6395. ;;
  6396. ;; The current modification is completely inside
  6397. ;; FIRST. Clear and update cached elements in
  6398. ;; region containing FIRST.
  6399. ((let ((first-end (org-element-property :end first)))
  6400. (when (> first-end end)
  6401. (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
  6402. (vector key first-beg first-end offset (org-element-property :parent first) 0))))
  6403. (t
  6404. ;; Now, FIRST is the first element after BEG or
  6405. ;; non-robust element containing BEG. However,
  6406. ;; FIRST ends before END and there might be
  6407. ;; another ELEMENT before END that spans beyond
  6408. ;; END. If there is such element, we need to
  6409. ;; extend the region down to end of the common
  6410. ;; parent of FIRST and everything inside
  6411. ;; BEG..END.
  6412. (let* ((element (org-element--cache-find end))
  6413. (element-end (org-element-property :end element))
  6414. (up element))
  6415. (while (and (not (eq up first))
  6416. (setq up (org-element-property :parent up))
  6417. (>= (org-element-property :begin up) first-beg))
  6418. ;; Note that UP might have been already
  6419. ;; shifted if it is a robust element. After
  6420. ;; deletion, it can put it's end before yet
  6421. ;; unprocessed ELEMENT.
  6422. (setq element-end (max (org-element-property :end up) element-end)
  6423. element up))
  6424. ;; Extend region to remove elements between
  6425. ;; beginning of first and the end of outermost
  6426. ;; element starting before END but after
  6427. ;; beginning of first.
  6428. ;; of the FIRST.
  6429. (org-element--cache-log-message
  6430. "Extending to all elements between:\n 1: %S\n 2: %S"
  6431. (org-element--format-element first)
  6432. (org-element--format-element element))
  6433. (vector key first-beg element-end offset up 0)))))
  6434. org-element--cache-sync-requests)
  6435. ;; No element to remove. No need to re-parent either.
  6436. ;; Simply shift additional elements, if any, by OFFSET.
  6437. (if org-element--cache-sync-requests
  6438. (progn
  6439. (org-element--cache-log-message
  6440. "Nothing to remove. Updating offset of the next request by 𝝙%S: %S"
  6441. offset
  6442. (let ((print-level 3))
  6443. (car org-element--cache-sync-requests)))
  6444. (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
  6445. offset))
  6446. (org-element--cache-log-message
  6447. "Nothing to remove. No elements in cache after %S. Terminating."
  6448. end))))))
  6449. (setq org-element--cache-change-warning nil)))
  6450. (defun org-element--cache-verify-element (element)
  6451. "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
  6452. Return non-nil when verification failed."
  6453. (let ((org-element--cache-self-verify
  6454. (or org-element--cache-self-verify
  6455. (and (boundp 'org-batch-test) org-batch-test)))
  6456. (org-element--cache-self-verify-frequency
  6457. (if (and (boundp 'org-batch-test) org-batch-test)
  6458. 1
  6459. org-element--cache-self-verify-frequency)))
  6460. ;; Verify correct parent for the element.
  6461. (unless (or (not org-element--cache-self-verify)
  6462. (org-element-property :parent element)
  6463. (eq 'org-data (org-element-type element)))
  6464. (org-element--cache-warn "Got element without parent (cache active?: %S). Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" (org-element--cache-active-p) element)
  6465. (org-element-cache-reset))
  6466. (when (and org-element--cache-self-verify
  6467. (org-element--cache-active-p)
  6468. (eq 'headline (org-element-type element))
  6469. ;; Avoid too much slowdown
  6470. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6471. (org-with-point-at (org-element-property :begin element)
  6472. (org-element-with-disabled-cache (org-up-heading-or-point-min))
  6473. (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
  6474. (eq (point) (point-min)))
  6475. (org-element--cache-warn
  6476. "Cached element has wrong parent in %s. Resetting.
  6477. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6478. The element is: %S\n The parent is: %S\n The real parent is: %S"
  6479. (buffer-name (current-buffer))
  6480. (org-element--format-element element)
  6481. (org-element--format-element (org-element-property :parent element))
  6482. (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
  6483. (org-element-cache-reset))
  6484. (org-element--cache-verify-element (org-element-property :parent element))))
  6485. ;; Verify the element itself.
  6486. (when (and org-element--cache-self-verify
  6487. (org-element--cache-active-p)
  6488. element
  6489. (not (memq (org-element-type element) '(section org-data)))
  6490. ;; Avoid too much slowdown
  6491. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6492. (let ((real-element (let (org-element-use-cache)
  6493. (org-element--parse-to
  6494. (if (memq (org-element-type element) '(table-row item))
  6495. (1+ (org-element-property :begin element))
  6496. (org-element-property :begin element))))))
  6497. (unless (and (eq (org-element-type real-element) (org-element-type element))
  6498. (eq (org-element-property :begin real-element) (org-element-property :begin element))
  6499. (eq (org-element-property :end real-element) (org-element-property :end element))
  6500. (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
  6501. (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
  6502. (or (not (org-element-property :ID real-element))
  6503. (string= (org-element-property :ID real-element) (org-element-property :ID element))))
  6504. (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
  6505. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6506. The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
  6507. this-command
  6508. (buffer-name (current-buffer))
  6509. (if (/= org-element--cache-change-tic
  6510. (buffer-chars-modified-tick))
  6511. "no" "yes")
  6512. (org-element--format-element element)
  6513. (org-element--format-element real-element)
  6514. (org-element--cache-find (1- (org-element-property :begin real-element)))
  6515. (car (org-element--cache-find (org-element-property :begin real-element) 'both))
  6516. (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
  6517. (org-element-cache-reset))))))
  6518. ;;; Cache persistence
  6519. (defun org-element--cache-persist-before-write (container &optional associated)
  6520. "Sync cache before saving."
  6521. (when (equal container '(elisp org-element--cache))
  6522. (if (and org-element-use-cache
  6523. (plist-get associated :file)
  6524. (get-file-buffer (plist-get associated :file))
  6525. org-element-cache-persistent)
  6526. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6527. (if (and (derived-mode-p 'org-mode)
  6528. org-element--cache)
  6529. (org-with-wide-buffer
  6530. (org-element--cache-sync (current-buffer) (point-max))
  6531. ;; Cleanup cache request keys to avoid collisions during next
  6532. ;; Emacs session.
  6533. (avl-tree-mapc
  6534. (lambda (el)
  6535. (org-element-put-property el :org-element--cache-sync-key nil))
  6536. org-element--cache)
  6537. nil)
  6538. 'forbid))
  6539. 'forbid)))
  6540. (defun org-element--cache-persist-before-read (container &optional associated)
  6541. "Avoid reading cache before Org mode is loaded."
  6542. (when (equal container '(elisp org-element--cache))
  6543. (if (not (and (plist-get associated :file)
  6544. (get-file-buffer (plist-get associated :file))))
  6545. 'forbid
  6546. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6547. (unless (and org-element-use-cache
  6548. org-element-cache-persistent
  6549. (derived-mode-p 'org-mode)
  6550. (equal (secure-hash 'md5 (current-buffer))
  6551. (plist-get associated :hash)))
  6552. 'forbid)))))
  6553. (defun org-element--cache-persist-after-read (container &optional associated)
  6554. "Setup restored cache."
  6555. (when (and (plist-get associated :file)
  6556. (get-file-buffer (plist-get associated :file)))
  6557. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6558. (when (and org-element-use-cache org-element-cache-persistent)
  6559. (when (and (equal container '(elisp org-element--cache)) org-element--cache)
  6560. (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
  6561. (when (and (equal container '(elisp org-element--headline-cache)) org-element--headline-cache)
  6562. (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache)))))))
  6563. (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
  6564. (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
  6565. (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
  6566. ;;;; Public Functions
  6567. (defvar-local org-element--cache-gapless nil
  6568. "An alist containing (granularity . `org-element--cache-change-tic') elements.
  6569. Each element indicates the latest `org-element--cache-change-tic' when
  6570. change did not contain gaps.")
  6571. ;;;###autoload
  6572. (defun org-element-cache-reset (&optional all)
  6573. "Reset cache in current buffer.
  6574. When optional argument ALL is non-nil, reset cache in all Org
  6575. buffers."
  6576. (interactive "P")
  6577. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  6578. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  6579. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  6580. ;; Only persist cache in file buffers.
  6581. (when (buffer-file-name)
  6582. (when (not org-element-cache-persistent)
  6583. (org-persist-unregister 'org-element--headline-cache (current-buffer))
  6584. (org-persist-unregister 'org-element--cache (current-buffer)))
  6585. (when (and org-element-cache-persistent
  6586. (buffer-file-name (current-buffer)))
  6587. (org-persist-register 'org-element--cache (current-buffer))
  6588. (org-persist-register 'org-element--headline-cache
  6589. (current-buffer)
  6590. :inherit 'org-element--cache)))
  6591. (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
  6592. (setq-local org-element--cache-last-buffer-size (buffer-size))
  6593. (setq-local org-element--cache-gapless nil)
  6594. (setq-local org-element--cache
  6595. (avl-tree-create #'org-element--cache-compare))
  6596. (setq-local org-element--headline-cache
  6597. (avl-tree-create #'org-element--cache-compare))
  6598. (setq-local org-element--cache-hash-left (make-vector org-element--cache-hash-size nil))
  6599. (setq-local org-element--cache-hash-right (make-vector org-element--cache-hash-size nil))
  6600. (setq-local org-element--cache-size 0)
  6601. (setq-local org-element--headline-cache-size 0)
  6602. (setq-local org-element--cache-sync-keys-value 0)
  6603. (setq-local org-element--cache-change-warning nil)
  6604. (setq-local org-element--cache-sync-requests nil)
  6605. (setq-local org-element--cache-sync-timer nil)
  6606. (org-element--cache-setup-change-functions)
  6607. ;; Make sure that `org-element--cache-after-change' and
  6608. ;; `org-element--cache-before-change' are working inside properly created
  6609. ;; indirect buffers. Note that `clone-indirect-buffer-hook'
  6610. ;; will not work inside indirect buffers not created by
  6611. ;; calling `clone-indirect-buffer'. We consider that the code
  6612. ;; not using `clone-indirect-buffer' to be written with
  6613. ;; awareness about possible consequences.
  6614. (add-hook 'clone-indirect-buffer-hook
  6615. #'org-element--cache-setup-change-functions)))))
  6616. ;;;###autoload
  6617. (defun org-element-cache-refresh (pos)
  6618. "Refresh cache at position POS."
  6619. (when (org-element--cache-active-p)
  6620. (org-element--cache-sync (current-buffer) pos)
  6621. (org-element--cache-submit-request pos pos 0)
  6622. (org-element--cache-set-timer (current-buffer))))
  6623. (defvar warning-minimum-log-level) ; Defined in warning.el
  6624. (defvar org-element-cache-map-continue-from nil
  6625. "Position from where mapping should continue.
  6626. This variable can be set by called function, especially when the
  6627. function modified the buffer.")
  6628. ;;;###autoload
  6629. (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
  6630. next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
  6631. narrow)
  6632. "Map all elements in current buffer with FUNC according to
  6633. GRANULARITY. Collect non-nil return values into result list.
  6634. FUNC should accept a single argument - the element.
  6635. FUNC can modify the buffer, but doing so may reduce performance. If
  6636. buffer is modified, the mapping will continue from an element starting
  6637. after the last mapped element. If the last mapped element is deleted,
  6638. the subsequent element will be skipped as it cannot be distinguished
  6639. deterministically from a changed element. If FUNC is expected to
  6640. delete the element, it should directly set the value of
  6641. `org-element-cache-map-continue-from' to force `org-element-cache-map'
  6642. continue from the right point in buffer.
  6643. If some elements are not yet in cache, they will be added.
  6644. GRANULARITY can be `headline', `headline+inlinetask'
  6645. `greater-element', or `element'. The default is
  6646. `headline+inlinetask'. `object' granularity is not supported.
  6647. RESTRICT-ELEMENTS is a list of element types to be mapped over.
  6648. NEXT-RE is a regexp used to search next candidate match when FUNC
  6649. returns non-nil and to search the first candidate match. FAIL-RE is a
  6650. regexp used to search next candidate match when FUNC returns nil. The
  6651. mapping will continue starting from headline at the RE match.
  6652. FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
  6653. mapped elements to elements starting at of after FROM-POS but before
  6654. TO-POS.
  6655. AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
  6656. after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
  6657. map all the elements starting from first element inside section, but
  6658. not including the section).
  6659. LIMIT-COUNT limits mapping to that many first matches where FUNC
  6660. returns non-nil.
  6661. NARROW controls whether current buffer narrowing should be preserved.
  6662. This function does a subset of what `org-element-map' does, but with
  6663. much better performance. Cached elements are supplied as the single
  6664. argument of FUNC. Changes to elements made in FUNC will also alter
  6665. the cache."
  6666. (unless (org-element--cache-active-p)
  6667. (error "Cache must be active."))
  6668. (unless (memq granularity '( headline headline+inlinetask
  6669. greater-element element))
  6670. (error "Unsupported granularity: %S" granularity))
  6671. ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
  6672. ;; process.
  6673. (unless (markerp to-pos)
  6674. (let ((mk (make-marker)))
  6675. (set-marker mk to-pos)
  6676. (setq to-pos mk)))
  6677. (let (;; Bind variables used inside loop to avoid memory
  6678. ;; re-allocation on every iteration.
  6679. ;; See https://emacsconf.org/2021/talks/faster/
  6680. tmpnext-start tmpparent tmpelement)
  6681. (save-excursion
  6682. (save-restriction
  6683. (unless narrow (widen))
  6684. ;; Synchronise cache up to the end of mapped region.
  6685. (org-element-at-point to-pos)
  6686. (cl-macrolet ((cache-root
  6687. ;; Use the most optimal version of cache available.
  6688. () `(if (memq granularity '(headline headline+inlinetask))
  6689. (org-element--headline-cache-root)
  6690. (org-element--cache-root)))
  6691. (cache-size
  6692. ;; Use the most optimal version of cache available.
  6693. () `(if (memq granularity '(headline headline+inlinetask))
  6694. org-element--headline-cache-size
  6695. org-element--cache-size))
  6696. (cache-walk-restart
  6697. ;; Restart tree traversal after AVL tree re-balance.
  6698. () `(when node
  6699. (org-element-at-point (point-max))
  6700. (setq node (cache-root)
  6701. stack (list nil)
  6702. leftp t
  6703. continue-flag t)))
  6704. (cache-walk-abort
  6705. ;; Abort tree traversal.
  6706. () `(setq continue-flag t
  6707. node nil))
  6708. (element-match-at-point
  6709. ;; Returning the first element to match around point.
  6710. ;; For example, if point is inside headline and
  6711. ;; granularity is restricted to headlines only, skip
  6712. ;; over all the child elements inside the headline
  6713. ;; and return the first parent headline.
  6714. ;; When we are inside a cache gap, calling
  6715. ;; `org-element-at-point' also fills the cache gap down to
  6716. ;; point.
  6717. () `(progn
  6718. ;; Parsing is one of the performance
  6719. ;; bottlenecks. Make sure to optimise it as
  6720. ;; much as possible.
  6721. ;;
  6722. ;; Avoid extra staff like timer cancels et al
  6723. ;; and only call `org-element--cache-sync-requests' when
  6724. ;; there are pending requests.
  6725. (when org-element--cache-sync-requests
  6726. (org-element--cache-sync (current-buffer)))
  6727. ;; Call `org-element--parse-to' directly avoiding any
  6728. ;; kind of `org-element-at-point' overheads.
  6729. (if restrict-elements
  6730. ;; Search directly instead of calling
  6731. ;; `org-element-lineage' to avoid funcall overheads
  6732. ;; and making sure that we do not go all
  6733. ;; the way to `org-data' as `org-element-lineage'
  6734. ;; does.
  6735. (progn
  6736. (setq tmpelement (org-element--parse-to (point)))
  6737. (while (and tmpelement (not (memq (org-element-type tmpelement) restrict-elements)))
  6738. (setq tmpelement (org-element-property :parent tmpelement)))
  6739. tmpelement)
  6740. (org-element--parse-to (point)))))
  6741. ;; Starting from (point), search RE and move START to
  6742. ;; the next valid element to be matched according to
  6743. ;; restriction. Abort cache walk if no next element
  6744. ;; can be found. When RE is nil, just find element at
  6745. ;; point.
  6746. (move-start-to-next-match
  6747. (re) `(save-match-data
  6748. (if (or (not ,re)
  6749. (if org-element--cache-map-statistics
  6750. (progn
  6751. (setq before-time (float-time))
  6752. (re-search-forward (or (car-safe ,re) ,re) nil 'move)
  6753. (cl-incf re-search-time
  6754. (- (float-time)
  6755. before-time)))
  6756. (re-search-forward (or (car-safe ,re) ,re) nil 'move)))
  6757. (unless (or (< (point) (or start -1))
  6758. (and data
  6759. (< (point) (org-element-property :begin data))))
  6760. (if (cdr-safe ,re)
  6761. ;; Avoid parsing when we are 100%
  6762. ;; sure that regexp is good enough
  6763. ;; to find new START.
  6764. (setq start (match-beginning 0))
  6765. (setq start (max (or start -1)
  6766. (or (org-element-property :begin data) -1)
  6767. (or (org-element-property :begin (element-match-at-point)) -1))))
  6768. (when (>= start to-pos) (cache-walk-abort))
  6769. (when (eq start -1) (setq start nil)))
  6770. (cache-walk-abort))))
  6771. ;; Find expected begin position of an element after
  6772. ;; DATA.
  6773. (next-element-start
  6774. () `(progn
  6775. (setq tmpnext-start nil)
  6776. (if (memq granularity '(headline headline+inlinetask))
  6777. (setq tmpnext-start (or (when (memq (org-element-type data) '(headline org-data))
  6778. (org-element-property :contents-begin data))
  6779. (org-element-property :end data)))
  6780. (setq tmpnext-start (or (when (memq (org-element-type data) org-element-greater-elements)
  6781. (org-element-property :contents-begin data))
  6782. (org-element-property :end data))))
  6783. ;; DATA end may be the last element inside
  6784. ;; i.e. source block. Skip up to the end
  6785. ;; of parent in such case.
  6786. (setq tmpparent data)
  6787. (catch :exit
  6788. (when (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6789. (setq tmpnext-start (org-element-property :end tmpparent)))
  6790. (while (setq tmpparent (org-element-property :parent tmpparent))
  6791. (if (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6792. (setq tmpnext-start (org-element-property :end tmpparent))
  6793. (throw :exit t))))
  6794. tmpnext-start))
  6795. ;; Check if cache does not have gaps.
  6796. (cache-gapless-p
  6797. () `(eq org-element--cache-change-tic
  6798. (alist-get granularity org-element--cache-gapless))))
  6799. ;; The core algorithm is simple walk along binary tree. However,
  6800. ;; instead of checking all the tree elements from first to last
  6801. ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
  6802. ;; the elements before FROM-POS efficiently: O(logN) instead of
  6803. ;; O(Nbefore).
  6804. ;;
  6805. ;; Later, we may also not check every single element in the
  6806. ;; binary tree after FROM-POS. Instead, we can find position of
  6807. ;; next candidate elements by means of regexp search and skip the
  6808. ;; binary tree branches that are before the next candidate:
  6809. ;; again, O(logN) instead of O(Nbetween).
  6810. ;;
  6811. ;; Some elements might not yet be in the tree. So, we also parse
  6812. ;; the empty gaps in cache as needed making sure that we do not
  6813. ;; miss anything.
  6814. (let* (;; START is always beginning of an element. When there is
  6815. ;; no element in cache at START, we are inside cache gap
  6816. ;; and need to fill it.
  6817. (start (and from-pos
  6818. (progn
  6819. (goto-char from-pos)
  6820. (org-element-property :begin (element-match-at-point)))))
  6821. ;; Some elements may start at the same position, so we
  6822. ;; also keep track of the last processed element and make
  6823. ;; sure that we do not try to search it again.
  6824. (prev after-element)
  6825. (node (cache-root))
  6826. data
  6827. (stack (list nil))
  6828. (leftp t)
  6829. result
  6830. ;; Whether previous element matched FUNC (FUNC
  6831. ;; returned non-nil).
  6832. (last-match t)
  6833. continue-flag
  6834. ;; Generic regexp to search next potential match. If it
  6835. ;; is a cons of (regexp . 'match-beg), we are 100% sure
  6836. ;; that the match beginning is the existing element
  6837. ;; beginning.
  6838. (next-element-re (pcase granularity
  6839. ((or `headline
  6840. (guard (eq '(headline)
  6841. restrict-elements)))
  6842. (cons
  6843. (org-with-limited-levels
  6844. org-element-headline-re)
  6845. 'match-beg))
  6846. (`headline+inlinetask
  6847. (cons
  6848. (if (eq '(inlinetask) restrict-elements)
  6849. (org-inlinetask-outline-regexp)
  6850. org-element-headline-re)
  6851. 'match-beg))
  6852. ;; TODO: May add other commonly
  6853. ;; searched elements as needed.
  6854. (_)))
  6855. ;; Make sure that we are not checking the same regexp twice.
  6856. (next-re (unless (and next-re
  6857. (string= next-re
  6858. (or (car-safe next-element-re)
  6859. next-element-re)))
  6860. next-re))
  6861. (fail-re (unless (and fail-re
  6862. (string= fail-re
  6863. (or (car-safe next-element-re)
  6864. next-element-re)))
  6865. fail-re))
  6866. (restrict-elements (or restrict-elements
  6867. (pcase granularity
  6868. (`headline
  6869. '(headline))
  6870. (`headline+inlinetask
  6871. '(headline inlinetask))
  6872. (`greater-element
  6873. org-element-greater-elements)
  6874. (_ nil))))
  6875. ;; Statistics
  6876. (time (float-time))
  6877. (predicate-time 0)
  6878. (pre-process-time 0)
  6879. (re-search-time 0)
  6880. (count-predicate-calls-match 0)
  6881. (count-predicate-calls-fail 0)
  6882. ;; Bind variables used inside loop to avoid memory
  6883. ;; re-allocation on every iteration.
  6884. ;; See https://emacsconf.org/2021/talks/faster/
  6885. cache-size before-time modified-tic)
  6886. ;; Skip to first element within region.
  6887. (goto-char (or start (point-min)))
  6888. (move-start-to-next-match next-element-re)
  6889. (unless (and start (>= start to-pos))
  6890. (while node
  6891. (setq data (avl-tree--node-data node))
  6892. (if (and leftp (avl-tree--node-left node) ; Left branch.
  6893. ;; Do not move to left branch when we are before
  6894. ;; PREV.
  6895. (or (not prev)
  6896. (not (org-element--cache-key-less-p
  6897. (org-element--cache-key data)
  6898. (org-element--cache-key prev))))
  6899. ;; ... or when we are before START.
  6900. (or (not start)
  6901. (not (> start (org-element-property :begin data)))))
  6902. (progn (push node stack)
  6903. (setq node (avl-tree--node-left node)))
  6904. ;; The whole tree left to DATA is before START and
  6905. ;; PREV. DATA may still be before START (i.e. when
  6906. ;; DATA is the root or when START moved), at START, or
  6907. ;; after START.
  6908. ;;
  6909. ;; If DATA is before start, skip it over and move to
  6910. ;; subsequent elements.
  6911. ;; If DATA is at start, run FUNC if necessary and
  6912. ;; update START according and NEXT-RE, FAIL-RE,
  6913. ;; NEXT-ELEMENT-RE.
  6914. ;; If DATA is after start, we have found a cache gap
  6915. ;; and need to fill it.
  6916. (unless (or (and start (< (org-element-property :begin data) start))
  6917. (and prev (not (org-element--cache-key-less-p
  6918. (org-element--cache-key prev)
  6919. (org-element--cache-key data)))))
  6920. ;; DATA is at of after START and PREV.
  6921. (if (or (not start) (= (org-element-property :begin data) start))
  6922. ;; DATA is at START. Match it.
  6923. ;; In the process, we may alter the buffer,
  6924. ;; so also keep track of the cache state.
  6925. (progn
  6926. (setq modified-tic org-element--cache-change-tic)
  6927. (setq cache-size (cache-size))
  6928. ;; When NEXT-RE/FAIL-RE is provided, skip to
  6929. ;; next regexp match after :begin of the current
  6930. ;; element.
  6931. (when (if last-match next-re fail-re)
  6932. (goto-char (org-element-property :begin data))
  6933. (move-start-to-next-match
  6934. (if last-match next-re fail-re)))
  6935. (when (and (or (not start) (eq (org-element-property :begin data) start))
  6936. (< (org-element-property :begin data) to-pos))
  6937. ;; Calculate where next possible element
  6938. ;; starts and update START if needed.
  6939. (setq start (next-element-start))
  6940. (goto-char start)
  6941. ;; Move START further if possible.
  6942. (when (and next-element-re
  6943. ;; Do not move if we know for
  6944. ;; sure that cache does not
  6945. ;; contain gaps. Regexp
  6946. ;; searches are not cheap.
  6947. (not (cache-gapless-p)))
  6948. (move-start-to-next-match next-element-re)
  6949. ;; Make sure that point is at START
  6950. ;; before running FUNC.
  6951. (goto-char start))
  6952. ;; Try FUNC if DATA matches all the
  6953. ;; restrictions. Calculate new START.
  6954. (when (or (not restrict-elements)
  6955. (memq (org-element-type data) restrict-elements))
  6956. ;; DATA matches restriction. FUNC may
  6957. ;;
  6958. ;; Call FUNC. FUNC may move point.
  6959. (setq org-element-cache-map-continue-from nil)
  6960. (if org-element--cache-map-statistics
  6961. (progn
  6962. (setq before-time (float-time))
  6963. (push (funcall func data) result)
  6964. (cl-incf predicate-time
  6965. (- (float-time)
  6966. before-time))
  6967. (if (car result)
  6968. (cl-incf count-predicate-calls-match)
  6969. (cl-incf count-predicate-calls-fail)))
  6970. (push (funcall func data) result)
  6971. (when (car result) (cl-incf count-predicate-calls-match)))
  6972. ;; Set `last-match'.
  6973. (setq last-match (car result))
  6974. ;; If FUNC moved point forward, update
  6975. ;; START.
  6976. (when org-element-cache-map-continue-from
  6977. (goto-char org-element-cache-map-continue-from))
  6978. (when (> (point) start)
  6979. (move-start-to-next-match nil))
  6980. ;; Drop nil.
  6981. (unless (car result) (pop result)))
  6982. ;; If FUNC did not move the point and we
  6983. ;; know for sure that cache does not contain
  6984. ;; gaps, do not try to calculate START in
  6985. ;; advance but simply loop to the next cache
  6986. ;; element.
  6987. (when (and (cache-gapless-p)
  6988. (eq (next-element-start)
  6989. start))
  6990. (setq start nil))
  6991. ;; Check if the buffer has been modified.
  6992. (unless (and (eq modified-tic org-element--cache-change-tic)
  6993. (eq cache-size (cache-size)))
  6994. ;; START may no longer be valid, update
  6995. ;; it to beginning of real element.
  6996. ;; Upon modification, START may lay
  6997. ;; inside an element. We want to move
  6998. ;; it to real beginning then despite
  6999. ;; START being larger.
  7000. (setq start nil)
  7001. (move-start-to-next-match nil)
  7002. ;; The new element may now start before
  7003. ;; or at already processed position.
  7004. ;; Make sure that we continue from an
  7005. ;; element past already processed
  7006. ;; place.
  7007. (when (and start
  7008. (<= start (org-element-property :begin data))
  7009. (not org-element-cache-map-continue-from))
  7010. (goto-char start)
  7011. (setq data (element-match-at-point))
  7012. ;; If DATA is nil, buffer is
  7013. ;; empty. Abort.
  7014. (when data
  7015. (goto-char (next-element-start))
  7016. (move-start-to-next-match next-element-re)))
  7017. (org-element-at-point to-pos)
  7018. (cache-walk-restart))
  7019. ;; Reached LIMIT-COUNT. Abort.
  7020. (when (and limit-count
  7021. (>= count-predicate-calls-match
  7022. limit-count))
  7023. (cache-walk-abort))
  7024. (if (org-element-property :cached data)
  7025. (setq prev data)
  7026. (setq prev nil))))
  7027. ;; DATA is after START. Fill the gap.
  7028. (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
  7029. ;; Tables and lists are special, we need a
  7030. ;; trickery to make items/rows be populated
  7031. ;; into cache.
  7032. (org-element--parse-to (1+ start)))
  7033. ;; Restart tree traversal as AVL tree is
  7034. ;; re-balanced upon adding elements. We can no
  7035. ;; longer trust STACK.
  7036. (cache-walk-restart)))
  7037. ;; Second, move to the right branch of the tree or skip
  7038. ;; it alltogether.
  7039. (if continue-flag
  7040. (setq continue-flag nil)
  7041. (setq node (if (and (car stack)
  7042. ;; If START advanced beyond stack parent, skip the right branch.
  7043. (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
  7044. (and prev (org-element--cache-key-less-p
  7045. (org-element--cache-key (avl-tree--node-data (car stack)))
  7046. (org-element--cache-key prev)))))
  7047. (progn
  7048. (setq leftp nil)
  7049. (pop stack))
  7050. ;; Otherwise, move ahead into the right
  7051. ;; branch when it exists.
  7052. (if (setq leftp (avl-tree--node-right node))
  7053. (avl-tree--node-right node)
  7054. (pop stack))))))))
  7055. (when (and org-element--cache-map-statistics
  7056. (or (not org-element--cache-map-statistics-threshold)
  7057. (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
  7058. (message "Mapped over elements in %S. %d/%d predicate matches. Total time: %f sec. Pre-process time: %f sec. Predicate time: %f sec. Re-search time: %f sec.
  7059. 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"
  7060. (current-buffer)
  7061. count-predicate-calls-match
  7062. (+ count-predicate-calls-match
  7063. count-predicate-calls-fail)
  7064. (- (float-time) time)
  7065. pre-process-time
  7066. predicate-time
  7067. re-search-time
  7068. granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
  7069. ;; Return result.
  7070. (nreverse result)))))))
  7071. ;;; The Toolbox
  7072. ;;
  7073. ;; The first move is to implement a way to obtain the smallest element
  7074. ;; containing point. This is the job of `org-element-at-point'. It
  7075. ;; basically jumps back to the beginning of section containing point
  7076. ;; and proceed, one element after the other, with
  7077. ;; `org-element--current-element' until the container is found. Note:
  7078. ;; When using `org-element-at-point', secondary values are never
  7079. ;; parsed since the function focuses on elements, not on objects.
  7080. ;;
  7081. ;; At a deeper level, `org-element-context' lists all elements and
  7082. ;; objects containing point.
  7083. ;;
  7084. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  7085. ;; internally by navigation and manipulation tools.
  7086. ;;;###autoload
  7087. (defun org-element-at-point (&optional pom cached-only)
  7088. "Determine closest element around point or POM.
  7089. Only check cached element when CACHED-ONLY is non-nil and return nil
  7090. unconditionally when element at POM is not in cache.
  7091. Return value is a list like (TYPE PROPS) where TYPE is the type
  7092. of the element and PROPS a plist of properties associated to the
  7093. element.
  7094. Possible types are defined in `org-element-all-elements'.
  7095. Properties depend on element or object type, but always include
  7096. `:begin', `:end', and `:post-blank' properties.
  7097. As a special case, if point is at the very beginning of the first
  7098. item in a list or sub-list, returned element will be that list
  7099. instead of the item. Likewise, if point is at the beginning of
  7100. the first row of a table, returned element will be the table
  7101. instead of the first row.
  7102. When point is at the end of the buffer, return the innermost
  7103. element ending there."
  7104. (setq pom (or pom (point)))
  7105. ;; Allow re-parsing when the command can benefit from it.
  7106. (when (and cached-only
  7107. (memq this-command org-element--cache-non-modifying-commands))
  7108. (setq cached-only nil))
  7109. (let (element)
  7110. (when (org-element--cache-active-p)
  7111. (if (not org-element--cache) (org-element-cache-reset)
  7112. (unless cached-only (org-element--cache-sync (current-buffer) pom))))
  7113. (setq element (if cached-only
  7114. (when (and (org-element--cache-active-p)
  7115. (or (not org-element--cache-sync-requests)
  7116. (< pom
  7117. (org-element--request-beg
  7118. (car org-element--cache-sync-requests)))))
  7119. (org-element--cache-find pom))
  7120. (condition-case err
  7121. (org-element--parse-to pom)
  7122. (error
  7123. (org-element--cache-warn
  7124. "Org parser error in %s::%S. Resetting.\n The error was: %S\n Backtrace:\n%S\n Please report this to Org mode mailing list (M-x org-submit-bug-report)."
  7125. (buffer-name (current-buffer))
  7126. pom
  7127. err
  7128. (when (and (fboundp 'backtrace-get-frames)
  7129. (fboundp 'backtrace-to-string))
  7130. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  7131. (org-element-cache-reset)
  7132. (org-element--parse-to pom)))))
  7133. (when (and (org-element--cache-active-p)
  7134. element
  7135. (org-element--cache-verify-element element))
  7136. (setq element (org-element--parse-to pom)))
  7137. (unless (eq 'org-data (org-element-type element))
  7138. (unless (and cached-only
  7139. (not (and element
  7140. (or (= pom (org-element-property :begin element))
  7141. (and (not (memq (org-element-type element) org-element-greater-elements))
  7142. (>= pom (org-element-property :begin element))
  7143. (< pom (org-element-property :end element)))
  7144. (and (org-element-property :contents-begin element)
  7145. (>= pom (org-element-property :begin element))
  7146. (< pom (org-element-property :contents-begin element)))
  7147. (and (not (org-element-property :contents-end element))
  7148. (>= pom (org-element-property :begin element))
  7149. (< pom (org-element-property :end element)))))))
  7150. (if (not (eq (org-element-type element) 'section))
  7151. element
  7152. (org-element-at-point (1+ pom) cached-only))))))
  7153. ;;;###autoload
  7154. (defsubst org-element-at-point-no-context (&optional pom)
  7155. "Quickly find element at point or POM.
  7156. It is a faster version of `org-element-at-point' that is not
  7157. guaranteed to return correct `:parent' properties even when cache is
  7158. enabled."
  7159. (or (org-element-at-point pom 'cached-only)
  7160. (let (org-element-use-cache) (org-element-at-point pom))))
  7161. ;;;###autoload
  7162. (defun org-element-context (&optional element)
  7163. "Return smallest element or object around point.
  7164. Return value is a list like (TYPE PROPS) where TYPE is the type
  7165. of the element or object and PROPS a plist of properties
  7166. associated to it.
  7167. Possible types are defined in `org-element-all-elements' and
  7168. `org-element-all-objects'. Properties depend on element or
  7169. object type, but always include `:begin', `:end', `:parent' and
  7170. `:post-blank'.
  7171. As a special case, if point is right after an object and not at
  7172. the beginning of any other object, return that object.
  7173. Optional argument ELEMENT, when non-nil, is the closest element
  7174. containing point, as returned by `org-element-at-point'.
  7175. Providing it allows for quicker computation."
  7176. (save-match-data
  7177. (catch 'objects-forbidden
  7178. (org-with-wide-buffer
  7179. (let* ((pos (point))
  7180. (element (or element (org-element-at-point)))
  7181. (type (org-element-type element))
  7182. (post (org-element-property :post-affiliated element)))
  7183. ;; If point is inside an element containing objects or
  7184. ;; a secondary string, narrow buffer to the container and
  7185. ;; proceed with parsing. Otherwise, return ELEMENT.
  7186. (cond
  7187. ;; At a parsed affiliated keyword, check if we're inside main
  7188. ;; or dual value.
  7189. ((and post (< pos post))
  7190. (beginning-of-line)
  7191. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  7192. (cond
  7193. ((not (member-ignore-case (match-string 1)
  7194. org-element-parsed-keywords))
  7195. (throw 'objects-forbidden element))
  7196. ((< (match-end 0) pos)
  7197. (narrow-to-region (match-end 0) (line-end-position)))
  7198. ((and (match-beginning 2)
  7199. (>= pos (match-beginning 2))
  7200. (< pos (match-end 2)))
  7201. (narrow-to-region (match-beginning 2) (match-end 2)))
  7202. (t (throw 'objects-forbidden element)))
  7203. ;; Also change type to retrieve correct restrictions.
  7204. (setq type 'keyword))
  7205. ;; At an item, objects can only be located within tag, if any.
  7206. ((eq type 'item)
  7207. (let ((tag (org-element-property :tag element)))
  7208. (if (or (not tag) (/= (line-beginning-position) post))
  7209. (throw 'objects-forbidden element)
  7210. (beginning-of-line)
  7211. (search-forward tag (line-end-position))
  7212. (goto-char (match-beginning 0))
  7213. (if (and (>= pos (point)) (< pos (match-end 0)))
  7214. (narrow-to-region (point) (match-end 0))
  7215. (throw 'objects-forbidden element)))))
  7216. ;; At an headline or inlinetask, objects are in title.
  7217. ((memq type '(headline inlinetask))
  7218. (let ((case-fold-search nil))
  7219. (goto-char (org-element-property :begin element))
  7220. (looking-at org-complex-heading-regexp)
  7221. (let ((end (match-end 4)))
  7222. (if (not end) (throw 'objects-forbidden element)
  7223. (goto-char (match-beginning 4))
  7224. (when (looking-at org-element-comment-string)
  7225. (goto-char (match-end 0)))
  7226. (if (>= (point) end) (throw 'objects-forbidden element)
  7227. (narrow-to-region (point) end))))))
  7228. ;; At a paragraph, a table-row or a verse block, objects are
  7229. ;; located within their contents.
  7230. ((memq type '(paragraph table-row verse-block))
  7231. (let ((cbeg (org-element-property :contents-begin element))
  7232. (cend (org-element-property :contents-end element)))
  7233. ;; CBEG is nil for table rules.
  7234. (if (and cbeg cend (>= pos cbeg)
  7235. (or (< pos cend) (and (= pos cend) (eobp))))
  7236. (narrow-to-region cbeg cend)
  7237. (throw 'objects-forbidden element))))
  7238. (t (throw 'objects-forbidden element)))
  7239. (goto-char (point-min))
  7240. (let ((restriction (org-element-restriction type))
  7241. (parent element)
  7242. last)
  7243. (catch 'exit
  7244. (while t
  7245. (let ((next (org-element--object-lex restriction)))
  7246. (when next (org-element-put-property next :parent parent))
  7247. ;; Process NEXT, if any, in order to know if we need to
  7248. ;; skip it, return it or move into it.
  7249. (if (or (not next) (> (org-element-property :begin next) pos))
  7250. (throw 'exit (or last parent))
  7251. (let ((end (org-element-property :end next))
  7252. (cbeg (org-element-property :contents-begin next))
  7253. (cend (org-element-property :contents-end next)))
  7254. (cond
  7255. ;; Skip objects ending before point. Also skip
  7256. ;; objects ending at point unless it is also the
  7257. ;; end of buffer, since we want to return the
  7258. ;; innermost object.
  7259. ((and (<= end pos) (/= (point-max) end))
  7260. (goto-char end)
  7261. ;; For convenience, when object ends at POS,
  7262. ;; without any space, store it in LAST, as we
  7263. ;; will return it if no object starts here.
  7264. (when (and (= end pos)
  7265. (not (memq (char-before) '(?\s ?\t))))
  7266. (setq last next)))
  7267. ;; If POS is within a container object, move into
  7268. ;; that object.
  7269. ((and cbeg cend
  7270. (>= pos cbeg)
  7271. (or (< pos cend)
  7272. ;; At contents' end, if there is no
  7273. ;; space before point, also move into
  7274. ;; object, for consistency with
  7275. ;; convenience feature above.
  7276. (and (= pos cend)
  7277. (or (= (point-max) pos)
  7278. (not (memq (char-before pos)
  7279. '(?\s ?\t)))))))
  7280. (goto-char cbeg)
  7281. (narrow-to-region (point) cend)
  7282. (setq parent next)
  7283. (setq restriction (org-element-restriction next)))
  7284. ;; Otherwise, return NEXT.
  7285. (t (throw 'exit next))))))))))))))
  7286. (defun org-element-lineage (datum &optional types with-self)
  7287. "List all ancestors of a given element or object.
  7288. DATUM is an object or element.
  7289. Return ancestors from the closest to the farthest. When optional
  7290. argument TYPES is a list of symbols, return the first element or
  7291. object in the lineage whose type belongs to that list instead.
  7292. When optional argument WITH-SELF is non-nil, lineage includes
  7293. DATUM itself as the first element, and TYPES, if provided, also
  7294. apply to it.
  7295. When DATUM is obtained through `org-element-context' or
  7296. `org-element-at-point', only ancestors from its section can be
  7297. found. There is no such limitation when DATUM belongs to a full
  7298. parse tree."
  7299. (let ((up (if with-self datum (org-element-property :parent datum)))
  7300. ancestors)
  7301. (while (and up (not (memq (org-element-type up) types)))
  7302. (unless types (push up ancestors))
  7303. (setq up (org-element-property :parent up)))
  7304. (if types up (nreverse ancestors))))
  7305. (defun org-element-nested-p (elem-A elem-B)
  7306. "Non-nil when elements ELEM-A and ELEM-B are nested."
  7307. (let ((beg-A (org-element-property :begin elem-A))
  7308. (beg-B (org-element-property :begin elem-B))
  7309. (end-A (org-element-property :end elem-A))
  7310. (end-B (org-element-property :end elem-B)))
  7311. (or (and (>= beg-A beg-B) (<= end-A end-B))
  7312. (and (>= beg-B beg-A) (<= end-B end-A)))))
  7313. (defun org-element-swap-A-B (elem-A elem-B)
  7314. "Swap elements ELEM-A and ELEM-B.
  7315. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7316. end of ELEM-A."
  7317. (goto-char (org-element-property :begin elem-A))
  7318. ;; There are two special cases when an element doesn't start at bol:
  7319. ;; the first paragraph in an item or in a footnote definition.
  7320. (let ((specialp (not (bolp))))
  7321. ;; Only a paragraph without any affiliated keyword can be moved at
  7322. ;; ELEM-A position in such a situation. Note that the case of
  7323. ;; a footnote definition is impossible: it cannot contain two
  7324. ;; paragraphs in a row because it cannot contain a blank line.
  7325. (when (and specialp
  7326. (or (not (eq (org-element-type elem-B) 'paragraph))
  7327. (/= (org-element-property :begin elem-B)
  7328. (org-element-property :contents-begin elem-B))))
  7329. (error "Cannot swap elements"))
  7330. ;; Preserve folding state when `org-fold-core-style' is set to
  7331. ;; `text-properties'.
  7332. (org-fold-core-ignore-modifications
  7333. ;; In a special situation, ELEM-A will have no indentation. We'll
  7334. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7335. (let* ((ind-B (when specialp
  7336. (goto-char (org-element-property :begin elem-B))
  7337. (current-indentation)))
  7338. (beg-A (org-element-property :begin elem-A))
  7339. (end-A (save-excursion
  7340. (goto-char (org-element-property :end elem-A))
  7341. (skip-chars-backward " \r\t\n")
  7342. (line-end-position)))
  7343. (beg-B (org-element-property :begin elem-B))
  7344. (end-B (save-excursion
  7345. (goto-char (org-element-property :end elem-B))
  7346. (skip-chars-backward " \r\t\n")
  7347. (line-end-position)))
  7348. ;; Store inner folds responsible for visibility status.
  7349. (folds
  7350. (cons
  7351. (org-fold-core-get-regions :from beg-A :to end-A :relative t)
  7352. (org-fold-core-get-regions :from beg-B :to end-B :relative t)))
  7353. ;; Get contents.
  7354. (body-A (buffer-substring beg-A end-A))
  7355. (body-B (buffer-substring beg-B end-B)))
  7356. ;; Clear up the folds.
  7357. (org-fold-region beg-A end-A nil)
  7358. (org-fold-region beg-B end-B nil)
  7359. (delete-region beg-B end-B)
  7360. (goto-char beg-B)
  7361. (when specialp
  7362. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7363. (indent-to-column ind-B))
  7364. (insert body-A)
  7365. ;; Restore ex ELEM-A folds.
  7366. (org-fold-core-regions (car folds) :relative beg-B)
  7367. (goto-char beg-A)
  7368. (delete-region beg-A end-A)
  7369. (insert body-B)
  7370. ;; Restore ex ELEM-A folds.
  7371. (org-fold-core-regions (cdr folds) :relative beg-A)
  7372. (goto-char (org-element-property :end elem-B))))))
  7373. (provide 'org-element)
  7374. ;; Local variables:
  7375. ;; generated-autoload-file: "org-loaddefs.el"
  7376. ;; End:
  7377. ;;; org-element.el ends here