org-element.el 216 KB

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