org-element.el 219 KB

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