org-element.el 213 KB

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