org-element.el 214 KB

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