org-element.el 216 KB

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