org-element.el 212 KB

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