org-element.el 212 KB

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