org-element.el 216 KB

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