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