org-element.el 216 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081
  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 affiliated)
  1629. "Parse a comment.
  1630. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1631. the buffer position at the beginning of the first affiliated
  1632. keyword and CDR is a plist of affiliated keywords along with
  1633. their value.
  1634. Return a list whose CAR is `comment' and CDR is a plist
  1635. containing `:begin', `:end', `:value', `:post-blank',
  1636. `:post-affiliated' keywords.
  1637. Assume point is at comment beginning."
  1638. (save-excursion
  1639. (let* ((begin (car affiliated))
  1640. (post-affiliated (point))
  1641. (value (prog2 (looking-at "[ \t]*# ?")
  1642. (buffer-substring-no-properties
  1643. (match-end 0) (line-end-position))
  1644. (forward-line)))
  1645. (com-end
  1646. ;; Get comments ending.
  1647. (progn
  1648. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1649. ;; Accumulate lines without leading hash and first
  1650. ;; whitespace.
  1651. (setq value
  1652. (concat value
  1653. "\n"
  1654. (buffer-substring-no-properties
  1655. (match-end 0) (line-end-position))))
  1656. (forward-line))
  1657. (point)))
  1658. (end (progn (goto-char com-end)
  1659. (skip-chars-forward " \r\t\n" limit)
  1660. (if (eobp) (point) (line-beginning-position)))))
  1661. (list 'comment
  1662. (nconc
  1663. (list :begin begin
  1664. :end end
  1665. :value value
  1666. :post-blank (count-lines com-end end)
  1667. :post-affiliated post-affiliated)
  1668. (cdr affiliated))))))
  1669. (defun org-element-comment-interpreter (comment _)
  1670. "Interpret COMMENT element as Org syntax.
  1671. CONTENTS is nil."
  1672. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1673. ;;;; Comment Block
  1674. (defun org-element-comment-block-parser (limit affiliated)
  1675. "Parse an export block.
  1676. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1677. the buffer position at the beginning of the first affiliated
  1678. keyword and CDR is a plist of affiliated keywords along with
  1679. their value.
  1680. Return a list whose CAR is `comment-block' and CDR is a plist
  1681. containing `:begin', `:end', `:value', `:post-blank' and
  1682. `:post-affiliated' keywords.
  1683. Assume point is at comment block beginning."
  1684. (let ((case-fold-search t))
  1685. (if (not (save-excursion
  1686. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1687. ;; Incomplete block: parse it as a paragraph.
  1688. (org-element-paragraph-parser limit affiliated)
  1689. (let ((contents-end (match-beginning 0)))
  1690. (save-excursion
  1691. (let* ((begin (car affiliated))
  1692. (post-affiliated (point))
  1693. (contents-begin (progn (forward-line) (point)))
  1694. (pos-before-blank (progn (goto-char contents-end)
  1695. (forward-line)
  1696. (point)))
  1697. (end (progn (skip-chars-forward " \r\t\n" limit)
  1698. (if (eobp) (point) (line-beginning-position))))
  1699. (value (buffer-substring-no-properties
  1700. contents-begin contents-end)))
  1701. (list 'comment-block
  1702. (nconc
  1703. (list :begin begin
  1704. :end end
  1705. :value value
  1706. :post-blank (count-lines pos-before-blank end)
  1707. :post-affiliated post-affiliated)
  1708. (cdr affiliated)))))))))
  1709. (defun org-element-comment-block-interpreter (comment-block _)
  1710. "Interpret COMMENT-BLOCK element as Org syntax."
  1711. (format "#+begin_comment\n%s#+end_comment"
  1712. (org-element-normalize-string
  1713. (org-remove-indentation
  1714. (org-element-property :value comment-block)))))
  1715. ;;;; Diary Sexp
  1716. (defun org-element-diary-sexp-parser (limit affiliated)
  1717. "Parse a diary sexp.
  1718. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1719. the buffer position at the beginning of the first affiliated
  1720. keyword and CDR is a plist of affiliated keywords along with
  1721. their value.
  1722. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1723. containing `:begin', `:end', `:value', `:post-blank' and
  1724. `:post-affiliated' keywords."
  1725. (save-excursion
  1726. (let ((begin (car affiliated))
  1727. (post-affiliated (point))
  1728. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1729. (match-string-no-properties 1)))
  1730. (pos-before-blank (progn (forward-line) (point)))
  1731. (end (progn (skip-chars-forward " \r\t\n" limit)
  1732. (if (eobp) (point) (line-beginning-position)))))
  1733. (list 'diary-sexp
  1734. (nconc
  1735. (list :value value
  1736. :begin begin
  1737. :end end
  1738. :post-blank (count-lines pos-before-blank end)
  1739. :post-affiliated post-affiliated)
  1740. (cdr affiliated))))))
  1741. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1742. "Interpret DIARY-SEXP as Org syntax."
  1743. (org-element-property :value diary-sexp))
  1744. ;;;; Example Block
  1745. (defun org-element-example-block-parser (limit affiliated)
  1746. "Parse an example block.
  1747. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1748. the buffer position at the beginning of the first affiliated
  1749. keyword and CDR is a plist of affiliated keywords along with
  1750. their value.
  1751. Return a list whose CAR is `example-block' and CDR is a plist
  1752. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1753. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1754. `:value', `:post-blank' and `:post-affiliated' keywords."
  1755. (let ((case-fold-search t))
  1756. (if (not (save-excursion
  1757. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1758. ;; Incomplete block: parse it as a paragraph.
  1759. (org-element-paragraph-parser limit affiliated)
  1760. (let ((contents-end (match-beginning 0)))
  1761. (save-excursion
  1762. (let* ((switches
  1763. (progn
  1764. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1765. (match-string-no-properties 1)))
  1766. ;; Switches analysis.
  1767. (number-lines
  1768. (and switches
  1769. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1770. switches)
  1771. (cons
  1772. (if (equal (match-string 1 switches) "-")
  1773. 'new
  1774. 'continued)
  1775. (if (not (match-end 2)) 0
  1776. ;; Subtract 1 to give number of lines before
  1777. ;; first line.
  1778. (1- (string-to-number (match-string 2 switches)))))))
  1779. (preserve-indent
  1780. (and switches (string-match "-i\\>" switches)))
  1781. ;; Should labels be retained in (or stripped from) example
  1782. ;; blocks?
  1783. (retain-labels
  1784. (or (not switches)
  1785. (not (string-match "-r\\>" switches))
  1786. (and number-lines (string-match "-k\\>" switches))))
  1787. ;; What should code-references use - labels or
  1788. ;; line-numbers?
  1789. (use-labels
  1790. (or (not switches)
  1791. (and retain-labels
  1792. (not (string-match "-k\\>" switches)))))
  1793. (label-fmt
  1794. (and switches
  1795. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1796. (match-string 1 switches)))
  1797. ;; Standard block parsing.
  1798. (begin (car affiliated))
  1799. (post-affiliated (point))
  1800. (contents-begin (line-beginning-position 2))
  1801. (value (org-unescape-code-in-string
  1802. (buffer-substring-no-properties
  1803. contents-begin contents-end)))
  1804. (pos-before-blank (progn (goto-char contents-end)
  1805. (forward-line)
  1806. (point)))
  1807. (end (progn (skip-chars-forward " \r\t\n" limit)
  1808. (if (eobp) (point) (line-beginning-position)))))
  1809. (list 'example-block
  1810. (nconc
  1811. (list :begin begin
  1812. :end end
  1813. :value value
  1814. :switches switches
  1815. :number-lines number-lines
  1816. :preserve-indent preserve-indent
  1817. :retain-labels retain-labels
  1818. :use-labels use-labels
  1819. :label-fmt label-fmt
  1820. :post-blank (count-lines pos-before-blank end)
  1821. :post-affiliated post-affiliated)
  1822. (cdr affiliated)))))))))
  1823. (defun org-element-example-block-interpreter (example-block _)
  1824. "Interpret EXAMPLE-BLOCK element as Org syntax."
  1825. (let ((switches (org-element-property :switches example-block))
  1826. (value
  1827. (let ((val (org-element-property :value example-block)))
  1828. (cond
  1829. ((or org-src-preserve-indentation
  1830. (org-element-property :preserve-indent example-block))
  1831. val)
  1832. ((= 0 org-edit-src-content-indentation)
  1833. (org-remove-indentation val))
  1834. (t
  1835. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  1836. (replace-regexp-in-string "^[ \t]*\\S-"
  1837. (concat ind "\\&")
  1838. (org-remove-indentation val))))))))
  1839. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  1840. (org-element-normalize-string (org-escape-code-in-string value))
  1841. "#+end_example")))
  1842. ;;;; Export Block
  1843. (defun org-element-export-block-parser (limit affiliated)
  1844. "Parse an export block.
  1845. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1846. the buffer position at the beginning of the first affiliated
  1847. keyword and CDR is a plist of affiliated keywords along with
  1848. their value.
  1849. Return a list whose CAR is `export-block' and CDR is a plist
  1850. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  1851. `:post-affiliated' keywords.
  1852. Assume point is at export-block beginning."
  1853. (let* ((case-fold-search t))
  1854. (if (not (save-excursion
  1855. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  1856. ;; Incomplete block: parse it as a paragraph.
  1857. (org-element-paragraph-parser limit affiliated)
  1858. (save-excursion
  1859. (let* ((contents-end (match-beginning 0))
  1860. (backend
  1861. (progn
  1862. (looking-at
  1863. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  1864. (match-string-no-properties 1)))
  1865. (begin (car affiliated))
  1866. (post-affiliated (point))
  1867. (contents-begin (progn (forward-line) (point)))
  1868. (pos-before-blank (progn (goto-char contents-end)
  1869. (forward-line)
  1870. (point)))
  1871. (end (progn (skip-chars-forward " \r\t\n" limit)
  1872. (if (eobp) (point) (line-beginning-position))))
  1873. (value (org-unescape-code-in-string
  1874. (buffer-substring-no-properties contents-begin
  1875. contents-end))))
  1876. (list 'export-block
  1877. (nconc
  1878. (list :type (and backend (upcase backend))
  1879. :begin begin
  1880. :end end
  1881. :value value
  1882. :post-blank (count-lines pos-before-blank end)
  1883. :post-affiliated post-affiliated)
  1884. (cdr affiliated))))))))
  1885. (defun org-element-export-block-interpreter (export-block _)
  1886. "Interpret EXPORT-BLOCK element as Org syntax."
  1887. (format "#+begin_export %s\n%s#+end_export"
  1888. (org-element-property :type export-block)
  1889. (org-element-property :value export-block)))
  1890. ;;;; Fixed-width
  1891. (defun org-element-fixed-width-parser (limit affiliated)
  1892. "Parse a fixed-width section.
  1893. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1894. the buffer position at the beginning of the first affiliated
  1895. keyword and CDR is a plist of affiliated keywords along with
  1896. their value.
  1897. Return a list whose CAR is `fixed-width' and CDR is a plist
  1898. containing `:begin', `:end', `:value', `:post-blank' and
  1899. `:post-affiliated' keywords.
  1900. Assume point is at the beginning of the fixed-width area."
  1901. (save-excursion
  1902. (let* ((begin (car affiliated))
  1903. (post-affiliated (point))
  1904. (end-area
  1905. (progn
  1906. (while (and (< (point) limit)
  1907. (looking-at "[ \t]*:\\( \\|$\\)"))
  1908. (forward-line))
  1909. (if (bolp) (line-end-position 0) (point))))
  1910. (end (progn (skip-chars-forward " \r\t\n" limit)
  1911. (if (eobp) (point) (line-beginning-position)))))
  1912. (list 'fixed-width
  1913. (nconc
  1914. (list :begin begin
  1915. :end end
  1916. :value (replace-regexp-in-string
  1917. "^[ \t]*: ?" ""
  1918. (buffer-substring-no-properties post-affiliated
  1919. end-area))
  1920. :post-blank (count-lines end-area end)
  1921. :post-affiliated post-affiliated)
  1922. (cdr affiliated))))))
  1923. (defun org-element-fixed-width-interpreter (fixed-width _)
  1924. "Interpret FIXED-WIDTH element as Org syntax."
  1925. (let ((value (org-element-property :value fixed-width)))
  1926. (and value (replace-regexp-in-string "^" ": " value))))
  1927. ;;;; Horizontal Rule
  1928. (defun org-element-horizontal-rule-parser (limit affiliated)
  1929. "Parse an horizontal rule.
  1930. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1931. the buffer position at the beginning of the first affiliated
  1932. keyword and CDR is a plist of affiliated keywords along with
  1933. their value.
  1934. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  1935. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  1936. keywords."
  1937. (save-excursion
  1938. (let ((begin (car affiliated))
  1939. (post-affiliated (point))
  1940. (post-hr (progn (forward-line) (point)))
  1941. (end (progn (skip-chars-forward " \r\t\n" limit)
  1942. (if (eobp) (point) (line-beginning-position)))))
  1943. (list 'horizontal-rule
  1944. (nconc
  1945. (list :begin begin
  1946. :end end
  1947. :post-blank (count-lines post-hr end)
  1948. :post-affiliated post-affiliated)
  1949. (cdr affiliated))))))
  1950. (defun org-element-horizontal-rule-interpreter (&rest _)
  1951. "Interpret HORIZONTAL-RULE element as Org syntax."
  1952. "-----")
  1953. ;;;; Keyword
  1954. (defun org-element-keyword-parser (limit affiliated)
  1955. "Parse a keyword at point.
  1956. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1957. the buffer position at the beginning of the first affiliated
  1958. keyword and CDR is a plist of affiliated keywords along with
  1959. their value.
  1960. Return a list whose CAR is `keyword' and CDR is a plist
  1961. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  1962. `:post-affiliated' keywords."
  1963. (save-excursion
  1964. ;; An orphaned affiliated keyword is considered as a regular
  1965. ;; keyword. In this case AFFILIATED is nil, so we take care of
  1966. ;; this corner case.
  1967. (let ((begin (or (car affiliated) (point)))
  1968. (post-affiliated (point))
  1969. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  1970. (upcase (match-string-no-properties 1))))
  1971. (value (org-trim (buffer-substring-no-properties
  1972. (match-end 0) (point-at-eol))))
  1973. (pos-before-blank (progn (forward-line) (point)))
  1974. (end (progn (skip-chars-forward " \r\t\n" limit)
  1975. (if (eobp) (point) (line-beginning-position)))))
  1976. (list 'keyword
  1977. (nconc
  1978. (list :key key
  1979. :value value
  1980. :begin begin
  1981. :end end
  1982. :post-blank (count-lines pos-before-blank end)
  1983. :post-affiliated post-affiliated)
  1984. (cdr affiliated))))))
  1985. (defun org-element-keyword-interpreter (keyword _)
  1986. "Interpret KEYWORD element as Org syntax."
  1987. (format "#+%s: %s"
  1988. (downcase (org-element-property :key keyword))
  1989. (org-element-property :value keyword)))
  1990. ;;;; Latex Environment
  1991. (defconst org-element--latex-begin-environment
  1992. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  1993. "Regexp matching the beginning of a LaTeX environment.
  1994. The environment is captured by the first group.
  1995. See also `org-element--latex-end-environment'.")
  1996. (defconst org-element--latex-end-environment
  1997. "\\\\end{%s}[ \t]*$"
  1998. "Format string matching the ending of a LaTeX environment.
  1999. See also `org-element--latex-begin-environment'.")
  2000. (defun org-element-latex-environment-parser (limit affiliated)
  2001. "Parse a LaTeX environment.
  2002. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2003. the buffer position at the beginning of the first affiliated
  2004. keyword and CDR is a plist of affiliated keywords along with
  2005. their value.
  2006. Return a list whose CAR is `latex-environment' and CDR is a plist
  2007. containing `:begin', `:end', `:value', `:post-blank' and
  2008. `:post-affiliated' keywords.
  2009. Assume point is at the beginning of the latex environment."
  2010. (save-excursion
  2011. (let ((case-fold-search t)
  2012. (code-begin (point)))
  2013. (looking-at org-element--latex-begin-environment)
  2014. (if (not (re-search-forward (format org-element--latex-end-environment
  2015. (regexp-quote (match-string 1)))
  2016. limit t))
  2017. ;; Incomplete latex environment: parse it as a paragraph.
  2018. (org-element-paragraph-parser limit affiliated)
  2019. (let* ((code-end (progn (forward-line) (point)))
  2020. (begin (car affiliated))
  2021. (value (buffer-substring-no-properties code-begin code-end))
  2022. (end (progn (skip-chars-forward " \r\t\n" limit)
  2023. (if (eobp) (point) (line-beginning-position)))))
  2024. (list 'latex-environment
  2025. (nconc
  2026. (list :begin begin
  2027. :end end
  2028. :value value
  2029. :post-blank (count-lines code-end end)
  2030. :post-affiliated code-begin)
  2031. (cdr affiliated))))))))
  2032. (defun org-element-latex-environment-interpreter (latex-environment _)
  2033. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2034. (org-element-property :value latex-environment))
  2035. ;;;; Node Property
  2036. (defun org-element-node-property-parser (limit)
  2037. "Parse a node-property at point.
  2038. LIMIT bounds the search.
  2039. Return a list whose CAR is `node-property' and CDR is a plist
  2040. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2041. `:post-affiliated' keywords."
  2042. (looking-at org-property-re)
  2043. (let ((case-fold-search t)
  2044. (begin (point))
  2045. (key (match-string-no-properties 2))
  2046. (value (match-string-no-properties 3))
  2047. (end (save-excursion
  2048. (end-of-line)
  2049. (if (re-search-forward org-property-re limit t)
  2050. (line-beginning-position)
  2051. limit))))
  2052. (list 'node-property
  2053. (list :key key
  2054. :value value
  2055. :begin begin
  2056. :end end
  2057. :post-blank 0
  2058. :post-affiliated begin))))
  2059. (defun org-element-node-property-interpreter (node-property _)
  2060. "Interpret NODE-PROPERTY element as Org syntax."
  2061. (format org-property-format
  2062. (format ":%s:" (org-element-property :key node-property))
  2063. (or (org-element-property :value node-property) "")))
  2064. ;;;; Paragraph
  2065. (defun org-element-paragraph-parser (limit affiliated)
  2066. "Parse a paragraph.
  2067. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2068. the buffer position at the beginning of the first affiliated
  2069. keyword and CDR is a plist of affiliated keywords along with
  2070. their value.
  2071. Return a list whose CAR is `paragraph' and CDR is a plist
  2072. containing `:begin', `:end', `:contents-begin' and
  2073. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2074. Assume point is at the beginning of the paragraph."
  2075. (save-excursion
  2076. (let* ((begin (car affiliated))
  2077. (contents-begin (point))
  2078. (before-blank
  2079. (let ((case-fold-search t))
  2080. (end-of-line)
  2081. ;; A matching `org-element-paragraph-separate' is not
  2082. ;; necessarily the end of the paragraph. In particular,
  2083. ;; drawers, blocks or LaTeX environments opening lines
  2084. ;; must be closed. Moreover keywords with a secondary
  2085. ;; value must belong to "dual keywords".
  2086. (while (not
  2087. (cond
  2088. ((not (and (re-search-forward
  2089. org-element-paragraph-separate limit 'move)
  2090. (progn (beginning-of-line) t))))
  2091. ((looking-at org-drawer-regexp)
  2092. (save-excursion
  2093. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2094. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2095. (save-excursion
  2096. (re-search-forward
  2097. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2098. (regexp-quote (match-string 1)))
  2099. limit t)))
  2100. ((looking-at org-element--latex-begin-environment)
  2101. (save-excursion
  2102. (re-search-forward
  2103. (format org-element--latex-end-environment
  2104. (regexp-quote (match-string 1)))
  2105. limit t)))
  2106. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2107. (member-ignore-case (match-string 1)
  2108. org-element-dual-keywords))
  2109. ;; Everything else is unambiguous.
  2110. (t)))
  2111. (end-of-line))
  2112. (if (= (point) limit) limit
  2113. (goto-char (line-beginning-position)))))
  2114. (contents-end (save-excursion
  2115. (skip-chars-backward " \r\t\n" contents-begin)
  2116. (line-beginning-position 2)))
  2117. (end (progn (skip-chars-forward " \r\t\n" limit)
  2118. (if (eobp) (point) (line-beginning-position)))))
  2119. (list 'paragraph
  2120. (nconc
  2121. (list :begin begin
  2122. :end end
  2123. :contents-begin contents-begin
  2124. :contents-end contents-end
  2125. :post-blank (count-lines before-blank end)
  2126. :post-affiliated contents-begin)
  2127. (cdr affiliated))))))
  2128. (defun org-element-paragraph-interpreter (_ contents)
  2129. "Interpret paragraph element as Org syntax.
  2130. CONTENTS is the contents of the element."
  2131. contents)
  2132. ;;;; Planning
  2133. (defun org-element-planning-parser (limit)
  2134. "Parse a planning.
  2135. LIMIT bounds the search.
  2136. Return a list whose CAR is `planning' and CDR is a plist
  2137. containing `:closed', `:deadline', `:scheduled', `:begin',
  2138. `:end', `:post-blank' and `:post-affiliated' keywords."
  2139. (save-excursion
  2140. (let* ((case-fold-search nil)
  2141. (begin (point))
  2142. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2143. (skip-chars-forward " \r\t\n" limit)
  2144. (skip-chars-backward " \t")
  2145. (unless (bolp) (end-of-line))
  2146. (count-lines before-blank (point))))
  2147. (end (point))
  2148. closed deadline scheduled)
  2149. (goto-char begin)
  2150. (while (re-search-forward org-keyword-time-not-clock-regexp end t)
  2151. (goto-char (match-end 1))
  2152. (skip-chars-forward " \t" end)
  2153. (let ((keyword (match-string 1))
  2154. (time (org-element-timestamp-parser)))
  2155. (cond ((equal keyword org-closed-string) (setq closed time))
  2156. ((equal keyword org-deadline-string) (setq deadline time))
  2157. (t (setq scheduled time)))))
  2158. (list 'planning
  2159. (list :closed closed
  2160. :deadline deadline
  2161. :scheduled scheduled
  2162. :begin begin
  2163. :end end
  2164. :post-blank post-blank
  2165. :post-affiliated begin)))))
  2166. (defun org-element-planning-interpreter (planning _)
  2167. "Interpret PLANNING element as Org syntax."
  2168. (mapconcat
  2169. #'identity
  2170. (delq nil
  2171. (list (let ((deadline (org-element-property :deadline planning)))
  2172. (when deadline
  2173. (concat org-deadline-string " "
  2174. (org-element-timestamp-interpreter deadline nil))))
  2175. (let ((scheduled (org-element-property :scheduled planning)))
  2176. (when scheduled
  2177. (concat org-scheduled-string " "
  2178. (org-element-timestamp-interpreter scheduled nil))))
  2179. (let ((closed (org-element-property :closed planning)))
  2180. (when closed
  2181. (concat org-closed-string " "
  2182. (org-element-timestamp-interpreter closed nil))))))
  2183. " "))
  2184. ;;;; Src Block
  2185. (defun org-element-src-block-parser (limit affiliated)
  2186. "Parse a source block.
  2187. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2188. the buffer position at the beginning of the first affiliated
  2189. keyword and CDR is a plist of affiliated keywords along with
  2190. their value.
  2191. Return a list whose CAR is `src-block' and CDR is a plist
  2192. containing `:language', `:switches', `:parameters', `:begin',
  2193. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2194. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2195. `:post-affiliated' keywords.
  2196. Assume point is at the beginning of the block."
  2197. (let ((case-fold-search t))
  2198. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2199. limit t)))
  2200. ;; Incomplete block: parse it as a paragraph.
  2201. (org-element-paragraph-parser limit affiliated)
  2202. (let ((contents-end (match-beginning 0)))
  2203. (save-excursion
  2204. (let* ((begin (car affiliated))
  2205. (post-affiliated (point))
  2206. ;; Get language as a string.
  2207. (language
  2208. (progn
  2209. (looking-at
  2210. "^[ \t]*#\\+BEGIN_SRC\
  2211. \\(?: +\\(\\S-+\\)\\)?\
  2212. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2213. \\(.*\\)[ \t]*$")
  2214. (match-string-no-properties 1)))
  2215. ;; Get switches.
  2216. (switches (match-string-no-properties 2))
  2217. ;; Get parameters.
  2218. (parameters (match-string-no-properties 3))
  2219. ;; Switches analysis.
  2220. (number-lines
  2221. (and switches
  2222. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2223. switches)
  2224. (cons
  2225. (if (equal (match-string 1 switches) "-")
  2226. 'new
  2227. 'continued)
  2228. (if (not (match-end 2)) 0
  2229. ;; Subtract 1 to give number of lines before
  2230. ;; first line.
  2231. (1- (string-to-number (match-string 2 switches)))))))
  2232. (preserve-indent (and switches
  2233. (string-match "-i\\>" switches)))
  2234. (label-fmt
  2235. (and switches
  2236. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2237. (match-string 1 switches)))
  2238. ;; Should labels be retained in (or stripped from)
  2239. ;; source blocks?
  2240. (retain-labels
  2241. (or (not switches)
  2242. (not (string-match "-r\\>" switches))
  2243. (and number-lines (string-match "-k\\>" switches))))
  2244. ;; What should code-references use - labels or
  2245. ;; line-numbers?
  2246. (use-labels
  2247. (or (not switches)
  2248. (and retain-labels
  2249. (not (string-match "-k\\>" switches)))))
  2250. ;; Retrieve code.
  2251. (value (org-unescape-code-in-string
  2252. (buffer-substring-no-properties
  2253. (line-beginning-position 2) contents-end)))
  2254. (pos-before-blank (progn (goto-char contents-end)
  2255. (forward-line)
  2256. (point)))
  2257. ;; Get position after ending blank lines.
  2258. (end (progn (skip-chars-forward " \r\t\n" limit)
  2259. (if (eobp) (point) (line-beginning-position)))))
  2260. (list 'src-block
  2261. (nconc
  2262. (list :language language
  2263. :switches (and (org-string-nw-p switches)
  2264. (org-trim switches))
  2265. :parameters (and (org-string-nw-p parameters)
  2266. (org-trim parameters))
  2267. :begin begin
  2268. :end end
  2269. :number-lines number-lines
  2270. :preserve-indent preserve-indent
  2271. :retain-labels retain-labels
  2272. :use-labels use-labels
  2273. :label-fmt label-fmt
  2274. :value value
  2275. :post-blank (count-lines pos-before-blank end)
  2276. :post-affiliated post-affiliated)
  2277. (cdr affiliated)))))))))
  2278. (defun org-element-src-block-interpreter (src-block _)
  2279. "Interpret SRC-BLOCK element as Org syntax."
  2280. (let ((lang (org-element-property :language src-block))
  2281. (switches (org-element-property :switches src-block))
  2282. (params (org-element-property :parameters src-block))
  2283. (value
  2284. (let ((val (org-element-property :value src-block)))
  2285. (cond
  2286. ((or org-src-preserve-indentation
  2287. (org-element-property :preserve-indent src-block))
  2288. val)
  2289. ((zerop org-edit-src-content-indentation)
  2290. (org-remove-indentation val))
  2291. (t
  2292. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2293. (replace-regexp-in-string "^[ \t]*\\S-"
  2294. (concat ind "\\&")
  2295. (org-remove-indentation val))))))))
  2296. (format "#+begin_src%s\n%s#+end_src"
  2297. (concat (and lang (concat " " lang))
  2298. (and switches (concat " " switches))
  2299. (and params (concat " " params)))
  2300. (org-element-normalize-string (org-escape-code-in-string value)))))
  2301. ;;;; Table
  2302. (defun org-element-table-parser (limit affiliated)
  2303. "Parse a table at point.
  2304. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2305. the buffer position at the beginning of the first affiliated
  2306. keyword and CDR is a plist of affiliated keywords along with
  2307. their value.
  2308. Return a list whose CAR is `table' and CDR is a plist containing
  2309. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2310. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2311. keywords.
  2312. Assume point is at the beginning of the table."
  2313. (save-excursion
  2314. (let* ((case-fold-search t)
  2315. (table-begin (point))
  2316. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2317. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2318. (if (eq type 'org) "" "+")))
  2319. (begin (car affiliated))
  2320. (table-end
  2321. (if (re-search-forward end-re limit 'move)
  2322. (goto-char (match-beginning 0))
  2323. (point)))
  2324. (tblfm (let (acc)
  2325. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2326. (push (match-string-no-properties 1) acc)
  2327. (forward-line))
  2328. acc))
  2329. (pos-before-blank (point))
  2330. (end (progn (skip-chars-forward " \r\t\n" limit)
  2331. (if (eobp) (point) (line-beginning-position)))))
  2332. (list 'table
  2333. (nconc
  2334. (list :begin begin
  2335. :end end
  2336. :type type
  2337. :tblfm tblfm
  2338. ;; Only `org' tables have contents. `table.el' tables
  2339. ;; use a `:value' property to store raw table as
  2340. ;; a string.
  2341. :contents-begin (and (eq type 'org) table-begin)
  2342. :contents-end (and (eq type 'org) table-end)
  2343. :value (and (eq type 'table.el)
  2344. (buffer-substring-no-properties
  2345. table-begin table-end))
  2346. :post-blank (count-lines pos-before-blank end)
  2347. :post-affiliated table-begin)
  2348. (cdr affiliated))))))
  2349. (defun org-element-table-interpreter (table contents)
  2350. "Interpret TABLE element as Org syntax.
  2351. CONTENTS is a string, if table's type is `org', or nil."
  2352. (if (eq (org-element-property :type table) 'table.el)
  2353. (org-remove-indentation (org-element-property :value table))
  2354. (concat (with-temp-buffer (insert contents)
  2355. (org-table-align)
  2356. (buffer-string))
  2357. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2358. (reverse (org-element-property :tblfm table))
  2359. "\n"))))
  2360. ;;;; Table Row
  2361. (defun org-element-table-row-parser (_)
  2362. "Parse table row at point.
  2363. Return a list whose CAR is `table-row' and CDR is a plist
  2364. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2365. `:type', `:post-blank' and `:post-affiliated' keywords."
  2366. (save-excursion
  2367. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2368. (begin (point))
  2369. ;; A table rule has no contents. In that case, ensure
  2370. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2371. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2372. (contents-end (and (eq type 'standard)
  2373. (progn
  2374. (end-of-line)
  2375. (skip-chars-backward " \t")
  2376. (point))))
  2377. (end (line-beginning-position 2)))
  2378. (list 'table-row
  2379. (list :type type
  2380. :begin begin
  2381. :end end
  2382. :contents-begin contents-begin
  2383. :contents-end contents-end
  2384. :post-blank 0
  2385. :post-affiliated begin)))))
  2386. (defun org-element-table-row-interpreter (table-row contents)
  2387. "Interpret TABLE-ROW element as Org syntax.
  2388. CONTENTS is the contents of the table row."
  2389. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2390. (concat "|" contents)))
  2391. ;;;; Verse Block
  2392. (defun org-element-verse-block-parser (limit affiliated)
  2393. "Parse a verse block.
  2394. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2395. the buffer position at the beginning of the first affiliated
  2396. keyword and CDR is a plist of affiliated keywords along with
  2397. their value.
  2398. Return a list whose CAR is `verse-block' and CDR is a plist
  2399. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2400. `:post-blank' and `:post-affiliated' keywords.
  2401. Assume point is at beginning of the block."
  2402. (let ((case-fold-search t))
  2403. (if (not (save-excursion
  2404. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2405. ;; Incomplete block: parse it as a paragraph.
  2406. (org-element-paragraph-parser limit affiliated)
  2407. (let ((contents-end (match-beginning 0)))
  2408. (save-excursion
  2409. (let* ((begin (car affiliated))
  2410. (post-affiliated (point))
  2411. (contents-begin (progn (forward-line) (point)))
  2412. (pos-before-blank (progn (goto-char contents-end)
  2413. (forward-line)
  2414. (point)))
  2415. (end (progn (skip-chars-forward " \r\t\n" limit)
  2416. (if (eobp) (point) (line-beginning-position)))))
  2417. (list 'verse-block
  2418. (nconc
  2419. (list :begin begin
  2420. :end end
  2421. :contents-begin contents-begin
  2422. :contents-end contents-end
  2423. :post-blank (count-lines pos-before-blank end)
  2424. :post-affiliated post-affiliated)
  2425. (cdr affiliated)))))))))
  2426. (defun org-element-verse-block-interpreter (_ contents)
  2427. "Interpret verse-block element as Org syntax.
  2428. CONTENTS is verse block contents."
  2429. (format "#+begin_verse\n%s#+end_verse" contents))
  2430. ;;; Objects
  2431. ;;
  2432. ;; Unlike to elements, raw text can be found between objects. Hence,
  2433. ;; `org-element--object-lex' is provided to find the next object in
  2434. ;; buffer.
  2435. ;;
  2436. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2437. ;; object types they can contain will be specified in
  2438. ;; `org-element-object-restrictions'.
  2439. ;;
  2440. ;; Creating a new type of object requires to alter
  2441. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2442. ;; new type in `org-element-all-objects', and possibly add
  2443. ;; restrictions in `org-element-object-restrictions'.
  2444. ;;;; Bold
  2445. (defun org-element-bold-parser ()
  2446. "Parse bold object at point, if any.
  2447. When at a bold object, return a list whose car is `bold' and cdr
  2448. is a plist with `:begin', `:end', `:contents-begin' and
  2449. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2450. nil.
  2451. Assume point is at the first star marker."
  2452. (save-excursion
  2453. (unless (bolp) (backward-char 1))
  2454. (when (looking-at org-emph-re)
  2455. (let ((begin (match-beginning 2))
  2456. (contents-begin (match-beginning 4))
  2457. (contents-end (match-end 4))
  2458. (post-blank (progn (goto-char (match-end 2))
  2459. (skip-chars-forward " \t")))
  2460. (end (point)))
  2461. (list 'bold
  2462. (list :begin begin
  2463. :end end
  2464. :contents-begin contents-begin
  2465. :contents-end contents-end
  2466. :post-blank post-blank))))))
  2467. (defun org-element-bold-interpreter (_ contents)
  2468. "Interpret bold object as Org syntax.
  2469. CONTENTS is the contents of the object."
  2470. (format "*%s*" contents))
  2471. ;;;; Code
  2472. (defun org-element-code-parser ()
  2473. "Parse code object at point, if any.
  2474. When at a code object, return a list whose car is `code' and cdr
  2475. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2476. keywords. Otherwise, return nil.
  2477. Assume point is at the first tilde marker."
  2478. (save-excursion
  2479. (unless (bolp) (backward-char 1))
  2480. (when (looking-at org-verbatim-re)
  2481. (let ((begin (match-beginning 2))
  2482. (value (match-string-no-properties 4))
  2483. (post-blank (progn (goto-char (match-end 2))
  2484. (skip-chars-forward " \t")))
  2485. (end (point)))
  2486. (list 'code
  2487. (list :value value
  2488. :begin begin
  2489. :end end
  2490. :post-blank post-blank))))))
  2491. (defun org-element-code-interpreter (code _)
  2492. "Interpret CODE object as Org syntax."
  2493. (format "~%s~" (org-element-property :value code)))
  2494. ;;;; Entity
  2495. (defun org-element-entity-parser ()
  2496. "Parse entity at point, if any.
  2497. When at an entity, return a list whose car is `entity' and cdr
  2498. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2499. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2500. `:post-blank' as keywords. Otherwise, return nil.
  2501. Assume point is at the beginning of the entity."
  2502. (catch 'no-object
  2503. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2504. (save-excursion
  2505. (let* ((value (or (org-entity-get (match-string 1))
  2506. (throw 'no-object nil)))
  2507. (begin (match-beginning 0))
  2508. (bracketsp (string= (match-string 2) "{}"))
  2509. (post-blank (progn (goto-char (match-end 1))
  2510. (when bracketsp (forward-char 2))
  2511. (skip-chars-forward " \t")))
  2512. (end (point)))
  2513. (list 'entity
  2514. (list :name (car value)
  2515. :latex (nth 1 value)
  2516. :latex-math-p (nth 2 value)
  2517. :html (nth 3 value)
  2518. :ascii (nth 4 value)
  2519. :latin1 (nth 5 value)
  2520. :utf-8 (nth 6 value)
  2521. :begin begin
  2522. :end end
  2523. :use-brackets-p bracketsp
  2524. :post-blank post-blank)))))))
  2525. (defun org-element-entity-interpreter (entity _)
  2526. "Interpret ENTITY object as Org syntax."
  2527. (concat "\\"
  2528. (org-element-property :name entity)
  2529. (when (org-element-property :use-brackets-p entity) "{}")))
  2530. ;;;; Export Snippet
  2531. (defun org-element-export-snippet-parser ()
  2532. "Parse export snippet at point.
  2533. When at an export snippet, return a list whose car is
  2534. `export-snippet' and cdr a plist with `:begin', `:end',
  2535. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2536. return nil.
  2537. Assume point is at the beginning of the snippet."
  2538. (save-excursion
  2539. (let (contents-end)
  2540. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2541. (setq contents-end
  2542. (save-match-data (goto-char (match-end 0))
  2543. (re-search-forward "@@" nil t)
  2544. (match-beginning 0))))
  2545. (let* ((begin (match-beginning 0))
  2546. (back-end (match-string-no-properties 1))
  2547. (value (buffer-substring-no-properties
  2548. (match-end 0) contents-end))
  2549. (post-blank (skip-chars-forward " \t"))
  2550. (end (point)))
  2551. (list 'export-snippet
  2552. (list :back-end back-end
  2553. :value value
  2554. :begin begin
  2555. :end end
  2556. :post-blank post-blank)))))))
  2557. (defun org-element-export-snippet-interpreter (export-snippet _)
  2558. "Interpret EXPORT-SNIPPET object as Org syntax."
  2559. (format "@@%s:%s@@"
  2560. (org-element-property :back-end export-snippet)
  2561. (org-element-property :value export-snippet)))
  2562. ;;;; Footnote Reference
  2563. (defun org-element-footnote-reference-parser ()
  2564. "Parse footnote reference at point, if any.
  2565. When at a footnote reference, return a list whose car is
  2566. `footnote-reference' and cdr a plist with `:label', `:type',
  2567. `:begin', `:end', `:contents-begin', `:contents-end' and
  2568. `:post-blank' as keywords. Otherwise, return nil."
  2569. (when (looking-at org-footnote-re)
  2570. (let ((closing (with-syntax-table org-element--pair-square-table
  2571. (ignore-errors (scan-lists (point) 1 0)))))
  2572. (when closing
  2573. (save-excursion
  2574. (let* ((begin (point))
  2575. (label (match-string-no-properties 1))
  2576. (inner-begin (match-end 0))
  2577. (inner-end (1- closing))
  2578. (type (if (match-end 2) 'inline 'standard))
  2579. (post-blank (progn (goto-char closing)
  2580. (skip-chars-forward " \t")))
  2581. (end (point)))
  2582. (list 'footnote-reference
  2583. (list :label label
  2584. :type type
  2585. :begin begin
  2586. :end end
  2587. :contents-begin (and (eq type 'inline) inner-begin)
  2588. :contents-end (and (eq type 'inline) inner-end)
  2589. :post-blank post-blank))))))))
  2590. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2591. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2592. CONTENTS is its definition, when inline, or nil."
  2593. (format "[fn:%s%s]"
  2594. (or (org-element-property :label footnote-reference) "")
  2595. (if contents (concat ":" contents) "")))
  2596. ;;;; Inline Babel Call
  2597. (defun org-element-inline-babel-call-parser ()
  2598. "Parse inline babel call at point, if any.
  2599. When at an inline babel call, return a list whose car is
  2600. `inline-babel-call' and cdr a plist with `:call',
  2601. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2602. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2603. Assume point is at the beginning of the babel call."
  2604. (save-excursion
  2605. (catch :no-object
  2606. (when (let ((case-fold-search nil))
  2607. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2608. (goto-char (match-end 1))
  2609. (let* ((begin (match-beginning 0))
  2610. (call (match-string-no-properties 1))
  2611. (inside-header
  2612. (let ((p (org-element--parse-paired-brackets ?\[)))
  2613. (and (org-string-nw-p p)
  2614. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2615. (arguments (org-string-nw-p
  2616. (or (org-element--parse-paired-brackets ?\()
  2617. ;; Parenthesis are mandatory.
  2618. (throw :no-object nil))))
  2619. (end-header
  2620. (let ((p (org-element--parse-paired-brackets ?\[)))
  2621. (and (org-string-nw-p p)
  2622. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2623. (value (buffer-substring-no-properties begin (point)))
  2624. (post-blank (skip-chars-forward " \t"))
  2625. (end (point)))
  2626. (list 'inline-babel-call
  2627. (list :call call
  2628. :inside-header inside-header
  2629. :arguments arguments
  2630. :end-header end-header
  2631. :begin begin
  2632. :end end
  2633. :value value
  2634. :post-blank post-blank)))))))
  2635. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2636. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2637. (concat "call_"
  2638. (org-element-property :call inline-babel-call)
  2639. (let ((h (org-element-property :inside-header inline-babel-call)))
  2640. (and h (format "[%s]" h)))
  2641. "(" (org-element-property :arguments inline-babel-call) ")"
  2642. (let ((h (org-element-property :end-header inline-babel-call)))
  2643. (and h (format "[%s]" h)))))
  2644. ;;;; Inline Src Block
  2645. (defun org-element-inline-src-block-parser ()
  2646. "Parse inline source block at point, if any.
  2647. When at an inline source block, return a list whose car is
  2648. `inline-src-block' and cdr a plist with `:begin', `:end',
  2649. `:language', `:value', `:parameters' and `:post-blank' as
  2650. keywords. Otherwise, return nil.
  2651. Assume point is at the beginning of the inline source block."
  2652. (save-excursion
  2653. (catch :no-object
  2654. (when (let ((case-fold-search nil))
  2655. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2656. (goto-char (match-end 1))
  2657. (let ((begin (match-beginning 0))
  2658. (language (match-string-no-properties 1))
  2659. (parameters
  2660. (let ((p (org-element--parse-paired-brackets ?\[)))
  2661. (and (org-string-nw-p p)
  2662. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2663. (value (or (org-element--parse-paired-brackets ?\{)
  2664. (throw :no-object nil)))
  2665. (post-blank (skip-chars-forward " \t")))
  2666. (list 'inline-src-block
  2667. (list :language language
  2668. :value value
  2669. :parameters parameters
  2670. :begin begin
  2671. :end (point)
  2672. :post-blank post-blank)))))))
  2673. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2674. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2675. (let ((language (org-element-property :language inline-src-block))
  2676. (arguments (org-element-property :parameters inline-src-block))
  2677. (body (org-element-property :value inline-src-block)))
  2678. (format "src_%s%s{%s}"
  2679. language
  2680. (if arguments (format "[%s]" arguments) "")
  2681. body)))
  2682. ;;;; Italic
  2683. (defun org-element-italic-parser ()
  2684. "Parse italic object at point, if any.
  2685. When at an italic object, return a list whose car is `italic' and
  2686. cdr is a plist with `:begin', `:end', `:contents-begin' and
  2687. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2688. nil.
  2689. Assume point is at the first slash marker."
  2690. (save-excursion
  2691. (unless (bolp) (backward-char 1))
  2692. (when (looking-at org-emph-re)
  2693. (let ((begin (match-beginning 2))
  2694. (contents-begin (match-beginning 4))
  2695. (contents-end (match-end 4))
  2696. (post-blank (progn (goto-char (match-end 2))
  2697. (skip-chars-forward " \t")))
  2698. (end (point)))
  2699. (list 'italic
  2700. (list :begin begin
  2701. :end end
  2702. :contents-begin contents-begin
  2703. :contents-end contents-end
  2704. :post-blank post-blank))))))
  2705. (defun org-element-italic-interpreter (_ contents)
  2706. "Interpret italic object as Org syntax.
  2707. CONTENTS is the contents of the object."
  2708. (format "/%s/" contents))
  2709. ;;;; Latex Fragment
  2710. (defun org-element-latex-fragment-parser ()
  2711. "Parse LaTeX fragment at point, if any.
  2712. When at a LaTeX fragment, return a list whose car is
  2713. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  2714. and `:post-blank' as keywords. Otherwise, return nil.
  2715. Assume point is at the beginning of the LaTeX fragment."
  2716. (catch 'no-object
  2717. (save-excursion
  2718. (let* ((begin (point))
  2719. (after-fragment
  2720. (cond
  2721. ((not (eq ?$ (char-after)))
  2722. (pcase (char-after (1+ (point)))
  2723. (?\( (search-forward "\\)" nil t))
  2724. (?\[ (search-forward "\\]" nil t))
  2725. (_
  2726. ;; Macro.
  2727. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  2728. \\|\\({[^{}\n]*}\\)\\)*")
  2729. (match-end 0)))))
  2730. ((eq ?$ (char-after (1+ (point))))
  2731. (search-forward "$$" nil t 2))
  2732. (t
  2733. (and (not (eq ?$ (char-before)))
  2734. (not (memq (char-after (1+ (point)))
  2735. '(?\s ?\t ?\n ?, ?. ?\;)))
  2736. (search-forward "$" nil t 2)
  2737. (not (memq (char-before (match-beginning 0))
  2738. '(?\s ?\t ?\n ?, ?.)))
  2739. (looking-at-p
  2740. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  2741. (point)))))
  2742. (post-blank
  2743. (if (not after-fragment) (throw 'no-object nil)
  2744. (goto-char after-fragment)
  2745. (skip-chars-forward " \t")))
  2746. (end (point)))
  2747. (list 'latex-fragment
  2748. (list :value (buffer-substring-no-properties begin after-fragment)
  2749. :begin begin
  2750. :end end
  2751. :post-blank post-blank))))))
  2752. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  2753. "Interpret LATEX-FRAGMENT object as Org syntax."
  2754. (org-element-property :value latex-fragment))
  2755. ;;;; Line Break
  2756. (defun org-element-line-break-parser ()
  2757. "Parse line break at point, if any.
  2758. When at a line break, return a list whose car is `line-break',
  2759. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  2760. Otherwise, return nil.
  2761. Assume point is at the beginning of the line break."
  2762. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  2763. (not (eq (char-before) ?\\)))
  2764. (list 'line-break
  2765. (list :begin (point)
  2766. :end (line-beginning-position 2)
  2767. :post-blank 0))))
  2768. (defun org-element-line-break-interpreter (&rest _)
  2769. "Interpret LINE-BREAK object as Org syntax."
  2770. "\\\\\n")
  2771. ;;;; Link
  2772. (defun org-element-link-parser ()
  2773. "Parse link at point, if any.
  2774. When at a link, return a list whose car is `link' and cdr a plist
  2775. with `:type', `:path', `:format', `:raw-link', `:application',
  2776. `:search-option', `:begin', `:end', `:contents-begin',
  2777. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  2778. nil.
  2779. Assume point is at the beginning of the link."
  2780. (catch 'no-object
  2781. (let ((begin (point))
  2782. end contents-begin contents-end link-end post-blank path type format
  2783. raw-link search-option application)
  2784. (cond
  2785. ;; Type 1: Text targeted from a radio target.
  2786. ((and org-target-link-regexp
  2787. (save-excursion (or (bolp) (backward-char))
  2788. (looking-at org-target-link-regexp)))
  2789. (setq type "radio")
  2790. (setq format 'plain)
  2791. (setq link-end (match-end 1))
  2792. (setq path (match-string-no-properties 1))
  2793. (setq contents-begin (match-beginning 1))
  2794. (setq contents-end (match-end 1)))
  2795. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  2796. ((looking-at org-link-bracket-re)
  2797. (setq format 'bracket)
  2798. (setq contents-begin (match-beginning 2))
  2799. (setq contents-end (match-end 2))
  2800. (setq link-end (match-end 0))
  2801. ;; RAW-LINK is the original link. Decode any encoding.
  2802. ;; Expand any abbreviation in it.
  2803. ;;
  2804. ;; Also treat any newline character and associated
  2805. ;; indentation as a single space character. This is not
  2806. ;; compatible with RFC 3986, which requires to ignore
  2807. ;; them altogether. However, doing so would require
  2808. ;; users to encode spaces on the fly when writing links
  2809. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  2810. ;; [[shell:ls *.org]], which defeats Org's focus on
  2811. ;; simplicity.
  2812. (setq raw-link (org-link-expand-abbrev
  2813. (org-link-unescape
  2814. (replace-regexp-in-string
  2815. "[ \t]*\n[ \t]*" " "
  2816. (match-string-no-properties 1)))))
  2817. ;; Determine TYPE of link and set PATH accordingly. According
  2818. ;; to RFC 3986, remove whitespaces from URI in external links.
  2819. ;; In internal ones, treat indentation as a single space.
  2820. (cond
  2821. ;; File type.
  2822. ((or (file-name-absolute-p raw-link)
  2823. (string-match "\\`\\.\\.?/" raw-link))
  2824. (setq type "file")
  2825. (setq path raw-link))
  2826. ;; Explicit type (http, irc, bbdb...).
  2827. ((string-match org-link-types-re raw-link)
  2828. (setq type (match-string 1 raw-link))
  2829. (setq path (substring raw-link (match-end 0))))
  2830. ;; Code-ref type: PATH is the name of the reference.
  2831. ((and (string-match-p "\\`(" raw-link)
  2832. (string-match-p ")\\'" raw-link))
  2833. (setq type "coderef")
  2834. (setq path (substring raw-link 1 -1)))
  2835. ;; Custom-id type: PATH is the name of the custom id.
  2836. ((= (string-to-char raw-link) ?#)
  2837. (setq type "custom-id")
  2838. (setq path (substring raw-link 1)))
  2839. ;; Fuzzy type: Internal link either matches a target, an
  2840. ;; headline name or nothing. PATH is the target or
  2841. ;; headline's name.
  2842. (t
  2843. (setq type "fuzzy")
  2844. (setq path raw-link))))
  2845. ;; Type 3: Plain link, e.g., https://orgmode.org
  2846. ((looking-at org-link-plain-re)
  2847. (setq format 'plain)
  2848. (setq raw-link (match-string-no-properties 0))
  2849. (setq type (match-string-no-properties 1))
  2850. (setq link-end (match-end 0))
  2851. (setq path (match-string-no-properties 2)))
  2852. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  2853. ;; bracket links, follow RFC 3986 and remove any extra
  2854. ;; whitespace in URI.
  2855. ((looking-at org-link-angle-re)
  2856. (setq format 'angle)
  2857. (setq type (match-string-no-properties 1))
  2858. (setq link-end (match-end 0))
  2859. (setq raw-link
  2860. (buffer-substring-no-properties
  2861. (match-beginning 1) (match-end 2)))
  2862. (setq path (replace-regexp-in-string
  2863. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  2864. (t (throw 'no-object nil)))
  2865. ;; In any case, deduce end point after trailing white space from
  2866. ;; LINK-END variable.
  2867. (save-excursion
  2868. (setq post-blank
  2869. (progn (goto-char link-end) (skip-chars-forward " \t")))
  2870. (setq end (point)))
  2871. ;; Special "file" type link processing. Extract opening
  2872. ;; application and search option, if any. Also normalize URI.
  2873. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  2874. (setq application (match-string 1 type) type "file")
  2875. (when (string-match "::\\(.*\\)\\'" path)
  2876. (setq search-option (match-string 1 path))
  2877. (setq path (replace-match "" nil nil path)))
  2878. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  2879. ;; Translate link, if `org-link-translation-function' is set.
  2880. (let ((trans (and (functionp org-link-translation-function)
  2881. (funcall org-link-translation-function type path))))
  2882. (when trans
  2883. (setq type (car trans))
  2884. (setq path (cdr trans))))
  2885. (list 'link
  2886. (list :type type
  2887. :path path
  2888. :format format
  2889. :raw-link (or raw-link path)
  2890. :application application
  2891. :search-option search-option
  2892. :begin begin
  2893. :end end
  2894. :contents-begin contents-begin
  2895. :contents-end contents-end
  2896. :post-blank post-blank)))))
  2897. (defun org-element-link-interpreter (link contents)
  2898. "Interpret LINK object as Org syntax.
  2899. CONTENTS is the contents of the object, or nil."
  2900. (let ((type (org-element-property :type link))
  2901. (path (org-element-property :path link)))
  2902. (if (string= type "radio") path
  2903. (let ((fmt (pcase (org-element-property :format link)
  2904. ;; Links with contents and internal links have to
  2905. ;; use bracket syntax. Ignore `:format' in these
  2906. ;; cases. This is also the default syntax when the
  2907. ;; property is not defined, e.g., when the object
  2908. ;; was crafted by the user.
  2909. ((guard contents)
  2910. (format "[[%%s][%s]]"
  2911. ;; Since this is going to be used as
  2912. ;; a format string, escape percent signs
  2913. ;; in description.
  2914. (replace-regexp-in-string "%" "%%" contents)))
  2915. ((or `bracket
  2916. `nil
  2917. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  2918. "[[%s]]")
  2919. ;; Otherwise, just obey to `:format'.
  2920. (`angle "<%s>")
  2921. (`plain "%s")
  2922. (f (error "Wrong `:format' value: %s" f)))))
  2923. (format fmt
  2924. (pcase type
  2925. ("coderef" (format "(%s)" path))
  2926. ("custom-id" (concat "#" path))
  2927. ("file"
  2928. (let ((app (org-element-property :application link))
  2929. (opt (org-element-property :search-option link)))
  2930. (concat type (and app (concat "+" app)) ":"
  2931. path
  2932. (and opt (concat "::" opt)))))
  2933. ("fuzzy" path)
  2934. (_ (concat type ":" path))))))))
  2935. ;;;; Macro
  2936. (defun org-element-macro-parser ()
  2937. "Parse macro at point, if any.
  2938. When at a macro, return a list whose car is `macro' and cdr
  2939. a plist with `:key', `:args', `:begin', `:end', `:value' and
  2940. `:post-blank' as keywords. Otherwise, return nil.
  2941. Assume point is at the macro."
  2942. (save-excursion
  2943. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  2944. (let ((begin (point))
  2945. (key (downcase (match-string-no-properties 1)))
  2946. (value (match-string-no-properties 0))
  2947. (post-blank (progn (goto-char (match-end 0))
  2948. (skip-chars-forward " \t")))
  2949. (end (point))
  2950. (args (pcase (match-string-no-properties 3)
  2951. (`nil nil)
  2952. (a (org-macro-extract-arguments
  2953. (replace-regexp-in-string
  2954. "[ \t\r\n]+" " " (org-trim a)))))))
  2955. (list 'macro
  2956. (list :key key
  2957. :value value
  2958. :args args
  2959. :begin begin
  2960. :end end
  2961. :post-blank post-blank))))))
  2962. (defun org-element-macro-interpreter (macro _)
  2963. "Interpret MACRO object as Org syntax."
  2964. (format "{{{%s%s}}}"
  2965. (org-element-property :key macro)
  2966. (pcase (org-element-property :args macro)
  2967. (`nil "")
  2968. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  2969. ;;;; Radio-target
  2970. (defun org-element-radio-target-parser ()
  2971. "Parse radio target at point, if any.
  2972. When at a radio target, return a list whose car is `radio-target'
  2973. and cdr a plist with `:begin', `:end', `:contents-begin',
  2974. `:contents-end', `:value' and `:post-blank' as keywords.
  2975. Otherwise, return nil.
  2976. Assume point is at the radio target."
  2977. (save-excursion
  2978. (when (looking-at org-radio-target-regexp)
  2979. (let ((begin (point))
  2980. (contents-begin (match-beginning 1))
  2981. (contents-end (match-end 1))
  2982. (value (match-string-no-properties 1))
  2983. (post-blank (progn (goto-char (match-end 0))
  2984. (skip-chars-forward " \t")))
  2985. (end (point)))
  2986. (list 'radio-target
  2987. (list :begin begin
  2988. :end end
  2989. :contents-begin contents-begin
  2990. :contents-end contents-end
  2991. :post-blank post-blank
  2992. :value value))))))
  2993. (defun org-element-radio-target-interpreter (_ contents)
  2994. "Interpret target object as Org syntax.
  2995. CONTENTS is the contents of the object."
  2996. (concat "<<<" contents ">>>"))
  2997. ;;;; Statistics Cookie
  2998. (defun org-element-statistics-cookie-parser ()
  2999. "Parse statistics cookie at point, if any.
  3000. When at a statistics cookie, return a list whose car is
  3001. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3002. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3003. Assume point is at the beginning of the statistics-cookie."
  3004. (save-excursion
  3005. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3006. (let* ((begin (point))
  3007. (value (buffer-substring-no-properties
  3008. (match-beginning 0) (match-end 0)))
  3009. (post-blank (progn (goto-char (match-end 0))
  3010. (skip-chars-forward " \t")))
  3011. (end (point)))
  3012. (list 'statistics-cookie
  3013. (list :begin begin
  3014. :end end
  3015. :value value
  3016. :post-blank post-blank))))))
  3017. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3018. "Interpret STATISTICS-COOKIE object as Org syntax."
  3019. (org-element-property :value statistics-cookie))
  3020. ;;;; Strike-Through
  3021. (defun org-element-strike-through-parser ()
  3022. "Parse strike-through object at point, if any.
  3023. When at a strike-through object, return a list whose car is
  3024. `strike-through' and cdr is a plist with `:begin', `:end',
  3025. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3026. Otherwise, return nil.
  3027. Assume point is at the first plus sign marker."
  3028. (save-excursion
  3029. (unless (bolp) (backward-char 1))
  3030. (when (looking-at org-emph-re)
  3031. (let ((begin (match-beginning 2))
  3032. (contents-begin (match-beginning 4))
  3033. (contents-end (match-end 4))
  3034. (post-blank (progn (goto-char (match-end 2))
  3035. (skip-chars-forward " \t")))
  3036. (end (point)))
  3037. (list 'strike-through
  3038. (list :begin begin
  3039. :end end
  3040. :contents-begin contents-begin
  3041. :contents-end contents-end
  3042. :post-blank post-blank))))))
  3043. (defun org-element-strike-through-interpreter (_ contents)
  3044. "Interpret strike-through object as Org syntax.
  3045. CONTENTS is the contents of the object."
  3046. (format "+%s+" contents))
  3047. ;;;; Subscript
  3048. (defun org-element-subscript-parser ()
  3049. "Parse subscript at point, if any.
  3050. When at a subscript object, return a list whose car is
  3051. `subscript' and cdr a plist with `:begin', `:end',
  3052. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3053. `:post-blank' as keywords. Otherwise, return nil.
  3054. Assume point is at the underscore."
  3055. (save-excursion
  3056. (unless (bolp) (backward-char))
  3057. (when (looking-at org-match-substring-regexp)
  3058. (let ((bracketsp (match-beginning 4))
  3059. (begin (match-beginning 2))
  3060. (contents-begin (or (match-beginning 4)
  3061. (match-beginning 3)))
  3062. (contents-end (or (match-end 4) (match-end 3)))
  3063. (post-blank (progn (goto-char (match-end 0))
  3064. (skip-chars-forward " \t")))
  3065. (end (point)))
  3066. (list 'subscript
  3067. (list :begin begin
  3068. :end end
  3069. :use-brackets-p bracketsp
  3070. :contents-begin contents-begin
  3071. :contents-end contents-end
  3072. :post-blank post-blank))))))
  3073. (defun org-element-subscript-interpreter (subscript contents)
  3074. "Interpret SUBSCRIPT object as Org syntax.
  3075. CONTENTS is the contents of the object."
  3076. (format
  3077. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3078. contents))
  3079. ;;;; Superscript
  3080. (defun org-element-superscript-parser ()
  3081. "Parse superscript at point, if any.
  3082. When at a superscript object, return a list whose car is
  3083. `superscript' and cdr a plist with `:begin', `:end',
  3084. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3085. `:post-blank' as keywords. Otherwise, return nil.
  3086. Assume point is at the caret."
  3087. (save-excursion
  3088. (unless (bolp) (backward-char))
  3089. (when (looking-at org-match-substring-regexp)
  3090. (let ((bracketsp (match-beginning 4))
  3091. (begin (match-beginning 2))
  3092. (contents-begin (or (match-beginning 4)
  3093. (match-beginning 3)))
  3094. (contents-end (or (match-end 4) (match-end 3)))
  3095. (post-blank (progn (goto-char (match-end 0))
  3096. (skip-chars-forward " \t")))
  3097. (end (point)))
  3098. (list 'superscript
  3099. (list :begin begin
  3100. :end end
  3101. :use-brackets-p bracketsp
  3102. :contents-begin contents-begin
  3103. :contents-end contents-end
  3104. :post-blank post-blank))))))
  3105. (defun org-element-superscript-interpreter (superscript contents)
  3106. "Interpret SUPERSCRIPT object as Org syntax.
  3107. CONTENTS is the contents of the object."
  3108. (format
  3109. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3110. contents))
  3111. ;;;; Table Cell
  3112. (defun org-element-table-cell-parser ()
  3113. "Parse table cell at point.
  3114. Return a list whose car is `table-cell' and cdr is a plist
  3115. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3116. and `:post-blank' keywords."
  3117. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3118. (let* ((begin (match-beginning 0))
  3119. (end (match-end 0))
  3120. (contents-begin (match-beginning 1))
  3121. (contents-end (match-end 1)))
  3122. (list 'table-cell
  3123. (list :begin begin
  3124. :end end
  3125. :contents-begin contents-begin
  3126. :contents-end contents-end
  3127. :post-blank 0))))
  3128. (defun org-element-table-cell-interpreter (_ contents)
  3129. "Interpret table-cell element as Org syntax.
  3130. CONTENTS is the contents of the cell, or nil."
  3131. (concat " " contents " |"))
  3132. ;;;; Target
  3133. (defun org-element-target-parser ()
  3134. "Parse target at point, if any.
  3135. When at a target, return a list whose car is `target' and cdr
  3136. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3137. keywords. Otherwise, return nil.
  3138. Assume point is at the target."
  3139. (save-excursion
  3140. (when (looking-at org-target-regexp)
  3141. (let ((begin (point))
  3142. (value (match-string-no-properties 1))
  3143. (post-blank (progn (goto-char (match-end 0))
  3144. (skip-chars-forward " \t")))
  3145. (end (point)))
  3146. (list 'target
  3147. (list :begin begin
  3148. :end end
  3149. :value value
  3150. :post-blank post-blank))))))
  3151. (defun org-element-target-interpreter (target _)
  3152. "Interpret TARGET object as Org syntax."
  3153. (format "<<%s>>" (org-element-property :value target)))
  3154. ;;;; Timestamp
  3155. (defconst org-element--timestamp-regexp
  3156. (concat org-ts-regexp-both
  3157. "\\|"
  3158. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3159. "\\|"
  3160. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3161. "Regexp matching any timestamp type object.")
  3162. (defun org-element-timestamp-parser ()
  3163. "Parse time stamp at point, if any.
  3164. When at a time stamp, return a list whose car is `timestamp', and
  3165. cdr a plist with `:type', `:raw-value', `:year-start',
  3166. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3167. `:year-end', `:month-end', `:day-end', `:hour-end',
  3168. `:minute-end', `:repeater-type', `:repeater-value',
  3169. `:repeater-unit', `:warning-type', `:warning-value',
  3170. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3171. Otherwise, return nil.
  3172. Assume point is at the beginning of the timestamp."
  3173. (when (looking-at-p org-element--timestamp-regexp)
  3174. (save-excursion
  3175. (let* ((begin (point))
  3176. (activep (eq (char-after) ?<))
  3177. (raw-value
  3178. (progn
  3179. (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
  3180. (match-string-no-properties 0)))
  3181. (date-start (match-string-no-properties 1))
  3182. (date-end (match-string 3))
  3183. (diaryp (match-beginning 2))
  3184. (post-blank (progn (goto-char (match-end 0))
  3185. (skip-chars-forward " \t")))
  3186. (end (point))
  3187. (time-range
  3188. (and (not diaryp)
  3189. (string-match
  3190. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3191. date-start)
  3192. (cons (string-to-number (match-string 2 date-start))
  3193. (string-to-number (match-string 3 date-start)))))
  3194. (type (cond (diaryp 'diary)
  3195. ((and activep (or date-end time-range)) 'active-range)
  3196. (activep 'active)
  3197. ((or date-end time-range) 'inactive-range)
  3198. (t 'inactive)))
  3199. (repeater-props
  3200. (and (not diaryp)
  3201. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3202. raw-value)
  3203. (list
  3204. :repeater-type
  3205. (let ((type (match-string 1 raw-value)))
  3206. (cond ((equal "++" type) 'catch-up)
  3207. ((equal ".+" type) 'restart)
  3208. (t 'cumulate)))
  3209. :repeater-value (string-to-number (match-string 2 raw-value))
  3210. :repeater-unit
  3211. (pcase (string-to-char (match-string 3 raw-value))
  3212. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3213. (warning-props
  3214. (and (not diaryp)
  3215. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3216. (list
  3217. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3218. :warning-value (string-to-number (match-string 2 raw-value))
  3219. :warning-unit
  3220. (pcase (string-to-char (match-string 3 raw-value))
  3221. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3222. year-start month-start day-start hour-start minute-start year-end
  3223. month-end day-end hour-end minute-end)
  3224. ;; Parse date-start.
  3225. (unless diaryp
  3226. (let ((date (org-parse-time-string date-start t)))
  3227. (setq year-start (nth 5 date)
  3228. month-start (nth 4 date)
  3229. day-start (nth 3 date)
  3230. hour-start (nth 2 date)
  3231. minute-start (nth 1 date))))
  3232. ;; Compute date-end. It can be provided directly in time-stamp,
  3233. ;; or extracted from time range. Otherwise, it defaults to the
  3234. ;; same values as date-start.
  3235. (unless diaryp
  3236. (let ((date (and date-end (org-parse-time-string date-end t))))
  3237. (setq year-end (or (nth 5 date) year-start)
  3238. month-end (or (nth 4 date) month-start)
  3239. day-end (or (nth 3 date) day-start)
  3240. hour-end (or (nth 2 date) (car time-range) hour-start)
  3241. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3242. (list 'timestamp
  3243. (nconc (list :type type
  3244. :raw-value raw-value
  3245. :year-start year-start
  3246. :month-start month-start
  3247. :day-start day-start
  3248. :hour-start hour-start
  3249. :minute-start minute-start
  3250. :year-end year-end
  3251. :month-end month-end
  3252. :day-end day-end
  3253. :hour-end hour-end
  3254. :minute-end minute-end
  3255. :begin begin
  3256. :end end
  3257. :post-blank post-blank)
  3258. repeater-props
  3259. warning-props))))))
  3260. (defun org-element-timestamp-interpreter (timestamp _)
  3261. "Interpret TIMESTAMP object as Org syntax."
  3262. (let* ((repeat-string
  3263. (concat
  3264. (pcase (org-element-property :repeater-type timestamp)
  3265. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3266. (let ((val (org-element-property :repeater-value timestamp)))
  3267. (and val (number-to-string val)))
  3268. (pcase (org-element-property :repeater-unit timestamp)
  3269. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3270. (warning-string
  3271. (concat
  3272. (pcase (org-element-property :warning-type timestamp)
  3273. (`first "--") (`all "-"))
  3274. (let ((val (org-element-property :warning-value timestamp)))
  3275. (and val (number-to-string val)))
  3276. (pcase (org-element-property :warning-unit timestamp)
  3277. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3278. (build-ts-string
  3279. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3280. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3281. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3282. ;; specify a time range in the timestamp. REPEAT-STRING is
  3283. ;; the repeater string, if any.
  3284. (lambda (time activep &optional with-time-p hour-end minute-end)
  3285. (let ((ts (format-time-string
  3286. (funcall (if with-time-p #'cdr #'car)
  3287. org-time-stamp-formats)
  3288. time)))
  3289. (when (and hour-end minute-end)
  3290. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3291. (setq ts
  3292. (replace-match
  3293. (format "\\&-%02d:%02d" hour-end minute-end)
  3294. nil nil ts)))
  3295. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3296. (dolist (s (list repeat-string warning-string))
  3297. (when (org-string-nw-p s)
  3298. (setq ts (concat (substring ts 0 -1)
  3299. " "
  3300. s
  3301. (substring ts -1)))))
  3302. ;; Return value.
  3303. ts)))
  3304. (type (org-element-property :type timestamp)))
  3305. (pcase type
  3306. ((or `active `inactive)
  3307. (let* ((minute-start (org-element-property :minute-start timestamp))
  3308. (minute-end (org-element-property :minute-end timestamp))
  3309. (hour-start (org-element-property :hour-start timestamp))
  3310. (hour-end (org-element-property :hour-end timestamp))
  3311. (time-range-p (and hour-start hour-end minute-start minute-end
  3312. (or (/= hour-start hour-end)
  3313. (/= minute-start minute-end)))))
  3314. (funcall
  3315. build-ts-string
  3316. (encode-time 0
  3317. (or minute-start 0)
  3318. (or hour-start 0)
  3319. (org-element-property :day-start timestamp)
  3320. (org-element-property :month-start timestamp)
  3321. (org-element-property :year-start timestamp))
  3322. (eq type 'active)
  3323. (and hour-start minute-start)
  3324. (and time-range-p hour-end)
  3325. (and time-range-p minute-end))))
  3326. ((or `active-range `inactive-range)
  3327. (let ((minute-start (org-element-property :minute-start timestamp))
  3328. (minute-end (org-element-property :minute-end timestamp))
  3329. (hour-start (org-element-property :hour-start timestamp))
  3330. (hour-end (org-element-property :hour-end timestamp)))
  3331. (concat
  3332. (funcall
  3333. build-ts-string (encode-time
  3334. 0
  3335. (or minute-start 0)
  3336. (or hour-start 0)
  3337. (org-element-property :day-start timestamp)
  3338. (org-element-property :month-start timestamp)
  3339. (org-element-property :year-start timestamp))
  3340. (eq type 'active-range)
  3341. (and hour-start minute-start))
  3342. "--"
  3343. (funcall build-ts-string
  3344. (encode-time 0
  3345. (or minute-end 0)
  3346. (or hour-end 0)
  3347. (org-element-property :day-end timestamp)
  3348. (org-element-property :month-end timestamp)
  3349. (org-element-property :year-end timestamp))
  3350. (eq type 'active-range)
  3351. (and hour-end minute-end)))))
  3352. (_ (org-element-property :raw-value timestamp)))))
  3353. ;;;; Underline
  3354. (defun org-element-underline-parser ()
  3355. "Parse underline object at point, if any.
  3356. When at an underline object, return a list whose car is
  3357. `underline' and cdr is a plist with `:begin', `:end',
  3358. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3359. Otherwise, return nil.
  3360. Assume point is at the first underscore marker."
  3361. (save-excursion
  3362. (unless (bolp) (backward-char 1))
  3363. (when (looking-at org-emph-re)
  3364. (let ((begin (match-beginning 2))
  3365. (contents-begin (match-beginning 4))
  3366. (contents-end (match-end 4))
  3367. (post-blank (progn (goto-char (match-end 2))
  3368. (skip-chars-forward " \t")))
  3369. (end (point)))
  3370. (list 'underline
  3371. (list :begin begin
  3372. :end end
  3373. :contents-begin contents-begin
  3374. :contents-end contents-end
  3375. :post-blank post-blank))))))
  3376. (defun org-element-underline-interpreter (_ contents)
  3377. "Interpret underline object as Org syntax.
  3378. CONTENTS is the contents of the object."
  3379. (format "_%s_" contents))
  3380. ;;;; Verbatim
  3381. (defun org-element-verbatim-parser ()
  3382. "Parse verbatim object at point, if any.
  3383. When at a verbatim object, return a list whose car is `verbatim'
  3384. and cdr is a plist with `:value', `:begin', `:end' and
  3385. `:post-blank' keywords. Otherwise, return nil.
  3386. Assume point is at the first equal sign marker."
  3387. (save-excursion
  3388. (unless (bolp) (backward-char 1))
  3389. (when (looking-at org-verbatim-re)
  3390. (let ((begin (match-beginning 2))
  3391. (value (match-string-no-properties 4))
  3392. (post-blank (progn (goto-char (match-end 2))
  3393. (skip-chars-forward " \t")))
  3394. (end (point)))
  3395. (list 'verbatim
  3396. (list :value value
  3397. :begin begin
  3398. :end end
  3399. :post-blank post-blank))))))
  3400. (defun org-element-verbatim-interpreter (verbatim _)
  3401. "Interpret VERBATIM object as Org syntax."
  3402. (format "=%s=" (org-element-property :value verbatim)))
  3403. ;;; Parsing Element Starting At Point
  3404. ;;
  3405. ;; `org-element--current-element' is the core function of this section.
  3406. ;; It returns the Lisp representation of the element starting at
  3407. ;; point.
  3408. ;;
  3409. ;; `org-element--current-element' makes use of special modes. They
  3410. ;; are activated for fixed element chaining (e.g., `plain-list' >
  3411. ;; `item') or fixed conditional element chaining (e.g., `headline' >
  3412. ;; `section'). Special modes are: `first-section', `item',
  3413. ;; `node-property', `section' and `table-row'.
  3414. (defun org-element--current-element (limit &optional granularity mode structure)
  3415. "Parse the element starting at point.
  3416. Return value is a list like (TYPE PROPS) where TYPE is the type
  3417. of the element and PROPS a plist of properties associated to the
  3418. element.
  3419. Possible types are defined in `org-element-all-elements'.
  3420. LIMIT bounds the search.
  3421. Optional argument GRANULARITY determines the depth of the
  3422. recursion. Allowed values are `headline', `greater-element',
  3423. `element', `object' or nil. When it is broader than `object' (or
  3424. nil), secondary values will not be parsed, since they only
  3425. contain objects.
  3426. Optional argument MODE, when non-nil, can be either
  3427. `first-section', `section', `planning', `item', `node-property'
  3428. and `table-row'.
  3429. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3430. computed.
  3431. This function assumes point is always at the beginning of the
  3432. element it has to parse."
  3433. (save-excursion
  3434. (let ((case-fold-search t)
  3435. ;; Determine if parsing depth allows for secondary strings
  3436. ;; parsing. It only applies to elements referenced in
  3437. ;; `org-element-secondary-value-alist'.
  3438. (raw-secondary-p (and granularity (not (eq granularity 'object)))))
  3439. (cond
  3440. ;; Item.
  3441. ((eq mode 'item)
  3442. (org-element-item-parser limit structure raw-secondary-p))
  3443. ;; Table Row.
  3444. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3445. ;; Node Property.
  3446. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3447. ;; Headline.
  3448. ((org-with-limited-levels (org-at-heading-p))
  3449. (org-element-headline-parser limit raw-secondary-p))
  3450. ;; Sections (must be checked after headline).
  3451. ((eq mode 'section) (org-element-section-parser limit))
  3452. ((eq mode 'first-section)
  3453. (org-element-section-parser
  3454. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3455. limit)))
  3456. ;; Planning.
  3457. ((and (eq mode 'planning)
  3458. (eq ?* (char-after (line-beginning-position 0)))
  3459. (looking-at org-planning-line-re))
  3460. (org-element-planning-parser limit))
  3461. ;; Property drawer.
  3462. ((and (memq mode '(planning property-drawer))
  3463. (eq ?* (char-after (line-beginning-position
  3464. (if (eq mode 'planning) 0 -1))))
  3465. (looking-at org-property-drawer-re))
  3466. (org-element-property-drawer-parser limit))
  3467. ;; When not at bol, point is at the beginning of an item or
  3468. ;; a footnote definition: next item is always a paragraph.
  3469. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3470. ;; Clock.
  3471. ((looking-at org-clock-line-re) (org-element-clock-parser limit))
  3472. ;; Inlinetask.
  3473. ((org-at-heading-p)
  3474. (org-element-inlinetask-parser limit raw-secondary-p))
  3475. ;; From there, elements can have affiliated keywords.
  3476. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3477. limit (memq granularity '(nil object)))))
  3478. (cond
  3479. ;; Jumping over affiliated keywords put point off-limits.
  3480. ;; Parse them as regular keywords.
  3481. ((and (cdr affiliated) (>= (point) limit))
  3482. (goto-char (car affiliated))
  3483. (org-element-keyword-parser limit nil))
  3484. ;; LaTeX Environment.
  3485. ((looking-at org-element--latex-begin-environment)
  3486. (org-element-latex-environment-parser limit affiliated))
  3487. ;; Drawer and Property Drawer.
  3488. ((looking-at org-drawer-regexp)
  3489. (org-element-drawer-parser limit affiliated))
  3490. ;; Fixed Width
  3491. ((looking-at "[ \t]*:\\( \\|$\\)")
  3492. (org-element-fixed-width-parser limit affiliated))
  3493. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3494. ;; Keywords.
  3495. ((looking-at "[ \t]*#")
  3496. (goto-char (match-end 0))
  3497. (cond
  3498. ((looking-at "\\(?: \\|$\\)")
  3499. (beginning-of-line)
  3500. (org-element-comment-parser limit affiliated))
  3501. ((looking-at "\\+BEGIN_\\(\\S-+\\)")
  3502. (beginning-of-line)
  3503. (funcall (pcase (upcase (match-string 1))
  3504. ("CENTER" #'org-element-center-block-parser)
  3505. ("COMMENT" #'org-element-comment-block-parser)
  3506. ("EXAMPLE" #'org-element-example-block-parser)
  3507. ("EXPORT" #'org-element-export-block-parser)
  3508. ("QUOTE" #'org-element-quote-block-parser)
  3509. ("SRC" #'org-element-src-block-parser)
  3510. ("VERSE" #'org-element-verse-block-parser)
  3511. (_ #'org-element-special-block-parser))
  3512. limit
  3513. affiliated))
  3514. ((looking-at "\\+CALL:")
  3515. (beginning-of-line)
  3516. (org-element-babel-call-parser limit affiliated))
  3517. ((looking-at "\\+BEGIN:? ")
  3518. (beginning-of-line)
  3519. (org-element-dynamic-block-parser limit affiliated))
  3520. ((looking-at "\\+\\S-+:")
  3521. (beginning-of-line)
  3522. (org-element-keyword-parser limit affiliated))
  3523. (t
  3524. (beginning-of-line)
  3525. (org-element-paragraph-parser limit affiliated))))
  3526. ;; Footnote Definition.
  3527. ((looking-at org-footnote-definition-re)
  3528. (org-element-footnote-definition-parser limit affiliated))
  3529. ;; Horizontal Rule.
  3530. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3531. (org-element-horizontal-rule-parser limit affiliated))
  3532. ;; Diary Sexp.
  3533. ((looking-at "%%(")
  3534. (org-element-diary-sexp-parser limit affiliated))
  3535. ;; Table.
  3536. ((or (looking-at "[ \t]*|")
  3537. ;; There is no strict definition of a table.el
  3538. ;; table. Try to prevent false positive while being
  3539. ;; quick.
  3540. (let ((rule-regexp "[ \t]*\\+\\(-+\\+\\)+[ \t]*$")
  3541. (next (line-beginning-position 2)))
  3542. (and (looking-at rule-regexp)
  3543. (save-excursion
  3544. (forward-line)
  3545. (re-search-forward "^[ \t]*\\($\\|[^|]\\)" limit t)
  3546. (and (> (line-beginning-position) next)
  3547. (org-match-line rule-regexp))))))
  3548. (org-element-table-parser limit affiliated))
  3549. ;; List.
  3550. ((looking-at (org-item-re))
  3551. (org-element-plain-list-parser
  3552. limit affiliated
  3553. (or structure (org-element--list-struct limit))))
  3554. ;; Default element: Paragraph.
  3555. (t (org-element-paragraph-parser limit affiliated)))))))))
  3556. ;; Most elements can have affiliated keywords. When looking for an
  3557. ;; element beginning, we want to move before them, as they belong to
  3558. ;; that element, and, in the meantime, collect information they give
  3559. ;; into appropriate properties. Hence the following function.
  3560. (defun org-element--collect-affiliated-keywords (limit parse)
  3561. "Collect affiliated keywords from point down to LIMIT.
  3562. Return a list whose CAR is the position at the first of them and
  3563. CDR a plist of keywords and values and move point to the
  3564. beginning of the first line after them.
  3565. As a special case, if element doesn't start at the beginning of
  3566. the line (e.g., a paragraph starting an item), CAR is current
  3567. position of point and CDR is nil.
  3568. When PARSE is non-nil, values from keywords belonging to
  3569. `org-element-parsed-keywords' are parsed as secondary strings."
  3570. (if (not (bolp)) (list (point))
  3571. (let ((case-fold-search t)
  3572. (origin (point))
  3573. ;; RESTRICT is the list of objects allowed in parsed
  3574. ;; keywords value. If PARSE is nil, no object is allowed.
  3575. (restrict (and parse (org-element-restriction 'keyword)))
  3576. output)
  3577. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3578. (let* ((raw-kwd (upcase (match-string 1)))
  3579. ;; Apply translation to RAW-KWD. From there, KWD is
  3580. ;; the official keyword.
  3581. (kwd (or (cdr (assoc raw-kwd
  3582. org-element-keyword-translation-alist))
  3583. raw-kwd))
  3584. ;; PARSED? is non-nil when keyword should have its
  3585. ;; value parsed.
  3586. (parsed? (member kwd org-element-parsed-keywords))
  3587. ;; Find main value for any keyword.
  3588. (value
  3589. (let ((beg (match-end 0))
  3590. (end (save-excursion
  3591. (end-of-line)
  3592. (skip-chars-backward " \t")
  3593. (point))))
  3594. (if parsed?
  3595. (save-match-data
  3596. (org-element--parse-objects beg end nil restrict))
  3597. (org-trim (buffer-substring-no-properties beg end)))))
  3598. ;; If KWD is a dual keyword, find its secondary value.
  3599. ;; Maybe parse it.
  3600. (dual? (member kwd org-element-dual-keywords))
  3601. (dual-value
  3602. (and dual?
  3603. (let ((sec (match-string-no-properties 2)))
  3604. (cond
  3605. ((and sec parsed?)
  3606. (save-match-data
  3607. (org-element--parse-objects
  3608. (match-beginning 2) (match-end 2) nil restrict)))
  3609. (sec sec)))))
  3610. ;; Attribute a property name to KWD.
  3611. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3612. ;; Now set final shape for VALUE.
  3613. (when dual?
  3614. (setq value (and (or value dual-value) (cons value dual-value))))
  3615. (when (or (member kwd org-element-multiple-keywords)
  3616. ;; Attributes can always appear on multiple lines.
  3617. (string-match "^ATTR_" kwd))
  3618. (setq value (cons value (plist-get output kwd-sym))))
  3619. ;; Eventually store the new value in OUTPUT.
  3620. (setq output (plist-put output kwd-sym value))
  3621. ;; Move to next keyword.
  3622. (forward-line)))
  3623. ;; If affiliated keywords are orphaned: move back to first one.
  3624. ;; They will be parsed as a paragraph.
  3625. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3626. ;; Return value.
  3627. (cons origin output))))
  3628. ;;; The Org Parser
  3629. ;;
  3630. ;; The two major functions here are `org-element-parse-buffer', which
  3631. ;; parses Org syntax inside the current buffer, taking into account
  3632. ;; region, narrowing, or even visibility if specified, and
  3633. ;; `org-element-parse-secondary-string', which parses objects within
  3634. ;; a given string.
  3635. ;;
  3636. ;; The (almost) almighty `org-element-map' allows applying a function
  3637. ;; on elements or objects matching some type, and accumulating the
  3638. ;; resulting values. In an export situation, it also skips unneeded
  3639. ;; parts of the parse tree.
  3640. (defun org-element-parse-buffer (&optional granularity visible-only)
  3641. "Recursively parse the buffer and return structure.
  3642. If narrowing is in effect, only parse the visible part of the
  3643. buffer.
  3644. Optional argument GRANULARITY determines the depth of the
  3645. recursion. It can be set to the following symbols:
  3646. `headline' Only parse headlines.
  3647. `greater-element' Don't recurse into greater elements except
  3648. headlines and sections. Thus, elements
  3649. parsed are the top-level ones.
  3650. `element' Parse everything but objects and plain text.
  3651. `object' Parse the complete buffer (default).
  3652. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3653. elements.
  3654. An element or object is represented as a list with the
  3655. pattern (TYPE PROPERTIES CONTENTS), where :
  3656. TYPE is a symbol describing the element or object. See
  3657. `org-element-all-elements' and `org-element-all-objects' for an
  3658. exhaustive list of such symbols. One can retrieve it with
  3659. `org-element-type' function.
  3660. PROPERTIES is the list of attributes attached to the element or
  3661. object, as a plist. Although most of them are specific to the
  3662. element or object type, all types share `:begin', `:end',
  3663. `:post-blank' and `:parent' properties, which respectively
  3664. refer to buffer position where the element or object starts,
  3665. ends, the number of white spaces or blank lines after it, and
  3666. the element or object containing it. Properties values can be
  3667. obtained by using `org-element-property' function.
  3668. CONTENTS is a list of elements, objects or raw strings
  3669. contained in the current element or object, when applicable.
  3670. One can access them with `org-element-contents' function.
  3671. The Org buffer has `org-data' as type and nil as properties.
  3672. `org-element-map' function can be used to find specific elements
  3673. or objects within the parse tree.
  3674. This function assumes that current major mode is `org-mode'."
  3675. (save-excursion
  3676. (goto-char (point-min))
  3677. (org-skip-whitespace)
  3678. (org-element--parse-elements
  3679. (point-at-bol) (point-max)
  3680. ;; Start in `first-section' mode so text before the first
  3681. ;; headline belongs to a section.
  3682. 'first-section nil granularity visible-only (list 'org-data nil))))
  3683. (defun org-element-parse-secondary-string (string restriction &optional parent)
  3684. "Recursively parse objects in STRING and return structure.
  3685. RESTRICTION is a symbol limiting the object types that will be
  3686. looked after.
  3687. Optional argument PARENT, when non-nil, is the element or object
  3688. containing the secondary string. It is used to set correctly
  3689. `:parent' property within the string.
  3690. If STRING is the empty string or nil, return nil."
  3691. (cond
  3692. ((not string) nil)
  3693. ((equal string "") nil)
  3694. (t (let ((local-variables (buffer-local-variables)))
  3695. (with-temp-buffer
  3696. (dolist (v local-variables)
  3697. (ignore-errors
  3698. (if (symbolp v) (makunbound v)
  3699. (set (make-local-variable (car v)) (cdr v)))))
  3700. ;; Transferring local variables may put the temporary buffer
  3701. ;; into a read-only state. Make sure we can insert STRING.
  3702. (let ((inhibit-read-only t)) (insert string))
  3703. ;; Prevent "Buffer *temp* modified; kill anyway?".
  3704. (restore-buffer-modified-p nil)
  3705. (org-element--parse-objects
  3706. (point-min) (point-max) nil restriction parent))))))
  3707. (defun org-element-map
  3708. (data types fun &optional info first-match no-recursion with-affiliated)
  3709. "Map a function on selected elements or objects.
  3710. DATA is a parse tree, an element, an object, a string, or a list
  3711. of such constructs. TYPES is a symbol or list of symbols of
  3712. elements or objects types (see `org-element-all-elements' and
  3713. `org-element-all-objects' for a complete list of types). FUN is
  3714. the function called on the matching element or object. It has to
  3715. accept one argument: the element or object itself.
  3716. When optional argument INFO is non-nil, it should be a plist
  3717. holding export options. In that case, parts of the parse tree
  3718. not exportable according to that property list will be skipped.
  3719. When optional argument FIRST-MATCH is non-nil, stop at the first
  3720. match for which FUN doesn't return nil, and return that value.
  3721. Optional argument NO-RECURSION is a symbol or a list of symbols
  3722. representing elements or objects types. `org-element-map' won't
  3723. enter any recursive element or object whose type belongs to that
  3724. list. Though, FUN can still be applied on them.
  3725. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  3726. apply to matching objects within parsed affiliated keywords (see
  3727. `org-element-parsed-keywords').
  3728. Nil values returned from FUN do not appear in the results.
  3729. Examples:
  3730. ---------
  3731. Assuming TREE is a variable containing an Org buffer parse tree,
  3732. the following example will return a flat list of all `src-block'
  3733. and `example-block' elements in it:
  3734. (org-element-map tree \\='(example-block src-block) #\\='identity)
  3735. The following snippet will find the first headline with a level
  3736. of 1 and a \"phone\" tag, and will return its beginning position:
  3737. (org-element-map tree \\='headline
  3738. (lambda (hl)
  3739. (and (= (org-element-property :level hl) 1)
  3740. (member \"phone\" (org-element-property :tags hl))
  3741. (org-element-property :begin hl)))
  3742. nil t)
  3743. The next example will return a flat list of all `plain-list' type
  3744. elements in TREE that are not a sub-list themselves:
  3745. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  3746. Eventually, this example will return a flat list of all `bold'
  3747. type objects containing a `latex-snippet' type object, even
  3748. looking into captions:
  3749. (org-element-map tree \\='bold
  3750. (lambda (b)
  3751. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  3752. nil nil nil t)"
  3753. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  3754. (let* ((types (if (listp types) types (list types)))
  3755. (no-recursion (if (listp no-recursion) no-recursion
  3756. (list no-recursion)))
  3757. ;; Recursion depth is determined by --CATEGORY.
  3758. (--category
  3759. (catch :--found
  3760. (let ((category 'greater-elements)
  3761. (all-objects (cons 'plain-text org-element-all-objects)))
  3762. (dolist (type types category)
  3763. (cond ((memq type all-objects)
  3764. ;; If one object is found, the function has
  3765. ;; to recurse into every object.
  3766. (throw :--found 'objects))
  3767. ((not (memq type org-element-greater-elements))
  3768. ;; If one regular element is found, the
  3769. ;; function has to recurse, at least, into
  3770. ;; every element it encounters.
  3771. (and (not (eq category 'elements))
  3772. (setq category 'elements))))))))
  3773. --acc)
  3774. (letrec ((--walk-tree
  3775. (lambda (--data)
  3776. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  3777. ;; holding contextual information.
  3778. (let ((--type (org-element-type --data)))
  3779. (cond
  3780. ((not --data))
  3781. ;; Ignored element in an export context.
  3782. ((and info (memq --data (plist-get info :ignore-list))))
  3783. ;; List of elements or objects.
  3784. ((not --type) (mapc --walk-tree --data))
  3785. ;; Unconditionally enter parse trees.
  3786. ((eq --type 'org-data)
  3787. (mapc --walk-tree (org-element-contents --data)))
  3788. (t
  3789. ;; Check if TYPE is matching among TYPES. If so,
  3790. ;; apply FUN to --DATA and accumulate return value
  3791. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  3792. (when (memq --type types)
  3793. (let ((result (funcall fun --data)))
  3794. (cond ((not result))
  3795. (first-match (throw :--map-first-match result))
  3796. (t (push result --acc)))))
  3797. ;; If --DATA has a secondary string that can contain
  3798. ;; objects with their type among TYPES, look inside.
  3799. (when (and (eq --category 'objects) (not (stringp --data)))
  3800. (dolist (p (cdr (assq --type
  3801. org-element-secondary-value-alist)))
  3802. (funcall --walk-tree (org-element-property p --data))))
  3803. ;; If --DATA has any parsed affiliated keywords and
  3804. ;; WITH-AFFILIATED is non-nil, look for objects in
  3805. ;; them.
  3806. (when (and with-affiliated
  3807. (eq --category 'objects)
  3808. (eq (org-element-class --data) 'element))
  3809. (dolist (kwd-pair org-element--parsed-properties-alist)
  3810. (let ((kwd (car kwd-pair))
  3811. (value (org-element-property (cdr kwd-pair) --data)))
  3812. ;; Pay attention to the type of parsed
  3813. ;; keyword. In particular, preserve order for
  3814. ;; multiple keywords.
  3815. (cond
  3816. ((not value))
  3817. ((member kwd org-element-dual-keywords)
  3818. (if (member kwd org-element-multiple-keywords)
  3819. (dolist (line (reverse value))
  3820. (funcall --walk-tree (cdr line))
  3821. (funcall --walk-tree (car line)))
  3822. (funcall --walk-tree (cdr value))
  3823. (funcall --walk-tree (car value))))
  3824. ((member kwd org-element-multiple-keywords)
  3825. (mapc --walk-tree (reverse value)))
  3826. (t (funcall --walk-tree value))))))
  3827. ;; Determine if a recursion into --DATA is possible.
  3828. (cond
  3829. ;; --TYPE is explicitly removed from recursion.
  3830. ((memq --type no-recursion))
  3831. ;; --DATA has no contents.
  3832. ((not (org-element-contents --data)))
  3833. ;; Looking for greater elements but --DATA is
  3834. ;; simply an element or an object.
  3835. ((and (eq --category 'greater-elements)
  3836. (not (memq --type org-element-greater-elements))))
  3837. ;; Looking for elements but --DATA is an object.
  3838. ((and (eq --category 'elements)
  3839. (eq (org-element-class --data) 'object)))
  3840. ;; In any other case, map contents.
  3841. (t (mapc --walk-tree (org-element-contents --data))))))))))
  3842. (catch :--map-first-match
  3843. (funcall --walk-tree data)
  3844. ;; Return value in a proper order.
  3845. (nreverse --acc)))))
  3846. (put 'org-element-map 'lisp-indent-function 2)
  3847. ;; The following functions are internal parts of the parser.
  3848. ;;
  3849. ;; The first one, `org-element--parse-elements' acts at the element's
  3850. ;; level.
  3851. ;;
  3852. ;; The second one, `org-element--parse-objects' applies on all objects
  3853. ;; of a paragraph or a secondary string. It calls
  3854. ;; `org-element--object-lex' to find the next object in the current
  3855. ;; container.
  3856. (defsubst org-element--next-mode (type parentp)
  3857. "Return next special mode according to TYPE, or nil.
  3858. TYPE is a symbol representing the type of an element or object
  3859. containing next element if PARENTP is non-nil, or before it
  3860. otherwise. Modes can be either `first-section', `item',
  3861. `node-property', `planning', `property-drawer', `section',
  3862. `table-row' or nil."
  3863. (if parentp
  3864. (pcase type
  3865. (`headline 'section)
  3866. (`inlinetask 'planning)
  3867. (`plain-list 'item)
  3868. (`property-drawer 'node-property)
  3869. (`section 'planning)
  3870. (`table 'table-row))
  3871. (pcase type
  3872. (`item 'item)
  3873. (`node-property 'node-property)
  3874. (`planning 'property-drawer)
  3875. (`table-row 'table-row))))
  3876. (defun org-element--parse-elements
  3877. (beg end mode structure granularity visible-only acc)
  3878. "Parse elements between BEG and END positions.
  3879. MODE prioritizes some elements over the others. It can be set to
  3880. `first-section', `section', `planning', `item', `node-property'
  3881. or `table-row'.
  3882. When value is `item', STRUCTURE will be used as the current list
  3883. structure.
  3884. GRANULARITY determines the depth of the recursion. See
  3885. `org-element-parse-buffer' for more information.
  3886. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3887. elements.
  3888. Elements are accumulated into ACC."
  3889. (save-excursion
  3890. (goto-char beg)
  3891. ;; When parsing only headlines, skip any text before first one.
  3892. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  3893. (org-with-limited-levels (outline-next-heading)))
  3894. (let (elements)
  3895. (while (< (point) end)
  3896. ;; Visible only: skip invisible parts due to folding.
  3897. (if (and visible-only (org-invisible-p nil t))
  3898. (progn
  3899. (goto-char (org-find-visible))
  3900. (when (and (eolp) (not (eobp))) (forward-char)))
  3901. ;; Find current element's type and parse it accordingly to
  3902. ;; its category.
  3903. (let* ((element (org-element--current-element
  3904. end granularity mode structure))
  3905. (type (org-element-type element))
  3906. (cbeg (org-element-property :contents-begin element)))
  3907. (goto-char (org-element-property :end element))
  3908. ;; Fill ELEMENT contents by side-effect.
  3909. (cond
  3910. ;; If element has no contents, don't modify it.
  3911. ((not cbeg))
  3912. ;; Greater element: parse it between `contents-begin' and
  3913. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  3914. ;; or ELEMENT is a headline, in which case going inside
  3915. ;; is mandatory, in order to get sub-level headings.
  3916. ((and (memq type org-element-greater-elements)
  3917. (or (memq granularity '(element object nil))
  3918. (and (eq granularity 'greater-element)
  3919. (eq type 'section))
  3920. (eq type 'headline)))
  3921. (org-element--parse-elements
  3922. cbeg (org-element-property :contents-end element)
  3923. ;; Possibly switch to a special mode.
  3924. (org-element--next-mode type t)
  3925. (and (memq type '(item plain-list))
  3926. (org-element-property :structure element))
  3927. granularity visible-only element))
  3928. ;; ELEMENT has contents. Parse objects inside, if
  3929. ;; GRANULARITY allows it.
  3930. ((memq granularity '(object nil))
  3931. (org-element--parse-objects
  3932. cbeg (org-element-property :contents-end element) element
  3933. (org-element-restriction type))))
  3934. (push (org-element-put-property element :parent acc) elements)
  3935. ;; Update mode.
  3936. (setq mode (org-element--next-mode type nil)))))
  3937. ;; Return result.
  3938. (apply #'org-element-set-contents acc (nreverse elements)))))
  3939. (defun org-element--object-lex (restriction)
  3940. "Return next object in current buffer or nil.
  3941. RESTRICTION is a list of object types, as symbols, that should be
  3942. looked after. This function assumes that the buffer is narrowed
  3943. to an appropriate container (e.g., a paragraph)."
  3944. (if (memq 'table-cell restriction) (org-element-table-cell-parser)
  3945. (let* ((start (point))
  3946. (limit
  3947. ;; Object regexp sometimes needs to have a peek at
  3948. ;; a character ahead. Therefore, when there is a hard
  3949. ;; limit, make it one more than the true beginning of the
  3950. ;; radio target.
  3951. (save-excursion
  3952. (cond ((not org-target-link-regexp) nil)
  3953. ((not (memq 'link restriction)) nil)
  3954. ((progn
  3955. (unless (bolp) (forward-char -1))
  3956. (not (re-search-forward org-target-link-regexp nil t)))
  3957. nil)
  3958. ;; Since we moved backward, we do not want to
  3959. ;; match again an hypothetical 1-character long
  3960. ;; radio link before us. Realizing that this can
  3961. ;; only happen if such a radio link starts at
  3962. ;; beginning of line, we prevent this here.
  3963. ((and (= start (1+ (line-beginning-position)))
  3964. (= start (match-end 1)))
  3965. (and (re-search-forward org-target-link-regexp nil t)
  3966. (1+ (match-beginning 1))))
  3967. (t (1+ (match-beginning 1))))))
  3968. found)
  3969. (save-excursion
  3970. (while (and (not found)
  3971. (re-search-forward org-element--object-regexp limit 'move))
  3972. (goto-char (match-beginning 0))
  3973. (let ((result (match-string 0)))
  3974. (setq found
  3975. (cond
  3976. ((string-prefix-p "call_" result t)
  3977. (and (memq 'inline-babel-call restriction)
  3978. (org-element-inline-babel-call-parser)))
  3979. ((string-prefix-p "src_" result t)
  3980. (and (memq 'inline-src-block restriction)
  3981. (org-element-inline-src-block-parser)))
  3982. (t
  3983. (pcase (char-after)
  3984. (?^ (and (memq 'superscript restriction)
  3985. (org-element-superscript-parser)))
  3986. (?_ (or (and (memq 'subscript restriction)
  3987. (org-element-subscript-parser))
  3988. (and (memq 'underline restriction)
  3989. (org-element-underline-parser))))
  3990. (?* (and (memq 'bold restriction)
  3991. (org-element-bold-parser)))
  3992. (?/ (and (memq 'italic restriction)
  3993. (org-element-italic-parser)))
  3994. (?~ (and (memq 'code restriction)
  3995. (org-element-code-parser)))
  3996. (?= (and (memq 'verbatim restriction)
  3997. (org-element-verbatim-parser)))
  3998. (?+ (and (memq 'strike-through restriction)
  3999. (org-element-strike-through-parser)))
  4000. (?@ (and (memq 'export-snippet restriction)
  4001. (org-element-export-snippet-parser)))
  4002. (?{ (and (memq 'macro restriction)
  4003. (org-element-macro-parser)))
  4004. (?$ (and (memq 'latex-fragment restriction)
  4005. (org-element-latex-fragment-parser)))
  4006. (?<
  4007. (if (eq (aref result 1) ?<)
  4008. (or (and (memq 'radio-target restriction)
  4009. (org-element-radio-target-parser))
  4010. (and (memq 'target restriction)
  4011. (org-element-target-parser)))
  4012. (or (and (memq 'timestamp restriction)
  4013. (org-element-timestamp-parser))
  4014. (and (memq 'link restriction)
  4015. (org-element-link-parser)))))
  4016. (?\\
  4017. (if (eq (aref result 1) ?\\)
  4018. (and (memq 'line-break restriction)
  4019. (org-element-line-break-parser))
  4020. (or (and (memq 'entity restriction)
  4021. (org-element-entity-parser))
  4022. (and (memq 'latex-fragment restriction)
  4023. (org-element-latex-fragment-parser)))))
  4024. (?\[
  4025. (if (eq (aref result 1) ?\[)
  4026. (and (memq 'link restriction)
  4027. (org-element-link-parser))
  4028. (or (and (memq 'footnote-reference restriction)
  4029. (org-element-footnote-reference-parser))
  4030. (and (memq 'timestamp restriction)
  4031. (org-element-timestamp-parser))
  4032. (and (memq 'statistics-cookie restriction)
  4033. (org-element-statistics-cookie-parser)))))
  4034. ;; This is probably a plain link.
  4035. (_ (and (memq 'link restriction)
  4036. (org-element-link-parser)))))))
  4037. (or (eobp) (forward-char))))
  4038. (cond (found)
  4039. (limit (forward-char -1)
  4040. (org-element-link-parser)) ;radio link
  4041. (t nil))))))
  4042. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4043. "Parse objects between BEG and END and return recursive structure.
  4044. Objects are accumulated in ACC. RESTRICTION is a list of object
  4045. successors which are allowed in the current object.
  4046. ACC becomes the parent for all parsed objects. However, if ACC
  4047. is nil (i.e., a secondary string is being parsed) and optional
  4048. argument PARENT is non-nil, use it as the parent for all objects.
  4049. Eventually, if both ACC and PARENT are nil, the common parent is
  4050. the list of objects itself."
  4051. (save-excursion
  4052. (save-restriction
  4053. (narrow-to-region beg end)
  4054. (goto-char (point-min))
  4055. (let (next-object contents)
  4056. (while (and (not (eobp))
  4057. (setq next-object (org-element--object-lex restriction)))
  4058. ;; Text before any object.
  4059. (let ((obj-beg (org-element-property :begin next-object)))
  4060. (unless (= (point) obj-beg)
  4061. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4062. (push (if acc (org-element-put-property text :parent acc) text)
  4063. contents))))
  4064. ;; Object...
  4065. (let ((obj-end (org-element-property :end next-object))
  4066. (cont-beg (org-element-property :contents-begin next-object)))
  4067. (when acc (org-element-put-property next-object :parent acc))
  4068. (push (if cont-beg
  4069. ;; Fill contents of NEXT-OBJECT if possible.
  4070. (org-element--parse-objects
  4071. cont-beg
  4072. (org-element-property :contents-end next-object)
  4073. next-object
  4074. (org-element-restriction next-object))
  4075. next-object)
  4076. contents)
  4077. (goto-char obj-end)))
  4078. ;; Text after last object.
  4079. (unless (eobp)
  4080. (let ((text (buffer-substring-no-properties (point) end)))
  4081. (push (if acc (org-element-put-property text :parent acc) text)
  4082. contents)))
  4083. ;; Result. Set appropriate parent.
  4084. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4085. (let* ((contents (nreverse contents))
  4086. (parent (or parent contents)))
  4087. (dolist (datum contents contents)
  4088. (org-element-put-property datum :parent parent))))))))
  4089. ;;; Towards A Bijective Process
  4090. ;;
  4091. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4092. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4093. ;; interpreted and expanded into a string with canonical Org syntax.
  4094. ;; Hence `org-element-interpret-data'.
  4095. ;;
  4096. ;; The function relies internally on
  4097. ;; `org-element--interpret-affiliated-keywords'.
  4098. ;;;###autoload
  4099. (defun org-element-interpret-data (data)
  4100. "Interpret DATA as Org syntax.
  4101. DATA is a parse tree, an element, an object or a secondary string
  4102. to interpret. Return Org syntax as a string."
  4103. (letrec ((fun
  4104. (lambda (data parent)
  4105. (let* ((type (org-element-type data))
  4106. ;; Find interpreter for current object or
  4107. ;; element. If it doesn't exist (e.g. this is
  4108. ;; a pseudo object or element), return contents,
  4109. ;; if any.
  4110. (interpret
  4111. (let ((fun (intern
  4112. (format "org-element-%s-interpreter" type))))
  4113. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4114. (results
  4115. (cond
  4116. ;; Secondary string.
  4117. ((not type)
  4118. (mapconcat (lambda (obj) (funcall fun obj parent))
  4119. data
  4120. ""))
  4121. ;; Full Org document.
  4122. ((eq type 'org-data)
  4123. (mapconcat (lambda (obj) (funcall fun obj parent))
  4124. (org-element-contents data)
  4125. ""))
  4126. ;; Plain text: return it.
  4127. ((stringp data) data)
  4128. ;; Element or object without contents.
  4129. ((not (org-element-contents data))
  4130. (funcall interpret data nil))
  4131. ;; Element or object with contents.
  4132. (t
  4133. (funcall
  4134. interpret
  4135. data
  4136. ;; Recursively interpret contents.
  4137. (mapconcat
  4138. (lambda (datum) (funcall fun datum data))
  4139. (org-element-contents
  4140. (if (not (memq type '(paragraph verse-block)))
  4141. data
  4142. ;; Fix indentation of elements containing
  4143. ;; objects. We ignore `table-row'
  4144. ;; elements as they are one line long
  4145. ;; anyway.
  4146. (org-element-normalize-contents
  4147. data
  4148. ;; When normalizing first paragraph of
  4149. ;; an item or a footnote-definition,
  4150. ;; ignore first line's indentation.
  4151. (and (eq type 'paragraph)
  4152. (memq (org-element-type parent)
  4153. '(footnote-definition item))
  4154. (eq data (car (org-element-contents parent)))
  4155. (eq (org-element-property :pre-blank parent)
  4156. 0)))))
  4157. ""))))))
  4158. (if (memq type '(org-data plain-text nil)) results
  4159. ;; Build white spaces. If no `:post-blank' property
  4160. ;; is specified, assume its value is 0.
  4161. (let ((blank (or (org-element-property :post-blank data) 0)))
  4162. (if (eq (org-element-class data parent) 'object)
  4163. (concat results (make-string blank ?\s))
  4164. (concat (org-element--interpret-affiliated-keywords data)
  4165. (org-element-normalize-string results)
  4166. (make-string blank ?\n)))))))))
  4167. (funcall fun data nil)))
  4168. (defun org-element--interpret-affiliated-keywords (element)
  4169. "Return ELEMENT's affiliated keywords as Org syntax.
  4170. If there is no affiliated keyword, return the empty string."
  4171. (let ((keyword-to-org
  4172. (function
  4173. (lambda (key value)
  4174. (let (dual)
  4175. (when (member key org-element-dual-keywords)
  4176. (setq dual (cdr value) value (car value)))
  4177. (concat "#+" (downcase key)
  4178. (and dual
  4179. (format "[%s]" (org-element-interpret-data dual)))
  4180. ": "
  4181. (if (member key org-element-parsed-keywords)
  4182. (org-element-interpret-data value)
  4183. value)
  4184. "\n"))))))
  4185. (mapconcat
  4186. (lambda (prop)
  4187. (let ((value (org-element-property prop element))
  4188. (keyword (upcase (substring (symbol-name prop) 1))))
  4189. (when value
  4190. (if (or (member keyword org-element-multiple-keywords)
  4191. ;; All attribute keywords can have multiple lines.
  4192. (string-match "^ATTR_" keyword))
  4193. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4194. (reverse value)
  4195. "")
  4196. (funcall keyword-to-org keyword value)))))
  4197. ;; List all ELEMENT's properties matching an attribute line or an
  4198. ;; affiliated keyword, but ignore translated keywords since they
  4199. ;; cannot belong to the property list.
  4200. (cl-loop for prop in (nth 1 element) by 'cddr
  4201. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4202. (or (string-match "^ATTR_" keyword)
  4203. (and
  4204. (member keyword org-element-affiliated-keywords)
  4205. (not (assoc keyword
  4206. org-element-keyword-translation-alist)))))
  4207. collect prop)
  4208. "")))
  4209. ;; Because interpretation of the parse tree must return the same
  4210. ;; number of blank lines between elements and the same number of white
  4211. ;; space after objects, some special care must be given to white
  4212. ;; spaces.
  4213. ;;
  4214. ;; The first function, `org-element-normalize-string', ensures any
  4215. ;; string different from the empty string will end with a single
  4216. ;; newline character.
  4217. ;;
  4218. ;; The second function, `org-element-normalize-contents', removes
  4219. ;; global indentation from the contents of the current element.
  4220. (defun org-element-normalize-string (s)
  4221. "Ensure string S ends with a single newline character.
  4222. If S isn't a string return it unchanged. If S is the empty
  4223. string, return it. Otherwise, return a new string with a single
  4224. newline character at its end."
  4225. (cond
  4226. ((not (stringp s)) s)
  4227. ((string= "" s) "")
  4228. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4229. (replace-match "\n" nil nil s)))))
  4230. (defun org-element-normalize-contents (element &optional ignore-first)
  4231. "Normalize plain text in ELEMENT's contents.
  4232. ELEMENT must only contain plain text and objects.
  4233. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4234. indentation to compute maximal common indentation.
  4235. Return the normalized element that is element with global
  4236. indentation removed from its contents."
  4237. (letrec ((find-min-ind
  4238. ;; Return minimal common indentation within BLOB. This is
  4239. ;; done by walking recursively BLOB and updating MIN-IND
  4240. ;; along the way. FIRST-FLAG is non-nil when the next
  4241. ;; object is expected to be a string that doesn't start
  4242. ;; with a newline character. It happens for strings at
  4243. ;; the beginnings of the contents or right after a line
  4244. ;; break.
  4245. (lambda (blob first-flag min-ind)
  4246. (dolist (datum (org-element-contents blob) min-ind)
  4247. (when first-flag
  4248. (setq first-flag nil)
  4249. (cond
  4250. ;; Objects cannot start with spaces: in this
  4251. ;; case, indentation is 0.
  4252. ((not (stringp datum)) (throw :zero 0))
  4253. ((not (string-match
  4254. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4255. (throw :zero 0))
  4256. ((equal (match-string 2 datum) "\n")
  4257. (put-text-property
  4258. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4259. (t
  4260. (let ((i (string-width (match-string 1 datum))))
  4261. (put-text-property
  4262. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4263. (setq min-ind (min i min-ind))))))
  4264. (cond
  4265. ((stringp datum)
  4266. (let ((s 0))
  4267. (while (string-match
  4268. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4269. (setq s (match-end 1))
  4270. (cond
  4271. ((equal (match-string 1 datum) "")
  4272. (unless (member (match-string 2 datum) '("" "\n"))
  4273. (throw :zero 0)))
  4274. ((equal (match-string 2 datum) "\n")
  4275. (put-text-property (match-beginning 1) (match-end 1)
  4276. 'org-ind 'empty datum))
  4277. (t
  4278. (let ((i (string-width (match-string 1 datum))))
  4279. (put-text-property (match-beginning 1) (match-end 1)
  4280. 'org-ind i datum)
  4281. (setq min-ind (min i min-ind))))))))
  4282. ((eq (org-element-type datum) 'line-break)
  4283. (setq first-flag t))
  4284. ((memq (org-element-type datum) org-element-recursive-objects)
  4285. (setq min-ind
  4286. (funcall find-min-ind datum first-flag min-ind)))))))
  4287. (min-ind
  4288. (catch :zero
  4289. (funcall find-min-ind
  4290. element (not ignore-first) most-positive-fixnum))))
  4291. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4292. ;; Build ELEMENT back, replacing each string with the same
  4293. ;; string minus common indentation.
  4294. (letrec ((build
  4295. (lambda (datum)
  4296. ;; Return DATUM with all its strings indentation
  4297. ;; shortened from MIN-IND white spaces.
  4298. (setcdr
  4299. (cdr datum)
  4300. (mapcar
  4301. (lambda (object)
  4302. (cond
  4303. ((stringp object)
  4304. (with-temp-buffer
  4305. (insert object)
  4306. (let ((s (point-min)))
  4307. (while (setq s (text-property-not-all
  4308. s (point-max) 'org-ind nil))
  4309. (goto-char s)
  4310. (let ((i (get-text-property s 'org-ind)))
  4311. (delete-region s (progn
  4312. (skip-chars-forward " \t")
  4313. (point)))
  4314. (when (integerp i) (indent-to (- i min-ind))))))
  4315. (buffer-string)))
  4316. ((memq (org-element-type object)
  4317. org-element-recursive-objects)
  4318. (funcall build object))
  4319. (t object)))
  4320. (org-element-contents datum)))
  4321. datum)))
  4322. (funcall build element)))))
  4323. ;;; Cache
  4324. ;;
  4325. ;; Implement a caching mechanism for `org-element-at-point' and
  4326. ;; `org-element-context', which see.
  4327. ;;
  4328. ;; A single public function is provided: `org-element-cache-reset'.
  4329. ;;
  4330. ;; Cache is enabled by default, but can be disabled globally with
  4331. ;; `org-element-use-cache'. `org-element-cache-sync-idle-time',
  4332. ;; org-element-cache-sync-duration' and `org-element-cache-sync-break'
  4333. ;; can be tweaked to control caching behavior.
  4334. ;;
  4335. ;; Internally, parsed elements are stored in an AVL tree,
  4336. ;; `org-element--cache'. This tree is updated lazily: whenever
  4337. ;; a change happens to the buffer, a synchronization request is
  4338. ;; registered in `org-element--cache-sync-requests' (see
  4339. ;; `org-element--cache-submit-request'). During idle time, requests
  4340. ;; are processed by `org-element--cache-sync'. Synchronization also
  4341. ;; happens when an element is required from the cache. In this case,
  4342. ;; the process stops as soon as the needed element is up-to-date.
  4343. ;;
  4344. ;; A synchronization request can only apply on a synchronized part of
  4345. ;; the cache. Therefore, the cache is updated at least to the
  4346. ;; location where the new request applies. Thus, requests are ordered
  4347. ;; from left to right and all elements starting before the first
  4348. ;; request are correct. This property is used by functions like
  4349. ;; `org-element--cache-find' to retrieve elements in the part of the
  4350. ;; cache that can be trusted.
  4351. ;;
  4352. ;; A request applies to every element, starting from its original
  4353. ;; location (or key, see below). When a request is processed, it
  4354. ;; moves forward and may collide the next one. In this case, both
  4355. ;; requests are merged into a new one that starts from that element.
  4356. ;; As a consequence, the whole synchronization complexity does not
  4357. ;; depend on the number of pending requests, but on the number of
  4358. ;; elements the very first request will be applied on.
  4359. ;;
  4360. ;; Elements cannot be accessed through their beginning position, which
  4361. ;; may or may not be up-to-date. Instead, each element in the tree is
  4362. ;; associated to a key, obtained with `org-element--cache-key'. This
  4363. ;; mechanism is robust enough to preserve total order among elements
  4364. ;; even when the tree is only partially synchronized.
  4365. (defvar org-element-use-cache nil
  4366. "Non-nil when Org parser should cache its results.
  4367. WARNING: for the time being, using cache sometimes triggers
  4368. freezes. Therefore, it is disabled by default. Activate it if
  4369. you want to help debugging the issue.")
  4370. (defvar org-element-cache-sync-idle-time 0.6
  4371. "Length, in seconds, of idle time before syncing cache.")
  4372. (defvar org-element-cache-sync-duration 0.04
  4373. "Maximum duration, as a time value, for a cache synchronization.
  4374. If the synchronization is not over after this delay, the process
  4375. pauses and resumes after `org-element-cache-sync-break'
  4376. seconds.")
  4377. (defvar org-element-cache-sync-break 0.3
  4378. "Duration, as a time value, of the pause between synchronizations.
  4379. See `org-element-cache-sync-duration' for more information.")
  4380. ;;;; Data Structure
  4381. (defvar org-element--cache nil
  4382. "AVL tree used to cache elements.
  4383. Each node of the tree contains an element. Comparison is done
  4384. with `org-element--cache-compare'. This cache is used in
  4385. `org-element-at-point'.")
  4386. (defvar org-element--cache-sync-requests nil
  4387. "List of pending synchronization requests.
  4388. A request is a vector with the following pattern:
  4389. \[NEXT BEG END OFFSET PARENT PHASE]
  4390. Processing a synchronization request consists of three phases:
  4391. 0. Delete modified elements,
  4392. 1. Fill missing area in cache,
  4393. 2. Shift positions and re-parent elements after the changes.
  4394. During phase 0, NEXT is the key of the first element to be
  4395. removed, BEG and END is buffer position delimiting the
  4396. modifications. Elements starting between them (inclusive) are
  4397. removed. So are elements whose parent is removed. PARENT, when
  4398. non-nil, is the parent of the first element to be removed.
  4399. During phase 1, NEXT is the key of the next known element in
  4400. cache and BEG its beginning position. Parse buffer between that
  4401. element and the one before it in order to determine the parent of
  4402. the next element. Set PARENT to the element containing NEXT.
  4403. During phase 2, NEXT is the key of the next element to shift in
  4404. the parse tree. All elements starting from this one have their
  4405. properties relatives to buffer positions shifted by integer
  4406. OFFSET and, if they belong to element PARENT, are adopted by it.
  4407. PHASE specifies the phase number, as an integer.")
  4408. (defvar org-element--cache-sync-timer nil
  4409. "Timer used for cache synchronization.")
  4410. (defvar org-element--cache-sync-keys nil
  4411. "Hash table used to store keys during synchronization.
  4412. See `org-element--cache-key' for more information.")
  4413. (defsubst org-element--cache-key (element)
  4414. "Return a unique key for ELEMENT in cache tree.
  4415. Keys are used to keep a total order among elements in the cache.
  4416. Comparison is done with `org-element--cache-key-less-p'.
  4417. When no synchronization is taking place, a key is simply the
  4418. beginning position of the element, or that position plus one in
  4419. the case of an first item (respectively row) in
  4420. a list (respectively a table).
  4421. During a synchronization, the key is the one the element had when
  4422. the cache was synchronized for the last time. Elements added to
  4423. cache during the synchronization get a new key generated with
  4424. `org-element--cache-generate-key'.
  4425. Such keys are stored in `org-element--cache-sync-keys'. The hash
  4426. table is cleared once the synchronization is complete."
  4427. (or (gethash element org-element--cache-sync-keys)
  4428. (let* ((begin (org-element-property :begin element))
  4429. ;; Increase beginning position of items (respectively
  4430. ;; table rows) by one, so the first item can get
  4431. ;; a different key from its parent list (respectively
  4432. ;; table).
  4433. (key (if (memq (org-element-type element) '(item table-row))
  4434. (1+ begin)
  4435. begin)))
  4436. (if org-element--cache-sync-requests
  4437. (puthash element key org-element--cache-sync-keys)
  4438. key))))
  4439. (defun org-element--cache-generate-key (lower upper)
  4440. "Generate a key between LOWER and UPPER.
  4441. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4442. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4443. a unique key, as an integer or a list of integers, according to
  4444. the following rules:
  4445. - LOWER and UPPER are compared level-wise until values differ.
  4446. - If, at a given level, LOWER and UPPER differ from more than
  4447. 2, the new key shares all the levels above with LOWER and
  4448. gets a new level. Its value is the mean between LOWER and
  4449. UPPER:
  4450. (1 2) + (1 4) --> (1 3)
  4451. - If LOWER has no value to compare with, it is assumed that its
  4452. value is `most-negative-fixnum'. E.g.,
  4453. (1 1) + (1 1 2)
  4454. is equivalent to
  4455. (1 1 m) + (1 1 2)
  4456. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4457. short of levels, the current value is `most-positive-fixnum'.
  4458. - If they differ from only one, the new key inherits from
  4459. current LOWER level and fork it at the next level. E.g.,
  4460. (2 1) + (3 3)
  4461. is equivalent to
  4462. (2 1) + (2 M)
  4463. where M is `most-positive-fixnum'.
  4464. - If the key is only one level long, it is returned as an
  4465. integer:
  4466. (1 2) + (3 2) --> 2
  4467. When they are not equals, the function assumes that LOWER is
  4468. lesser than UPPER, per `org-element--cache-key-less-p'."
  4469. (if (equal lower upper) lower
  4470. (let ((lower (if (integerp lower) (list lower) lower))
  4471. (upper (if (integerp upper) (list upper) upper))
  4472. skip-upper key)
  4473. (catch 'exit
  4474. (while t
  4475. (let ((min (or (car lower) most-negative-fixnum))
  4476. (max (cond (skip-upper most-positive-fixnum)
  4477. ((car upper))
  4478. (t most-positive-fixnum))))
  4479. (if (< (1+ min) max)
  4480. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  4481. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  4482. (when (and (< min max) (not skip-upper))
  4483. ;; When at a given level, LOWER and UPPER differ from
  4484. ;; 1, ignore UPPER altogether. Instead create a key
  4485. ;; between LOWER and the greatest key with the same
  4486. ;; prefix as LOWER so far.
  4487. (setq skip-upper t))
  4488. (push min key)
  4489. (setq lower (cdr lower) upper (cdr upper)))))))))
  4490. (defsubst org-element--cache-key-less-p (a b)
  4491. "Non-nil if key A is less than key B.
  4492. A and B are either integers or lists of integers, as returned by
  4493. `org-element--cache-key'."
  4494. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  4495. (if (integerp b) (< (car a) b)
  4496. (catch 'exit
  4497. (while (and a b)
  4498. (cond ((car-less-than-car a b) (throw 'exit t))
  4499. ((car-less-than-car b a) (throw 'exit nil))
  4500. (t (setq a (cdr a) b (cdr b)))))
  4501. ;; If A is empty, either keys are equal (B is also empty) and
  4502. ;; we return nil, or A is lesser than B (B is longer) and we
  4503. ;; return a non-nil value.
  4504. ;;
  4505. ;; If A is not empty, B is necessarily empty and A is greater
  4506. ;; than B (A is longer). Therefore, return nil.
  4507. (and (null a) b)))))
  4508. (defun org-element--cache-compare (a b)
  4509. "Non-nil when element A is located before element B."
  4510. (org-element--cache-key-less-p (org-element--cache-key a)
  4511. (org-element--cache-key b)))
  4512. (defsubst org-element--cache-root ()
  4513. "Return root value in cache.
  4514. This function assumes `org-element--cache' is a valid AVL tree."
  4515. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  4516. ;;;; Tools
  4517. (defsubst org-element--cache-active-p ()
  4518. "Non-nil when cache is active in current buffer."
  4519. (and org-element-use-cache
  4520. org-element--cache
  4521. (derived-mode-p 'org-mode)))
  4522. (defun org-element--cache-find (pos &optional side)
  4523. "Find element in cache starting at POS or before.
  4524. POS refers to a buffer position.
  4525. When optional argument SIDE is non-nil, the function checks for
  4526. elements starting at or past POS instead. If SIDE is `both', the
  4527. function returns a cons cell where car is the first element
  4528. starting at or before POS and cdr the first element starting
  4529. after POS.
  4530. The function can only find elements in the synchronized part of
  4531. the cache."
  4532. (let ((limit (and org-element--cache-sync-requests
  4533. (aref (car org-element--cache-sync-requests) 0)))
  4534. (node (org-element--cache-root))
  4535. lower upper)
  4536. (while node
  4537. (let* ((element (avl-tree--node-data node))
  4538. (begin (org-element-property :begin element)))
  4539. (cond
  4540. ((and limit
  4541. (not (org-element--cache-key-less-p
  4542. (org-element--cache-key element) limit)))
  4543. (setq node (avl-tree--node-left node)))
  4544. ((> begin pos)
  4545. (setq upper element
  4546. node (avl-tree--node-left node)))
  4547. ((< begin pos)
  4548. (setq lower element
  4549. node (avl-tree--node-right node)))
  4550. ;; We found an element in cache starting at POS. If `side'
  4551. ;; is `both' we also want the next one in order to generate
  4552. ;; a key in-between.
  4553. ;;
  4554. ;; If the element is the first row or item in a table or
  4555. ;; a plain list, we always return the table or the plain
  4556. ;; list.
  4557. ;;
  4558. ;; In any other case, we return the element found.
  4559. ((eq side 'both)
  4560. (setq lower element)
  4561. (setq node (avl-tree--node-right node)))
  4562. ((and (memq (org-element-type element) '(item table-row))
  4563. (let ((parent (org-element-property :parent element)))
  4564. (and (= (org-element-property :begin element)
  4565. (org-element-property :contents-begin parent))
  4566. (setq node nil
  4567. lower parent
  4568. upper parent)))))
  4569. (t
  4570. (setq node nil
  4571. lower element
  4572. upper element)))))
  4573. (pcase side
  4574. (`both (cons lower upper))
  4575. (`nil lower)
  4576. (_ upper))))
  4577. (defun org-element--cache-put (element)
  4578. "Store ELEMENT in current buffer's cache, if allowed."
  4579. (when (org-element--cache-active-p)
  4580. (when org-element--cache-sync-requests
  4581. ;; During synchronization, first build an appropriate key for
  4582. ;; the new element so `avl-tree-enter' can insert it at the
  4583. ;; right spot in the cache.
  4584. (let ((keys (org-element--cache-find
  4585. (org-element-property :begin element) 'both)))
  4586. (puthash element
  4587. (org-element--cache-generate-key
  4588. (and (car keys) (org-element--cache-key (car keys)))
  4589. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  4590. (org-element--cache-sync-requests
  4591. (aref (car org-element--cache-sync-requests) 0))))
  4592. org-element--cache-sync-keys)))
  4593. (avl-tree-enter org-element--cache element)))
  4594. (defsubst org-element--cache-remove (element)
  4595. "Remove ELEMENT from cache.
  4596. Assume ELEMENT belongs to cache and that a cache is active."
  4597. (avl-tree-delete org-element--cache element))
  4598. ;;;; Synchronization
  4599. (defsubst org-element--cache-set-timer (buffer)
  4600. "Set idle timer for cache synchronization in BUFFER."
  4601. (when org-element--cache-sync-timer
  4602. (cancel-timer org-element--cache-sync-timer))
  4603. (setq org-element--cache-sync-timer
  4604. (run-with-idle-timer
  4605. (let ((idle (current-idle-time)))
  4606. (if idle (org-time-add idle org-element-cache-sync-break)
  4607. org-element-cache-sync-idle-time))
  4608. nil
  4609. #'org-element--cache-sync
  4610. buffer)))
  4611. (defsubst org-element--cache-interrupt-p (time-limit)
  4612. "Non-nil when synchronization process should be interrupted.
  4613. TIME-LIMIT is a time value or nil."
  4614. (and time-limit
  4615. (or (input-pending-p)
  4616. (org-time-less-p time-limit nil))))
  4617. (defsubst org-element--cache-shift-positions (element offset &optional props)
  4618. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  4619. Properties containing buffer positions are `:begin', `:end',
  4620. `:contents-begin', `:contents-end' and `:structure'. When
  4621. optional argument PROPS is a list of keywords, only shift
  4622. properties provided in that list.
  4623. Properties are modified by side-effect."
  4624. (let ((properties (nth 1 element)))
  4625. ;; Shift `:structure' property for the first plain list only: it
  4626. ;; is the only one that really matters and it prevents from
  4627. ;; shifting it more than once.
  4628. (when (and (or (not props) (memq :structure props))
  4629. (eq (org-element-type element) 'plain-list)
  4630. (not (eq (org-element-type (plist-get properties :parent))
  4631. 'item)))
  4632. (dolist (item (plist-get properties :structure))
  4633. (cl-incf (car item) offset)
  4634. (cl-incf (nth 6 item) offset)))
  4635. (dolist (key '(:begin :contents-begin :contents-end :end :post-affiliated))
  4636. (let ((value (and (or (not props) (memq key props))
  4637. (plist-get properties key))))
  4638. (and value (plist-put properties key (+ offset value)))))))
  4639. (defun org-element--cache-sync (buffer &optional threshold future-change)
  4640. "Synchronize cache with recent modification in BUFFER.
  4641. When optional argument THRESHOLD is non-nil, do the
  4642. synchronization for all elements starting before or at threshold,
  4643. then exit. Otherwise, synchronize cache for as long as
  4644. `org-element-cache-sync-duration' or until Emacs leaves idle
  4645. state.
  4646. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  4647. not registered yet in the cache are going to happen. It is used
  4648. in `org-element--cache-submit-request', where cache is partially
  4649. updated before current modification are actually submitted."
  4650. (when (buffer-live-p buffer)
  4651. (with-current-buffer buffer
  4652. (let ((inhibit-quit t) request next)
  4653. (when org-element--cache-sync-timer
  4654. (cancel-timer org-element--cache-sync-timer))
  4655. (catch 'interrupt
  4656. (while org-element--cache-sync-requests
  4657. (setq request (car org-element--cache-sync-requests)
  4658. next (nth 1 org-element--cache-sync-requests))
  4659. (org-element--cache-process-request
  4660. request
  4661. (and next (aref next 0))
  4662. threshold
  4663. (and (not threshold)
  4664. (org-time-add nil
  4665. org-element-cache-sync-duration))
  4666. future-change)
  4667. ;; Request processed. Merge current and next offsets and
  4668. ;; transfer ending position.
  4669. (when next
  4670. (cl-incf (aref next 3) (aref request 3))
  4671. (aset next 2 (aref request 2)))
  4672. (setq org-element--cache-sync-requests
  4673. (cdr org-element--cache-sync-requests))))
  4674. ;; If more requests are awaiting, set idle timer accordingly.
  4675. ;; Otherwise, reset keys.
  4676. (if org-element--cache-sync-requests
  4677. (org-element--cache-set-timer buffer)
  4678. (clrhash org-element--cache-sync-keys))))))
  4679. (defun org-element--cache-process-request
  4680. (request next threshold time-limit future-change)
  4681. "Process synchronization REQUEST for all entries before NEXT.
  4682. REQUEST is a vector, built by `org-element--cache-submit-request'.
  4683. NEXT is a cache key, as returned by `org-element--cache-key'.
  4684. When non-nil, THRESHOLD is a buffer position. Synchronization
  4685. stops as soon as a shifted element begins after it.
  4686. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  4687. after this time or when Emacs exits idle state.
  4688. When non-nil, FUTURE-CHANGE is a buffer position where changes
  4689. not registered yet in the cache are going to happen. See
  4690. `org-element--cache-submit-request' for more information.
  4691. Throw `interrupt' if the process stops before completing the
  4692. request."
  4693. (catch 'quit
  4694. (when (= (aref request 5) 0)
  4695. ;; Phase 0.
  4696. ;;
  4697. ;; Delete all elements starting after BEG, but not after buffer
  4698. ;; position END or past element with key NEXT. Also delete
  4699. ;; elements contained within a previously removed element
  4700. ;; (stored in `last-container').
  4701. ;;
  4702. ;; At each iteration, we start again at tree root since
  4703. ;; a deletion modifies structure of the balanced tree.
  4704. (catch 'end-phase
  4705. (while t
  4706. (when (org-element--cache-interrupt-p time-limit)
  4707. (throw 'interrupt nil))
  4708. ;; Find first element in cache with key BEG or after it.
  4709. (let ((beg (aref request 0))
  4710. (end (aref request 2))
  4711. (node (org-element--cache-root))
  4712. data data-key last-container)
  4713. (while node
  4714. (let* ((element (avl-tree--node-data node))
  4715. (key (org-element--cache-key element)))
  4716. (cond
  4717. ((org-element--cache-key-less-p key beg)
  4718. (setq node (avl-tree--node-right node)))
  4719. ((org-element--cache-key-less-p beg key)
  4720. (setq data element
  4721. data-key key
  4722. node (avl-tree--node-left node)))
  4723. (t (setq data element
  4724. data-key key
  4725. node nil)))))
  4726. (if data
  4727. (let ((pos (org-element-property :begin data)))
  4728. (if (if (or (not next)
  4729. (org-element--cache-key-less-p data-key next))
  4730. (<= pos end)
  4731. (and last-container
  4732. (let ((up data))
  4733. (while (and up (not (eq up last-container)))
  4734. (setq up (org-element-property :parent up)))
  4735. up)))
  4736. (progn (when (and (not last-container)
  4737. (> (org-element-property :end data)
  4738. end))
  4739. (setq last-container data))
  4740. (org-element--cache-remove data))
  4741. (aset request 0 data-key)
  4742. (aset request 1 pos)
  4743. (aset request 5 1)
  4744. (throw 'end-phase nil)))
  4745. ;; No element starting after modifications left in
  4746. ;; cache: further processing is futile.
  4747. (throw 'quit t))))))
  4748. (when (= (aref request 5) 1)
  4749. ;; Phase 1.
  4750. ;;
  4751. ;; Phase 0 left a hole in the cache. Some elements after it
  4752. ;; could have parents within. For example, in the following
  4753. ;; buffer:
  4754. ;;
  4755. ;; - item
  4756. ;;
  4757. ;;
  4758. ;; Paragraph1
  4759. ;;
  4760. ;; Paragraph2
  4761. ;;
  4762. ;; if we remove a blank line between "item" and "Paragraph1",
  4763. ;; everything down to "Paragraph2" is removed from cache. But
  4764. ;; the paragraph now belongs to the list, and its `:parent'
  4765. ;; property no longer is accurate.
  4766. ;;
  4767. ;; Therefore we need to parse again elements in the hole, or at
  4768. ;; least in its last section, so that we can re-parent
  4769. ;; subsequent elements, during phase 2.
  4770. ;;
  4771. ;; Note that we only need to get the parent from the first
  4772. ;; element in cache after the hole.
  4773. ;;
  4774. ;; When next key is lesser or equal to the current one, delegate
  4775. ;; phase 1 processing to next request in order to preserve key
  4776. ;; order among requests.
  4777. (let ((key (aref request 0)))
  4778. (when (and next (not (org-element--cache-key-less-p key next)))
  4779. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  4780. (aset next-request 0 key)
  4781. (aset next-request 1 (aref request 1))
  4782. (aset next-request 5 1))
  4783. (throw 'quit t)))
  4784. ;; Next element will start at its beginning position plus
  4785. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  4786. ;; contains the real beginning position of the first element to
  4787. ;; shift and re-parent.
  4788. (let ((limit (+ (aref request 1) (aref request 3))))
  4789. (cond ((and threshold (> limit threshold)) (throw 'interrupt nil))
  4790. ((and future-change (>= limit future-change))
  4791. ;; Changes are going to happen around this element and
  4792. ;; they will trigger another phase 1 request. Skip the
  4793. ;; current one.
  4794. (aset request 5 2))
  4795. (t
  4796. (let ((parent (org-element--parse-to limit t time-limit)))
  4797. (aset request 4 parent)
  4798. (aset request 5 2))))))
  4799. ;; Phase 2.
  4800. ;;
  4801. ;; Shift all elements starting from key START, but before NEXT, by
  4802. ;; OFFSET, and re-parent them when appropriate.
  4803. ;;
  4804. ;; Elements are modified by side-effect so the tree structure
  4805. ;; remains intact.
  4806. ;;
  4807. ;; Once THRESHOLD, if any, is reached, or once there is an input
  4808. ;; pending, exit. Before leaving, the current synchronization
  4809. ;; request is updated.
  4810. (let ((start (aref request 0))
  4811. (offset (aref request 3))
  4812. (parent (aref request 4))
  4813. (node (org-element--cache-root))
  4814. (stack (list nil))
  4815. (leftp t)
  4816. exit-flag)
  4817. ;; No re-parenting nor shifting planned: request is over.
  4818. (when (and (not parent) (zerop offset)) (throw 'quit t))
  4819. (while node
  4820. (let* ((data (avl-tree--node-data node))
  4821. (key (org-element--cache-key data)))
  4822. (if (and leftp (avl-tree--node-left node)
  4823. (not (org-element--cache-key-less-p key start)))
  4824. (progn (push node stack)
  4825. (setq node (avl-tree--node-left node)))
  4826. (unless (org-element--cache-key-less-p key start)
  4827. ;; We reached NEXT. Request is complete.
  4828. (when (equal key next) (throw 'quit t))
  4829. ;; Handle interruption request. Update current request.
  4830. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  4831. (aset request 0 key)
  4832. (aset request 4 parent)
  4833. (throw 'interrupt nil))
  4834. ;; Shift element.
  4835. (unless (zerop offset)
  4836. (org-element--cache-shift-positions data offset))
  4837. (let ((begin (org-element-property :begin data)))
  4838. ;; Update PARENT and re-parent DATA, only when
  4839. ;; necessary. Propagate new structures for lists.
  4840. (while (and parent
  4841. (<= (org-element-property :end parent) begin))
  4842. (setq parent (org-element-property :parent parent)))
  4843. (cond ((and (not parent) (zerop offset)) (throw 'quit nil))
  4844. ((and parent
  4845. (let ((p (org-element-property :parent data)))
  4846. (or (not p)
  4847. (< (org-element-property :begin p)
  4848. (org-element-property :begin parent)))))
  4849. (org-element-put-property data :parent parent)
  4850. (let ((s (org-element-property :structure parent)))
  4851. (when (and s (org-element-property :structure data))
  4852. (org-element-put-property data :structure s)))))
  4853. ;; Cache is up-to-date past THRESHOLD. Request
  4854. ;; interruption.
  4855. (when (and threshold (> begin threshold)) (setq exit-flag t))))
  4856. (setq node (if (setq leftp (avl-tree--node-right node))
  4857. (avl-tree--node-right node)
  4858. (pop stack))))))
  4859. ;; We reached end of tree: synchronization complete.
  4860. t)))
  4861. (defun org-element--parse-to (pos &optional syncp time-limit)
  4862. "Parse elements in current section, down to POS.
  4863. Start parsing from the closest between the last known element in
  4864. cache or headline above. Return the smallest element containing
  4865. POS.
  4866. When optional argument SYNCP is non-nil, return the parent of the
  4867. element containing POS instead. In that case, it is also
  4868. possible to provide TIME-LIMIT, which is a time value specifying
  4869. when the parsing should stop. The function throws `interrupt' if
  4870. the process stopped before finding the expected result."
  4871. (catch 'exit
  4872. (org-with-wide-buffer
  4873. (goto-char pos)
  4874. (let* ((cached (and (org-element--cache-active-p)
  4875. (org-element--cache-find pos nil)))
  4876. (begin (org-element-property :begin cached))
  4877. element next mode)
  4878. (cond
  4879. ;; Nothing in cache before point: start parsing from first
  4880. ;; element following headline above, or first element in
  4881. ;; buffer.
  4882. ((not cached)
  4883. (when (org-with-limited-levels (outline-previous-heading))
  4884. (setq mode 'planning)
  4885. (forward-line))
  4886. (skip-chars-forward " \r\t\n")
  4887. (beginning-of-line))
  4888. ;; Cache returned exact match: return it.
  4889. ((= pos begin)
  4890. (throw 'exit (if syncp (org-element-property :parent cached) cached)))
  4891. ;; There's a headline between cached value and POS: cached
  4892. ;; value is invalid. Start parsing from first element
  4893. ;; following the headline.
  4894. ((re-search-backward
  4895. (org-with-limited-levels org-outline-regexp-bol) begin t)
  4896. (forward-line)
  4897. (skip-chars-forward " \r\t\n")
  4898. (beginning-of-line)
  4899. (setq mode 'planning))
  4900. ;; Check if CACHED or any of its ancestors contain point.
  4901. ;;
  4902. ;; If there is such an element, we inspect it in order to know
  4903. ;; if we return it or if we need to parse its contents.
  4904. ;; Otherwise, we just start parsing from current location,
  4905. ;; which is right after the top-most element containing
  4906. ;; CACHED.
  4907. ;;
  4908. ;; As a special case, if POS is at the end of the buffer, we
  4909. ;; want to return the innermost element ending there.
  4910. ;;
  4911. ;; Also, if we find an ancestor and discover that we need to
  4912. ;; parse its contents, make sure we don't start from
  4913. ;; `:contents-begin', as we would otherwise go past CACHED
  4914. ;; again. Instead, in that situation, we will resume parsing
  4915. ;; from NEXT, which is located after CACHED or its higher
  4916. ;; ancestor not containing point.
  4917. (t
  4918. (let ((up cached)
  4919. (pos (if (= (point-max) pos) (1- pos) pos)))
  4920. (goto-char (or (org-element-property :contents-begin cached) begin))
  4921. (while (let ((end (org-element-property :end up)))
  4922. (and (<= end pos)
  4923. (goto-char end)
  4924. (setq up (org-element-property :parent up)))))
  4925. (cond ((not up))
  4926. ((eobp) (setq element up))
  4927. (t (setq element up next (point)))))))
  4928. ;; Parse successively each element until we reach POS.
  4929. (let ((end (or (org-element-property :end element)
  4930. (save-excursion
  4931. (org-with-limited-levels (outline-next-heading))
  4932. (point))))
  4933. (parent element))
  4934. (while t
  4935. (when syncp
  4936. (cond ((= (point) pos) (throw 'exit parent))
  4937. ((org-element--cache-interrupt-p time-limit)
  4938. (throw 'interrupt nil))))
  4939. (unless element
  4940. (setq element (org-element--current-element
  4941. end 'element mode
  4942. (org-element-property :structure parent)))
  4943. (org-element-put-property element :parent parent)
  4944. (org-element--cache-put element))
  4945. (let ((elem-end (org-element-property :end element))
  4946. (type (org-element-type element)))
  4947. (cond
  4948. ;; Skip any element ending before point. Also skip
  4949. ;; element ending at point (unless it is also the end of
  4950. ;; buffer) since we're sure that another element begins
  4951. ;; after it.
  4952. ((and (<= elem-end pos) (/= (point-max) elem-end))
  4953. (goto-char elem-end)
  4954. (setq mode (org-element--next-mode type nil)))
  4955. ;; A non-greater element contains point: return it.
  4956. ((not (memq type org-element-greater-elements))
  4957. (throw 'exit element))
  4958. ;; Otherwise, we have to decide if ELEMENT really
  4959. ;; contains POS. In that case we start parsing from
  4960. ;; contents' beginning.
  4961. ;;
  4962. ;; If POS is at contents' beginning but it is also at
  4963. ;; the beginning of the first item in a list or a table.
  4964. ;; In that case, we need to create an anchor for that
  4965. ;; list or table, so return it.
  4966. ;;
  4967. ;; Also, if POS is at the end of the buffer, no element
  4968. ;; can start after it, but more than one may end there.
  4969. ;; Arbitrarily, we choose to return the innermost of
  4970. ;; such elements.
  4971. ((let ((cbeg (org-element-property :contents-begin element))
  4972. (cend (org-element-property :contents-end element)))
  4973. (when (or syncp
  4974. (and cbeg cend
  4975. (or (< cbeg pos)
  4976. (and (= cbeg pos)
  4977. (not (memq type '(plain-list table)))))
  4978. (or (> cend pos)
  4979. (and (= cend pos) (= (point-max) pos)))))
  4980. (goto-char (or next cbeg))
  4981. (setq next nil
  4982. mode (org-element--next-mode type t)
  4983. parent element
  4984. end cend))))
  4985. ;; Otherwise, return ELEMENT as it is the smallest
  4986. ;; element containing POS.
  4987. (t (throw 'exit element))))
  4988. (setq element nil)))))))
  4989. ;;;; Staging Buffer Changes
  4990. (defconst org-element--cache-sensitive-re
  4991. (concat
  4992. "^\\*+ " "\\|"
  4993. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  4994. "^[ \t]*\\(?:"
  4995. "#\\+\\(?:BEGIN[:_]\\|END\\(?:_\\|:?[ \t]*$\\)\\)" "\\|"
  4996. "\\\\begin{[A-Za-z0-9*]+}" "\\|"
  4997. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  4998. "\\)")
  4999. "Regexp matching a sensitive line, structure wise.
  5000. A sensitive line is a headline, inlinetask, block, drawer, or
  5001. latex-environment boundary. When such a line is modified,
  5002. structure changes in the document may propagate in the whole
  5003. section, possibly making cache invalid.")
  5004. (defvar org-element--cache-change-warning nil
  5005. "Non-nil when a sensitive line is about to be changed.
  5006. It is a symbol among nil, t and `headline'.")
  5007. (defun org-element--cache-before-change (beg end)
  5008. "Request extension of area going to be modified if needed.
  5009. BEG and END are the beginning and end of the range of changed
  5010. text. See `before-change-functions' for more information."
  5011. (when (org-element--cache-active-p)
  5012. (org-with-wide-buffer
  5013. (goto-char beg)
  5014. (beginning-of-line)
  5015. (let ((bottom (save-excursion (goto-char end) (line-end-position))))
  5016. (setq org-element--cache-change-warning
  5017. (save-match-data
  5018. (if (and (org-with-limited-levels (org-at-heading-p))
  5019. (= (line-end-position) bottom))
  5020. 'headline
  5021. (let ((case-fold-search t))
  5022. (re-search-forward
  5023. org-element--cache-sensitive-re bottom t)))))))))
  5024. (defun org-element--cache-after-change (beg end pre)
  5025. "Update buffer modifications for current buffer.
  5026. BEG and END are the beginning and end of the range of changed
  5027. text, and the length in bytes of the pre-change text replaced by
  5028. that range. See `after-change-functions' for more information."
  5029. (when (org-element--cache-active-p)
  5030. (org-with-wide-buffer
  5031. (goto-char beg)
  5032. (beginning-of-line)
  5033. (save-match-data
  5034. (let ((top (point))
  5035. (bottom (save-excursion (goto-char end) (line-end-position))))
  5036. ;; Determine if modified area needs to be extended, according
  5037. ;; to both previous and current state. We make a special
  5038. ;; case for headline editing: if a headline is modified but
  5039. ;; not removed, do not extend.
  5040. (when (pcase org-element--cache-change-warning
  5041. (`t t)
  5042. (`headline
  5043. (not (and (org-with-limited-levels (org-at-heading-p))
  5044. (= (line-end-position) bottom))))
  5045. (_
  5046. (let ((case-fold-search t))
  5047. (re-search-forward
  5048. org-element--cache-sensitive-re bottom t))))
  5049. ;; Effectively extend modified area.
  5050. (org-with-limited-levels
  5051. (setq top (progn (goto-char top)
  5052. (when (outline-previous-heading) (forward-line))
  5053. (point)))
  5054. (setq bottom (progn (goto-char bottom)
  5055. (if (outline-next-heading) (1- (point))
  5056. (point))))))
  5057. ;; Store synchronization request.
  5058. (let ((offset (- end beg pre)))
  5059. (org-element--cache-submit-request top (- bottom offset) offset)))))
  5060. ;; Activate a timer to process the request during idle time.
  5061. (org-element--cache-set-timer (current-buffer))))
  5062. (defun org-element--cache-for-removal (beg end offset)
  5063. "Return first element to remove from cache.
  5064. BEG and END are buffer positions delimiting buffer modifications.
  5065. OFFSET is the size of the changes.
  5066. Returned element is usually the first element in cache containing
  5067. any position between BEG and END. As an exception, greater
  5068. elements around the changes that are robust to contents
  5069. modifications are preserved and updated according to the
  5070. changes."
  5071. (let* ((elements (org-element--cache-find (1- beg) 'both))
  5072. (before (car elements))
  5073. (after (cdr elements)))
  5074. (if (not before) after
  5075. (let ((up before)
  5076. (robust-flag t))
  5077. (while up
  5078. (if (let ((type (org-element-type up)))
  5079. (and (or (memq type '(center-block dynamic-block quote-block
  5080. special-block))
  5081. ;; Drawers named "PROPERTIES" are probably
  5082. ;; a properties drawer being edited. Force
  5083. ;; parsing to check if editing is over.
  5084. (and (eq type 'drawer)
  5085. (not (string=
  5086. (org-element-property :drawer-name up)
  5087. "PROPERTIES"))))
  5088. (let ((cbeg (org-element-property :contents-begin up)))
  5089. (and cbeg
  5090. (<= cbeg beg)
  5091. (> (org-element-property :contents-end up) end)))))
  5092. ;; UP is a robust greater element containing changes.
  5093. ;; We only need to extend its ending boundaries.
  5094. (org-element--cache-shift-positions
  5095. up offset '(:contents-end :end))
  5096. (setq before up)
  5097. (when robust-flag (setq robust-flag nil)))
  5098. (setq up (org-element-property :parent up)))
  5099. ;; We're at top level element containing ELEMENT: if it's
  5100. ;; altered by buffer modifications, it is first element in
  5101. ;; cache to be removed. Otherwise, that first element is the
  5102. ;; following one.
  5103. ;;
  5104. ;; As a special case, do not remove BEFORE if it is a robust
  5105. ;; container for current changes.
  5106. (if (or (< (org-element-property :end before) beg) robust-flag) after
  5107. before)))))
  5108. (defun org-element--cache-submit-request (beg end offset)
  5109. "Submit a new cache synchronization request for current buffer.
  5110. BEG and END are buffer positions delimiting the minimal area
  5111. where cache data should be removed. OFFSET is the size of the
  5112. change, as an integer."
  5113. (let ((next (car org-element--cache-sync-requests))
  5114. delete-to delete-from)
  5115. (if (and next
  5116. (zerop (aref next 5))
  5117. (> (setq delete-to (+ (aref next 2) (aref next 3))) end)
  5118. (<= (setq delete-from (aref next 1)) end))
  5119. ;; Current changes can be merged with first sync request: we
  5120. ;; can save a partial cache synchronization.
  5121. (progn
  5122. (cl-incf (aref next 3) offset)
  5123. ;; If last change happened within area to be removed, extend
  5124. ;; boundaries of robust parents, if any. Otherwise, find
  5125. ;; first element to remove and update request accordingly.
  5126. (if (> beg delete-from)
  5127. (let ((up (aref next 4)))
  5128. (while up
  5129. (org-element--cache-shift-positions
  5130. up offset '(:contents-end :end))
  5131. (setq up (org-element-property :parent up))))
  5132. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  5133. (when first
  5134. (aset next 0 (org-element--cache-key first))
  5135. (aset next 1 (org-element-property :begin first))
  5136. (aset next 4 (org-element-property :parent first))))))
  5137. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  5138. ;; if any, is no longer a 0-phase request, thus ensuring that
  5139. ;; phases are properly ordered. We need to provide OFFSET as
  5140. ;; optional parameter since current modifications are not known
  5141. ;; yet to the otherwise correct part of the cache (i.e, before
  5142. ;; the first request).
  5143. (when next (org-element--cache-sync (current-buffer) end beg))
  5144. (let ((first (org-element--cache-for-removal beg end offset)))
  5145. (if first
  5146. (push (let ((beg (org-element-property :begin first))
  5147. (key (org-element--cache-key first)))
  5148. (cond
  5149. ;; When changes happen before the first known
  5150. ;; element, re-parent and shift the rest of the
  5151. ;; cache.
  5152. ((> beg end) (vector key beg nil offset nil 1))
  5153. ;; Otherwise, we find the first non robust
  5154. ;; element containing END. All elements between
  5155. ;; FIRST and this one are to be removed.
  5156. ((let ((first-end (org-element-property :end first)))
  5157. (and (> first-end end)
  5158. (vector key beg first-end offset first 0))))
  5159. (t
  5160. (let* ((element (org-element--cache-find end))
  5161. (end (org-element-property :end element))
  5162. (up element))
  5163. (while (and (setq up (org-element-property :parent up))
  5164. (>= (org-element-property :begin up) beg))
  5165. (setq end (org-element-property :end up)
  5166. element up))
  5167. (vector key beg end offset element 0)))))
  5168. org-element--cache-sync-requests)
  5169. ;; No element to remove. No need to re-parent either.
  5170. ;; Simply shift additional elements, if any, by OFFSET.
  5171. (when org-element--cache-sync-requests
  5172. (cl-incf (aref (car org-element--cache-sync-requests) 3)
  5173. offset)))))))
  5174. ;;;; Public Functions
  5175. ;;;###autoload
  5176. (defun org-element-cache-reset (&optional all)
  5177. "Reset cache in current buffer.
  5178. When optional argument ALL is non-nil, reset cache in all Org
  5179. buffers."
  5180. (interactive "P")
  5181. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  5182. (with-current-buffer buffer
  5183. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  5184. (setq-local org-element--cache
  5185. (avl-tree-create #'org-element--cache-compare))
  5186. (setq-local org-element--cache-sync-keys
  5187. (make-hash-table :weakness 'key :test #'eq))
  5188. (setq-local org-element--cache-change-warning nil)
  5189. (setq-local org-element--cache-sync-requests nil)
  5190. (setq-local org-element--cache-sync-timer nil)
  5191. (add-hook 'before-change-functions
  5192. #'org-element--cache-before-change nil t)
  5193. (add-hook 'after-change-functions
  5194. #'org-element--cache-after-change nil t)))))
  5195. ;;;###autoload
  5196. (defun org-element-cache-refresh (pos)
  5197. "Refresh cache at position POS."
  5198. (when (org-element--cache-active-p)
  5199. (org-element--cache-sync (current-buffer) pos)
  5200. (org-element--cache-submit-request pos pos 0)
  5201. (org-element--cache-set-timer (current-buffer))))
  5202. ;;; The Toolbox
  5203. ;;
  5204. ;; The first move is to implement a way to obtain the smallest element
  5205. ;; containing point. This is the job of `org-element-at-point'. It
  5206. ;; basically jumps back to the beginning of section containing point
  5207. ;; and proceed, one element after the other, with
  5208. ;; `org-element--current-element' until the container is found. Note:
  5209. ;; When using `org-element-at-point', secondary values are never
  5210. ;; parsed since the function focuses on elements, not on objects.
  5211. ;;
  5212. ;; At a deeper level, `org-element-context' lists all elements and
  5213. ;; objects containing point.
  5214. ;;
  5215. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  5216. ;; internally by navigation and manipulation tools.
  5217. ;;;###autoload
  5218. (defun org-element-at-point ()
  5219. "Determine closest element around point.
  5220. Return value is a list like (TYPE PROPS) where TYPE is the type
  5221. of the element and PROPS a plist of properties associated to the
  5222. element.
  5223. Possible types are defined in `org-element-all-elements'.
  5224. Properties depend on element or object type, but always include
  5225. `:begin', `:end', and `:post-blank' properties.
  5226. As a special case, if point is at the very beginning of the first
  5227. item in a list or sub-list, returned element will be that list
  5228. instead of the item. Likewise, if point is at the beginning of
  5229. the first row of a table, returned element will be the table
  5230. instead of the first row.
  5231. When point is at the end of the buffer, return the innermost
  5232. element ending there."
  5233. (org-with-wide-buffer
  5234. (let ((origin (point)))
  5235. (end-of-line)
  5236. (skip-chars-backward " \r\t\n")
  5237. (cond
  5238. ;; Within blank lines at the beginning of buffer, return nil.
  5239. ((bobp) nil)
  5240. ;; Within blank lines right after a headline, return that
  5241. ;; headline.
  5242. ((org-with-limited-levels (org-at-heading-p))
  5243. (beginning-of-line)
  5244. (org-element-headline-parser (point-max) t))
  5245. ;; Otherwise parse until we find element containing ORIGIN.
  5246. (t
  5247. (when (org-element--cache-active-p)
  5248. (if (not org-element--cache) (org-element-cache-reset)
  5249. (org-element--cache-sync (current-buffer) origin)))
  5250. (org-element--parse-to origin))))))
  5251. ;;;###autoload
  5252. (defun org-element-context (&optional element)
  5253. "Return smallest element or object around point.
  5254. Return value is a list like (TYPE PROPS) where TYPE is the type
  5255. of the element or object and PROPS a plist of properties
  5256. associated to it.
  5257. Possible types are defined in `org-element-all-elements' and
  5258. `org-element-all-objects'. Properties depend on element or
  5259. object type, but always include `:begin', `:end', `:parent' and
  5260. `:post-blank'.
  5261. As a special case, if point is right after an object and not at
  5262. the beginning of any other object, return that object.
  5263. Optional argument ELEMENT, when non-nil, is the closest element
  5264. containing point, as returned by `org-element-at-point'.
  5265. Providing it allows for quicker computation."
  5266. (catch 'objects-forbidden
  5267. (org-with-wide-buffer
  5268. (let* ((pos (point))
  5269. (element (or element (org-element-at-point)))
  5270. (type (org-element-type element))
  5271. (post (org-element-property :post-affiliated element)))
  5272. ;; If point is inside an element containing objects or
  5273. ;; a secondary string, narrow buffer to the container and
  5274. ;; proceed with parsing. Otherwise, return ELEMENT.
  5275. (cond
  5276. ;; At a parsed affiliated keyword, check if we're inside main
  5277. ;; or dual value.
  5278. ((and post (< pos post))
  5279. (beginning-of-line)
  5280. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  5281. (cond
  5282. ((not (member-ignore-case (match-string 1)
  5283. org-element-parsed-keywords))
  5284. (throw 'objects-forbidden element))
  5285. ((< (match-end 0) pos)
  5286. (narrow-to-region (match-end 0) (line-end-position)))
  5287. ((and (match-beginning 2)
  5288. (>= pos (match-beginning 2))
  5289. (< pos (match-end 2)))
  5290. (narrow-to-region (match-beginning 2) (match-end 2)))
  5291. (t (throw 'objects-forbidden element)))
  5292. ;; Also change type to retrieve correct restrictions.
  5293. (setq type 'keyword))
  5294. ;; At an item, objects can only be located within tag, if any.
  5295. ((eq type 'item)
  5296. (let ((tag (org-element-property :tag element)))
  5297. (if (or (not tag) (/= (line-beginning-position) post))
  5298. (throw 'objects-forbidden element)
  5299. (beginning-of-line)
  5300. (search-forward tag (line-end-position))
  5301. (goto-char (match-beginning 0))
  5302. (if (and (>= pos (point)) (< pos (match-end 0)))
  5303. (narrow-to-region (point) (match-end 0))
  5304. (throw 'objects-forbidden element)))))
  5305. ;; At an headline or inlinetask, objects are in title.
  5306. ((memq type '(headline inlinetask))
  5307. (let ((case-fold-search nil))
  5308. (goto-char (org-element-property :begin element))
  5309. (looking-at org-complex-heading-regexp)
  5310. (let ((end (match-end 4)))
  5311. (if (not end) (throw 'objects-forbidden element)
  5312. (goto-char (match-beginning 4))
  5313. (when (looking-at org-comment-string)
  5314. (goto-char (match-end 0)))
  5315. (if (>= (point) end) (throw 'objects-forbidden element)
  5316. (narrow-to-region (point) end))))))
  5317. ;; At a paragraph, a table-row or a verse block, objects are
  5318. ;; located within their contents.
  5319. ((memq type '(paragraph table-row verse-block))
  5320. (let ((cbeg (org-element-property :contents-begin element))
  5321. (cend (org-element-property :contents-end element)))
  5322. ;; CBEG is nil for table rules.
  5323. (if (and cbeg cend (>= pos cbeg)
  5324. (or (< pos cend) (and (= pos cend) (eobp))))
  5325. (narrow-to-region cbeg cend)
  5326. (throw 'objects-forbidden element))))
  5327. (t (throw 'objects-forbidden element)))
  5328. (goto-char (point-min))
  5329. (let ((restriction (org-element-restriction type))
  5330. (parent element)
  5331. last)
  5332. (catch 'exit
  5333. (while t
  5334. (let ((next (org-element--object-lex restriction)))
  5335. (when next (org-element-put-property next :parent parent))
  5336. ;; Process NEXT, if any, in order to know if we need to
  5337. ;; skip it, return it or move into it.
  5338. (if (or (not next) (> (org-element-property :begin next) pos))
  5339. (throw 'exit (or last parent))
  5340. (let ((end (org-element-property :end next))
  5341. (cbeg (org-element-property :contents-begin next))
  5342. (cend (org-element-property :contents-end next)))
  5343. (cond
  5344. ;; Skip objects ending before point. Also skip
  5345. ;; objects ending at point unless it is also the
  5346. ;; end of buffer, since we want to return the
  5347. ;; innermost object.
  5348. ((and (<= end pos) (/= (point-max) end))
  5349. (goto-char end)
  5350. ;; For convenience, when object ends at POS,
  5351. ;; without any space, store it in LAST, as we
  5352. ;; will return it if no object starts here.
  5353. (when (and (= end pos)
  5354. (not (memq (char-before) '(?\s ?\t))))
  5355. (setq last next)))
  5356. ;; If POS is within a container object, move into
  5357. ;; that object.
  5358. ((and cbeg cend
  5359. (>= pos cbeg)
  5360. (or (< pos cend)
  5361. ;; At contents' end, if there is no
  5362. ;; space before point, also move into
  5363. ;; object, for consistency with
  5364. ;; convenience feature above.
  5365. (and (= pos cend)
  5366. (or (= (point-max) pos)
  5367. (not (memq (char-before pos)
  5368. '(?\s ?\t)))))))
  5369. (goto-char cbeg)
  5370. (narrow-to-region (point) cend)
  5371. (setq parent next)
  5372. (setq restriction (org-element-restriction next)))
  5373. ;; Otherwise, return NEXT.
  5374. (t (throw 'exit next)))))))))))))
  5375. (defun org-element-lineage (datum &optional types with-self)
  5376. "List all ancestors of a given element or object.
  5377. DATUM is an object or element.
  5378. Return ancestors from the closest to the farthest. When optional
  5379. argument TYPES is a list of symbols, return the first element or
  5380. object in the lineage whose type belongs to that list instead.
  5381. When optional argument WITH-SELF is non-nil, lineage includes
  5382. DATUM itself as the first element, and TYPES, if provided, also
  5383. apply to it.
  5384. When DATUM is obtained through `org-element-context' or
  5385. `org-element-at-point', only ancestors from its section can be
  5386. found. There is no such limitation when DATUM belongs to a full
  5387. parse tree."
  5388. (let ((up (if with-self datum (org-element-property :parent datum)))
  5389. ancestors)
  5390. (while (and up (not (memq (org-element-type up) types)))
  5391. (unless types (push up ancestors))
  5392. (setq up (org-element-property :parent up)))
  5393. (if types up (nreverse ancestors))))
  5394. (defun org-element-nested-p (elem-A elem-B)
  5395. "Non-nil when elements ELEM-A and ELEM-B are nested."
  5396. (let ((beg-A (org-element-property :begin elem-A))
  5397. (beg-B (org-element-property :begin elem-B))
  5398. (end-A (org-element-property :end elem-A))
  5399. (end-B (org-element-property :end elem-B)))
  5400. (or (and (>= beg-A beg-B) (<= end-A end-B))
  5401. (and (>= beg-B beg-A) (<= end-B end-A)))))
  5402. (defun org-element-swap-A-B (elem-A elem-B)
  5403. "Swap elements ELEM-A and ELEM-B.
  5404. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  5405. end of ELEM-A."
  5406. (goto-char (org-element-property :begin elem-A))
  5407. ;; There are two special cases when an element doesn't start at bol:
  5408. ;; the first paragraph in an item or in a footnote definition.
  5409. (let ((specialp (not (bolp))))
  5410. ;; Only a paragraph without any affiliated keyword can be moved at
  5411. ;; ELEM-A position in such a situation. Note that the case of
  5412. ;; a footnote definition is impossible: it cannot contain two
  5413. ;; paragraphs in a row because it cannot contain a blank line.
  5414. (when (and specialp
  5415. (or (not (eq (org-element-type elem-B) 'paragraph))
  5416. (/= (org-element-property :begin elem-B)
  5417. (org-element-property :contents-begin elem-B))))
  5418. (error "Cannot swap elements"))
  5419. ;; In a special situation, ELEM-A will have no indentation. We'll
  5420. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  5421. (let* ((ind-B (when specialp
  5422. (goto-char (org-element-property :begin elem-B))
  5423. (current-indentation)))
  5424. (beg-A (org-element-property :begin elem-A))
  5425. (end-A (save-excursion
  5426. (goto-char (org-element-property :end elem-A))
  5427. (skip-chars-backward " \r\t\n")
  5428. (point-at-eol)))
  5429. (beg-B (org-element-property :begin elem-B))
  5430. (end-B (save-excursion
  5431. (goto-char (org-element-property :end elem-B))
  5432. (skip-chars-backward " \r\t\n")
  5433. (point-at-eol)))
  5434. ;; Store inner overlays responsible for visibility status.
  5435. ;; We also need to store their boundaries as they will be
  5436. ;; removed from buffer.
  5437. (overlays
  5438. (cons
  5439. (delq nil
  5440. (mapcar (lambda (o)
  5441. (and (>= (overlay-start o) beg-A)
  5442. (<= (overlay-end o) end-A)
  5443. (list o (overlay-start o) (overlay-end o))))
  5444. (overlays-in beg-A end-A)))
  5445. (delq nil
  5446. (mapcar (lambda (o)
  5447. (and (>= (overlay-start o) beg-B)
  5448. (<= (overlay-end o) end-B)
  5449. (list o (overlay-start o) (overlay-end o))))
  5450. (overlays-in beg-B end-B)))))
  5451. ;; Get contents.
  5452. (body-A (buffer-substring beg-A end-A))
  5453. (body-B (delete-and-extract-region beg-B end-B)))
  5454. (goto-char beg-B)
  5455. (when specialp
  5456. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  5457. (indent-to-column ind-B))
  5458. (insert body-A)
  5459. ;; Restore ex ELEM-A overlays.
  5460. (let ((offset (- beg-B beg-A)))
  5461. (dolist (o (car overlays))
  5462. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  5463. (goto-char beg-A)
  5464. (delete-region beg-A end-A)
  5465. (insert body-B)
  5466. ;; Restore ex ELEM-B overlays.
  5467. (dolist (o (cdr overlays))
  5468. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  5469. (goto-char (org-element-property :end elem-B)))))
  5470. (provide 'org-element)
  5471. ;; Local variables:
  5472. ;; generated-autoload-file: "org-loaddefs.el"
  5473. ;; End:
  5474. ;;; org-element.el ends here