org-element.el 216 KB

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