org-element.el 216 KB

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