org-element.el 213 KB

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