org-element.el 214 KB

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