org-element.el 213 KB

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