org-element.el 214 KB

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