org-element.el 213 KB

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