org-element.el 216 KB

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