org-element.el 213 KB

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