org-element.el 214 KB

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