org-element.el 216 KB

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