org-element.el 218 KB

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