org-element.el 222 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2021 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;;
  18. ;; See <https://orgmode.org/worg/dev/org-syntax.html> for details about
  19. ;; Org syntax.
  20. ;;
  21. ;; Lisp-wise, a syntax object can be represented as a list.
  22. ;; It follows the pattern (TYPE PROPERTIES CONTENTS), where:
  23. ;; TYPE is a symbol describing the object.
  24. ;; PROPERTIES is the property list attached to it. See docstring of
  25. ;; appropriate parsing function to get an exhaustive list.
  26. ;; CONTENTS is a list of syntax objects or raw strings contained
  27. ;; in the current object, when applicable.
  28. ;;
  29. ;; For the whole document, TYPE is `org-data' and PROPERTIES is nil.
  30. ;;
  31. ;; The first part of this file defines constants for the Org syntax,
  32. ;; while the second one provide accessors and setters functions.
  33. ;;
  34. ;; The next part implements a parser and an interpreter for each
  35. ;; element and object type in Org syntax.
  36. ;;
  37. ;; The following part creates a fully recursive buffer parser. It
  38. ;; also provides a tool to map a function to elements or objects
  39. ;; matching some criteria in the parse tree. Functions of interest
  40. ;; are `org-element-parse-buffer', `org-element-map' and, to a lesser
  41. ;; extent, `org-element-parse-secondary-string'.
  42. ;;
  43. ;; The penultimate part is the cradle of an interpreter for the
  44. ;; obtained parse tree: `org-element-interpret-data'.
  45. ;;
  46. ;; The library ends by furnishing `org-element-at-point' function, and
  47. ;; a way to give information about document structure around point
  48. ;; with `org-element-context'. A cache mechanism is also provided for
  49. ;; these functions.
  50. ;;; Code:
  51. (require 'avl-tree)
  52. (require 'cl-lib)
  53. (require 'ol)
  54. (require 'org)
  55. (require 'org-compat)
  56. (require 'org-entities)
  57. (require 'org-footnote)
  58. (require 'org-list)
  59. (require 'org-macs)
  60. (require 'org-table)
  61. (declare-function org-at-heading-p "org" (&optional _))
  62. (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
  63. (declare-function org-escape-code-in-string "org-src" (s))
  64. (declare-function org-macro-escape-arguments "org-macro" (&rest args))
  65. (declare-function org-macro-extract-arguments "org-macro" (s))
  66. (declare-function org-reduced-level "org" (l))
  67. (declare-function org-unescape-code-in-string "org-src" (s))
  68. (declare-function outline-next-heading "outline" ())
  69. (declare-function outline-previous-heading "outline" ())
  70. (defvar org-archive-tag)
  71. (defvar org-clock-line-re)
  72. (defvar org-closed-string)
  73. (defvar org-comment-string)
  74. (defvar org-complex-heading-regexp)
  75. (defvar org-dblock-start-re)
  76. (defvar org-deadline-string)
  77. (defvar org-done-keywords)
  78. (defvar org-drawer-regexp)
  79. (defvar org-edit-src-content-indentation)
  80. (defvar org-emph-re)
  81. (defvar org-emphasis-regexp-components)
  82. (defvar org-keyword-time-not-clock-regexp)
  83. (defvar org-match-substring-regexp)
  84. (defvar org-odd-levels-only)
  85. (defvar org-outline-regexp-bol)
  86. (defvar org-planning-line-re)
  87. (defvar org-property-drawer-re)
  88. (defvar org-property-format)
  89. (defvar org-property-re)
  90. (defvar org-scheduled-string)
  91. (defvar org-src-preserve-indentation)
  92. (defvar org-tags-column)
  93. (defvar org-time-stamp-formats)
  94. (defvar org-todo-regexp)
  95. (defvar org-ts-regexp-both)
  96. (defvar org-verbatim-re)
  97. ;;; Definitions And Rules
  98. ;;
  99. ;; Define elements, greater elements and specify recursive objects,
  100. ;; along with the affiliated keywords recognized. Also set up
  101. ;; restrictions on recursive objects combinations.
  102. ;;
  103. ;; `org-element-update-syntax' builds proper syntax regexps according
  104. ;; to current setup.
  105. (defconst org-element-citation-key-re
  106. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  107. "Regexp matching a citation key.
  108. Key is located in match group 1.")
  109. (defconst org-element-citation-prefix-re
  110. (rx "[cite"
  111. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  112. ":"
  113. (zero-or-more (any "\t\n ")))
  114. "Regexp matching a citation prefix.
  115. Style, if any, is located in match group 1.")
  116. (defvar org-element-paragraph-separate nil
  117. "Regexp to separate paragraphs in an Org buffer.
  118. In the case of lines starting with \"#\" and \":\", this regexp
  119. is not sufficient to know if point is at a paragraph ending. See
  120. `org-element-paragraph-parser' for more information.")
  121. (defvar org-element--object-regexp nil
  122. "Regexp possibly matching the beginning of an object.
  123. This regexp allows false positives. Dedicated parser (e.g.,
  124. `org-export-bold-parser') will take care of further filtering.
  125. Radio links are not matched by this regexp, as they are treated
  126. specially in `org-element--object-lex'.")
  127. (defun org-element--set-regexps ()
  128. "Build variable syntax regexps."
  129. (setq org-element-paragraph-separate
  130. (concat "^\\(?:"
  131. ;; Headlines, inlinetasks.
  132. "\\*+ " "\\|"
  133. ;; Footnote definitions.
  134. "\\[fn:[-_[:word:]]+\\]" "\\|"
  135. ;; Diary sexps.
  136. "%%(" "\\|"
  137. "[ \t]*\\(?:"
  138. ;; Empty lines.
  139. "$" "\\|"
  140. ;; Tables (any type).
  141. "|" "\\|"
  142. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  143. ;; Comments, keyword-like or block-like constructs.
  144. ;; Blocks and keywords with dual values need to be
  145. ;; double-checked.
  146. "#\\(?: \\|$\\|\\+\\(?:"
  147. "BEGIN_\\S-+" "\\|"
  148. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  149. "\\|"
  150. ;; Drawers (any type) and fixed-width areas. Drawers
  151. ;; need to be double-checked.
  152. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  153. ;; Horizontal rules.
  154. "-\\{5,\\}[ \t]*$" "\\|"
  155. ;; LaTeX environments.
  156. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  157. ;; Clock lines.
  158. "CLOCK:" "\\|"
  159. ;; Lists.
  160. (let ((term (pcase org-plain-list-ordered-item-terminator
  161. (?\) ")") (?. "\\.") (_ "[.)]")))
  162. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  163. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  164. "\\(?:[ \t]\\|$\\)"))
  165. "\\)\\)")
  166. org-element--object-regexp
  167. (mapconcat #'identity
  168. (let ((link-types (regexp-opt (org-link-types))))
  169. (list
  170. ;; Sub/superscript.
  171. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  172. ;; Bold, code, italic, strike-through, underline
  173. ;; and verbatim.
  174. (concat "[*~=+_/]"
  175. (format "[^%s]"
  176. (nth 2 org-emphasis-regexp-components)))
  177. ;; Plain links.
  178. (concat "\\<" link-types ":")
  179. ;; Objects starting with "[": citations,
  180. ;; footnote reference, statistics cookie,
  181. ;; timestamp (inactive) and regular link.
  182. (format "\\[\\(?:%s\\)"
  183. (mapconcat
  184. #'identity
  185. (list "cite[:/]"
  186. "fn:"
  187. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  188. "\\[")
  189. "\\|"))
  190. ;; Objects starting with "@": export snippets.
  191. "@@"
  192. ;; Objects starting with "{": macro.
  193. "{{{"
  194. ;; Objects starting with "<" : timestamp
  195. ;; (active, diary), target, radio target and
  196. ;; angular links.
  197. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  198. ;; Objects starting with "$": latex fragment.
  199. "\\$"
  200. ;; Objects starting with "\": line break,
  201. ;; entity, latex fragment.
  202. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  203. ;; Objects starting with raw text: inline Babel
  204. ;; source block, inline Babel call.
  205. "\\(?:call\\|src\\)_"))
  206. "\\|")))
  207. (org-element--set-regexps)
  208. ;;;###autoload
  209. (defun org-element-update-syntax ()
  210. "Update parser internals."
  211. (interactive)
  212. (org-element--set-regexps)
  213. (org-element-cache-reset 'all))
  214. (defconst org-element-all-elements
  215. '(babel-call center-block clock comment comment-block diary-sexp drawer
  216. dynamic-block example-block export-block fixed-width
  217. footnote-definition headline horizontal-rule inlinetask item
  218. keyword latex-environment node-property paragraph plain-list
  219. planning property-drawer quote-block section
  220. special-block src-block table table-row verse-block)
  221. "Complete list of element types.")
  222. (defconst org-element-greater-elements
  223. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  224. item plain-list property-drawer quote-block section
  225. special-block table)
  226. "List of recursive element types aka Greater Elements.")
  227. (defconst org-element-all-objects
  228. '(bold citation citation-reference code entity export-snippet
  229. footnote-reference inline-babel-call inline-src-block italic line-break
  230. latex-fragment link macro radio-target statistics-cookie strike-through
  231. subscript superscript table-cell target timestamp underline verbatim)
  232. "Complete list of object types.")
  233. (defconst org-element-recursive-objects
  234. '(bold citation footnote-reference italic link subscript radio-target
  235. strike-through superscript table-cell underline)
  236. "List of recursive object types.")
  237. (defconst org-element-object-containers
  238. (append org-element-recursive-objects '(paragraph table-row verse-block))
  239. "List of object or element types that can directly contain objects.")
  240. (defconst org-element-affiliated-keywords
  241. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  242. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  243. "List of affiliated keywords as strings.
  244. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  245. are affiliated keywords and need not to be in this list.")
  246. (defconst org-element-keyword-translation-alist
  247. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  248. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  249. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  250. "Alist of usual translations for keywords.
  251. The key is the old name and the value the new one. The property
  252. holding their value will be named after the translated name.")
  253. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  254. "List of affiliated keywords that can occur more than once in an element.
  255. Their value will be consed into a list of strings, which will be
  256. returned as the value of the property.
  257. This list is checked after translations have been applied. See
  258. `org-element-keyword-translation-alist'.
  259. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  260. allow multiple occurrences and need not to be in this list.")
  261. (defconst org-element-parsed-keywords '("CAPTION")
  262. "List of affiliated keywords whose value can be parsed.
  263. Their value will be stored as a secondary string: a list of
  264. strings and objects.
  265. This list is checked after translations have been applied. See
  266. `org-element-keyword-translation-alist'.")
  267. (defconst org-element--parsed-properties-alist
  268. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  269. org-element-parsed-keywords)
  270. "Alist of parsed keywords and associated properties.
  271. This is generated from `org-element-parsed-keywords', which
  272. see.")
  273. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  274. "List of affiliated keywords which can have a secondary value.
  275. In Org syntax, they can be written with optional square brackets
  276. before the colons. For example, RESULTS keyword can be
  277. associated to a hash value with the following:
  278. #+RESULTS[hash-string]: some-source
  279. This list is checked after translations have been applied. See
  280. `org-element-keyword-translation-alist'.")
  281. (defconst org-element--affiliated-re
  282. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  283. (concat
  284. ;; Dual affiliated keywords.
  285. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  286. (regexp-opt org-element-dual-keywords))
  287. "\\|"
  288. ;; Regular affiliated keywords.
  289. (format "\\(?1:%s\\)"
  290. (regexp-opt
  291. (cl-remove-if
  292. (lambda (k) (member k org-element-dual-keywords))
  293. org-element-affiliated-keywords)))
  294. "\\|"
  295. ;; Export attributes.
  296. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  297. "Regexp matching any affiliated keyword.
  298. Keyword name is put in match group 1. Moreover, if keyword
  299. belongs to `org-element-dual-keywords', put the dual value in
  300. match group 2.
  301. Don't modify it, set `org-element-affiliated-keywords' instead.")
  302. (defconst org-element-object-restrictions
  303. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  304. subscript superscript underline verbatim))
  305. (standard-set
  306. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  307. (standard-set-no-line-break (remq 'line-break standard-set)))
  308. `((bold ,@standard-set)
  309. (citation citation-reference)
  310. (citation-reference ,@minimal-set)
  311. (footnote-reference ,@standard-set)
  312. (headline ,@standard-set-no-line-break)
  313. (inlinetask ,@standard-set-no-line-break)
  314. (italic ,@standard-set)
  315. (item ,@standard-set-no-line-break)
  316. (keyword ,@(remq 'footnote-reference standard-set))
  317. ;; Ignore all links in a link description. Also ignore
  318. ;; radio-targets and line breaks.
  319. (link export-snippet inline-babel-call inline-src-block macro
  320. statistics-cookie ,@minimal-set)
  321. (paragraph ,@standard-set)
  322. ;; Remove any variable object from radio target as it would
  323. ;; prevent it from being properly recognized.
  324. (radio-target ,@minimal-set)
  325. (strike-through ,@standard-set)
  326. (subscript ,@standard-set)
  327. (superscript ,@standard-set)
  328. ;; Ignore inline babel call and inline source block as formulas
  329. ;; are possible. Also ignore line breaks and statistics
  330. ;; cookies.
  331. (table-cell citation export-snippet footnote-reference link macro
  332. radio-target target timestamp ,@minimal-set)
  333. (table-row table-cell)
  334. (underline ,@standard-set)
  335. (verse-block ,@standard-set)))
  336. "Alist of objects restrictions.
  337. key is an element or object type containing objects and value is
  338. a list of types that can be contained within an element or object
  339. of such type.
  340. This alist also applies to secondary string. For example, an
  341. `headline' type element doesn't directly contain objects, but
  342. still has an entry since one of its properties (`:title') does.")
  343. (defconst org-element-secondary-value-alist
  344. '((citation :prefix :suffix)
  345. (headline :title)
  346. (inlinetask :title)
  347. (item :tag)
  348. (citation-reference :prefix :suffix))
  349. "Alist between element types and locations of secondary values.")
  350. (defconst org-element--pair-round-table
  351. (let ((table (make-syntax-table)))
  352. (modify-syntax-entry ?\( "()" table)
  353. (modify-syntax-entry ?\) ")(" table)
  354. (dolist (char '(?\{ ?\} ?\[ ?\] ?\< ?\>) table)
  355. (modify-syntax-entry char " " table)))
  356. "Table used internally to pair only round brackets.
  357. Other brackets are treated as spaces.")
  358. (defconst org-element--pair-square-table
  359. (let ((table (make-syntax-table)))
  360. (modify-syntax-entry ?\[ "(]" table)
  361. (modify-syntax-entry ?\] ")[" table)
  362. (dolist (char '(?\{ ?\} ?\( ?\) ?\< ?\>) table)
  363. (modify-syntax-entry char " " table)))
  364. "Table used internally to pair only square brackets.
  365. Other brackets are treated as spaces.")
  366. (defconst org-element--pair-curly-table
  367. (let ((table (make-syntax-table)))
  368. (modify-syntax-entry ?\{ "(}" table)
  369. (modify-syntax-entry ?\} "){" table)
  370. (dolist (char '(?\[ ?\] ?\( ?\) ?\< ?\>) table)
  371. (modify-syntax-entry char " " table)))
  372. "Table used internally to pair only curly brackets.
  373. Other brackets are treated as spaces.")
  374. (defun org-element--parse-paired-brackets (char)
  375. "Parse paired brackets at point.
  376. CHAR is the opening bracket to consider, as a character. Return
  377. contents between brackets, as a string, or nil. Also move point
  378. past the brackets."
  379. (when (eq char (char-after))
  380. (let ((syntax-table (pcase char
  381. (?\{ org-element--pair-curly-table)
  382. (?\[ org-element--pair-square-table)
  383. (?\( org-element--pair-round-table)
  384. (_ nil)))
  385. (pos (point)))
  386. (when syntax-table
  387. (with-syntax-table syntax-table
  388. (let ((end (ignore-errors (scan-lists pos 1 0))))
  389. (when end
  390. (goto-char end)
  391. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  392. ;;; Accessors and Setters
  393. ;;
  394. ;; Provide four accessors: `org-element-type', `org-element-property'
  395. ;; `org-element-contents' and `org-element-restriction'.
  396. ;;
  397. ;; Setter functions allow modification of elements by side effect.
  398. ;; There is `org-element-put-property', `org-element-set-contents'.
  399. ;; These low-level functions are useful to build a parse tree.
  400. ;;
  401. ;; `org-element-adopt-elements', `org-element-set-element',
  402. ;; `org-element-extract-element' and `org-element-insert-before' are
  403. ;; high-level functions useful to modify a parse tree.
  404. ;;
  405. ;; `org-element-secondary-p' is a predicate used to know if a given
  406. ;; object belongs to a secondary string. `org-element-class' tells if
  407. ;; some parsed data is an element or an object, handling pseudo
  408. ;; elements and objects. `org-element-copy' returns an element or
  409. ;; object, stripping its parent property in the process.
  410. (defsubst org-element-type (element)
  411. "Return type of ELEMENT.
  412. The function returns the type of the element or object provided.
  413. It can also return the following special value:
  414. `plain-text' for a string
  415. `org-data' for a complete document
  416. nil in any other case."
  417. (cond
  418. ((not (consp element)) (and (stringp element) 'plain-text))
  419. ((symbolp (car element)) (car element))))
  420. (defsubst org-element-property (property element)
  421. "Extract the value from the PROPERTY of an ELEMENT."
  422. (if (stringp element) (get-text-property 0 property element)
  423. (plist-get (nth 1 element) property)))
  424. (defsubst org-element-contents (element)
  425. "Extract contents from an ELEMENT."
  426. (cond ((not (consp element)) nil)
  427. ((symbolp (car element)) (nthcdr 2 element))
  428. (t element)))
  429. (defsubst org-element-restriction (element)
  430. "Return restriction associated to ELEMENT.
  431. ELEMENT can be an element, an object or a symbol representing an
  432. element or object type."
  433. (cdr (assq (if (symbolp element) element (org-element-type element))
  434. org-element-object-restrictions)))
  435. (defsubst org-element-put-property (element property value)
  436. "In ELEMENT set PROPERTY to VALUE.
  437. Return modified element."
  438. (if (stringp element) (org-add-props element nil property value)
  439. (setcar (cdr element) (plist-put (nth 1 element) property value))
  440. element))
  441. (defsubst org-element-set-contents (element &rest contents)
  442. "Set ELEMENT's contents to CONTENTS.
  443. Return ELEMENT."
  444. (cond ((null element) contents)
  445. ((not (symbolp (car element))) contents)
  446. ((cdr element) (setcdr (cdr element) contents) element)
  447. (t (nconc element contents))))
  448. (defun org-element-secondary-p (object)
  449. "Non-nil when OBJECT directly belongs to a secondary string.
  450. Return value is the property name, as a keyword, or nil."
  451. (let* ((parent (org-element-property :parent object))
  452. (properties (cdr (assq (org-element-type parent)
  453. org-element-secondary-value-alist))))
  454. (catch 'exit
  455. (dolist (p properties)
  456. (and (memq object (org-element-property p parent))
  457. (throw 'exit p))))))
  458. (defsubst org-element-class (datum &optional parent)
  459. "Return class for ELEMENT, as a symbol.
  460. Class is either `element' or `object'. Optional argument PARENT
  461. is the element or object containing DATUM. It defaults to the
  462. value of DATUM `:parent' property."
  463. (let ((type (org-element-type datum))
  464. (parent (or parent (org-element-property :parent datum))))
  465. (cond
  466. ;; Trivial cases.
  467. ((memq type org-element-all-objects) 'object)
  468. ((memq type org-element-all-elements) 'element)
  469. ;; Special cases.
  470. ((eq type 'org-data) 'element)
  471. ((eq type 'plain-text) 'object)
  472. ((not type) 'object)
  473. ;; Pseudo object or elements. Make a guess about its class.
  474. ;; Basically a pseudo object is contained within another object,
  475. ;; a secondary string or a container element.
  476. ((not parent) 'element)
  477. (t
  478. (let ((parent-type (org-element-type parent)))
  479. (cond ((not parent-type) 'object)
  480. ((memq parent-type org-element-object-containers) 'object)
  481. ((org-element-secondary-p datum) 'object)
  482. (t 'element)))))))
  483. (defsubst org-element-adopt-elements (parent &rest children)
  484. "Append elements to the contents of another element.
  485. PARENT is an element or object. CHILDREN can be elements,
  486. objects, or a strings.
  487. The function takes care of setting `:parent' property for CHILD.
  488. Return parent element."
  489. (declare (indent 1))
  490. (if (not children) parent
  491. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  492. ;; string: parent is the list itself.
  493. (dolist (child children)
  494. (org-element-put-property child :parent (or parent children)))
  495. ;; Add CHILDREN at the end of PARENT contents.
  496. (when parent
  497. (apply #'org-element-set-contents
  498. parent
  499. (nconc (org-element-contents parent) children)))
  500. ;; Return modified PARENT element.
  501. (or parent children)))
  502. (defun org-element-extract-element (element)
  503. "Extract ELEMENT from parse tree.
  504. Remove element from the parse tree by side-effect, and return it
  505. with its `:parent' property stripped out."
  506. (let ((parent (org-element-property :parent element))
  507. (secondary (org-element-secondary-p element)))
  508. (if secondary
  509. (org-element-put-property
  510. parent secondary
  511. (delq element (org-element-property secondary parent)))
  512. (apply #'org-element-set-contents
  513. parent
  514. (delq element (org-element-contents parent))))
  515. ;; Return ELEMENT with its :parent removed.
  516. (org-element-put-property element :parent nil)))
  517. (defun org-element-insert-before (element location)
  518. "Insert ELEMENT before LOCATION in parse tree.
  519. LOCATION is an element, object or string within the parse tree.
  520. Parse tree is modified by side effect."
  521. (let* ((parent (org-element-property :parent location))
  522. (property (org-element-secondary-p location))
  523. (siblings (if property (org-element-property property parent)
  524. (org-element-contents parent)))
  525. ;; Special case: LOCATION is the first element of an
  526. ;; independent secondary string (e.g. :title property). Add
  527. ;; ELEMENT in-place.
  528. (specialp (and (not property)
  529. (eq siblings parent)
  530. (eq (car parent) location))))
  531. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  532. (cond (specialp)
  533. ((or (null siblings) (eq (car siblings) location))
  534. (push element siblings))
  535. ((null location) (nconc siblings (list element)))
  536. (t
  537. (let ((index (cl-position location siblings)))
  538. (unless index (error "No location found to insert element"))
  539. (push element (cdr (nthcdr (1- index) siblings))))))
  540. ;; Store SIBLINGS at appropriate place in parse tree.
  541. (cond
  542. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  543. (property (org-element-put-property parent property siblings))
  544. (t (apply #'org-element-set-contents parent siblings)))
  545. ;; Set appropriate :parent property.
  546. (org-element-put-property element :parent parent)))
  547. (defun org-element-set-element (old new)
  548. "Replace element or object OLD with element or object NEW.
  549. The function takes care of setting `:parent' property for NEW."
  550. ;; Ensure OLD and NEW have the same parent.
  551. (org-element-put-property new :parent (org-element-property :parent old))
  552. (if (or (memq (org-element-type old) '(plain-text nil))
  553. (memq (org-element-type new) '(plain-text nil)))
  554. ;; We cannot replace OLD with NEW since one of them is not an
  555. ;; object or element. We take the long path.
  556. (progn (org-element-insert-before new old)
  557. (org-element-extract-element old))
  558. ;; Since OLD is going to be changed into NEW by side-effect, first
  559. ;; make sure that every element or object within NEW has OLD as
  560. ;; parent.
  561. (dolist (blob (org-element-contents new))
  562. (org-element-put-property blob :parent old))
  563. ;; Transfer contents.
  564. (apply #'org-element-set-contents old (org-element-contents new))
  565. ;; Overwrite OLD's properties with NEW's.
  566. (setcar (cdr old) (nth 1 new))
  567. ;; Transfer type.
  568. (setcar old (car new))))
  569. (defun org-element-create (type &optional props &rest children)
  570. "Create a new element of type TYPE.
  571. Optional argument PROPS, when non-nil, is a plist defining the
  572. properties of the element. CHILDREN can be elements, objects or
  573. strings."
  574. (apply #'org-element-adopt-elements (list type props) children))
  575. (defun org-element-copy (datum)
  576. "Return a copy of DATUM.
  577. DATUM is an element, object, string or nil. `:parent' property
  578. is cleared and contents are removed in the process."
  579. (when datum
  580. (let ((type (org-element-type datum)))
  581. (pcase type
  582. (`org-data (list 'org-data nil))
  583. (`plain-text (substring-no-properties datum))
  584. (`nil (copy-sequence datum))
  585. (_
  586. (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil)))))))
  587. ;;; Greater elements
  588. ;;
  589. ;; For each greater element type, we define a parser and an
  590. ;; interpreter.
  591. ;;
  592. ;; A parser returns the element or object as the list described above.
  593. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  594. ;; every element containing a secondary string (see
  595. ;; `org-element-secondary-value-alist') will accept an optional
  596. ;; argument to toggle parsing of these secondary strings. Moreover,
  597. ;; `item' parser requires current list's structure as its first
  598. ;; element.
  599. ;;
  600. ;; An interpreter accepts two arguments: the list representation of
  601. ;; the element or object, and its contents. The latter may be nil,
  602. ;; depending on the element or object considered. It returns the
  603. ;; appropriate Org syntax, as a string.
  604. ;;
  605. ;; Parsing functions must follow the naming convention:
  606. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  607. ;; defined in `org-element-greater-elements'.
  608. ;;
  609. ;; Similarly, interpreting functions must follow the naming
  610. ;; convention: org-element-TYPE-interpreter.
  611. ;;
  612. ;; With the exception of `headline' and `item' types, greater elements
  613. ;; cannot contain other greater elements of their own type.
  614. ;;
  615. ;; Beside implementing a parser and an interpreter, adding a new
  616. ;; greater element requires tweaking `org-element--current-element'.
  617. ;; Moreover, the newly defined type must be added to both
  618. ;; `org-element-all-elements' and `org-element-greater-elements'.
  619. ;;;; Center Block
  620. (defun org-element-center-block-parser (limit affiliated)
  621. "Parse a center block.
  622. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  623. the buffer position at the beginning of the first affiliated
  624. keyword and CDR is a plist of affiliated keywords along with
  625. their value.
  626. Return a list whose CAR is `center-block' and CDR is a plist
  627. containing `:begin', `:end', `:contents-begin', `:contents-end',
  628. `:post-blank' and `:post-affiliated' keywords.
  629. Assume point is at the beginning of the block."
  630. (let ((case-fold-search t))
  631. (if (not (save-excursion
  632. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  633. ;; Incomplete block: parse it as a paragraph.
  634. (org-element-paragraph-parser limit affiliated)
  635. (let ((block-end-line (match-beginning 0)))
  636. (let* ((begin (car affiliated))
  637. (post-affiliated (point))
  638. ;; Empty blocks have no contents.
  639. (contents-begin (progn (forward-line)
  640. (and (< (point) block-end-line)
  641. (point))))
  642. (contents-end (and contents-begin block-end-line))
  643. (pos-before-blank (progn (goto-char block-end-line)
  644. (forward-line)
  645. (point)))
  646. (end (save-excursion
  647. (skip-chars-forward " \r\t\n" limit)
  648. (if (eobp) (point) (line-beginning-position)))))
  649. (list 'center-block
  650. (nconc
  651. (list :begin begin
  652. :end end
  653. :contents-begin contents-begin
  654. :contents-end contents-end
  655. :post-blank (count-lines pos-before-blank end)
  656. :post-affiliated post-affiliated)
  657. (cdr affiliated))))))))
  658. (defun org-element-center-block-interpreter (_ contents)
  659. "Interpret a center-block element as Org syntax.
  660. CONTENTS is the contents of the element."
  661. (format "#+begin_center\n%s#+end_center" contents))
  662. ;;;; Drawer
  663. (defun org-element-drawer-parser (limit affiliated)
  664. "Parse a drawer.
  665. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  666. the buffer position at the beginning of the first affiliated
  667. keyword and CDR is a plist of affiliated keywords along with
  668. their value.
  669. Return a list whose CAR is `drawer' and CDR is a plist containing
  670. `:drawer-name', `:begin', `:end', `:contents-begin',
  671. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  672. Assume point is at beginning of drawer."
  673. (let ((case-fold-search t))
  674. (if (not (save-excursion
  675. (goto-char (min limit (line-end-position)))
  676. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  677. ;; Incomplete drawer: parse it as a paragraph.
  678. (org-element-paragraph-parser limit affiliated)
  679. (save-excursion
  680. (let* ((drawer-end-line (match-beginning 0))
  681. (name (progn (looking-at org-drawer-regexp)
  682. (match-string-no-properties 1)))
  683. (begin (car affiliated))
  684. (post-affiliated (point))
  685. ;; Empty drawers have no contents.
  686. (contents-begin (progn (forward-line)
  687. (and (< (point) drawer-end-line)
  688. (point))))
  689. (contents-end (and contents-begin drawer-end-line))
  690. (pos-before-blank (progn (goto-char drawer-end-line)
  691. (forward-line)
  692. (point)))
  693. (end (progn (skip-chars-forward " \r\t\n" limit)
  694. (if (eobp) (point) (line-beginning-position)))))
  695. (list 'drawer
  696. (nconc
  697. (list :begin begin
  698. :end end
  699. :drawer-name name
  700. :contents-begin contents-begin
  701. :contents-end contents-end
  702. :post-blank (count-lines pos-before-blank end)
  703. :post-affiliated post-affiliated)
  704. (cdr affiliated))))))))
  705. (defun org-element-drawer-interpreter (drawer contents)
  706. "Interpret DRAWER element as Org syntax.
  707. CONTENTS is the contents of the element."
  708. (format ":%s:\n%s:END:"
  709. (org-element-property :drawer-name drawer)
  710. contents))
  711. ;;;; Dynamic Block
  712. (defun org-element-dynamic-block-parser (limit affiliated)
  713. "Parse a dynamic block.
  714. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  715. the buffer position at the beginning of the first affiliated
  716. keyword and CDR is a plist of affiliated keywords along with
  717. their value.
  718. Return a list whose CAR is `dynamic-block' and CDR is a plist
  719. containing `:block-name', `:begin', `:end', `:contents-begin',
  720. `:contents-end', `:arguments', `:post-blank' and
  721. `:post-affiliated' keywords.
  722. Assume point is at beginning of dynamic block."
  723. (let ((case-fold-search t))
  724. (if (not (save-excursion
  725. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  726. ;; Incomplete block: parse it as a paragraph.
  727. (org-element-paragraph-parser limit affiliated)
  728. (let ((block-end-line (match-beginning 0)))
  729. (save-excursion
  730. (let* ((name (progn (looking-at org-dblock-start-re)
  731. (match-string-no-properties 1)))
  732. (arguments (match-string-no-properties 3))
  733. (begin (car affiliated))
  734. (post-affiliated (point))
  735. ;; Empty blocks have no contents.
  736. (contents-begin (progn (forward-line)
  737. (and (< (point) block-end-line)
  738. (point))))
  739. (contents-end (and contents-begin block-end-line))
  740. (pos-before-blank (progn (goto-char block-end-line)
  741. (forward-line)
  742. (point)))
  743. (end (progn (skip-chars-forward " \r\t\n" limit)
  744. (if (eobp) (point) (line-beginning-position)))))
  745. (list 'dynamic-block
  746. (nconc
  747. (list :begin begin
  748. :end end
  749. :block-name name
  750. :arguments arguments
  751. :contents-begin contents-begin
  752. :contents-end contents-end
  753. :post-blank (count-lines pos-before-blank end)
  754. :post-affiliated post-affiliated)
  755. (cdr affiliated)))))))))
  756. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  757. "Interpret DYNAMIC-BLOCK element as Org syntax.
  758. CONTENTS is the contents of the element."
  759. (format "#+begin: %s%s\n%s#+end:"
  760. (org-element-property :block-name dynamic-block)
  761. (let ((args (org-element-property :arguments dynamic-block)))
  762. (if args (concat " " args) ""))
  763. contents))
  764. ;;;; Footnote Definition
  765. (defconst org-element--footnote-separator
  766. (concat org-outline-regexp-bol "\\|"
  767. org-footnote-definition-re "\\|"
  768. "^\\([ \t]*\n\\)\\{2,\\}")
  769. "Regexp used as a footnote definition separator.")
  770. (defun org-element-footnote-definition-parser (limit affiliated)
  771. "Parse a footnote definition.
  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 `footnote-definition' and CDR is
  777. a plist containing `:label', `:begin' `:end', `:contents-begin',
  778. `:contents-end', `:pre-blank',`:post-blank' and
  779. `:post-affiliated' keywords.
  780. Assume point is at the beginning of the footnote definition."
  781. (save-excursion
  782. (let* ((label (progn (looking-at org-footnote-definition-re)
  783. (match-string-no-properties 1)))
  784. (begin (car affiliated))
  785. (post-affiliated (point))
  786. (end
  787. (save-excursion
  788. (end-of-line)
  789. (cond
  790. ((not
  791. (re-search-forward org-element--footnote-separator limit t))
  792. limit)
  793. ((eq ?\[ (char-after (match-beginning 0)))
  794. ;; At a new footnote definition, make sure we end
  795. ;; before any affiliated keyword above.
  796. (forward-line -1)
  797. (while (and (> (point) post-affiliated)
  798. (looking-at-p org-element--affiliated-re))
  799. (forward-line -1))
  800. (line-beginning-position 2))
  801. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  802. (t (skip-chars-forward " \r\t\n" limit)
  803. (if (= limit (point)) limit (line-beginning-position))))))
  804. (pre-blank 0)
  805. (contents-begin
  806. (progn (search-forward "]")
  807. (skip-chars-forward " \r\t\n" end)
  808. (cond ((= (point) end) nil)
  809. ((= (line-beginning-position) post-affiliated) (point))
  810. (t
  811. (setq pre-blank
  812. (count-lines (line-beginning-position) begin))
  813. (line-beginning-position)))))
  814. (contents-end
  815. (progn (goto-char end)
  816. (skip-chars-backward " \r\t\n")
  817. (line-beginning-position 2))))
  818. (list 'footnote-definition
  819. (nconc
  820. (list :label label
  821. :begin begin
  822. :end end
  823. :contents-begin contents-begin
  824. :contents-end (and contents-begin contents-end)
  825. :pre-blank pre-blank
  826. :post-blank (count-lines contents-end end)
  827. :post-affiliated post-affiliated)
  828. (cdr affiliated))))))
  829. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  830. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  831. CONTENTS is the contents of the footnote-definition."
  832. (let ((pre-blank
  833. (min (or (org-element-property :pre-blank footnote-definition)
  834. ;; 0 is specific to paragraphs at the beginning of
  835. ;; the footnote definition, so we use 1 as
  836. ;; a fall-back value, which is more universal.
  837. 1)
  838. ;; Footnote ends after more than two consecutive empty
  839. ;; lines: limit ourselves to 2 newline characters.
  840. 2)))
  841. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  842. (if (= pre-blank 0) (concat " " (org-trim contents))
  843. (concat (make-string pre-blank ?\n) contents)))))
  844. ;;;; Headline
  845. (defun org-element--get-node-properties ()
  846. "Return node properties associated to headline at point.
  847. Upcase property names. It avoids confusion between properties
  848. obtained through property drawer and default properties from the
  849. parser (e.g. `:end' and :END:). Return value is a plist."
  850. (save-excursion
  851. (forward-line)
  852. (when (looking-at-p org-planning-line-re) (forward-line))
  853. (when (looking-at org-property-drawer-re)
  854. (forward-line)
  855. (let ((end (match-end 0)) properties)
  856. (while (< (line-end-position) end)
  857. (looking-at org-property-re)
  858. (push (match-string-no-properties 3) properties)
  859. (push (intern (concat ":" (upcase (match-string 2)))) properties)
  860. (forward-line))
  861. properties))))
  862. (defun org-element--get-time-properties ()
  863. "Return time properties associated to headline at point.
  864. Return value is a plist."
  865. (save-excursion
  866. (when (progn (forward-line) (looking-at org-planning-line-re))
  867. (let ((end (line-end-position)) plist)
  868. (while (re-search-forward org-keyword-time-not-clock-regexp end t)
  869. (goto-char (match-end 1))
  870. (skip-chars-forward " \t")
  871. (let ((keyword (match-string 1))
  872. (time (org-element-timestamp-parser)))
  873. (cond ((equal keyword org-scheduled-string)
  874. (setq plist (plist-put plist :scheduled time)))
  875. ((equal keyword org-deadline-string)
  876. (setq plist (plist-put plist :deadline time)))
  877. (t (setq plist (plist-put plist :closed time))))))
  878. plist))))
  879. (defun org-element-headline-parser (limit &optional raw-secondary-p)
  880. "Parse a headline.
  881. Return a list whose CAR is `headline' and CDR is a plist
  882. containing `:raw-value', `:title', `:begin', `:end',
  883. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  884. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  885. `:deadline', `:closed', `:archivedp', `:commentedp'
  886. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  887. keywords.
  888. The plist also contains any property set in the property drawer,
  889. with its name in upper cases and colons added at the
  890. beginning (e.g., `:CUSTOM_ID').
  891. LIMIT is a buffer position bounding the search.
  892. When RAW-SECONDARY-P is non-nil, headline's title will not be
  893. parsed as a secondary string, but as a plain string instead.
  894. Assume point is at beginning of the headline."
  895. (save-excursion
  896. (let* ((begin (point))
  897. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  898. (skip-chars-forward " \t")))
  899. (todo (and org-todo-regexp
  900. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  901. (progn (goto-char (match-end 0))
  902. (skip-chars-forward " \t")
  903. (match-string 1))))
  904. (todo-type
  905. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  906. (priority (and (looking-at "\\[#.\\][ \t]*")
  907. (progn (goto-char (match-end 0))
  908. (aref (match-string 0) 2))))
  909. (commentedp
  910. (and (let (case-fold-search) (looking-at org-comment-string))
  911. (goto-char (match-end 0))))
  912. (title-start (prog1 (point)
  913. (unless (or todo priority commentedp)
  914. ;; Headline like "* :tag:"
  915. (skip-chars-backward " \t"))))
  916. (tags (when (re-search-forward
  917. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  918. (line-end-position)
  919. 'move)
  920. (goto-char (match-beginning 0))
  921. (org-split-string (match-string 1) ":")))
  922. (title-end (point))
  923. (raw-value (org-trim
  924. (buffer-substring-no-properties title-start title-end)))
  925. (archivedp (member org-archive-tag tags))
  926. (footnote-section-p (and org-footnote-section
  927. (string= org-footnote-section raw-value)))
  928. (standard-props (org-element--get-node-properties))
  929. (time-props (org-element--get-time-properties))
  930. (end (min (save-excursion (org-end-of-subtree t t)) limit))
  931. (contents-begin (save-excursion
  932. (forward-line)
  933. (skip-chars-forward " \r\t\n" end)
  934. (and (/= (point) end) (line-beginning-position))))
  935. (contents-end (and contents-begin
  936. (progn (goto-char end)
  937. (skip-chars-backward " \r\t\n")
  938. (line-beginning-position 2)))))
  939. (let ((headline
  940. (list 'headline
  941. (nconc
  942. (list :raw-value raw-value
  943. :begin begin
  944. :end end
  945. :pre-blank
  946. (if (not contents-begin) 0
  947. (1- (count-lines begin contents-begin)))
  948. :contents-begin contents-begin
  949. :contents-end contents-end
  950. :level level
  951. :priority priority
  952. :tags tags
  953. :todo-keyword todo
  954. :todo-type todo-type
  955. :post-blank
  956. (if contents-end
  957. (count-lines contents-end end)
  958. (1- (count-lines begin end)))
  959. :footnote-section-p footnote-section-p
  960. :archivedp archivedp
  961. :commentedp commentedp
  962. :post-affiliated begin)
  963. time-props
  964. standard-props))))
  965. (org-element-put-property
  966. headline :title
  967. (if raw-secondary-p raw-value
  968. (org-element--parse-objects
  969. (progn (goto-char title-start)
  970. (skip-chars-forward " \t")
  971. (point))
  972. (progn (goto-char title-end)
  973. (skip-chars-backward " \t")
  974. (point))
  975. nil
  976. (org-element-restriction 'headline)
  977. headline)))))))
  978. (defun org-element-headline-interpreter (headline contents)
  979. "Interpret HEADLINE element as Org syntax.
  980. CONTENTS is the contents of the element."
  981. (let* ((level (org-element-property :level headline))
  982. (todo (org-element-property :todo-keyword headline))
  983. (priority (org-element-property :priority headline))
  984. (title (org-element-interpret-data
  985. (org-element-property :title headline)))
  986. (tags (let ((tag-list (org-element-property :tags headline)))
  987. (and tag-list
  988. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  989. (commentedp (org-element-property :commentedp headline))
  990. (pre-blank (or (org-element-property :pre-blank headline) 0))
  991. (heading
  992. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  993. ?*)
  994. (and todo (concat " " todo))
  995. (and commentedp (concat " " org-comment-string))
  996. (and priority (format " [#%c]" priority))
  997. " "
  998. (if (and org-footnote-section
  999. (org-element-property :footnote-section-p headline))
  1000. org-footnote-section
  1001. title))))
  1002. (concat
  1003. heading
  1004. ;; Align tags.
  1005. (when tags
  1006. (cond
  1007. ((zerop org-tags-column) (format " %s" tags))
  1008. ((< org-tags-column 0)
  1009. (concat
  1010. (make-string
  1011. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1012. ?\s)
  1013. tags))
  1014. (t
  1015. (concat
  1016. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1017. tags))))
  1018. (make-string (1+ pre-blank) ?\n)
  1019. contents)))
  1020. ;;;; Inlinetask
  1021. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1022. "Parse an inline task.
  1023. Return a list whose CAR is `inlinetask' and CDR is a plist
  1024. containing `:title', `:begin', `:end', `:pre-blank',
  1025. `:contents-begin' and `:contents-end', `:level', `:priority',
  1026. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1027. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1028. `:post-affiliated' keywords.
  1029. The plist also contains any property set in the property drawer,
  1030. with its name in upper cases and colons added at the
  1031. beginning (e.g., `:CUSTOM_ID').
  1032. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1033. title will not be parsed as a secondary string, but as a plain
  1034. string instead.
  1035. Assume point is at beginning of the inline task."
  1036. (save-excursion
  1037. (let* ((begin (point))
  1038. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1039. (skip-chars-forward " \t")))
  1040. (todo (and org-todo-regexp
  1041. (let (case-fold-search) (looking-at org-todo-regexp))
  1042. (progn (goto-char (match-end 0))
  1043. (skip-chars-forward " \t")
  1044. (match-string 0))))
  1045. (todo-type (and todo
  1046. (if (member todo org-done-keywords) 'done 'todo)))
  1047. (priority (and (looking-at "\\[#.\\][ \t]*")
  1048. (progn (goto-char (match-end 0))
  1049. (aref (match-string 0) 2))))
  1050. (title-start (point))
  1051. (tags (when (re-search-forward
  1052. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1053. (line-end-position)
  1054. 'move)
  1055. (goto-char (match-beginning 0))
  1056. (org-split-string (match-string 1) ":")))
  1057. (title-end (point))
  1058. (raw-value (org-trim
  1059. (buffer-substring-no-properties title-start title-end)))
  1060. (task-end (save-excursion
  1061. (end-of-line)
  1062. (and (re-search-forward org-outline-regexp-bol limit t)
  1063. (looking-at-p "[ \t]*END[ \t]*$")
  1064. (line-beginning-position))))
  1065. (standard-props (and task-end (org-element--get-node-properties)))
  1066. (time-props (and task-end (org-element--get-time-properties)))
  1067. (contents-begin (and task-end
  1068. (< (point) task-end)
  1069. (progn
  1070. (forward-line)
  1071. (skip-chars-forward " \t\n")
  1072. (line-beginning-position))))
  1073. (contents-end (and contents-begin task-end))
  1074. (end (progn (when task-end (goto-char task-end))
  1075. (forward-line)
  1076. (skip-chars-forward " \r\t\n" limit)
  1077. (if (eobp) (point) (line-beginning-position))))
  1078. (inlinetask
  1079. (list 'inlinetask
  1080. (nconc
  1081. (list :raw-value raw-value
  1082. :begin begin
  1083. :end end
  1084. :pre-blank
  1085. (if (not contents-begin) 0
  1086. (1- (count-lines begin contents-begin)))
  1087. :contents-begin contents-begin
  1088. :contents-end contents-end
  1089. :level level
  1090. :priority priority
  1091. :tags tags
  1092. :todo-keyword todo
  1093. :todo-type todo-type
  1094. :post-blank (1- (count-lines (or task-end begin) end))
  1095. :post-affiliated begin)
  1096. time-props
  1097. standard-props))))
  1098. (org-element-put-property
  1099. inlinetask :title
  1100. (if raw-secondary-p raw-value
  1101. (org-element--parse-objects
  1102. (progn (goto-char title-start)
  1103. (skip-chars-forward " \t")
  1104. (point))
  1105. (progn (goto-char title-end)
  1106. (skip-chars-backward " \t")
  1107. (point))
  1108. nil
  1109. (org-element-restriction 'inlinetask)
  1110. inlinetask))))))
  1111. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1112. "Interpret INLINETASK element as Org syntax.
  1113. CONTENTS is the contents of inlinetask."
  1114. (let* ((level (org-element-property :level inlinetask))
  1115. (todo (org-element-property :todo-keyword inlinetask))
  1116. (priority (org-element-property :priority inlinetask))
  1117. (title (org-element-interpret-data
  1118. (org-element-property :title inlinetask)))
  1119. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1120. (and tag-list
  1121. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1122. (task (concat (make-string level ?*)
  1123. (and todo (concat " " todo))
  1124. (and priority (format " [#%c]" priority))
  1125. (and title (concat " " title)))))
  1126. (concat task
  1127. ;; Align tags.
  1128. (when tags
  1129. (cond
  1130. ((zerop org-tags-column) (format " %s" tags))
  1131. ((< org-tags-column 0)
  1132. (concat
  1133. (make-string
  1134. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1135. ?\s)
  1136. tags))
  1137. (t
  1138. (concat
  1139. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1140. tags))))
  1141. ;; Prefer degenerate inlinetasks when there are no
  1142. ;; contents.
  1143. (when contents
  1144. (concat "\n"
  1145. contents
  1146. (make-string level ?*) " end")))))
  1147. ;;;; Item
  1148. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1149. "Parse an item.
  1150. STRUCT is the structure of the plain list.
  1151. Return a list whose CAR is `item' and CDR is a plist containing
  1152. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1153. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1154. `:post-blank' and `:post-affiliated' keywords.
  1155. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1156. any, will not be parsed as a secondary string, but as a plain
  1157. string instead.
  1158. Assume point is at the beginning of the item."
  1159. (save-excursion
  1160. (beginning-of-line)
  1161. (looking-at org-list-full-item-re)
  1162. (let* ((begin (point))
  1163. (bullet (match-string-no-properties 1))
  1164. (checkbox (let ((box (match-string 3)))
  1165. (cond ((equal "[ ]" box) 'off)
  1166. ((equal "[X]" box) 'on)
  1167. ((equal "[-]" box) 'trans))))
  1168. (counter (let ((c (match-string 2)))
  1169. (save-match-data
  1170. (cond
  1171. ((not c) nil)
  1172. ((string-match "[A-Za-z]" c)
  1173. (- (string-to-char (upcase (match-string 0 c)))
  1174. 64))
  1175. ((string-match "[0-9]+" c)
  1176. (string-to-number (match-string 0 c)))))))
  1177. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1178. (if (bolp) (point) (line-beginning-position 2))))
  1179. (pre-blank 0)
  1180. (contents-begin
  1181. (progn
  1182. (goto-char
  1183. ;; Ignore tags in un-ordered lists: they are just
  1184. ;; a part of item's body.
  1185. (if (and (match-beginning 4)
  1186. (save-match-data (string-match "[.)]" bullet)))
  1187. (match-beginning 4)
  1188. (match-end 0)))
  1189. (skip-chars-forward " \r\t\n" end)
  1190. (cond ((= (point) end) nil)
  1191. ;; If first line isn't empty, contents really
  1192. ;; start at the text after item's meta-data.
  1193. ((= (line-beginning-position) begin) (point))
  1194. (t
  1195. (setq pre-blank
  1196. (count-lines (line-beginning-position) begin))
  1197. (line-beginning-position)))))
  1198. (contents-end (and contents-begin
  1199. (progn (goto-char end)
  1200. (skip-chars-backward " \r\t\n")
  1201. (line-beginning-position 2))))
  1202. (item
  1203. (list 'item
  1204. (list :bullet bullet
  1205. :begin begin
  1206. :end end
  1207. :contents-begin contents-begin
  1208. :contents-end contents-end
  1209. :checkbox checkbox
  1210. :counter counter
  1211. :structure struct
  1212. :pre-blank pre-blank
  1213. :post-blank (count-lines (or contents-end begin) end)
  1214. :post-affiliated begin))))
  1215. (org-element-put-property
  1216. item :tag
  1217. (let ((raw (org-list-get-tag begin struct)))
  1218. (when raw
  1219. (if raw-secondary-p raw
  1220. (org-element--parse-objects
  1221. (match-beginning 4) (match-end 4) nil
  1222. (org-element-restriction 'item)
  1223. item))))))))
  1224. (defun org-element-item-interpreter (item contents)
  1225. "Interpret ITEM element as Org syntax.
  1226. CONTENTS is the contents of the element."
  1227. (let ((tag (pcase (org-element-property :tag item)
  1228. (`nil nil)
  1229. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1230. (bullet
  1231. (org-list-bullet-string
  1232. (cond
  1233. ((not (string-match-p "[0-9a-zA-Z]"
  1234. (org-element-property :bullet item))) "- ")
  1235. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1236. (t "1.")))))
  1237. (concat
  1238. bullet
  1239. (pcase (org-element-property :counter item)
  1240. (`nil nil)
  1241. (counter (format "[@%d] " counter)))
  1242. (pcase (org-element-property :checkbox item)
  1243. (`on "[X] ")
  1244. (`off "[ ] ")
  1245. (`trans "[-] ")
  1246. (_ nil))
  1247. tag
  1248. (when contents
  1249. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1250. (pre-blank
  1251. (min (or (org-element-property :pre-blank item)
  1252. ;; 0 is specific to paragraphs at the
  1253. ;; beginning of the item, so we use 1 as
  1254. ;; a fall-back value, which is more universal.
  1255. 1)
  1256. ;; Lists ends after more than two consecutive
  1257. ;; empty lines: limit ourselves to 2 newline
  1258. ;; characters.
  1259. 2))
  1260. (contents (replace-regexp-in-string
  1261. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1262. (if (= pre-blank 0) (org-trim contents)
  1263. (concat (make-string pre-blank ?\n) contents)))))))
  1264. ;;;; Plain List
  1265. (defun org-element--list-struct (limit)
  1266. ;; Return structure of list at point. Internal function. See
  1267. ;; `org-list-struct' for details.
  1268. (let ((case-fold-search t)
  1269. (top-ind limit)
  1270. (item-re (org-item-re))
  1271. (inlinetask-re (and (featurep 'org-inlinetask) "^\\*+ "))
  1272. items struct)
  1273. (save-excursion
  1274. (catch :exit
  1275. (while t
  1276. (cond
  1277. ;; At limit: end all items.
  1278. ((>= (point) limit)
  1279. (let ((end (progn (skip-chars-backward " \r\t\n")
  1280. (line-beginning-position 2))))
  1281. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1282. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1283. ;; At list end: end all items.
  1284. ((looking-at org-list-end-re)
  1285. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1286. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1287. ;; At a new item: end previous sibling.
  1288. ((looking-at item-re)
  1289. (let ((ind (save-excursion (skip-chars-forward " \t")
  1290. (current-column))))
  1291. (setq top-ind (min top-ind ind))
  1292. (while (and items (<= ind (nth 1 (car items))))
  1293. (let ((item (pop items)))
  1294. (setcar (nthcdr 6 item) (point))
  1295. (push item struct)))
  1296. (push (progn (looking-at org-list-full-item-re)
  1297. (let ((bullet (match-string-no-properties 1)))
  1298. (list (point)
  1299. ind
  1300. bullet
  1301. (match-string-no-properties 2) ; counter
  1302. (match-string-no-properties 3) ; checkbox
  1303. ;; Description tag.
  1304. (and (save-match-data
  1305. (string-match "[-+*]" bullet))
  1306. (match-string-no-properties 4))
  1307. ;; Ending position, unknown so far.
  1308. nil)))
  1309. items))
  1310. (forward-line))
  1311. ;; Skip empty lines.
  1312. ((looking-at "^[ \t]*$") (forward-line))
  1313. ;; Skip inline tasks and blank lines along the way.
  1314. ((and inlinetask-re (looking-at inlinetask-re))
  1315. (forward-line)
  1316. (let ((origin (point)))
  1317. (when (re-search-forward inlinetask-re limit t)
  1318. (if (looking-at-p "END[ \t]*$") (forward-line)
  1319. (goto-char origin)))))
  1320. ;; At some text line. Check if it ends any previous item.
  1321. (t
  1322. (let ((ind (save-excursion
  1323. (skip-chars-forward " \t")
  1324. (current-column)))
  1325. (end (save-excursion
  1326. (skip-chars-backward " \r\t\n")
  1327. (line-beginning-position 2))))
  1328. (while (<= ind (nth 1 (car items)))
  1329. (let ((item (pop items)))
  1330. (setcar (nthcdr 6 item) end)
  1331. (push item struct)
  1332. (unless items
  1333. (throw :exit (sort struct #'car-less-than-car))))))
  1334. ;; Skip blocks (any type) and drawers contents.
  1335. (cond
  1336. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1337. (re-search-forward
  1338. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1339. limit t)))
  1340. ((and (looking-at org-drawer-regexp)
  1341. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1342. (forward-line))))))))
  1343. (defun org-element-plain-list-parser (limit affiliated structure)
  1344. "Parse a plain list.
  1345. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1346. the buffer position at the beginning of the first affiliated
  1347. keyword and CDR is a plist of affiliated keywords along with
  1348. their value. STRUCTURE is the structure of the plain list being
  1349. parsed.
  1350. Return a list whose CAR is `plain-list' and CDR is a plist
  1351. containing `:type', `:begin', `:end', `:contents-begin' and
  1352. `:contents-end', `:structure', `:post-blank' and
  1353. `:post-affiliated' keywords.
  1354. Assume point is at the beginning of the list."
  1355. (save-excursion
  1356. (let* ((struct (or structure (org-element--list-struct limit)))
  1357. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1358. ((nth 5 (assq (point) struct)) 'descriptive)
  1359. (t 'unordered)))
  1360. (contents-begin (point))
  1361. (begin (car affiliated))
  1362. (contents-end (let* ((item (assq contents-begin struct))
  1363. (ind (nth 1 item))
  1364. (pos (nth 6 item)))
  1365. (while (and (setq item (assq pos struct))
  1366. (= (nth 1 item) ind))
  1367. (setq pos (nth 6 item)))
  1368. pos))
  1369. (end (progn (goto-char contents-end)
  1370. (skip-chars-forward " \r\t\n" limit)
  1371. (if (= (point) limit) limit (line-beginning-position)))))
  1372. ;; Return value.
  1373. (list 'plain-list
  1374. (nconc
  1375. (list :type type
  1376. :begin begin
  1377. :end end
  1378. :contents-begin contents-begin
  1379. :contents-end contents-end
  1380. :structure struct
  1381. :post-blank (count-lines contents-end end)
  1382. :post-affiliated contents-begin)
  1383. (cdr affiliated))))))
  1384. (defun org-element-plain-list-interpreter (_ contents)
  1385. "Interpret plain-list element as Org syntax.
  1386. CONTENTS is the contents of the element."
  1387. (with-temp-buffer
  1388. (insert contents)
  1389. (goto-char (point-min))
  1390. (org-list-repair)
  1391. (buffer-string)))
  1392. ;;;; Property Drawer
  1393. (defun org-element-property-drawer-parser (limit)
  1394. "Parse a property drawer.
  1395. LIMIT bounds the search.
  1396. Return a list whose car is `property-drawer' and cdr is a plist
  1397. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1398. `:post-blank' and `:post-affiliated' keywords.
  1399. Assume point is at the beginning of the property drawer."
  1400. (save-excursion
  1401. (let ((case-fold-search t)
  1402. (begin (point))
  1403. (contents-begin (line-beginning-position 2)))
  1404. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1405. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1406. (match-beginning 0)))
  1407. (before-blank (progn (forward-line) (point)))
  1408. (end (progn (skip-chars-forward " \r\t\n" limit)
  1409. (if (eobp) (point) (line-beginning-position)))))
  1410. (list 'property-drawer
  1411. (list :begin begin
  1412. :end end
  1413. :contents-begin (and contents-end contents-begin)
  1414. :contents-end contents-end
  1415. :post-blank (count-lines before-blank end)
  1416. :post-affiliated begin))))))
  1417. (defun org-element-property-drawer-interpreter (_ contents)
  1418. "Interpret property-drawer element as Org syntax.
  1419. CONTENTS is the properties within the drawer."
  1420. (format ":PROPERTIES:\n%s:END:" contents))
  1421. ;;;; Quote Block
  1422. (defun org-element-quote-block-parser (limit affiliated)
  1423. "Parse a quote block.
  1424. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1425. the buffer position at the beginning of the first affiliated
  1426. keyword and CDR is a plist of affiliated keywords along with
  1427. their value.
  1428. Return a list whose CAR is `quote-block' and CDR is a plist
  1429. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1430. `:post-blank' and `:post-affiliated' keywords.
  1431. Assume point is at the beginning of the block."
  1432. (let ((case-fold-search t))
  1433. (if (not (save-excursion
  1434. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1435. ;; Incomplete block: parse it as a paragraph.
  1436. (org-element-paragraph-parser limit affiliated)
  1437. (let ((block-end-line (match-beginning 0)))
  1438. (save-excursion
  1439. (let* ((begin (car affiliated))
  1440. (post-affiliated (point))
  1441. ;; Empty blocks have no contents.
  1442. (contents-begin (progn (forward-line)
  1443. (and (< (point) block-end-line)
  1444. (point))))
  1445. (contents-end (and contents-begin block-end-line))
  1446. (pos-before-blank (progn (goto-char block-end-line)
  1447. (forward-line)
  1448. (point)))
  1449. (end (progn (skip-chars-forward " \r\t\n" limit)
  1450. (if (eobp) (point) (line-beginning-position)))))
  1451. (list 'quote-block
  1452. (nconc
  1453. (list :begin begin
  1454. :end end
  1455. :contents-begin contents-begin
  1456. :contents-end contents-end
  1457. :post-blank (count-lines pos-before-blank end)
  1458. :post-affiliated post-affiliated)
  1459. (cdr affiliated)))))))))
  1460. (defun org-element-quote-block-interpreter (_ contents)
  1461. "Interpret quote-block element as Org syntax.
  1462. CONTENTS is the contents of the element."
  1463. (format "#+begin_quote\n%s#+end_quote" contents))
  1464. ;;;; Section
  1465. (defun org-element-section-parser (_)
  1466. "Parse a section.
  1467. Return a list whose CAR is `section' and CDR is a plist
  1468. containing `:begin', `:end', `:contents-begin', `contents-end',
  1469. `:post-blank' and `:post-affiliated' keywords."
  1470. (save-excursion
  1471. ;; Beginning of section is the beginning of the first non-blank
  1472. ;; line after previous headline.
  1473. (let ((begin (point))
  1474. (end (progn (org-with-limited-levels (outline-next-heading))
  1475. (point)))
  1476. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1477. (line-beginning-position 2))))
  1478. (list 'section
  1479. (list :begin begin
  1480. :end end
  1481. :contents-begin begin
  1482. :contents-end pos-before-blank
  1483. :post-blank (count-lines pos-before-blank end)
  1484. :post-affiliated begin)))))
  1485. (defun org-element-section-interpreter (_ contents)
  1486. "Interpret section element as Org syntax.
  1487. CONTENTS is the contents of the element."
  1488. contents)
  1489. ;;;; Special Block
  1490. (defun org-element-special-block-parser (limit affiliated)
  1491. "Parse a special block.
  1492. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1493. the buffer position at the beginning of the first affiliated
  1494. keyword and CDR is a plist of affiliated keywords along with
  1495. their value.
  1496. Return a list whose CAR is `special-block' and CDR is a plist
  1497. containing `:type', `:begin', `:end', `:contents-begin',
  1498. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1499. Assume point is at the beginning of the block."
  1500. (let* ((case-fold-search t)
  1501. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1502. (match-string-no-properties 1))))
  1503. (if (not (save-excursion
  1504. (re-search-forward
  1505. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1506. limit t)))
  1507. ;; Incomplete block: parse it as a paragraph.
  1508. (org-element-paragraph-parser limit affiliated)
  1509. (let ((block-end-line (match-beginning 0)))
  1510. (save-excursion
  1511. (let* ((begin (car affiliated))
  1512. (post-affiliated (point))
  1513. ;; Empty blocks have no contents.
  1514. (contents-begin (progn (forward-line)
  1515. (and (< (point) block-end-line)
  1516. (point))))
  1517. (contents-end (and contents-begin block-end-line))
  1518. (pos-before-blank (progn (goto-char block-end-line)
  1519. (forward-line)
  1520. (point)))
  1521. (end (progn (skip-chars-forward " \r\t\n" limit)
  1522. (if (eobp) (point) (line-beginning-position)))))
  1523. (list 'special-block
  1524. (nconc
  1525. (list :type type
  1526. :begin begin
  1527. :end end
  1528. :contents-begin contents-begin
  1529. :contents-end contents-end
  1530. :post-blank (count-lines pos-before-blank end)
  1531. :post-affiliated post-affiliated)
  1532. (cdr affiliated)))))))))
  1533. (defun org-element-special-block-interpreter (special-block contents)
  1534. "Interpret SPECIAL-BLOCK element as Org syntax.
  1535. CONTENTS is the contents of the element."
  1536. (let ((block-type (org-element-property :type special-block)))
  1537. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1538. ;;; Elements
  1539. ;;
  1540. ;; For each element, a parser and an interpreter are also defined.
  1541. ;; Both follow the same naming convention used for greater elements.
  1542. ;;
  1543. ;; Also, as for greater elements, adding a new element type is done
  1544. ;; through the following steps: implement a parser and an interpreter,
  1545. ;; tweak `org-element--current-element' so that it recognizes the new
  1546. ;; type and add that new type to `org-element-all-elements'.
  1547. ;;;; Babel Call
  1548. (defun org-element-babel-call-parser (limit affiliated)
  1549. "Parse a babel call.
  1550. LIMIT bounds the search. AFFILIATED is a list of which car is
  1551. the buffer position at the beginning of the first affiliated
  1552. keyword and cdr is a plist of affiliated keywords along with
  1553. their value.
  1554. Return a list whose car is `babel-call' and cdr is a plist
  1555. containing `:call', `:inside-header', `:arguments',
  1556. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1557. `:post-affiliated' as keywords."
  1558. (save-excursion
  1559. (let* ((begin (car affiliated))
  1560. (post-affiliated (point))
  1561. (before-blank (line-beginning-position 2))
  1562. (value (progn (search-forward ":" before-blank t)
  1563. (skip-chars-forward " \t")
  1564. (org-trim
  1565. (buffer-substring-no-properties
  1566. (point) (line-end-position)))))
  1567. (call
  1568. (or (org-string-nw-p
  1569. (buffer-substring-no-properties
  1570. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1571. (point))))))
  1572. (inside-header (org-element--parse-paired-brackets ?\[))
  1573. (arguments (org-string-nw-p
  1574. (org-element--parse-paired-brackets ?\()))
  1575. (end-header
  1576. (org-string-nw-p
  1577. (org-trim
  1578. (buffer-substring-no-properties (point) (line-end-position)))))
  1579. (end (progn (forward-line)
  1580. (skip-chars-forward " \r\t\n" limit)
  1581. (if (eobp) (point) (line-beginning-position)))))
  1582. (list 'babel-call
  1583. (nconc
  1584. (list :call call
  1585. :inside-header inside-header
  1586. :arguments arguments
  1587. :end-header end-header
  1588. :begin begin
  1589. :end end
  1590. :value value
  1591. :post-blank (count-lines before-blank end)
  1592. :post-affiliated post-affiliated)
  1593. (cdr affiliated))))))
  1594. (defun org-element-babel-call-interpreter (babel-call _)
  1595. "Interpret BABEL-CALL element as Org syntax."
  1596. (concat "#+call: "
  1597. (org-element-property :call babel-call)
  1598. (let ((h (org-element-property :inside-header babel-call)))
  1599. (and h (format "[%s]" h)))
  1600. (concat "(" (org-element-property :arguments babel-call) ")")
  1601. (let ((h (org-element-property :end-header babel-call)))
  1602. (and h (concat " " h)))))
  1603. ;;;; Clock
  1604. (defun org-element-clock-parser (limit)
  1605. "Parse a clock.
  1606. LIMIT bounds the search.
  1607. Return a list whose CAR is `clock' and CDR is a plist containing
  1608. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1609. `:post-affiliated' as keywords."
  1610. (save-excursion
  1611. (let* ((case-fold-search nil)
  1612. (begin (point))
  1613. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1614. (skip-chars-forward " \t")
  1615. (org-element-timestamp-parser)))
  1616. (duration (and (search-forward " => " (line-end-position) t)
  1617. (progn (skip-chars-forward " \t")
  1618. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1619. (match-string-no-properties 1)))
  1620. (status (if duration 'closed 'running))
  1621. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1622. (skip-chars-forward " \r\t\n" limit)
  1623. (skip-chars-backward " \t")
  1624. (unless (bolp) (end-of-line))
  1625. (count-lines before-blank (point))))
  1626. (end (point)))
  1627. (list 'clock
  1628. (list :status status
  1629. :value value
  1630. :duration duration
  1631. :begin begin
  1632. :end end
  1633. :post-blank post-blank
  1634. :post-affiliated begin)))))
  1635. (defun org-element-clock-interpreter (clock _)
  1636. "Interpret CLOCK element as Org syntax."
  1637. (concat "CLOCK: "
  1638. (org-element-timestamp-interpreter
  1639. (org-element-property :value clock) nil)
  1640. (let ((duration (org-element-property :duration clock)))
  1641. (and duration
  1642. (concat " => "
  1643. (apply 'format
  1644. "%2s:%02s"
  1645. (org-split-string duration ":")))))))
  1646. ;;;; Comment
  1647. (defun org-element-comment-parser (limit)
  1648. "Parse a comment.
  1649. LIMIT bounds the search.
  1650. Return a list whose CAR is `comment' and CDR is a plist
  1651. containing `:begin', `:end', `:value', `:post-blank',
  1652. `:post-affiliated' keywords.
  1653. Assume point is at comment beginning."
  1654. (save-excursion
  1655. (let* ((begin (point))
  1656. (value (prog2 (looking-at "[ \t]*# ?")
  1657. (buffer-substring-no-properties
  1658. (match-end 0) (line-end-position))
  1659. (forward-line)))
  1660. (com-end
  1661. ;; Get comments ending.
  1662. (progn
  1663. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1664. ;; Accumulate lines without leading hash and first
  1665. ;; whitespace.
  1666. (setq value
  1667. (concat value
  1668. "\n"
  1669. (buffer-substring-no-properties
  1670. (match-end 0) (line-end-position))))
  1671. (forward-line))
  1672. (point)))
  1673. (end (progn (goto-char com-end)
  1674. (skip-chars-forward " \r\t\n" limit)
  1675. (if (eobp) (point) (line-beginning-position)))))
  1676. (list 'comment
  1677. (list :begin begin
  1678. :end end
  1679. :value value
  1680. :post-blank (count-lines com-end end)
  1681. :post-affiliated begin)))))
  1682. (defun org-element-comment-interpreter (comment _)
  1683. "Interpret COMMENT element as Org syntax.
  1684. CONTENTS is nil."
  1685. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1686. ;;;; Comment Block
  1687. (defun org-element-comment-block-parser (limit affiliated)
  1688. "Parse an export 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 `comment-block' and CDR is a plist
  1694. containing `:begin', `:end', `:value', `:post-blank' and
  1695. `:post-affiliated' keywords.
  1696. Assume point is at comment block beginning."
  1697. (let ((case-fold-search t))
  1698. (if (not (save-excursion
  1699. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1700. ;; Incomplete block: parse it as a paragraph.
  1701. (org-element-paragraph-parser limit affiliated)
  1702. (let ((contents-end (match-beginning 0)))
  1703. (save-excursion
  1704. (let* ((begin (car affiliated))
  1705. (post-affiliated (point))
  1706. (contents-begin (progn (forward-line) (point)))
  1707. (pos-before-blank (progn (goto-char contents-end)
  1708. (forward-line)
  1709. (point)))
  1710. (end (progn (skip-chars-forward " \r\t\n" limit)
  1711. (if (eobp) (point) (line-beginning-position))))
  1712. (value (buffer-substring-no-properties
  1713. contents-begin contents-end)))
  1714. (list 'comment-block
  1715. (nconc
  1716. (list :begin begin
  1717. :end end
  1718. :value value
  1719. :post-blank (count-lines pos-before-blank end)
  1720. :post-affiliated post-affiliated)
  1721. (cdr affiliated)))))))))
  1722. (defun org-element-comment-block-interpreter (comment-block _)
  1723. "Interpret COMMENT-BLOCK element as Org syntax."
  1724. (format "#+begin_comment\n%s#+end_comment"
  1725. (org-element-normalize-string
  1726. (org-remove-indentation
  1727. (org-element-property :value comment-block)))))
  1728. ;;;; Diary Sexp
  1729. (defun org-element-diary-sexp-parser (limit affiliated)
  1730. "Parse a diary sexp.
  1731. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1732. the buffer position at the beginning of the first affiliated
  1733. keyword and CDR is a plist of affiliated keywords along with
  1734. their value.
  1735. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1736. containing `:begin', `:end', `:value', `:post-blank' and
  1737. `:post-affiliated' keywords."
  1738. (save-excursion
  1739. (let ((begin (car affiliated))
  1740. (post-affiliated (point))
  1741. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1742. (match-string-no-properties 1)))
  1743. (pos-before-blank (progn (forward-line) (point)))
  1744. (end (progn (skip-chars-forward " \r\t\n" limit)
  1745. (if (eobp) (point) (line-beginning-position)))))
  1746. (list 'diary-sexp
  1747. (nconc
  1748. (list :value value
  1749. :begin begin
  1750. :end end
  1751. :post-blank (count-lines pos-before-blank end)
  1752. :post-affiliated post-affiliated)
  1753. (cdr affiliated))))))
  1754. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1755. "Interpret DIARY-SEXP as Org syntax."
  1756. (org-element-property :value diary-sexp))
  1757. ;;;; Example Block
  1758. (defun org-element-example-block-parser (limit affiliated)
  1759. "Parse an example block.
  1760. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1761. the buffer position at the beginning of the first affiliated
  1762. keyword and CDR is a plist of affiliated keywords along with
  1763. their value.
  1764. Return a list whose CAR is `example-block' and CDR is a plist
  1765. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1766. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1767. `:value', `:post-blank' and `:post-affiliated' keywords."
  1768. (let ((case-fold-search t))
  1769. (if (not (save-excursion
  1770. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1771. ;; Incomplete block: parse it as a paragraph.
  1772. (org-element-paragraph-parser limit affiliated)
  1773. (let ((contents-end (match-beginning 0)))
  1774. (save-excursion
  1775. (let* ((switches
  1776. (progn
  1777. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1778. (match-string-no-properties 1)))
  1779. ;; Switches analysis.
  1780. (number-lines
  1781. (and switches
  1782. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1783. switches)
  1784. (cons
  1785. (if (equal (match-string 1 switches) "-")
  1786. 'new
  1787. 'continued)
  1788. (if (not (match-end 2)) 0
  1789. ;; Subtract 1 to give number of lines before
  1790. ;; first line.
  1791. (1- (string-to-number (match-string 2 switches)))))))
  1792. (preserve-indent
  1793. (and switches (string-match "-i\\>" switches)))
  1794. ;; Should labels be retained in (or stripped from) example
  1795. ;; blocks?
  1796. (retain-labels
  1797. (or (not switches)
  1798. (not (string-match "-r\\>" switches))
  1799. (and number-lines (string-match "-k\\>" switches))))
  1800. ;; What should code-references use - labels or
  1801. ;; line-numbers?
  1802. (use-labels
  1803. (or (not switches)
  1804. (and retain-labels
  1805. (not (string-match "-k\\>" switches)))))
  1806. (label-fmt
  1807. (and switches
  1808. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1809. (match-string 1 switches)))
  1810. ;; Standard block parsing.
  1811. (begin (car affiliated))
  1812. (post-affiliated (point))
  1813. (contents-begin (line-beginning-position 2))
  1814. (value (org-unescape-code-in-string
  1815. (buffer-substring-no-properties
  1816. contents-begin contents-end)))
  1817. (pos-before-blank (progn (goto-char contents-end)
  1818. (forward-line)
  1819. (point)))
  1820. (end (progn (skip-chars-forward " \r\t\n" limit)
  1821. (if (eobp) (point) (line-beginning-position)))))
  1822. (list 'example-block
  1823. (nconc
  1824. (list :begin begin
  1825. :end end
  1826. :value value
  1827. :switches switches
  1828. :number-lines number-lines
  1829. :preserve-indent preserve-indent
  1830. :retain-labels retain-labels
  1831. :use-labels use-labels
  1832. :label-fmt label-fmt
  1833. :post-blank (count-lines pos-before-blank end)
  1834. :post-affiliated post-affiliated)
  1835. (cdr affiliated)))))))))
  1836. (defun org-element-example-block-interpreter (example-block _)
  1837. "Interpret EXAMPLE-BLOCK element as Org syntax."
  1838. (let ((switches (org-element-property :switches example-block))
  1839. (value
  1840. (let ((val (org-element-property :value example-block)))
  1841. (cond
  1842. ((or org-src-preserve-indentation
  1843. (org-element-property :preserve-indent example-block))
  1844. val)
  1845. ((= 0 org-edit-src-content-indentation)
  1846. (org-remove-indentation val))
  1847. (t
  1848. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  1849. (replace-regexp-in-string "^[ \t]*\\S-"
  1850. (concat ind "\\&")
  1851. (org-remove-indentation val))))))))
  1852. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  1853. (org-element-normalize-string (org-escape-code-in-string value))
  1854. "#+end_example")))
  1855. ;;;; Export Block
  1856. (defun org-element-export-block-parser (limit affiliated)
  1857. "Parse an export block.
  1858. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1859. the buffer position at the beginning of the first affiliated
  1860. keyword and CDR is a plist of affiliated keywords along with
  1861. their value.
  1862. Return a list whose CAR is `export-block' and CDR is a plist
  1863. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  1864. `:post-affiliated' keywords.
  1865. Assume point is at export-block beginning."
  1866. (let* ((case-fold-search t))
  1867. (if (not (save-excursion
  1868. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  1869. ;; Incomplete block: parse it as a paragraph.
  1870. (org-element-paragraph-parser limit affiliated)
  1871. (save-excursion
  1872. (let* ((contents-end (match-beginning 0))
  1873. (backend
  1874. (progn
  1875. (looking-at
  1876. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  1877. (match-string-no-properties 1)))
  1878. (begin (car affiliated))
  1879. (post-affiliated (point))
  1880. (contents-begin (progn (forward-line) (point)))
  1881. (pos-before-blank (progn (goto-char contents-end)
  1882. (forward-line)
  1883. (point)))
  1884. (end (progn (skip-chars-forward " \r\t\n" limit)
  1885. (if (eobp) (point) (line-beginning-position))))
  1886. (value (org-unescape-code-in-string
  1887. (buffer-substring-no-properties contents-begin
  1888. contents-end))))
  1889. (list 'export-block
  1890. (nconc
  1891. (list :type (and backend (upcase backend))
  1892. :begin begin
  1893. :end end
  1894. :value value
  1895. :post-blank (count-lines pos-before-blank end)
  1896. :post-affiliated post-affiliated)
  1897. (cdr affiliated))))))))
  1898. (defun org-element-export-block-interpreter (export-block _)
  1899. "Interpret EXPORT-BLOCK element as Org syntax."
  1900. (format "#+begin_export %s\n%s#+end_export"
  1901. (org-element-property :type export-block)
  1902. (org-element-property :value export-block)))
  1903. ;;;; Fixed-width
  1904. (defun org-element-fixed-width-parser (limit affiliated)
  1905. "Parse a fixed-width section.
  1906. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1907. the buffer position at the beginning of the first affiliated
  1908. keyword and CDR is a plist of affiliated keywords along with
  1909. their value.
  1910. Return a list whose CAR is `fixed-width' and CDR is a plist
  1911. containing `:begin', `:end', `:value', `:post-blank' and
  1912. `:post-affiliated' keywords.
  1913. Assume point is at the beginning of the fixed-width area."
  1914. (save-excursion
  1915. (let* ((begin (car affiliated))
  1916. (post-affiliated (point))
  1917. (end-area
  1918. (progn
  1919. (while (and (< (point) limit)
  1920. (looking-at "[ \t]*:\\( \\|$\\)"))
  1921. (forward-line))
  1922. (if (bolp) (line-end-position 0) (point))))
  1923. (end (progn (skip-chars-forward " \r\t\n" limit)
  1924. (if (eobp) (point) (line-beginning-position)))))
  1925. (list 'fixed-width
  1926. (nconc
  1927. (list :begin begin
  1928. :end end
  1929. :value (replace-regexp-in-string
  1930. "^[ \t]*: ?" ""
  1931. (buffer-substring-no-properties post-affiliated
  1932. end-area))
  1933. :post-blank (count-lines end-area end)
  1934. :post-affiliated post-affiliated)
  1935. (cdr affiliated))))))
  1936. (defun org-element-fixed-width-interpreter (fixed-width _)
  1937. "Interpret FIXED-WIDTH element as Org syntax."
  1938. (let ((value (org-element-property :value fixed-width)))
  1939. (and value (replace-regexp-in-string "^" ": " value))))
  1940. ;;;; Horizontal Rule
  1941. (defun org-element-horizontal-rule-parser (limit affiliated)
  1942. "Parse an horizontal rule.
  1943. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1944. the buffer position at the beginning of the first affiliated
  1945. keyword and CDR is a plist of affiliated keywords along with
  1946. their value.
  1947. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  1948. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  1949. keywords."
  1950. (save-excursion
  1951. (let ((begin (car affiliated))
  1952. (post-affiliated (point))
  1953. (post-hr (progn (forward-line) (point)))
  1954. (end (progn (skip-chars-forward " \r\t\n" limit)
  1955. (if (eobp) (point) (line-beginning-position)))))
  1956. (list 'horizontal-rule
  1957. (nconc
  1958. (list :begin begin
  1959. :end end
  1960. :post-blank (count-lines post-hr end)
  1961. :post-affiliated post-affiliated)
  1962. (cdr affiliated))))))
  1963. (defun org-element-horizontal-rule-interpreter (&rest _)
  1964. "Interpret HORIZONTAL-RULE element as Org syntax."
  1965. "-----")
  1966. ;;;; Keyword
  1967. (defun org-element-keyword-parser (limit affiliated)
  1968. "Parse a keyword at point.
  1969. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1970. the buffer position at the beginning of the first affiliated
  1971. keyword and CDR is a plist of affiliated keywords along with
  1972. their value.
  1973. Return a list whose CAR is a normalized `keyword' (uppercase) and
  1974. CDR is a plist containing `:key', `:value', `:begin', `:end',
  1975. `:post-blank' and `:post-affiliated' keywords."
  1976. (save-excursion
  1977. ;; An orphaned affiliated keyword is considered as a regular
  1978. ;; keyword. In this case AFFILIATED is nil, so we take care of
  1979. ;; this corner case.
  1980. (let ((begin (or (car affiliated) (point)))
  1981. (post-affiliated (point))
  1982. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  1983. (upcase (match-string-no-properties 1))))
  1984. (value (org-trim (buffer-substring-no-properties
  1985. (match-end 0) (point-at-eol))))
  1986. (pos-before-blank (progn (forward-line) (point)))
  1987. (end (progn (skip-chars-forward " \r\t\n" limit)
  1988. (if (eobp) (point) (line-beginning-position)))))
  1989. (list 'keyword
  1990. (nconc
  1991. (list :key key
  1992. :value value
  1993. :begin begin
  1994. :end end
  1995. :post-blank (count-lines pos-before-blank end)
  1996. :post-affiliated post-affiliated)
  1997. (cdr affiliated))))))
  1998. (defun org-element-keyword-interpreter (keyword _)
  1999. "Interpret KEYWORD element as Org syntax."
  2000. (format "#+%s: %s"
  2001. (downcase (org-element-property :key keyword))
  2002. (org-element-property :value keyword)))
  2003. ;;;; Latex Environment
  2004. (defconst org-element--latex-begin-environment
  2005. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2006. "Regexp matching the beginning of a LaTeX environment.
  2007. The environment is captured by the first group.
  2008. See also `org-element--latex-end-environment'.")
  2009. (defconst org-element--latex-end-environment
  2010. "\\\\end{%s}[ \t]*$"
  2011. "Format string matching the ending of a LaTeX environment.
  2012. See also `org-element--latex-begin-environment'.")
  2013. (defun org-element-latex-environment-parser (limit affiliated)
  2014. "Parse a LaTeX environment.
  2015. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2016. the buffer position at the beginning of the first affiliated
  2017. keyword and CDR is a plist of affiliated keywords along with
  2018. their value.
  2019. Return a list whose CAR is `latex-environment' and CDR is a plist
  2020. containing `:begin', `:end', `:value', `:post-blank' and
  2021. `:post-affiliated' keywords.
  2022. Assume point is at the beginning of the latex environment."
  2023. (save-excursion
  2024. (let ((case-fold-search t)
  2025. (code-begin (point)))
  2026. (looking-at org-element--latex-begin-environment)
  2027. (if (not (re-search-forward (format org-element--latex-end-environment
  2028. (regexp-quote (match-string 1)))
  2029. limit t))
  2030. ;; Incomplete latex environment: parse it as a paragraph.
  2031. (org-element-paragraph-parser limit affiliated)
  2032. (let* ((code-end (progn (forward-line) (point)))
  2033. (begin (car affiliated))
  2034. (value (buffer-substring-no-properties code-begin code-end))
  2035. (end (progn (skip-chars-forward " \r\t\n" limit)
  2036. (if (eobp) (point) (line-beginning-position)))))
  2037. (list 'latex-environment
  2038. (nconc
  2039. (list :begin begin
  2040. :end end
  2041. :value value
  2042. :post-blank (count-lines code-end end)
  2043. :post-affiliated code-begin)
  2044. (cdr affiliated))))))))
  2045. (defun org-element-latex-environment-interpreter (latex-environment _)
  2046. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2047. (org-element-property :value latex-environment))
  2048. ;;;; Node Property
  2049. (defun org-element-node-property-parser (limit)
  2050. "Parse a node-property at point.
  2051. LIMIT bounds the search.
  2052. Return a list whose CAR is `node-property' and CDR is a plist
  2053. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2054. `:post-affiliated' keywords."
  2055. (looking-at org-property-re)
  2056. (let ((case-fold-search t)
  2057. (begin (point))
  2058. (key (match-string-no-properties 2))
  2059. (value (match-string-no-properties 3))
  2060. (end (save-excursion
  2061. (end-of-line)
  2062. (if (re-search-forward org-property-re limit t)
  2063. (line-beginning-position)
  2064. limit))))
  2065. (list 'node-property
  2066. (list :key key
  2067. :value value
  2068. :begin begin
  2069. :end end
  2070. :post-blank 0
  2071. :post-affiliated begin))))
  2072. (defun org-element-node-property-interpreter (node-property _)
  2073. "Interpret NODE-PROPERTY element as Org syntax."
  2074. (format org-property-format
  2075. (format ":%s:" (org-element-property :key node-property))
  2076. (or (org-element-property :value node-property) "")))
  2077. ;;;; Paragraph
  2078. (defun org-element-paragraph-parser (limit affiliated)
  2079. "Parse a paragraph.
  2080. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2081. the buffer position at the beginning of the first affiliated
  2082. keyword and CDR is a plist of affiliated keywords along with
  2083. their value.
  2084. Return a list whose CAR is `paragraph' and CDR is a plist
  2085. containing `:begin', `:end', `:contents-begin' and
  2086. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2087. Assume point is at the beginning of the paragraph."
  2088. (save-excursion
  2089. (let* ((begin (car affiliated))
  2090. (contents-begin (point))
  2091. (before-blank
  2092. (let ((case-fold-search t))
  2093. (end-of-line)
  2094. ;; A matching `org-element-paragraph-separate' is not
  2095. ;; necessarily the end of the paragraph. In particular,
  2096. ;; drawers, blocks or LaTeX environments opening lines
  2097. ;; must be closed. Moreover keywords with a secondary
  2098. ;; value must belong to "dual keywords".
  2099. (while (not
  2100. (cond
  2101. ((not (and (re-search-forward
  2102. org-element-paragraph-separate limit 'move)
  2103. (progn (beginning-of-line) t))))
  2104. ((looking-at org-drawer-regexp)
  2105. (save-excursion
  2106. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2107. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2108. (save-excursion
  2109. (re-search-forward
  2110. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2111. (regexp-quote (match-string 1)))
  2112. limit t)))
  2113. ((looking-at org-element--latex-begin-environment)
  2114. (save-excursion
  2115. (re-search-forward
  2116. (format org-element--latex-end-environment
  2117. (regexp-quote (match-string 1)))
  2118. limit t)))
  2119. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2120. (member-ignore-case (match-string 1)
  2121. org-element-dual-keywords))
  2122. ;; Everything else is unambiguous.
  2123. (t)))
  2124. (end-of-line))
  2125. (if (= (point) limit) limit
  2126. (goto-char (line-beginning-position)))))
  2127. (contents-end (save-excursion
  2128. (skip-chars-backward " \r\t\n" contents-begin)
  2129. (line-beginning-position 2)))
  2130. (end (progn (skip-chars-forward " \r\t\n" limit)
  2131. (if (eobp) (point) (line-beginning-position)))))
  2132. (list 'paragraph
  2133. (nconc
  2134. (list :begin begin
  2135. :end end
  2136. :contents-begin contents-begin
  2137. :contents-end contents-end
  2138. :post-blank (count-lines before-blank end)
  2139. :post-affiliated contents-begin)
  2140. (cdr affiliated))))))
  2141. (defun org-element-paragraph-interpreter (_ contents)
  2142. "Interpret paragraph element as Org syntax.
  2143. CONTENTS is the contents of the element."
  2144. contents)
  2145. ;;;; Planning
  2146. (defun org-element-planning-parser (limit)
  2147. "Parse a planning.
  2148. LIMIT bounds the search.
  2149. Return a list whose CAR is `planning' and CDR is a plist
  2150. containing `:closed', `:deadline', `:scheduled', `:begin',
  2151. `:end', `:post-blank' and `:post-affiliated' keywords."
  2152. (save-excursion
  2153. (let* ((case-fold-search nil)
  2154. (begin (point))
  2155. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2156. (skip-chars-forward " \r\t\n" limit)
  2157. (skip-chars-backward " \t")
  2158. (unless (bolp) (end-of-line))
  2159. (count-lines before-blank (point))))
  2160. (end (point))
  2161. closed deadline scheduled)
  2162. (goto-char begin)
  2163. (while (re-search-forward org-keyword-time-not-clock-regexp end t)
  2164. (goto-char (match-end 1))
  2165. (skip-chars-forward " \t" end)
  2166. (let ((keyword (match-string 1))
  2167. (time (org-element-timestamp-parser)))
  2168. (cond ((equal keyword org-closed-string) (setq closed time))
  2169. ((equal keyword org-deadline-string) (setq deadline time))
  2170. (t (setq scheduled time)))))
  2171. (list 'planning
  2172. (list :closed closed
  2173. :deadline deadline
  2174. :scheduled scheduled
  2175. :begin begin
  2176. :end end
  2177. :post-blank post-blank
  2178. :post-affiliated begin)))))
  2179. (defun org-element-planning-interpreter (planning _)
  2180. "Interpret PLANNING element as Org syntax."
  2181. (mapconcat
  2182. #'identity
  2183. (delq nil
  2184. (list (let ((deadline (org-element-property :deadline planning)))
  2185. (when deadline
  2186. (concat org-deadline-string " "
  2187. (org-element-timestamp-interpreter deadline nil))))
  2188. (let ((scheduled (org-element-property :scheduled planning)))
  2189. (when scheduled
  2190. (concat org-scheduled-string " "
  2191. (org-element-timestamp-interpreter scheduled nil))))
  2192. (let ((closed (org-element-property :closed planning)))
  2193. (when closed
  2194. (concat org-closed-string " "
  2195. (org-element-timestamp-interpreter closed nil))))))
  2196. " "))
  2197. ;;;; Src Block
  2198. (defun org-element-src-block-parser (limit affiliated)
  2199. "Parse a source block.
  2200. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2201. the buffer position at the beginning of the first affiliated
  2202. keyword and CDR is a plist of affiliated keywords along with
  2203. their value.
  2204. Return a list whose CAR is `src-block' and CDR is a plist
  2205. containing `:language', `:switches', `:parameters', `:begin',
  2206. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2207. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2208. `:post-affiliated' keywords.
  2209. Assume point is at the beginning of the block."
  2210. (let ((case-fold-search t))
  2211. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2212. limit t)))
  2213. ;; Incomplete block: parse it as a paragraph.
  2214. (org-element-paragraph-parser limit affiliated)
  2215. (let ((contents-end (match-beginning 0)))
  2216. (save-excursion
  2217. (let* ((begin (car affiliated))
  2218. (post-affiliated (point))
  2219. ;; Get language as a string.
  2220. (language
  2221. (progn
  2222. (looking-at
  2223. "^[ \t]*#\\+BEGIN_SRC\
  2224. \\(?: +\\(\\S-+\\)\\)?\
  2225. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2226. \\(.*\\)[ \t]*$")
  2227. (match-string-no-properties 1)))
  2228. ;; Get switches.
  2229. (switches (match-string-no-properties 2))
  2230. ;; Get parameters.
  2231. (parameters (match-string-no-properties 3))
  2232. ;; Switches analysis.
  2233. (number-lines
  2234. (and switches
  2235. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2236. switches)
  2237. (cons
  2238. (if (equal (match-string 1 switches) "-")
  2239. 'new
  2240. 'continued)
  2241. (if (not (match-end 2)) 0
  2242. ;; Subtract 1 to give number of lines before
  2243. ;; first line.
  2244. (1- (string-to-number (match-string 2 switches)))))))
  2245. (preserve-indent (and switches
  2246. (string-match "-i\\>" switches)))
  2247. (label-fmt
  2248. (and switches
  2249. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2250. (match-string 1 switches)))
  2251. ;; Should labels be retained in (or stripped from)
  2252. ;; source blocks?
  2253. (retain-labels
  2254. (or (not switches)
  2255. (not (string-match "-r\\>" switches))
  2256. (and number-lines (string-match "-k\\>" switches))))
  2257. ;; What should code-references use - labels or
  2258. ;; line-numbers?
  2259. (use-labels
  2260. (or (not switches)
  2261. (and retain-labels
  2262. (not (string-match "-k\\>" switches)))))
  2263. ;; Retrieve code.
  2264. (value (org-unescape-code-in-string
  2265. (buffer-substring-no-properties
  2266. (line-beginning-position 2) contents-end)))
  2267. (pos-before-blank (progn (goto-char contents-end)
  2268. (forward-line)
  2269. (point)))
  2270. ;; Get position after ending blank lines.
  2271. (end (progn (skip-chars-forward " \r\t\n" limit)
  2272. (if (eobp) (point) (line-beginning-position)))))
  2273. (list 'src-block
  2274. (nconc
  2275. (list :language language
  2276. :switches (and (org-string-nw-p switches)
  2277. (org-trim switches))
  2278. :parameters (and (org-string-nw-p parameters)
  2279. (org-trim parameters))
  2280. :begin begin
  2281. :end end
  2282. :number-lines number-lines
  2283. :preserve-indent preserve-indent
  2284. :retain-labels retain-labels
  2285. :use-labels use-labels
  2286. :label-fmt label-fmt
  2287. :value value
  2288. :post-blank (count-lines pos-before-blank end)
  2289. :post-affiliated post-affiliated)
  2290. (cdr affiliated)))))))))
  2291. (defun org-element-src-block-interpreter (src-block _)
  2292. "Interpret SRC-BLOCK element as Org syntax."
  2293. (let ((lang (org-element-property :language src-block))
  2294. (switches (org-element-property :switches src-block))
  2295. (params (org-element-property :parameters src-block))
  2296. (value
  2297. (let ((val (org-element-property :value src-block)))
  2298. (cond
  2299. ((or org-src-preserve-indentation
  2300. (org-element-property :preserve-indent src-block))
  2301. val)
  2302. ((zerop org-edit-src-content-indentation)
  2303. (org-remove-indentation val))
  2304. (t
  2305. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2306. (replace-regexp-in-string "^[ \t]*\\S-"
  2307. (concat ind "\\&")
  2308. (org-remove-indentation val))))))))
  2309. (format "#+begin_src%s\n%s#+end_src"
  2310. (concat (and lang (concat " " lang))
  2311. (and switches (concat " " switches))
  2312. (and params (concat " " params)))
  2313. (org-element-normalize-string (org-escape-code-in-string value)))))
  2314. ;;;; Table
  2315. (defun org-element-table-parser (limit affiliated)
  2316. "Parse a table at point.
  2317. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2318. the buffer position at the beginning of the first affiliated
  2319. keyword and CDR is a plist of affiliated keywords along with
  2320. their value.
  2321. Return a list whose CAR is `table' and CDR is a plist containing
  2322. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2323. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2324. keywords.
  2325. Assume point is at the beginning of the table."
  2326. (save-excursion
  2327. (let* ((case-fold-search t)
  2328. (table-begin (point))
  2329. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2330. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2331. (if (eq type 'org) "" "+")))
  2332. (begin (car affiliated))
  2333. (table-end
  2334. (if (re-search-forward end-re limit 'move)
  2335. (goto-char (match-beginning 0))
  2336. (point)))
  2337. (tblfm (let (acc)
  2338. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2339. (push (match-string-no-properties 1) acc)
  2340. (forward-line))
  2341. acc))
  2342. (pos-before-blank (point))
  2343. (end (progn (skip-chars-forward " \r\t\n" limit)
  2344. (if (eobp) (point) (line-beginning-position)))))
  2345. (list 'table
  2346. (nconc
  2347. (list :begin begin
  2348. :end end
  2349. :type type
  2350. :tblfm tblfm
  2351. ;; Only `org' tables have contents. `table.el' tables
  2352. ;; use a `:value' property to store raw table as
  2353. ;; a string.
  2354. :contents-begin (and (eq type 'org) table-begin)
  2355. :contents-end (and (eq type 'org) table-end)
  2356. :value (and (eq type 'table.el)
  2357. (buffer-substring-no-properties
  2358. table-begin table-end))
  2359. :post-blank (count-lines pos-before-blank end)
  2360. :post-affiliated table-begin)
  2361. (cdr affiliated))))))
  2362. (defun org-element-table-interpreter (table contents)
  2363. "Interpret TABLE element as Org syntax.
  2364. CONTENTS is a string, if table's type is `org', or nil."
  2365. (if (eq (org-element-property :type table) 'table.el)
  2366. (org-remove-indentation (org-element-property :value table))
  2367. (concat (with-temp-buffer (insert contents)
  2368. (org-table-align)
  2369. (buffer-string))
  2370. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2371. (reverse (org-element-property :tblfm table))
  2372. "\n"))))
  2373. ;;;; Table Row
  2374. (defun org-element-table-row-parser (_)
  2375. "Parse table row at point.
  2376. Return a list whose CAR is `table-row' and CDR is a plist
  2377. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2378. `:type', `:post-blank' and `:post-affiliated' keywords."
  2379. (save-excursion
  2380. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2381. (begin (point))
  2382. ;; A table rule has no contents. In that case, ensure
  2383. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2384. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2385. (contents-end (and (eq type 'standard)
  2386. (progn
  2387. (end-of-line)
  2388. (skip-chars-backward " \t")
  2389. (point))))
  2390. (end (line-beginning-position 2)))
  2391. (list 'table-row
  2392. (list :type type
  2393. :begin begin
  2394. :end end
  2395. :contents-begin contents-begin
  2396. :contents-end contents-end
  2397. :post-blank 0
  2398. :post-affiliated begin)))))
  2399. (defun org-element-table-row-interpreter (table-row contents)
  2400. "Interpret TABLE-ROW element as Org syntax.
  2401. CONTENTS is the contents of the table row."
  2402. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2403. (concat "|" contents)))
  2404. ;;;; Verse Block
  2405. (defun org-element-verse-block-parser (limit affiliated)
  2406. "Parse a verse block.
  2407. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2408. the buffer position at the beginning of the first affiliated
  2409. keyword and CDR is a plist of affiliated keywords along with
  2410. their value.
  2411. Return a list whose CAR is `verse-block' and CDR is a plist
  2412. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2413. `:post-blank' and `:post-affiliated' keywords.
  2414. Assume point is at beginning of the block."
  2415. (let ((case-fold-search t))
  2416. (if (not (save-excursion
  2417. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2418. ;; Incomplete block: parse it as a paragraph.
  2419. (org-element-paragraph-parser limit affiliated)
  2420. (let ((contents-end (match-beginning 0)))
  2421. (save-excursion
  2422. (let* ((begin (car affiliated))
  2423. (post-affiliated (point))
  2424. (contents-begin (progn (forward-line) (point)))
  2425. (pos-before-blank (progn (goto-char contents-end)
  2426. (forward-line)
  2427. (point)))
  2428. (end (progn (skip-chars-forward " \r\t\n" limit)
  2429. (if (eobp) (point) (line-beginning-position)))))
  2430. (list 'verse-block
  2431. (nconc
  2432. (list :begin begin
  2433. :end end
  2434. :contents-begin contents-begin
  2435. :contents-end contents-end
  2436. :post-blank (count-lines pos-before-blank end)
  2437. :post-affiliated post-affiliated)
  2438. (cdr affiliated)))))))))
  2439. (defun org-element-verse-block-interpreter (_ contents)
  2440. "Interpret verse-block element as Org syntax.
  2441. CONTENTS is verse block contents."
  2442. (format "#+begin_verse\n%s#+end_verse" contents))
  2443. ;;; Objects
  2444. ;;
  2445. ;; Unlike to elements, raw text can be found between objects. Hence,
  2446. ;; `org-element--object-lex' is provided to find the next object in
  2447. ;; buffer.
  2448. ;;
  2449. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2450. ;; object types they can contain will be specified in
  2451. ;; `org-element-object-restrictions'.
  2452. ;;
  2453. ;; Creating a new type of object requires to alter
  2454. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2455. ;; new type in `org-element-all-objects', and possibly add
  2456. ;; restrictions in `org-element-object-restrictions'.
  2457. ;;;; Bold
  2458. (defun org-element-bold-parser ()
  2459. "Parse bold object at point, if any.
  2460. When at a bold object, return a list whose car is `bold' and cdr
  2461. is a plist with `:begin', `:end', `:contents-begin' and
  2462. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2463. nil.
  2464. Assume point is at the first star marker."
  2465. (save-excursion
  2466. (unless (bolp) (backward-char 1))
  2467. (when (looking-at org-emph-re)
  2468. (let ((begin (match-beginning 2))
  2469. (contents-begin (match-beginning 4))
  2470. (contents-end (match-end 4))
  2471. (post-blank (progn (goto-char (match-end 2))
  2472. (skip-chars-forward " \t")))
  2473. (end (point)))
  2474. (list 'bold
  2475. (list :begin begin
  2476. :end end
  2477. :contents-begin contents-begin
  2478. :contents-end contents-end
  2479. :post-blank post-blank))))))
  2480. (defun org-element-bold-interpreter (_ contents)
  2481. "Interpret bold object as Org syntax.
  2482. CONTENTS is the contents of the object."
  2483. (format "*%s*" contents))
  2484. ;;;; Citation
  2485. (defun org-element-citation-parser ()
  2486. "Parse citation object at point, if any.
  2487. When at a citation object, return a list whose car is `citation'
  2488. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2489. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2490. keywords. Otherwise, return nil.
  2491. Assume point is at the beginning of the citation."
  2492. (when (looking-at org-element-citation-prefix-re)
  2493. (let* ((begin (point))
  2494. (style (and (match-end 1)
  2495. (match-string-no-properties 1)))
  2496. ;; Ignore blanks between cite type and prefix or key.
  2497. (start (match-end 0))
  2498. (closing (with-syntax-table org-element--pair-square-table
  2499. (ignore-errors (scan-lists begin 1 0)))))
  2500. (save-excursion
  2501. (when (and closing
  2502. (re-search-forward org-element-citation-key-re closing t))
  2503. ;; Find prefix, if any.
  2504. (let ((first-key-end (match-end 0))
  2505. (types (org-element-restriction 'citation-reference))
  2506. (cite
  2507. (list 'citation
  2508. (list :style style
  2509. :begin begin
  2510. :post-blank (progn
  2511. (goto-char closing)
  2512. (skip-chars-forward " \t"))
  2513. :end (point)))))
  2514. ;; `:contents-begin' depends on the presence of
  2515. ;; a non-empty common prefix.
  2516. (goto-char first-key-end)
  2517. (if (not (search-backward ";" start t))
  2518. (org-element-put-property cite :contents-begin start)
  2519. (when (< start (point))
  2520. (org-element-put-property
  2521. cite :prefix
  2522. (org-element--parse-objects start (point) nil types cite)))
  2523. (forward-char)
  2524. (org-element-put-property cite :contents-begin (point)))
  2525. ;; `:contents-end' depends on the presence of a non-empty
  2526. ;; common suffix.
  2527. (goto-char (1- closing))
  2528. (skip-chars-backward " \r\t\n")
  2529. (let ((end (point)))
  2530. (if (or (not (search-backward ";" first-key-end t))
  2531. (re-search-forward org-element-citation-key-re end t))
  2532. (org-element-put-property cite :contents-end end)
  2533. (forward-char)
  2534. (when (< (point) end)
  2535. (org-element-put-property
  2536. cite :suffix
  2537. (org-element--parse-objects (point) end nil types cite)))
  2538. (org-element-put-property cite :contents-end (point))))
  2539. cite))))))
  2540. (defun org-element-citation-interpreter (citation contents)
  2541. "Interpret CITATION object as Org syntax.
  2542. CONTENTS is the contents of the object, as a string."
  2543. (let ((prefix (org-element-property :prefix citation))
  2544. (suffix (org-element-property :suffix citation))
  2545. (style (org-element-property :style citation)))
  2546. (concat "[cite"
  2547. (and style (concat "/" style))
  2548. ":"
  2549. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2550. (if suffix
  2551. (concat contents (org-element-interpret-data suffix))
  2552. ;; Remove spurious semicolon.
  2553. (substring contents nil -1))
  2554. "]")))
  2555. ;;;; Citation Reference
  2556. (defun org-element-citation-reference-parser ()
  2557. "Parse citation reference object at point, if any.
  2558. When at a reference, return a list whose car is
  2559. `citation-reference', and cdr is a plist with `:key',
  2560. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2561. Assume point is at the beginning of the reference."
  2562. (save-excursion
  2563. (let ((begin (point)))
  2564. (when (re-search-forward org-element-citation-key-re nil t)
  2565. (let* ((key (match-string-no-properties 1))
  2566. (key-start (match-beginning 0))
  2567. (key-end (match-end 0))
  2568. (separator (search-forward ";" nil t))
  2569. (end (or separator (point-max)))
  2570. (suffix-end (if separator (1- end) end))
  2571. (types (org-element-restriction 'citation-reference))
  2572. (reference
  2573. (list 'citation-reference
  2574. (list :key key
  2575. :begin begin
  2576. :end end
  2577. :post-blank 0))))
  2578. (when (< begin key-start)
  2579. (org-element-put-property
  2580. reference :prefix
  2581. (org-element--parse-objects begin key-start nil types reference)))
  2582. (when (< key-end suffix-end)
  2583. (org-element-put-property
  2584. reference :suffix
  2585. (org-element--parse-objects key-end suffix-end nil types reference)))
  2586. reference)))))
  2587. (defun org-element-citation-reference-interpreter (citation-reference _)
  2588. "Interpret CITATION-REFERENCE object as Org syntax."
  2589. (concat (org-element-interpret-data
  2590. (org-element-property :prefix citation-reference))
  2591. "@" (org-element-property :key citation-reference)
  2592. (org-element-interpret-data
  2593. (org-element-property :suffix citation-reference))
  2594. ";"))
  2595. ;;;; Code
  2596. (defun org-element-code-parser ()
  2597. "Parse code object at point, if any.
  2598. When at a code object, return a list whose car is `code' and cdr
  2599. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2600. keywords. Otherwise, return nil.
  2601. Assume point is at the first tilde marker."
  2602. (save-excursion
  2603. (unless (bolp) (backward-char 1))
  2604. (when (looking-at org-verbatim-re)
  2605. (let ((begin (match-beginning 2))
  2606. (value (match-string-no-properties 4))
  2607. (post-blank (progn (goto-char (match-end 2))
  2608. (skip-chars-forward " \t")))
  2609. (end (point)))
  2610. (list 'code
  2611. (list :value value
  2612. :begin begin
  2613. :end end
  2614. :post-blank post-blank))))))
  2615. (defun org-element-code-interpreter (code _)
  2616. "Interpret CODE object as Org syntax."
  2617. (format "~%s~" (org-element-property :value code)))
  2618. ;;;; Entity
  2619. (defun org-element-entity-parser ()
  2620. "Parse entity at point, if any.
  2621. When at an entity, return a list whose car is `entity' and cdr
  2622. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2623. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2624. `:post-blank' as keywords. Otherwise, return nil.
  2625. Assume point is at the beginning of the entity."
  2626. (catch 'no-object
  2627. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2628. (save-excursion
  2629. (let* ((value (or (org-entity-get (match-string 1))
  2630. (throw 'no-object nil)))
  2631. (begin (match-beginning 0))
  2632. (bracketsp (string= (match-string 2) "{}"))
  2633. (post-blank (progn (goto-char (match-end 1))
  2634. (when bracketsp (forward-char 2))
  2635. (skip-chars-forward " \t")))
  2636. (end (point)))
  2637. (list 'entity
  2638. (list :name (car value)
  2639. :latex (nth 1 value)
  2640. :latex-math-p (nth 2 value)
  2641. :html (nth 3 value)
  2642. :ascii (nth 4 value)
  2643. :latin1 (nth 5 value)
  2644. :utf-8 (nth 6 value)
  2645. :begin begin
  2646. :end end
  2647. :use-brackets-p bracketsp
  2648. :post-blank post-blank)))))))
  2649. (defun org-element-entity-interpreter (entity _)
  2650. "Interpret ENTITY object as Org syntax."
  2651. (concat "\\"
  2652. (org-element-property :name entity)
  2653. (when (org-element-property :use-brackets-p entity) "{}")))
  2654. ;;;; Export Snippet
  2655. (defun org-element-export-snippet-parser ()
  2656. "Parse export snippet at point.
  2657. When at an export snippet, return a list whose car is
  2658. `export-snippet' and cdr a plist with `:begin', `:end',
  2659. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2660. return nil.
  2661. Assume point is at the beginning of the snippet."
  2662. (save-excursion
  2663. (let (contents-end)
  2664. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2665. (setq contents-end
  2666. (save-match-data (goto-char (match-end 0))
  2667. (re-search-forward "@@" nil t)
  2668. (match-beginning 0))))
  2669. (let* ((begin (match-beginning 0))
  2670. (back-end (match-string-no-properties 1))
  2671. (value (buffer-substring-no-properties
  2672. (match-end 0) contents-end))
  2673. (post-blank (skip-chars-forward " \t"))
  2674. (end (point)))
  2675. (list 'export-snippet
  2676. (list :back-end back-end
  2677. :value value
  2678. :begin begin
  2679. :end end
  2680. :post-blank post-blank)))))))
  2681. (defun org-element-export-snippet-interpreter (export-snippet _)
  2682. "Interpret EXPORT-SNIPPET object as Org syntax."
  2683. (format "@@%s:%s@@"
  2684. (org-element-property :back-end export-snippet)
  2685. (org-element-property :value export-snippet)))
  2686. ;;;; Footnote Reference
  2687. (defun org-element-footnote-reference-parser ()
  2688. "Parse footnote reference at point, if any.
  2689. When at a footnote reference, return a list whose car is
  2690. `footnote-reference' and cdr a plist with `:label', `:type',
  2691. `:begin', `:end', `:contents-begin', `:contents-end' and
  2692. `:post-blank' as keywords. Otherwise, return nil."
  2693. (when (looking-at org-footnote-re)
  2694. (let ((closing (with-syntax-table org-element--pair-square-table
  2695. (ignore-errors (scan-lists (point) 1 0)))))
  2696. (when closing
  2697. (save-excursion
  2698. (let* ((begin (point))
  2699. (label (match-string-no-properties 1))
  2700. (inner-begin (match-end 0))
  2701. (inner-end (1- closing))
  2702. (type (if (match-end 2) 'inline 'standard))
  2703. (post-blank (progn (goto-char closing)
  2704. (skip-chars-forward " \t")))
  2705. (end (point)))
  2706. (list 'footnote-reference
  2707. (list :label label
  2708. :type type
  2709. :begin begin
  2710. :end end
  2711. :contents-begin (and (eq type 'inline) inner-begin)
  2712. :contents-end (and (eq type 'inline) inner-end)
  2713. :post-blank post-blank))))))))
  2714. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2715. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2716. CONTENTS is its definition, when inline, or nil."
  2717. (format "[fn:%s%s]"
  2718. (or (org-element-property :label footnote-reference) "")
  2719. (if contents (concat ":" contents) "")))
  2720. ;;;; Inline Babel Call
  2721. (defun org-element-inline-babel-call-parser ()
  2722. "Parse inline babel call at point, if any.
  2723. When at an inline babel call, return a list whose car is
  2724. `inline-babel-call' and cdr a plist with `:call',
  2725. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2726. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2727. Assume point is at the beginning of the babel call."
  2728. (save-excursion
  2729. (catch :no-object
  2730. (when (let ((case-fold-search nil))
  2731. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2732. (goto-char (match-end 1))
  2733. (let* ((begin (match-beginning 0))
  2734. (call (match-string-no-properties 1))
  2735. (inside-header
  2736. (let ((p (org-element--parse-paired-brackets ?\[)))
  2737. (and (org-string-nw-p p)
  2738. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2739. (arguments (org-string-nw-p
  2740. (or (org-element--parse-paired-brackets ?\()
  2741. ;; Parenthesis are mandatory.
  2742. (throw :no-object nil))))
  2743. (end-header
  2744. (let ((p (org-element--parse-paired-brackets ?\[)))
  2745. (and (org-string-nw-p p)
  2746. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2747. (value (buffer-substring-no-properties begin (point)))
  2748. (post-blank (skip-chars-forward " \t"))
  2749. (end (point)))
  2750. (list 'inline-babel-call
  2751. (list :call call
  2752. :inside-header inside-header
  2753. :arguments arguments
  2754. :end-header end-header
  2755. :begin begin
  2756. :end end
  2757. :value value
  2758. :post-blank post-blank)))))))
  2759. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2760. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2761. (concat "call_"
  2762. (org-element-property :call inline-babel-call)
  2763. (let ((h (org-element-property :inside-header inline-babel-call)))
  2764. (and h (format "[%s]" h)))
  2765. "(" (org-element-property :arguments inline-babel-call) ")"
  2766. (let ((h (org-element-property :end-header inline-babel-call)))
  2767. (and h (format "[%s]" h)))))
  2768. ;;;; Inline Src Block
  2769. (defun org-element-inline-src-block-parser ()
  2770. "Parse inline source block at point, if any.
  2771. When at an inline source block, return a list whose car is
  2772. `inline-src-block' and cdr a plist with `:begin', `:end',
  2773. `:language', `:value', `:parameters' and `:post-blank' as
  2774. keywords. Otherwise, return nil.
  2775. Assume point is at the beginning of the inline source block."
  2776. (save-excursion
  2777. (catch :no-object
  2778. (when (let ((case-fold-search nil))
  2779. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2780. (goto-char (match-end 1))
  2781. (let ((begin (match-beginning 0))
  2782. (language (match-string-no-properties 1))
  2783. (parameters
  2784. (let ((p (org-element--parse-paired-brackets ?\[)))
  2785. (and (org-string-nw-p p)
  2786. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2787. (value (or (org-element--parse-paired-brackets ?\{)
  2788. (throw :no-object nil)))
  2789. (post-blank (skip-chars-forward " \t")))
  2790. (list 'inline-src-block
  2791. (list :language language
  2792. :value value
  2793. :parameters parameters
  2794. :begin begin
  2795. :end (point)
  2796. :post-blank post-blank)))))))
  2797. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2798. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2799. (let ((language (org-element-property :language inline-src-block))
  2800. (arguments (org-element-property :parameters inline-src-block))
  2801. (body (org-element-property :value inline-src-block)))
  2802. (format "src_%s%s{%s}"
  2803. language
  2804. (if arguments (format "[%s]" arguments) "")
  2805. body)))
  2806. ;;;; Italic
  2807. (defun org-element-italic-parser ()
  2808. "Parse italic object at point, if any.
  2809. When at an italic object, return a list whose car is `italic' and
  2810. cdr is a plist with `:begin', `:end', `:contents-begin' and
  2811. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2812. nil.
  2813. Assume point is at the first slash marker."
  2814. (save-excursion
  2815. (unless (bolp) (backward-char 1))
  2816. (when (looking-at org-emph-re)
  2817. (let ((begin (match-beginning 2))
  2818. (contents-begin (match-beginning 4))
  2819. (contents-end (match-end 4))
  2820. (post-blank (progn (goto-char (match-end 2))
  2821. (skip-chars-forward " \t")))
  2822. (end (point)))
  2823. (list 'italic
  2824. (list :begin begin
  2825. :end end
  2826. :contents-begin contents-begin
  2827. :contents-end contents-end
  2828. :post-blank post-blank))))))
  2829. (defun org-element-italic-interpreter (_ contents)
  2830. "Interpret italic object as Org syntax.
  2831. CONTENTS is the contents of the object."
  2832. (format "/%s/" contents))
  2833. ;;;; Latex Fragment
  2834. (defun org-element-latex-fragment-parser ()
  2835. "Parse LaTeX fragment at point, if any.
  2836. When at a LaTeX fragment, return a list whose car is
  2837. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  2838. and `:post-blank' as keywords. Otherwise, return nil.
  2839. Assume point is at the beginning of the LaTeX fragment."
  2840. (catch 'no-object
  2841. (save-excursion
  2842. (let* ((begin (point))
  2843. (after-fragment
  2844. (cond
  2845. ((not (eq ?$ (char-after)))
  2846. (pcase (char-after (1+ (point)))
  2847. (?\( (search-forward "\\)" nil t))
  2848. (?\[ (search-forward "\\]" nil t))
  2849. (_
  2850. ;; Macro.
  2851. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  2852. \\|\\({[^{}\n]*}\\)\\)*")
  2853. (match-end 0)))))
  2854. ((eq ?$ (char-after (1+ (point))))
  2855. (search-forward "$$" nil t 2))
  2856. (t
  2857. (and (not (eq ?$ (char-before)))
  2858. (not (memq (char-after (1+ (point)))
  2859. '(?\s ?\t ?\n ?, ?. ?\;)))
  2860. (search-forward "$" nil t 2)
  2861. (not (memq (char-before (match-beginning 0))
  2862. '(?\s ?\t ?\n ?, ?.)))
  2863. (looking-at-p
  2864. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  2865. (point)))))
  2866. (post-blank
  2867. (if (not after-fragment) (throw 'no-object nil)
  2868. (goto-char after-fragment)
  2869. (skip-chars-forward " \t")))
  2870. (end (point)))
  2871. (list 'latex-fragment
  2872. (list :value (buffer-substring-no-properties begin after-fragment)
  2873. :begin begin
  2874. :end end
  2875. :post-blank post-blank))))))
  2876. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  2877. "Interpret LATEX-FRAGMENT object as Org syntax."
  2878. (org-element-property :value latex-fragment))
  2879. ;;;; Line Break
  2880. (defun org-element-line-break-parser ()
  2881. "Parse line break at point, if any.
  2882. When at a line break, return a list whose car is `line-break',
  2883. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  2884. Otherwise, return nil.
  2885. Assume point is at the beginning of the line break."
  2886. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  2887. (not (eq (char-before) ?\\)))
  2888. (list 'line-break
  2889. (list :begin (point)
  2890. :end (line-beginning-position 2)
  2891. :post-blank 0))))
  2892. (defun org-element-line-break-interpreter (&rest _)
  2893. "Interpret LINE-BREAK object as Org syntax."
  2894. "\\\\\n")
  2895. ;;;; Link
  2896. (defun org-element-link-parser ()
  2897. "Parse link at point, if any.
  2898. When at a link, return a list whose car is `link' and cdr a plist
  2899. with `:type', `:path', `:format', `:raw-link', `:application',
  2900. `:search-option', `:begin', `:end', `:contents-begin',
  2901. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  2902. nil.
  2903. Assume point is at the beginning of the link."
  2904. (catch 'no-object
  2905. (let ((begin (point))
  2906. end contents-begin contents-end link-end post-blank path type format
  2907. raw-link search-option application)
  2908. (cond
  2909. ;; Type 1: Text targeted from a radio target.
  2910. ((and org-target-link-regexp
  2911. (save-excursion (or (bolp) (backward-char))
  2912. (looking-at org-target-link-regexp)))
  2913. (setq type "radio")
  2914. (setq format 'plain)
  2915. (setq link-end (match-end 1))
  2916. (setq path (match-string-no-properties 1))
  2917. (setq contents-begin (match-beginning 1))
  2918. (setq contents-end (match-end 1)))
  2919. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  2920. ((looking-at org-link-bracket-re)
  2921. (setq format 'bracket)
  2922. (setq contents-begin (match-beginning 2))
  2923. (setq contents-end (match-end 2))
  2924. (setq link-end (match-end 0))
  2925. ;; RAW-LINK is the original link. Decode any encoding.
  2926. ;; Expand any abbreviation in it.
  2927. ;;
  2928. ;; Also treat any newline character and associated
  2929. ;; indentation as a single space character. This is not
  2930. ;; compatible with RFC 3986, which requires to ignore
  2931. ;; them altogether. However, doing so would require
  2932. ;; users to encode spaces on the fly when writing links
  2933. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  2934. ;; [[shell:ls *.org]], which defeats Org's focus on
  2935. ;; simplicity.
  2936. (setq raw-link (org-link-expand-abbrev
  2937. (org-link-unescape
  2938. (replace-regexp-in-string
  2939. "[ \t]*\n[ \t]*" " "
  2940. (match-string-no-properties 1)))))
  2941. ;; Determine TYPE of link and set PATH accordingly. According
  2942. ;; to RFC 3986, remove whitespaces from URI in external links.
  2943. ;; In internal ones, treat indentation as a single space.
  2944. (cond
  2945. ;; File type.
  2946. ((or (file-name-absolute-p raw-link)
  2947. (string-match "\\`\\.\\.?/" raw-link))
  2948. (setq type "file")
  2949. (setq path raw-link))
  2950. ;; Explicit type (http, irc, bbdb...).
  2951. ((string-match org-link-types-re raw-link)
  2952. (setq type (match-string 1 raw-link))
  2953. (setq path (substring raw-link (match-end 0))))
  2954. ;; Code-ref type: PATH is the name of the reference.
  2955. ((and (string-match-p "\\`(" raw-link)
  2956. (string-match-p ")\\'" raw-link))
  2957. (setq type "coderef")
  2958. (setq path (substring raw-link 1 -1)))
  2959. ;; Custom-id type: PATH is the name of the custom id.
  2960. ((= (string-to-char raw-link) ?#)
  2961. (setq type "custom-id")
  2962. (setq path (substring raw-link 1)))
  2963. ;; Fuzzy type: Internal link either matches a target, an
  2964. ;; headline name or nothing. PATH is the target or
  2965. ;; headline's name.
  2966. (t
  2967. (setq type "fuzzy")
  2968. (setq path raw-link))))
  2969. ;; Type 3: Plain link, e.g., https://orgmode.org
  2970. ((looking-at org-link-plain-re)
  2971. (setq format 'plain)
  2972. (setq raw-link (match-string-no-properties 0))
  2973. (setq type (match-string-no-properties 1))
  2974. (setq link-end (match-end 0))
  2975. (setq path (match-string-no-properties 2)))
  2976. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  2977. ;; bracket links, follow RFC 3986 and remove any extra
  2978. ;; whitespace in URI.
  2979. ((looking-at org-link-angle-re)
  2980. (setq format 'angle)
  2981. (setq type (match-string-no-properties 1))
  2982. (setq link-end (match-end 0))
  2983. (setq raw-link
  2984. (buffer-substring-no-properties
  2985. (match-beginning 1) (match-end 2)))
  2986. (setq path (replace-regexp-in-string
  2987. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  2988. (t (throw 'no-object nil)))
  2989. ;; In any case, deduce end point after trailing white space from
  2990. ;; LINK-END variable.
  2991. (save-excursion
  2992. (setq post-blank
  2993. (progn (goto-char link-end) (skip-chars-forward " \t")))
  2994. (setq end (point)))
  2995. ;; Special "file"-type link processing. Extract opening
  2996. ;; application and search option, if any. Also normalize URI.
  2997. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  2998. (setq application (match-string 1 type))
  2999. (setq type "file")
  3000. (when (string-match "::\\(.*\\)\\'" path)
  3001. (setq search-option (match-string 1 path))
  3002. (setq path (replace-match "" nil nil path)))
  3003. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3004. ;; Translate link, if `org-link-translation-function' is set.
  3005. (let ((trans (and (functionp org-link-translation-function)
  3006. (funcall org-link-translation-function type path))))
  3007. (when trans
  3008. (setq type (car trans))
  3009. (setq path (cdr trans))))
  3010. (list 'link
  3011. (list :type type
  3012. :path path
  3013. :format format
  3014. :raw-link (or raw-link path)
  3015. :application application
  3016. :search-option search-option
  3017. :begin begin
  3018. :end end
  3019. :contents-begin contents-begin
  3020. :contents-end contents-end
  3021. :post-blank post-blank)))))
  3022. (defun org-element-link-interpreter (link contents)
  3023. "Interpret LINK object as Org syntax.
  3024. CONTENTS is the contents of the object, or nil."
  3025. (let ((type (org-element-property :type link))
  3026. (path (org-element-property :path link)))
  3027. (if (string= type "radio") path
  3028. (let ((fmt (pcase (org-element-property :format link)
  3029. ;; Links with contents and internal links have to
  3030. ;; use bracket syntax. Ignore `:format' in these
  3031. ;; cases. This is also the default syntax when the
  3032. ;; property is not defined, e.g., when the object
  3033. ;; was crafted by the user.
  3034. ((guard contents)
  3035. (format "[[%%s][%s]]"
  3036. ;; Since this is going to be used as
  3037. ;; a format string, escape percent signs
  3038. ;; in description.
  3039. (replace-regexp-in-string "%" "%%" contents)))
  3040. ((or `bracket
  3041. `nil
  3042. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3043. "[[%s]]")
  3044. ;; Otherwise, just obey to `:format'.
  3045. (`angle "<%s>")
  3046. (`plain "%s")
  3047. (f (error "Wrong `:format' value: %s" f)))))
  3048. (format fmt
  3049. (pcase type
  3050. ("coderef" (format "(%s)" path))
  3051. ("custom-id" (concat "#" path))
  3052. ("file"
  3053. (let ((app (org-element-property :application link))
  3054. (opt (org-element-property :search-option link)))
  3055. (concat type (and app (concat "+" app)) ":"
  3056. path
  3057. (and opt (concat "::" opt)))))
  3058. ("fuzzy" path)
  3059. (_ (concat type ":" path))))))))
  3060. ;;;; Macro
  3061. (defun org-element-macro-parser ()
  3062. "Parse macro at point, if any.
  3063. When at a macro, return a list whose car is `macro' and cdr
  3064. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3065. `:post-blank' as keywords. Otherwise, return nil.
  3066. Assume point is at the macro."
  3067. (save-excursion
  3068. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3069. (let ((begin (point))
  3070. (key (downcase (match-string-no-properties 1)))
  3071. (value (match-string-no-properties 0))
  3072. (post-blank (progn (goto-char (match-end 0))
  3073. (skip-chars-forward " \t")))
  3074. (end (point))
  3075. (args (pcase (match-string-no-properties 3)
  3076. (`nil nil)
  3077. (a (org-macro-extract-arguments
  3078. (replace-regexp-in-string
  3079. "[ \t\r\n]+" " " (org-trim a)))))))
  3080. (list 'macro
  3081. (list :key key
  3082. :value value
  3083. :args args
  3084. :begin begin
  3085. :end end
  3086. :post-blank post-blank))))))
  3087. (defun org-element-macro-interpreter (macro _)
  3088. "Interpret MACRO object as Org syntax."
  3089. (format "{{{%s%s}}}"
  3090. (org-element-property :key macro)
  3091. (pcase (org-element-property :args macro)
  3092. (`nil "")
  3093. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3094. ;;;; Radio-target
  3095. (defun org-element-radio-target-parser ()
  3096. "Parse radio target at point, if any.
  3097. When at a radio target, return a list whose car is `radio-target'
  3098. and cdr a plist with `:begin', `:end', `:contents-begin',
  3099. `:contents-end', `:value' and `:post-blank' as keywords.
  3100. Otherwise, return nil.
  3101. Assume point is at the radio target."
  3102. (save-excursion
  3103. (when (looking-at org-radio-target-regexp)
  3104. (let ((begin (point))
  3105. (contents-begin (match-beginning 1))
  3106. (contents-end (match-end 1))
  3107. (value (match-string-no-properties 1))
  3108. (post-blank (progn (goto-char (match-end 0))
  3109. (skip-chars-forward " \t")))
  3110. (end (point)))
  3111. (list 'radio-target
  3112. (list :begin begin
  3113. :end end
  3114. :contents-begin contents-begin
  3115. :contents-end contents-end
  3116. :post-blank post-blank
  3117. :value value))))))
  3118. (defun org-element-radio-target-interpreter (_ contents)
  3119. "Interpret target object as Org syntax.
  3120. CONTENTS is the contents of the object."
  3121. (concat "<<<" contents ">>>"))
  3122. ;;;; Statistics Cookie
  3123. (defun org-element-statistics-cookie-parser ()
  3124. "Parse statistics cookie at point, if any.
  3125. When at a statistics cookie, return a list whose car is
  3126. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3127. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3128. Assume point is at the beginning of the statistics-cookie."
  3129. (save-excursion
  3130. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3131. (let* ((begin (point))
  3132. (value (buffer-substring-no-properties
  3133. (match-beginning 0) (match-end 0)))
  3134. (post-blank (progn (goto-char (match-end 0))
  3135. (skip-chars-forward " \t")))
  3136. (end (point)))
  3137. (list 'statistics-cookie
  3138. (list :begin begin
  3139. :end end
  3140. :value value
  3141. :post-blank post-blank))))))
  3142. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3143. "Interpret STATISTICS-COOKIE object as Org syntax."
  3144. (org-element-property :value statistics-cookie))
  3145. ;;;; Strike-Through
  3146. (defun org-element-strike-through-parser ()
  3147. "Parse strike-through object at point, if any.
  3148. When at a strike-through object, return a list whose car is
  3149. `strike-through' and cdr is a plist with `:begin', `:end',
  3150. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3151. Otherwise, return nil.
  3152. Assume point is at the first plus sign marker."
  3153. (save-excursion
  3154. (unless (bolp) (backward-char 1))
  3155. (when (looking-at org-emph-re)
  3156. (let ((begin (match-beginning 2))
  3157. (contents-begin (match-beginning 4))
  3158. (contents-end (match-end 4))
  3159. (post-blank (progn (goto-char (match-end 2))
  3160. (skip-chars-forward " \t")))
  3161. (end (point)))
  3162. (list 'strike-through
  3163. (list :begin begin
  3164. :end end
  3165. :contents-begin contents-begin
  3166. :contents-end contents-end
  3167. :post-blank post-blank))))))
  3168. (defun org-element-strike-through-interpreter (_ contents)
  3169. "Interpret strike-through object as Org syntax.
  3170. CONTENTS is the contents of the object."
  3171. (format "+%s+" contents))
  3172. ;;;; Subscript
  3173. (defun org-element-subscript-parser ()
  3174. "Parse subscript at point, if any.
  3175. When at a subscript object, return a list whose car is
  3176. `subscript' and cdr a plist with `:begin', `:end',
  3177. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3178. `:post-blank' as keywords. Otherwise, return nil.
  3179. Assume point is at the underscore."
  3180. (save-excursion
  3181. (unless (bolp) (backward-char))
  3182. (when (looking-at org-match-substring-regexp)
  3183. (let ((bracketsp (match-beginning 4))
  3184. (begin (match-beginning 2))
  3185. (contents-begin (or (match-beginning 4)
  3186. (match-beginning 3)))
  3187. (contents-end (or (match-end 4) (match-end 3)))
  3188. (post-blank (progn (goto-char (match-end 0))
  3189. (skip-chars-forward " \t")))
  3190. (end (point)))
  3191. (list 'subscript
  3192. (list :begin begin
  3193. :end end
  3194. :use-brackets-p bracketsp
  3195. :contents-begin contents-begin
  3196. :contents-end contents-end
  3197. :post-blank post-blank))))))
  3198. (defun org-element-subscript-interpreter (subscript contents)
  3199. "Interpret SUBSCRIPT object as Org syntax.
  3200. CONTENTS is the contents of the object."
  3201. (format
  3202. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3203. contents))
  3204. ;;;; Superscript
  3205. (defun org-element-superscript-parser ()
  3206. "Parse superscript at point, if any.
  3207. When at a superscript object, return a list whose car is
  3208. `superscript' and cdr a plist with `:begin', `:end',
  3209. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3210. `:post-blank' as keywords. Otherwise, return nil.
  3211. Assume point is at the caret."
  3212. (save-excursion
  3213. (unless (bolp) (backward-char))
  3214. (when (looking-at org-match-substring-regexp)
  3215. (let ((bracketsp (match-beginning 4))
  3216. (begin (match-beginning 2))
  3217. (contents-begin (or (match-beginning 4)
  3218. (match-beginning 3)))
  3219. (contents-end (or (match-end 4) (match-end 3)))
  3220. (post-blank (progn (goto-char (match-end 0))
  3221. (skip-chars-forward " \t")))
  3222. (end (point)))
  3223. (list 'superscript
  3224. (list :begin begin
  3225. :end end
  3226. :use-brackets-p bracketsp
  3227. :contents-begin contents-begin
  3228. :contents-end contents-end
  3229. :post-blank post-blank))))))
  3230. (defun org-element-superscript-interpreter (superscript contents)
  3231. "Interpret SUPERSCRIPT object as Org syntax.
  3232. CONTENTS is the contents of the object."
  3233. (format
  3234. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3235. contents))
  3236. ;;;; Table Cell
  3237. (defun org-element-table-cell-parser ()
  3238. "Parse table cell at point.
  3239. Return a list whose car is `table-cell' and cdr is a plist
  3240. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3241. and `:post-blank' keywords."
  3242. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3243. (let* ((begin (match-beginning 0))
  3244. (end (match-end 0))
  3245. (contents-begin (match-beginning 1))
  3246. (contents-end (match-end 1)))
  3247. (list 'table-cell
  3248. (list :begin begin
  3249. :end end
  3250. :contents-begin contents-begin
  3251. :contents-end contents-end
  3252. :post-blank 0))))
  3253. (defun org-element-table-cell-interpreter (_ contents)
  3254. "Interpret table-cell element as Org syntax.
  3255. CONTENTS is the contents of the cell, or nil."
  3256. (concat " " contents " |"))
  3257. ;;;; Target
  3258. (defun org-element-target-parser ()
  3259. "Parse target at point, if any.
  3260. When at a target, return a list whose car is `target' and cdr
  3261. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3262. keywords. Otherwise, return nil.
  3263. Assume point is at the target."
  3264. (save-excursion
  3265. (when (looking-at org-target-regexp)
  3266. (let ((begin (point))
  3267. (value (match-string-no-properties 1))
  3268. (post-blank (progn (goto-char (match-end 0))
  3269. (skip-chars-forward " \t")))
  3270. (end (point)))
  3271. (list 'target
  3272. (list :begin begin
  3273. :end end
  3274. :value value
  3275. :post-blank post-blank))))))
  3276. (defun org-element-target-interpreter (target _)
  3277. "Interpret TARGET object as Org syntax."
  3278. (format "<<%s>>" (org-element-property :value target)))
  3279. ;;;; Timestamp
  3280. (defconst org-element--timestamp-regexp
  3281. (concat org-ts-regexp-both
  3282. "\\|"
  3283. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3284. "\\|"
  3285. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3286. "Regexp matching any timestamp type object.")
  3287. (defun org-element-timestamp-parser ()
  3288. "Parse time stamp at point, if any.
  3289. When at a time stamp, return a list whose car is `timestamp', and
  3290. cdr a plist with `:type', `:raw-value', `:year-start',
  3291. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3292. `:year-end', `:month-end', `:day-end', `:hour-end',
  3293. `:minute-end', `:repeater-type', `:repeater-value',
  3294. `:repeater-unit', `:warning-type', `:warning-value',
  3295. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3296. Otherwise, return nil.
  3297. Assume point is at the beginning of the timestamp."
  3298. (when (looking-at-p org-element--timestamp-regexp)
  3299. (save-excursion
  3300. (let* ((begin (point))
  3301. (activep (eq (char-after) ?<))
  3302. (raw-value
  3303. (progn
  3304. (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
  3305. (match-string-no-properties 0)))
  3306. (date-start (match-string-no-properties 1))
  3307. (date-end (match-string 3))
  3308. (diaryp (match-beginning 2))
  3309. (post-blank (progn (goto-char (match-end 0))
  3310. (skip-chars-forward " \t")))
  3311. (end (point))
  3312. (time-range
  3313. (and (not diaryp)
  3314. (string-match
  3315. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3316. date-start)
  3317. (cons (string-to-number (match-string 2 date-start))
  3318. (string-to-number (match-string 3 date-start)))))
  3319. (type (cond (diaryp 'diary)
  3320. ((and activep (or date-end time-range)) 'active-range)
  3321. (activep 'active)
  3322. ((or date-end time-range) 'inactive-range)
  3323. (t 'inactive)))
  3324. (repeater-props
  3325. (and (not diaryp)
  3326. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3327. raw-value)
  3328. (list
  3329. :repeater-type
  3330. (let ((type (match-string 1 raw-value)))
  3331. (cond ((equal "++" type) 'catch-up)
  3332. ((equal ".+" type) 'restart)
  3333. (t 'cumulate)))
  3334. :repeater-value (string-to-number (match-string 2 raw-value))
  3335. :repeater-unit
  3336. (pcase (string-to-char (match-string 3 raw-value))
  3337. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3338. (warning-props
  3339. (and (not diaryp)
  3340. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3341. (list
  3342. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3343. :warning-value (string-to-number (match-string 2 raw-value))
  3344. :warning-unit
  3345. (pcase (string-to-char (match-string 3 raw-value))
  3346. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3347. year-start month-start day-start hour-start minute-start year-end
  3348. month-end day-end hour-end minute-end)
  3349. ;; Parse date-start.
  3350. (unless diaryp
  3351. (let ((date (org-parse-time-string date-start t)))
  3352. (setq year-start (nth 5 date)
  3353. month-start (nth 4 date)
  3354. day-start (nth 3 date)
  3355. hour-start (nth 2 date)
  3356. minute-start (nth 1 date))))
  3357. ;; Compute date-end. It can be provided directly in time-stamp,
  3358. ;; or extracted from time range. Otherwise, it defaults to the
  3359. ;; same values as date-start.
  3360. (unless diaryp
  3361. (let ((date (and date-end (org-parse-time-string date-end t))))
  3362. (setq year-end (or (nth 5 date) year-start)
  3363. month-end (or (nth 4 date) month-start)
  3364. day-end (or (nth 3 date) day-start)
  3365. hour-end (or (nth 2 date) (car time-range) hour-start)
  3366. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3367. (list 'timestamp
  3368. (nconc (list :type type
  3369. :raw-value raw-value
  3370. :year-start year-start
  3371. :month-start month-start
  3372. :day-start day-start
  3373. :hour-start hour-start
  3374. :minute-start minute-start
  3375. :year-end year-end
  3376. :month-end month-end
  3377. :day-end day-end
  3378. :hour-end hour-end
  3379. :minute-end minute-end
  3380. :begin begin
  3381. :end end
  3382. :post-blank post-blank)
  3383. repeater-props
  3384. warning-props))))))
  3385. (defun org-element-timestamp-interpreter (timestamp _)
  3386. "Interpret TIMESTAMP object as Org syntax."
  3387. (let* ((repeat-string
  3388. (concat
  3389. (pcase (org-element-property :repeater-type timestamp)
  3390. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3391. (let ((val (org-element-property :repeater-value timestamp)))
  3392. (and val (number-to-string val)))
  3393. (pcase (org-element-property :repeater-unit timestamp)
  3394. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3395. (warning-string
  3396. (concat
  3397. (pcase (org-element-property :warning-type timestamp)
  3398. (`first "--") (`all "-"))
  3399. (let ((val (org-element-property :warning-value timestamp)))
  3400. (and val (number-to-string val)))
  3401. (pcase (org-element-property :warning-unit timestamp)
  3402. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3403. (build-ts-string
  3404. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3405. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3406. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3407. ;; specify a time range in the timestamp. REPEAT-STRING is
  3408. ;; the repeater string, if any.
  3409. (lambda (time activep &optional with-time-p hour-end minute-end)
  3410. (let ((ts (format-time-string
  3411. (funcall (if with-time-p #'cdr #'car)
  3412. org-time-stamp-formats)
  3413. time)))
  3414. (when (and hour-end minute-end)
  3415. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3416. (setq ts
  3417. (replace-match
  3418. (format "\\&-%02d:%02d" hour-end minute-end)
  3419. nil nil ts)))
  3420. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3421. (dolist (s (list repeat-string warning-string))
  3422. (when (org-string-nw-p s)
  3423. (setq ts (concat (substring ts 0 -1)
  3424. " "
  3425. s
  3426. (substring ts -1)))))
  3427. ;; Return value.
  3428. ts)))
  3429. (type (org-element-property :type timestamp)))
  3430. (pcase type
  3431. ((or `active `inactive)
  3432. (let* ((minute-start (org-element-property :minute-start timestamp))
  3433. (minute-end (org-element-property :minute-end timestamp))
  3434. (hour-start (org-element-property :hour-start timestamp))
  3435. (hour-end (org-element-property :hour-end timestamp))
  3436. (time-range-p (and hour-start hour-end minute-start minute-end
  3437. (or (/= hour-start hour-end)
  3438. (/= minute-start minute-end)))))
  3439. (funcall
  3440. build-ts-string
  3441. (encode-time 0
  3442. (or minute-start 0)
  3443. (or hour-start 0)
  3444. (org-element-property :day-start timestamp)
  3445. (org-element-property :month-start timestamp)
  3446. (org-element-property :year-start timestamp))
  3447. (eq type 'active)
  3448. (and hour-start minute-start)
  3449. (and time-range-p hour-end)
  3450. (and time-range-p minute-end))))
  3451. ((or `active-range `inactive-range)
  3452. (let ((minute-start (org-element-property :minute-start timestamp))
  3453. (minute-end (org-element-property :minute-end timestamp))
  3454. (hour-start (org-element-property :hour-start timestamp))
  3455. (hour-end (org-element-property :hour-end timestamp)))
  3456. (concat
  3457. (funcall
  3458. build-ts-string (encode-time
  3459. 0
  3460. (or minute-start 0)
  3461. (or hour-start 0)
  3462. (org-element-property :day-start timestamp)
  3463. (org-element-property :month-start timestamp)
  3464. (org-element-property :year-start timestamp))
  3465. (eq type 'active-range)
  3466. (and hour-start minute-start))
  3467. "--"
  3468. (funcall build-ts-string
  3469. (encode-time 0
  3470. (or minute-end 0)
  3471. (or hour-end 0)
  3472. (org-element-property :day-end timestamp)
  3473. (org-element-property :month-end timestamp)
  3474. (org-element-property :year-end timestamp))
  3475. (eq type 'active-range)
  3476. (and hour-end minute-end)))))
  3477. (_ (org-element-property :raw-value timestamp)))))
  3478. ;;;; Underline
  3479. (defun org-element-underline-parser ()
  3480. "Parse underline object at point, if any.
  3481. When at an underline object, return a list whose car is
  3482. `underline' and cdr is a plist with `:begin', `:end',
  3483. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3484. Otherwise, return nil.
  3485. Assume point is at the first underscore marker."
  3486. (save-excursion
  3487. (unless (bolp) (backward-char 1))
  3488. (when (looking-at org-emph-re)
  3489. (let ((begin (match-beginning 2))
  3490. (contents-begin (match-beginning 4))
  3491. (contents-end (match-end 4))
  3492. (post-blank (progn (goto-char (match-end 2))
  3493. (skip-chars-forward " \t")))
  3494. (end (point)))
  3495. (list 'underline
  3496. (list :begin begin
  3497. :end end
  3498. :contents-begin contents-begin
  3499. :contents-end contents-end
  3500. :post-blank post-blank))))))
  3501. (defun org-element-underline-interpreter (_ contents)
  3502. "Interpret underline object as Org syntax.
  3503. CONTENTS is the contents of the object."
  3504. (format "_%s_" contents))
  3505. ;;;; Verbatim
  3506. (defun org-element-verbatim-parser ()
  3507. "Parse verbatim object at point, if any.
  3508. When at a verbatim object, return a list whose car is `verbatim'
  3509. and cdr is a plist with `:value', `:begin', `:end' and
  3510. `:post-blank' keywords. Otherwise, return nil.
  3511. Assume point is at the first equal sign marker."
  3512. (save-excursion
  3513. (unless (bolp) (backward-char 1))
  3514. (when (looking-at org-verbatim-re)
  3515. (let ((begin (match-beginning 2))
  3516. (value (match-string-no-properties 4))
  3517. (post-blank (progn (goto-char (match-end 2))
  3518. (skip-chars-forward " \t")))
  3519. (end (point)))
  3520. (list 'verbatim
  3521. (list :value value
  3522. :begin begin
  3523. :end end
  3524. :post-blank post-blank))))))
  3525. (defun org-element-verbatim-interpreter (verbatim _)
  3526. "Interpret VERBATIM object as Org syntax."
  3527. (format "=%s=" (org-element-property :value verbatim)))
  3528. ;;; Parsing Element Starting At Point
  3529. ;;
  3530. ;; `org-element--current-element' is the core function of this section.
  3531. ;; It returns the Lisp representation of the element starting at
  3532. ;; point.
  3533. (defun org-element--current-element (limit &optional granularity mode structure)
  3534. "Parse the element starting at point.
  3535. Return value is a list like (TYPE PROPS) where TYPE is the type
  3536. of the element and PROPS a plist of properties associated to the
  3537. element.
  3538. Possible types are defined in `org-element-all-elements'.
  3539. LIMIT bounds the search.
  3540. Optional argument GRANULARITY determines the depth of the
  3541. recursion. Allowed values are `headline', `greater-element',
  3542. `element', `object' or nil. When it is broader than `object' (or
  3543. nil), secondary values will not be parsed, since they only
  3544. contain objects.
  3545. Optional argument MODE, when non-nil, can be either
  3546. `first-section', `item', `node-property', `planning',
  3547. `property-drawer', `section', `table-row', or `top-comment'.
  3548. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3549. computed.
  3550. This function assumes point is always at the beginning of the
  3551. element it has to parse."
  3552. (save-excursion
  3553. (let ((case-fold-search t)
  3554. ;; Determine if parsing depth allows for secondary strings
  3555. ;; parsing. It only applies to elements referenced in
  3556. ;; `org-element-secondary-value-alist'.
  3557. (raw-secondary-p (and granularity (not (eq granularity 'object)))))
  3558. (cond
  3559. ;; Item.
  3560. ((eq mode 'item)
  3561. (org-element-item-parser limit structure raw-secondary-p))
  3562. ;; Table Row.
  3563. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3564. ;; Node Property.
  3565. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3566. ;; Headline.
  3567. ((org-with-limited-levels (org-at-heading-p))
  3568. (org-element-headline-parser limit raw-secondary-p))
  3569. ;; Sections (must be checked after headline).
  3570. ((eq mode 'section) (org-element-section-parser limit))
  3571. ((eq mode 'first-section)
  3572. (org-element-section-parser
  3573. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3574. limit)))
  3575. ;; Comments.
  3576. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3577. (org-element-comment-parser limit))
  3578. ;; Planning.
  3579. ((and (eq mode 'planning)
  3580. (eq ?* (char-after (line-beginning-position 0)))
  3581. (looking-at org-planning-line-re))
  3582. (org-element-planning-parser limit))
  3583. ;; Property drawer.
  3584. ((and (pcase mode
  3585. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3586. ((or `property-drawer `top-comment)
  3587. (save-excursion
  3588. (beginning-of-line 0)
  3589. (not (looking-at "[[:blank:]]*$"))))
  3590. (_ nil))
  3591. (looking-at org-property-drawer-re))
  3592. (org-element-property-drawer-parser limit))
  3593. ;; When not at bol, point is at the beginning of an item or
  3594. ;; a footnote definition: next item is always a paragraph.
  3595. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3596. ;; Clock.
  3597. ((looking-at org-clock-line-re) (org-element-clock-parser limit))
  3598. ;; Inlinetask.
  3599. ((looking-at "^\\*+ ")
  3600. (org-element-inlinetask-parser limit raw-secondary-p))
  3601. ;; From there, elements can have affiliated keywords.
  3602. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3603. limit (memq granularity '(nil object)))))
  3604. (cond
  3605. ;; Jumping over affiliated keywords put point off-limits.
  3606. ;; Parse them as regular keywords.
  3607. ((and (cdr affiliated) (>= (point) limit))
  3608. (goto-char (car affiliated))
  3609. (org-element-keyword-parser limit nil))
  3610. ;; LaTeX Environment.
  3611. ((looking-at org-element--latex-begin-environment)
  3612. (org-element-latex-environment-parser limit affiliated))
  3613. ;; Drawer.
  3614. ((looking-at org-drawer-regexp)
  3615. (org-element-drawer-parser limit affiliated))
  3616. ;; Fixed Width
  3617. ((looking-at "[ \t]*:\\( \\|$\\)")
  3618. (org-element-fixed-width-parser limit affiliated))
  3619. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3620. ;; Keywords.
  3621. ((looking-at "[ \t]*#\\+")
  3622. (goto-char (match-end 0))
  3623. (cond
  3624. ((looking-at "BEGIN_\\(\\S-+\\)")
  3625. (beginning-of-line)
  3626. (funcall (pcase (upcase (match-string 1))
  3627. ("CENTER" #'org-element-center-block-parser)
  3628. ("COMMENT" #'org-element-comment-block-parser)
  3629. ("EXAMPLE" #'org-element-example-block-parser)
  3630. ("EXPORT" #'org-element-export-block-parser)
  3631. ("QUOTE" #'org-element-quote-block-parser)
  3632. ("SRC" #'org-element-src-block-parser)
  3633. ("VERSE" #'org-element-verse-block-parser)
  3634. (_ #'org-element-special-block-parser))
  3635. limit
  3636. affiliated))
  3637. ((looking-at "CALL:")
  3638. (beginning-of-line)
  3639. (org-element-babel-call-parser limit affiliated))
  3640. ((looking-at "BEGIN:? ")
  3641. (beginning-of-line)
  3642. (org-element-dynamic-block-parser limit affiliated))
  3643. ((looking-at "\\S-+:")
  3644. (beginning-of-line)
  3645. (org-element-keyword-parser limit affiliated))
  3646. (t
  3647. (beginning-of-line)
  3648. (org-element-paragraph-parser limit affiliated))))
  3649. ;; Footnote Definition.
  3650. ((looking-at org-footnote-definition-re)
  3651. (org-element-footnote-definition-parser limit affiliated))
  3652. ;; Horizontal Rule.
  3653. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3654. (org-element-horizontal-rule-parser limit affiliated))
  3655. ;; Diary Sexp.
  3656. ((looking-at "%%(")
  3657. (org-element-diary-sexp-parser limit affiliated))
  3658. ;; Table.
  3659. ((or (looking-at "[ \t]*|")
  3660. ;; There is no strict definition of a table.el
  3661. ;; table. Try to prevent false positive while being
  3662. ;; quick.
  3663. (let ((rule-regexp
  3664. (rx (zero-or-more (any " \t"))
  3665. "+"
  3666. (one-or-more (one-or-more "-") "+")
  3667. (zero-or-more (any " \t"))
  3668. eol))
  3669. (non-table.el-line
  3670. (rx bol
  3671. (zero-or-more (any " \t"))
  3672. (or eol (not (any "+| \t")))))
  3673. (next (line-beginning-position 2)))
  3674. ;; Start with a full rule.
  3675. (and
  3676. (looking-at rule-regexp)
  3677. (< next limit) ;no room for a table.el table
  3678. (save-excursion
  3679. (end-of-line)
  3680. (cond
  3681. ;; Must end with a full rule.
  3682. ((not (re-search-forward non-table.el-line limit 'move))
  3683. (if (bolp) (forward-line -1) (beginning-of-line))
  3684. (looking-at rule-regexp))
  3685. ;; Ignore pseudo-tables with a single
  3686. ;; rule.
  3687. ((= next (line-beginning-position))
  3688. nil)
  3689. ;; Must end with a full rule.
  3690. (t
  3691. (forward-line -1)
  3692. (looking-at rule-regexp)))))))
  3693. (org-element-table-parser limit affiliated))
  3694. ;; List.
  3695. ((looking-at (org-item-re))
  3696. (org-element-plain-list-parser
  3697. limit affiliated
  3698. (or structure (org-element--list-struct limit))))
  3699. ;; Default element: Paragraph.
  3700. (t (org-element-paragraph-parser limit affiliated)))))))))
  3701. ;; Most elements can have affiliated keywords. When looking for an
  3702. ;; element beginning, we want to move before them, as they belong to
  3703. ;; that element, and, in the meantime, collect information they give
  3704. ;; into appropriate properties. Hence the following function.
  3705. (defun org-element--collect-affiliated-keywords (limit parse)
  3706. "Collect affiliated keywords from point down to LIMIT.
  3707. Return a list whose CAR is the position at the first of them and
  3708. CDR a plist of keywords and values and move point to the
  3709. beginning of the first line after them.
  3710. As a special case, if element doesn't start at the beginning of
  3711. the line (e.g., a paragraph starting an item), CAR is current
  3712. position of point and CDR is nil.
  3713. When PARSE is non-nil, values from keywords belonging to
  3714. `org-element-parsed-keywords' are parsed as secondary strings."
  3715. (if (not (bolp)) (list (point))
  3716. (let ((case-fold-search t)
  3717. (origin (point))
  3718. ;; RESTRICT is the list of objects allowed in parsed
  3719. ;; keywords value. If PARSE is nil, no object is allowed.
  3720. (restrict (and parse (org-element-restriction 'keyword)))
  3721. output)
  3722. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3723. (let* ((raw-kwd (upcase (match-string 1)))
  3724. ;; Apply translation to RAW-KWD. From there, KWD is
  3725. ;; the official keyword.
  3726. (kwd (or (cdr (assoc raw-kwd
  3727. org-element-keyword-translation-alist))
  3728. raw-kwd))
  3729. ;; PARSED? is non-nil when keyword should have its
  3730. ;; value parsed.
  3731. (parsed? (member kwd org-element-parsed-keywords))
  3732. ;; Find main value for any keyword.
  3733. (value
  3734. (let ((beg (match-end 0))
  3735. (end (save-excursion
  3736. (end-of-line)
  3737. (skip-chars-backward " \t")
  3738. (point))))
  3739. (if parsed?
  3740. (save-match-data
  3741. (org-element--parse-objects beg end nil restrict))
  3742. (org-trim (buffer-substring-no-properties beg end)))))
  3743. ;; If KWD is a dual keyword, find its secondary value.
  3744. ;; Maybe parse it.
  3745. (dual? (member kwd org-element-dual-keywords))
  3746. (dual-value
  3747. (and dual?
  3748. (let ((sec (match-string-no-properties 2)))
  3749. (cond
  3750. ((and sec parsed?)
  3751. (save-match-data
  3752. (org-element--parse-objects
  3753. (match-beginning 2) (match-end 2) nil restrict)))
  3754. (sec sec)))))
  3755. ;; Attribute a property name to KWD.
  3756. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3757. ;; Now set final shape for VALUE.
  3758. (when dual?
  3759. (setq value (and (or value dual-value) (cons value dual-value))))
  3760. (when (or (member kwd org-element-multiple-keywords)
  3761. ;; Attributes can always appear on multiple lines.
  3762. (string-match "^ATTR_" kwd))
  3763. (setq value (cons value (plist-get output kwd-sym))))
  3764. ;; Eventually store the new value in OUTPUT.
  3765. (setq output (plist-put output kwd-sym value))
  3766. ;; Move to next keyword.
  3767. (forward-line)))
  3768. ;; If affiliated keywords are orphaned: move back to first one.
  3769. ;; They will be parsed as a paragraph.
  3770. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3771. ;; Return value.
  3772. (cons origin output))))
  3773. ;;; The Org Parser
  3774. ;;
  3775. ;; The two major functions here are `org-element-parse-buffer', which
  3776. ;; parses Org syntax inside the current buffer, taking into account
  3777. ;; region, narrowing, or even visibility if specified, and
  3778. ;; `org-element-parse-secondary-string', which parses objects within
  3779. ;; a given string.
  3780. ;;
  3781. ;; The (almost) almighty `org-element-map' allows applying a function
  3782. ;; on elements or objects matching some type, and accumulating the
  3783. ;; resulting values. In an export situation, it also skips unneeded
  3784. ;; parts of the parse tree.
  3785. (defun org-element-parse-buffer (&optional granularity visible-only)
  3786. "Recursively parse the buffer and return structure.
  3787. If narrowing is in effect, only parse the visible part of the
  3788. buffer.
  3789. Optional argument GRANULARITY determines the depth of the
  3790. recursion. It can be set to the following symbols:
  3791. `headline' Only parse headlines.
  3792. `greater-element' Don't recurse into greater elements except
  3793. headlines and sections. Thus, elements
  3794. parsed are the top-level ones.
  3795. `element' Parse everything but objects and plain text.
  3796. `object' Parse the complete buffer (default).
  3797. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3798. elements.
  3799. An element or object is represented as a list with the
  3800. pattern (TYPE PROPERTIES CONTENTS), where :
  3801. TYPE is a symbol describing the element or object. See
  3802. `org-element-all-elements' and `org-element-all-objects' for an
  3803. exhaustive list of such symbols. One can retrieve it with
  3804. `org-element-type' function.
  3805. PROPERTIES is the list of attributes attached to the element or
  3806. object, as a plist. Although most of them are specific to the
  3807. element or object type, all types share `:begin', `:end',
  3808. `:post-blank' and `:parent' properties, which respectively
  3809. refer to buffer position where the element or object starts,
  3810. ends, the number of white spaces or blank lines after it, and
  3811. the element or object containing it. Properties values can be
  3812. obtained by using `org-element-property' function.
  3813. CONTENTS is a list of elements, objects or raw strings
  3814. contained in the current element or object, when applicable.
  3815. One can access them with `org-element-contents' function.
  3816. The Org buffer has `org-data' as type and nil as properties.
  3817. `org-element-map' function can be used to find specific elements
  3818. or objects within the parse tree.
  3819. This function assumes that current major mode is `org-mode'."
  3820. (save-excursion
  3821. (goto-char (point-min))
  3822. (org-skip-whitespace)
  3823. (org-element--parse-elements
  3824. (point-at-bol) (point-max)
  3825. ;; Start in `first-section' mode so text before the first
  3826. ;; headline belongs to a section.
  3827. 'first-section nil granularity visible-only (list 'org-data nil))))
  3828. (defun org-element-parse-secondary-string (string restriction &optional parent)
  3829. "Recursively parse objects in STRING and return structure.
  3830. RESTRICTION is a symbol limiting the object types that will be
  3831. looked after.
  3832. Optional argument PARENT, when non-nil, is the element or object
  3833. containing the secondary string. It is used to set correctly
  3834. `:parent' property within the string.
  3835. If STRING is the empty string or nil, return nil."
  3836. (cond
  3837. ((not string) nil)
  3838. ((equal string "") nil)
  3839. (t (let ((local-variables (buffer-local-variables)))
  3840. (with-temp-buffer
  3841. (dolist (v local-variables)
  3842. (ignore-errors
  3843. (if (symbolp v) (makunbound v)
  3844. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  3845. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  3846. (set (make-local-variable (car v)) (cdr v))))))
  3847. ;; Transferring local variables may put the temporary buffer
  3848. ;; into a read-only state. Make sure we can insert STRING.
  3849. (let ((inhibit-read-only t)) (insert string))
  3850. ;; Prevent "Buffer *temp* modified; kill anyway?".
  3851. (restore-buffer-modified-p nil)
  3852. (org-element--parse-objects
  3853. (point-min) (point-max) nil restriction parent))))))
  3854. (defun org-element-map
  3855. (data types fun &optional info first-match no-recursion with-affiliated)
  3856. "Map a function on selected elements or objects.
  3857. DATA is a parse tree, an element, an object, a string, or a list
  3858. of such constructs. TYPES is a symbol or list of symbols of
  3859. elements or objects types (see `org-element-all-elements' and
  3860. `org-element-all-objects' for a complete list of types). FUN is
  3861. the function called on the matching element or object. It has to
  3862. accept one argument: the element or object itself.
  3863. When optional argument INFO is non-nil, it should be a plist
  3864. holding export options. In that case, parts of the parse tree
  3865. not exportable according to that property list will be skipped.
  3866. When optional argument FIRST-MATCH is non-nil, stop at the first
  3867. match for which FUN doesn't return nil, and return that value.
  3868. Optional argument NO-RECURSION is a symbol or a list of symbols
  3869. representing elements or objects types. `org-element-map' won't
  3870. enter any recursive element or object whose type belongs to that
  3871. list. Though, FUN can still be applied on them.
  3872. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  3873. apply to matching objects within parsed affiliated keywords (see
  3874. `org-element-parsed-keywords').
  3875. Nil values returned from FUN do not appear in the results.
  3876. Examples:
  3877. ---------
  3878. Assuming TREE is a variable containing an Org buffer parse tree,
  3879. the following example will return a flat list of all `src-block'
  3880. and `example-block' elements in it:
  3881. (org-element-map tree \\='(example-block src-block) #\\='identity)
  3882. The following snippet will find the first headline with a level
  3883. of 1 and a \"phone\" tag, and will return its beginning position:
  3884. (org-element-map tree \\='headline
  3885. (lambda (hl)
  3886. (and (= (org-element-property :level hl) 1)
  3887. (member \"phone\" (org-element-property :tags hl))
  3888. (org-element-property :begin hl)))
  3889. nil t)
  3890. The next example will return a flat list of all `plain-list' type
  3891. elements in TREE that are not a sub-list themselves:
  3892. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  3893. Eventually, this example will return a flat list of all `bold'
  3894. type objects containing a `latex-snippet' type object, even
  3895. looking into captions:
  3896. (org-element-map tree \\='bold
  3897. (lambda (b)
  3898. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  3899. nil nil nil t)"
  3900. (declare (indent 2))
  3901. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  3902. (let* ((types (if (listp types) types (list types)))
  3903. (no-recursion (if (listp no-recursion) no-recursion
  3904. (list no-recursion)))
  3905. ;; Recursion depth is determined by --CATEGORY.
  3906. (--category
  3907. (catch :--found
  3908. (let ((category 'greater-elements)
  3909. (all-objects (cons 'plain-text org-element-all-objects)))
  3910. (dolist (type types category)
  3911. (cond ((memq type all-objects)
  3912. ;; If one object is found, the function has
  3913. ;; to recurse into every object.
  3914. (throw :--found 'objects))
  3915. ((not (memq type org-element-greater-elements))
  3916. ;; If one regular element is found, the
  3917. ;; function has to recurse, at least, into
  3918. ;; every element it encounters.
  3919. (and (not (eq category 'elements))
  3920. (setq category 'elements))))))))
  3921. --acc)
  3922. (letrec ((--walk-tree
  3923. (lambda (--data)
  3924. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  3925. ;; holding contextual information.
  3926. (let ((--type (org-element-type --data)))
  3927. (cond
  3928. ((not --data))
  3929. ;; Ignored element in an export context.
  3930. ((and info (memq --data (plist-get info :ignore-list))))
  3931. ;; List of elements or objects.
  3932. ((not --type) (mapc --walk-tree --data))
  3933. ;; Unconditionally enter parse trees.
  3934. ((eq --type 'org-data)
  3935. (mapc --walk-tree (org-element-contents --data)))
  3936. (t
  3937. ;; Check if TYPE is matching among TYPES. If so,
  3938. ;; apply FUN to --DATA and accumulate return value
  3939. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  3940. (when (memq --type types)
  3941. (let ((result (funcall fun --data)))
  3942. (cond ((not result))
  3943. (first-match (throw :--map-first-match result))
  3944. (t (push result --acc)))))
  3945. ;; If --DATA has a secondary string that can contain
  3946. ;; objects with their type among TYPES, look inside.
  3947. (when (and (eq --category 'objects) (not (stringp --data)))
  3948. (dolist (p (cdr (assq --type
  3949. org-element-secondary-value-alist)))
  3950. (funcall --walk-tree (org-element-property p --data))))
  3951. ;; If --DATA has any parsed affiliated keywords and
  3952. ;; WITH-AFFILIATED is non-nil, look for objects in
  3953. ;; them.
  3954. (when (and with-affiliated
  3955. (eq --category 'objects)
  3956. (eq (org-element-class --data) 'element))
  3957. (dolist (kwd-pair org-element--parsed-properties-alist)
  3958. (let ((kwd (car kwd-pair))
  3959. (value (org-element-property (cdr kwd-pair) --data)))
  3960. ;; Pay attention to the type of parsed
  3961. ;; keyword. In particular, preserve order for
  3962. ;; multiple keywords.
  3963. (cond
  3964. ((not value))
  3965. ((member kwd org-element-dual-keywords)
  3966. (if (member kwd org-element-multiple-keywords)
  3967. (dolist (line (reverse value))
  3968. (funcall --walk-tree (cdr line))
  3969. (funcall --walk-tree (car line)))
  3970. (funcall --walk-tree (cdr value))
  3971. (funcall --walk-tree (car value))))
  3972. ((member kwd org-element-multiple-keywords)
  3973. (mapc --walk-tree (reverse value)))
  3974. (t (funcall --walk-tree value))))))
  3975. ;; Determine if a recursion into --DATA is possible.
  3976. (cond
  3977. ;; --TYPE is explicitly removed from recursion.
  3978. ((memq --type no-recursion))
  3979. ;; --DATA has no contents.
  3980. ((not (org-element-contents --data)))
  3981. ;; Looking for greater elements but --DATA is
  3982. ;; simply an element or an object.
  3983. ((and (eq --category 'greater-elements)
  3984. (not (memq --type org-element-greater-elements))))
  3985. ;; Looking for elements but --DATA is an object.
  3986. ((and (eq --category 'elements)
  3987. (eq (org-element-class --data) 'object)))
  3988. ;; In any other case, map contents.
  3989. (t (mapc --walk-tree (org-element-contents --data))))))))))
  3990. (catch :--map-first-match
  3991. (funcall --walk-tree data)
  3992. ;; Return value in a proper order.
  3993. (nreverse --acc)))))
  3994. ;; The following functions are internal parts of the parser.
  3995. ;;
  3996. ;; The first one, `org-element--parse-elements' acts at the element's
  3997. ;; level.
  3998. ;;
  3999. ;; The second one, `org-element--parse-objects' applies on all objects
  4000. ;; of a paragraph or a secondary string. It calls
  4001. ;; `org-element--object-lex' to find the next object in the current
  4002. ;; container.
  4003. (defsubst org-element--next-mode (mode type parent?)
  4004. "Return next mode according to current one.
  4005. MODE is a symbol representing the expectation about the next
  4006. element or object. Meaningful values are `first-section',
  4007. `item', `node-property', `planning', `property-drawer',
  4008. `section', `table-row', `top-comment', and nil.
  4009. TYPE is the type of the current element or object.
  4010. If PARENT? is non-nil, assume the next element or object will be
  4011. located inside the current one."
  4012. (if parent?
  4013. (pcase type
  4014. (`headline 'section)
  4015. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4016. (`inlinetask 'planning)
  4017. (`plain-list 'item)
  4018. (`property-drawer 'node-property)
  4019. (`section 'planning)
  4020. (`table 'table-row))
  4021. (pcase mode
  4022. (`item 'item)
  4023. (`node-property 'node-property)
  4024. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4025. (`table-row 'table-row)
  4026. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4027. (defun org-element--parse-elements
  4028. (beg end mode structure granularity visible-only acc)
  4029. "Parse elements between BEG and END positions.
  4030. MODE prioritizes some elements over the others. It can be set to
  4031. `first-section', `item', `node-property', `planning',
  4032. `property-drawer', `section', `table-row', `top-comment', or nil.
  4033. When value is `item', STRUCTURE will be used as the current list
  4034. structure.
  4035. GRANULARITY determines the depth of the recursion. See
  4036. `org-element-parse-buffer' for more information.
  4037. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4038. elements.
  4039. Elements are accumulated into ACC."
  4040. (save-excursion
  4041. (goto-char beg)
  4042. ;; When parsing only headlines, skip any text before first one.
  4043. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4044. (org-with-limited-levels (outline-next-heading)))
  4045. (let (elements)
  4046. (while (< (point) end)
  4047. ;; Visible only: skip invisible parts due to folding.
  4048. (if (and visible-only (org-invisible-p nil t))
  4049. (progn
  4050. (goto-char (org-find-visible))
  4051. (when (and (eolp) (not (eobp))) (forward-char)))
  4052. ;; Find current element's type and parse it accordingly to
  4053. ;; its category.
  4054. (let* ((element (org-element--current-element
  4055. end granularity mode structure))
  4056. (type (org-element-type element))
  4057. (cbeg (org-element-property :contents-begin element)))
  4058. (goto-char (org-element-property :end element))
  4059. ;; Fill ELEMENT contents by side-effect.
  4060. (cond
  4061. ;; If element has no contents, don't modify it.
  4062. ((not cbeg))
  4063. ;; Greater element: parse it between `contents-begin' and
  4064. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4065. ;; or ELEMENT is a headline, in which case going inside
  4066. ;; is mandatory, in order to get sub-level headings.
  4067. ((and (memq type org-element-greater-elements)
  4068. (or (memq granularity '(element object nil))
  4069. (and (eq granularity 'greater-element)
  4070. (eq type 'section))
  4071. (eq type 'headline)))
  4072. (org-element--parse-elements
  4073. cbeg (org-element-property :contents-end element)
  4074. ;; Possibly switch to a special mode.
  4075. (org-element--next-mode mode type t)
  4076. (and (memq type '(item plain-list))
  4077. (org-element-property :structure element))
  4078. granularity visible-only element))
  4079. ;; ELEMENT has contents. Parse objects inside, if
  4080. ;; GRANULARITY allows it.
  4081. ((memq granularity '(object nil))
  4082. (org-element--parse-objects
  4083. cbeg (org-element-property :contents-end element) element
  4084. (org-element-restriction type))))
  4085. (push (org-element-put-property element :parent acc) elements)
  4086. ;; Update mode.
  4087. (setq mode (org-element--next-mode mode type nil)))))
  4088. ;; Return result.
  4089. (apply #'org-element-set-contents acc (nreverse elements)))))
  4090. (defun org-element--object-lex (restriction)
  4091. "Return next object in current buffer or nil.
  4092. RESTRICTION is a list of object types, as symbols, that should be
  4093. looked after. This function assumes that the buffer is narrowed
  4094. to an appropriate container (e.g., a paragraph)."
  4095. (cond
  4096. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4097. ((memq 'citation-reference restriction)
  4098. (org-element-citation-reference-parser))
  4099. (t
  4100. (let* ((start (point))
  4101. (limit
  4102. ;; Object regexp sometimes needs to have a peek at
  4103. ;; a character ahead. Therefore, when there is a hard
  4104. ;; limit, make it one more than the true beginning of the
  4105. ;; radio target.
  4106. (save-excursion
  4107. (cond ((not org-target-link-regexp) nil)
  4108. ((not (memq 'link restriction)) nil)
  4109. ((progn
  4110. (unless (bolp) (forward-char -1))
  4111. (not (re-search-forward org-target-link-regexp nil t)))
  4112. nil)
  4113. ;; Since we moved backward, we do not want to
  4114. ;; match again an hypothetical 1-character long
  4115. ;; radio link before us. Realizing that this can
  4116. ;; only happen if such a radio link starts at
  4117. ;; beginning of line, we prevent this here.
  4118. ((and (= start (1+ (line-beginning-position)))
  4119. (= start (match-end 1)))
  4120. (and (re-search-forward org-target-link-regexp nil t)
  4121. (1+ (match-beginning 1))))
  4122. (t (1+ (match-beginning 1))))))
  4123. found)
  4124. (save-excursion
  4125. (while (and (not found)
  4126. (re-search-forward org-element--object-regexp limit 'move))
  4127. (goto-char (match-beginning 0))
  4128. (let ((result (match-string 0)))
  4129. (setq found
  4130. (cond
  4131. ((string-prefix-p "call_" result t)
  4132. (and (memq 'inline-babel-call restriction)
  4133. (org-element-inline-babel-call-parser)))
  4134. ((string-prefix-p "src_" result t)
  4135. (and (memq 'inline-src-block restriction)
  4136. (org-element-inline-src-block-parser)))
  4137. (t
  4138. (pcase (char-after)
  4139. (?^ (and (memq 'superscript restriction)
  4140. (org-element-superscript-parser)))
  4141. (?_ (or (and (memq 'subscript restriction)
  4142. (org-element-subscript-parser))
  4143. (and (memq 'underline restriction)
  4144. (org-element-underline-parser))))
  4145. (?* (and (memq 'bold restriction)
  4146. (org-element-bold-parser)))
  4147. (?/ (and (memq 'italic restriction)
  4148. (org-element-italic-parser)))
  4149. (?~ (and (memq 'code restriction)
  4150. (org-element-code-parser)))
  4151. (?= (and (memq 'verbatim restriction)
  4152. (org-element-verbatim-parser)))
  4153. (?+ (and (memq 'strike-through restriction)
  4154. (org-element-strike-through-parser)))
  4155. (?@ (and (memq 'export-snippet restriction)
  4156. (org-element-export-snippet-parser)))
  4157. (?{ (and (memq 'macro restriction)
  4158. (org-element-macro-parser)))
  4159. (?$ (and (memq 'latex-fragment restriction)
  4160. (org-element-latex-fragment-parser)))
  4161. (?<
  4162. (if (eq (aref result 1) ?<)
  4163. (or (and (memq 'radio-target restriction)
  4164. (org-element-radio-target-parser))
  4165. (and (memq 'target restriction)
  4166. (org-element-target-parser)))
  4167. (or (and (memq 'timestamp restriction)
  4168. (org-element-timestamp-parser))
  4169. (and (memq 'link restriction)
  4170. (org-element-link-parser)))))
  4171. (?\\
  4172. (if (eq (aref result 1) ?\\)
  4173. (and (memq 'line-break restriction)
  4174. (org-element-line-break-parser))
  4175. (or (and (memq 'entity restriction)
  4176. (org-element-entity-parser))
  4177. (and (memq 'latex-fragment restriction)
  4178. (org-element-latex-fragment-parser)))))
  4179. (?\[
  4180. (pcase (aref result 1)
  4181. ((and ?\[
  4182. (guard (memq 'link restriction)))
  4183. (org-element-link-parser))
  4184. ((and ?f
  4185. (guard (memq 'footnote-reference restriction)))
  4186. (org-element-footnote-reference-parser))
  4187. ((and ?c
  4188. (guard (memq 'citation restriction)))
  4189. (org-element-citation-parser))
  4190. ((and (or ?% ?/)
  4191. (guard (memq 'statistics-cookie restriction)))
  4192. (org-element-statistics-cookie-parser))
  4193. (_
  4194. (or (and (memq 'timestamp restriction)
  4195. (org-element-timestamp-parser))
  4196. (and (memq 'statistics-cookie restriction)
  4197. (org-element-statistics-cookie-parser))))))
  4198. ;; This is probably a plain link.
  4199. (_ (and (memq 'link restriction)
  4200. (org-element-link-parser)))))))
  4201. (or (eobp) (forward-char))))
  4202. (cond (found)
  4203. (limit (forward-char -1)
  4204. (org-element-link-parser)) ;radio link
  4205. (t nil)))))))
  4206. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4207. "Parse objects between BEG and END and return recursive structure.
  4208. Objects are accumulated in ACC. RESTRICTION is a list of object
  4209. successors which are allowed in the current object.
  4210. ACC becomes the parent for all parsed objects. However, if ACC
  4211. is nil (i.e., a secondary string is being parsed) and optional
  4212. argument PARENT is non-nil, use it as the parent for all objects.
  4213. Eventually, if both ACC and PARENT are nil, the common parent is
  4214. the list of objects itself."
  4215. (save-excursion
  4216. (save-restriction
  4217. (narrow-to-region beg end)
  4218. (goto-char (point-min))
  4219. (let (next-object contents)
  4220. (while (and (not (eobp))
  4221. (setq next-object (org-element--object-lex restriction)))
  4222. ;; Text before any object.
  4223. (let ((obj-beg (org-element-property :begin next-object)))
  4224. (unless (= (point) obj-beg)
  4225. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4226. (push (if acc (org-element-put-property text :parent acc) text)
  4227. contents))))
  4228. ;; Object...
  4229. (let ((obj-end (org-element-property :end next-object))
  4230. (cont-beg (org-element-property :contents-begin next-object)))
  4231. (when acc (org-element-put-property next-object :parent acc))
  4232. (push (if cont-beg
  4233. ;; Fill contents of NEXT-OBJECT if possible.
  4234. (org-element--parse-objects
  4235. cont-beg
  4236. (org-element-property :contents-end next-object)
  4237. next-object
  4238. (org-element-restriction next-object))
  4239. next-object)
  4240. contents)
  4241. (goto-char obj-end)))
  4242. ;; Text after last object.
  4243. (unless (eobp)
  4244. (let ((text (buffer-substring-no-properties (point) end)))
  4245. (push (if acc (org-element-put-property text :parent acc) text)
  4246. contents)))
  4247. ;; Result. Set appropriate parent.
  4248. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4249. (let* ((contents (nreverse contents))
  4250. (parent (or parent contents)))
  4251. (dolist (datum contents contents)
  4252. (org-element-put-property datum :parent parent))))))))
  4253. ;;; Towards A Bijective Process
  4254. ;;
  4255. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4256. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4257. ;; interpreted and expanded into a string with canonical Org syntax.
  4258. ;; Hence `org-element-interpret-data'.
  4259. ;;
  4260. ;; The function relies internally on
  4261. ;; `org-element--interpret-affiliated-keywords'.
  4262. ;;;###autoload
  4263. (defun org-element-interpret-data (data)
  4264. "Interpret DATA as Org syntax.
  4265. DATA is a parse tree, an element, an object or a secondary string
  4266. to interpret. Return Org syntax as a string."
  4267. (letrec ((fun
  4268. (lambda (data parent)
  4269. (let* ((type (org-element-type data))
  4270. ;; Find interpreter for current object or
  4271. ;; element. If it doesn't exist (e.g. this is
  4272. ;; a pseudo object or element), return contents,
  4273. ;; if any.
  4274. (interpret
  4275. (let ((fun (intern
  4276. (format "org-element-%s-interpreter" type))))
  4277. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4278. (results
  4279. (cond
  4280. ;; Secondary string.
  4281. ((not type)
  4282. (mapconcat (lambda (obj) (funcall fun obj parent))
  4283. data
  4284. ""))
  4285. ;; Full Org document.
  4286. ((eq type 'org-data)
  4287. (mapconcat (lambda (obj) (funcall fun obj parent))
  4288. (org-element-contents data)
  4289. ""))
  4290. ;; Plain text: return it.
  4291. ((stringp data) data)
  4292. ;; Element or object without contents.
  4293. ((not (org-element-contents data))
  4294. (funcall interpret data nil))
  4295. ;; Element or object with contents.
  4296. (t
  4297. (funcall
  4298. interpret
  4299. data
  4300. ;; Recursively interpret contents.
  4301. (mapconcat
  4302. (lambda (datum) (funcall fun datum data))
  4303. (org-element-contents
  4304. (if (not (memq type '(paragraph verse-block)))
  4305. data
  4306. ;; Fix indentation of elements containing
  4307. ;; objects. We ignore `table-row'
  4308. ;; elements as they are one line long
  4309. ;; anyway.
  4310. (org-element-normalize-contents
  4311. data
  4312. ;; When normalizing first paragraph of
  4313. ;; an item or a footnote-definition,
  4314. ;; ignore first line's indentation.
  4315. (and (eq type 'paragraph)
  4316. (memq (org-element-type parent)
  4317. '(footnote-definition item))
  4318. (eq data (car (org-element-contents parent)))
  4319. (eq (org-element-property :pre-blank parent)
  4320. 0)))))
  4321. ""))))))
  4322. (if (memq type '(org-data nil)) results
  4323. ;; Build white spaces. If no `:post-blank' property
  4324. ;; is specified, assume its value is 0.
  4325. (let ((blank (or (org-element-property :post-blank data) 0)))
  4326. (if (eq (org-element-class data parent) 'object)
  4327. (concat results (make-string blank ?\s))
  4328. (concat (org-element--interpret-affiliated-keywords data)
  4329. (org-element-normalize-string results)
  4330. (make-string blank ?\n)))))))))
  4331. (funcall fun data nil)))
  4332. (defun org-element--interpret-affiliated-keywords (element)
  4333. "Return ELEMENT's affiliated keywords as Org syntax.
  4334. If there is no affiliated keyword, return the empty string."
  4335. (let ((keyword-to-org
  4336. (lambda (key value)
  4337. (let (dual)
  4338. (when (member key org-element-dual-keywords)
  4339. (setq dual (cdr value) value (car value)))
  4340. (concat "#+" (downcase key)
  4341. (and dual
  4342. (format "[%s]" (org-element-interpret-data dual)))
  4343. ": "
  4344. (if (member key org-element-parsed-keywords)
  4345. (org-element-interpret-data value)
  4346. value)
  4347. "\n")))))
  4348. (mapconcat
  4349. (lambda (prop)
  4350. (let ((value (org-element-property prop element))
  4351. (keyword (upcase (substring (symbol-name prop) 1))))
  4352. (when value
  4353. (if (or (member keyword org-element-multiple-keywords)
  4354. ;; All attribute keywords can have multiple lines.
  4355. (string-match "^ATTR_" keyword))
  4356. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4357. (reverse value)
  4358. "")
  4359. (funcall keyword-to-org keyword value)))))
  4360. ;; List all ELEMENT's properties matching an attribute line or an
  4361. ;; affiliated keyword, but ignore translated keywords since they
  4362. ;; cannot belong to the property list.
  4363. (cl-loop for prop in (nth 1 element) by 'cddr
  4364. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4365. (or (string-match "^ATTR_" keyword)
  4366. (and
  4367. (member keyword org-element-affiliated-keywords)
  4368. (not (assoc keyword
  4369. org-element-keyword-translation-alist)))))
  4370. collect prop)
  4371. "")))
  4372. ;; Because interpretation of the parse tree must return the same
  4373. ;; number of blank lines between elements and the same number of white
  4374. ;; space after objects, some special care must be given to white
  4375. ;; spaces.
  4376. ;;
  4377. ;; The first function, `org-element-normalize-string', ensures any
  4378. ;; string different from the empty string will end with a single
  4379. ;; newline character.
  4380. ;;
  4381. ;; The second function, `org-element-normalize-contents', removes
  4382. ;; global indentation from the contents of the current element.
  4383. (defun org-element-normalize-string (s)
  4384. "Ensure string S ends with a single newline character.
  4385. If S isn't a string return it unchanged. If S is the empty
  4386. string, return it. Otherwise, return a new string with a single
  4387. newline character at its end."
  4388. (cond
  4389. ((not (stringp s)) s)
  4390. ((string= "" s) "")
  4391. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4392. (replace-match "\n" nil nil s)))))
  4393. (defun org-element-normalize-contents (element &optional ignore-first)
  4394. "Normalize plain text in ELEMENT's contents.
  4395. ELEMENT must only contain plain text and objects.
  4396. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4397. indentation to compute maximal common indentation.
  4398. Return the normalized element that is element with global
  4399. indentation removed from its contents."
  4400. (letrec ((find-min-ind
  4401. ;; Return minimal common indentation within BLOB. This is
  4402. ;; done by walking recursively BLOB and updating MIN-IND
  4403. ;; along the way. FIRST-FLAG is non-nil when the next
  4404. ;; object is expected to be a string that doesn't start
  4405. ;; with a newline character. It happens for strings at
  4406. ;; the beginnings of the contents or right after a line
  4407. ;; break.
  4408. (lambda (blob first-flag min-ind)
  4409. (dolist (datum (org-element-contents blob) min-ind)
  4410. (when first-flag
  4411. (setq first-flag nil)
  4412. (cond
  4413. ;; Objects cannot start with spaces: in this
  4414. ;; case, indentation is 0.
  4415. ((not (stringp datum)) (throw :zero 0))
  4416. ((not (string-match
  4417. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4418. (throw :zero 0))
  4419. ((equal (match-string 2 datum) "\n")
  4420. (put-text-property
  4421. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4422. (t
  4423. (let ((i (string-width (match-string 1 datum))))
  4424. (put-text-property
  4425. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4426. (setq min-ind (min i min-ind))))))
  4427. (cond
  4428. ((stringp datum)
  4429. (let ((s 0))
  4430. (while (string-match
  4431. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4432. (setq s (match-end 1))
  4433. (cond
  4434. ((equal (match-string 1 datum) "")
  4435. (unless (member (match-string 2 datum) '("" "\n"))
  4436. (throw :zero 0)))
  4437. ((equal (match-string 2 datum) "\n")
  4438. (put-text-property (match-beginning 1) (match-end 1)
  4439. 'org-ind 'empty datum))
  4440. (t
  4441. (let ((i (string-width (match-string 1 datum))))
  4442. (put-text-property (match-beginning 1) (match-end 1)
  4443. 'org-ind i datum)
  4444. (setq min-ind (min i min-ind))))))))
  4445. ((eq (org-element-type datum) 'line-break)
  4446. (setq first-flag t))
  4447. ((memq (org-element-type datum) org-element-recursive-objects)
  4448. (setq min-ind
  4449. (funcall find-min-ind datum first-flag min-ind)))))))
  4450. (min-ind
  4451. (catch :zero
  4452. (funcall find-min-ind
  4453. element (not ignore-first) most-positive-fixnum))))
  4454. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4455. ;; Build ELEMENT back, replacing each string with the same
  4456. ;; string minus common indentation.
  4457. (letrec ((build
  4458. (lambda (datum)
  4459. ;; Return DATUM with all its strings indentation
  4460. ;; shortened from MIN-IND white spaces.
  4461. (setcdr
  4462. (cdr datum)
  4463. (mapcar
  4464. (lambda (object)
  4465. (cond
  4466. ((stringp object)
  4467. (with-temp-buffer
  4468. (insert object)
  4469. (let ((s (point-min)))
  4470. (while (setq s (text-property-not-all
  4471. s (point-max) 'org-ind nil))
  4472. (goto-char s)
  4473. (let ((i (get-text-property s 'org-ind)))
  4474. (delete-region s (progn
  4475. (skip-chars-forward " \t")
  4476. (point)))
  4477. (when (integerp i) (indent-to (- i min-ind))))))
  4478. (buffer-string)))
  4479. ((memq (org-element-type object)
  4480. org-element-recursive-objects)
  4481. (funcall build object))
  4482. (t object)))
  4483. (org-element-contents datum)))
  4484. datum)))
  4485. (funcall build element)))))
  4486. ;;; Cache
  4487. ;;
  4488. ;; Implement a caching mechanism for `org-element-at-point' and
  4489. ;; `org-element-context', which see.
  4490. ;;
  4491. ;; A single public function is provided: `org-element-cache-reset'.
  4492. ;;
  4493. ;; Cache is disabled by default for now because it sometimes triggers
  4494. ;; freezes, but it can be enabled globally with
  4495. ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
  4496. ;; `org-element-cache-sync-duration' and
  4497. ;; `org-element-cache-sync-break' can be tweaked to control caching
  4498. ;; behavior.
  4499. ;;
  4500. ;; Internally, parsed elements are stored in an AVL tree,
  4501. ;; `org-element--cache'. This tree is updated lazily: whenever
  4502. ;; a change happens to the buffer, a synchronization request is
  4503. ;; registered in `org-element--cache-sync-requests' (see
  4504. ;; `org-element--cache-submit-request'). During idle time, requests
  4505. ;; are processed by `org-element--cache-sync'. Synchronization also
  4506. ;; happens when an element is required from the cache. In this case,
  4507. ;; the process stops as soon as the needed element is up-to-date.
  4508. ;;
  4509. ;; A synchronization request can only apply on a synchronized part of
  4510. ;; the cache. Therefore, the cache is updated at least to the
  4511. ;; location where the new request applies. Thus, requests are ordered
  4512. ;; from left to right and all elements starting before the first
  4513. ;; request are correct. This property is used by functions like
  4514. ;; `org-element--cache-find' to retrieve elements in the part of the
  4515. ;; cache that can be trusted.
  4516. ;;
  4517. ;; A request applies to every element, starting from its original
  4518. ;; location (or key, see below). When a request is processed, it
  4519. ;; moves forward and may collide the next one. In this case, both
  4520. ;; requests are merged into a new one that starts from that element.
  4521. ;; As a consequence, the whole synchronization complexity does not
  4522. ;; depend on the number of pending requests, but on the number of
  4523. ;; elements the very first request will be applied on.
  4524. ;;
  4525. ;; Elements cannot be accessed through their beginning position, which
  4526. ;; may or may not be up-to-date. Instead, each element in the tree is
  4527. ;; associated to a key, obtained with `org-element--cache-key'. This
  4528. ;; mechanism is robust enough to preserve total order among elements
  4529. ;; even when the tree is only partially synchronized.
  4530. (defvar org-element-use-cache nil
  4531. "Non-nil when Org parser should cache its results.
  4532. WARNING: for the time being, using cache sometimes triggers
  4533. freezes. Therefore, it is disabled by default. Activate it if
  4534. you want to help debugging the issue.")
  4535. (defvar org-element-cache-sync-idle-time 0.6
  4536. "Length, in seconds, of idle time before syncing cache.")
  4537. (defvar org-element-cache-sync-duration 0.04
  4538. "Maximum duration, as a time value, for a cache synchronization.
  4539. If the synchronization is not over after this delay, the process
  4540. pauses and resumes after `org-element-cache-sync-break'
  4541. seconds.")
  4542. (defvar org-element-cache-sync-break 0.3
  4543. "Duration, as a time value, of the pause between synchronizations.
  4544. See `org-element-cache-sync-duration' for more information.")
  4545. ;;;; Data Structure
  4546. (defvar org-element--cache nil
  4547. "AVL tree used to cache elements.
  4548. Each node of the tree contains an element. Comparison is done
  4549. with `org-element--cache-compare'. This cache is used in
  4550. `org-element-at-point'.")
  4551. (defvar org-element--cache-sync-requests nil
  4552. "List of pending synchronization requests.
  4553. A request is a vector with the following pattern:
  4554. [NEXT BEG END OFFSET PARENT PHASE]
  4555. Processing a synchronization request consists of three phases:
  4556. 0. Delete modified elements,
  4557. 1. Fill missing area in cache,
  4558. 2. Shift positions and re-parent elements after the changes.
  4559. During phase 0, NEXT is the key of the first element to be
  4560. removed, BEG and END is buffer position delimiting the
  4561. modifications. Elements starting between them (inclusive) are
  4562. removed. So are elements whose parent is removed. PARENT, when
  4563. non-nil, is the parent of the first element to be removed.
  4564. During phase 1, NEXT is the key of the next known element in
  4565. cache and BEG its beginning position. Parse buffer between that
  4566. element and the one before it in order to determine the parent of
  4567. the next element. Set PARENT to the element containing NEXT.
  4568. During phase 2, NEXT is the key of the next element to shift in
  4569. the parse tree. All elements starting from this one have their
  4570. properties relatives to buffer positions shifted by integer
  4571. OFFSET and, if they belong to element PARENT, are adopted by it.
  4572. PHASE specifies the phase number, as an integer.")
  4573. (defvar org-element--cache-sync-timer nil
  4574. "Timer used for cache synchronization.")
  4575. (defvar org-element--cache-sync-keys nil
  4576. "Hash table used to store keys during synchronization.
  4577. See `org-element--cache-key' for more information.")
  4578. (defsubst org-element--cache-key (element)
  4579. "Return a unique key for ELEMENT in cache tree.
  4580. Keys are used to keep a total order among elements in the cache.
  4581. Comparison is done with `org-element--cache-key-less-p'.
  4582. When no synchronization is taking place, a key is simply the
  4583. beginning position of the element, or that position plus one in
  4584. the case of an first item (respectively row) in
  4585. a list (respectively a table).
  4586. During a synchronization, the key is the one the element had when
  4587. the cache was synchronized for the last time. Elements added to
  4588. cache during the synchronization get a new key generated with
  4589. `org-element--cache-generate-key'.
  4590. Such keys are stored in `org-element--cache-sync-keys'. The hash
  4591. table is cleared once the synchronization is complete."
  4592. (or (gethash element org-element--cache-sync-keys)
  4593. (let* ((begin (org-element-property :begin element))
  4594. ;; Increase beginning position of items (respectively
  4595. ;; table rows) by one, so the first item can get
  4596. ;; a different key from its parent list (respectively
  4597. ;; table).
  4598. (key (if (memq (org-element-type element) '(item table-row))
  4599. (1+ begin)
  4600. begin)))
  4601. (if org-element--cache-sync-requests
  4602. (puthash element key org-element--cache-sync-keys)
  4603. key))))
  4604. (defun org-element--cache-generate-key (lower upper)
  4605. "Generate a key between LOWER and UPPER.
  4606. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4607. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4608. a unique key, as an integer or a list of integers, according to
  4609. the following rules:
  4610. - LOWER and UPPER are compared level-wise until values differ.
  4611. - If, at a given level, LOWER and UPPER differ from more than
  4612. 2, the new key shares all the levels above with LOWER and
  4613. gets a new level. Its value is the mean between LOWER and
  4614. UPPER:
  4615. (1 2) + (1 4) --> (1 3)
  4616. - If LOWER has no value to compare with, it is assumed that its
  4617. value is `most-negative-fixnum'. E.g.,
  4618. (1 1) + (1 1 2)
  4619. is equivalent to
  4620. (1 1 m) + (1 1 2)
  4621. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4622. short of levels, the current value is `most-positive-fixnum'.
  4623. - If they differ from only one, the new key inherits from
  4624. current LOWER level and fork it at the next level. E.g.,
  4625. (2 1) + (3 3)
  4626. is equivalent to
  4627. (2 1) + (2 M)
  4628. where M is `most-positive-fixnum'.
  4629. - If the key is only one level long, it is returned as an
  4630. integer:
  4631. (1 2) + (3 2) --> 2
  4632. When they are not equals, the function assumes that LOWER is
  4633. lesser than UPPER, per `org-element--cache-key-less-p'."
  4634. (if (equal lower upper) lower
  4635. (let ((lower (if (integerp lower) (list lower) lower))
  4636. (upper (if (integerp upper) (list upper) upper))
  4637. skip-upper key)
  4638. (catch 'exit
  4639. (while t
  4640. (let ((min (or (car lower) most-negative-fixnum))
  4641. (max (cond (skip-upper most-positive-fixnum)
  4642. ((car upper))
  4643. (t most-positive-fixnum))))
  4644. (if (< (1+ min) max)
  4645. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  4646. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  4647. (when (and (< min max) (not skip-upper))
  4648. ;; When at a given level, LOWER and UPPER differ from
  4649. ;; 1, ignore UPPER altogether. Instead create a key
  4650. ;; between LOWER and the greatest key with the same
  4651. ;; prefix as LOWER so far.
  4652. (setq skip-upper t))
  4653. (push min key)
  4654. (setq lower (cdr lower) upper (cdr upper)))))))))
  4655. (defsubst org-element--cache-key-less-p (a b)
  4656. "Non-nil if key A is less than key B.
  4657. A and B are either integers or lists of integers, as returned by
  4658. `org-element--cache-key'."
  4659. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  4660. (if (integerp b) (< (car a) b)
  4661. (catch 'exit
  4662. (while (and a b)
  4663. (cond ((car-less-than-car a b) (throw 'exit t))
  4664. ((car-less-than-car b a) (throw 'exit nil))
  4665. (t (setq a (cdr a) b (cdr b)))))
  4666. ;; If A is empty, either keys are equal (B is also empty) and
  4667. ;; we return nil, or A is lesser than B (B is longer) and we
  4668. ;; return a non-nil value.
  4669. ;;
  4670. ;; If A is not empty, B is necessarily empty and A is greater
  4671. ;; than B (A is longer). Therefore, return nil.
  4672. (and (null a) b)))))
  4673. (defun org-element--cache-compare (a b)
  4674. "Non-nil when element A is located before element B."
  4675. (org-element--cache-key-less-p (org-element--cache-key a)
  4676. (org-element--cache-key b)))
  4677. (defsubst org-element--cache-root ()
  4678. "Return root value in cache.
  4679. This function assumes `org-element--cache' is a valid AVL tree."
  4680. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  4681. ;;;; Tools
  4682. (defsubst org-element--cache-active-p ()
  4683. "Non-nil when cache is active in current buffer."
  4684. (and org-element-use-cache
  4685. org-element--cache
  4686. (derived-mode-p 'org-mode)))
  4687. (defun org-element--cache-find (pos &optional side)
  4688. "Find element in cache starting at POS or before.
  4689. POS refers to a buffer position.
  4690. When optional argument SIDE is non-nil, the function checks for
  4691. elements starting at or past POS instead. If SIDE is `both', the
  4692. function returns a cons cell where car is the first element
  4693. starting at or before POS and cdr the first element starting
  4694. after POS.
  4695. The function can only find elements in the synchronized part of
  4696. the cache."
  4697. (let ((limit (and org-element--cache-sync-requests
  4698. (aref (car org-element--cache-sync-requests) 0)))
  4699. (node (org-element--cache-root))
  4700. lower upper)
  4701. (while node
  4702. (let* ((element (avl-tree--node-data node))
  4703. (begin (org-element-property :begin element)))
  4704. (cond
  4705. ((and limit
  4706. (not (org-element--cache-key-less-p
  4707. (org-element--cache-key element) limit)))
  4708. (setq node (avl-tree--node-left node)))
  4709. ((> begin pos)
  4710. (setq upper element
  4711. node (avl-tree--node-left node)))
  4712. ((< begin pos)
  4713. (setq lower element
  4714. node (avl-tree--node-right node)))
  4715. ;; We found an element in cache starting at POS. If `side'
  4716. ;; is `both' we also want the next one in order to generate
  4717. ;; a key in-between.
  4718. ;;
  4719. ;; If the element is the first row or item in a table or
  4720. ;; a plain list, we always return the table or the plain
  4721. ;; list.
  4722. ;;
  4723. ;; In any other case, we return the element found.
  4724. ((eq side 'both)
  4725. (setq lower element)
  4726. (setq node (avl-tree--node-right node)))
  4727. ((and (memq (org-element-type element) '(item table-row))
  4728. (let ((parent (org-element-property :parent element)))
  4729. (and (= (org-element-property :begin element)
  4730. (org-element-property :contents-begin parent))
  4731. (setq node nil
  4732. lower parent
  4733. upper parent)))))
  4734. (t
  4735. (setq node nil
  4736. lower element
  4737. upper element)))))
  4738. (pcase side
  4739. (`both (cons lower upper))
  4740. (`nil lower)
  4741. (_ upper))))
  4742. (defun org-element--cache-put (element)
  4743. "Store ELEMENT in current buffer's cache, if allowed."
  4744. (when (org-element--cache-active-p)
  4745. (when org-element--cache-sync-requests
  4746. ;; During synchronization, first build an appropriate key for
  4747. ;; the new element so `avl-tree-enter' can insert it at the
  4748. ;; right spot in the cache.
  4749. (let ((keys (org-element--cache-find
  4750. (org-element-property :begin element) 'both)))
  4751. (puthash element
  4752. (org-element--cache-generate-key
  4753. (and (car keys) (org-element--cache-key (car keys)))
  4754. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  4755. (org-element--cache-sync-requests
  4756. (aref (car org-element--cache-sync-requests) 0))))
  4757. org-element--cache-sync-keys)))
  4758. (avl-tree-enter org-element--cache element)))
  4759. (defsubst org-element--cache-remove (element)
  4760. "Remove ELEMENT from cache.
  4761. Assume ELEMENT belongs to cache and that a cache is active."
  4762. (avl-tree-delete org-element--cache element))
  4763. ;;;; Synchronization
  4764. (defsubst org-element--cache-set-timer (buffer)
  4765. "Set idle timer for cache synchronization in BUFFER."
  4766. (when org-element--cache-sync-timer
  4767. (cancel-timer org-element--cache-sync-timer))
  4768. (setq org-element--cache-sync-timer
  4769. (run-with-idle-timer
  4770. (let ((idle (current-idle-time)))
  4771. (if idle (time-add idle org-element-cache-sync-break)
  4772. org-element-cache-sync-idle-time))
  4773. nil
  4774. #'org-element--cache-sync
  4775. buffer)))
  4776. (defsubst org-element--cache-interrupt-p (time-limit)
  4777. "Non-nil when synchronization process should be interrupted.
  4778. TIME-LIMIT is a time value or nil."
  4779. (and time-limit
  4780. (or (input-pending-p)
  4781. (time-less-p time-limit nil))))
  4782. (defsubst org-element--cache-shift-positions (element offset &optional props)
  4783. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  4784. Properties containing buffer positions are `:begin', `:end',
  4785. `:contents-begin', `:contents-end' and `:structure'. When
  4786. optional argument PROPS is a list of keywords, only shift
  4787. properties provided in that list.
  4788. Properties are modified by side-effect."
  4789. (let ((properties (nth 1 element)))
  4790. ;; Shift `:structure' property for the first plain list only: it
  4791. ;; is the only one that really matters and it prevents from
  4792. ;; shifting it more than once.
  4793. (when (and (or (not props) (memq :structure props))
  4794. (eq (org-element-type element) 'plain-list)
  4795. (not (eq (org-element-type (plist-get properties :parent))
  4796. 'item)))
  4797. (dolist (item (plist-get properties :structure))
  4798. (cl-incf (car item) offset)
  4799. (cl-incf (nth 6 item) offset)))
  4800. (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
  4801. (let ((value (and (or (not props) (memq key props))
  4802. (plist-get properties key))))
  4803. (and value (plist-put properties key (+ offset value)))))))
  4804. (defun org-element--cache-sync (buffer &optional threshold future-change)
  4805. "Synchronize cache with recent modification in BUFFER.
  4806. When optional argument THRESHOLD is non-nil, do the
  4807. synchronization for all elements starting before or at threshold,
  4808. then exit. Otherwise, synchronize cache for as long as
  4809. `org-element-cache-sync-duration' or until Emacs leaves idle
  4810. state.
  4811. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  4812. not registered yet in the cache are going to happen. It is used
  4813. in `org-element--cache-submit-request', where cache is partially
  4814. updated before current modification are actually submitted."
  4815. (when (buffer-live-p buffer)
  4816. (with-current-buffer buffer
  4817. (let ((inhibit-quit t) request next)
  4818. (when org-element--cache-sync-timer
  4819. (cancel-timer org-element--cache-sync-timer))
  4820. (catch 'interrupt
  4821. (while org-element--cache-sync-requests
  4822. (setq request (car org-element--cache-sync-requests)
  4823. next (nth 1 org-element--cache-sync-requests))
  4824. (org-element--cache-process-request
  4825. request
  4826. (and next (aref next 0))
  4827. threshold
  4828. (and (not threshold)
  4829. (time-add nil org-element-cache-sync-duration))
  4830. future-change)
  4831. ;; Request processed. Merge current and next offsets and
  4832. ;; transfer ending position.
  4833. (when next
  4834. (cl-incf (aref next 3) (aref request 3))
  4835. (aset next 2 (aref request 2)))
  4836. (setq org-element--cache-sync-requests
  4837. (cdr org-element--cache-sync-requests))))
  4838. ;; If more requests are awaiting, set idle timer accordingly.
  4839. ;; Otherwise, reset keys.
  4840. (if org-element--cache-sync-requests
  4841. (org-element--cache-set-timer buffer)
  4842. (clrhash org-element--cache-sync-keys))))))
  4843. (defun org-element--cache-process-request
  4844. (request next threshold time-limit future-change)
  4845. "Process synchronization REQUEST for all entries before NEXT.
  4846. REQUEST is a vector, built by `org-element--cache-submit-request'.
  4847. NEXT is a cache key, as returned by `org-element--cache-key'.
  4848. When non-nil, THRESHOLD is a buffer position. Synchronization
  4849. stops as soon as a shifted element begins after it.
  4850. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  4851. after this time or when Emacs exits idle state.
  4852. When non-nil, FUTURE-CHANGE is a buffer position where changes
  4853. not registered yet in the cache are going to happen. See
  4854. `org-element--cache-submit-request' for more information.
  4855. Throw `interrupt' if the process stops before completing the
  4856. request."
  4857. (catch 'quit
  4858. (when (= (aref request 5) 0)
  4859. ;; Phase 0.
  4860. ;;
  4861. ;; Delete all elements starting after BEG, but not after buffer
  4862. ;; position END or past element with key NEXT. Also delete
  4863. ;; elements contained within a previously removed element
  4864. ;; (stored in `last-container').
  4865. ;;
  4866. ;; At each iteration, we start again at tree root since
  4867. ;; a deletion modifies structure of the balanced tree.
  4868. (catch 'end-phase
  4869. (while t
  4870. (when (org-element--cache-interrupt-p time-limit)
  4871. (throw 'interrupt nil))
  4872. ;; Find first element in cache with key BEG or after it.
  4873. (let ((beg (aref request 0))
  4874. (end (aref request 2))
  4875. (node (org-element--cache-root))
  4876. data data-key last-container)
  4877. (while node
  4878. (let* ((element (avl-tree--node-data node))
  4879. (key (org-element--cache-key element)))
  4880. (cond
  4881. ((org-element--cache-key-less-p key beg)
  4882. (setq node (avl-tree--node-right node)))
  4883. ((org-element--cache-key-less-p beg key)
  4884. (setq data element
  4885. data-key key
  4886. node (avl-tree--node-left node)))
  4887. (t (setq data element
  4888. data-key key
  4889. node nil)))))
  4890. (if data
  4891. (let ((pos (org-element-property :begin data)))
  4892. (if (if (or (not next)
  4893. (org-element--cache-key-less-p data-key next))
  4894. (<= pos end)
  4895. (and last-container
  4896. (let ((up data))
  4897. (while (and up (not (eq up last-container)))
  4898. (setq up (org-element-property :parent up)))
  4899. up)))
  4900. (progn (when (and (not last-container)
  4901. (> (org-element-property :end data)
  4902. end))
  4903. (setq last-container data))
  4904. (org-element--cache-remove data))
  4905. (aset request 0 data-key)
  4906. (aset request 1 pos)
  4907. (aset request 5 1)
  4908. (throw 'end-phase nil)))
  4909. ;; No element starting after modifications left in
  4910. ;; cache: further processing is futile.
  4911. (throw 'quit t))))))
  4912. (when (= (aref request 5) 1)
  4913. ;; Phase 1.
  4914. ;;
  4915. ;; Phase 0 left a hole in the cache. Some elements after it
  4916. ;; could have parents within. For example, in the following
  4917. ;; buffer:
  4918. ;;
  4919. ;; - item
  4920. ;;
  4921. ;;
  4922. ;; Paragraph1
  4923. ;;
  4924. ;; Paragraph2
  4925. ;;
  4926. ;; if we remove a blank line between "item" and "Paragraph1",
  4927. ;; everything down to "Paragraph2" is removed from cache. But
  4928. ;; the paragraph now belongs to the list, and its `:parent'
  4929. ;; property no longer is accurate.
  4930. ;;
  4931. ;; Therefore we need to parse again elements in the hole, or at
  4932. ;; least in its last section, so that we can re-parent
  4933. ;; subsequent elements, during phase 2.
  4934. ;;
  4935. ;; Note that we only need to get the parent from the first
  4936. ;; element in cache after the hole.
  4937. ;;
  4938. ;; When next key is lesser or equal to the current one, delegate
  4939. ;; phase 1 processing to next request in order to preserve key
  4940. ;; order among requests.
  4941. (let ((key (aref request 0)))
  4942. (when (and next (not (org-element--cache-key-less-p key next)))
  4943. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  4944. (aset next-request 0 key)
  4945. (aset next-request 1 (aref request 1))
  4946. (aset next-request 5 1))
  4947. (throw 'quit t)))
  4948. ;; Next element will start at its beginning position plus
  4949. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  4950. ;; contains the real beginning position of the first element to
  4951. ;; shift and re-parent.
  4952. (let ((limit (+ (aref request 1) (aref request 3))))
  4953. (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
  4954. ((and future-change (>= limit future-change))
  4955. ;; Changes are going to happen around this element and
  4956. ;; they will trigger another phase 1 request. Skip the
  4957. ;; current one.
  4958. (aset request 5 2))
  4959. (t
  4960. (let ((parent (org-element--parse-to limit t time-limit)))
  4961. (aset request 4 parent)
  4962. (aset request 5 2))))))
  4963. ;; Phase 2.
  4964. ;;
  4965. ;; Shift all elements starting from key START, but before NEXT, by
  4966. ;; OFFSET, and re-parent them when appropriate.
  4967. ;;
  4968. ;; Elements are modified by side-effect so the tree structure
  4969. ;; remains intact.
  4970. ;;
  4971. ;; Once THRESHOLD, if any, is reached, or once there is an input
  4972. ;; pending, exit. Before leaving, the current synchronization
  4973. ;; request is updated.
  4974. (let ((start (aref request 0))
  4975. (offset (aref request 3))
  4976. (parent (aref request 4))
  4977. (node (org-element--cache-root))
  4978. (stack (list nil))
  4979. (leftp t)
  4980. exit-flag)
  4981. ;; No re-parenting nor shifting planned: request is over.
  4982. (when (and (not parent) (zerop offset)) (throw 'quit t))
  4983. (while node
  4984. (let* ((data (avl-tree--node-data node))
  4985. (key (org-element--cache-key data)))
  4986. (if (and leftp (avl-tree--node-left node)
  4987. (not (org-element--cache-key-less-p key start)))
  4988. (progn (push node stack)
  4989. (setq node (avl-tree--node-left node)))
  4990. (unless (org-element--cache-key-less-p key start)
  4991. ;; We reached NEXT. Request is complete.
  4992. (when (equal key next) (throw 'quit t))
  4993. ;; Handle interruption request. Update current request.
  4994. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  4995. (aset request 0 key)
  4996. (aset request 4 parent)
  4997. (throw 'interrupt nil))
  4998. ;; Shift element.
  4999. (unless (zerop offset)
  5000. (org-element--cache-shift-positions data offset))
  5001. (let ((begin (org-element-property :begin data)))
  5002. ;; Update PARENT and re-parent DATA, only when
  5003. ;; necessary. Propagate new structures for lists.
  5004. (while (and parent
  5005. (<= (org-element-property :end parent) begin))
  5006. (setq parent (org-element-property :parent parent)))
  5007. (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
  5008. ((and parent
  5009. (let ((p (org-element-property :parent data)))
  5010. (or (not p)
  5011. (< (org-element-property :begin p)
  5012. (org-element-property :begin parent)))))
  5013. (org-element-put-property data :parent parent)
  5014. (let ((s (org-element-property :structure parent)))
  5015. (when (and s (org-element-property :structure data))
  5016. (org-element-put-property data :structure s)))))
  5017. ;; Cache is up-to-date past THRESHOLD. Request
  5018. ;; interruption.
  5019. (when (and threshold (> begin threshold)) (setq exit-flag t))))
  5020. (setq node (if (setq leftp (avl-tree--node-right node))
  5021. (avl-tree--node-right node)
  5022. (pop stack))))))
  5023. ;; We reached end of tree: synchronization complete.
  5024. t)))
  5025. (defun org-element--parse-to (pos &optional syncp time-limit)
  5026. "Parse elements in current section, down to POS.
  5027. Start parsing from the closest between the last known element in
  5028. cache or headline above. Return the smallest element containing
  5029. POS.
  5030. When optional argument SYNCP is non-nil, return the parent of the
  5031. element containing POS instead. In that case, it is also
  5032. possible to provide TIME-LIMIT, which is a time value specifying
  5033. when the parsing should stop. The function throws `interrupt' if
  5034. the process stopped before finding the expected result."
  5035. (catch 'exit
  5036. (org-with-wide-buffer
  5037. (goto-char pos)
  5038. (let* ((cached (and (org-element--cache-active-p)
  5039. (org-element--cache-find pos nil)))
  5040. (begin (org-element-property :begin cached))
  5041. element next mode)
  5042. (cond
  5043. ;; Nothing in cache before point: start parsing from first
  5044. ;; element following headline above, or first element in
  5045. ;; buffer.
  5046. ((not cached)
  5047. (if (org-with-limited-levels (outline-previous-heading))
  5048. (progn
  5049. (setq mode 'planning)
  5050. (forward-line))
  5051. (setq mode 'top-comment))
  5052. (skip-chars-forward " \r\t\n")
  5053. (beginning-of-line))
  5054. ;; Cache returned exact match: return it.
  5055. ((= pos begin)
  5056. (throw 'exit (if syncp (org-element-property :parent cached) cached)))
  5057. ;; There's a headline between cached value and POS: cached
  5058. ;; value is invalid. Start parsing from first element
  5059. ;; following the headline.
  5060. ((re-search-backward
  5061. (org-with-limited-levels org-outline-regexp-bol) begin t)
  5062. (forward-line)
  5063. (skip-chars-forward " \r\t\n")
  5064. (beginning-of-line)
  5065. (setq mode 'planning))
  5066. ;; Check if CACHED or any of its ancestors contain point.
  5067. ;;
  5068. ;; If there is such an element, we inspect it in order to know
  5069. ;; if we return it or if we need to parse its contents.
  5070. ;; Otherwise, we just start parsing from current location,
  5071. ;; which is right after the top-most element containing
  5072. ;; CACHED.
  5073. ;;
  5074. ;; As a special case, if POS is at the end of the buffer, we
  5075. ;; want to return the innermost element ending there.
  5076. ;;
  5077. ;; Also, if we find an ancestor and discover that we need to
  5078. ;; parse its contents, make sure we don't start from
  5079. ;; `:contents-begin', as we would otherwise go past CACHED
  5080. ;; again. Instead, in that situation, we will resume parsing
  5081. ;; from NEXT, which is located after CACHED or its higher
  5082. ;; ancestor not containing point.
  5083. (t
  5084. (let ((up cached)
  5085. (pos (if (= (point-max) pos) (1- pos) pos)))
  5086. (goto-char (or (org-element-property :contents-begin cached) begin))
  5087. (while (let ((end (org-element-property :end up)))
  5088. (and (<= end pos)
  5089. (goto-char end)
  5090. (setq up (org-element-property :parent up)))))
  5091. (cond ((not up))
  5092. ((eobp) (setq element up))
  5093. (t (setq element up next (point)))))))
  5094. ;; Parse successively each element until we reach POS.
  5095. (let ((end (or (org-element-property :end element)
  5096. (save-excursion
  5097. (org-with-limited-levels (outline-next-heading))
  5098. (point))))
  5099. (parent element))
  5100. (while t
  5101. (when syncp
  5102. (cond ((= (point) pos) (throw 'exit parent))
  5103. ((org-element--cache-interrupt-p time-limit)
  5104. (throw 'interrupt nil))))
  5105. (unless element
  5106. (setq element (org-element--current-element
  5107. end 'element mode
  5108. (org-element-property :structure parent)))
  5109. (org-element-put-property element :parent parent)
  5110. (org-element--cache-put element))
  5111. (let ((elem-end (org-element-property :end element))
  5112. (type (org-element-type element)))
  5113. (cond
  5114. ;; Skip any element ending before point. Also skip
  5115. ;; element ending at point (unless it is also the end of
  5116. ;; buffer) since we're sure that another element begins
  5117. ;; after it.
  5118. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5119. (goto-char elem-end)
  5120. (setq mode (org-element--next-mode mode type nil)))
  5121. ;; A non-greater element contains point: return it.
  5122. ((not (memq type org-element-greater-elements))
  5123. (throw 'exit element))
  5124. ;; Otherwise, we have to decide if ELEMENT really
  5125. ;; contains POS. In that case we start parsing from
  5126. ;; contents' beginning.
  5127. ;;
  5128. ;; If POS is at contents' beginning but it is also at
  5129. ;; the beginning of the first item in a list or a table.
  5130. ;; In that case, we need to create an anchor for that
  5131. ;; list or table, so return it.
  5132. ;;
  5133. ;; Also, if POS is at the end of the buffer, no element
  5134. ;; can start after it, but more than one may end there.
  5135. ;; Arbitrarily, we choose to return the innermost of
  5136. ;; such elements.
  5137. ((let ((cbeg (org-element-property :contents-begin element))
  5138. (cend (org-element-property :contents-end element)))
  5139. (when (or syncp
  5140. (and cbeg cend
  5141. (or (< cbeg pos)
  5142. (and (= cbeg pos)
  5143. (not (memq type '(plain-list table)))))
  5144. (or (> cend pos)
  5145. (and (= cend pos) (= (point-max) pos)))))
  5146. (goto-char (or next cbeg))
  5147. (setq next nil
  5148. mode (org-element--next-mode mode type t)
  5149. parent element
  5150. end cend))))
  5151. ;; Otherwise, return ELEMENT as it is the smallest
  5152. ;; element containing POS.
  5153. (t (throw 'exit element))))
  5154. (setq element nil)))))))
  5155. ;;;; Staging Buffer Changes
  5156. (defconst org-element--cache-sensitive-re
  5157. (concat
  5158. "^\\*+ " "\\|"
  5159. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5160. "^[ \t]*\\(?:"
  5161. "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
  5162. "\\\\begin{[A-Za-z0-9*]+}" "\\|"
  5163. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  5164. "\\)")
  5165. "Regexp matching a sensitive line, structure wise.
  5166. A sensitive line is a headline, inlinetask, block, drawer, or
  5167. latex-environment boundary. When such a line is modified,
  5168. structure changes in the document may propagate in the whole
  5169. section, possibly making cache invalid.")
  5170. (defvar org-element--cache-change-warning nil
  5171. "Non-nil when a sensitive line is about to be changed.
  5172. It is a symbol among nil, t and `headline'.")
  5173. (defun org-element--cache-before-change (beg end)
  5174. "Request extension of area going to be modified if needed.
  5175. BEG and END are the beginning and end of the range of changed
  5176. text. See `before-change-functions' for more information."
  5177. (when (org-element--cache-active-p)
  5178. (org-with-wide-buffer
  5179. (goto-char beg)
  5180. (beginning-of-line)
  5181. (let ((bottom (save-excursion (goto-char end) (line-end-position))))
  5182. (setq org-element--cache-change-warning
  5183. (save-match-data
  5184. (if (and (org-with-limited-levels (org-at-heading-p))
  5185. (= (line-end-position) bottom))
  5186. 'headline
  5187. (let ((case-fold-search t))
  5188. (re-search-forward
  5189. org-element--cache-sensitive-re bottom t)))))))))
  5190. (defun org-element--cache-after-change (beg end pre)
  5191. "Update buffer modifications for current buffer.
  5192. BEG and END are the beginning and end of the range of changed
  5193. text, and the length in bytes of the pre-change text replaced by
  5194. that range. See `after-change-functions' for more information."
  5195. (when (org-element--cache-active-p)
  5196. (org-with-wide-buffer
  5197. (goto-char beg)
  5198. (beginning-of-line)
  5199. (save-match-data
  5200. (let ((top (point))
  5201. (bottom (save-excursion (goto-char end) (line-end-position))))
  5202. ;; Determine if modified area needs to be extended, according
  5203. ;; to both previous and current state. We make a special
  5204. ;; case for headline editing: if a headline is modified but
  5205. ;; not removed, do not extend.
  5206. (when (pcase org-element--cache-change-warning
  5207. (`t t)
  5208. (`headline
  5209. (not (and (org-with-limited-levels (org-at-heading-p))
  5210. (= (line-end-position) bottom))))
  5211. (_
  5212. (let ((case-fold-search t))
  5213. (re-search-forward
  5214. org-element--cache-sensitive-re bottom t))))
  5215. ;; Effectively extend modified area.
  5216. (org-with-limited-levels
  5217. (setq top (progn (goto-char top)
  5218. (when (outline-previous-heading) (forward-line))
  5219. (point)))
  5220. (setq bottom (progn (goto-char bottom)
  5221. (if (outline-next-heading) (1- (point))
  5222. (point))))))
  5223. ;; Store synchronization request.
  5224. (let ((offset (- end beg pre)))
  5225. (org-element--cache-submit-request top (- bottom offset) offset)))))
  5226. ;; Activate a timer to process the request during idle time.
  5227. (org-element--cache-set-timer (current-buffer))))
  5228. (defun org-element--cache-for-removal (beg end offset)
  5229. "Return first element to remove from cache.
  5230. BEG and END are buffer positions delimiting buffer modifications.
  5231. OFFSET is the size of the changes.
  5232. Returned element is usually the first element in cache containing
  5233. any position between BEG and END. As an exception, greater
  5234. elements around the changes that are robust to contents
  5235. modifications are preserved and updated according to the
  5236. changes."
  5237. (let* ((elements (org-element--cache-find (1- beg) 'both))
  5238. (before (car elements))
  5239. (after (cdr elements)))
  5240. (if (not before) after
  5241. (let ((up before)
  5242. (robust-flag t))
  5243. (while up
  5244. (if (let ((type (org-element-type up)))
  5245. (and (or (memq type '(center-block dynamic-block quote-block
  5246. special-block))
  5247. ;; Drawers named "PROPERTIES" are probably
  5248. ;; a properties drawer being edited. Force
  5249. ;; parsing to check if editing is over.
  5250. (and (eq type 'drawer)
  5251. (not (string=
  5252. (org-element-property :drawer-name up)
  5253. "PROPERTIES"))))
  5254. (let ((cbeg (org-element-property :contents-begin up)))
  5255. (and cbeg
  5256. (<= cbeg beg)
  5257. (> (org-element-property :contents-end up) end)))))
  5258. ;; UP is a robust greater element containing changes.
  5259. ;; We only need to extend its ending boundaries.
  5260. (org-element--cache-shift-positions
  5261. up offset '(:contents-end :end))
  5262. (setq before up)
  5263. (when robust-flag (setq robust-flag nil)))
  5264. (setq up (org-element-property :parent up)))
  5265. ;; We're at top level element containing ELEMENT: if it's
  5266. ;; altered by buffer modifications, it is first element in
  5267. ;; cache to be removed. Otherwise, that first element is the
  5268. ;; following one.
  5269. ;;
  5270. ;; As a special case, do not remove BEFORE if it is a robust
  5271. ;; container for current changes.
  5272. (if (or (< (org-element-property :end before) beg) robust-flag) after
  5273. before)))))
  5274. (defun org-element--cache-submit-request (beg end offset)
  5275. "Submit a new cache synchronization request for current buffer.
  5276. BEG and END are buffer positions delimiting the minimal area
  5277. where cache data should be removed. OFFSET is the size of the
  5278. change, as an integer."
  5279. (let ((next (car org-element--cache-sync-requests))
  5280. delete-to delete-from)
  5281. (if (and next
  5282. (zerop (aref next 5))
  5283. (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
  5284. (<= (setq delete-from (aref next 1)) end))
  5285. ;; Current changes can be merged with first sync request: we
  5286. ;; can save a partial cache synchronization.
  5287. (progn
  5288. (cl-incf (aref next 3) offset)
  5289. ;; If last change happened within area to be removed, extend
  5290. ;; boundaries of robust parents, if any. Otherwise, find
  5291. ;; first element to remove and update request accordingly.
  5292. (if (> beg delete-from)
  5293. (let ((up (aref next 4)))
  5294. (while up
  5295. (org-element--cache-shift-positions
  5296. up offset '(:contents-end :end))
  5297. (setq up (org-element-property :parent up))))
  5298. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  5299. (when first
  5300. (aset next 0 (org-element--cache-key first))
  5301. (aset next 1 (org-element-property :begin first))
  5302. (aset next 4 (org-element-property :parent first))))))
  5303. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  5304. ;; if any, is no longer a 0-phase request, thus ensuring that
  5305. ;; phases are properly ordered. We need to provide OFFSET as
  5306. ;; optional parameter since current modifications are not known
  5307. ;; yet to the otherwise correct part of the cache (i.e, before
  5308. ;; the first request).
  5309. (when next (org-element--cache-sync (current-buffer) end beg))
  5310. (let ((first (org-element--cache-for-removal beg end offset)))
  5311. (if first
  5312. (push (let ((beg (org-element-property :begin first))
  5313. (key (org-element--cache-key first)))
  5314. (cond
  5315. ;; When changes happen before the first known
  5316. ;; element, re-parent and shift the rest of the
  5317. ;; cache.
  5318. ((> beg end) (vector key beg nil offset nil 1))
  5319. ;; Otherwise, we find the first non robust
  5320. ;; element containing END. All elements between
  5321. ;; FIRST and this one are to be removed.
  5322. ((let ((first-end (org-element-property :end first)))
  5323. (and (> first-end end)
  5324. (vector key beg first-end offset first 0))))
  5325. (t
  5326. (let* ((element (org-element--cache-find end))
  5327. (end (org-element-property :end element))
  5328. (up element))
  5329. (while (and (setq up (org-element-property :parent up))
  5330. (>= (org-element-property :begin up) beg))
  5331. (setq end (org-element-property :end up)
  5332. element up))
  5333. (vector key beg end offset element 0)))))
  5334. org-element--cache-sync-requests)
  5335. ;; No element to remove. No need to re-parent either.
  5336. ;; Simply shift additional elements, if any, by OFFSET.
  5337. (when org-element--cache-sync-requests
  5338. (cl-incf (aref (car org-element--cache-sync-requests) 3)
  5339. offset)))))))
  5340. ;;;; Public Functions
  5341. ;;;###autoload
  5342. (defun org-element-cache-reset (&optional all)
  5343. "Reset cache in current buffer.
  5344. When optional argument ALL is non-nil, reset cache in all Org
  5345. buffers."
  5346. (interactive "P")
  5347. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  5348. (with-current-buffer buffer
  5349. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  5350. (setq-local org-element--cache
  5351. (avl-tree-create #'org-element--cache-compare))
  5352. (setq-local org-element--cache-sync-keys
  5353. (make-hash-table :weakness 'key :test #'eq))
  5354. (setq-local org-element--cache-change-warning nil)
  5355. (setq-local org-element--cache-sync-requests nil)
  5356. (setq-local org-element--cache-sync-timer nil)
  5357. (add-hook 'before-change-functions
  5358. #'org-element--cache-before-change nil t)
  5359. (add-hook 'after-change-functions
  5360. #'org-element--cache-after-change nil t)))))
  5361. ;;;###autoload
  5362. (defun org-element-cache-refresh (pos)
  5363. "Refresh cache at position POS."
  5364. (when (org-element--cache-active-p)
  5365. (org-element--cache-sync (current-buffer) pos)
  5366. (org-element--cache-submit-request pos pos 0)
  5367. (org-element--cache-set-timer (current-buffer))))
  5368. ;;; The Toolbox
  5369. ;;
  5370. ;; The first move is to implement a way to obtain the smallest element
  5371. ;; containing point. This is the job of `org-element-at-point'. It
  5372. ;; basically jumps back to the beginning of section containing point
  5373. ;; and proceed, one element after the other, with
  5374. ;; `org-element--current-element' until the container is found. Note:
  5375. ;; When using `org-element-at-point', secondary values are never
  5376. ;; parsed since the function focuses on elements, not on objects.
  5377. ;;
  5378. ;; At a deeper level, `org-element-context' lists all elements and
  5379. ;; objects containing point.
  5380. ;;
  5381. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  5382. ;; internally by navigation and manipulation tools.
  5383. ;;;###autoload
  5384. (defun org-element-at-point ()
  5385. "Determine closest element around point.
  5386. Return value is a list like (TYPE PROPS) where TYPE is the type
  5387. of the element and PROPS a plist of properties associated to the
  5388. element.
  5389. Possible types are defined in `org-element-all-elements'.
  5390. Properties depend on element or object type, but always include
  5391. `:begin', `:end', and `:post-blank' properties.
  5392. As a special case, if point is at the very beginning of the first
  5393. item in a list or sub-list, returned element will be that list
  5394. instead of the item. Likewise, if point is at the beginning of
  5395. the first row of a table, returned element will be the table
  5396. instead of the first row.
  5397. When point is at the end of the buffer, return the innermost
  5398. element ending there."
  5399. (org-with-wide-buffer
  5400. (let ((origin (point)))
  5401. (end-of-line)
  5402. (skip-chars-backward " \r\t\n")
  5403. (cond
  5404. ;; Within blank lines at the beginning of buffer, return nil.
  5405. ((bobp) nil)
  5406. ;; Within blank lines right after a headline, return that
  5407. ;; headline.
  5408. ((org-with-limited-levels (org-at-heading-p))
  5409. (beginning-of-line)
  5410. (org-element-headline-parser (point-max) t))
  5411. ;; Otherwise parse until we find element containing ORIGIN.
  5412. (t
  5413. (when (org-element--cache-active-p)
  5414. (if (not org-element--cache) (org-element-cache-reset)
  5415. (org-element--cache-sync (current-buffer) origin)))
  5416. (org-element--parse-to origin))))))
  5417. ;;;###autoload
  5418. (defun org-element-context (&optional element)
  5419. "Return smallest element or object around point.
  5420. Return value is a list like (TYPE PROPS) where TYPE is the type
  5421. of the element or object and PROPS a plist of properties
  5422. associated to it.
  5423. Possible types are defined in `org-element-all-elements' and
  5424. `org-element-all-objects'. Properties depend on element or
  5425. object type, but always include `:begin', `:end', `:parent' and
  5426. `:post-blank'.
  5427. As a special case, if point is right after an object and not at
  5428. the beginning of any other object, return that object.
  5429. Optional argument ELEMENT, when non-nil, is the closest element
  5430. containing point, as returned by `org-element-at-point'.
  5431. Providing it allows for quicker computation."
  5432. (catch 'objects-forbidden
  5433. (org-with-wide-buffer
  5434. (let* ((pos (point))
  5435. (element (or element (org-element-at-point)))
  5436. (type (org-element-type element))
  5437. (post (org-element-property :post-affiliated element)))
  5438. ;; If point is inside an element containing objects or
  5439. ;; a secondary string, narrow buffer to the container and
  5440. ;; proceed with parsing. Otherwise, return ELEMENT.
  5441. (cond
  5442. ;; At a parsed affiliated keyword, check if we're inside main
  5443. ;; or dual value.
  5444. ((and post (< pos post))
  5445. (beginning-of-line)
  5446. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  5447. (cond
  5448. ((not (member-ignore-case (match-string 1)
  5449. org-element-parsed-keywords))
  5450. (throw 'objects-forbidden element))
  5451. ((< (match-end 0) pos)
  5452. (narrow-to-region (match-end 0) (line-end-position)))
  5453. ((and (match-beginning 2)
  5454. (>= pos (match-beginning 2))
  5455. (< pos (match-end 2)))
  5456. (narrow-to-region (match-beginning 2) (match-end 2)))
  5457. (t (throw 'objects-forbidden element)))
  5458. ;; Also change type to retrieve correct restrictions.
  5459. (setq type 'keyword))
  5460. ;; At an item, objects can only be located within tag, if any.
  5461. ((eq type 'item)
  5462. (let ((tag (org-element-property :tag element)))
  5463. (if (or (not tag) (/= (line-beginning-position) post))
  5464. (throw 'objects-forbidden element)
  5465. (beginning-of-line)
  5466. (search-forward tag (line-end-position))
  5467. (goto-char (match-beginning 0))
  5468. (if (and (>= pos (point)) (< pos (match-end 0)))
  5469. (narrow-to-region (point) (match-end 0))
  5470. (throw 'objects-forbidden element)))))
  5471. ;; At an headline or inlinetask, objects are in title.
  5472. ((memq type '(headline inlinetask))
  5473. (let ((case-fold-search nil))
  5474. (goto-char (org-element-property :begin element))
  5475. (looking-at org-complex-heading-regexp)
  5476. (let ((end (match-end 4)))
  5477. (if (not end) (throw 'objects-forbidden element)
  5478. (goto-char (match-beginning 4))
  5479. (when (looking-at org-comment-string)
  5480. (goto-char (match-end 0)))
  5481. (if (>= (point) end) (throw 'objects-forbidden element)
  5482. (narrow-to-region (point) end))))))
  5483. ;; At a paragraph, a table-row or a verse block, objects are
  5484. ;; located within their contents.
  5485. ((memq type '(paragraph table-row verse-block))
  5486. (let ((cbeg (org-element-property :contents-begin element))
  5487. (cend (org-element-property :contents-end element)))
  5488. ;; CBEG is nil for table rules.
  5489. (if (and cbeg cend (>= pos cbeg)
  5490. (or (< pos cend) (and (= pos cend) (eobp))))
  5491. (narrow-to-region cbeg cend)
  5492. (throw 'objects-forbidden element))))
  5493. (t (throw 'objects-forbidden element)))
  5494. (goto-char (point-min))
  5495. (let ((restriction (org-element-restriction type))
  5496. (parent element)
  5497. last)
  5498. (catch 'exit
  5499. (while t
  5500. (let ((next (org-element--object-lex restriction)))
  5501. (when next (org-element-put-property next :parent parent))
  5502. ;; Process NEXT, if any, in order to know if we need to
  5503. ;; skip it, return it or move into it.
  5504. (if (or (not next) (> (org-element-property :begin next) pos))
  5505. (throw 'exit (or last parent))
  5506. (let ((end (org-element-property :end next))
  5507. (cbeg (org-element-property :contents-begin next))
  5508. (cend (org-element-property :contents-end next)))
  5509. (cond
  5510. ;; Skip objects ending before point. Also skip
  5511. ;; objects ending at point unless it is also the
  5512. ;; end of buffer, since we want to return the
  5513. ;; innermost object.
  5514. ((and (<= end pos) (/= (point-max) end))
  5515. (goto-char end)
  5516. ;; For convenience, when object ends at POS,
  5517. ;; without any space, store it in LAST, as we
  5518. ;; will return it if no object starts here.
  5519. (when (and (= end pos)
  5520. (not (memq (char-before) '(?\s ?\t))))
  5521. (setq last next)))
  5522. ;; If POS is within a container object, move into
  5523. ;; that object.
  5524. ((and cbeg cend
  5525. (>= pos cbeg)
  5526. (or (< pos cend)
  5527. ;; At contents' end, if there is no
  5528. ;; space before point, also move into
  5529. ;; object, for consistency with
  5530. ;; convenience feature above.
  5531. (and (= pos cend)
  5532. (or (= (point-max) pos)
  5533. (not (memq (char-before pos)
  5534. '(?\s ?\t)))))))
  5535. (goto-char cbeg)
  5536. (narrow-to-region (point) cend)
  5537. (setq parent next)
  5538. (setq restriction (org-element-restriction next)))
  5539. ;; Otherwise, return NEXT.
  5540. (t (throw 'exit next)))))))))))))
  5541. (defun org-element-lineage (datum &optional types with-self)
  5542. "List all ancestors of a given element or object.
  5543. DATUM is an object or element.
  5544. Return ancestors from the closest to the farthest. When optional
  5545. argument TYPES is a list of symbols, return the first element or
  5546. object in the lineage whose type belongs to that list instead.
  5547. When optional argument WITH-SELF is non-nil, lineage includes
  5548. DATUM itself as the first element, and TYPES, if provided, also
  5549. apply to it.
  5550. When DATUM is obtained through `org-element-context' or
  5551. `org-element-at-point', only ancestors from its section can be
  5552. found. There is no such limitation when DATUM belongs to a full
  5553. parse tree."
  5554. (let ((up (if with-self datum (org-element-property :parent datum)))
  5555. ancestors)
  5556. (while (and up (not (memq (org-element-type up) types)))
  5557. (unless types (push up ancestors))
  5558. (setq up (org-element-property :parent up)))
  5559. (if types up (nreverse ancestors))))
  5560. (defun org-element-nested-p (elem-A elem-B)
  5561. "Non-nil when elements ELEM-A and ELEM-B are nested."
  5562. (let ((beg-A (org-element-property :begin elem-A))
  5563. (beg-B (org-element-property :begin elem-B))
  5564. (end-A (org-element-property :end elem-A))
  5565. (end-B (org-element-property :end elem-B)))
  5566. (or (and (>= beg-A beg-B) (<= end-A end-B))
  5567. (and (>= beg-B beg-A) (<= end-B end-A)))))
  5568. (defun org-element-swap-A-B (elem-A elem-B)
  5569. "Swap elements ELEM-A and ELEM-B.
  5570. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  5571. end of ELEM-A."
  5572. (goto-char (org-element-property :begin elem-A))
  5573. ;; There are two special cases when an element doesn't start at bol:
  5574. ;; the first paragraph in an item or in a footnote definition.
  5575. (let ((specialp (not (bolp))))
  5576. ;; Only a paragraph without any affiliated keyword can be moved at
  5577. ;; ELEM-A position in such a situation. Note that the case of
  5578. ;; a footnote definition is impossible: it cannot contain two
  5579. ;; paragraphs in a row because it cannot contain a blank line.
  5580. (when (and specialp
  5581. (or (not (eq (org-element-type elem-B) 'paragraph))
  5582. (/= (org-element-property :begin elem-B)
  5583. (org-element-property :contents-begin elem-B))))
  5584. (error "Cannot swap elements"))
  5585. ;; In a special situation, ELEM-A will have no indentation. We'll
  5586. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  5587. (let* ((ind-B (when specialp
  5588. (goto-char (org-element-property :begin elem-B))
  5589. (current-indentation)))
  5590. (beg-A (org-element-property :begin elem-A))
  5591. (end-A (save-excursion
  5592. (goto-char (org-element-property :end elem-A))
  5593. (skip-chars-backward " \r\t\n")
  5594. (point-at-eol)))
  5595. (beg-B (org-element-property :begin elem-B))
  5596. (end-B (save-excursion
  5597. (goto-char (org-element-property :end elem-B))
  5598. (skip-chars-backward " \r\t\n")
  5599. (point-at-eol)))
  5600. ;; Store inner overlays responsible for visibility status.
  5601. ;; We also need to store their boundaries as they will be
  5602. ;; removed from buffer.
  5603. (overlays
  5604. (cons
  5605. (delq nil
  5606. (mapcar (lambda (o)
  5607. (and (>= (overlay-start o) beg-A)
  5608. (<= (overlay-end o) end-A)
  5609. (list o (overlay-start o) (overlay-end o))))
  5610. (overlays-in beg-A end-A)))
  5611. (delq nil
  5612. (mapcar (lambda (o)
  5613. (and (>= (overlay-start o) beg-B)
  5614. (<= (overlay-end o) end-B)
  5615. (list o (overlay-start o) (overlay-end o))))
  5616. (overlays-in beg-B end-B)))))
  5617. ;; Get contents.
  5618. (body-A (buffer-substring beg-A end-A))
  5619. (body-B (delete-and-extract-region beg-B end-B)))
  5620. (goto-char beg-B)
  5621. (when specialp
  5622. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  5623. (indent-to-column ind-B))
  5624. (insert body-A)
  5625. ;; Restore ex ELEM-A overlays.
  5626. (let ((offset (- beg-B beg-A)))
  5627. (dolist (o (car overlays))
  5628. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  5629. (goto-char beg-A)
  5630. (delete-region beg-A end-A)
  5631. (insert body-B)
  5632. ;; Restore ex ELEM-B overlays.
  5633. (dolist (o (cdr overlays))
  5634. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  5635. (goto-char (org-element-property :end elem-B)))))
  5636. (provide 'org-element)
  5637. ;; Local variables:
  5638. ;; generated-autoload-file: "org-loaddefs.el"
  5639. ;; End:
  5640. ;;; org-element.el ends here