org-element.el 216 KB

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