org-element.el 222 KB

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