org-element.el 215 KB

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