org-element.el 216 KB

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