org-element.el 328 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990
  1. ;;; org-element.el --- Parser for Org Syntax -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2012-2022 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 'ring)
  53. (require 'cl-lib)
  54. (require 'ol)
  55. (require 'org)
  56. (require 'org-persist)
  57. (require 'org-compat)
  58. (require 'org-entities)
  59. (require 'org-footnote)
  60. (require 'org-list)
  61. (require 'org-macs)
  62. (require 'org-table)
  63. (declare-function org-at-heading-p "org" (&optional _))
  64. (declare-function org-escape-code-in-string "org-src" (s))
  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 org-inlinetask-outline-regexp "org-inlinetask" ())
  70. (declare-function outline-next-heading "outline" ())
  71. (declare-function outline-previous-heading "outline" ())
  72. (defvar org-complex-heading-regexp)
  73. (defvar org-done-keywords)
  74. (defvar org-edit-src-content-indentation)
  75. (defvar org-match-substring-regexp)
  76. (defvar org-odd-levels-only)
  77. (defvar org-property-drawer-re)
  78. (defvar org-property-format)
  79. (defvar org-property-re)
  80. (defvar org-src-preserve-indentation)
  81. (defvar org-tags-column)
  82. (defvar org-time-stamp-formats)
  83. (defvar org-todo-regexp)
  84. (defvar org-ts-regexp-both)
  85. ;;; Definitions And Rules
  86. ;;
  87. ;; Define elements, greater elements and specify recursive objects,
  88. ;; along with the affiliated keywords recognized. Also set up
  89. ;; restrictions on recursive objects combinations.
  90. ;;
  91. ;; `org-element-update-syntax' builds proper syntax regexps according
  92. ;; to current setup.
  93. (defconst org-element-archive-tag "ARCHIVE"
  94. "Tag marking a substree as archived.")
  95. (defconst org-element-citation-key-re
  96. (rx "@" (group (one-or-more (any word "-.:?!`'/*@+|(){}<>&_^$#%~"))))
  97. "Regexp matching a citation key.
  98. Key is located in match group 1.")
  99. (defconst org-element-citation-prefix-re
  100. (rx "[cite"
  101. (opt "/" (group (one-or-more (any "/_-" alnum)))) ;style
  102. ":"
  103. (zero-or-more (any "\t\n ")))
  104. "Regexp matching a citation prefix.
  105. Style, if any, is located in match group 1.")
  106. (defconst org-element-clock-line-re
  107. (rx line-start (0+ (or ?\t ?\s)) "CLOCK:")
  108. "Regexp matching a clock line.")
  109. (defconst org-element-comment-string "COMMENT"
  110. "String marker for commented headlines.")
  111. (defconst org-element-closed-keyword "CLOSED:"
  112. "Keyword used to close TODO entries.")
  113. (defconst org-element-deadline-keyword "DEADLINE:"
  114. "Keyword used to mark deadline entries.")
  115. (defconst org-element-scheduled-keyword "SCHEDULED:"
  116. "Keyword used to mark scheduled entries.")
  117. (defconst org-element-planning-keywords-re
  118. (regexp-opt (list org-element-closed-keyword
  119. org-element-deadline-keyword
  120. org-element-scheduled-keyword))
  121. "Regexp matching any planning line keyword.")
  122. (defconst org-element-planning-line-re
  123. (rx-to-string
  124. `(seq line-start (0+ (any ?\s ?\t))
  125. (group (regexp ,org-element-planning-keywords-re))))
  126. "Regexp matching a planning line.")
  127. (defconst org-element-drawer-re
  128. (rx line-start (0+ (any ?\s ?\t))
  129. ":" (group (1+ (any ?- ?_ word))) ":"
  130. (0+ (any ?\s ?\t)) line-end)
  131. "Regexp matching opening or closing line of a drawer.
  132. Drawer's name is located in match group 1.")
  133. (defconst org-element-dynamic-block-open-re
  134. (rx line-start (0+ (any ?\s ?\t))
  135. "#+BEGIN:" (0+ (any ?\s ?\t))
  136. (group (1+ word))
  137. (opt
  138. (1+ (any ?\s ?\t))
  139. (group (1+ nonl))))
  140. "Regexp matching the opening line of a dynamic block.
  141. Dynamic block's name is located in match group 1.
  142. Parameters are in match group 2.")
  143. (defconst org-element-headline-re
  144. (rx line-start (1+ "*") " ")
  145. "Regexp matching a headline.")
  146. (defvar org-element-paragraph-separate nil
  147. "Regexp to separate paragraphs in an Org buffer.
  148. In the case of lines starting with \"#\" and \":\", this regexp
  149. is not sufficient to know if point is at a paragraph ending. See
  150. `org-element-paragraph-parser' for more information.")
  151. (defvar org-element--object-regexp nil
  152. "Regexp possibly matching the beginning of an object.
  153. This regexp allows false positives. Dedicated parser (e.g.,
  154. `org-export-bold-parser') will take care of further filtering.
  155. Radio links are not matched by this regexp, as they are treated
  156. specially in `org-element--object-lex'.")
  157. (defun org-element--set-regexps ()
  158. "Build variable syntax regexps."
  159. (setq org-element-paragraph-separate
  160. (concat "^\\(?:"
  161. ;; Headlines, inlinetasks.
  162. "\\*+ " "\\|"
  163. ;; Footnote definitions.
  164. "\\[fn:[-_[:word:]]+\\]" "\\|"
  165. ;; Diary sexps.
  166. "%%(" "\\|"
  167. "[ \t]*\\(?:"
  168. ;; Empty lines.
  169. "$" "\\|"
  170. ;; Tables (any type).
  171. "|" "\\|"
  172. "\\+\\(?:-+\\+\\)+[ \t]*$" "\\|"
  173. ;; Comments, keyword-like or block-like constructs.
  174. ;; Blocks and keywords with dual values need to be
  175. ;; double-checked.
  176. "#\\(?: \\|$\\|\\+\\(?:"
  177. "BEGIN_\\S-+" "\\|"
  178. "\\S-+\\(?:\\[.*\\]\\)?:[ \t]*\\)\\)"
  179. "\\|"
  180. ;; Drawers (any type) and fixed-width areas. Drawers
  181. ;; need to be double-checked.
  182. ":\\(?: \\|$\\|[-_[:word:]]+:[ \t]*$\\)" "\\|"
  183. ;; Horizontal rules.
  184. "-\\{5,\\}[ \t]*$" "\\|"
  185. ;; LaTeX environments.
  186. "\\\\begin{\\([A-Za-z0-9*]+\\)}" "\\|"
  187. ;; Clock lines.
  188. "CLOCK:" "\\|"
  189. ;; Lists.
  190. (let ((term (pcase org-plain-list-ordered-item-terminator
  191. (?\) ")") (?. "\\.") (_ "[.)]")))
  192. (alpha (and org-list-allow-alphabetical "\\|[A-Za-z]")))
  193. (concat "\\(?:[-+*]\\|\\(?:[0-9]+" alpha "\\)" term "\\)"
  194. "\\(?:[ \t]\\|$\\)"))
  195. "\\)\\)")
  196. org-element--object-regexp
  197. (mapconcat #'identity
  198. (let ((link-types (regexp-opt (org-link-types))))
  199. (list
  200. ;; Sub/superscript.
  201. "\\(?:[_^][-{(*+.,[:alnum:]]\\)"
  202. ;; Bold, code, italic, strike-through, underline
  203. ;; and verbatim.
  204. (rx (or "*" "~" "=" "+" "_" "/") (not space))
  205. ;; Plain links.
  206. (concat "\\<" link-types ":")
  207. ;; Objects starting with "[": citations,
  208. ;; footnote reference, statistics cookie,
  209. ;; timestamp (inactive) and regular link.
  210. (format "\\[\\(?:%s\\)"
  211. (mapconcat
  212. #'identity
  213. (list "cite[:/]"
  214. "fn:"
  215. "\\(?:[0-9]\\|\\(?:%\\|/[0-9]*\\)\\]\\)"
  216. "\\[")
  217. "\\|"))
  218. ;; Objects starting with "@": export snippets.
  219. "@@"
  220. ;; Objects starting with "{": macro.
  221. "{{{"
  222. ;; Objects starting with "<" : timestamp
  223. ;; (active, diary), target, radio target and
  224. ;; angular links.
  225. (concat "<\\(?:%%\\|<\\|[0-9]\\|" link-types "\\)")
  226. ;; Objects starting with "$": latex fragment.
  227. "\\$"
  228. ;; Objects starting with "\": line break,
  229. ;; entity, latex fragment.
  230. "\\\\\\(?:[a-zA-Z[(]\\|\\\\[ \t]*$\\|_ +\\)"
  231. ;; Objects starting with raw text: inline Babel
  232. ;; source block, inline Babel call.
  233. "\\(?:call\\|src\\)_"))
  234. "\\|")))
  235. (org-element--set-regexps)
  236. ;;;###autoload
  237. (defun org-element-update-syntax ()
  238. "Update parser internals."
  239. (interactive)
  240. (org-element--set-regexps)
  241. (org-element-cache-reset 'all))
  242. (defconst org-element-all-elements
  243. '(babel-call center-block clock comment comment-block diary-sexp drawer
  244. dynamic-block example-block export-block fixed-width
  245. footnote-definition headline horizontal-rule inlinetask item
  246. keyword latex-environment node-property paragraph plain-list
  247. planning property-drawer quote-block section
  248. special-block src-block table table-row verse-block)
  249. "Complete list of element types.")
  250. (defconst org-element-greater-elements
  251. '(center-block drawer dynamic-block footnote-definition headline inlinetask
  252. item plain-list property-drawer quote-block section
  253. special-block table org-data)
  254. "List of recursive element types aka Greater Elements.")
  255. (defconst org-element-all-objects
  256. '(bold citation citation-reference code entity export-snippet
  257. footnote-reference inline-babel-call inline-src-block italic line-break
  258. latex-fragment link macro radio-target statistics-cookie strike-through
  259. subscript superscript table-cell target timestamp underline verbatim)
  260. "Complete list of object types.")
  261. (defconst org-element-recursive-objects
  262. '(bold citation footnote-reference italic link subscript radio-target
  263. strike-through superscript table-cell underline)
  264. "List of recursive object types.")
  265. (defconst org-element-object-containers
  266. (append org-element-recursive-objects '(paragraph table-row verse-block))
  267. "List of object or element types that can directly contain objects.")
  268. (defconst org-element-affiliated-keywords
  269. '("CAPTION" "DATA" "HEADER" "HEADERS" "LABEL" "NAME" "PLOT" "RESNAME" "RESULT"
  270. "RESULTS" "SOURCE" "SRCNAME" "TBLNAME")
  271. "List of affiliated keywords as strings.
  272. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  273. are affiliated keywords and need not to be in this list.")
  274. (defconst org-element-keyword-translation-alist
  275. '(("DATA" . "NAME") ("LABEL" . "NAME") ("RESNAME" . "NAME")
  276. ("SOURCE" . "NAME") ("SRCNAME" . "NAME") ("TBLNAME" . "NAME")
  277. ("RESULT" . "RESULTS") ("HEADERS" . "HEADER"))
  278. "Alist of usual translations for keywords.
  279. The key is the old name and the value the new one. The property
  280. holding their value will be named after the translated name.")
  281. (defconst org-element-multiple-keywords '("CAPTION" "HEADER")
  282. "List of affiliated keywords that can occur more than once in an element.
  283. Their value will be consed into a list of strings, which will be
  284. returned as the value of the property.
  285. This list is checked after translations have been applied. See
  286. `org-element-keyword-translation-alist'.
  287. By default, all keywords setting attributes (e.g., \"ATTR_LATEX\")
  288. allow multiple occurrences and need not to be in this list.")
  289. (defconst org-element-parsed-keywords '("CAPTION")
  290. "List of affiliated keywords whose value can be parsed.
  291. Their value will be stored as a secondary string: a list of
  292. strings and objects.
  293. This list is checked after translations have been applied. See
  294. `org-element-keyword-translation-alist'.")
  295. (defconst org-element--parsed-properties-alist
  296. (mapcar (lambda (k) (cons k (intern (concat ":" (downcase k)))))
  297. org-element-parsed-keywords)
  298. "Alist of parsed keywords and associated properties.
  299. This is generated from `org-element-parsed-keywords', which
  300. see.")
  301. (defconst org-element-dual-keywords '("CAPTION" "RESULTS")
  302. "List of affiliated keywords which can have a secondary value.
  303. In Org syntax, they can be written with optional square brackets
  304. before the colons. For example, RESULTS keyword can be
  305. associated to a hash value with the following:
  306. #+RESULTS[hash-string]: some-source
  307. This list is checked after translations have been applied. See
  308. `org-element-keyword-translation-alist'.")
  309. (defconst org-element--affiliated-re
  310. (format "[ \t]*#\\+\\(?:%s\\):[ \t]*"
  311. (concat
  312. ;; Dual affiliated keywords.
  313. (format "\\(?1:%s\\)\\(?:\\[\\(.*\\)\\]\\)?"
  314. (regexp-opt org-element-dual-keywords))
  315. "\\|"
  316. ;; Regular affiliated keywords.
  317. (format "\\(?1:%s\\)"
  318. (regexp-opt
  319. (cl-remove-if
  320. (lambda (k) (member k org-element-dual-keywords))
  321. org-element-affiliated-keywords)))
  322. "\\|"
  323. ;; Export attributes.
  324. "\\(?1:ATTR_[-_A-Za-z0-9]+\\)"))
  325. "Regexp matching any affiliated keyword.
  326. Keyword name is put in match group 1. Moreover, if keyword
  327. belongs to `org-element-dual-keywords', put the dual value in
  328. match group 2.
  329. Don't modify it, set `org-element-affiliated-keywords' instead.")
  330. (defconst org-element-object-restrictions
  331. (let* ((minimal-set '(bold code entity italic latex-fragment strike-through
  332. subscript superscript underline verbatim))
  333. (standard-set
  334. (remq 'citation-reference (remq 'table-cell org-element-all-objects)))
  335. (standard-set-no-line-break (remq 'line-break standard-set)))
  336. `((bold ,@standard-set)
  337. (citation citation-reference)
  338. (citation-reference ,@minimal-set)
  339. (footnote-reference ,@standard-set)
  340. (headline ,@standard-set-no-line-break)
  341. (inlinetask ,@standard-set-no-line-break)
  342. (italic ,@standard-set)
  343. (item ,@standard-set-no-line-break)
  344. (keyword ,@(remq 'footnote-reference standard-set))
  345. ;; Ignore all links in a link description. Also ignore
  346. ;; radio-targets and line breaks.
  347. (link export-snippet inline-babel-call inline-src-block macro
  348. statistics-cookie ,@minimal-set)
  349. (paragraph ,@standard-set)
  350. ;; Remove any variable object from radio target as it would
  351. ;; prevent it from being properly recognized.
  352. (radio-target ,@minimal-set)
  353. (strike-through ,@standard-set)
  354. (subscript ,@standard-set)
  355. (superscript ,@standard-set)
  356. ;; Ignore inline babel call and inline source block as formulas
  357. ;; are possible. Also ignore line breaks and statistics
  358. ;; cookies.
  359. (table-cell citation export-snippet footnote-reference link macro
  360. radio-target target timestamp ,@minimal-set)
  361. (table-row table-cell)
  362. (underline ,@standard-set)
  363. (verse-block ,@standard-set)))
  364. "Alist of objects restrictions.
  365. key is an element or object type containing objects and value is
  366. a list of types that can be contained within an element or object
  367. of such type.
  368. This alist also applies to secondary string. For example, an
  369. `headline' type element doesn't directly contain objects, but
  370. still has an entry since one of its properties (`:title') does.")
  371. (defconst org-element-secondary-value-alist
  372. '((citation :prefix :suffix)
  373. (headline :title)
  374. (inlinetask :title)
  375. (item :tag)
  376. (citation-reference :prefix :suffix))
  377. "Alist between element types and locations of secondary values.")
  378. (defconst org-element--pair-round-table
  379. (let ((table (make-char-table 'syntax-table '(2))))
  380. (modify-syntax-entry ?\( "()" table)
  381. (modify-syntax-entry ?\) ")(" table)
  382. table)
  383. "Table used internally to pair only round brackets.")
  384. (defconst org-element--pair-square-table
  385. (let ((table (make-char-table 'syntax-table '(2))))
  386. (modify-syntax-entry ?\[ "(]" table)
  387. (modify-syntax-entry ?\] ")[" table)
  388. table)
  389. "Table used internally to pair only square brackets.")
  390. (defconst org-element--pair-curly-table
  391. (let ((table (make-char-table 'syntax-table '(2))))
  392. (modify-syntax-entry ?\{ "(}" table)
  393. (modify-syntax-entry ?\} "){" table)
  394. table)
  395. "Table used internally to pair only curly brackets.")
  396. (defun org-element--parse-paired-brackets (char)
  397. "Parse paired brackets at point.
  398. CHAR is the opening bracket to consider, as a character. Return
  399. contents between brackets, as a string, or nil. Also move point
  400. past the brackets."
  401. (when (eq char (char-after))
  402. (let ((syntax-table (pcase char
  403. (?\{ org-element--pair-curly-table)
  404. (?\[ org-element--pair-square-table)
  405. (?\( org-element--pair-round-table)
  406. (_ nil)))
  407. (pos (point)))
  408. (when syntax-table
  409. (with-syntax-table syntax-table
  410. (let ((end (ignore-errors (scan-lists pos 1 0))))
  411. (when end
  412. (goto-char end)
  413. (buffer-substring-no-properties (1+ pos) (1- end)))))))))
  414. ;;; Accessors and Setters
  415. ;;
  416. ;; Provide four accessors: `org-element-type', `org-element-property'
  417. ;; `org-element-contents' and `org-element-restriction'.
  418. ;;
  419. ;; Setter functions allow modification of elements by side effect.
  420. ;; There is `org-element-put-property', `org-element-set-contents'.
  421. ;; These low-level functions are useful to build a parse tree.
  422. ;;
  423. ;; `org-element-adopt-elements', `org-element-set-element',
  424. ;; `org-element-extract-element' and `org-element-insert-before' are
  425. ;; high-level functions useful to modify a parse tree.
  426. ;;
  427. ;; `org-element-secondary-p' is a predicate used to know if a given
  428. ;; object belongs to a secondary string. `org-element-class' tells if
  429. ;; some parsed data is an element or an object, handling pseudo
  430. ;; elements and objects. `org-element-copy' returns an element or
  431. ;; object, stripping its parent property in the process.
  432. (defsubst org-element-type (element)
  433. "Return type of ELEMENT.
  434. The function returns the type of the element or object provided.
  435. It can also return the following special value:
  436. `plain-text' for a string
  437. `org-data' for a complete document
  438. nil in any other case."
  439. (cond
  440. ((not (consp element)) (and (stringp element) 'plain-text))
  441. ((symbolp (car element)) (car element))))
  442. (defsubst org-element-property (property element)
  443. "Extract the value from the PROPERTY of an ELEMENT."
  444. (if (stringp element) (get-text-property 0 property element)
  445. (plist-get (nth 1 element) property)))
  446. (defsubst org-element-contents (element)
  447. "Extract contents from an ELEMENT."
  448. (cond ((not (consp element)) nil)
  449. ((symbolp (car element)) (nthcdr 2 element))
  450. (t element)))
  451. (defsubst org-element-restriction (element)
  452. "Return restriction associated to ELEMENT.
  453. ELEMENT can be an element, an object or a symbol representing an
  454. element or object type."
  455. (cdr (assq (if (symbolp element) element (org-element-type element))
  456. org-element-object-restrictions)))
  457. (defsubst org-element-put-property (element property value)
  458. "In ELEMENT set PROPERTY to VALUE.
  459. Return modified element."
  460. (if (stringp element) (org-add-props element nil property value)
  461. (setcar (cdr element) (plist-put (nth 1 element) property value))
  462. element))
  463. (defsubst org-element-set-contents (element &rest contents)
  464. "Set ELEMENT's contents to CONTENTS.
  465. Return ELEMENT."
  466. (cond ((null element) contents)
  467. ((not (symbolp (car element))) contents)
  468. ((cdr element) (setcdr (cdr element) contents) element)
  469. (t (nconc element contents))))
  470. (defun org-element-secondary-p (object)
  471. "Non-nil when OBJECT directly belongs to a secondary string.
  472. Return value is the property name, as a keyword, or nil."
  473. (let* ((parent (org-element-property :parent object))
  474. (properties (cdr (assq (org-element-type parent)
  475. org-element-secondary-value-alist))))
  476. (catch 'exit
  477. (dolist (p properties)
  478. (and (memq object (org-element-property p parent))
  479. (throw 'exit p))))))
  480. (defsubst org-element-class (datum &optional parent)
  481. "Return class for ELEMENT, as a symbol.
  482. Class is either `element' or `object'. Optional argument PARENT
  483. is the element or object containing DATUM. It defaults to the
  484. value of DATUM `:parent' property."
  485. (let ((type (org-element-type datum))
  486. (parent (or parent (org-element-property :parent datum))))
  487. (cond
  488. ;; Trivial cases.
  489. ((memq type org-element-all-objects) 'object)
  490. ((memq type org-element-all-elements) 'element)
  491. ;; Special cases.
  492. ((eq type 'org-data) 'element)
  493. ((eq type 'plain-text) 'object)
  494. ((not type) 'object)
  495. ;; Pseudo object or elements. Make a guess about its class.
  496. ;; Basically a pseudo object is contained within another object,
  497. ;; a secondary string or a container element.
  498. ((not parent) 'element)
  499. (t
  500. (let ((parent-type (org-element-type parent)))
  501. (cond ((not parent-type) 'object)
  502. ((memq parent-type org-element-object-containers) 'object)
  503. ((org-element-secondary-p datum) 'object)
  504. (t 'element)))))))
  505. (defsubst org-element-adopt-elements (parent &rest children)
  506. "Append elements to the contents of another element.
  507. PARENT is an element or object. CHILDREN can be elements,
  508. objects, or a strings.
  509. The function takes care of setting `:parent' property for CHILD.
  510. Return parent element."
  511. (declare (indent 1))
  512. (if (not children) parent
  513. ;; Link every child to PARENT. If PARENT is nil, it is a secondary
  514. ;; string: parent is the list itself.
  515. (dolist (child children)
  516. (org-element-put-property child :parent (or parent children)))
  517. ;; Add CHILDREN at the end of PARENT contents.
  518. (when parent
  519. (apply #'org-element-set-contents
  520. parent
  521. (nconc (org-element-contents parent) children)))
  522. ;; Return modified PARENT element.
  523. (or parent children)))
  524. (defun org-element-extract-element (element)
  525. "Extract ELEMENT from parse tree.
  526. Remove element from the parse tree by side-effect, and return it
  527. with its `:parent' property stripped out."
  528. (let ((parent (org-element-property :parent element))
  529. (secondary (org-element-secondary-p element)))
  530. (if secondary
  531. (org-element-put-property
  532. parent secondary
  533. (delq element (org-element-property secondary parent)))
  534. (apply #'org-element-set-contents
  535. parent
  536. (delq element (org-element-contents parent))))
  537. ;; Return ELEMENT with its :parent removed.
  538. (org-element-put-property element :parent nil)))
  539. (defun org-element-insert-before (element location)
  540. "Insert ELEMENT before LOCATION in parse tree.
  541. LOCATION is an element, object or string within the parse tree.
  542. Parse tree is modified by side effect."
  543. (let* ((parent (org-element-property :parent location))
  544. (property (org-element-secondary-p location))
  545. (siblings (if property (org-element-property property parent)
  546. (org-element-contents parent)))
  547. ;; Special case: LOCATION is the first element of an
  548. ;; independent secondary string (e.g. :title property). Add
  549. ;; ELEMENT in-place.
  550. (specialp (and (not property)
  551. (eq siblings parent)
  552. (eq (car parent) location))))
  553. ;; Install ELEMENT at the appropriate LOCATION within SIBLINGS.
  554. (cond (specialp)
  555. ((or (null siblings) (eq (car siblings) location))
  556. (push element siblings))
  557. ((null location) (nconc siblings (list element)))
  558. (t
  559. (let ((index (cl-position location siblings)))
  560. (unless index (error "No location found to insert element"))
  561. (push element (cdr (nthcdr (1- index) siblings))))))
  562. ;; Store SIBLINGS at appropriate place in parse tree.
  563. (cond
  564. (specialp (setcdr parent (copy-sequence parent)) (setcar parent element))
  565. (property (org-element-put-property parent property siblings))
  566. (t (apply #'org-element-set-contents parent siblings)))
  567. ;; Set appropriate :parent property.
  568. (org-element-put-property element :parent parent)))
  569. (defconst org-element--cache-element-properties '(:cached
  570. :org-element--cache-sync-key)
  571. "List of element properties used internally by cache.")
  572. (defun org-element-set-element (old new)
  573. "Replace element or object OLD with element or object NEW.
  574. The function takes care of setting `:parent' property for NEW."
  575. ;; Ensure OLD and NEW have the same parent.
  576. (org-element-put-property new :parent (org-element-property :parent old))
  577. (dolist (p org-element--cache-element-properties)
  578. (when (org-element-property p old)
  579. (org-element-put-property new p (org-element-property p old))))
  580. (if (or (memq (org-element-type old) '(plain-text nil))
  581. (memq (org-element-type new) '(plain-text nil)))
  582. ;; We cannot replace OLD with NEW since one of them is not an
  583. ;; object or element. We take the long path.
  584. (progn (org-element-insert-before new old)
  585. (org-element-extract-element old))
  586. ;; Since OLD is going to be changed into NEW by side-effect, first
  587. ;; make sure that every element or object within NEW has OLD as
  588. ;; parent.
  589. (dolist (blob (org-element-contents new))
  590. (org-element-put-property blob :parent old))
  591. ;; Transfer contents.
  592. (apply #'org-element-set-contents old (org-element-contents new))
  593. ;; Overwrite OLD's properties with NEW's.
  594. (setcar (cdr old) (nth 1 new))
  595. ;; Transfer type.
  596. (setcar old (car new))))
  597. (defun org-element-create (type &optional props &rest children)
  598. "Create a new element of type TYPE.
  599. Optional argument PROPS, when non-nil, is a plist defining the
  600. properties of the element. CHILDREN can be elements, objects or
  601. strings."
  602. (apply #'org-element-adopt-elements (list type props) children))
  603. (defun org-element-copy (datum)
  604. "Return a copy of DATUM.
  605. DATUM is an element, object, string or nil. `:parent' property
  606. is cleared and contents are removed in the process."
  607. (when datum
  608. (let ((type (org-element-type datum)))
  609. (pcase type
  610. (`org-data (list 'org-data nil))
  611. (`plain-text (substring-no-properties datum))
  612. (`nil (copy-sequence datum))
  613. (_
  614. (let ((element-copy (list type (plist-put (copy-sequence (nth 1 datum)) :parent nil))))
  615. ;; We cannot simply return the copies property list. When
  616. ;; DATUM is i.e. a headline, it's property list (`:title'
  617. ;; in case of headline) can contain parsed objects. The
  618. ;; objects will contain `:parent' property set to the DATUM
  619. ;; iteself. When copied, these inner `:parent' propery
  620. ;; values will contain incorrect object decoupled from
  621. ;; DATUM. Changes to the DATUM copy will not longer be
  622. ;; reflected in the `:parent' properties. So, we need to
  623. ;; reassign inner `:parent' propreties to the DATUM copy
  624. ;; explicitly.
  625. (org-element-map element-copy (cons 'plain-text org-element-all-objects)
  626. (lambda (obj) (when (equal datum (org-element-property :parent obj))
  627. (org-element-put-property obj :parent element-copy))))
  628. element-copy))))))
  629. ;;; Greater elements
  630. ;;
  631. ;; For each greater element type, we define a parser and an
  632. ;; interpreter.
  633. ;;
  634. ;; A parser returns the element or object as the list described above.
  635. ;; Most of them accepts no argument. Though, exceptions exist. Hence
  636. ;; every element containing a secondary string (see
  637. ;; `org-element-secondary-value-alist') will accept an optional
  638. ;; argument to toggle parsing of these secondary strings. Moreover,
  639. ;; `item' parser requires current list's structure as its first
  640. ;; element.
  641. ;;
  642. ;; An interpreter accepts two arguments: the list representation of
  643. ;; the element or object, and its contents. The latter may be nil,
  644. ;; depending on the element or object considered. It returns the
  645. ;; appropriate Org syntax, as a string.
  646. ;;
  647. ;; Parsing functions must follow the naming convention:
  648. ;; org-element-TYPE-parser, where TYPE is greater element's type, as
  649. ;; defined in `org-element-greater-elements'.
  650. ;;
  651. ;; Similarly, interpreting functions must follow the naming
  652. ;; convention: org-element-TYPE-interpreter.
  653. ;;
  654. ;; With the exception of `headline' and `item' types, greater elements
  655. ;; cannot contain other greater elements of their own type.
  656. ;;
  657. ;; Beside implementing a parser and an interpreter, adding a new
  658. ;; greater element requires tweaking `org-element--current-element'.
  659. ;; Moreover, the newly defined type must be added to both
  660. ;; `org-element-all-elements' and `org-element-greater-elements'.
  661. ;;;; Center Block
  662. (defun org-element-center-block-parser (limit affiliated)
  663. "Parse a center block.
  664. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  665. the buffer position at the beginning of the first affiliated
  666. keyword and CDR is a plist of affiliated keywords along with
  667. their value.
  668. Return a list whose CAR is `center-block' and CDR is a plist
  669. containing `:begin', `:end', `:contents-begin', `:contents-end',
  670. `:post-blank' and `:post-affiliated' keywords.
  671. Assume point is at the beginning of the block."
  672. (let ((case-fold-search t))
  673. (if (not (save-excursion
  674. (re-search-forward "^[ \t]*#\\+END_CENTER[ \t]*$" limit t)))
  675. ;; Incomplete block: parse it as a paragraph.
  676. (org-element-paragraph-parser limit affiliated)
  677. (let ((block-end-line (match-beginning 0)))
  678. (let* ((begin (car affiliated))
  679. (post-affiliated (point))
  680. ;; Empty blocks have no contents.
  681. (contents-begin (progn (forward-line)
  682. (and (< (point) block-end-line)
  683. (point))))
  684. (contents-end (and contents-begin block-end-line))
  685. (pos-before-blank (progn (goto-char block-end-line)
  686. (forward-line)
  687. (point)))
  688. (end (save-excursion
  689. (skip-chars-forward " \r\t\n" limit)
  690. (if (eobp) (point) (line-beginning-position)))))
  691. (list 'center-block
  692. (nconc
  693. (list :begin begin
  694. :end end
  695. :contents-begin contents-begin
  696. :contents-end contents-end
  697. :post-blank (count-lines pos-before-blank end)
  698. :post-affiliated post-affiliated)
  699. (cdr affiliated))))))))
  700. (defun org-element-center-block-interpreter (_ contents)
  701. "Interpret a center-block element as Org syntax.
  702. CONTENTS is the contents of the element."
  703. (format "#+begin_center\n%s#+end_center" contents))
  704. ;;;; Drawer
  705. (defun org-element-drawer-parser (limit affiliated)
  706. "Parse a drawer.
  707. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  708. the buffer position at the beginning of the first affiliated
  709. keyword and CDR is a plist of affiliated keywords along with
  710. their value.
  711. Return a list whose CAR is `drawer' and CDR is a plist containing
  712. `:drawer-name', `:begin', `:end', `:contents-begin',
  713. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  714. Assume point is at beginning of drawer."
  715. (let ((case-fold-search t))
  716. (if (not (save-excursion
  717. (goto-char (min limit (line-end-position)))
  718. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  719. ;; Incomplete drawer: parse it as a paragraph.
  720. (org-element-paragraph-parser limit affiliated)
  721. (save-excursion
  722. (let* ((drawer-end-line (match-beginning 0))
  723. (name
  724. (progn
  725. (looking-at org-element-drawer-re)
  726. (match-string-no-properties 1)))
  727. (begin (car affiliated))
  728. (post-affiliated (point))
  729. ;; Empty drawers have no contents.
  730. (contents-begin (progn (forward-line)
  731. (and (< (point) drawer-end-line)
  732. (point))))
  733. (contents-end (and contents-begin drawer-end-line))
  734. (pos-before-blank (progn (goto-char drawer-end-line)
  735. (forward-line)
  736. (point)))
  737. (end (progn (skip-chars-forward " \r\t\n" limit)
  738. (if (eobp) (point) (line-beginning-position)))))
  739. (list 'drawer
  740. (nconc
  741. (list :begin begin
  742. :end end
  743. :drawer-name name
  744. :contents-begin contents-begin
  745. :contents-end contents-end
  746. :post-blank (count-lines pos-before-blank end)
  747. :post-affiliated post-affiliated)
  748. (cdr affiliated))))))))
  749. (defun org-element-drawer-interpreter (drawer contents)
  750. "Interpret DRAWER element as Org syntax.
  751. CONTENTS is the contents of the element."
  752. (format ":%s:\n%s:END:"
  753. (org-element-property :drawer-name drawer)
  754. contents))
  755. ;;;; Dynamic Block
  756. (defun org-element-dynamic-block-parser (limit affiliated)
  757. "Parse a dynamic block.
  758. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  759. the buffer position at the beginning of the first affiliated
  760. keyword and CDR is a plist of affiliated keywords along with
  761. their value.
  762. Return a list whose CAR is `dynamic-block' and CDR is a plist
  763. containing `:block-name', `:begin', `:end', `:contents-begin',
  764. `:contents-end', `:arguments', `:post-blank' and
  765. `:post-affiliated' keywords.
  766. Assume point is at beginning of dynamic block."
  767. (let ((case-fold-search t))
  768. (if (not (save-excursion
  769. (re-search-forward "^[ \t]*#\\+END:?[ \t]*$" limit t)))
  770. ;; Incomplete block: parse it as a paragraph.
  771. (org-element-paragraph-parser limit affiliated)
  772. (let ((block-end-line (match-beginning 0)))
  773. (save-excursion
  774. (let* ((name (progn
  775. (looking-at org-element-dynamic-block-open-re)
  776. (match-string-no-properties 1)))
  777. (arguments (match-string-no-properties 2))
  778. (begin (car affiliated))
  779. (post-affiliated (point))
  780. ;; Empty blocks have no contents.
  781. (contents-begin (progn (forward-line)
  782. (and (< (point) block-end-line)
  783. (point))))
  784. (contents-end (and contents-begin block-end-line))
  785. (pos-before-blank (progn (goto-char block-end-line)
  786. (forward-line)
  787. (point)))
  788. (end (progn (skip-chars-forward " \r\t\n" limit)
  789. (if (eobp) (point) (line-beginning-position)))))
  790. (list 'dynamic-block
  791. (nconc
  792. (list :begin begin
  793. :end end
  794. :block-name name
  795. :arguments arguments
  796. :contents-begin contents-begin
  797. :contents-end contents-end
  798. :post-blank (count-lines pos-before-blank end)
  799. :post-affiliated post-affiliated)
  800. (cdr affiliated)))))))))
  801. (defun org-element-dynamic-block-interpreter (dynamic-block contents)
  802. "Interpret DYNAMIC-BLOCK element as Org syntax.
  803. CONTENTS is the contents of the element."
  804. (format "#+begin: %s%s\n%s#+end:"
  805. (org-element-property :block-name dynamic-block)
  806. (let ((args (org-element-property :arguments dynamic-block)))
  807. (if args (concat " " args) ""))
  808. contents))
  809. ;;;; Footnote Definition
  810. (defconst org-element--footnote-separator
  811. (concat org-element-headline-re "\\|"
  812. org-footnote-definition-re "\\|"
  813. "^\\([ \t]*\n\\)\\{2,\\}")
  814. "Regexp used as a footnote definition separator.")
  815. (defun org-element-footnote-definition-parser (limit affiliated)
  816. "Parse a footnote definition.
  817. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  818. the buffer position at the beginning of the first affiliated
  819. keyword and CDR is a plist of affiliated keywords along with
  820. their value.
  821. Return a list whose CAR is `footnote-definition' and CDR is
  822. a plist containing `:label', `:begin' `:end', `:contents-begin',
  823. `:contents-end', `:pre-blank',`:post-blank' and
  824. `:post-affiliated' keywords.
  825. Assume point is at the beginning of the footnote definition."
  826. (save-excursion
  827. (let* ((label (progn (looking-at org-footnote-definition-re)
  828. (match-string-no-properties 1)))
  829. (begin (car affiliated))
  830. (post-affiliated (point))
  831. (end
  832. (save-excursion
  833. (end-of-line)
  834. (cond
  835. ((not
  836. (re-search-forward org-element--footnote-separator limit t))
  837. limit)
  838. ((eq ?\[ (char-after (match-beginning 0)))
  839. ;; At a new footnote definition, make sure we end
  840. ;; before any affiliated keyword above.
  841. (forward-line -1)
  842. (while (and (> (point) post-affiliated)
  843. (looking-at-p org-element--affiliated-re))
  844. (forward-line -1))
  845. (line-beginning-position 2))
  846. ((eq ?* (char-after (match-beginning 0))) (match-beginning 0))
  847. (t (skip-chars-forward " \r\t\n" limit)
  848. (if (= limit (point)) limit (line-beginning-position))))))
  849. (pre-blank 0)
  850. (contents-begin
  851. (progn (search-forward "]")
  852. (skip-chars-forward " \r\t\n" end)
  853. (cond ((= (point) end) nil)
  854. ((= (line-beginning-position) post-affiliated) (point))
  855. (t
  856. (setq pre-blank
  857. (count-lines (line-beginning-position) begin))
  858. (line-beginning-position)))))
  859. (contents-end
  860. (progn (goto-char end)
  861. (skip-chars-backward " \r\t\n")
  862. (line-beginning-position 2))))
  863. (list 'footnote-definition
  864. (nconc
  865. (list :label label
  866. :begin begin
  867. :end end
  868. :contents-begin contents-begin
  869. :contents-end (and contents-begin contents-end)
  870. :pre-blank pre-blank
  871. :post-blank (count-lines contents-end end)
  872. :post-affiliated post-affiliated)
  873. (cdr affiliated))))))
  874. (defun org-element-footnote-definition-interpreter (footnote-definition contents)
  875. "Interpret FOOTNOTE-DEFINITION element as Org syntax.
  876. CONTENTS is the contents of the footnote-definition."
  877. (let ((pre-blank
  878. (min (or (org-element-property :pre-blank footnote-definition)
  879. ;; 0 is specific to paragraphs at the beginning of
  880. ;; the footnote definition, so we use 1 as
  881. ;; a fall-back value, which is more universal.
  882. 1)
  883. ;; Footnote ends after more than two consecutive empty
  884. ;; lines: limit ourselves to 2 newline characters.
  885. 2)))
  886. (concat (format "[fn:%s]" (org-element-property :label footnote-definition))
  887. (if (= pre-blank 0) (concat " " (org-trim contents))
  888. (concat (make-string pre-blank ?\n) contents)))))
  889. ;;;; Headline
  890. (defun org-element--get-node-properties (&optional at-point-p?)
  891. "Return node properties for headline or property drawer at point.
  892. Upcase property names. It avoids confusion between properties
  893. obtained through property drawer and default properties from the
  894. parser (e.g. `:end' and :END:). Return value is a plist.
  895. When AT-POINT-P? is nil, assume that point as at a headline. Otherwise
  896. parse properties for property drawer at point."
  897. (save-excursion
  898. (unless at-point-p?
  899. (forward-line)
  900. (when (looking-at-p org-element-planning-line-re) (forward-line)))
  901. (when (looking-at org-property-drawer-re)
  902. (forward-line)
  903. (let ((end (match-end 0)) properties)
  904. (while (< (line-end-position) end)
  905. (looking-at org-property-re)
  906. (let* ((property-name (concat ":" (upcase (match-string 2))))
  907. (property-name-symbol (intern property-name))
  908. (property-value (match-string-no-properties 3)))
  909. (cond
  910. ((and (plist-member properties property-name-symbol)
  911. (string-match-p "+$" property-name))
  912. (let ((val (plist-get properties property-name-symbol)))
  913. (if (listp val)
  914. (setq properties
  915. (plist-put properties
  916. property-name-symbol
  917. (append (plist-get properties property-name-symbol)
  918. (list property-value))))
  919. (plist-put properties property-name-symbol (list val property-value)))))
  920. (t (setq properties (plist-put properties property-name-symbol property-value)))))
  921. (forward-line))
  922. properties))))
  923. (defun org-element--get-time-properties ()
  924. "Return time properties associated to headline at point.
  925. Return value is a plist."
  926. (save-excursion
  927. (when (progn (forward-line) (looking-at org-element-planning-line-re))
  928. (let ((end (line-end-position))
  929. plist)
  930. (while (re-search-forward org-element-planning-keywords-re end t)
  931. (skip-chars-forward " \t")
  932. (let ((keyword (match-string 0))
  933. (time (org-element-timestamp-parser)))
  934. (cond ((equal keyword org-element-scheduled-keyword)
  935. (setq plist (plist-put plist :scheduled time)))
  936. ((equal keyword org-element-deadline-keyword)
  937. (setq plist (plist-put plist :deadline time)))
  938. (t (setq plist (plist-put plist :closed time))))))
  939. plist))))
  940. (defun org-element-headline-parser (&optional _ raw-secondary-p)
  941. "Parse a headline.
  942. Return a list whose CAR is `headline' and CDR is a plist
  943. containing `:raw-value', `:title', `:begin', `:end',
  944. `:pre-blank', `:contents-begin' and `:contents-end', `:level',
  945. `:priority', `:tags', `:todo-keyword', `:todo-type', `:scheduled',
  946. `:deadline', `:closed', `:archivedp', `:commentedp'
  947. `:footnote-section-p', `:post-blank' and `:post-affiliated'
  948. keywords.
  949. The plist also contains any property set in the property drawer,
  950. with its name in upper cases and colons added at the
  951. beginning (e.g., `:CUSTOM_ID').
  952. When RAW-SECONDARY-P is non-nil, headline's title will not be
  953. parsed as a secondary string, but as a plain string instead.
  954. Assume point is at beginning of the headline."
  955. (save-excursion
  956. (let* ((begin (point))
  957. (true-level (prog1 (skip-chars-forward "*")
  958. (skip-chars-forward " \t")))
  959. (level (org-reduced-level true-level))
  960. (todo (and org-todo-regexp
  961. (let (case-fold-search) (looking-at (concat org-todo-regexp " ")))
  962. (progn (goto-char (match-end 0))
  963. (skip-chars-forward " \t")
  964. (match-string 1))))
  965. (todo-type
  966. (and todo (if (member todo org-done-keywords) 'done 'todo)))
  967. (priority (and (looking-at "\\[#.\\][ \t]*")
  968. (progn (goto-char (match-end 0))
  969. (aref (match-string 0) 2))))
  970. (commentedp
  971. (and (let ((case-fold-search nil))
  972. (looking-at org-element-comment-string))
  973. (goto-char (match-end 0))))
  974. (title-start (prog1 (point)
  975. (unless (or todo priority commentedp)
  976. ;; Headline like "* :tag:"
  977. (skip-chars-backward " \t"))))
  978. (tags (when (re-search-forward
  979. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  980. (line-end-position)
  981. 'move)
  982. (goto-char (match-beginning 0))
  983. (org-split-string (match-string 1) ":")))
  984. (title-end (point))
  985. (raw-value (org-trim
  986. (buffer-substring-no-properties title-start title-end)))
  987. (archivedp (member org-element-archive-tag tags))
  988. (footnote-section-p (and org-footnote-section
  989. (string= org-footnote-section raw-value)))
  990. (standard-props (org-element--get-node-properties))
  991. (time-props (org-element--get-time-properties))
  992. (end
  993. (save-excursion
  994. (let ((re (rx-to-string
  995. `(seq line-start (** 1 ,true-level "*") " "))))
  996. (if (re-search-forward re nil t)
  997. (line-beginning-position)
  998. (point-max)))))
  999. (contents-begin (save-excursion
  1000. (forward-line)
  1001. (skip-chars-forward " \r\t\n" end)
  1002. (and (/= (point) end) (line-beginning-position))))
  1003. (contents-end (and contents-begin
  1004. (progn (goto-char end)
  1005. (skip-chars-backward " \r\t\n")
  1006. (line-beginning-position 2))))
  1007. (robust-begin (and contents-begin
  1008. (progn (goto-char contents-begin)
  1009. (when (looking-at-p org-element-planning-line-re)
  1010. (forward-line))
  1011. (when (looking-at org-property-drawer-re)
  1012. (goto-char (match-end 0)))
  1013. ;; If there is :pre-blank, we
  1014. ;; need to be careful about
  1015. ;; robust beginning.
  1016. (max (if (< (+ 2 contents-begin) contents-end)
  1017. (+ 2 contents-begin)
  1018. 0)
  1019. (point)))))
  1020. (robust-end (and robust-begin
  1021. (when (> (- contents-end 2) robust-begin)
  1022. (- contents-end 2)))))
  1023. (unless robust-end (setq robust-begin nil))
  1024. (let ((headline
  1025. (list 'headline
  1026. (nconc
  1027. (list :raw-value raw-value
  1028. :begin begin
  1029. :end end
  1030. :pre-blank
  1031. (if (not contents-begin) 0
  1032. (1- (count-lines begin contents-begin)))
  1033. :contents-begin contents-begin
  1034. :contents-end contents-end
  1035. :robust-begin robust-begin
  1036. :robust-end robust-end
  1037. :level level
  1038. :priority priority
  1039. :tags tags
  1040. :todo-keyword todo
  1041. :todo-type todo-type
  1042. :post-blank
  1043. (if contents-end
  1044. (count-lines contents-end end)
  1045. (1- (count-lines begin end)))
  1046. :footnote-section-p footnote-section-p
  1047. :archivedp archivedp
  1048. :commentedp commentedp
  1049. :post-affiliated begin)
  1050. time-props
  1051. standard-props))))
  1052. (org-element-put-property
  1053. headline :title
  1054. (if raw-secondary-p raw-value
  1055. (org-element--parse-objects
  1056. (progn (goto-char title-start)
  1057. (skip-chars-forward " \t")
  1058. (point))
  1059. (progn (goto-char title-end)
  1060. (skip-chars-backward " \t")
  1061. (point))
  1062. nil
  1063. (org-element-restriction 'headline)
  1064. headline)))))))
  1065. (defun org-element-headline-interpreter (headline contents)
  1066. "Interpret HEADLINE element as Org syntax.
  1067. CONTENTS is the contents of the element."
  1068. (let* ((level (org-element-property :level headline))
  1069. (todo (org-element-property :todo-keyword headline))
  1070. (priority (org-element-property :priority headline))
  1071. (title (org-element-interpret-data
  1072. (org-element-property :title headline)))
  1073. (tags (let ((tag-list (org-element-property :tags headline)))
  1074. (and tag-list
  1075. (format ":%s:" (mapconcat #'identity tag-list ":")))))
  1076. (commentedp (org-element-property :commentedp headline))
  1077. (pre-blank (or (org-element-property :pre-blank headline) 0))
  1078. (heading
  1079. (concat (make-string (if org-odd-levels-only (1- (* level 2)) level)
  1080. ?*)
  1081. (and todo (concat " " todo))
  1082. (and commentedp (concat " " org-element-comment-string))
  1083. (and priority (format " [#%c]" priority))
  1084. " "
  1085. (if (and org-footnote-section
  1086. (org-element-property :footnote-section-p headline))
  1087. org-footnote-section
  1088. title))))
  1089. (concat
  1090. heading
  1091. ;; Align tags.
  1092. (when tags
  1093. (cond
  1094. ((zerop org-tags-column) (format " %s" tags))
  1095. ((< org-tags-column 0)
  1096. (concat
  1097. (make-string
  1098. (max (- (+ org-tags-column (length heading) (length tags))) 1)
  1099. ?\s)
  1100. tags))
  1101. (t
  1102. (concat
  1103. (make-string (max (- org-tags-column (length heading)) 1) ?\s)
  1104. tags))))
  1105. (make-string (1+ pre-blank) ?\n)
  1106. contents)))
  1107. ;;;; org-data
  1108. (defun org-element--get-global-node-properties ()
  1109. "Return node properties associated with the whole Org buffer.
  1110. Upcase property names. It avoids confusion between properties
  1111. obtained through property drawer and default properties from the
  1112. parser (e.g. `:end' and :END:). Return value is a plist."
  1113. (org-with-wide-buffer
  1114. (goto-char (point-min))
  1115. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1116. (org-element--get-node-properties t)))
  1117. (defvar org-element-org-data-parser--recurse nil)
  1118. (defun org-element-org-data-parser (&optional _)
  1119. "Parse org-data."
  1120. (org-with-wide-buffer
  1121. (let* ((begin 1)
  1122. (contents-begin (progn
  1123. (goto-char 1)
  1124. (org-skip-whitespace)
  1125. (beginning-of-line)
  1126. (point)))
  1127. (end (point-max))
  1128. (pos-before-blank (progn (goto-char (point-max))
  1129. (skip-chars-backward " \r\t\n")
  1130. (line-beginning-position 2)))
  1131. (robust-end (when (> (- pos-before-blank 2) contents-begin)
  1132. (- pos-before-blank 2)))
  1133. (robust-begin (when (and robust-end
  1134. (< (+ 2 contents-begin) pos-before-blank))
  1135. (or
  1136. (org-with-wide-buffer
  1137. (goto-char (point-min))
  1138. (while (and (org-at-comment-p) (bolp)) (forward-line))
  1139. (when (looking-at org-property-drawer-re)
  1140. (goto-char (match-end 0))
  1141. (skip-chars-backward " \t")
  1142. (min robust-end (point))))
  1143. (+ 2 contents-begin))))
  1144. (category (cond ((null org-category)
  1145. (when (with-current-buffer
  1146. (or (buffer-base-buffer)
  1147. (current-buffer))
  1148. buffer-file-name)
  1149. (file-name-sans-extension
  1150. (file-name-nondirectory
  1151. (with-current-buffer
  1152. (or (buffer-base-buffer)
  1153. (current-buffer))
  1154. buffer-file-name)))))
  1155. ((symbolp org-category) (symbol-name org-category))
  1156. (t org-category)))
  1157. (category (catch 'buffer-category
  1158. (unless org-element-org-data-parser--recurse
  1159. (org-with-point-at end
  1160. ;; Avoid recusrive calls from
  1161. ;; `org-element-at-point-no-context'.
  1162. (let ((org-element-org-data-parser--recurse t))
  1163. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  1164. (org-element-with-disabled-cache
  1165. (let ((element (org-element-at-point-no-context)))
  1166. (when (eq (org-element-type element) 'keyword)
  1167. (throw 'buffer-category
  1168. (org-element-property :value element)))))))))
  1169. category))
  1170. (properties (org-element--get-global-node-properties)))
  1171. (unless (plist-get properties :CATEGORY)
  1172. (setq properties (plist-put properties :CATEGORY category)))
  1173. (list 'org-data
  1174. (nconc
  1175. (list :begin begin
  1176. :contents-begin contents-begin
  1177. :contents-end pos-before-blank
  1178. :end end
  1179. :robust-begin robust-begin
  1180. :robust-end robust-end
  1181. :post-blank (count-lines pos-before-blank end)
  1182. :post-affiliated begin
  1183. :path (buffer-file-name)
  1184. :mode 'org-data)
  1185. properties)))))
  1186. (defun org-element-org-data-interpreter (_ contents)
  1187. "Interpret ORG-DATA element as Org syntax.
  1188. CONTENTS is the contents of the element."
  1189. contents)
  1190. ;;;; Inlinetask
  1191. (defun org-element-inlinetask-parser (limit &optional raw-secondary-p)
  1192. "Parse an inline task.
  1193. Return a list whose CAR is `inlinetask' and CDR is a plist
  1194. containing `:title', `:begin', `:end', `:pre-blank',
  1195. `:contents-begin' and `:contents-end', `:level', `:priority',
  1196. `:raw-value', `:tags', `:todo-keyword', `:todo-type',
  1197. `:scheduled', `:deadline', `:closed', `:post-blank' and
  1198. `:post-affiliated' keywords.
  1199. The plist also contains any property set in the property drawer,
  1200. with its name in upper cases and colons added at the
  1201. beginning (e.g., `:CUSTOM_ID').
  1202. When optional argument RAW-SECONDARY-P is non-nil, inline-task's
  1203. title will not be parsed as a secondary string, but as a plain
  1204. string instead.
  1205. Assume point is at beginning of the inline task."
  1206. (save-excursion
  1207. (let* ((begin (point))
  1208. (level (prog1 (org-reduced-level (skip-chars-forward "*"))
  1209. (skip-chars-forward " \t")))
  1210. (todo (and org-todo-regexp
  1211. (let (case-fold-search) (looking-at org-todo-regexp))
  1212. (progn (goto-char (match-end 0))
  1213. (skip-chars-forward " \t")
  1214. (match-string 0))))
  1215. (todo-type (and todo
  1216. (if (member todo org-done-keywords) 'done 'todo)))
  1217. (priority (and (looking-at "\\[#.\\][ \t]*")
  1218. (progn (goto-char (match-end 0))
  1219. (aref (match-string 0) 2))))
  1220. (title-start (point))
  1221. (tags (when (re-search-forward
  1222. "[ \t]+\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"
  1223. (line-end-position)
  1224. 'move)
  1225. (goto-char (match-beginning 0))
  1226. (org-split-string (match-string 1) ":")))
  1227. (title-end (point))
  1228. (raw-value (org-trim
  1229. (buffer-substring-no-properties title-start title-end)))
  1230. (task-end (save-excursion
  1231. (end-of-line)
  1232. (and (re-search-forward org-element-headline-re limit t)
  1233. (looking-at-p "[ \t]*END[ \t]*$")
  1234. (line-beginning-position))))
  1235. (standard-props (and task-end (org-element--get-node-properties)))
  1236. (time-props (and task-end (org-element--get-time-properties)))
  1237. (contents-begin (and task-end
  1238. (< (point) task-end)
  1239. (progn
  1240. (forward-line)
  1241. (skip-chars-forward " \t\n")
  1242. (line-beginning-position))))
  1243. (contents-end (and contents-begin task-end))
  1244. (end (progn (when task-end (goto-char task-end))
  1245. (forward-line)
  1246. (skip-chars-forward " \r\t\n" limit)
  1247. (if (eobp) (point) (line-beginning-position))))
  1248. (inlinetask
  1249. (list 'inlinetask
  1250. (nconc
  1251. (list :raw-value raw-value
  1252. :begin begin
  1253. :end end
  1254. :pre-blank
  1255. (if (not contents-begin) 0
  1256. (1- (count-lines begin contents-begin)))
  1257. :contents-begin contents-begin
  1258. :contents-end contents-end
  1259. :level level
  1260. :priority priority
  1261. :tags tags
  1262. :todo-keyword todo
  1263. :todo-type todo-type
  1264. :post-blank (1- (count-lines (or task-end begin) end))
  1265. :post-affiliated begin)
  1266. time-props
  1267. standard-props))))
  1268. (org-element-put-property
  1269. inlinetask :title
  1270. (if raw-secondary-p raw-value
  1271. (org-element--parse-objects
  1272. (progn (goto-char title-start)
  1273. (skip-chars-forward " \t")
  1274. (point))
  1275. (progn (goto-char title-end)
  1276. (skip-chars-backward " \t")
  1277. (point))
  1278. nil
  1279. (org-element-restriction 'inlinetask)
  1280. inlinetask))))))
  1281. (defun org-element-inlinetask-interpreter (inlinetask contents)
  1282. "Interpret INLINETASK element as Org syntax.
  1283. CONTENTS is the contents of inlinetask."
  1284. (let* ((level (org-element-property :level inlinetask))
  1285. (todo (org-element-property :todo-keyword inlinetask))
  1286. (priority (org-element-property :priority inlinetask))
  1287. (title (org-element-interpret-data
  1288. (org-element-property :title inlinetask)))
  1289. (tags (let ((tag-list (org-element-property :tags inlinetask)))
  1290. (and tag-list
  1291. (format ":%s:" (mapconcat 'identity tag-list ":")))))
  1292. (task (concat (make-string level ?*)
  1293. (and todo (concat " " todo))
  1294. (and priority (format " [#%c]" priority))
  1295. (and title (concat " " title)))))
  1296. (concat task
  1297. ;; Align tags.
  1298. (when tags
  1299. (cond
  1300. ((zerop org-tags-column) (format " %s" tags))
  1301. ((< org-tags-column 0)
  1302. (concat
  1303. (make-string
  1304. (max (- (+ org-tags-column (length task) (length tags))) 1)
  1305. ?\s)
  1306. tags))
  1307. (t
  1308. (concat
  1309. (make-string (max (- org-tags-column (length task)) 1) ?\s)
  1310. tags))))
  1311. ;; Prefer degenerate inlinetasks when there are no
  1312. ;; contents.
  1313. (when contents
  1314. (concat "\n"
  1315. contents
  1316. (make-string level ?*) " end")))))
  1317. ;;;; Item
  1318. (defun org-element-item-parser (_ struct &optional raw-secondary-p)
  1319. "Parse an item.
  1320. STRUCT is the structure of the plain list.
  1321. Return a list whose CAR is `item' and CDR is a plist containing
  1322. `:bullet', `:begin', `:end', `:contents-begin', `:contents-end',
  1323. `:checkbox', `:counter', `:tag', `:structure', `:pre-blank',
  1324. `:post-blank' and `:post-affiliated' keywords.
  1325. When optional argument RAW-SECONDARY-P is non-nil, item's tag, if
  1326. any, will not be parsed as a secondary string, but as a plain
  1327. string instead.
  1328. Assume point is at the beginning of the item."
  1329. (save-excursion
  1330. (beginning-of-line)
  1331. (looking-at org-list-full-item-re)
  1332. (let* ((begin (point))
  1333. (bullet (match-string-no-properties 1))
  1334. (checkbox (let ((box (match-string 3)))
  1335. (cond ((equal "[ ]" box) 'off)
  1336. ((equal "[X]" box) 'on)
  1337. ((equal "[-]" box) 'trans))))
  1338. (counter (let ((c (match-string 2)))
  1339. (save-match-data
  1340. (cond
  1341. ((not c) nil)
  1342. ((string-match "[A-Za-z]" c)
  1343. (- (string-to-char (upcase (match-string 0 c)))
  1344. 64))
  1345. ((string-match "[0-9]+" c)
  1346. (string-to-number (match-string 0 c)))))))
  1347. (end (progn (goto-char (nth 6 (assq (point) struct)))
  1348. (if (bolp) (point) (line-beginning-position 2))))
  1349. (pre-blank 0)
  1350. (contents-begin
  1351. (progn
  1352. (goto-char
  1353. ;; Ignore tags in un-ordered lists: they are just
  1354. ;; a part of item's body.
  1355. (if (and (match-beginning 4)
  1356. (save-match-data (string-match "[.)]" bullet)))
  1357. (match-beginning 4)
  1358. (match-end 0)))
  1359. (skip-chars-forward " \r\t\n" end)
  1360. (cond ((= (point) end) nil)
  1361. ;; If first line isn't empty, contents really
  1362. ;; start at the text after item's meta-data.
  1363. ((= (line-beginning-position) begin) (point))
  1364. (t
  1365. (setq pre-blank
  1366. (count-lines (line-beginning-position) begin))
  1367. (line-beginning-position)))))
  1368. (contents-end (and contents-begin
  1369. (progn (goto-char end)
  1370. (skip-chars-backward " \r\t\n")
  1371. (line-beginning-position 2))))
  1372. (item
  1373. (list 'item
  1374. (list :bullet bullet
  1375. :begin begin
  1376. :end end
  1377. :contents-begin contents-begin
  1378. :contents-end contents-end
  1379. :checkbox checkbox
  1380. :counter counter
  1381. :structure struct
  1382. :pre-blank pre-blank
  1383. :post-blank (count-lines (or contents-end begin) end)
  1384. :post-affiliated begin))))
  1385. (org-element-put-property
  1386. item :tag
  1387. (let ((raw (org-list-get-tag begin struct)))
  1388. (when raw
  1389. (if raw-secondary-p raw
  1390. (org-element--parse-objects
  1391. (match-beginning 4) (match-end 4) nil
  1392. (org-element-restriction 'item)
  1393. item))))))))
  1394. (defun org-element-item-interpreter (item contents)
  1395. "Interpret ITEM element as Org syntax.
  1396. CONTENTS is the contents of the element."
  1397. (let ((tag (pcase (org-element-property :tag item)
  1398. (`nil nil)
  1399. (tag (format "%s :: " (org-element-interpret-data tag)))))
  1400. (bullet
  1401. (org-list-bullet-string
  1402. (cond
  1403. ((not (string-match-p "[0-9a-zA-Z]"
  1404. (org-element-property :bullet item))) "- ")
  1405. ((eq org-plain-list-ordered-item-terminator ?\)) "1)")
  1406. (t "1.")))))
  1407. (concat
  1408. bullet
  1409. (pcase (org-element-property :counter item)
  1410. (`nil nil)
  1411. (counter (format "[@%d] " counter)))
  1412. (pcase (org-element-property :checkbox item)
  1413. (`on "[X] ")
  1414. (`off "[ ] ")
  1415. (`trans "[-] ")
  1416. (_ nil))
  1417. tag
  1418. (when contents
  1419. (let* ((ind (make-string (if tag 5 (length bullet)) ?\s))
  1420. (pre-blank
  1421. (min (or (org-element-property :pre-blank item)
  1422. ;; 0 is specific to paragraphs at the
  1423. ;; beginning of the item, so we use 1 as
  1424. ;; a fall-back value, which is more universal.
  1425. 1)
  1426. ;; Lists ends after more than two consecutive
  1427. ;; empty lines: limit ourselves to 2 newline
  1428. ;; characters.
  1429. 2))
  1430. (contents (replace-regexp-in-string
  1431. "\\(^\\)[ \t]*\\S-" ind contents nil nil 1)))
  1432. (if (= pre-blank 0) (org-trim contents)
  1433. (concat (make-string pre-blank ?\n) contents)))))))
  1434. ;;;; Plain List
  1435. (defun org-element--list-struct (limit)
  1436. ;; Return structure of list at point. Internal function. See
  1437. ;; `org-list-struct' for details.
  1438. (let ((case-fold-search t)
  1439. (top-ind limit)
  1440. (item-re (org-item-re))
  1441. (inlinetask-re (and (featurep 'org-inlinetask)
  1442. (boundp 'org-inlinetask-min-level)
  1443. (boundp 'org-inlinetask-max-level)
  1444. (format "^\\*\\{%d,%d\\}+ "
  1445. org-inlinetask-min-level
  1446. org-inlinetask-max-level)))
  1447. items struct)
  1448. (save-excursion
  1449. (catch :exit
  1450. (while t
  1451. (cond
  1452. ;; At limit: end all items.
  1453. ((>= (point) limit)
  1454. (let ((end (progn (skip-chars-backward " \r\t\n")
  1455. (line-beginning-position 2))))
  1456. (dolist (item items) (setcar (nthcdr 6 item) end)))
  1457. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1458. ;; At list end: end all items.
  1459. ((looking-at org-list-end-re)
  1460. (dolist (item items) (setcar (nthcdr 6 item) (point)))
  1461. (throw :exit (sort (nconc items struct) #'car-less-than-car)))
  1462. ;; At a new item: end previous sibling.
  1463. ((looking-at item-re)
  1464. (let ((ind (save-excursion (skip-chars-forward " \t")
  1465. (current-column))))
  1466. (setq top-ind (min top-ind ind))
  1467. (while (and items (<= ind (nth 1 (car items))))
  1468. (let ((item (pop items)))
  1469. (setcar (nthcdr 6 item) (point))
  1470. (push item struct)))
  1471. (push (progn (looking-at org-list-full-item-re)
  1472. (let ((bullet (match-string-no-properties 1)))
  1473. (list (point)
  1474. ind
  1475. bullet
  1476. (match-string-no-properties 2) ; counter
  1477. (match-string-no-properties 3) ; checkbox
  1478. ;; Description tag.
  1479. (and (save-match-data
  1480. (string-match "[-+*]" bullet))
  1481. (match-string-no-properties 4))
  1482. ;; Ending position, unknown so far.
  1483. nil)))
  1484. items))
  1485. (forward-line))
  1486. ;; Skip empty lines.
  1487. ((looking-at "^[ \t]*$") (forward-line))
  1488. ;; Skip inline tasks and blank lines along the way.
  1489. ((and inlinetask-re (looking-at inlinetask-re))
  1490. (forward-line)
  1491. (let ((origin (point)))
  1492. (when (re-search-forward inlinetask-re limit t)
  1493. (if (looking-at-p "END[ \t]*$") (forward-line)
  1494. (goto-char origin)))))
  1495. ;; At some text line. Check if it ends any previous item.
  1496. (t
  1497. (let ((ind (save-excursion
  1498. (skip-chars-forward " \t")
  1499. (current-column)))
  1500. (end (save-excursion
  1501. (skip-chars-backward " \r\t\n")
  1502. (line-beginning-position 2))))
  1503. (while (<= ind (nth 1 (car items)))
  1504. (let ((item (pop items)))
  1505. (setcar (nthcdr 6 item) end)
  1506. (push item struct)
  1507. (unless items
  1508. (throw :exit (sort struct #'car-less-than-car))))))
  1509. ;; Skip blocks (any type) and drawers contents.
  1510. (cond
  1511. ((and (looking-at "[ \t]*#\\+BEGIN\\(:\\|_\\S-+\\)")
  1512. (re-search-forward
  1513. (format "^[ \t]*#\\+END%s[ \t]*$" (match-string 1))
  1514. limit t)))
  1515. ((and (looking-at org-element-drawer-re)
  1516. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t))))
  1517. (forward-line))))))))
  1518. (defun org-element-plain-list-parser (limit affiliated structure)
  1519. "Parse a plain list.
  1520. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1521. the buffer position at the beginning of the first affiliated
  1522. keyword and CDR is a plist of affiliated keywords along with
  1523. their value. STRUCTURE is the structure of the plain list being
  1524. parsed.
  1525. Return a list whose CAR is `plain-list' and CDR is a plist
  1526. containing `:type', `:begin', `:end', `:contents-begin' and
  1527. `:contents-end', `:structure', `:post-blank' and
  1528. `:post-affiliated' keywords.
  1529. Assume point is at the beginning of the list."
  1530. (save-excursion
  1531. (let* ((struct (or structure (org-element--list-struct limit)))
  1532. (type (cond ((looking-at-p "[ \t]*[A-Za-z0-9]") 'ordered)
  1533. ((nth 5 (assq (point) struct)) 'descriptive)
  1534. (t 'unordered)))
  1535. (contents-begin (point))
  1536. (begin (car affiliated))
  1537. (contents-end (let* ((item (assq contents-begin struct))
  1538. (ind (nth 1 item))
  1539. (pos (nth 6 item)))
  1540. (while (and (setq item (assq pos struct))
  1541. (= (nth 1 item) ind))
  1542. (setq pos (nth 6 item)))
  1543. pos))
  1544. (end (progn (goto-char contents-end)
  1545. (skip-chars-forward " \r\t\n" limit)
  1546. (if (= (point) limit) limit (line-beginning-position)))))
  1547. ;; Return value.
  1548. (list 'plain-list
  1549. (nconc
  1550. (list :type type
  1551. :begin begin
  1552. :end end
  1553. :contents-begin contents-begin
  1554. :contents-end contents-end
  1555. :structure struct
  1556. :post-blank (count-lines contents-end end)
  1557. :post-affiliated contents-begin)
  1558. (cdr affiliated))))))
  1559. (defun org-element-plain-list-interpreter (_ contents)
  1560. "Interpret plain-list element as Org syntax.
  1561. CONTENTS is the contents of the element."
  1562. (with-temp-buffer
  1563. (insert contents)
  1564. (goto-char (point-min))
  1565. (org-list-repair)
  1566. (buffer-string)))
  1567. ;;;; Property Drawer
  1568. (defun org-element-property-drawer-parser (limit)
  1569. "Parse a property drawer.
  1570. LIMIT bounds the search.
  1571. Return a list whose car is `property-drawer' and cdr is a plist
  1572. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1573. `:post-blank' and `:post-affiliated' keywords.
  1574. Assume point is at the beginning of the property drawer."
  1575. (save-excursion
  1576. (let ((case-fold-search t)
  1577. (begin (point))
  1578. (contents-begin (line-beginning-position 2)))
  1579. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)
  1580. (let ((contents-end (and (> (match-beginning 0) contents-begin)
  1581. (match-beginning 0)))
  1582. (before-blank (progn (forward-line) (point)))
  1583. (end (progn (skip-chars-forward " \r\t\n" limit)
  1584. (if (eobp) (point) (line-beginning-position)))))
  1585. (list 'property-drawer
  1586. (list :begin begin
  1587. :end end
  1588. :contents-begin (and contents-end contents-begin)
  1589. :contents-end contents-end
  1590. :post-blank (count-lines before-blank end)
  1591. :post-affiliated begin))))))
  1592. (defun org-element-property-drawer-interpreter (_ contents)
  1593. "Interpret property-drawer element as Org syntax.
  1594. CONTENTS is the properties within the drawer."
  1595. (format ":PROPERTIES:\n%s:END:" contents))
  1596. ;;;; Quote Block
  1597. (defun org-element-quote-block-parser (limit affiliated)
  1598. "Parse a quote block.
  1599. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1600. the buffer position at the beginning of the first affiliated
  1601. keyword and CDR is a plist of affiliated keywords along with
  1602. their value.
  1603. Return a list whose CAR is `quote-block' and CDR is a plist
  1604. containing `:begin', `:end', `:contents-begin', `:contents-end',
  1605. `:post-blank' and `:post-affiliated' keywords.
  1606. Assume point is at the beginning of the block."
  1607. (let ((case-fold-search t))
  1608. (if (not (save-excursion
  1609. (re-search-forward "^[ \t]*#\\+END_QUOTE[ \t]*$" limit t)))
  1610. ;; Incomplete block: parse it as a paragraph.
  1611. (org-element-paragraph-parser limit affiliated)
  1612. (let ((block-end-line (match-beginning 0)))
  1613. (save-excursion
  1614. (let* ((begin (car affiliated))
  1615. (post-affiliated (point))
  1616. ;; Empty blocks have no contents.
  1617. (contents-begin (progn (forward-line)
  1618. (and (< (point) block-end-line)
  1619. (point))))
  1620. (contents-end (and contents-begin block-end-line))
  1621. (pos-before-blank (progn (goto-char block-end-line)
  1622. (forward-line)
  1623. (point)))
  1624. (end (progn (skip-chars-forward " \r\t\n" limit)
  1625. (if (eobp) (point) (line-beginning-position)))))
  1626. (list 'quote-block
  1627. (nconc
  1628. (list :begin begin
  1629. :end end
  1630. :contents-begin contents-begin
  1631. :contents-end contents-end
  1632. :post-blank (count-lines pos-before-blank end)
  1633. :post-affiliated post-affiliated)
  1634. (cdr affiliated)))))))))
  1635. (defun org-element-quote-block-interpreter (_ contents)
  1636. "Interpret quote-block element as Org syntax.
  1637. CONTENTS is the contents of the element."
  1638. (format "#+begin_quote\n%s#+end_quote" contents))
  1639. ;;;; Section
  1640. (defun org-element-section-parser (_)
  1641. "Parse a section.
  1642. Return a list whose CAR is `section' and CDR is a plist
  1643. containing `:begin', `:end', `:contents-begin', `contents-end',
  1644. `:post-blank' and `:post-affiliated' keywords."
  1645. (save-excursion
  1646. ;; Beginning of section is the beginning of the first non-blank
  1647. ;; line after previous headline.
  1648. (let* ((begin (point))
  1649. (end (progn (org-with-limited-levels (outline-next-heading))
  1650. (point)))
  1651. (pos-before-blank (progn (skip-chars-backward " \r\t\n")
  1652. (line-beginning-position 2)))
  1653. (robust-end (when (> (- pos-before-blank 2) begin)
  1654. (- pos-before-blank 2)))
  1655. (robust-begin (when robust-end begin))
  1656. )
  1657. (list 'section
  1658. (list :begin begin
  1659. :end end
  1660. :contents-begin begin
  1661. :contents-end pos-before-blank
  1662. :robust-begin robust-begin
  1663. :robust-end robust-end
  1664. :post-blank (count-lines pos-before-blank end)
  1665. :post-affiliated begin)))))
  1666. (defun org-element-section-interpreter (_ contents)
  1667. "Interpret section element as Org syntax.
  1668. CONTENTS is the contents of the element."
  1669. contents)
  1670. ;;;; Special Block
  1671. (defun org-element-special-block-parser (limit affiliated)
  1672. "Parse a special block.
  1673. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1674. the buffer position at the beginning of the first affiliated
  1675. keyword and CDR is a plist of affiliated keywords along with
  1676. their value.
  1677. Return a list whose CAR is `special-block' and CDR is a plist
  1678. containing `:type', `:begin', `:end', `:contents-begin',
  1679. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  1680. Assume point is at the beginning of the block."
  1681. (let* ((case-fold-search t)
  1682. (type (progn (looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  1683. (match-string-no-properties 1))))
  1684. (if (not (save-excursion
  1685. (re-search-forward
  1686. (format "^[ \t]*#\\+END_%s[ \t]*$" (regexp-quote type))
  1687. limit t)))
  1688. ;; Incomplete block: parse it as a paragraph.
  1689. (org-element-paragraph-parser limit affiliated)
  1690. (let ((block-end-line (match-beginning 0)))
  1691. (save-excursion
  1692. (let* ((begin (car affiliated))
  1693. (post-affiliated (point))
  1694. ;; Empty blocks have no contents.
  1695. (contents-begin (progn (forward-line)
  1696. (and (< (point) block-end-line)
  1697. (point))))
  1698. (contents-end (and contents-begin block-end-line))
  1699. (pos-before-blank (progn (goto-char block-end-line)
  1700. (forward-line)
  1701. (point)))
  1702. (end (progn (skip-chars-forward " \r\t\n" limit)
  1703. (if (eobp) (point) (line-beginning-position)))))
  1704. (list 'special-block
  1705. (nconc
  1706. (list :type type
  1707. :begin begin
  1708. :end end
  1709. :contents-begin contents-begin
  1710. :contents-end contents-end
  1711. :post-blank (count-lines pos-before-blank end)
  1712. :post-affiliated post-affiliated)
  1713. (cdr affiliated)))))))))
  1714. (defun org-element-special-block-interpreter (special-block contents)
  1715. "Interpret SPECIAL-BLOCK element as Org syntax.
  1716. CONTENTS is the contents of the element."
  1717. (let ((block-type (org-element-property :type special-block)))
  1718. (format "#+begin_%s\n%s#+end_%s" block-type contents block-type)))
  1719. ;;; Elements
  1720. ;;
  1721. ;; For each element, a parser and an interpreter are also defined.
  1722. ;; Both follow the same naming convention used for greater elements.
  1723. ;;
  1724. ;; Also, as for greater elements, adding a new element type is done
  1725. ;; through the following steps: implement a parser and an interpreter,
  1726. ;; tweak `org-element--current-element' so that it recognizes the new
  1727. ;; type and add that new type to `org-element-all-elements'.
  1728. ;;;; Babel Call
  1729. (defun org-element-babel-call-parser (limit affiliated)
  1730. "Parse a babel call.
  1731. LIMIT bounds the search. AFFILIATED is a list of which car is
  1732. the buffer position at the beginning of the first affiliated
  1733. keyword and cdr is a plist of affiliated keywords along with
  1734. their value.
  1735. Return a list whose car is `babel-call' and cdr is a plist
  1736. containing `:call', `:inside-header', `:arguments',
  1737. `:end-header', `:begin', `:end', `:value', `:post-blank' and
  1738. `:post-affiliated' as keywords."
  1739. (save-excursion
  1740. (let* ((begin (car affiliated))
  1741. (post-affiliated (point))
  1742. (before-blank (line-beginning-position 2))
  1743. (value (progn (search-forward ":" before-blank t)
  1744. (skip-chars-forward " \t")
  1745. (org-trim
  1746. (buffer-substring-no-properties
  1747. (point) (line-end-position)))))
  1748. (call
  1749. (or (org-string-nw-p
  1750. (buffer-substring-no-properties
  1751. (point) (progn (skip-chars-forward "^[]()" before-blank)
  1752. (point))))))
  1753. (inside-header (org-element--parse-paired-brackets ?\[))
  1754. (arguments (org-string-nw-p
  1755. (org-element--parse-paired-brackets ?\()))
  1756. (end-header
  1757. (org-string-nw-p
  1758. (org-trim
  1759. (buffer-substring-no-properties (point) (line-end-position)))))
  1760. (end (progn (forward-line)
  1761. (skip-chars-forward " \r\t\n" limit)
  1762. (if (eobp) (point) (line-beginning-position)))))
  1763. (list 'babel-call
  1764. (nconc
  1765. (list :call call
  1766. :inside-header inside-header
  1767. :arguments arguments
  1768. :end-header end-header
  1769. :begin begin
  1770. :end end
  1771. :value value
  1772. :post-blank (count-lines before-blank end)
  1773. :post-affiliated post-affiliated)
  1774. (cdr affiliated))))))
  1775. (defun org-element-babel-call-interpreter (babel-call _)
  1776. "Interpret BABEL-CALL element as Org syntax."
  1777. (concat "#+call: "
  1778. (org-element-property :call babel-call)
  1779. (let ((h (org-element-property :inside-header babel-call)))
  1780. (and h (format "[%s]" h)))
  1781. (concat "(" (org-element-property :arguments babel-call) ")")
  1782. (let ((h (org-element-property :end-header babel-call)))
  1783. (and h (concat " " h)))))
  1784. ;;;; Clock
  1785. (defun org-element-clock-parser (limit)
  1786. "Parse a clock.
  1787. LIMIT bounds the search.
  1788. Return a list whose CAR is `clock' and CDR is a plist containing
  1789. `:status', `:value', `:time', `:begin', `:end', `:post-blank' and
  1790. `:post-affiliated' as keywords."
  1791. (save-excursion
  1792. (let* ((case-fold-search nil)
  1793. (begin (point))
  1794. (value (progn (search-forward "CLOCK:" (line-end-position) t)
  1795. (skip-chars-forward " \t")
  1796. (org-element-timestamp-parser)))
  1797. (duration (and (search-forward " => " (line-end-position) t)
  1798. (progn (skip-chars-forward " \t")
  1799. (looking-at "\\(\\S-+\\)[ \t]*$"))
  1800. (match-string-no-properties 1)))
  1801. (status (if duration 'closed 'running))
  1802. (post-blank (let ((before-blank (progn (forward-line) (point))))
  1803. (skip-chars-forward " \r\t\n" limit)
  1804. (skip-chars-backward " \t")
  1805. (unless (bolp) (end-of-line))
  1806. (count-lines before-blank (point))))
  1807. (end (point)))
  1808. (list 'clock
  1809. (list :status status
  1810. :value value
  1811. :duration duration
  1812. :begin begin
  1813. :end end
  1814. :post-blank post-blank
  1815. :post-affiliated begin)))))
  1816. (defun org-element-clock-interpreter (clock _)
  1817. "Interpret CLOCK element as Org syntax."
  1818. (concat "CLOCK: "
  1819. (org-element-timestamp-interpreter
  1820. (org-element-property :value clock) nil)
  1821. (let ((duration (org-element-property :duration clock)))
  1822. (and duration
  1823. (concat " => "
  1824. (apply 'format
  1825. "%2s:%02s"
  1826. (org-split-string duration ":")))))))
  1827. ;;;; Comment
  1828. (defun org-element-comment-parser (limit)
  1829. "Parse a comment.
  1830. LIMIT bounds the search.
  1831. Return a list whose CAR is `comment' and CDR is a plist
  1832. containing `:begin', `:end', `:value', `:post-blank',
  1833. `:post-affiliated' keywords.
  1834. Assume point is at comment beginning."
  1835. (save-excursion
  1836. (let* ((begin (point))
  1837. (value (prog2 (looking-at "[ \t]*# ?")
  1838. (buffer-substring-no-properties
  1839. (match-end 0) (line-end-position))
  1840. (forward-line)))
  1841. (com-end
  1842. ;; Get comments ending.
  1843. (progn
  1844. (while (and (< (point) limit) (looking-at "[ \t]*#\\( \\|$\\)"))
  1845. ;; Accumulate lines without leading hash and first
  1846. ;; whitespace.
  1847. (setq value
  1848. (concat value
  1849. "\n"
  1850. (buffer-substring-no-properties
  1851. (match-end 0) (line-end-position))))
  1852. (forward-line))
  1853. (point)))
  1854. (end (progn (goto-char com-end)
  1855. (skip-chars-forward " \r\t\n" limit)
  1856. (if (eobp) (point) (line-beginning-position)))))
  1857. (list 'comment
  1858. (list :begin begin
  1859. :end end
  1860. :value value
  1861. :post-blank (count-lines com-end end)
  1862. :post-affiliated begin)))))
  1863. (defun org-element-comment-interpreter (comment _)
  1864. "Interpret COMMENT element as Org syntax.
  1865. CONTENTS is nil."
  1866. (replace-regexp-in-string "^" "# " (org-element-property :value comment)))
  1867. ;;;; Comment Block
  1868. (defun org-element-comment-block-parser (limit affiliated)
  1869. "Parse an export block.
  1870. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1871. the buffer position at the beginning of the first affiliated
  1872. keyword and CDR is a plist of affiliated keywords along with
  1873. their value.
  1874. Return a list whose CAR is `comment-block' and CDR is a plist
  1875. containing `:begin', `:end', `:value', `:post-blank' and
  1876. `:post-affiliated' keywords.
  1877. Assume point is at comment block beginning."
  1878. (let ((case-fold-search t))
  1879. (if (not (save-excursion
  1880. (re-search-forward "^[ \t]*#\\+END_COMMENT[ \t]*$" limit t)))
  1881. ;; Incomplete block: parse it as a paragraph.
  1882. (org-element-paragraph-parser limit affiliated)
  1883. (let ((contents-end (match-beginning 0)))
  1884. (save-excursion
  1885. (let* ((begin (car affiliated))
  1886. (post-affiliated (point))
  1887. (contents-begin (progn (forward-line) (point)))
  1888. (pos-before-blank (progn (goto-char contents-end)
  1889. (forward-line)
  1890. (point)))
  1891. (end (progn (skip-chars-forward " \r\t\n" limit)
  1892. (if (eobp) (point) (line-beginning-position))))
  1893. (value (buffer-substring-no-properties
  1894. contents-begin contents-end)))
  1895. (list 'comment-block
  1896. (nconc
  1897. (list :begin begin
  1898. :end end
  1899. :value value
  1900. :post-blank (count-lines pos-before-blank end)
  1901. :post-affiliated post-affiliated)
  1902. (cdr affiliated)))))))))
  1903. (defun org-element-comment-block-interpreter (comment-block _)
  1904. "Interpret COMMENT-BLOCK element as Org syntax."
  1905. (format "#+begin_comment\n%s#+end_comment"
  1906. (org-element-normalize-string
  1907. (org-remove-indentation
  1908. (org-element-property :value comment-block)))))
  1909. ;;;; Diary Sexp
  1910. (defun org-element-diary-sexp-parser (limit affiliated)
  1911. "Parse a diary sexp.
  1912. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1913. the buffer position at the beginning of the first affiliated
  1914. keyword and CDR is a plist of affiliated keywords along with
  1915. their value.
  1916. Return a list whose CAR is `diary-sexp' and CDR is a plist
  1917. containing `:begin', `:end', `:value', `:post-blank' and
  1918. `:post-affiliated' keywords."
  1919. (save-excursion
  1920. (let ((begin (car affiliated))
  1921. (post-affiliated (point))
  1922. (value (progn (looking-at "\\(%%(.*\\)[ \t]*$")
  1923. (match-string-no-properties 1)))
  1924. (pos-before-blank (progn (forward-line) (point)))
  1925. (end (progn (skip-chars-forward " \r\t\n" limit)
  1926. (if (eobp) (point) (line-beginning-position)))))
  1927. (list 'diary-sexp
  1928. (nconc
  1929. (list :value value
  1930. :begin begin
  1931. :end end
  1932. :post-blank (count-lines pos-before-blank end)
  1933. :post-affiliated post-affiliated)
  1934. (cdr affiliated))))))
  1935. (defun org-element-diary-sexp-interpreter (diary-sexp _)
  1936. "Interpret DIARY-SEXP as Org syntax."
  1937. (org-element-property :value diary-sexp))
  1938. ;;;; Example Block
  1939. (defun org-element-example-block-parser (limit affiliated)
  1940. "Parse an example block.
  1941. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  1942. the buffer position at the beginning of the first affiliated
  1943. keyword and CDR is a plist of affiliated keywords along with
  1944. their value.
  1945. Return a list whose CAR is `example-block' and CDR is a plist
  1946. containing `:begin', `:end', `:number-lines', `:preserve-indent',
  1947. `:retain-labels', `:use-labels', `:label-fmt', `:switches',
  1948. `:value', `:post-blank' and `:post-affiliated' keywords."
  1949. (let ((case-fold-search t))
  1950. (if (not (save-excursion
  1951. (re-search-forward "^[ \t]*#\\+END_EXAMPLE[ \t]*$" limit t)))
  1952. ;; Incomplete block: parse it as a paragraph.
  1953. (org-element-paragraph-parser limit affiliated)
  1954. (let ((contents-end (match-beginning 0)))
  1955. (save-excursion
  1956. (let* ((switches
  1957. (progn
  1958. (looking-at "^[ \t]*#\\+BEGIN_EXAMPLE\\(?: +\\(.*\\)\\)?")
  1959. (match-string-no-properties 1)))
  1960. ;; Switches analysis.
  1961. (number-lines
  1962. (and switches
  1963. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  1964. switches)
  1965. (cons
  1966. (if (equal (match-string 1 switches) "-")
  1967. 'new
  1968. 'continued)
  1969. (if (not (match-end 2)) 0
  1970. ;; Subtract 1 to give number of lines before
  1971. ;; first line.
  1972. (1- (string-to-number (match-string 2 switches)))))))
  1973. (preserve-indent
  1974. (and switches (string-match "-i\\>" switches)))
  1975. ;; Should labels be retained in (or stripped from) example
  1976. ;; blocks?
  1977. (retain-labels
  1978. (or (not switches)
  1979. (not (string-match "-r\\>" switches))
  1980. (and number-lines (string-match "-k\\>" switches))))
  1981. ;; What should code-references use - labels or
  1982. ;; line-numbers?
  1983. (use-labels
  1984. (or (not switches)
  1985. (and retain-labels
  1986. (not (string-match "-k\\>" switches)))))
  1987. (label-fmt
  1988. (and switches
  1989. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  1990. (match-string 1 switches)))
  1991. ;; Standard block parsing.
  1992. (begin (car affiliated))
  1993. (post-affiliated (point))
  1994. (contents-begin (line-beginning-position 2))
  1995. (value (org-unescape-code-in-string
  1996. (buffer-substring-no-properties
  1997. contents-begin contents-end)))
  1998. (pos-before-blank (progn (goto-char contents-end)
  1999. (forward-line)
  2000. (point)))
  2001. (end (progn (skip-chars-forward " \r\t\n" limit)
  2002. (if (eobp) (point) (line-beginning-position)))))
  2003. (list 'example-block
  2004. (nconc
  2005. (list :begin begin
  2006. :end end
  2007. :value value
  2008. :switches switches
  2009. :number-lines number-lines
  2010. :preserve-indent preserve-indent
  2011. :retain-labels retain-labels
  2012. :use-labels use-labels
  2013. :label-fmt label-fmt
  2014. :post-blank (count-lines pos-before-blank end)
  2015. :post-affiliated post-affiliated)
  2016. (cdr affiliated)))))))))
  2017. (defun org-element-example-block-interpreter (example-block _)
  2018. "Interpret EXAMPLE-BLOCK element as Org syntax."
  2019. (let ((switches (org-element-property :switches example-block))
  2020. (value
  2021. (let ((val (org-element-property :value example-block)))
  2022. (cond
  2023. ((or org-src-preserve-indentation
  2024. (org-element-property :preserve-indent example-block))
  2025. val)
  2026. ((= 0 org-edit-src-content-indentation)
  2027. (org-remove-indentation val))
  2028. (t
  2029. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2030. (replace-regexp-in-string "^[ \t]*\\S-"
  2031. (concat ind "\\&")
  2032. (org-remove-indentation val))))))))
  2033. (concat "#+begin_example" (and switches (concat " " switches)) "\n"
  2034. (org-element-normalize-string (org-escape-code-in-string value))
  2035. "#+end_example")))
  2036. ;;;; Export Block
  2037. (defun org-element-export-block-parser (limit affiliated)
  2038. "Parse an export block.
  2039. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2040. the buffer position at the beginning of the first affiliated
  2041. keyword and CDR is a plist of affiliated keywords along with
  2042. their value.
  2043. Return a list whose CAR is `export-block' and CDR is a plist
  2044. containing `:begin', `:end', `:type', `:value', `:post-blank' and
  2045. `:post-affiliated' keywords.
  2046. Assume point is at export-block beginning."
  2047. (let* ((case-fold-search t))
  2048. (if (not (save-excursion
  2049. (re-search-forward "^[ \t]*#\\+END_EXPORT[ \t]*$" limit t)))
  2050. ;; Incomplete block: parse it as a paragraph.
  2051. (org-element-paragraph-parser limit affiliated)
  2052. (save-excursion
  2053. (let* ((contents-end (match-beginning 0))
  2054. (backend
  2055. (progn
  2056. (looking-at
  2057. "[ \t]*#\\+BEGIN_EXPORT\\(?:[ \t]+\\(\\S-+\\)\\)?[ \t]*$")
  2058. (match-string-no-properties 1)))
  2059. (begin (car affiliated))
  2060. (post-affiliated (point))
  2061. (contents-begin (progn (forward-line) (point)))
  2062. (pos-before-blank (progn (goto-char contents-end)
  2063. (forward-line)
  2064. (point)))
  2065. (end (progn (skip-chars-forward " \r\t\n" limit)
  2066. (if (eobp) (point) (line-beginning-position))))
  2067. (value (org-unescape-code-in-string
  2068. (buffer-substring-no-properties contents-begin
  2069. contents-end))))
  2070. (list 'export-block
  2071. (nconc
  2072. (list :type (and backend (upcase backend))
  2073. :begin begin
  2074. :end end
  2075. :value value
  2076. :post-blank (count-lines pos-before-blank end)
  2077. :post-affiliated post-affiliated)
  2078. (cdr affiliated))))))))
  2079. (defun org-element-export-block-interpreter (export-block _)
  2080. "Interpret EXPORT-BLOCK element as Org syntax."
  2081. (format "#+begin_export %s\n%s#+end_export"
  2082. (org-element-property :type export-block)
  2083. (org-element-property :value export-block)))
  2084. ;;;; Fixed-width
  2085. (defun org-element-fixed-width-parser (limit affiliated)
  2086. "Parse a fixed-width section.
  2087. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2088. the buffer position at the beginning of the first affiliated
  2089. keyword and CDR is a plist of affiliated keywords along with
  2090. their value.
  2091. Return a list whose CAR is `fixed-width' and CDR is a plist
  2092. containing `:begin', `:end', `:value', `:post-blank' and
  2093. `:post-affiliated' keywords.
  2094. Assume point is at the beginning of the fixed-width area."
  2095. (save-excursion
  2096. (let* ((begin (car affiliated))
  2097. (post-affiliated (point))
  2098. (end-area
  2099. (progn
  2100. (while (and (< (point) limit)
  2101. (looking-at "[ \t]*:\\( \\|$\\)"))
  2102. (forward-line))
  2103. (if (bolp) (line-end-position 0) (point))))
  2104. (end (progn (skip-chars-forward " \r\t\n" limit)
  2105. (if (eobp) (point) (line-beginning-position)))))
  2106. (list 'fixed-width
  2107. (nconc
  2108. (list :begin begin
  2109. :end end
  2110. :value (replace-regexp-in-string
  2111. "^[ \t]*: ?" ""
  2112. (buffer-substring-no-properties post-affiliated
  2113. end-area))
  2114. :post-blank (count-lines end-area end)
  2115. :post-affiliated post-affiliated)
  2116. (cdr affiliated))))))
  2117. (defun org-element-fixed-width-interpreter (fixed-width _)
  2118. "Interpret FIXED-WIDTH element as Org syntax."
  2119. (let ((value (org-element-property :value fixed-width)))
  2120. (and value (replace-regexp-in-string "^" ": " value))))
  2121. ;;;; Horizontal Rule
  2122. (defun org-element-horizontal-rule-parser (limit affiliated)
  2123. "Parse an horizontal rule.
  2124. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2125. the buffer position at the beginning of the first affiliated
  2126. keyword and CDR is a plist of affiliated keywords along with
  2127. their value.
  2128. Return a list whose CAR is `horizontal-rule' and CDR is a plist
  2129. containing `:begin', `:end', `:post-blank' and `:post-affiliated'
  2130. keywords."
  2131. (save-excursion
  2132. (let ((begin (car affiliated))
  2133. (post-affiliated (point))
  2134. (post-hr (progn (forward-line) (point)))
  2135. (end (progn (skip-chars-forward " \r\t\n" limit)
  2136. (if (eobp) (point) (line-beginning-position)))))
  2137. (list 'horizontal-rule
  2138. (nconc
  2139. (list :begin begin
  2140. :end end
  2141. :post-blank (count-lines post-hr end)
  2142. :post-affiliated post-affiliated)
  2143. (cdr affiliated))))))
  2144. (defun org-element-horizontal-rule-interpreter (&rest _)
  2145. "Interpret HORIZONTAL-RULE element as Org syntax."
  2146. "-----")
  2147. ;;;; Keyword
  2148. (defun org-element-keyword-parser (limit affiliated)
  2149. "Parse a keyword at point.
  2150. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2151. the buffer position at the beginning of the first affiliated
  2152. keyword and CDR is a plist of affiliated keywords along with
  2153. their value.
  2154. Return a list whose CAR is a normalized `keyword' (uppercase) and
  2155. CDR is a plist containing `:key', `:value', `:begin', `:end',
  2156. `:post-blank' and `:post-affiliated' keywords."
  2157. (save-excursion
  2158. ;; An orphaned affiliated keyword is considered as a regular
  2159. ;; keyword. In this case AFFILIATED is nil, so we take care of
  2160. ;; this corner case.
  2161. (let ((begin (or (car affiliated) (point)))
  2162. (post-affiliated (point))
  2163. (key (progn (looking-at "[ \t]*#\\+\\(\\S-*\\):")
  2164. (upcase (match-string-no-properties 1))))
  2165. (value (org-trim (buffer-substring-no-properties
  2166. (match-end 0) (point-at-eol))))
  2167. (pos-before-blank (progn (forward-line) (point)))
  2168. (end (progn (skip-chars-forward " \r\t\n" limit)
  2169. (if (eobp) (point) (line-beginning-position)))))
  2170. (list 'keyword
  2171. (nconc
  2172. (list :key key
  2173. :value value
  2174. :begin begin
  2175. :end end
  2176. :post-blank (count-lines pos-before-blank end)
  2177. :post-affiliated post-affiliated)
  2178. (cdr affiliated))))))
  2179. (defun org-element-keyword-interpreter (keyword _)
  2180. "Interpret KEYWORD element as Org syntax."
  2181. (format "#+%s: %s"
  2182. (downcase (org-element-property :key keyword))
  2183. (org-element-property :value keyword)))
  2184. ;;;; Latex Environment
  2185. (defconst org-element--latex-begin-environment
  2186. "^[ \t]*\\\\begin{\\([A-Za-z0-9*]+\\)}"
  2187. "Regexp matching the beginning of a LaTeX environment.
  2188. The environment is captured by the first group.
  2189. See also `org-element--latex-end-environment'.")
  2190. (defconst org-element--latex-end-environment
  2191. "\\\\end{%s}[ \t]*$"
  2192. "Format string matching the ending of a LaTeX environment.
  2193. See also `org-element--latex-begin-environment'.")
  2194. (defun org-element-latex-environment-parser (limit affiliated)
  2195. "Parse a LaTeX environment.
  2196. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2197. the buffer position at the beginning of the first affiliated
  2198. keyword and CDR is a plist of affiliated keywords along with
  2199. their value.
  2200. Return a list whose CAR is `latex-environment' and CDR is a plist
  2201. containing `:begin', `:end', `:value', `:post-blank' and
  2202. `:post-affiliated' keywords.
  2203. Assume point is at the beginning of the latex environment."
  2204. (save-excursion
  2205. (let ((case-fold-search t)
  2206. (code-begin (point)))
  2207. (looking-at org-element--latex-begin-environment)
  2208. (if (not (re-search-forward (format org-element--latex-end-environment
  2209. (regexp-quote (match-string 1)))
  2210. limit t))
  2211. ;; Incomplete latex environment: parse it as a paragraph.
  2212. (org-element-paragraph-parser limit affiliated)
  2213. (let* ((code-end (progn (forward-line) (point)))
  2214. (begin (car affiliated))
  2215. (value (buffer-substring-no-properties code-begin code-end))
  2216. (end (progn (skip-chars-forward " \r\t\n" limit)
  2217. (if (eobp) (point) (line-beginning-position)))))
  2218. (list 'latex-environment
  2219. (nconc
  2220. (list :begin begin
  2221. :end end
  2222. :value value
  2223. :post-blank (count-lines code-end end)
  2224. :post-affiliated code-begin)
  2225. (cdr affiliated))))))))
  2226. (defun org-element-latex-environment-interpreter (latex-environment _)
  2227. "Interpret LATEX-ENVIRONMENT element as Org syntax."
  2228. (org-element-property :value latex-environment))
  2229. ;;;; Node Property
  2230. (defun org-element-node-property-parser (limit)
  2231. "Parse a node-property at point.
  2232. LIMIT bounds the search.
  2233. Return a list whose CAR is `node-property' and CDR is a plist
  2234. containing `:key', `:value', `:begin', `:end', `:post-blank' and
  2235. `:post-affiliated' keywords."
  2236. (looking-at org-property-re)
  2237. (let ((case-fold-search t)
  2238. (begin (point))
  2239. (key (match-string-no-properties 2))
  2240. (value (match-string-no-properties 3))
  2241. (end (save-excursion
  2242. (end-of-line)
  2243. (if (re-search-forward org-property-re limit t)
  2244. (line-beginning-position)
  2245. limit))))
  2246. (list 'node-property
  2247. (list :key key
  2248. :value value
  2249. :begin begin
  2250. :end end
  2251. :post-blank 0
  2252. :post-affiliated begin))))
  2253. (defun org-element-node-property-interpreter (node-property _)
  2254. "Interpret NODE-PROPERTY element as Org syntax."
  2255. (format org-property-format
  2256. (format ":%s:" (org-element-property :key node-property))
  2257. (or (org-element-property :value node-property) "")))
  2258. ;;;; Paragraph
  2259. (defun org-element-paragraph-parser (limit affiliated)
  2260. "Parse a paragraph.
  2261. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2262. the buffer position at the beginning of the first affiliated
  2263. keyword and CDR is a plist of affiliated keywords along with
  2264. their value.
  2265. Return a list whose CAR is `paragraph' and CDR is a plist
  2266. containing `:begin', `:end', `:contents-begin' and
  2267. `:contents-end', `:post-blank' and `:post-affiliated' keywords.
  2268. Assume point is at the beginning of the paragraph."
  2269. (save-excursion
  2270. (let* ((begin (car affiliated))
  2271. (contents-begin (point))
  2272. (before-blank
  2273. (let ((case-fold-search t))
  2274. (end-of-line)
  2275. ;; A matching `org-element-paragraph-separate' is not
  2276. ;; necessarily the end of the paragraph. In particular,
  2277. ;; drawers, blocks or LaTeX environments opening lines
  2278. ;; must be closed. Moreover keywords with a secondary
  2279. ;; value must belong to "dual keywords".
  2280. (while (not
  2281. (cond
  2282. ((not (and (re-search-forward
  2283. org-element-paragraph-separate limit 'move)
  2284. (progn (beginning-of-line) t))))
  2285. ((looking-at org-element-drawer-re)
  2286. (save-excursion
  2287. (re-search-forward "^[ \t]*:END:[ \t]*$" limit t)))
  2288. ((looking-at "[ \t]*#\\+BEGIN_\\(\\S-+\\)")
  2289. (save-excursion
  2290. (re-search-forward
  2291. (format "^[ \t]*#\\+END_%s[ \t]*$"
  2292. (regexp-quote (match-string 1)))
  2293. limit t)))
  2294. ((looking-at org-element--latex-begin-environment)
  2295. (save-excursion
  2296. (re-search-forward
  2297. (format org-element--latex-end-environment
  2298. (regexp-quote (match-string 1)))
  2299. limit t)))
  2300. ((looking-at "[ \t]*#\\+\\(\\S-+\\)\\[.*\\]:")
  2301. (member-ignore-case (match-string 1)
  2302. org-element-dual-keywords))
  2303. ;; Everything else is unambiguous.
  2304. (t)))
  2305. (end-of-line))
  2306. (if (= (point) limit) limit
  2307. (goto-char (line-beginning-position)))))
  2308. (contents-end (save-excursion
  2309. (skip-chars-backward " \r\t\n" contents-begin)
  2310. (line-beginning-position 2)))
  2311. (end (progn (skip-chars-forward " \r\t\n" limit)
  2312. (if (eobp) (point) (line-beginning-position)))))
  2313. (list 'paragraph
  2314. (nconc
  2315. (list :begin begin
  2316. :end end
  2317. :contents-begin contents-begin
  2318. :contents-end contents-end
  2319. :post-blank (count-lines before-blank end)
  2320. :post-affiliated contents-begin)
  2321. (cdr affiliated))))))
  2322. (defun org-element-paragraph-interpreter (_ contents)
  2323. "Interpret paragraph element as Org syntax.
  2324. CONTENTS is the contents of the element."
  2325. contents)
  2326. ;;;; Planning
  2327. (defun org-element-planning-parser (limit)
  2328. "Parse a planning.
  2329. LIMIT bounds the search.
  2330. Return a list whose CAR is `planning' and CDR is a plist
  2331. containing `:closed', `:deadline', `:scheduled', `:begin',
  2332. `:end', `:post-blank' and `:post-affiliated' keywords."
  2333. (save-excursion
  2334. (let* ((case-fold-search nil)
  2335. (begin (point))
  2336. (post-blank (let ((before-blank (progn (forward-line) (point))))
  2337. (skip-chars-forward " \r\t\n" limit)
  2338. (skip-chars-backward " \t")
  2339. (unless (bolp) (end-of-line))
  2340. (count-lines before-blank (point))))
  2341. (end (point))
  2342. closed deadline scheduled)
  2343. (goto-char begin)
  2344. (while (re-search-forward org-element-planning-keywords-re end t)
  2345. (skip-chars-forward " \t" end)
  2346. (let ((keyword (match-string 0))
  2347. (time (org-element-timestamp-parser)))
  2348. (cond
  2349. ((equal keyword org-element-closed-keyword) (setq closed time))
  2350. ((equal keyword org-element-deadline-keyword) (setq deadline time))
  2351. (t (setq scheduled time)))))
  2352. (list 'planning
  2353. (list :closed closed
  2354. :deadline deadline
  2355. :scheduled scheduled
  2356. :begin begin
  2357. :end end
  2358. :post-blank post-blank
  2359. :post-affiliated begin)))))
  2360. (defun org-element-planning-interpreter (planning _)
  2361. "Interpret PLANNING element as Org syntax."
  2362. (mapconcat
  2363. #'identity
  2364. (delq nil
  2365. (list (let ((deadline (org-element-property :deadline planning)))
  2366. (when deadline
  2367. (concat org-element-deadline-keyword " "
  2368. (org-element-timestamp-interpreter deadline nil))))
  2369. (let ((scheduled (org-element-property :scheduled planning)))
  2370. (when scheduled
  2371. (concat org-element-scheduled-keyword " "
  2372. (org-element-timestamp-interpreter scheduled nil))))
  2373. (let ((closed (org-element-property :closed planning)))
  2374. (when closed
  2375. (concat org-element-closed-keyword " "
  2376. (org-element-timestamp-interpreter closed nil))))))
  2377. " "))
  2378. ;;;; Src Block
  2379. (defun org-element-src-block-parser (limit affiliated)
  2380. "Parse a source block.
  2381. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2382. the buffer position at the beginning of the first affiliated
  2383. keyword and CDR is a plist of affiliated keywords along with
  2384. their value.
  2385. Return a list whose CAR is `src-block' and CDR is a plist
  2386. containing `:language', `:switches', `:parameters', `:begin',
  2387. `:end', `:number-lines', `:retain-labels', `:use-labels',
  2388. `:label-fmt', `:preserve-indent', `:value', `:post-blank' and
  2389. `:post-affiliated' keywords.
  2390. Assume point is at the beginning of the block."
  2391. (let ((case-fold-search t))
  2392. (if (not (save-excursion (re-search-forward "^[ \t]*#\\+END_SRC[ \t]*$"
  2393. limit t)))
  2394. ;; Incomplete block: parse it as a paragraph.
  2395. (org-element-paragraph-parser limit affiliated)
  2396. (let ((contents-end (match-beginning 0)))
  2397. (save-excursion
  2398. (let* ((begin (car affiliated))
  2399. (post-affiliated (point))
  2400. ;; Get language as a string.
  2401. (language
  2402. (progn
  2403. (looking-at
  2404. "^[ \t]*#\\+BEGIN_SRC\
  2405. \\(?: +\\(\\S-+\\)\\)?\
  2406. \\(\\(?: +\\(?:-\\(?:l \".+\"\\|[ikr]\\)\\|[-+]n\\(?: *[0-9]+\\)?\\)\\)+\\)?\
  2407. \\(.*\\)[ \t]*$")
  2408. (match-string-no-properties 1)))
  2409. ;; Get switches.
  2410. (switches (match-string-no-properties 2))
  2411. ;; Get parameters.
  2412. (parameters (match-string-no-properties 3))
  2413. ;; Switches analysis.
  2414. (number-lines
  2415. (and switches
  2416. (string-match "\\([-+]\\)n\\(?: *\\([0-9]+\\)\\)?\\>"
  2417. switches)
  2418. (cons
  2419. (if (equal (match-string 1 switches) "-")
  2420. 'new
  2421. 'continued)
  2422. (if (not (match-end 2)) 0
  2423. ;; Subtract 1 to give number of lines before
  2424. ;; first line.
  2425. (1- (string-to-number (match-string 2 switches)))))))
  2426. (preserve-indent (and switches
  2427. (string-match "-i\\>" switches)))
  2428. (label-fmt
  2429. (and switches
  2430. (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
  2431. (match-string 1 switches)))
  2432. ;; Should labels be retained in (or stripped from)
  2433. ;; source blocks?
  2434. (retain-labels
  2435. (or (not switches)
  2436. (not (string-match "-r\\>" switches))
  2437. (and number-lines (string-match "-k\\>" switches))))
  2438. ;; What should code-references use - labels or
  2439. ;; line-numbers?
  2440. (use-labels
  2441. (or (not switches)
  2442. (and retain-labels
  2443. (not (string-match "-k\\>" switches)))))
  2444. ;; Retrieve code.
  2445. (value (org-unescape-code-in-string
  2446. (buffer-substring-no-properties
  2447. (line-beginning-position 2) contents-end)))
  2448. (pos-before-blank (progn (goto-char contents-end)
  2449. (forward-line)
  2450. (point)))
  2451. ;; Get position after ending blank lines.
  2452. (end (progn (skip-chars-forward " \r\t\n" limit)
  2453. (if (eobp) (point) (line-beginning-position)))))
  2454. (list 'src-block
  2455. (nconc
  2456. (list :language language
  2457. :switches (and (org-string-nw-p switches)
  2458. (org-trim switches))
  2459. :parameters (and (org-string-nw-p parameters)
  2460. (org-trim parameters))
  2461. :begin begin
  2462. :end end
  2463. :number-lines number-lines
  2464. :preserve-indent preserve-indent
  2465. :retain-labels retain-labels
  2466. :use-labels use-labels
  2467. :label-fmt label-fmt
  2468. :value value
  2469. :post-blank (count-lines pos-before-blank end)
  2470. :post-affiliated post-affiliated)
  2471. (cdr affiliated)))))))))
  2472. (defun org-element-src-block-interpreter (src-block _)
  2473. "Interpret SRC-BLOCK element as Org syntax."
  2474. (let ((lang (org-element-property :language src-block))
  2475. (switches (org-element-property :switches src-block))
  2476. (params (org-element-property :parameters src-block))
  2477. (value
  2478. (let ((val (org-element-property :value src-block)))
  2479. (cond
  2480. ((or org-src-preserve-indentation
  2481. (org-element-property :preserve-indent src-block))
  2482. val)
  2483. ((zerop org-edit-src-content-indentation)
  2484. (org-remove-indentation val))
  2485. (t
  2486. (let ((ind (make-string org-edit-src-content-indentation ?\s)))
  2487. (replace-regexp-in-string "^[ \t]*\\S-"
  2488. (concat ind "\\&")
  2489. (org-remove-indentation val))))))))
  2490. (format "#+begin_src%s\n%s#+end_src"
  2491. (concat (and lang (concat " " lang))
  2492. (and switches (concat " " switches))
  2493. (and params (concat " " params)))
  2494. (org-element-normalize-string (org-escape-code-in-string value)))))
  2495. ;;;; Table
  2496. (defun org-element-table-parser (limit affiliated)
  2497. "Parse a table at point.
  2498. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2499. the buffer position at the beginning of the first affiliated
  2500. keyword and CDR is a plist of affiliated keywords along with
  2501. their value.
  2502. Return a list whose CAR is `table' and CDR is a plist containing
  2503. `:begin', `:end', `:tblfm', `:type', `:contents-begin',
  2504. `:contents-end', `:value', `:post-blank' and `:post-affiliated'
  2505. keywords.
  2506. Assume point is at the beginning of the table."
  2507. (save-excursion
  2508. (let* ((case-fold-search t)
  2509. (table-begin (point))
  2510. (type (if (looking-at "[ \t]*|") 'org 'table.el))
  2511. (end-re (format "^[ \t]*\\($\\|[^| \t%s]\\)"
  2512. (if (eq type 'org) "" "+")))
  2513. (begin (car affiliated))
  2514. (table-end
  2515. (if (re-search-forward end-re limit 'move)
  2516. (goto-char (match-beginning 0))
  2517. (point)))
  2518. (tblfm (let (acc)
  2519. (while (looking-at "[ \t]*#\\+TBLFM: +\\(.*\\)[ \t]*$")
  2520. (push (match-string-no-properties 1) acc)
  2521. (forward-line))
  2522. acc))
  2523. (pos-before-blank (point))
  2524. (end (progn (skip-chars-forward " \r\t\n" limit)
  2525. (if (eobp) (point) (line-beginning-position)))))
  2526. (list 'table
  2527. (nconc
  2528. (list :begin begin
  2529. :end end
  2530. :type type
  2531. :tblfm tblfm
  2532. ;; Only `org' tables have contents. `table.el' tables
  2533. ;; use a `:value' property to store raw table as
  2534. ;; a string.
  2535. :contents-begin (and (eq type 'org) table-begin)
  2536. :contents-end (and (eq type 'org) table-end)
  2537. :value (and (eq type 'table.el)
  2538. (buffer-substring-no-properties
  2539. table-begin table-end))
  2540. :post-blank (count-lines pos-before-blank end)
  2541. :post-affiliated table-begin)
  2542. (cdr affiliated))))))
  2543. (defun org-element-table-interpreter (table contents)
  2544. "Interpret TABLE element as Org syntax.
  2545. CONTENTS is a string, if table's type is `org', or nil."
  2546. (if (eq (org-element-property :type table) 'table.el)
  2547. (org-remove-indentation (org-element-property :value table))
  2548. (concat (with-temp-buffer (insert contents)
  2549. (org-table-align)
  2550. (buffer-string))
  2551. (mapconcat (lambda (fm) (concat "#+TBLFM: " fm))
  2552. (reverse (org-element-property :tblfm table))
  2553. "\n"))))
  2554. ;;;; Table Row
  2555. (defun org-element-table-row-parser (_)
  2556. "Parse table row at point.
  2557. Return a list whose CAR is `table-row' and CDR is a plist
  2558. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2559. `:type', `:post-blank' and `:post-affiliated' keywords."
  2560. (save-excursion
  2561. (let* ((type (if (looking-at "^[ \t]*|-") 'rule 'standard))
  2562. (begin (point))
  2563. ;; A table rule has no contents. In that case, ensure
  2564. ;; CONTENTS-BEGIN matches CONTENTS-END.
  2565. (contents-begin (and (eq type 'standard) (search-forward "|")))
  2566. (contents-end (and (eq type 'standard)
  2567. (progn
  2568. (end-of-line)
  2569. (skip-chars-backward " \t")
  2570. (point))))
  2571. (end (line-beginning-position 2)))
  2572. (list 'table-row
  2573. (list :type type
  2574. :begin begin
  2575. :end end
  2576. :contents-begin contents-begin
  2577. :contents-end contents-end
  2578. :post-blank 0
  2579. :post-affiliated begin)))))
  2580. (defun org-element-table-row-interpreter (table-row contents)
  2581. "Interpret TABLE-ROW element as Org syntax.
  2582. CONTENTS is the contents of the table row."
  2583. (if (eq (org-element-property :type table-row) 'rule) "|-"
  2584. (concat "|" contents)))
  2585. ;;;; Verse Block
  2586. (defun org-element-verse-block-parser (limit affiliated)
  2587. "Parse a verse block.
  2588. LIMIT bounds the search. AFFILIATED is a list of which CAR is
  2589. the buffer position at the beginning of the first affiliated
  2590. keyword and CDR is a plist of affiliated keywords along with
  2591. their value.
  2592. Return a list whose CAR is `verse-block' and CDR is a plist
  2593. containing `:begin', `:end', `:contents-begin', `:contents-end',
  2594. `:post-blank' and `:post-affiliated' keywords.
  2595. Assume point is at beginning of the block."
  2596. (let ((case-fold-search t))
  2597. (if (not (save-excursion
  2598. (re-search-forward "^[ \t]*#\\+END_VERSE[ \t]*$" limit t)))
  2599. ;; Incomplete block: parse it as a paragraph.
  2600. (org-element-paragraph-parser limit affiliated)
  2601. (let ((contents-end (match-beginning 0)))
  2602. (save-excursion
  2603. (let* ((begin (car affiliated))
  2604. (post-affiliated (point))
  2605. (contents-begin (progn (forward-line) (point)))
  2606. (pos-before-blank (progn (goto-char contents-end)
  2607. (forward-line)
  2608. (point)))
  2609. (end (progn (skip-chars-forward " \r\t\n" limit)
  2610. (if (eobp) (point) (line-beginning-position)))))
  2611. (list 'verse-block
  2612. (nconc
  2613. (list :begin begin
  2614. :end end
  2615. :contents-begin contents-begin
  2616. :contents-end contents-end
  2617. :post-blank (count-lines pos-before-blank end)
  2618. :post-affiliated post-affiliated)
  2619. (cdr affiliated)))))))))
  2620. (defun org-element-verse-block-interpreter (_ contents)
  2621. "Interpret verse-block element as Org syntax.
  2622. CONTENTS is verse block contents."
  2623. (format "#+begin_verse\n%s#+end_verse" contents))
  2624. ;;; Objects
  2625. ;;
  2626. ;; Unlike to elements, raw text can be found between objects. Hence,
  2627. ;; `org-element--object-lex' is provided to find the next object in
  2628. ;; buffer.
  2629. ;;
  2630. ;; Some object types (e.g., `italic') are recursive. Restrictions on
  2631. ;; object types they can contain will be specified in
  2632. ;; `org-element-object-restrictions'.
  2633. ;;
  2634. ;; Creating a new type of object requires to alter
  2635. ;; `org-element--object-regexp' and `org-element--object-lex', add the
  2636. ;; new type in `org-element-all-objects', and possibly add
  2637. ;; restrictions in `org-element-object-restrictions'.
  2638. ;;;; Bold
  2639. (defun org-element--parse-generic-emphasis (mark type)
  2640. "Parse emphasis object at point, if any.
  2641. MARK is the delimiter string used. TYPE is a symbol among
  2642. ‘bold’, ‘code’, ‘italic’, ‘strike-through’, ‘underline’, and
  2643. ‘verbatim’.
  2644. Assume point is at first MARK."
  2645. (save-excursion
  2646. (let ((origin (point)))
  2647. (unless (bolp) (forward-char -1))
  2648. (let ((opening-re
  2649. (rx-to-string
  2650. `(seq (or line-start (any space ?- ?\( ?' ?\" ?\{))
  2651. ,mark
  2652. (not space)))))
  2653. (when (looking-at opening-re)
  2654. (goto-char (1+ origin))
  2655. (let ((closing-re
  2656. (rx-to-string
  2657. `(seq
  2658. (not space)
  2659. (group ,mark)
  2660. (or (any space ?- ?. ?, ?\; ?: ?! ?? ?' ?\" ?\) ?\} ?\\ ?\[)
  2661. line-end)))))
  2662. (when (re-search-forward closing-re nil t)
  2663. (let ((closing (match-end 1)))
  2664. (goto-char closing)
  2665. (let* ((post-blank (skip-chars-forward " \t"))
  2666. (contents-begin (1+ origin))
  2667. (contents-end (1- closing)))
  2668. (list type
  2669. (append
  2670. (list :begin origin
  2671. :end (point)
  2672. :post-blank post-blank)
  2673. (if (memq type '(code verbatim))
  2674. (list :value
  2675. (and (memq type '(code verbatim))
  2676. (buffer-substring
  2677. contents-begin contents-end)))
  2678. (list :contents-begin contents-begin
  2679. :contents-end contents-end)))))))))))))
  2680. (defun org-element-bold-parser ()
  2681. "Parse bold object at point, if any.
  2682. When at a bold object, return a list whose car is `bold' and cdr
  2683. is a plist with `:begin', `:end', `:contents-begin' and
  2684. `:contents-end' and `:post-blank' keywords. Otherwise, return
  2685. nil.
  2686. Assume point is at the first star marker."
  2687. (org-element--parse-generic-emphasis "*" 'bold))
  2688. (defun org-element-bold-interpreter (_ contents)
  2689. "Interpret bold object as Org syntax.
  2690. CONTENTS is the contents of the object."
  2691. (format "*%s*" contents))
  2692. ;;;; Citation
  2693. (defun org-element-citation-parser ()
  2694. "Parse citation object at point, if any.
  2695. When at a citation object, return a list whose car is `citation'
  2696. and cdr is a plist with `:style', `:prefix', `:suffix', `:begin',
  2697. `:end', `:contents-begin', `:contents-end', and `:post-blank'
  2698. keywords. Otherwise, return nil.
  2699. Assume point is at the beginning of the citation."
  2700. (when (looking-at org-element-citation-prefix-re)
  2701. (let* ((begin (point))
  2702. (style (and (match-end 1)
  2703. (match-string-no-properties 1)))
  2704. ;; Ignore blanks between cite type and prefix or key.
  2705. (start (match-end 0))
  2706. (closing (with-syntax-table org-element--pair-square-table
  2707. (ignore-errors (scan-lists begin 1 0)))))
  2708. (save-excursion
  2709. (when (and closing
  2710. (re-search-forward org-element-citation-key-re closing t))
  2711. ;; Find prefix, if any.
  2712. (let ((first-key-end (match-end 0))
  2713. (types (org-element-restriction 'citation-reference))
  2714. (cite
  2715. (list 'citation
  2716. (list :style style
  2717. :begin begin
  2718. :post-blank (progn
  2719. (goto-char closing)
  2720. (skip-chars-forward " \t"))
  2721. :end (point)))))
  2722. ;; `:contents-begin' depends on the presence of
  2723. ;; a non-empty common prefix.
  2724. (goto-char first-key-end)
  2725. (if (not (search-backward ";" start t))
  2726. (org-element-put-property cite :contents-begin start)
  2727. (when (< start (point))
  2728. (org-element-put-property
  2729. cite :prefix
  2730. (org-element--parse-objects start (point) nil types cite)))
  2731. (forward-char)
  2732. (org-element-put-property cite :contents-begin (point)))
  2733. ;; `:contents-end' depends on the presence of a non-empty
  2734. ;; common suffix.
  2735. (goto-char (1- closing))
  2736. (skip-chars-backward " \r\t\n")
  2737. (let ((end (point)))
  2738. (if (or (not (search-backward ";" first-key-end t))
  2739. (re-search-forward org-element-citation-key-re end t))
  2740. (org-element-put-property cite :contents-end end)
  2741. (forward-char)
  2742. (when (< (point) end)
  2743. (org-element-put-property
  2744. cite :suffix
  2745. (org-element--parse-objects (point) end nil types cite)))
  2746. (org-element-put-property cite :contents-end (point))))
  2747. cite))))))
  2748. (defun org-element-citation-interpreter (citation contents)
  2749. "Interpret CITATION object as Org syntax.
  2750. CONTENTS is the contents of the object, as a string."
  2751. (let ((prefix (org-element-property :prefix citation))
  2752. (suffix (org-element-property :suffix citation))
  2753. (style (org-element-property :style citation)))
  2754. (concat "[cite"
  2755. (and style (concat "/" style))
  2756. ":"
  2757. (and prefix (concat (org-element-interpret-data prefix) ";"))
  2758. (if suffix
  2759. (concat contents (org-element-interpret-data suffix))
  2760. ;; Remove spurious semicolon.
  2761. (substring contents nil -1))
  2762. "]")))
  2763. ;;;; Citation Reference
  2764. (defun org-element-citation-reference-parser ()
  2765. "Parse citation reference object at point, if any.
  2766. When at a reference, return a list whose car is
  2767. `citation-reference', and cdr is a plist with `:key',
  2768. `:prefix', `:suffix', `:begin', `:end', and `:post-blank' keywords.
  2769. Assume point is at the beginning of the reference."
  2770. (save-excursion
  2771. (let ((begin (point)))
  2772. (when (re-search-forward org-element-citation-key-re nil t)
  2773. (let* ((key (match-string-no-properties 1))
  2774. (key-start (match-beginning 0))
  2775. (key-end (match-end 0))
  2776. (separator (search-forward ";" nil t))
  2777. (end (or separator (point-max)))
  2778. (suffix-end (if separator (1- end) end))
  2779. (types (org-element-restriction 'citation-reference))
  2780. (reference
  2781. (list 'citation-reference
  2782. (list :key key
  2783. :begin begin
  2784. :end end
  2785. :post-blank 0))))
  2786. (when (< begin key-start)
  2787. (org-element-put-property
  2788. reference :prefix
  2789. (org-element--parse-objects begin key-start nil types reference)))
  2790. (when (< key-end suffix-end)
  2791. (org-element-put-property
  2792. reference :suffix
  2793. (org-element--parse-objects key-end suffix-end nil types reference)))
  2794. reference)))))
  2795. (defun org-element-citation-reference-interpreter (citation-reference _)
  2796. "Interpret CITATION-REFERENCE object as Org syntax."
  2797. (concat (org-element-interpret-data
  2798. (org-element-property :prefix citation-reference))
  2799. "@" (org-element-property :key citation-reference)
  2800. (org-element-interpret-data
  2801. (org-element-property :suffix citation-reference))
  2802. ";"))
  2803. ;;;; Code
  2804. (defun org-element-code-parser ()
  2805. "Parse code object at point, if any.
  2806. When at a code object, return a list whose car is `code' and cdr
  2807. is a plist with `:value', `:begin', `:end' and `:post-blank'
  2808. keywords. Otherwise, return nil.
  2809. Assume point is at the first tilde marker."
  2810. (org-element--parse-generic-emphasis "~" 'code))
  2811. (defun org-element-code-interpreter (code _)
  2812. "Interpret CODE object as Org syntax."
  2813. (format "~%s~" (org-element-property :value code)))
  2814. ;;;; Entity
  2815. (defun org-element-entity-parser ()
  2816. "Parse entity at point, if any.
  2817. When at an entity, return a list whose car is `entity' and cdr
  2818. a plist with `:begin', `:end', `:latex', `:latex-math-p',
  2819. `:html', `:latin1', `:utf-8', `:ascii', `:use-brackets-p' and
  2820. `:post-blank' as keywords. Otherwise, return nil.
  2821. Assume point is at the beginning of the entity."
  2822. (catch 'no-object
  2823. (when (looking-at "\\\\\\(?:\\(?1:_ +\\)\\|\\(?1:there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\(?2:$\\|{}\\|[^[:alpha:]]\\)\\)")
  2824. (save-excursion
  2825. (let* ((value (or (org-entity-get (match-string 1))
  2826. (throw 'no-object nil)))
  2827. (begin (match-beginning 0))
  2828. (bracketsp (string= (match-string 2) "{}"))
  2829. (post-blank (progn (goto-char (match-end 1))
  2830. (when bracketsp (forward-char 2))
  2831. (skip-chars-forward " \t")))
  2832. (end (point)))
  2833. (list 'entity
  2834. (list :name (car value)
  2835. :latex (nth 1 value)
  2836. :latex-math-p (nth 2 value)
  2837. :html (nth 3 value)
  2838. :ascii (nth 4 value)
  2839. :latin1 (nth 5 value)
  2840. :utf-8 (nth 6 value)
  2841. :begin begin
  2842. :end end
  2843. :use-brackets-p bracketsp
  2844. :post-blank post-blank)))))))
  2845. (defun org-element-entity-interpreter (entity _)
  2846. "Interpret ENTITY object as Org syntax."
  2847. (concat "\\"
  2848. (org-element-property :name entity)
  2849. (when (org-element-property :use-brackets-p entity) "{}")))
  2850. ;;;; Export Snippet
  2851. (defun org-element-export-snippet-parser ()
  2852. "Parse export snippet at point.
  2853. When at an export snippet, return a list whose car is
  2854. `export-snippet' and cdr a plist with `:begin', `:end',
  2855. `:back-end', `:value' and `:post-blank' as keywords. Otherwise,
  2856. return nil.
  2857. Assume point is at the beginning of the snippet."
  2858. (save-excursion
  2859. (let (contents-end)
  2860. (when (and (looking-at "@@\\([-A-Za-z0-9]+\\):")
  2861. (setq contents-end
  2862. (save-match-data (goto-char (match-end 0))
  2863. (re-search-forward "@@" nil t)
  2864. (match-beginning 0))))
  2865. (let* ((begin (match-beginning 0))
  2866. (back-end (match-string-no-properties 1))
  2867. (value (buffer-substring-no-properties
  2868. (match-end 0) contents-end))
  2869. (post-blank (skip-chars-forward " \t"))
  2870. (end (point)))
  2871. (list 'export-snippet
  2872. (list :back-end back-end
  2873. :value value
  2874. :begin begin
  2875. :end end
  2876. :post-blank post-blank)))))))
  2877. (defun org-element-export-snippet-interpreter (export-snippet _)
  2878. "Interpret EXPORT-SNIPPET object as Org syntax."
  2879. (format "@@%s:%s@@"
  2880. (org-element-property :back-end export-snippet)
  2881. (org-element-property :value export-snippet)))
  2882. ;;;; Footnote Reference
  2883. (defun org-element-footnote-reference-parser ()
  2884. "Parse footnote reference at point, if any.
  2885. When at a footnote reference, return a list whose car is
  2886. `footnote-reference' and cdr a plist with `:label', `:type',
  2887. `:begin', `:end', `:contents-begin', `:contents-end' and
  2888. `:post-blank' as keywords. Otherwise, return nil."
  2889. (when (looking-at org-footnote-re)
  2890. (let ((closing (with-syntax-table org-element--pair-square-table
  2891. (ignore-errors (scan-lists (point) 1 0)))))
  2892. (when closing
  2893. (save-excursion
  2894. (let* ((begin (point))
  2895. (label (match-string-no-properties 1))
  2896. (inner-begin (match-end 0))
  2897. (inner-end (1- closing))
  2898. (type (if (match-end 2) 'inline 'standard))
  2899. (post-blank (progn (goto-char closing)
  2900. (skip-chars-forward " \t")))
  2901. (end (point)))
  2902. (list 'footnote-reference
  2903. (list :label label
  2904. :type type
  2905. :begin begin
  2906. :end end
  2907. :contents-begin (and (eq type 'inline) inner-begin)
  2908. :contents-end (and (eq type 'inline) inner-end)
  2909. :post-blank post-blank))))))))
  2910. (defun org-element-footnote-reference-interpreter (footnote-reference contents)
  2911. "Interpret FOOTNOTE-REFERENCE object as Org syntax.
  2912. CONTENTS is its definition, when inline, or nil."
  2913. (format "[fn:%s%s]"
  2914. (or (org-element-property :label footnote-reference) "")
  2915. (if contents (concat ":" contents) "")))
  2916. ;;;; Inline Babel Call
  2917. (defun org-element-inline-babel-call-parser ()
  2918. "Parse inline babel call at point, if any.
  2919. When at an inline babel call, return a list whose car is
  2920. `inline-babel-call' and cdr a plist with `:call',
  2921. `:inside-header', `:arguments', `:end-header', `:begin', `:end',
  2922. `:value' and `:post-blank' as keywords. Otherwise, return nil.
  2923. Assume point is at the beginning of the babel call."
  2924. (save-excursion
  2925. (catch :no-object
  2926. (when (let ((case-fold-search nil))
  2927. (looking-at "\\<call_\\([^ \t\n[(]+\\)[([]"))
  2928. (goto-char (match-end 1))
  2929. (let* ((begin (match-beginning 0))
  2930. (call (match-string-no-properties 1))
  2931. (inside-header
  2932. (let ((p (org-element--parse-paired-brackets ?\[)))
  2933. (and (org-string-nw-p p)
  2934. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2935. (arguments (org-string-nw-p
  2936. (or (org-element--parse-paired-brackets ?\()
  2937. ;; Parenthesis are mandatory.
  2938. (throw :no-object nil))))
  2939. (end-header
  2940. (let ((p (org-element--parse-paired-brackets ?\[)))
  2941. (and (org-string-nw-p p)
  2942. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2943. (value (buffer-substring-no-properties begin (point)))
  2944. (post-blank (skip-chars-forward " \t"))
  2945. (end (point)))
  2946. (list 'inline-babel-call
  2947. (list :call call
  2948. :inside-header inside-header
  2949. :arguments arguments
  2950. :end-header end-header
  2951. :begin begin
  2952. :end end
  2953. :value value
  2954. :post-blank post-blank)))))))
  2955. (defun org-element-inline-babel-call-interpreter (inline-babel-call _)
  2956. "Interpret INLINE-BABEL-CALL object as Org syntax."
  2957. (concat "call_"
  2958. (org-element-property :call inline-babel-call)
  2959. (let ((h (org-element-property :inside-header inline-babel-call)))
  2960. (and h (format "[%s]" h)))
  2961. "(" (org-element-property :arguments inline-babel-call) ")"
  2962. (let ((h (org-element-property :end-header inline-babel-call)))
  2963. (and h (format "[%s]" h)))))
  2964. ;;;; Inline Src Block
  2965. (defun org-element-inline-src-block-parser ()
  2966. "Parse inline source block at point, if any.
  2967. When at an inline source block, return a list whose car is
  2968. `inline-src-block' and cdr a plist with `:begin', `:end',
  2969. `:language', `:value', `:parameters' and `:post-blank' as
  2970. keywords. Otherwise, return nil.
  2971. Assume point is at the beginning of the inline source block."
  2972. (save-excursion
  2973. (catch :no-object
  2974. (when (let ((case-fold-search nil))
  2975. (looking-at "\\<src_\\([^ \t\n[{]+\\)[{[]"))
  2976. (goto-char (match-end 1))
  2977. (let ((begin (match-beginning 0))
  2978. (language (match-string-no-properties 1))
  2979. (parameters
  2980. (let ((p (org-element--parse-paired-brackets ?\[)))
  2981. (and (org-string-nw-p p)
  2982. (replace-regexp-in-string "\n[ \t]*" " " (org-trim p)))))
  2983. (value (or (org-element--parse-paired-brackets ?\{)
  2984. (throw :no-object nil)))
  2985. (post-blank (skip-chars-forward " \t")))
  2986. (list 'inline-src-block
  2987. (list :language language
  2988. :value value
  2989. :parameters parameters
  2990. :begin begin
  2991. :end (point)
  2992. :post-blank post-blank)))))))
  2993. (defun org-element-inline-src-block-interpreter (inline-src-block _)
  2994. "Interpret INLINE-SRC-BLOCK object as Org syntax."
  2995. (let ((language (org-element-property :language inline-src-block))
  2996. (arguments (org-element-property :parameters inline-src-block))
  2997. (body (org-element-property :value inline-src-block)))
  2998. (format "src_%s%s{%s}"
  2999. language
  3000. (if arguments (format "[%s]" arguments) "")
  3001. body)))
  3002. ;;;; Italic
  3003. (defun org-element-italic-parser ()
  3004. "Parse italic object at point, if any.
  3005. When at an italic object, return a list whose car is `italic' and
  3006. cdr is a plist with `:begin', `:end', `:contents-begin' and
  3007. `:contents-end' and `:post-blank' keywords. Otherwise, return
  3008. nil.
  3009. Assume point is at the first slash marker."
  3010. (org-element--parse-generic-emphasis "/" 'italic))
  3011. (defun org-element-italic-interpreter (_ contents)
  3012. "Interpret italic object as Org syntax.
  3013. CONTENTS is the contents of the object."
  3014. (format "/%s/" contents))
  3015. ;;;; Latex Fragment
  3016. (defun org-element-latex-fragment-parser ()
  3017. "Parse LaTeX fragment at point, if any.
  3018. When at a LaTeX fragment, return a list whose car is
  3019. `latex-fragment' and cdr a plist with `:value', `:begin', `:end',
  3020. and `:post-blank' as keywords. Otherwise, return nil.
  3021. Assume point is at the beginning of the LaTeX fragment."
  3022. (catch 'no-object
  3023. (save-excursion
  3024. (let* ((begin (point))
  3025. (after-fragment
  3026. (cond
  3027. ((not (eq ?$ (char-after)))
  3028. (pcase (char-after (1+ (point)))
  3029. (?\( (search-forward "\\)" nil t))
  3030. (?\[ (search-forward "\\]" nil t))
  3031. (_
  3032. ;; Macro.
  3033. (and (looking-at "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\
  3034. \\|\\({[^{}\n]*}\\)\\)*")
  3035. (match-end 0)))))
  3036. ((eq ?$ (char-after (1+ (point))))
  3037. (search-forward "$$" nil t 2))
  3038. (t
  3039. (and (not (eq ?$ (char-before)))
  3040. (not (memq (char-after (1+ (point)))
  3041. '(?\s ?\t ?\n ?, ?. ?\;)))
  3042. (search-forward "$" nil t 2)
  3043. (not (memq (char-before (match-beginning 0))
  3044. '(?\s ?\t ?\n ?, ?.)))
  3045. (looking-at-p
  3046. "\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|'\\|$\\)")
  3047. (point)))))
  3048. (post-blank
  3049. (if (not after-fragment) (throw 'no-object nil)
  3050. (goto-char after-fragment)
  3051. (skip-chars-forward " \t")))
  3052. (end (point)))
  3053. (list 'latex-fragment
  3054. (list :value (buffer-substring-no-properties begin after-fragment)
  3055. :begin begin
  3056. :end end
  3057. :post-blank post-blank))))))
  3058. (defun org-element-latex-fragment-interpreter (latex-fragment _)
  3059. "Interpret LATEX-FRAGMENT object as Org syntax."
  3060. (org-element-property :value latex-fragment))
  3061. ;;;; Line Break
  3062. (defun org-element-line-break-parser ()
  3063. "Parse line break at point, if any.
  3064. When at a line break, return a list whose car is `line-break',
  3065. and cdr a plist with `:begin', `:end' and `:post-blank' keywords.
  3066. Otherwise, return nil.
  3067. Assume point is at the beginning of the line break."
  3068. (when (and (looking-at-p "\\\\\\\\[ \t]*$")
  3069. (not (eq (char-before) ?\\)))
  3070. (list 'line-break
  3071. (list :begin (point)
  3072. :end (line-beginning-position 2)
  3073. :post-blank 0))))
  3074. (defun org-element-line-break-interpreter (&rest _)
  3075. "Interpret LINE-BREAK object as Org syntax."
  3076. "\\\\\n")
  3077. ;;;; Link
  3078. (defun org-element-link-parser ()
  3079. "Parse link at point, if any.
  3080. When at a link, return a list whose car is `link' and cdr a plist
  3081. with `:type', `:path', `:format', `:raw-link', `:application',
  3082. `:search-option', `:begin', `:end', `:contents-begin',
  3083. `:contents-end' and `:post-blank' as keywords. Otherwise, return
  3084. nil.
  3085. Assume point is at the beginning of the link."
  3086. (catch 'no-object
  3087. (let ((begin (point))
  3088. end contents-begin contents-end link-end post-blank path type format
  3089. raw-link search-option application)
  3090. (cond
  3091. ;; Type 1: Text targeted from a radio target.
  3092. ((and org-target-link-regexp
  3093. (save-excursion (or (bolp) (backward-char))
  3094. (looking-at org-target-link-regexp)))
  3095. (setq type "radio")
  3096. (setq format 'plain)
  3097. (setq link-end (match-end 1))
  3098. (setq path (match-string-no-properties 1))
  3099. (setq contents-begin (match-beginning 1))
  3100. (setq contents-end (match-end 1)))
  3101. ;; Type 2: Standard link, i.e. [[https://orgmode.org][homepage]]
  3102. ((looking-at org-link-bracket-re)
  3103. (setq format 'bracket)
  3104. (setq contents-begin (match-beginning 2))
  3105. (setq contents-end (match-end 2))
  3106. (setq link-end (match-end 0))
  3107. ;; RAW-LINK is the original link. Decode any encoding.
  3108. ;; Expand any abbreviation in it.
  3109. ;;
  3110. ;; Also treat any newline character and associated
  3111. ;; indentation as a single space character. This is not
  3112. ;; compatible with RFC 3986, which requires to ignore
  3113. ;; them altogether. However, doing so would require
  3114. ;; users to encode spaces on the fly when writing links
  3115. ;; (e.g., insert [[shell:ls%20*.org]] instead of
  3116. ;; [[shell:ls *.org]], which defeats Org's focus on
  3117. ;; simplicity.
  3118. (setq raw-link (org-link-expand-abbrev
  3119. (org-link-unescape
  3120. (replace-regexp-in-string
  3121. "[ \t]*\n[ \t]*" " "
  3122. (match-string-no-properties 1)))))
  3123. ;; Determine TYPE of link and set PATH accordingly. According
  3124. ;; to RFC 3986, remove whitespaces from URI in external links.
  3125. ;; In internal ones, treat indentation as a single space.
  3126. (cond
  3127. ;; File type.
  3128. ((or (file-name-absolute-p raw-link)
  3129. (string-match "\\`\\.\\.?/" raw-link))
  3130. (setq type "file")
  3131. (setq path raw-link))
  3132. ;; Explicit type (http, irc, bbdb...).
  3133. ((string-match org-link-types-re raw-link)
  3134. (setq type (match-string 1 raw-link))
  3135. (setq path (substring raw-link (match-end 0))))
  3136. ;; Code-ref type: PATH is the name of the reference.
  3137. ((and (string-match-p "\\`(" raw-link)
  3138. (string-match-p ")\\'" raw-link))
  3139. (setq type "coderef")
  3140. (setq path (substring raw-link 1 -1)))
  3141. ;; Custom-id type: PATH is the name of the custom id.
  3142. ((= (string-to-char raw-link) ?#)
  3143. (setq type "custom-id")
  3144. (setq path (substring raw-link 1)))
  3145. ;; Fuzzy type: Internal link either matches a target, an
  3146. ;; headline name or nothing. PATH is the target or
  3147. ;; headline's name.
  3148. (t
  3149. (setq type "fuzzy")
  3150. (setq path raw-link))))
  3151. ;; Type 3: Plain link, e.g., https://orgmode.org
  3152. ((looking-at org-link-plain-re)
  3153. (setq format 'plain)
  3154. (setq raw-link (match-string-no-properties 0))
  3155. (setq type (match-string-no-properties 1))
  3156. (setq link-end (match-end 0))
  3157. (setq path (match-string-no-properties 2)))
  3158. ;; Type 4: Angular link, e.g., <https://orgmode.org>. Unlike to
  3159. ;; bracket links, follow RFC 3986 and remove any extra
  3160. ;; whitespace in URI.
  3161. ((looking-at org-link-angle-re)
  3162. (setq format 'angle)
  3163. (setq type (match-string-no-properties 1))
  3164. (setq link-end (match-end 0))
  3165. (setq raw-link
  3166. (buffer-substring-no-properties
  3167. (match-beginning 1) (match-end 2)))
  3168. (setq path (replace-regexp-in-string
  3169. "[ \t]*\n[ \t]*" "" (match-string-no-properties 2))))
  3170. (t (throw 'no-object nil)))
  3171. ;; In any case, deduce end point after trailing white space from
  3172. ;; LINK-END variable.
  3173. (save-excursion
  3174. (setq post-blank
  3175. (progn (goto-char link-end) (skip-chars-forward " \t")))
  3176. (setq end (point)))
  3177. ;; Special "file"-type link processing. Extract opening
  3178. ;; application and search option, if any. Also normalize URI.
  3179. (when (string-match "\\`file\\(?:\\+\\(.+\\)\\)?\\'" type)
  3180. (setq application (match-string 1 type))
  3181. (setq type "file")
  3182. (when (string-match "::\\(.*\\)\\'" path)
  3183. (setq search-option (match-string 1 path))
  3184. (setq path (replace-match "" nil nil path)))
  3185. (setq path (replace-regexp-in-string "\\`///*\\(.:\\)?/" "\\1/" path)))
  3186. ;; Translate link, if `org-link-translation-function' is set.
  3187. (let ((trans (and (functionp org-link-translation-function)
  3188. (funcall org-link-translation-function type path))))
  3189. (when trans
  3190. (setq type (car trans))
  3191. (setq path (cdr trans))))
  3192. (list 'link
  3193. (list :type type
  3194. :path path
  3195. :format format
  3196. :raw-link (or raw-link path)
  3197. :application application
  3198. :search-option search-option
  3199. :begin begin
  3200. :end end
  3201. :contents-begin contents-begin
  3202. :contents-end contents-end
  3203. :post-blank post-blank)))))
  3204. (defun org-element-link-interpreter (link contents)
  3205. "Interpret LINK object as Org syntax.
  3206. CONTENTS is the contents of the object, or nil."
  3207. (let ((type (org-element-property :type link))
  3208. (path (org-element-property :path link)))
  3209. (if (string= type "radio") path
  3210. (let ((fmt (pcase (org-element-property :format link)
  3211. ;; Links with contents and internal links have to
  3212. ;; use bracket syntax. Ignore `:format' in these
  3213. ;; cases. This is also the default syntax when the
  3214. ;; property is not defined, e.g., when the object
  3215. ;; was crafted by the user.
  3216. ((guard contents)
  3217. (format "[[%%s][%s]]"
  3218. ;; Since this is going to be used as
  3219. ;; a format string, escape percent signs
  3220. ;; in description.
  3221. (replace-regexp-in-string "%" "%%" contents)))
  3222. ((or `bracket
  3223. `nil
  3224. (guard (member type '("coderef" "custom-id" "fuzzy"))))
  3225. "[[%s]]")
  3226. ;; Otherwise, just obey to `:format'.
  3227. (`angle "<%s>")
  3228. (`plain "%s")
  3229. (f (error "Wrong `:format' value: %s" f)))))
  3230. (format fmt
  3231. (pcase type
  3232. ("coderef" (format "(%s)" path))
  3233. ("custom-id" (concat "#" path))
  3234. ("file"
  3235. (let ((app (org-element-property :application link))
  3236. (opt (org-element-property :search-option link)))
  3237. (concat type (and app (concat "+" app)) ":"
  3238. path
  3239. (and opt (concat "::" opt)))))
  3240. ("fuzzy" path)
  3241. (_ (concat type ":" path))))))))
  3242. ;;;; Macro
  3243. (defun org-element-macro-parser ()
  3244. "Parse macro at point, if any.
  3245. When at a macro, return a list whose car is `macro' and cdr
  3246. a plist with `:key', `:args', `:begin', `:end', `:value' and
  3247. `:post-blank' as keywords. Otherwise, return nil.
  3248. Assume point is at the macro."
  3249. (save-excursion
  3250. (when (looking-at "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)\\((\\([^\000]*?\\))\\)?}}}")
  3251. (let ((begin (point))
  3252. (key (downcase (match-string-no-properties 1)))
  3253. (value (match-string-no-properties 0))
  3254. (post-blank (progn (goto-char (match-end 0))
  3255. (skip-chars-forward " \t")))
  3256. (end (point))
  3257. (args (pcase (match-string-no-properties 3)
  3258. (`nil nil)
  3259. (a (org-macro-extract-arguments
  3260. (replace-regexp-in-string
  3261. "[ \t\r\n]+" " " (org-trim a)))))))
  3262. (list 'macro
  3263. (list :key key
  3264. :value value
  3265. :args args
  3266. :begin begin
  3267. :end end
  3268. :post-blank post-blank))))))
  3269. (defun org-element-macro-interpreter (macro _)
  3270. "Interpret MACRO object as Org syntax."
  3271. (format "{{{%s%s}}}"
  3272. (org-element-property :key macro)
  3273. (pcase (org-element-property :args macro)
  3274. (`nil "")
  3275. (args (format "(%s)" (apply #'org-macro-escape-arguments args))))))
  3276. ;;;; Radio-target
  3277. (defun org-element-radio-target-parser ()
  3278. "Parse radio target at point, if any.
  3279. When at a radio target, return a list whose car is `radio-target'
  3280. and cdr a plist with `:begin', `:end', `:contents-begin',
  3281. `:contents-end', `:value' and `:post-blank' as keywords.
  3282. Otherwise, return nil.
  3283. Assume point is at the radio target."
  3284. (save-excursion
  3285. (when (looking-at org-radio-target-regexp)
  3286. (let ((begin (point))
  3287. (contents-begin (match-beginning 1))
  3288. (contents-end (match-end 1))
  3289. (value (match-string-no-properties 1))
  3290. (post-blank (progn (goto-char (match-end 0))
  3291. (skip-chars-forward " \t")))
  3292. (end (point)))
  3293. (list 'radio-target
  3294. (list :begin begin
  3295. :end end
  3296. :contents-begin contents-begin
  3297. :contents-end contents-end
  3298. :post-blank post-blank
  3299. :value value))))))
  3300. (defun org-element-radio-target-interpreter (_ contents)
  3301. "Interpret target object as Org syntax.
  3302. CONTENTS is the contents of the object."
  3303. (concat "<<<" contents ">>>"))
  3304. ;;;; Statistics Cookie
  3305. (defun org-element-statistics-cookie-parser ()
  3306. "Parse statistics cookie at point, if any.
  3307. When at a statistics cookie, return a list whose car is
  3308. `statistics-cookie', and cdr a plist with `:begin', `:end',
  3309. `:value' and `:post-blank' keywords. Otherwise, return nil.
  3310. Assume point is at the beginning of the statistics-cookie."
  3311. (save-excursion
  3312. (when (looking-at "\\[[0-9]*\\(%\\|/[0-9]*\\)\\]")
  3313. (let* ((begin (point))
  3314. (value (buffer-substring-no-properties
  3315. (match-beginning 0) (match-end 0)))
  3316. (post-blank (progn (goto-char (match-end 0))
  3317. (skip-chars-forward " \t")))
  3318. (end (point)))
  3319. (list 'statistics-cookie
  3320. (list :begin begin
  3321. :end end
  3322. :value value
  3323. :post-blank post-blank))))))
  3324. (defun org-element-statistics-cookie-interpreter (statistics-cookie _)
  3325. "Interpret STATISTICS-COOKIE object as Org syntax."
  3326. (org-element-property :value statistics-cookie))
  3327. ;;;; Strike-Through
  3328. (defun org-element-strike-through-parser ()
  3329. "Parse strike-through object at point, if any.
  3330. When at a strike-through object, return a list whose car is
  3331. `strike-through' and cdr is a plist with `:begin', `:end',
  3332. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3333. Otherwise, return nil.
  3334. Assume point is at the first plus sign marker."
  3335. (org-element--parse-generic-emphasis "+" 'strike-through))
  3336. (defun org-element-strike-through-interpreter (_ contents)
  3337. "Interpret strike-through object as Org syntax.
  3338. CONTENTS is the contents of the object."
  3339. (format "+%s+" contents))
  3340. ;;;; Subscript
  3341. (defun org-element-subscript-parser ()
  3342. "Parse subscript at point, if any.
  3343. When at a subscript object, return a list whose car is
  3344. `subscript' and cdr a plist with `:begin', `:end',
  3345. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3346. `:post-blank' as keywords. Otherwise, return nil.
  3347. Assume point is at the underscore."
  3348. (save-excursion
  3349. (unless (bolp) (backward-char))
  3350. (when (looking-at org-match-substring-regexp)
  3351. (let ((bracketsp (match-beginning 4))
  3352. (begin (match-beginning 2))
  3353. (contents-begin (or (match-beginning 4)
  3354. (match-beginning 3)))
  3355. (contents-end (or (match-end 4) (match-end 3)))
  3356. (post-blank (progn (goto-char (match-end 0))
  3357. (skip-chars-forward " \t")))
  3358. (end (point)))
  3359. (list 'subscript
  3360. (list :begin begin
  3361. :end end
  3362. :use-brackets-p bracketsp
  3363. :contents-begin contents-begin
  3364. :contents-end contents-end
  3365. :post-blank post-blank))))))
  3366. (defun org-element-subscript-interpreter (subscript contents)
  3367. "Interpret SUBSCRIPT object as Org syntax.
  3368. CONTENTS is the contents of the object."
  3369. (format
  3370. (if (org-element-property :use-brackets-p subscript) "_{%s}" "_%s")
  3371. contents))
  3372. ;;;; Superscript
  3373. (defun org-element-superscript-parser ()
  3374. "Parse superscript at point, if any.
  3375. When at a superscript object, return a list whose car is
  3376. `superscript' and cdr a plist with `:begin', `:end',
  3377. `:contents-begin', `:contents-end', `:use-brackets-p' and
  3378. `:post-blank' as keywords. Otherwise, return nil.
  3379. Assume point is at the caret."
  3380. (save-excursion
  3381. (unless (bolp) (backward-char))
  3382. (when (looking-at org-match-substring-regexp)
  3383. (let ((bracketsp (match-beginning 4))
  3384. (begin (match-beginning 2))
  3385. (contents-begin (or (match-beginning 4)
  3386. (match-beginning 3)))
  3387. (contents-end (or (match-end 4) (match-end 3)))
  3388. (post-blank (progn (goto-char (match-end 0))
  3389. (skip-chars-forward " \t")))
  3390. (end (point)))
  3391. (list 'superscript
  3392. (list :begin begin
  3393. :end end
  3394. :use-brackets-p bracketsp
  3395. :contents-begin contents-begin
  3396. :contents-end contents-end
  3397. :post-blank post-blank))))))
  3398. (defun org-element-superscript-interpreter (superscript contents)
  3399. "Interpret SUPERSCRIPT object as Org syntax.
  3400. CONTENTS is the contents of the object."
  3401. (format
  3402. (if (org-element-property :use-brackets-p superscript) "^{%s}" "^%s")
  3403. contents))
  3404. ;;;; Table Cell
  3405. (defun org-element-table-cell-parser ()
  3406. "Parse table cell at point.
  3407. Return a list whose car is `table-cell' and cdr is a plist
  3408. containing `:begin', `:end', `:contents-begin', `:contents-end'
  3409. and `:post-blank' keywords."
  3410. (looking-at "[ \t]*\\(.*?\\)[ \t]*\\(?:|\\|$\\)")
  3411. (let* ((begin (match-beginning 0))
  3412. (end (match-end 0))
  3413. (contents-begin (match-beginning 1))
  3414. (contents-end (match-end 1)))
  3415. (list 'table-cell
  3416. (list :begin begin
  3417. :end end
  3418. :contents-begin contents-begin
  3419. :contents-end contents-end
  3420. :post-blank 0))))
  3421. (defun org-element-table-cell-interpreter (_ contents)
  3422. "Interpret table-cell element as Org syntax.
  3423. CONTENTS is the contents of the cell, or nil."
  3424. (concat " " contents " |"))
  3425. ;;;; Target
  3426. (defun org-element-target-parser ()
  3427. "Parse target at point, if any.
  3428. When at a target, return a list whose car is `target' and cdr
  3429. a plist with `:begin', `:end', `:value' and `:post-blank' as
  3430. keywords. Otherwise, return nil.
  3431. Assume point is at the target."
  3432. (save-excursion
  3433. (when (looking-at org-target-regexp)
  3434. (let ((begin (point))
  3435. (value (match-string-no-properties 1))
  3436. (post-blank (progn (goto-char (match-end 0))
  3437. (skip-chars-forward " \t")))
  3438. (end (point)))
  3439. (list 'target
  3440. (list :begin begin
  3441. :end end
  3442. :value value
  3443. :post-blank post-blank))))))
  3444. (defun org-element-target-interpreter (target _)
  3445. "Interpret TARGET object as Org syntax."
  3446. (format "<<%s>>" (org-element-property :value target)))
  3447. ;;;; Timestamp
  3448. (defconst org-element--timestamp-regexp
  3449. (concat org-ts-regexp-both
  3450. "\\|"
  3451. "\\(?:<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
  3452. "\\|"
  3453. "\\(?:<%%\\(?:([^>\n]+)\\)>\\)")
  3454. "Regexp matching any timestamp type object.")
  3455. (defun org-element-timestamp-parser ()
  3456. "Parse time stamp at point, if any.
  3457. When at a time stamp, return a list whose car is `timestamp', and
  3458. cdr a plist with `:type', `:raw-value', `:year-start',
  3459. `:month-start', `:day-start', `:hour-start', `:minute-start',
  3460. `:year-end', `:month-end', `:day-end', `:hour-end',
  3461. `:minute-end', `:repeater-type', `:repeater-value',
  3462. `:repeater-unit', `:warning-type', `:warning-value',
  3463. `:warning-unit', `:begin', `:end' and `:post-blank' keywords.
  3464. Otherwise, return nil.
  3465. Assume point is at the beginning of the timestamp."
  3466. (when (looking-at-p org-element--timestamp-regexp)
  3467. (save-excursion
  3468. (let* ((begin (point))
  3469. (activep (eq (char-after) ?<))
  3470. (raw-value
  3471. (progn
  3472. (looking-at "\\([<[]\\(%%\\)?.*?\\)[]>]\\(?:--\\([<[].*?[]>]\\)\\)?")
  3473. (match-string-no-properties 0)))
  3474. (date-start (match-string-no-properties 1))
  3475. (date-end (match-string 3))
  3476. (diaryp (match-beginning 2))
  3477. (post-blank (progn (goto-char (match-end 0))
  3478. (skip-chars-forward " \t")))
  3479. (end (point))
  3480. (time-range
  3481. (and (not diaryp)
  3482. (string-match
  3483. "[012]?[0-9]:[0-5][0-9]\\(-\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)"
  3484. date-start)
  3485. (cons (string-to-number (match-string 2 date-start))
  3486. (string-to-number (match-string 3 date-start)))))
  3487. (type (cond (diaryp 'diary)
  3488. ((and activep (or date-end time-range)) 'active-range)
  3489. (activep 'active)
  3490. ((or date-end time-range) 'inactive-range)
  3491. (t 'inactive)))
  3492. (repeater-props
  3493. (and (not diaryp)
  3494. (string-match "\\([.+]?\\+\\)\\([0-9]+\\)\\([hdwmy]\\)"
  3495. raw-value)
  3496. (list
  3497. :repeater-type
  3498. (let ((type (match-string 1 raw-value)))
  3499. (cond ((equal "++" type) 'catch-up)
  3500. ((equal ".+" type) 'restart)
  3501. (t 'cumulate)))
  3502. :repeater-value (string-to-number (match-string 2 raw-value))
  3503. :repeater-unit
  3504. (pcase (string-to-char (match-string 3 raw-value))
  3505. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3506. (warning-props
  3507. (and (not diaryp)
  3508. (string-match "\\(-\\)?-\\([0-9]+\\)\\([hdwmy]\\)" raw-value)
  3509. (list
  3510. :warning-type (if (match-string 1 raw-value) 'first 'all)
  3511. :warning-value (string-to-number (match-string 2 raw-value))
  3512. :warning-unit
  3513. (pcase (string-to-char (match-string 3 raw-value))
  3514. (?h 'hour) (?d 'day) (?w 'week) (?m 'month) (_ 'year)))))
  3515. year-start month-start day-start hour-start minute-start year-end
  3516. month-end day-end hour-end minute-end)
  3517. ;; Parse date-start.
  3518. (unless diaryp
  3519. (let ((date (org-parse-time-string date-start t)))
  3520. (setq year-start (nth 5 date)
  3521. month-start (nth 4 date)
  3522. day-start (nth 3 date)
  3523. hour-start (nth 2 date)
  3524. minute-start (nth 1 date))))
  3525. ;; Compute date-end. It can be provided directly in time-stamp,
  3526. ;; or extracted from time range. Otherwise, it defaults to the
  3527. ;; same values as date-start.
  3528. (unless diaryp
  3529. (let ((date (and date-end (org-parse-time-string date-end t))))
  3530. (setq year-end (or (nth 5 date) year-start)
  3531. month-end (or (nth 4 date) month-start)
  3532. day-end (or (nth 3 date) day-start)
  3533. hour-end (or (nth 2 date) (car time-range) hour-start)
  3534. minute-end (or (nth 1 date) (cdr time-range) minute-start))))
  3535. (list 'timestamp
  3536. (nconc (list :type type
  3537. :raw-value raw-value
  3538. :year-start year-start
  3539. :month-start month-start
  3540. :day-start day-start
  3541. :hour-start hour-start
  3542. :minute-start minute-start
  3543. :year-end year-end
  3544. :month-end month-end
  3545. :day-end day-end
  3546. :hour-end hour-end
  3547. :minute-end minute-end
  3548. :begin begin
  3549. :end end
  3550. :post-blank post-blank)
  3551. repeater-props
  3552. warning-props))))))
  3553. (defun org-element-timestamp-interpreter (timestamp _)
  3554. "Interpret TIMESTAMP object as Org syntax."
  3555. (let* ((repeat-string
  3556. (concat
  3557. (pcase (org-element-property :repeater-type timestamp)
  3558. (`cumulate "+") (`catch-up "++") (`restart ".+"))
  3559. (let ((val (org-element-property :repeater-value timestamp)))
  3560. (and val (number-to-string val)))
  3561. (pcase (org-element-property :repeater-unit timestamp)
  3562. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3563. (warning-string
  3564. (concat
  3565. (pcase (org-element-property :warning-type timestamp)
  3566. (`first "--") (`all "-"))
  3567. (let ((val (org-element-property :warning-value timestamp)))
  3568. (and val (number-to-string val)))
  3569. (pcase (org-element-property :warning-unit timestamp)
  3570. (`hour "h") (`day "d") (`week "w") (`month "m") (`year "y"))))
  3571. (build-ts-string
  3572. ;; Build an Org timestamp string from TIME. ACTIVEP is
  3573. ;; non-nil when time stamp is active. If WITH-TIME-P is
  3574. ;; non-nil, add a time part. HOUR-END and MINUTE-END
  3575. ;; specify a time range in the timestamp. REPEAT-STRING is
  3576. ;; the repeater string, if any.
  3577. (lambda (time activep &optional with-time-p hour-end minute-end)
  3578. (let ((ts (format-time-string
  3579. (funcall (if with-time-p #'cdr #'car)
  3580. org-time-stamp-formats)
  3581. time)))
  3582. (when (and hour-end minute-end)
  3583. (string-match "[012]?[0-9]:[0-5][0-9]" ts)
  3584. (setq ts
  3585. (replace-match
  3586. (format "\\&-%02d:%02d" hour-end minute-end)
  3587. nil nil ts)))
  3588. (unless activep (setq ts (format "[%s]" (substring ts 1 -1))))
  3589. (dolist (s (list repeat-string warning-string))
  3590. (when (org-string-nw-p s)
  3591. (setq ts (concat (substring ts 0 -1)
  3592. " "
  3593. s
  3594. (substring ts -1)))))
  3595. ;; Return value.
  3596. ts)))
  3597. (type (org-element-property :type timestamp)))
  3598. (pcase type
  3599. ((or `active `inactive)
  3600. (let* ((minute-start (org-element-property :minute-start timestamp))
  3601. (minute-end (org-element-property :minute-end timestamp))
  3602. (hour-start (org-element-property :hour-start timestamp))
  3603. (hour-end (org-element-property :hour-end timestamp))
  3604. (time-range-p (and hour-start hour-end minute-start minute-end
  3605. (or (/= hour-start hour-end)
  3606. (/= minute-start minute-end)))))
  3607. (funcall
  3608. build-ts-string
  3609. (encode-time 0
  3610. (or minute-start 0)
  3611. (or hour-start 0)
  3612. (org-element-property :day-start timestamp)
  3613. (org-element-property :month-start timestamp)
  3614. (org-element-property :year-start timestamp))
  3615. (eq type 'active)
  3616. (and hour-start minute-start)
  3617. (and time-range-p hour-end)
  3618. (and time-range-p minute-end))))
  3619. ((or `active-range `inactive-range)
  3620. (let ((minute-start (org-element-property :minute-start timestamp))
  3621. (minute-end (org-element-property :minute-end timestamp))
  3622. (hour-start (org-element-property :hour-start timestamp))
  3623. (hour-end (org-element-property :hour-end timestamp)))
  3624. (concat
  3625. (funcall
  3626. build-ts-string (encode-time
  3627. 0
  3628. (or minute-start 0)
  3629. (or hour-start 0)
  3630. (org-element-property :day-start timestamp)
  3631. (org-element-property :month-start timestamp)
  3632. (org-element-property :year-start timestamp))
  3633. (eq type 'active-range)
  3634. (and hour-start minute-start))
  3635. "--"
  3636. (funcall build-ts-string
  3637. (encode-time 0
  3638. (or minute-end 0)
  3639. (or hour-end 0)
  3640. (org-element-property :day-end timestamp)
  3641. (org-element-property :month-end timestamp)
  3642. (org-element-property :year-end timestamp))
  3643. (eq type 'active-range)
  3644. (and hour-end minute-end)))))
  3645. (_ (org-element-property :raw-value timestamp)))))
  3646. ;;;; Underline
  3647. (defun org-element-underline-parser ()
  3648. "Parse underline object at point, if any.
  3649. When at an underline object, return a list whose car is
  3650. `underline' and cdr is a plist with `:begin', `:end',
  3651. `:contents-begin' and `:contents-end' and `:post-blank' keywords.
  3652. Otherwise, return nil.
  3653. Assume point is at the first underscore marker."
  3654. (org-element--parse-generic-emphasis "_" 'underline))
  3655. (defun org-element-underline-interpreter (_ contents)
  3656. "Interpret underline object as Org syntax.
  3657. CONTENTS is the contents of the object."
  3658. (format "_%s_" contents))
  3659. ;;;; Verbatim
  3660. (defun org-element-verbatim-parser ()
  3661. "Parse verbatim object at point, if any.
  3662. When at a verbatim object, return a list whose car is `verbatim'
  3663. and cdr is a plist with `:value', `:begin', `:end' and
  3664. `:post-blank' keywords. Otherwise, return nil.
  3665. Assume point is at the first equal sign marker."
  3666. (org-element--parse-generic-emphasis "=" 'verbatim))
  3667. (defun org-element-verbatim-interpreter (verbatim _)
  3668. "Interpret VERBATIM object as Org syntax."
  3669. (format "=%s=" (org-element-property :value verbatim)))
  3670. ;;; Parsing Element Starting At Point
  3671. ;;
  3672. ;; `org-element--current-element' is the core function of this section.
  3673. ;; It returns the Lisp representation of the element starting at
  3674. ;; point.
  3675. (defvar org-element--cache-sync-requests); Declared later
  3676. (defun org-element--current-element (limit &optional granularity mode structure add-to-cache)
  3677. "Parse the element starting at point.
  3678. Return value is a list like (TYPE PROPS) where TYPE is the type
  3679. of the element and PROPS a plist of properties associated to the
  3680. element.
  3681. Possible types are defined in `org-element-all-elements'.
  3682. LIMIT bounds the search.
  3683. Optional argument GRANULARITY determines the depth of the
  3684. recursion. Allowed values are `headline', `greater-element',
  3685. `element', `object' or nil. When it is broader than `object' (or
  3686. nil), secondary values will not be parsed, since they only
  3687. contain objects.
  3688. Optional argument MODE, when non-nil, can be either
  3689. `first-section', `item', `node-property', `planning',
  3690. `property-drawer', `section', `table-row', or `top-comment'.
  3691. If STRUCTURE isn't provided but MODE is set to `item', it will be
  3692. computed.
  3693. Optional argument ADD-TO-CACHE, when non-nil, and when cache is active,
  3694. will also add current element to cache if it is not yet there. Use
  3695. this argument with care, as validity of the element in parse tree is
  3696. not checked.
  3697. This function assumes point is always at the beginning of the
  3698. element it has to parse."
  3699. (let* ((element (and (not (buffer-narrowed-p))
  3700. (org-element--cache-active-p)
  3701. (not org-element--cache-sync-requests)
  3702. (org-element--cache-find (point) t)))
  3703. (element (progn (while (and element
  3704. (not (and (eq (point) (org-element-property :begin element))
  3705. (eq mode (org-element-property :mode element)))))
  3706. (setq element (org-element-property :parent element)))
  3707. element))
  3708. (old-element element)
  3709. (element (when
  3710. (pcase (org-element-property :granularity element)
  3711. (`nil t)
  3712. (`object t)
  3713. (`element (not (memq granularity '(nil object))))
  3714. (`greater-element (not (memq granularity '(nil object element))))
  3715. (`headline (eq granularity 'headline)))
  3716. element)))
  3717. (if element
  3718. element
  3719. (save-excursion
  3720. (let ((case-fold-search t)
  3721. ;; Determine if parsing depth allows for secondary strings
  3722. ;; parsing. It only applies to elements referenced in
  3723. ;; `org-element-secondary-value-alist'.
  3724. (raw-secondary-p (and granularity (not (eq granularity 'object))))
  3725. result)
  3726. (setq
  3727. result
  3728. (cond
  3729. ;; Item.
  3730. ((eq mode 'item)
  3731. (org-element-item-parser limit structure raw-secondary-p))
  3732. ;; Table Row.
  3733. ((eq mode 'table-row) (org-element-table-row-parser limit))
  3734. ;; Node Property.
  3735. ((eq mode 'node-property) (org-element-node-property-parser limit))
  3736. ;; Headline.
  3737. ((org-with-limited-levels (looking-at-p org-outline-regexp-bol))
  3738. (org-element-headline-parser limit raw-secondary-p))
  3739. ;; Sections (must be checked after headline).
  3740. ((eq mode 'section) (org-element-section-parser limit))
  3741. ((eq mode 'first-section)
  3742. (org-element-section-parser
  3743. (or (save-excursion (org-with-limited-levels (outline-next-heading)))
  3744. limit)))
  3745. ;; Comments.
  3746. ((looking-at "^[ \t]*#\\(?: \\|$\\)")
  3747. (org-element-comment-parser limit))
  3748. ;; Planning.
  3749. ((and (eq mode 'planning)
  3750. (eq ?* (char-after (line-beginning-position 0)))
  3751. (looking-at org-element-planning-line-re))
  3752. (org-element-planning-parser limit))
  3753. ;; Property drawer.
  3754. ((and (pcase mode
  3755. (`planning (eq ?* (char-after (line-beginning-position 0))))
  3756. ((or `property-drawer `top-comment)
  3757. (save-excursion
  3758. (beginning-of-line 0)
  3759. (not (looking-at "[[:blank:]]*$"))))
  3760. (_ nil))
  3761. (looking-at org-property-drawer-re))
  3762. (org-element-property-drawer-parser limit))
  3763. ;; When not at bol, point is at the beginning of an item or
  3764. ;; a footnote definition: next item is always a paragraph.
  3765. ((not (bolp)) (org-element-paragraph-parser limit (list (point))))
  3766. ;; Clock.
  3767. ((looking-at org-element-clock-line-re)
  3768. (org-element-clock-parser limit))
  3769. ;; Inlinetask.
  3770. ((looking-at "^\\*+ ")
  3771. (org-element-inlinetask-parser limit raw-secondary-p))
  3772. ;; From there, elements can have affiliated keywords.
  3773. (t (let ((affiliated (org-element--collect-affiliated-keywords
  3774. limit (memq granularity '(nil object)))))
  3775. (cond
  3776. ;; Jumping over affiliated keywords put point off-limits.
  3777. ;; Parse them as regular keywords.
  3778. ((and (cdr affiliated) (>= (point) limit))
  3779. (goto-char (car affiliated))
  3780. (org-element-keyword-parser limit nil))
  3781. ;; LaTeX Environment.
  3782. ((looking-at org-element--latex-begin-environment)
  3783. (org-element-latex-environment-parser limit affiliated))
  3784. ;; Drawer.
  3785. ((looking-at org-element-drawer-re)
  3786. (org-element-drawer-parser limit affiliated))
  3787. ;; Fixed Width
  3788. ((looking-at "[ \t]*:\\( \\|$\\)")
  3789. (org-element-fixed-width-parser limit affiliated))
  3790. ;; Inline Comments, Blocks, Babel Calls, Dynamic Blocks and
  3791. ;; Keywords.
  3792. ((looking-at "[ \t]*#\\+")
  3793. (goto-char (match-end 0))
  3794. (cond
  3795. ((looking-at "BEGIN_\\(\\S-+\\)")
  3796. (beginning-of-line)
  3797. (funcall (pcase (upcase (match-string 1))
  3798. ("CENTER" #'org-element-center-block-parser)
  3799. ("COMMENT" #'org-element-comment-block-parser)
  3800. ("EXAMPLE" #'org-element-example-block-parser)
  3801. ("EXPORT" #'org-element-export-block-parser)
  3802. ("QUOTE" #'org-element-quote-block-parser)
  3803. ("SRC" #'org-element-src-block-parser)
  3804. ("VERSE" #'org-element-verse-block-parser)
  3805. (_ #'org-element-special-block-parser))
  3806. limit
  3807. affiliated))
  3808. ((looking-at "CALL:")
  3809. (beginning-of-line)
  3810. (org-element-babel-call-parser limit affiliated))
  3811. ((looking-at "BEGIN:? ")
  3812. (beginning-of-line)
  3813. (org-element-dynamic-block-parser limit affiliated))
  3814. ((looking-at "\\S-+:")
  3815. (beginning-of-line)
  3816. (org-element-keyword-parser limit affiliated))
  3817. (t
  3818. (beginning-of-line)
  3819. (org-element-paragraph-parser limit affiliated))))
  3820. ;; Footnote Definition.
  3821. ((looking-at org-footnote-definition-re)
  3822. (org-element-footnote-definition-parser limit affiliated))
  3823. ;; Horizontal Rule.
  3824. ((looking-at "[ \t]*-\\{5,\\}[ \t]*$")
  3825. (org-element-horizontal-rule-parser limit affiliated))
  3826. ;; Diary Sexp.
  3827. ((looking-at "%%(")
  3828. (org-element-diary-sexp-parser limit affiliated))
  3829. ;; Table.
  3830. ((or (looking-at "[ \t]*|")
  3831. ;; There is no strict definition of a table.el
  3832. ;; table. Try to prevent false positive while being
  3833. ;; quick.
  3834. (let ((rule-regexp
  3835. (rx (zero-or-more (any " \t"))
  3836. "+"
  3837. (one-or-more (one-or-more "-") "+")
  3838. (zero-or-more (any " \t"))
  3839. eol))
  3840. (non-table.el-line
  3841. (rx bol
  3842. (zero-or-more (any " \t"))
  3843. (or eol (not (any "+| \t")))))
  3844. (next (line-beginning-position 2)))
  3845. ;; Start with a full rule.
  3846. (and
  3847. (looking-at rule-regexp)
  3848. (< next limit) ;no room for a table.el table
  3849. (save-excursion
  3850. (end-of-line)
  3851. (cond
  3852. ;; Must end with a full rule.
  3853. ((not (re-search-forward non-table.el-line limit 'move))
  3854. (if (bolp) (forward-line -1) (beginning-of-line))
  3855. (looking-at rule-regexp))
  3856. ;; Ignore pseudo-tables with a single
  3857. ;; rule.
  3858. ((= next (line-beginning-position))
  3859. nil)
  3860. ;; Must end with a full rule.
  3861. (t
  3862. (forward-line -1)
  3863. (looking-at rule-regexp)))))))
  3864. (org-element-table-parser limit affiliated))
  3865. ;; List.
  3866. ((looking-at (org-item-re))
  3867. (org-element-plain-list-parser
  3868. limit affiliated
  3869. (or structure (org-element--list-struct limit))))
  3870. ;; Default element: Paragraph.
  3871. (t (org-element-paragraph-parser limit affiliated)))))))
  3872. (when result
  3873. (org-element-put-property result :mode mode)
  3874. (org-element-put-property result :granularity granularity))
  3875. (when (and (not (buffer-narrowed-p))
  3876. (org-element--cache-active-p)
  3877. (not org-element--cache-sync-requests)
  3878. add-to-cache)
  3879. (if (not old-element)
  3880. (setq result (org-element--cache-put result))
  3881. (org-element-set-element old-element result)
  3882. (setq result old-element)))
  3883. result)))))
  3884. ;; Most elements can have affiliated keywords. When looking for an
  3885. ;; element beginning, we want to move before them, as they belong to
  3886. ;; that element, and, in the meantime, collect information they give
  3887. ;; into appropriate properties. Hence the following function.
  3888. (defun org-element--collect-affiliated-keywords (limit parse)
  3889. "Collect affiliated keywords from point down to LIMIT.
  3890. Return a list whose CAR is the position at the first of them and
  3891. CDR a plist of keywords and values and move point to the
  3892. beginning of the first line after them.
  3893. As a special case, if element doesn't start at the beginning of
  3894. the line (e.g., a paragraph starting an item), CAR is current
  3895. position of point and CDR is nil.
  3896. When PARSE is non-nil, values from keywords belonging to
  3897. `org-element-parsed-keywords' are parsed as secondary strings."
  3898. (if (not (bolp)) (list (point))
  3899. (let ((case-fold-search t)
  3900. (origin (point))
  3901. ;; RESTRICT is the list of objects allowed in parsed
  3902. ;; keywords value. If PARSE is nil, no object is allowed.
  3903. (restrict (and parse (org-element-restriction 'keyword)))
  3904. output)
  3905. (while (and (< (point) limit) (looking-at org-element--affiliated-re))
  3906. (let* ((raw-kwd (upcase (match-string 1)))
  3907. ;; Apply translation to RAW-KWD. From there, KWD is
  3908. ;; the official keyword.
  3909. (kwd (or (cdr (assoc raw-kwd
  3910. org-element-keyword-translation-alist))
  3911. raw-kwd))
  3912. ;; PARSED? is non-nil when keyword should have its
  3913. ;; value parsed.
  3914. (parsed? (member kwd org-element-parsed-keywords))
  3915. ;; Find main value for any keyword.
  3916. (value
  3917. (let ((beg (match-end 0))
  3918. (end (save-excursion
  3919. (end-of-line)
  3920. (skip-chars-backward " \t")
  3921. (point))))
  3922. (if parsed?
  3923. (save-match-data
  3924. (org-element--parse-objects beg end nil restrict))
  3925. (org-trim (buffer-substring-no-properties beg end)))))
  3926. ;; If KWD is a dual keyword, find its secondary value.
  3927. ;; Maybe parse it.
  3928. (dual? (member kwd org-element-dual-keywords))
  3929. (dual-value
  3930. (and dual?
  3931. (let ((sec (match-string-no-properties 2)))
  3932. (cond
  3933. ((and sec parsed?)
  3934. (save-match-data
  3935. (org-element--parse-objects
  3936. (match-beginning 2) (match-end 2) nil restrict)))
  3937. (sec sec)))))
  3938. ;; Attribute a property name to KWD.
  3939. (kwd-sym (and kwd (intern (concat ":" (downcase kwd))))))
  3940. ;; Now set final shape for VALUE.
  3941. (when dual?
  3942. (setq value (and (or value dual-value) (cons value dual-value))))
  3943. (when (or (member kwd org-element-multiple-keywords)
  3944. ;; Attributes can always appear on multiple lines.
  3945. (string-match "^ATTR_" kwd))
  3946. (setq value (cons value (plist-get output kwd-sym))))
  3947. ;; Eventually store the new value in OUTPUT.
  3948. (setq output (plist-put output kwd-sym value))
  3949. ;; Move to next keyword.
  3950. (forward-line)))
  3951. ;; If affiliated keywords are orphaned: move back to first one.
  3952. ;; They will be parsed as a paragraph.
  3953. (when (looking-at "[ \t]*$") (goto-char origin) (setq output nil))
  3954. ;; Return value.
  3955. (cons origin output))))
  3956. ;;; The Org Parser
  3957. ;;
  3958. ;; The two major functions here are `org-element-parse-buffer', which
  3959. ;; parses Org syntax inside the current buffer, taking into account
  3960. ;; region, narrowing, or even visibility if specified, and
  3961. ;; `org-element-parse-secondary-string', which parses objects within
  3962. ;; a given string.
  3963. ;;
  3964. ;; The (almost) almighty `org-element-map' allows applying a function
  3965. ;; on elements or objects matching some type, and accumulating the
  3966. ;; resulting values. In an export situation, it also skips unneeded
  3967. ;; parts of the parse tree.
  3968. (defun org-element-parse-buffer (&optional granularity visible-only)
  3969. "Recursively parse the buffer and return structure.
  3970. If narrowing is in effect, only parse the visible part of the
  3971. buffer.
  3972. Optional argument GRANULARITY determines the depth of the
  3973. recursion. It can be set to the following symbols:
  3974. `headline' Only parse headlines.
  3975. `greater-element' Don't recurse into greater elements except
  3976. headlines and sections. Thus, elements
  3977. parsed are the top-level ones.
  3978. `element' Parse everything but objects and plain text.
  3979. `object' Parse the complete buffer (default).
  3980. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  3981. elements.
  3982. An element or object is represented as a list with the
  3983. pattern (TYPE PROPERTIES CONTENTS), where :
  3984. TYPE is a symbol describing the element or object. See
  3985. `org-element-all-elements' and `org-element-all-objects' for an
  3986. exhaustive list of such symbols. One can retrieve it with
  3987. `org-element-type' function.
  3988. PROPERTIES is the list of attributes attached to the element or
  3989. object, as a plist. Although most of them are specific to the
  3990. element or object type, all types share `:begin', `:end',
  3991. `:post-blank' and `:parent' properties, which respectively
  3992. refer to buffer position where the element or object starts,
  3993. ends, the number of white spaces or blank lines after it, and
  3994. the element or object containing it. Properties values can be
  3995. obtained by using `org-element-property' function.
  3996. CONTENTS is a list of elements, objects or raw strings
  3997. contained in the current element or object, when applicable.
  3998. One can access them with `org-element-contents' function.
  3999. The Org buffer has `org-data' as type and nil as properties.
  4000. `org-element-map' function can be used to find specific elements
  4001. or objects within the parse tree.
  4002. This function assumes that current major mode is `org-mode'."
  4003. (save-excursion
  4004. (goto-char (point-min))
  4005. (let ((org-data (org-element-org-data-parser))
  4006. (gc-cons-threshold #x40000000))
  4007. (org-skip-whitespace)
  4008. (org-element--parse-elements
  4009. (point-at-bol) (point-max)
  4010. ;; Start in `first-section' mode so text before the first
  4011. ;; headline belongs to a section.
  4012. 'first-section nil granularity visible-only org-data))))
  4013. (defun org-element-parse-secondary-string (string restriction &optional parent)
  4014. "Recursively parse objects in STRING and return structure.
  4015. RESTRICTION is a symbol limiting the object types that will be
  4016. looked after.
  4017. Optional argument PARENT, when non-nil, is the element or object
  4018. containing the secondary string. It is used to set correctly
  4019. `:parent' property within the string.
  4020. If STRING is the empty string or nil, return nil."
  4021. (cond
  4022. ((not string) nil)
  4023. ((equal string "") nil)
  4024. (t (let ((local-variables (buffer-local-variables)))
  4025. (with-temp-buffer
  4026. (dolist (v local-variables)
  4027. (ignore-errors
  4028. (if (symbolp v) (makunbound v)
  4029. ;; Don't set file name to avoid mishandling hooks (bug#44524)
  4030. (unless (memq (car v) '(buffer-file-name buffer-file-truename))
  4031. (set (make-local-variable (car v)) (cdr v))))))
  4032. ;; Transferring local variables may put the temporary buffer
  4033. ;; into a read-only state. Make sure we can insert STRING.
  4034. (let ((inhibit-read-only t)) (insert string))
  4035. ;; Prevent "Buffer *temp* modified; kill anyway?".
  4036. (restore-buffer-modified-p nil)
  4037. (org-element--parse-objects
  4038. (point-min) (point-max) nil restriction parent))))))
  4039. (defun org-element-map
  4040. (data types fun &optional info first-match no-recursion with-affiliated)
  4041. "Map a function on selected elements or objects.
  4042. DATA is a parse tree, an element, an object, a string, or a list
  4043. of such constructs. TYPES is a symbol or list of symbols of
  4044. elements or objects types (see `org-element-all-elements' and
  4045. `org-element-all-objects' for a complete list of types). FUN is
  4046. the function called on the matching element or object. It has to
  4047. accept one argument: the element or object itself.
  4048. When optional argument INFO is non-nil, it should be a plist
  4049. holding export options. In that case, parts of the parse tree
  4050. not exportable according to that property list will be skipped.
  4051. When optional argument FIRST-MATCH is non-nil, stop at the first
  4052. match for which FUN doesn't return nil, and return that value.
  4053. Optional argument NO-RECURSION is a symbol or a list of symbols
  4054. representing elements or objects types. `org-element-map' won't
  4055. enter any recursive element or object whose type belongs to that
  4056. list. Though, FUN can still be applied on them.
  4057. When optional argument WITH-AFFILIATED is non-nil, FUN will also
  4058. apply to matching objects within parsed affiliated keywords (see
  4059. `org-element-parsed-keywords').
  4060. Nil values returned from FUN do not appear in the results.
  4061. Examples:
  4062. ---------
  4063. Assuming TREE is a variable containing an Org buffer parse tree,
  4064. the following example will return a flat list of all `src-block'
  4065. and `example-block' elements in it:
  4066. (org-element-map tree \\='(example-block src-block) #\\='identity)
  4067. The following snippet will find the first headline with a level
  4068. of 1 and a \"phone\" tag, and will return its beginning position:
  4069. (org-element-map tree \\='headline
  4070. (lambda (hl)
  4071. (and (= (org-element-property :level hl) 1)
  4072. (member \"phone\" (org-element-property :tags hl))
  4073. (org-element-property :begin hl)))
  4074. nil t)
  4075. The next example will return a flat list of all `plain-list' type
  4076. elements in TREE that are not a sub-list themselves:
  4077. (org-element-map tree \\='plain-list #\\='identity nil nil \\='plain-list)
  4078. Eventually, this example will return a flat list of all `bold'
  4079. type objects containing a `latex-snippet' type object, even
  4080. looking into captions:
  4081. (org-element-map tree \\='bold
  4082. (lambda (b)
  4083. (and (org-element-map b \\='latex-snippet #\\='identity nil t) b))
  4084. nil nil nil t)"
  4085. (declare (indent 2))
  4086. ;; Ensure TYPES and NO-RECURSION are a list, even of one element.
  4087. (let* ((types (if (listp types) types (list types)))
  4088. (no-recursion (if (listp no-recursion) no-recursion
  4089. (list no-recursion)))
  4090. ;; Recursion depth is determined by --CATEGORY.
  4091. (--category
  4092. (catch :--found
  4093. (let ((category 'greater-elements)
  4094. (all-objects (cons 'plain-text org-element-all-objects)))
  4095. (dolist (type types category)
  4096. (cond ((memq type all-objects)
  4097. ;; If one object is found, the function has
  4098. ;; to recurse into every object.
  4099. (throw :--found 'objects))
  4100. ((not (memq type org-element-greater-elements))
  4101. ;; If one regular element is found, the
  4102. ;; function has to recurse, at least, into
  4103. ;; every element it encounters.
  4104. (and (not (eq category 'elements))
  4105. (setq category 'elements))))))))
  4106. --acc)
  4107. (letrec ((--walk-tree
  4108. (lambda (--data)
  4109. ;; Recursively walk DATA. INFO, if non-nil, is a plist
  4110. ;; holding contextual information.
  4111. (let ((--type (org-element-type --data)))
  4112. (cond
  4113. ((not --data))
  4114. ;; Ignored element in an export context.
  4115. ((and info (memq --data (plist-get info :ignore-list))))
  4116. ;; List of elements or objects.
  4117. ((not --type) (mapc --walk-tree --data))
  4118. ;; Unconditionally enter parse trees.
  4119. ((eq --type 'org-data)
  4120. (mapc --walk-tree (org-element-contents --data)))
  4121. (t
  4122. ;; Check if TYPE is matching among TYPES. If so,
  4123. ;; apply FUN to --DATA and accumulate return value
  4124. ;; into --ACC (or exit if FIRST-MATCH is non-nil).
  4125. (when (memq --type types)
  4126. (let ((result (funcall fun --data)))
  4127. (cond ((not result))
  4128. (first-match (throw :--map-first-match result))
  4129. (t (push result --acc)))))
  4130. ;; If --DATA has a secondary string that can contain
  4131. ;; objects with their type among TYPES, look inside.
  4132. (when (and (eq --category 'objects) (not (stringp --data)))
  4133. (dolist (p (cdr (assq --type
  4134. org-element-secondary-value-alist)))
  4135. (funcall --walk-tree (org-element-property p --data))))
  4136. ;; If --DATA has any parsed affiliated keywords and
  4137. ;; WITH-AFFILIATED is non-nil, look for objects in
  4138. ;; them.
  4139. (when (and with-affiliated
  4140. (eq --category 'objects)
  4141. (eq (org-element-class --data) 'element))
  4142. (dolist (kwd-pair org-element--parsed-properties-alist)
  4143. (let ((kwd (car kwd-pair))
  4144. (value (org-element-property (cdr kwd-pair) --data)))
  4145. ;; Pay attention to the type of parsed
  4146. ;; keyword. In particular, preserve order for
  4147. ;; multiple keywords.
  4148. (cond
  4149. ((not value))
  4150. ((member kwd org-element-dual-keywords)
  4151. (if (member kwd org-element-multiple-keywords)
  4152. (dolist (line (reverse value))
  4153. (funcall --walk-tree (cdr line))
  4154. (funcall --walk-tree (car line)))
  4155. (funcall --walk-tree (cdr value))
  4156. (funcall --walk-tree (car value))))
  4157. ((member kwd org-element-multiple-keywords)
  4158. (mapc --walk-tree (reverse value)))
  4159. (t (funcall --walk-tree value))))))
  4160. ;; Determine if a recursion into --DATA is possible.
  4161. (cond
  4162. ;; --TYPE is explicitly removed from recursion.
  4163. ((memq --type no-recursion))
  4164. ;; --DATA has no contents.
  4165. ((not (org-element-contents --data)))
  4166. ;; Looking for greater elements but --DATA is
  4167. ;; simply an element or an object.
  4168. ((and (eq --category 'greater-elements)
  4169. (not (memq --type org-element-greater-elements))))
  4170. ;; Looking for elements but --DATA is an object.
  4171. ((and (eq --category 'elements)
  4172. (eq (org-element-class --data) 'object)))
  4173. ;; In any other case, map contents.
  4174. (t (mapc --walk-tree (org-element-contents --data))))))))))
  4175. (catch :--map-first-match
  4176. (funcall --walk-tree data)
  4177. ;; Return value in a proper order.
  4178. (nreverse --acc)))))
  4179. ;; The following functions are internal parts of the parser.
  4180. ;;
  4181. ;; The first one, `org-element--parse-elements' acts at the element's
  4182. ;; level.
  4183. ;;
  4184. ;; The second one, `org-element--parse-objects' applies on all objects
  4185. ;; of a paragraph or a secondary string. It calls
  4186. ;; `org-element--object-lex' to find the next object in the current
  4187. ;; container.
  4188. (defsubst org-element--next-mode (mode type parent?)
  4189. "Return next mode according to current one.
  4190. MODE is a symbol representing the expectation about the next
  4191. element or object. Meaningful values are `first-section',
  4192. `item', `node-property', `planning', `property-drawer',
  4193. `section', `table-row', `top-comment', and nil.
  4194. TYPE is the type of the current element or object.
  4195. If PARENT? is non-nil, assume the next element or object will be
  4196. located inside the current one."
  4197. (if parent?
  4198. (pcase type
  4199. (`headline 'section)
  4200. ((and (guard (eq mode 'first-section)) `section) 'top-comment)
  4201. ((and (guard (eq mode 'org-data)) `org-data) 'first-section)
  4202. ((and (guard (not mode)) `org-data) 'first-section)
  4203. (`inlinetask 'planning)
  4204. (`plain-list 'item)
  4205. (`property-drawer 'node-property)
  4206. (`section 'planning)
  4207. (`table 'table-row))
  4208. (pcase mode
  4209. (`item 'item)
  4210. (`node-property 'node-property)
  4211. ((and `planning (guard (eq type 'planning))) 'property-drawer)
  4212. (`table-row 'table-row)
  4213. ((and `top-comment (guard (eq type 'comment))) 'property-drawer))))
  4214. (defun org-element--parse-elements
  4215. (beg end mode structure granularity visible-only acc)
  4216. "Parse elements between BEG and END positions.
  4217. MODE prioritizes some elements over the others. It can be set to
  4218. `first-section', `item', `node-property', `planning',
  4219. `property-drawer', `section', `table-row', `top-comment', or nil.
  4220. When value is `item', STRUCTURE will be used as the current list
  4221. structure.
  4222. GRANULARITY determines the depth of the recursion. See
  4223. `org-element-parse-buffer' for more information.
  4224. When VISIBLE-ONLY is non-nil, don't parse contents of hidden
  4225. elements.
  4226. Elements are accumulated into ACC."
  4227. (save-excursion
  4228. (goto-char beg)
  4229. ;; When parsing only headlines, skip any text before first one.
  4230. (when (and (eq granularity 'headline) (not (org-at-heading-p)))
  4231. (org-with-limited-levels (outline-next-heading)))
  4232. (let (elements)
  4233. (while (< (point) end)
  4234. ;; Visible only: skip invisible parts due to folding.
  4235. (if (and visible-only (org-invisible-p nil t))
  4236. (progn
  4237. (goto-char (org-find-visible))
  4238. (when (and (eolp) (not (eobp))) (forward-char)))
  4239. ;; Find current element's type and parse it accordingly to
  4240. ;; its category.
  4241. (let* ((element (org-element-copy
  4242. ;; `org-element--current-element' may return cached
  4243. ;; elements. Below code reassigns
  4244. ;; `:parent' property of the element and
  4245. ;; may interfere with cache
  4246. ;; synchronisation if parent element is not
  4247. ;; yet in cache. Moreover, the returned
  4248. ;; structure may be altered by caller code
  4249. ;; arbitrarily. Hence, we return a copy of
  4250. ;; the potentially cached element to make
  4251. ;; potential modifications safe for element
  4252. ;; cache.
  4253. (org-element--current-element
  4254. end granularity mode structure)))
  4255. (type (org-element-type element))
  4256. (cbeg (org-element-property :contents-begin element)))
  4257. (goto-char (org-element-property :end element))
  4258. ;; Fill ELEMENT contents by side-effect.
  4259. (cond
  4260. ;; If element has no contents, don't modify it.
  4261. ((not cbeg))
  4262. ;; Greater element: parse it between `contents-begin' and
  4263. ;; `contents-end'. Ensure GRANULARITY allows recursion,
  4264. ;; or ELEMENT is a headline, in which case going inside
  4265. ;; is mandatory, in order to get sub-level headings.
  4266. ((and (memq type org-element-greater-elements)
  4267. (or (memq granularity '(element object nil))
  4268. (and (eq granularity 'greater-element)
  4269. (eq type 'section))
  4270. (eq type 'headline)))
  4271. (org-element--parse-elements
  4272. cbeg (org-element-property :contents-end element)
  4273. ;; Possibly switch to a special mode.
  4274. (org-element--next-mode mode type t)
  4275. (and (memq type '(item plain-list))
  4276. (org-element-property :structure element))
  4277. granularity visible-only element))
  4278. ;; ELEMENT has contents. Parse objects inside, if
  4279. ;; GRANULARITY allows it.
  4280. ((memq granularity '(object nil))
  4281. (org-element--parse-objects
  4282. cbeg (org-element-property :contents-end element) element
  4283. (org-element-restriction type))))
  4284. (push (org-element-put-property element :parent acc) elements)
  4285. ;; Update mode.
  4286. (setq mode (org-element--next-mode mode type nil)))))
  4287. ;; Return result.
  4288. (org-element-put-property acc :granularity granularity)
  4289. (apply #'org-element-set-contents acc (nreverse elements)))))
  4290. (defun org-element--object-lex (restriction)
  4291. "Return next object in current buffer or nil.
  4292. RESTRICTION is a list of object types, as symbols, that should be
  4293. looked after. This function assumes that the buffer is narrowed
  4294. to an appropriate container (e.g., a paragraph)."
  4295. (cond
  4296. ((memq 'table-cell restriction) (org-element-table-cell-parser))
  4297. ((memq 'citation-reference restriction)
  4298. (org-element-citation-reference-parser))
  4299. (t
  4300. (let* ((start (point))
  4301. (limit
  4302. ;; Object regexp sometimes needs to have a peek at
  4303. ;; a character ahead. Therefore, when there is a hard
  4304. ;; limit, make it one more than the true beginning of the
  4305. ;; radio target.
  4306. (save-excursion
  4307. (cond ((not org-target-link-regexp) nil)
  4308. ((not (memq 'link restriction)) nil)
  4309. ((progn
  4310. (unless (bolp) (forward-char -1))
  4311. (not (re-search-forward org-target-link-regexp nil t)))
  4312. nil)
  4313. ;; Since we moved backward, we do not want to
  4314. ;; match again an hypothetical 1-character long
  4315. ;; radio link before us. Realizing that this can
  4316. ;; only happen if such a radio link starts at
  4317. ;; beginning of line, we prevent this here.
  4318. ((and (= start (1+ (line-beginning-position)))
  4319. (= start (match-end 1)))
  4320. (and (re-search-forward org-target-link-regexp nil t)
  4321. (1+ (match-beginning 1))))
  4322. (t (1+ (match-beginning 1))))))
  4323. found)
  4324. (save-excursion
  4325. (while (and (not found)
  4326. (re-search-forward org-element--object-regexp limit 'move))
  4327. (goto-char (match-beginning 0))
  4328. (let ((result (match-string 0)))
  4329. (setq found
  4330. (cond
  4331. ((string-prefix-p "call_" result t)
  4332. (and (memq 'inline-babel-call restriction)
  4333. (org-element-inline-babel-call-parser)))
  4334. ((string-prefix-p "src_" result t)
  4335. (and (memq 'inline-src-block restriction)
  4336. (org-element-inline-src-block-parser)))
  4337. (t
  4338. (pcase (char-after)
  4339. (?^ (and (memq 'superscript restriction)
  4340. (org-element-superscript-parser)))
  4341. (?_ (or (and (memq 'subscript restriction)
  4342. (org-element-subscript-parser))
  4343. (and (memq 'underline restriction)
  4344. (org-element-underline-parser))))
  4345. (?* (and (memq 'bold restriction)
  4346. (org-element-bold-parser)))
  4347. (?/ (and (memq 'italic restriction)
  4348. (org-element-italic-parser)))
  4349. (?~ (and (memq 'code restriction)
  4350. (org-element-code-parser)))
  4351. (?= (and (memq 'verbatim restriction)
  4352. (org-element-verbatim-parser)))
  4353. (?+ (and (memq 'strike-through restriction)
  4354. (org-element-strike-through-parser)))
  4355. (?@ (and (memq 'export-snippet restriction)
  4356. (org-element-export-snippet-parser)))
  4357. (?{ (and (memq 'macro restriction)
  4358. (org-element-macro-parser)))
  4359. (?$ (and (memq 'latex-fragment restriction)
  4360. (org-element-latex-fragment-parser)))
  4361. (?<
  4362. (if (eq (aref result 1) ?<)
  4363. (or (and (memq 'radio-target restriction)
  4364. (org-element-radio-target-parser))
  4365. (and (memq 'target restriction)
  4366. (org-element-target-parser)))
  4367. (or (and (memq 'timestamp restriction)
  4368. (org-element-timestamp-parser))
  4369. (and (memq 'link restriction)
  4370. (org-element-link-parser)))))
  4371. (?\\
  4372. (if (eq (aref result 1) ?\\)
  4373. (and (memq 'line-break restriction)
  4374. (org-element-line-break-parser))
  4375. (or (and (memq 'entity restriction)
  4376. (org-element-entity-parser))
  4377. (and (memq 'latex-fragment restriction)
  4378. (org-element-latex-fragment-parser)))))
  4379. (?\[
  4380. (pcase (aref result 1)
  4381. ((and ?\[
  4382. (guard (memq 'link restriction)))
  4383. (org-element-link-parser))
  4384. ((and ?f
  4385. (guard (memq 'footnote-reference restriction)))
  4386. (org-element-footnote-reference-parser))
  4387. ((and ?c
  4388. (guard (memq 'citation restriction)))
  4389. (org-element-citation-parser))
  4390. ((and (or ?% ?/)
  4391. (guard (memq 'statistics-cookie restriction)))
  4392. (org-element-statistics-cookie-parser))
  4393. (_
  4394. (or (and (memq 'timestamp restriction)
  4395. (org-element-timestamp-parser))
  4396. (and (memq 'statistics-cookie restriction)
  4397. (org-element-statistics-cookie-parser))))))
  4398. ;; This is probably a plain link.
  4399. (_ (and (memq 'link restriction)
  4400. (org-element-link-parser)))))))
  4401. (or (eobp) (forward-char))))
  4402. (cond (found)
  4403. (limit (forward-char -1)
  4404. (org-element-link-parser)) ;radio link
  4405. (t nil)))))))
  4406. (defun org-element--parse-objects (beg end acc restriction &optional parent)
  4407. "Parse objects between BEG and END and return recursive structure.
  4408. Objects are accumulated in ACC. RESTRICTION is a list of object
  4409. successors which are allowed in the current object.
  4410. ACC becomes the parent for all parsed objects. However, if ACC
  4411. is nil (i.e., a secondary string is being parsed) and optional
  4412. argument PARENT is non-nil, use it as the parent for all objects.
  4413. Eventually, if both ACC and PARENT are nil, the common parent is
  4414. the list of objects itself."
  4415. (save-excursion
  4416. (save-restriction
  4417. (narrow-to-region beg end)
  4418. (goto-char (point-min))
  4419. (let (next-object contents)
  4420. (while (and (not (eobp))
  4421. (setq next-object (org-element--object-lex restriction)))
  4422. ;; Text before any object.
  4423. (let ((obj-beg (org-element-property :begin next-object)))
  4424. (unless (= (point) obj-beg)
  4425. (let ((text (buffer-substring-no-properties (point) obj-beg)))
  4426. (push (if acc (org-element-put-property text :parent acc) text)
  4427. contents))))
  4428. ;; Object...
  4429. (let ((obj-end (org-element-property :end next-object))
  4430. (cont-beg (org-element-property :contents-begin next-object)))
  4431. (when acc (org-element-put-property next-object :parent acc))
  4432. (push (if cont-beg
  4433. ;; Fill contents of NEXT-OBJECT if possible.
  4434. (org-element--parse-objects
  4435. cont-beg
  4436. (org-element-property :contents-end next-object)
  4437. next-object
  4438. (org-element-restriction next-object))
  4439. next-object)
  4440. contents)
  4441. (goto-char obj-end)))
  4442. ;; Text after last object.
  4443. (unless (eobp)
  4444. (let ((text (buffer-substring-no-properties (point) end)))
  4445. (push (if acc (org-element-put-property text :parent acc) text)
  4446. contents)))
  4447. ;; Result. Set appropriate parent.
  4448. (if acc (apply #'org-element-set-contents acc (nreverse contents))
  4449. (let* ((contents (nreverse contents))
  4450. (parent (or parent contents)))
  4451. (dolist (datum contents contents)
  4452. (org-element-put-property datum :parent parent))))))))
  4453. ;;; Towards A Bijective Process
  4454. ;;
  4455. ;; The parse tree obtained with `org-element-parse-buffer' is really
  4456. ;; a snapshot of the corresponding Org buffer. Therefore, it can be
  4457. ;; interpreted and expanded into a string with canonical Org syntax.
  4458. ;; Hence `org-element-interpret-data'.
  4459. ;;
  4460. ;; The function relies internally on
  4461. ;; `org-element--interpret-affiliated-keywords'.
  4462. ;;;###autoload
  4463. (defun org-element-interpret-data (data)
  4464. "Interpret DATA as Org syntax.
  4465. DATA is a parse tree, an element, an object or a secondary string
  4466. to interpret. Return Org syntax as a string."
  4467. (letrec ((fun
  4468. (lambda (data parent)
  4469. (let* ((type (org-element-type data))
  4470. ;; Find interpreter for current object or
  4471. ;; element. If it doesn't exist (e.g. this is
  4472. ;; a pseudo object or element), return contents,
  4473. ;; if any.
  4474. (interpret
  4475. (let ((fun (intern
  4476. (format "org-element-%s-interpreter" type))))
  4477. (if (fboundp fun) fun (lambda (_ contents) contents))))
  4478. (results
  4479. (cond
  4480. ;; Secondary string.
  4481. ((not type)
  4482. (mapconcat (lambda (obj) (funcall fun obj parent))
  4483. data
  4484. ""))
  4485. ;; Full Org document.
  4486. ((eq type 'org-data)
  4487. (mapconcat (lambda (obj) (funcall fun obj parent))
  4488. (org-element-contents data)
  4489. ""))
  4490. ;; Plain text: return it.
  4491. ((stringp data) data)
  4492. ;; Element or object without contents.
  4493. ((not (org-element-contents data))
  4494. (funcall interpret data nil))
  4495. ;; Element or object with contents.
  4496. (t
  4497. (funcall
  4498. interpret
  4499. data
  4500. ;; Recursively interpret contents.
  4501. (mapconcat
  4502. (lambda (datum) (funcall fun datum data))
  4503. (org-element-contents
  4504. (if (not (memq type '(paragraph verse-block)))
  4505. data
  4506. ;; Fix indentation of elements containing
  4507. ;; objects. We ignore `table-row'
  4508. ;; elements as they are one line long
  4509. ;; anyway.
  4510. (org-element-normalize-contents
  4511. data
  4512. ;; When normalizing first paragraph of
  4513. ;; an item or a footnote-definition,
  4514. ;; ignore first line's indentation.
  4515. (and (eq type 'paragraph)
  4516. (memq (org-element-type parent)
  4517. '(footnote-definition item))
  4518. (eq data (car (org-element-contents parent)))
  4519. (eq (org-element-property :pre-blank parent)
  4520. 0)))))
  4521. ""))))))
  4522. (if (memq type '(org-data nil)) results
  4523. ;; Build white spaces. If no `:post-blank' property
  4524. ;; is specified, assume its value is 0.
  4525. (let ((blank (or (org-element-property :post-blank data) 0)))
  4526. (if (eq (org-element-class data parent) 'object)
  4527. (concat results (make-string blank ?\s))
  4528. (concat (org-element--interpret-affiliated-keywords data)
  4529. (org-element-normalize-string results)
  4530. (make-string blank ?\n)))))))))
  4531. (funcall fun data nil)))
  4532. (defun org-element--interpret-affiliated-keywords (element)
  4533. "Return ELEMENT's affiliated keywords as Org syntax.
  4534. If there is no affiliated keyword, return the empty string."
  4535. (let ((keyword-to-org
  4536. (lambda (key value)
  4537. (let (dual)
  4538. (when (member key org-element-dual-keywords)
  4539. (setq dual (cdr value) value (car value)))
  4540. (concat "#+" (downcase key)
  4541. (and dual
  4542. (format "[%s]" (org-element-interpret-data dual)))
  4543. ": "
  4544. (if (member key org-element-parsed-keywords)
  4545. (org-element-interpret-data value)
  4546. value)
  4547. "\n")))))
  4548. (mapconcat
  4549. (lambda (prop)
  4550. (let ((value (org-element-property prop element))
  4551. (keyword (upcase (substring (symbol-name prop) 1))))
  4552. (when value
  4553. (if (or (member keyword org-element-multiple-keywords)
  4554. ;; All attribute keywords can have multiple lines.
  4555. (string-match "^ATTR_" keyword))
  4556. (mapconcat (lambda (line) (funcall keyword-to-org keyword line))
  4557. (reverse value)
  4558. "")
  4559. (funcall keyword-to-org keyword value)))))
  4560. ;; List all ELEMENT's properties matching an attribute line or an
  4561. ;; affiliated keyword, but ignore translated keywords since they
  4562. ;; cannot belong to the property list.
  4563. (cl-loop for prop in (nth 1 element) by 'cddr
  4564. when (let ((keyword (upcase (substring (symbol-name prop) 1))))
  4565. (or (string-match "^ATTR_" keyword)
  4566. (and
  4567. (member keyword org-element-affiliated-keywords)
  4568. (not (assoc keyword
  4569. org-element-keyword-translation-alist)))))
  4570. collect prop)
  4571. "")))
  4572. ;; Because interpretation of the parse tree must return the same
  4573. ;; number of blank lines between elements and the same number of white
  4574. ;; space after objects, some special care must be given to white
  4575. ;; spaces.
  4576. ;;
  4577. ;; The first function, `org-element-normalize-string', ensures any
  4578. ;; string different from the empty string will end with a single
  4579. ;; newline character.
  4580. ;;
  4581. ;; The second function, `org-element-normalize-contents', removes
  4582. ;; global indentation from the contents of the current element.
  4583. (defun org-element-normalize-string (s)
  4584. "Ensure string S ends with a single newline character.
  4585. If S isn't a string return it unchanged. If S is the empty
  4586. string, return it. Otherwise, return a new string with a single
  4587. newline character at its end."
  4588. (cond
  4589. ((not (stringp s)) s)
  4590. ((string= "" s) "")
  4591. (t (and (string-match "\\(\n[ \t]*\\)*\\'" s)
  4592. (replace-match "\n" nil nil s)))))
  4593. (defun org-element-normalize-contents (element &optional ignore-first)
  4594. "Normalize plain text in ELEMENT's contents.
  4595. ELEMENT must only contain plain text and objects.
  4596. If optional argument IGNORE-FIRST is non-nil, ignore first line's
  4597. indentation to compute maximal common indentation.
  4598. Return the normalized element that is element with global
  4599. indentation removed from its contents."
  4600. (letrec ((find-min-ind
  4601. ;; Return minimal common indentation within BLOB. This is
  4602. ;; done by walking recursively BLOB and updating MIN-IND
  4603. ;; along the way. FIRST-FLAG is non-nil when the next
  4604. ;; object is expected to be a string that doesn't start
  4605. ;; with a newline character. It happens for strings at
  4606. ;; the beginnings of the contents or right after a line
  4607. ;; break.
  4608. (lambda (blob first-flag min-ind)
  4609. (dolist (datum (org-element-contents blob) min-ind)
  4610. (when first-flag
  4611. (setq first-flag nil)
  4612. (cond
  4613. ;; Objects cannot start with spaces: in this
  4614. ;; case, indentation is 0.
  4615. ((not (stringp datum)) (throw :zero 0))
  4616. ((not (string-match
  4617. "\\`\\([ \t]+\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum))
  4618. (throw :zero 0))
  4619. ((equal (match-string 2 datum) "\n")
  4620. (put-text-property
  4621. (match-beginning 1) (match-end 1) 'org-ind 'empty datum))
  4622. (t
  4623. (let ((i (string-width (match-string 1 datum))))
  4624. (put-text-property
  4625. (match-beginning 1) (match-end 1) 'org-ind i datum)
  4626. (setq min-ind (min i min-ind))))))
  4627. (cond
  4628. ((stringp datum)
  4629. (let ((s 0))
  4630. (while (string-match
  4631. "\n\\([ \t]*\\)\\([^ \t\n]\\|\n\\|\\'\\)" datum s)
  4632. (setq s (match-end 1))
  4633. (cond
  4634. ((equal (match-string 1 datum) "")
  4635. (unless (member (match-string 2 datum) '("" "\n"))
  4636. (throw :zero 0)))
  4637. ((equal (match-string 2 datum) "\n")
  4638. (put-text-property (match-beginning 1) (match-end 1)
  4639. 'org-ind 'empty datum))
  4640. (t
  4641. (let ((i (string-width (match-string 1 datum))))
  4642. (put-text-property (match-beginning 1) (match-end 1)
  4643. 'org-ind i datum)
  4644. (setq min-ind (min i min-ind))))))))
  4645. ((eq (org-element-type datum) 'line-break)
  4646. (setq first-flag t))
  4647. ((memq (org-element-type datum) org-element-recursive-objects)
  4648. (setq min-ind
  4649. (funcall find-min-ind datum first-flag min-ind)))))))
  4650. (min-ind
  4651. (catch :zero
  4652. (funcall find-min-ind
  4653. element (not ignore-first) most-positive-fixnum))))
  4654. (if (or (zerop min-ind) (= min-ind most-positive-fixnum)) element
  4655. ;; Build ELEMENT back, replacing each string with the same
  4656. ;; string minus common indentation.
  4657. (letrec ((build
  4658. (lambda (datum)
  4659. ;; Return DATUM with all its strings indentation
  4660. ;; shortened from MIN-IND white spaces.
  4661. (setcdr
  4662. (cdr datum)
  4663. (mapcar
  4664. (lambda (object)
  4665. (cond
  4666. ((stringp object)
  4667. (with-temp-buffer
  4668. (insert object)
  4669. (let ((s (point-min)))
  4670. (while (setq s (text-property-not-all
  4671. s (point-max) 'org-ind nil))
  4672. (goto-char s)
  4673. (let ((i (get-text-property s 'org-ind)))
  4674. (delete-region s (progn
  4675. (skip-chars-forward " \t")
  4676. (point)))
  4677. (when (integerp i) (indent-to (- i min-ind))))))
  4678. (buffer-string)))
  4679. ((memq (org-element-type object)
  4680. org-element-recursive-objects)
  4681. (funcall build object))
  4682. (t object)))
  4683. (org-element-contents datum)))
  4684. datum)))
  4685. (funcall build element)))))
  4686. ;;; Cache
  4687. ;;
  4688. ;; Implement a caching mechanism for `org-element-at-point', `org-element-context', and for
  4689. ;; fast mapping across Org elements in `org-element-cache-map', which see.
  4690. ;;
  4691. ;; When cache is enabled, the elements returned by `org-element-at-point' and
  4692. ;; `org-element-context' are returned by reference. Altering these elements will
  4693. ;; also alter their cache representation. The same is true for
  4694. ;; elements passed to mapping function in `org-element-cache-map'.
  4695. ;;
  4696. ;; Public functions are: `org-element-cache-reset', `org-element-cache-refresh', and
  4697. ;; `org-element-cache-map'.
  4698. ;;
  4699. ;; Cache can be controlled using `org-element-use-cache' and `org-element-cache-persistent'.
  4700. ;; `org-element-cache-sync-idle-time', `org-element-cache-sync-duration' and
  4701. ;; `org-element-cache-sync-break' can be tweaked to control caching behavior.
  4702. ;;
  4703. ;; Internally, parsed elements are stored in an AVL tree,
  4704. ;; `org-element--cache'. This tree is updated lazily: whenever
  4705. ;; a change happens to the buffer, a synchronization request is
  4706. ;; registered in `org-element--cache-sync-requests' (see
  4707. ;; `org-element--cache-submit-request'). During idle time, requests
  4708. ;; are processed by `org-element--cache-sync'. Synchronization also
  4709. ;; happens when an element is required from the cache. In this case,
  4710. ;; the process stops as soon as the needed element is up-to-date.
  4711. ;;
  4712. ;; A synchronization request can only apply on a synchronized part of
  4713. ;; the cache. Therefore, the cache is updated at least to the
  4714. ;; location where the new request applies. Thus, requests are ordered
  4715. ;; from left to right and all elements starting before the first
  4716. ;; request are correct. This property is used by functions like
  4717. ;; `org-element--cache-find' to retrieve elements in the part of the
  4718. ;; cache that can be trusted.
  4719. ;;
  4720. ;; A request applies to every element, starting from its original
  4721. ;; location (or key, see below). When a request is processed, it
  4722. ;; moves forward and may collide the next one. In this case, both
  4723. ;; requests are merged into a new one that starts from that element.
  4724. ;; As a consequence, the whole synchronization complexity does not
  4725. ;; depend on the number of pending requests, but on the number of
  4726. ;; elements the very first request will be applied on.
  4727. ;;
  4728. ;; Elements cannot be accessed through their beginning position, which
  4729. ;; may or may not be up-to-date. Instead, each element in the tree is
  4730. ;; associated to a key, obtained with `org-element--cache-key'. This
  4731. ;; mechanism is robust enough to preserve total order among elements
  4732. ;; even when the tree is only partially synchronized.
  4733. ;;
  4734. ;; The cache code debuggin is fairly complex because cache request
  4735. ;; state is often hard to reproduce. An extensive diagnostics
  4736. ;; functionality is built into the cache code to assist hunting bugs.
  4737. ;; See `org-element--cache-self-verify', `org-element--cache-self-verify-frequency',
  4738. ;; `org-element--cache-diagnostics', `org-element--cache-diagnostics-level',
  4739. ;; `org-element--cache-diagnostics-ring-size', `org-element--cache-map-statistics',
  4740. ;; `org-element--cache-map-statistics-threshold'.
  4741. (defvar org-element-use-cache t
  4742. "Non-nil when Org parser should cache its results.")
  4743. (defvar org-element-cache-persistent t
  4744. "Non-nil when cache should persist between Emacs sessions.")
  4745. (defvar org-element-cache-sync-idle-time 0.6
  4746. "Length, in seconds, of idle time before syncing cache.")
  4747. (defvar org-element-cache-sync-duration 0.04
  4748. "Maximum duration, as a time value, for a cache synchronization.
  4749. If the synchronization is not over after this delay, the process
  4750. pauses and resumes after `org-element-cache-sync-break'
  4751. seconds.")
  4752. (defvar org-element-cache-sync-break 0.3
  4753. "Duration, as a time value, of the pause between synchronizations.
  4754. See `org-element-cache-sync-duration' for more information.")
  4755. (defvar org-element--cache-self-verify t
  4756. "Activate extra consistency checks for the cache.
  4757. This may cause serious performance degradation depending on the value
  4758. of `org-element--cache-self-verify-frequency'.
  4759. When set to symbol `backtrace', record and display backtrace log if
  4760. any inconsistency is detected.")
  4761. (defvar org-element--cache-self-verify-frequency 0.03
  4762. "Frequency of cache element verification.
  4763. This number is a probability to check an element requested from cache
  4764. to be correct. Setting this to a value less than 0.0001 is useless.")
  4765. (defvar org-element--cache-diagnostics nil
  4766. "Print detailed diagnostics of cache processing.")
  4767. (defvar org-element--cache-map-statistics nil
  4768. "Print statistics for `org-element-cache-map'.")
  4769. (defvar org-element--cache-map-statistics-threshold 0.1
  4770. "Time threshold in seconds to log statistics for `org-element-cache-map'.")
  4771. (defvar org-element--cache-diagnostics-modifications t
  4772. "Non-nil enables cache warnings when for silent modifications.
  4773. Silent modifications are the modifications in Org buffers that are not
  4774. registered by `org-element--cache-before-change' and
  4775. `org-element--cache-after-change'.
  4776. This variable may cause false-positives because some Emacs versions
  4777. can change `buffer-chars-modified-tick' internally even though no
  4778. visible changes in buffer are being made. Some of such expected cases
  4779. are covered by heuristics, but not all.")
  4780. (defvar org-element--cache-silent-modification-check t
  4781. "Detect changes in buffer made inside `with-silent-modifications'.
  4782. Note that some internal Emacs functions may also trigger a warning and
  4783. cache reset. The warning can be suppressed by setting
  4784. `org-element--cache-diagnostics-modifications' to nil, but the cache
  4785. will still be refreshed to be safe.
  4786. WARNING: Setting this variable to nil may cause cache corruption is some
  4787. third-party packages make undetected changes in buffers.")
  4788. (defvar org-element--cache-diagnostics-level 2
  4789. "Detail level of the diagnostics.")
  4790. (defvar-local org-element--cache-diagnostics-ring nil
  4791. "Ring containing last `org-element--cache-diagnostics-ring-size'
  4792. cache process log entries.")
  4793. (defvar org-element--cache-diagnostics-ring-size 5000
  4794. "Size of `org-element--cache-diagnostics-ring'.")
  4795. ;;;; Data Structure
  4796. (defvar-local org-element--cache nil
  4797. "AVL tree used to cache elements.
  4798. Each node of the tree contains an element. Comparison is done
  4799. with `org-element--cache-compare'. This cache is used in
  4800. `org-element-at-point'.")
  4801. (defvar-local org-element--headline-cache nil
  4802. "AVL tree used to cache headline and inlinetask elements.
  4803. Each node of the tree contains an element. Comparison is done
  4804. with `org-element--cache-compare'. This cache is used in
  4805. `org-element-cache-map'.")
  4806. (defvar-local org-element--cache-size 0
  4807. "Size of the `org-element--cache'.
  4808. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4809. (defvar-local org-element--headline-cache-size 0
  4810. "Size of the `org-element--headline-cache'.
  4811. Storing value is variable is faster because `avl-tree-size' is O(N).")
  4812. (defvar-local org-element--cache-sync-requests nil
  4813. "List of pending synchronization requests.
  4814. A request is a vector with the following pattern:
  4815. [NEXT BEG END OFFSET PARENT PHASE]
  4816. Processing a synchronization request consists of three phases:
  4817. 0. Delete modified elements,
  4818. 1. Fill missing area in cache,
  4819. 2. Shift positions and re-parent elements after the changes.
  4820. During phase 0, NEXT is the key of the first element to be
  4821. removed, BEG and END is buffer position delimiting the
  4822. modifications. Elements starting between them (inclusive) are
  4823. removed. So are elements whose parent is removed. PARENT, when
  4824. non-nil, is the common parent of all the elements between BEG and END.
  4825. It is guaranteed that only a single phase 0 request exists at any
  4826. moment of time. If it does, it must be the first request in the list.
  4827. During phase 1, NEXT is the key of the next known element in
  4828. cache and BEG its beginning position. Parse buffer between that
  4829. element and the one before it in order to determine the parent of
  4830. the next element. Set PARENT to the element containing NEXT.
  4831. During phase 2, NEXT is the key of the next element to shift in
  4832. the parse tree. All elements starting from this one have their
  4833. properties relative to buffer positions shifted by integer
  4834. OFFSET and, if they belong to element PARENT, are adopted by it.
  4835. PHASE specifies the phase number, as an integer.
  4836. For any synchronisation request, all the later requests in the cache
  4837. must not start at or before END. See `org-element--cache-submit-request'.")
  4838. (defvar-local org-element--cache-sync-timer nil
  4839. "Timer used for cache synchronization.")
  4840. (defvar-local org-element--cache-sync-keys-value nil
  4841. "Id value used to identify keys during synchronisation.
  4842. See `org-element--cache-key' for more information.")
  4843. (defvar-local org-element--cache-change-tic nil
  4844. "Last `buffer-chars-modified-tick' for registered changes.")
  4845. (defvar org-element--cache-non-modifying-commands '(org-agenda
  4846. org-agenda-redo
  4847. org-sparse-tree
  4848. org-occur
  4849. org-columns
  4850. org-columns-redo
  4851. org-columns-new
  4852. org-columns-delete
  4853. org-columns-compute
  4854. org-columns-insert-dblock
  4855. org-agenda-columns
  4856. org-ctrl-c-ctrl-c)
  4857. "List of commands that are not expected to change the cache state.
  4858. This variable is used to determine when re-parsing buffer is not going
  4859. to slow down the command.
  4860. If the commends end up modifying the cache, the worst case scenario is
  4861. performance drop. So, advicing these commands is safe. Yet, it is
  4862. better to remove the commands adviced in such way from this list.")
  4863. (defmacro org-element--request-key (request)
  4864. "Get NEXT part of a `org-element--cache-sync-requests' REQUEST."
  4865. `(aref ,request 0))
  4866. (defmacro org-element--request-beg (request)
  4867. "Get BEG part of a `org-element--cache-sync-requests' REQUEST."
  4868. `(aref ,request 1))
  4869. (defmacro org-element--request-end (request)
  4870. "Get END part of a `org-element--cache-sync-requests' REQUEST."
  4871. `(aref ,request 2))
  4872. (defmacro org-element--request-offset (request)
  4873. "Get OFFSET part of a `org-element--cache-sync-requests' REQUEST."
  4874. `(aref ,request 3))
  4875. (defmacro org-element--request-parent (request)
  4876. "Get PARENT part of a `org-element--cache-sync-requests' REQUEST."
  4877. `(aref ,request 4))
  4878. (defmacro org-element--request-phase (request)
  4879. "Get PHASE part of a `org-element--cache-sync-requests' REQUEST."
  4880. `(aref ,request 5))
  4881. (defmacro org-element--format-element (element)
  4882. "Format ELEMENT for printing in diagnostics."
  4883. `(let ((print-length 50)
  4884. (print-level 5))
  4885. (prin1-to-string ,element)))
  4886. (defmacro org-element--cache-log-message (format-string &rest args)
  4887. "Add a new log message for org-element-cache."
  4888. `(when (or org-element--cache-diagnostics
  4889. (eq org-element--cache-self-verify 'backtrace))
  4890. (let* ((format-string (concat (format "org-element-cache diagnostics(%s): "
  4891. (buffer-name (current-buffer)))
  4892. ,format-string))
  4893. (format-string (funcall #'format format-string ,@args)))
  4894. (if org-element--cache-diagnostics
  4895. (display-warning 'org-element-cache format-string)
  4896. (unless org-element--cache-diagnostics-ring
  4897. (setq org-element--cache-diagnostics-ring
  4898. (make-ring org-element--cache-diagnostics-ring-size)))
  4899. (ring-insert org-element--cache-diagnostics-ring format-string)))))
  4900. (defmacro org-element--cache-warn (format-string &rest args)
  4901. "Raise warning for org-element-cache."
  4902. `(let* ((format-string (funcall #'format ,format-string ,@args))
  4903. (format-string
  4904. (if (or (not org-element--cache-diagnostics-ring)
  4905. (not (eq 'backtrace org-element--cache-self-verify)))
  4906. format-string
  4907. (prog1
  4908. (concat (format "Warning(%s): "
  4909. (buffer-name (current-buffer)))
  4910. format-string
  4911. "\nBacktrace:\n "
  4912. (mapconcat #'identity
  4913. (ring-elements org-element--cache-diagnostics-ring)
  4914. "\n "))
  4915. (setq org-element--cache-diagnostics-ring nil)))))
  4916. (if (and (boundp 'org-batch-test) org-batch-test)
  4917. (error "%s" (concat "org-element--cache: " format-string))
  4918. (display-warning 'org-element-cache
  4919. (concat "org-element--cache: " format-string)))))
  4920. (defsubst org-element--cache-key (element)
  4921. "Return a unique key for ELEMENT in cache tree.
  4922. Keys are used to keep a total order among elements in the cache.
  4923. Comparison is done with `org-element--cache-key-less-p'.
  4924. When no synchronization is taking place, a key is simply the
  4925. beginning position of the element, or that position plus one in
  4926. the case of an first item (respectively row) in
  4927. a list (respectively a table). They key of a section is its beginning
  4928. position minus one.
  4929. During a synchronization, the key is the one the element had when
  4930. the cache was synchronized for the last time. Elements added to
  4931. cache during the synchronization get a new key generated with
  4932. `org-element--cache-generate-key'.
  4933. Such keys are stored inside the element property
  4934. `:org-element--cache-sync-key'. The property is a cons containing
  4935. current `org-element--cache-sync-keys-value' and the element key."
  4936. (or (when (eq org-element--cache-sync-keys-value (car (org-element-property :org-element--cache-sync-key element)))
  4937. (cdr (org-element-property :org-element--cache-sync-key element)))
  4938. (let* ((begin (org-element-property :begin element))
  4939. ;; Increase beginning position of items (respectively
  4940. ;; table rows) by one, so the first item can get
  4941. ;; a different key from its parent list (respectively
  4942. ;; table).
  4943. (key (if (memq (org-element-type element) '(item table-row))
  4944. (1+ begin)
  4945. ;; Decrease beginning position of sections by one,
  4946. ;; so that the first element of the section get
  4947. ;; different key from the parent section.
  4948. (if (eq (org-element-type element) 'section)
  4949. (1- begin)
  4950. (if (eq (org-element-type element) 'org-data)
  4951. (- begin 2)
  4952. begin)))))
  4953. (when org-element--cache-sync-requests
  4954. (org-element-put-property element
  4955. :org-element--cache-sync-key
  4956. (cons org-element--cache-sync-keys-value key)))
  4957. key)))
  4958. (defun org-element--cache-generate-key (lower upper)
  4959. "Generate a key between LOWER and UPPER.
  4960. LOWER and UPPER are fixnums or lists of same, possibly empty.
  4961. If LOWER and UPPER are equals, return LOWER. Otherwise, return
  4962. a unique key, as an integer or a list of integers, according to
  4963. the following rules:
  4964. - LOWER and UPPER are compared level-wise until values differ.
  4965. - If, at a given level, LOWER and UPPER differ from more than
  4966. 2, the new key shares all the levels above with LOWER and
  4967. gets a new level. Its value is the mean between LOWER and
  4968. UPPER:
  4969. (1 2) + (1 4) --> (1 3)
  4970. - If LOWER has no value to compare with, it is assumed that its
  4971. value is `most-negative-fixnum'. E.g.,
  4972. (1 1) + (1 1 2)
  4973. is equivalent to
  4974. (1 1 m) + (1 1 2)
  4975. where m is `most-negative-fixnum'. Likewise, if UPPER is
  4976. short of levels, the current value is `most-positive-fixnum'.
  4977. - If they differ from only one, the new key inherits from
  4978. current LOWER level and fork it at the next level. E.g.,
  4979. (2 1) + (3 3)
  4980. is equivalent to
  4981. (2 1) + (2 M)
  4982. where M is `most-positive-fixnum'.
  4983. - If the key is only one level long, it is returned as an
  4984. integer:
  4985. (1 2) + (3 2) --> 2
  4986. When they are not equals, the function assumes that LOWER is
  4987. lesser than UPPER, per `org-element--cache-key-less-p'."
  4988. (if (equal lower upper) lower
  4989. (let ((lower (if (integerp lower) (list lower) lower))
  4990. (upper (if (integerp upper) (list upper) upper))
  4991. skip-upper key)
  4992. (catch 'exit
  4993. (while t
  4994. (let ((min (or (car lower) most-negative-fixnum))
  4995. (max (cond (skip-upper most-positive-fixnum)
  4996. ((car upper))
  4997. (t most-positive-fixnum))))
  4998. (if (< (1+ min) max)
  4999. (let ((mean (+ (ash min -1) (ash max -1) (logand min max 1))))
  5000. (throw 'exit (if key (nreverse (cons mean key)) mean)))
  5001. (when (and (< min max) (not skip-upper))
  5002. ;; When at a given level, LOWER and UPPER differ from
  5003. ;; 1, ignore UPPER altogether. Instead create a key
  5004. ;; between LOWER and the greatest key with the same
  5005. ;; prefix as LOWER so far.
  5006. (setq skip-upper t))
  5007. (push min key)
  5008. (setq lower (cdr lower) upper (cdr upper)))))))))
  5009. (defsubst org-element--cache-key-less-p (a b)
  5010. "Non-nil if key A is less than key B.
  5011. A and B are either integers or lists of integers, as returned by
  5012. `org-element--cache-key'."
  5013. (if (integerp a) (if (integerp b) (< a b) (<= a (car b)))
  5014. (if (integerp b) (< (car a) b)
  5015. (catch 'exit
  5016. (while (and a b)
  5017. (cond ((car-less-than-car a b) (throw 'exit t))
  5018. ((car-less-than-car b a) (throw 'exit nil))
  5019. (t (setq a (cdr a) b (cdr b)))))
  5020. ;; If A is empty, either keys are equal (B is also empty) and
  5021. ;; we return nil, or A is lesser than B (B is longer) and we
  5022. ;; return a non-nil value.
  5023. ;;
  5024. ;; If A is not empty, B is necessarily empty and A is greater
  5025. ;; than B (A is longer). Therefore, return nil.
  5026. (and (null a) b)))))
  5027. (defun org-element--cache-compare (a b)
  5028. "Non-nil when element A is located before element B."
  5029. (org-element--cache-key-less-p (org-element--cache-key a) (org-element--cache-key b)))
  5030. (defsubst org-element--cache-root ()
  5031. "Return root value in `org-element--cache' .
  5032. This function assumes `org-element--cache' is a valid AVL tree."
  5033. (avl-tree--node-left (avl-tree--dummyroot org-element--cache)))
  5034. (defsubst org-element--headline-cache-root ()
  5035. "Return root value in `org-element--headline-cache' .
  5036. This function assumes `org-element--headline-cache' is a valid AVL tree."
  5037. (avl-tree--node-left (avl-tree--dummyroot org-element--headline-cache)))
  5038. ;;;; Tools
  5039. (defun org-element--cache-active-p (&optional called-from-cache-change-func-p)
  5040. "Non-nil when cache is active in current buffer."
  5041. (and org-element-use-cache
  5042. org-element--cache
  5043. (derived-mode-p 'org-mode)
  5044. (or called-from-cache-change-func-p
  5045. (and
  5046. ;; org-num-mode calls some Org structure analysis functions
  5047. ;; that can trigger cache update in the middle of changes. See
  5048. ;; `org-num--verify' calling `org-num--skip-value' calling
  5049. ;; `org-entry-get' that uses cache.
  5050. ;; Forcefully disable cache when called from inside a
  5051. ;; modification hook, where `inhibit-modification-hooks' is set
  5052. ;; to t.
  5053. (not inhibit-modification-hooks)
  5054. ;; `combine-change-calls' sets `after-change-functions' to
  5055. ;; nil. We need not to use cache inside
  5056. ;; `combine-change-calls' because the buffer is potentially
  5057. ;; changed without notice (the change will be registered
  5058. ;; after exiting the `combine-change-calls' body though).
  5059. (memq #'org-element--cache-after-change after-change-functions))
  5060. (eq org-element--cache-change-tic (buffer-chars-modified-tick)))))
  5061. (defun org-element--cache-find (pos &optional side)
  5062. "Find element in cache starting at POS or before.
  5063. POS refers to a buffer position.
  5064. When optional argument SIDE is non-nil, the function checks for
  5065. elements starting at or past POS instead. If SIDE is `both', the
  5066. function returns a cons cell where car is the first element
  5067. starting at or before POS and cdr the first element starting
  5068. after POS.
  5069. The function can only find elements in the synchronized part of
  5070. the cache."
  5071. (with-current-buffer (or (buffer-base-buffer) (current-buffer))
  5072. (let ((limit (and org-element--cache-sync-requests
  5073. (org-element--request-key (car org-element--cache-sync-requests))))
  5074. (node (org-element--cache-root))
  5075. lower upper)
  5076. (while node
  5077. (let* ((element (avl-tree--node-data node))
  5078. (begin (org-element-property :begin element)))
  5079. (cond
  5080. ((and limit
  5081. (not (org-element--cache-key-less-p
  5082. (org-element--cache-key element) limit)))
  5083. (setq node (avl-tree--node-left node)))
  5084. ((> begin pos)
  5085. (setq upper element
  5086. node (avl-tree--node-left node)))
  5087. ((or (< begin pos)
  5088. ;; If the element is section or org-data, we also need
  5089. ;; to check the following element.
  5090. (memq (org-element-type element) '(section org-data)))
  5091. (setq lower element
  5092. node (avl-tree--node-right node)))
  5093. ;; We found an element in cache starting at POS. If `side'
  5094. ;; is `both' we also want the next one in order to generate
  5095. ;; a key in-between.
  5096. ;;
  5097. ;; If the element is the first row or item in a table or
  5098. ;; a plain list, we always return the table or the plain
  5099. ;; list.
  5100. ;;
  5101. ;; In any other case, we return the element found.
  5102. ((eq side 'both)
  5103. (setq lower element)
  5104. (setq node (avl-tree--node-right node)))
  5105. ((and (memq (org-element-type element) '(item table-row))
  5106. (let ((parent (org-element-property :parent element)))
  5107. (and (= (org-element-property :begin element)
  5108. (org-element-property :contents-begin parent))
  5109. (setq node nil
  5110. lower parent
  5111. upper parent)))))
  5112. (t
  5113. (setq node nil
  5114. lower element
  5115. upper element)))))
  5116. (pcase side
  5117. (`both (cons lower upper))
  5118. (`nil lower)
  5119. (_ upper)))))
  5120. (defun org-element--cache-put (element)
  5121. "Store ELEMENT in current buffer's cache, if allowed."
  5122. (when (org-element--cache-active-p)
  5123. (when org-element--cache-sync-requests
  5124. ;; During synchronization, first build an appropriate key for
  5125. ;; the new element so `avl-tree-enter' can insert it at the
  5126. ;; right spot in the cache.
  5127. (let* ((keys (org-element--cache-find
  5128. (org-element-property :begin element) 'both))
  5129. (new-key (org-element--cache-generate-key
  5130. (and (car keys) (org-element--cache-key (car keys)))
  5131. (cond ((cdr keys) (org-element--cache-key (cdr keys)))
  5132. (org-element--cache-sync-requests
  5133. (org-element--request-key (car org-element--cache-sync-requests)))))))
  5134. (org-element-put-property element
  5135. :org-element--cache-sync-key
  5136. (cons org-element--cache-sync-keys-value new-key))))
  5137. (when (>= org-element--cache-diagnostics-level 2)
  5138. (org-element--cache-log-message "Added new element with %S key: %S"
  5139. (org-element-property :org-element--cache-sync-key element)
  5140. (org-element--format-element element)))
  5141. (org-element-put-property element :cached t)
  5142. (when (memq (org-element-type element) '(headline inlinetask))
  5143. (cl-incf org-element--headline-cache-size)
  5144. (avl-tree-enter org-element--headline-cache element))
  5145. (cl-incf org-element--cache-size)
  5146. (avl-tree-enter org-element--cache element)))
  5147. (defsubst org-element--cache-remove (element)
  5148. "Remove ELEMENT from cache.
  5149. Assume ELEMENT belongs to cache and that a cache is active."
  5150. (org-element-put-property element :cached nil)
  5151. (cl-decf org-element--cache-size)
  5152. ;; Invalidate contents of parent.
  5153. (when (and (org-element-property :parent element)
  5154. (org-element-contents (org-element-property :parent element)))
  5155. (org-element-set-contents (org-element-property :parent element) nil))
  5156. (when (memq (org-element-type element) '(headline inlinetask))
  5157. (cl-decf org-element--headline-cache-size)
  5158. (avl-tree-delete org-element--headline-cache element))
  5159. (or (avl-tree-delete org-element--cache element)
  5160. (progn
  5161. ;; This should not happen, but if it is, would be better to know
  5162. ;; where it happens.
  5163. (org-element--cache-warn "Failed to delete %S element in %S at %S. The element cache key was %S.
  5164. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5165. (org-element-type element)
  5166. (current-buffer)
  5167. (org-element-property :begin element)
  5168. (org-element-property :org-element--cache-sync-key element))
  5169. (org-element-cache-reset)
  5170. (throw 'quit nil))))
  5171. ;;;; Synchronization
  5172. (defsubst org-element--cache-set-timer (buffer)
  5173. "Set idle timer for cache synchronization in BUFFER."
  5174. (when org-element--cache-sync-timer
  5175. (cancel-timer org-element--cache-sync-timer))
  5176. (setq org-element--cache-sync-timer
  5177. (run-with-idle-timer
  5178. (let ((idle (current-idle-time)))
  5179. (if idle (time-add idle org-element-cache-sync-break)
  5180. org-element-cache-sync-idle-time))
  5181. nil
  5182. #'org-element--cache-sync
  5183. buffer)))
  5184. (defsubst org-element--cache-interrupt-p (time-limit)
  5185. "Non-nil when synchronization process should be interrupted.
  5186. TIME-LIMIT is a time value or nil."
  5187. (and time-limit
  5188. (or (input-pending-p)
  5189. (time-less-p time-limit nil))))
  5190. (defsubst org-element--cache-shift-positions (element offset &optional props)
  5191. "Shift ELEMENT properties relative to buffer positions by OFFSET.
  5192. Properties containing buffer positions are `:begin', `:end',
  5193. `:contents-begin', `:contents-end' and `:structure'. When
  5194. optional argument PROPS is a list of keywords, only shift
  5195. properties provided in that list.
  5196. Properties are modified by side-effect."
  5197. (let ((properties (nth 1 element)))
  5198. ;; Shift `:structure' property for the first plain list only: it
  5199. ;; is the only one that really matters and it prevents from
  5200. ;; shifting it more than once.
  5201. (when (and (or (not props) (memq :structure props))
  5202. (eq (org-element-type element) 'plain-list)
  5203. (not (eq (org-element-type (plist-get properties :parent)) 'item)))
  5204. (dolist (item (plist-get properties :structure))
  5205. (cl-incf (car item) offset)
  5206. (cl-incf (nth 6 item) offset)))
  5207. (dolist (key '( :begin :contents-begin :contents-end :end
  5208. :post-affiliated :robust-begin :robust-end))
  5209. (let ((value (and (or (not props) (memq key props))
  5210. (plist-get properties key))))
  5211. (and value (plist-put properties key (+ offset value)))))))
  5212. (defvar org-element--cache-interrupt-C-g t
  5213. "When non-nil, allow the user to abort `org-element--cache-sync'.
  5214. The execution is aborted upon pressing `\\[keyboard-quit]'
  5215. `org-element--cache-interrupt-C-g-max-count' times.")
  5216. (defvar org-element--cache-interrupt-C-g-max-count 5
  5217. "`\\[keyboard-quit]' count to interrupt `org-element--cache-sync'.
  5218. See `org-element--cache-interrupt-C-g'.")
  5219. (defvar org-element--cache-interrupt-C-g-count 0
  5220. "Current number of `org-element--cache-sync' calls.
  5221. See `org-element--cache-interrupt-C-g'.")
  5222. (defvar org-element--cache-change-warning nil
  5223. "Non-nil when a sensitive line is about to be changed.
  5224. It is a symbol among nil, t, or a number representing smallest level of
  5225. modified headline. The level considers headline levels both before
  5226. and after the modification.")
  5227. (defun org-element--cache-sync (buffer &optional threshold future-change offset)
  5228. "Synchronize cache with recent modification in BUFFER.
  5229. When optional argument THRESHOLD is non-nil, do the
  5230. synchronization for all elements starting before or at threshold,
  5231. then exit. Otherwise, synchronize cache for as long as
  5232. `org-element-cache-sync-duration' or until Emacs leaves idle
  5233. state.
  5234. FUTURE-CHANGE, when non-nil, is a buffer position where changes
  5235. not registered yet in the cache are going to happen. OFFSET is the
  5236. change offset. It is used in `org-element--cache-submit-request',
  5237. where cache is partially updated before current modification are
  5238. actually submitted."
  5239. (when (buffer-live-p buffer)
  5240. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  5241. ;; Check if the buffer have been changed outside visibility of
  5242. ;; `org-element--cache-before-change' and `org-element--cache-after-change'.
  5243. (if (and (/= org-element--cache-change-tic
  5244. (buffer-chars-modified-tick))
  5245. org-element--cache-silent-modification-check
  5246. ;; FIXME: Below is a heuristics noticed by observation.
  5247. ;; quail.el with non-latin input does silent
  5248. ;; modifications in buffer increasing the tick counter
  5249. ;; but not actually changing the buffer text:
  5250. ;; https://list.orgmode.org/87sfw2luhj.fsf@localhost/T/#you
  5251. ;; https://lists.gnu.org/archive/html/bug-gnu-emacs/2021-11/msg00894.html
  5252. ;; However, the values of `buffer-chars-modified-tick'
  5253. ;; and `buffer-modified-tick' appear to be same after
  5254. ;; the quail.el's changes in buffer. We do not
  5255. ;; consider these exact changes as a dangerous silent
  5256. ;; edit.
  5257. (/= (buffer-chars-modified-tick)
  5258. (buffer-modified-tick)))
  5259. (progn
  5260. (when (or (and org-element--cache-diagnostics-modifications
  5261. ;; A number of Emacs internal operations in
  5262. ;; Emacs 26 and 27 alter
  5263. ;; `buffer-chars-modified-tick' (see
  5264. ;; https://list.orgmode.org/87ee7jdv70.fsf@localhost/T/#t
  5265. ;; https://list.orgmode.org/2022-01-06T12-13-17@devnull.Karl-Voit.at/T/#mb3771758f81b31721ba2f420878a4d16081dc483).
  5266. ;; We have no way to distinguish them from
  5267. ;; dangerious silent edits. So, we can
  5268. ;; only reset the cache, but do not show
  5269. ;; warning to not irritate the users.)
  5270. (not (version< emacs-version "28")))
  5271. (and (boundp 'org-batch-test) org-batch-test))
  5272. (org-element--cache-warn "Unregistered buffer modifications detected. Resetting.
  5273. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  5274. The buffer is: %s\n Current command: %S\n Chars modified: %S\n Buffer modified: %S\n Backtrace:\n%S"
  5275. (buffer-name (current-buffer))
  5276. (list this-command (buffer-chars-modified-tick) (buffer-modified-tick))
  5277. (buffer-chars-modified-tick)
  5278. (buffer-modified-tick)
  5279. (when (and (fboundp 'backtrace-get-frames)
  5280. (fboundp 'backtrace-to-string))
  5281. (backtrace-to-string (backtrace-get-frames 'backtrace)))))
  5282. (org-element-cache-reset))
  5283. (let ((inhibit-quit t) request next)
  5284. (setq org-element--cache-interrupt-C-g-count 0)
  5285. (when org-element--cache-sync-timer
  5286. (cancel-timer org-element--cache-sync-timer))
  5287. (let ((time-limit (time-add nil org-element-cache-sync-duration)))
  5288. (catch 'org-element--cache-interrupt
  5289. (when org-element--cache-sync-requests
  5290. (org-element--cache-log-message "Syncing down to %S-%S" (or future-change threshold) threshold))
  5291. (while org-element--cache-sync-requests
  5292. (setq request (car org-element--cache-sync-requests)
  5293. next (nth 1 org-element--cache-sync-requests))
  5294. (org-element--cache-process-request
  5295. request
  5296. (when next (org-element--request-key next))
  5297. threshold
  5298. (unless threshold time-limit)
  5299. future-change
  5300. offset)
  5301. ;; Re-assign current and next requests. It could have
  5302. ;; been altered during phase 1.
  5303. (setq request (car org-element--cache-sync-requests)
  5304. next (nth 1 org-element--cache-sync-requests))
  5305. ;; Request processed. Merge current and next offsets and
  5306. ;; transfer ending position.
  5307. (when next
  5308. ;; The following requests can only be either phase 1
  5309. ;; or phase 2 requests. We need to let them know
  5310. ;; that additional shifting happened ahead of them.
  5311. (cl-incf (org-element--request-offset next) (org-element--request-offset request))
  5312. (org-element--cache-log-message "Updating next request offset to %S: %s"
  5313. (org-element--request-offset next)
  5314. (let ((print-length 10) (print-level 3)) (prin1-to-string next)))
  5315. ;; FIXME: END part of the request only matters for
  5316. ;; phase 0 requests. However, the only possible
  5317. ;; phase 0 request must be the first request in the
  5318. ;; list all the time. END position should be
  5319. ;; unused.
  5320. (setf (org-element--request-end next) (org-element--request-end request)))
  5321. (setq org-element--cache-sync-requests
  5322. (cdr org-element--cache-sync-requests)))))
  5323. ;; If more requests are awaiting, set idle timer accordingly.
  5324. ;; Otherwise, reset keys.
  5325. (if org-element--cache-sync-requests
  5326. (org-element--cache-set-timer buffer)
  5327. (setq org-element--cache-change-warning nil)
  5328. (setq org-element--cache-sync-keys-value (1+ org-element--cache-sync-keys-value))))))))
  5329. (defun org-element--cache-process-request
  5330. (request next-request-key threshold time-limit future-change offset)
  5331. "Process synchronization REQUEST for all entries before NEXT.
  5332. REQUEST is a vector, built by `org-element--cache-submit-request'.
  5333. NEXT-REQUEST-KEY is a cache key of the next request, as returned by
  5334. `org-element--cache-key'.
  5335. When non-nil, THRESHOLD is a buffer position. Synchronization
  5336. stops as soon as a shifted element begins after it.
  5337. When non-nil, TIME-LIMIT is a time value. Synchronization stops
  5338. after this time or when Emacs exits idle state.
  5339. When non-nil, FUTURE-CHANGE is a buffer position where changes not
  5340. registered yet in the cache are going to happen. OFFSET is the
  5341. changed text length. See `org-element--cache-submit-request' for more
  5342. information.
  5343. Throw `org-element--cache-interrupt' if the process stops before
  5344. completing the request."
  5345. (org-element--cache-log-message "org-element-cache: Processing request %s up to %S-%S, next: %S"
  5346. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5347. future-change
  5348. threshold
  5349. next-request-key)
  5350. (catch 'org-element--cache-quit
  5351. (when (= (org-element--request-phase request) 0)
  5352. ;; Phase 0.
  5353. ;;
  5354. ;; Delete all elements starting after beginning of the element
  5355. ;; with request key NEXT, but not after buffer position END.
  5356. ;;
  5357. ;; At each iteration, we start again at tree root since
  5358. ;; a deletion modifies structure of the balanced tree.
  5359. (org-element--cache-log-message "Phase 0")
  5360. (catch 'org-element--cache-end-phase
  5361. (let ((deletion-count 0))
  5362. (while t
  5363. (when (org-element--cache-interrupt-p time-limit)
  5364. (org-element--cache-log-message "Interrupt: time limit")
  5365. (throw 'org-element--cache-interrupt nil))
  5366. (let ((request-key (org-element--request-key request))
  5367. (end (org-element--request-end request))
  5368. (node (org-element--cache-root))
  5369. data data-key)
  5370. ;; Find first element in cache with key REQUEST-KEY or
  5371. ;; after it.
  5372. (while node
  5373. (let* ((element (avl-tree--node-data node))
  5374. (key (org-element--cache-key element)))
  5375. (cond
  5376. ((org-element--cache-key-less-p key request-key)
  5377. (setq node (avl-tree--node-right node)))
  5378. ((org-element--cache-key-less-p request-key key)
  5379. (setq data element
  5380. data-key key
  5381. node (avl-tree--node-left node)))
  5382. (t (setq data element
  5383. data-key key
  5384. node nil)))))
  5385. (if data
  5386. ;; We found first element in cache starting at or
  5387. ;; after REQUEST-KEY.
  5388. (let ((pos (org-element-property :begin data)))
  5389. ;; FIXME: Maybe simply (< pos end)?
  5390. (if (<= pos end)
  5391. (progn
  5392. (org-element--cache-log-message "removing %S::%S"
  5393. (org-element-property :org-element--cache-sync-key data)
  5394. (org-element--format-element data))
  5395. (cl-incf deletion-count)
  5396. (org-element--cache-remove data)
  5397. (when (and (> (log org-element--cache-size 2) 10)
  5398. (> deletion-count
  5399. (/ org-element--cache-size (log org-element--cache-size 2))))
  5400. (org-element--cache-log-message "Removed %S>N/LogN(=%S/%S) elements. Resetting cache to prevent performance degradation"
  5401. deletion-count
  5402. org-element--cache-size
  5403. (log org-element--cache-size 2))
  5404. (org-element-cache-reset)
  5405. (throw 'org-element--cache-quit t)))
  5406. ;; Done deleting everthing starting before END.
  5407. ;; DATA-KEY is the first known element after END.
  5408. ;; Move on to phase 1.
  5409. (org-element--cache-log-message "found element after %S: %S::%S"
  5410. end
  5411. (org-element-property :org-element--cache-sync-key data)
  5412. (org-element--format-element data))
  5413. (setf (org-element--request-key request) data-key)
  5414. (setf (org-element--request-beg request) pos)
  5415. (setf (org-element--request-phase request) 1)
  5416. (throw 'org-element--cache-end-phase nil)))
  5417. ;; No element starting after modifications left in
  5418. ;; cache: further processing is futile.
  5419. (org-element--cache-log-message "Phase 0 deleted all elements in cache after %S!"
  5420. request-key)
  5421. (throw 'org-element--cache-quit t)))))))
  5422. (when (= (org-element--request-phase request) 1)
  5423. ;; Phase 1.
  5424. ;;
  5425. ;; Phase 0 left a hole in the cache. Some elements after it
  5426. ;; could have parents within. For example, in the following
  5427. ;; buffer:
  5428. ;;
  5429. ;; - item
  5430. ;;
  5431. ;;
  5432. ;; Paragraph1
  5433. ;;
  5434. ;; Paragraph2
  5435. ;;
  5436. ;; if we remove a blank line between "item" and "Paragraph1",
  5437. ;; everything down to "Paragraph2" is removed from cache. But
  5438. ;; the paragraph now belongs to the list, and its `:parent'
  5439. ;; property no longer is accurate.
  5440. ;;
  5441. ;; Therefore we need to parse again elements in the hole, or at
  5442. ;; least in its last section, so that we can re-parent
  5443. ;; subsequent elements, during phase 2.
  5444. ;;
  5445. ;; Note that we only need to get the parent from the first
  5446. ;; element in cache after the hole.
  5447. ;;
  5448. ;; When next key is lesser or equal to the current one, current
  5449. ;; request is inside a to-be-shifted part of the cache. It is
  5450. ;; fine because the order of elements will not be altered by
  5451. ;; shifting. However, we cannot know the real position of the
  5452. ;; unshifted NEXT element in the current request. So, we need
  5453. ;; to sort the request list according to keys and re-start
  5454. ;; processing from the new leftmost request.
  5455. (org-element--cache-log-message "Phase 1")
  5456. (let ((key (org-element--request-key request)))
  5457. (when (and next-request-key (not (org-element--cache-key-less-p key next-request-key)))
  5458. ;; In theory, the only case when requests are not
  5459. ;; ordered is when key of the next request is either the
  5460. ;; same with current key or it is a key for a removed
  5461. ;; element. Either way, we can simply merge the two
  5462. ;; requests.
  5463. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5464. (org-element--cache-log-message "Phase 1: Unorderered requests. Merging: %S\n%S\n"
  5465. (let ((print-length 10) (print-level 3)) (prin1-to-string request))
  5466. (let ((print-length 10) (print-level 3)) (prin1-to-string next-request)))
  5467. (setf (org-element--request-key next-request) key)
  5468. (setf (org-element--request-beg next-request) (org-element--request-beg request))
  5469. (setf (org-element--request-phase next-request) 1)
  5470. (throw 'org-element--cache-quit t))))
  5471. ;; Next element will start at its beginning position plus
  5472. ;; offset, since it hasn't been shifted yet. Therefore, LIMIT
  5473. ;; contains the real beginning position of the first element to
  5474. ;; shift and re-parent.
  5475. (let ((limit (+ (org-element--request-beg request) (org-element--request-offset request)))
  5476. cached-before)
  5477. (cond ((and threshold (> limit threshold))
  5478. (org-element--cache-log-message "Interrupt: position %S after threshold %S" limit threshold)
  5479. (throw 'org-element--cache-interrupt nil))
  5480. ((and future-change (>= limit future-change))
  5481. ;; Changes happened around this element and they will
  5482. ;; trigger another phase 1 request. Skip re-parenting
  5483. ;; and simply proceed with shifting (phase 2) to make
  5484. ;; sure that followup phase 0 request for the recent
  5485. ;; changes can operate on the correctly shifted cache.
  5486. (org-element--cache-log-message "position %S after future change %S" limit future-change)
  5487. (setf (org-element--request-parent request) nil)
  5488. (setf (org-element--request-phase request) 2))
  5489. (t
  5490. (when future-change
  5491. ;; Changes happened, but not yet registered after
  5492. ;; this element. However, we a not yet safe to look
  5493. ;; at the buffer and parse elements in the cache gap.
  5494. ;; Some of the parents to be added to cache may end
  5495. ;; after the changes. Parsing this parents will
  5496. ;; assign the :end correct value for cache state
  5497. ;; after future-change. Then, when the future change
  5498. ;; is going to be processed, such parent boundary
  5499. ;; will be altered unnecessarily. To avoid this,
  5500. ;; we alter the new parents by -OFFSET.
  5501. ;; For now, just save last known cached element and
  5502. ;; then check all the parents below.
  5503. (setq cached-before (org-element--cache-find (1- limit) nil)))
  5504. ;; No relevant changes happened after submitting this
  5505. ;; request. We are safe to look at the actual Org
  5506. ;; buffer and calculate the new parent.
  5507. (let ((parent (org-element--parse-to (1- limit) nil time-limit)))
  5508. (when future-change
  5509. ;; Check all the newly added parents to not
  5510. ;; intersect with future change.
  5511. (let ((up parent))
  5512. (while (and up
  5513. (or (not cached-before)
  5514. (> (org-element-property :begin up)
  5515. (org-element-property :begin cached-before))))
  5516. (when (> (org-element-property :end up) future-change)
  5517. ;; Offset future cache request.
  5518. (org-element--cache-shift-positions
  5519. up (- offset)
  5520. (if (and (org-element-property :robust-begin up)
  5521. (org-element-property :robust-end up))
  5522. '(:contents-end :end :robust-end)
  5523. '(:contents-end :end))))
  5524. (setq up (org-element-property :parent up)))))
  5525. (org-element--cache-log-message "New parent at %S: %S::%S"
  5526. limit
  5527. (org-element-property :org-element--cache-sync-key parent)
  5528. (org-element--format-element parent))
  5529. (setf (org-element--request-parent request) parent)
  5530. (setf (org-element--request-phase request) 2))))))
  5531. ;; Phase 2.
  5532. ;;
  5533. ;; Shift all elements starting from key START, but before NEXT, by
  5534. ;; OFFSET, and re-parent them when appropriate.
  5535. ;;
  5536. ;; Elements are modified by side-effect so the tree structure
  5537. ;; remains intact.
  5538. ;;
  5539. ;; Once THRESHOLD, if any, is reached, or once there is an input
  5540. ;; pending, exit. Before leaving, the current synchronization
  5541. ;; request is updated.
  5542. (org-element--cache-log-message "Phase 2")
  5543. (let ((start (org-element--request-key request))
  5544. (offset (org-element--request-offset request))
  5545. (parent (org-element--request-parent request))
  5546. (node (org-element--cache-root))
  5547. (stack (list nil))
  5548. (leftp t)
  5549. exit-flag continue-flag)
  5550. ;; No re-parenting nor shifting planned: request is over.
  5551. (when (and (not parent) (zerop offset))
  5552. (org-element--cache-log-message "Empty offset. Request completed.")
  5553. (throw 'org-element--cache-quit t))
  5554. (while node
  5555. (let* ((data (avl-tree--node-data node))
  5556. (key (org-element--cache-key data)))
  5557. ;; Traverse the cache tree. Ignore all the elements before
  5558. ;; START. Note that `avl-tree-stack' would not bypass the
  5559. ;; elements before START and thus would have beeen less
  5560. ;; efficient.
  5561. (if (and leftp (avl-tree--node-left node)
  5562. (not (org-element--cache-key-less-p key start)))
  5563. (progn (push node stack)
  5564. (setq node (avl-tree--node-left node)))
  5565. ;; Shift and re-parent when current node starts at or
  5566. ;; after START, but before NEXT.
  5567. (unless (org-element--cache-key-less-p key start)
  5568. ;; We reached NEXT. Request is complete.
  5569. (when (and next-request-key
  5570. (not (org-element--cache-key-less-p key next-request-key)))
  5571. (org-element--cache-log-message "Reached next request.")
  5572. (let ((next-request (nth 1 org-element--cache-sync-requests)))
  5573. (unless (and (org-element-property :cached (org-element--request-parent next-request))
  5574. (org-element-property :begin (org-element--request-parent next-request))
  5575. parent
  5576. (> (org-element-property :begin (org-element--request-parent next-request))
  5577. (org-element-property :begin parent)))
  5578. (setf (org-element--request-parent next-request) parent)))
  5579. (throw 'org-element--cache-quit t))
  5580. ;; Handle interruption request. Update current request.
  5581. (when (or exit-flag (org-element--cache-interrupt-p time-limit))
  5582. (org-element--cache-log-message "Interrupt: %s" (if exit-flag "threshold" "time limit"))
  5583. (setf (org-element--request-key request) key)
  5584. (setf (org-element--request-parent request) parent)
  5585. (throw 'org-element--cache-interrupt nil))
  5586. ;; Shift element.
  5587. (unless (zerop offset)
  5588. (when (>= org-element--cache-diagnostics-level 3)
  5589. (org-element--cache-log-message "Shifting positions (𝝙%S) in %S::%S"
  5590. offset
  5591. (org-element-property :org-element--cache-sync-key data)
  5592. (org-element--format-element data)))
  5593. (org-element--cache-shift-positions data offset))
  5594. (let ((begin (org-element-property :begin data)))
  5595. ;; Update PARENT and re-parent DATA, only when
  5596. ;; necessary. Propagate new structures for lists.
  5597. (while (and parent
  5598. (<= (org-element-property :end parent) begin))
  5599. (setq parent (org-element-property :parent parent)))
  5600. (cond ((and (not parent) (zerop offset)) (throw 'org-element--cache-quit nil))
  5601. ;; Consider scenario when DATA lays within
  5602. ;; sensitive lines of PARENT that was found
  5603. ;; during phase 2. For example:
  5604. ;;
  5605. ;; #+ begin_quote
  5606. ;; Paragraph
  5607. ;; #+end_quote
  5608. ;;
  5609. ;; In the above source block, remove space in
  5610. ;; the first line will trigger re-parenting of
  5611. ;; the paragraph and "#+end_quote" that is also
  5612. ;; considered paragraph before the modification.
  5613. ;; However, the paragraph element stored in
  5614. ;; cache must be deleted instead.
  5615. ((and parent
  5616. (or (not (memq (org-element-type parent) org-element-greater-elements))
  5617. (and (org-element-property :contents-begin parent)
  5618. (< (org-element-property :begin data) (org-element-property :contents-begin parent)))
  5619. (and (org-element-property :contents-end parent)
  5620. (>= (org-element-property :begin data) (org-element-property :contents-end parent)))
  5621. (> (org-element-property :end data) (org-element-property :end parent))
  5622. (and (org-element-property :contents-end data)
  5623. (> (org-element-property :contents-end data) (org-element-property :contents-end parent)))))
  5624. (org-element--cache-log-message "org-element-cache: Removing obsolete element with key %S::%S"
  5625. (org-element-property :org-element--cache-sync-key data)
  5626. (org-element--format-element data))
  5627. (org-element--cache-remove data)
  5628. ;; We altered the tree structure. The tree
  5629. ;; traversal needs to be restarted.
  5630. (setf (org-element--request-key request) key)
  5631. (setf (org-element--request-parent request) parent)
  5632. ;; Restart tree traversal.
  5633. (setq node (org-element--cache-root)
  5634. stack (list nil)
  5635. leftp t
  5636. begin -1
  5637. continue-flag t))
  5638. ((and parent
  5639. (not (eq parent data))
  5640. (let ((p (org-element-property :parent data)))
  5641. (or (not p)
  5642. (< (org-element-property :begin p)
  5643. (org-element-property :begin parent))
  5644. (unless (eq p parent)
  5645. (not (org-element-property :cached p))
  5646. ;; (not (avl-tree-member-p org-element--cache p))
  5647. ))))
  5648. (org-element--cache-log-message "Updating parent in %S\n Old parent: %S\n New parent: %S"
  5649. (org-element--format-element data)
  5650. (org-element--format-element (org-element-property :parent data))
  5651. (org-element--format-element parent))
  5652. (when (and (eq 'org-data (org-element-type parent))
  5653. (not (eq 'headline (org-element-type data))))
  5654. ;; FIXME: This check is here to see whether
  5655. ;; such error happens within
  5656. ;; `org-element--cache-process-request' or somewhere
  5657. ;; else.
  5658. (org-element--cache-warn "Added org-data parent to non-headline element: %S
  5659. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report)."
  5660. data)
  5661. (org-element-cache-reset)
  5662. (throw 'org-element--cache-quit t))
  5663. (org-element-put-property data :parent parent)
  5664. (let ((s (org-element-property :structure parent)))
  5665. (when (and s (org-element-property :structure data))
  5666. (org-element-put-property data :structure s)))))
  5667. ;; Cache is up-to-date past THRESHOLD. Request
  5668. ;; interruption.
  5669. (when (and threshold (> begin threshold))
  5670. (org-element--cache-log-message "Reached threshold %S: %S"
  5671. threshold
  5672. (org-element--format-element data))
  5673. (setq exit-flag t))))
  5674. (if continue-flag
  5675. (setq continue-flag nil)
  5676. (setq node (if (setq leftp (avl-tree--node-right node))
  5677. (avl-tree--node-right node)
  5678. (pop stack)))))))
  5679. ;; We reached end of tree: synchronization complete.
  5680. t))
  5681. (org-element--cache-log-message "org-element-cache: Finished process. The cache size is %S. The remaining sync requests: %S"
  5682. org-element--cache-size
  5683. (let ((print-level 2)) (prin1-to-string org-element--cache-sync-requests))))
  5684. (defsubst org-element--open-end-p (element)
  5685. "Check if ELEMENT in current buffer contains extra blank lines after
  5686. it and does not have closing term.
  5687. Examples of such elements are: section, headline, org-data,
  5688. and footnote-definition."
  5689. (and (org-element-property :contents-end element)
  5690. (= (org-element-property :contents-end element)
  5691. (save-excursion
  5692. (goto-char (org-element-property :end element))
  5693. (skip-chars-backward " \r\n\t")
  5694. (line-beginning-position 2)))))
  5695. (defun org-element--parse-to (pos &optional syncp time-limit)
  5696. "Parse elements in current section, down to POS.
  5697. Start parsing from the closest between the last known element in
  5698. cache or headline above. Return the smallest element containing
  5699. POS.
  5700. When optional argument SYNCP is non-nil, return the parent of the
  5701. element containing POS instead. In that case, it is also
  5702. possible to provide TIME-LIMIT, which is a time value specifying
  5703. when the parsing should stop. The function throws
  5704. `org-element--cache-interrupt' if the process stopped before finding
  5705. the expected result."
  5706. (catch 'exit
  5707. (save-match-data
  5708. (org-with-wide-buffer
  5709. (goto-char pos)
  5710. (save-excursion
  5711. (end-of-line)
  5712. (skip-chars-backward " \r\t\n")
  5713. ;; Within blank lines at the beginning of buffer, return nil.
  5714. (when (bobp) (throw 'exit nil)))
  5715. (let* ((cached (and (org-element--cache-active-p)
  5716. (org-element--cache-find pos nil)))
  5717. (mode (org-element-property :mode cached))
  5718. element next)
  5719. (cond
  5720. ;; Nothing in cache before point: start parsing from first
  5721. ;; element in buffer down to POS or from the beginning of the
  5722. ;; file.
  5723. ((and (not cached) (org-element--cache-active-p))
  5724. (setq element (org-element-org-data-parser))
  5725. (unless (org-element-property :begin element)
  5726. (org-element--cache-warn "Error parsing org-data. Got %S\nPlease report to Org mode mailing list (M-x org-submit-bug-report)." element))
  5727. (org-element--cache-log-message "Nothing in cache. Adding org-data: %S"
  5728. (org-element--format-element element))
  5729. (org-element--cache-put element)
  5730. (goto-char (org-element-property :contents-begin element))
  5731. (setq mode 'org-data))
  5732. ;; Nothing in cache before point because cache is not active.
  5733. ;; Parse from previous heading to avoid re-parsing the whole
  5734. ;; buffer above. This comes at the cost of not calculating
  5735. ;; `:parent' property for headings.
  5736. ((not cached)
  5737. (if (org-with-limited-levels (outline-previous-heading))
  5738. (progn
  5739. (setq element (org-element-headline-parser nil 'fast))
  5740. (setq mode 'planning)
  5741. (forward-line))
  5742. (setq element (org-element-org-data-parser))
  5743. (setq mode 'org-data))
  5744. (org-skip-whitespace)
  5745. (beginning-of-line))
  5746. ;; Check if CACHED or any of its ancestors contain point.
  5747. ;;
  5748. ;; If there is such an element, we inspect it in order to know
  5749. ;; if we return it or if we need to parse its contents.
  5750. ;; Otherwise, we just start parsing from location, which is
  5751. ;; right after the top-most element containing CACHED but
  5752. ;; still before POS.
  5753. ;;
  5754. ;; As a special case, if POS is at the end of the buffer, we
  5755. ;; want to return the innermost element ending there.
  5756. ;;
  5757. ;; Also, if we find an ancestor and discover that we need to
  5758. ;; parse its contents, make sure we don't start from
  5759. ;; `:contents-begin', as we would otherwise go past CACHED
  5760. ;; again. Instead, in that situation, we will resume parsing
  5761. ;; from NEXT, which is located after CACHED or its higher
  5762. ;; ancestor not containing point.
  5763. (t
  5764. (let ((up cached)
  5765. (pos (if (= (point-max) pos) (1- pos) pos)))
  5766. (while (and up (<= (org-element-property :end up) pos))
  5767. (goto-char (org-element-property :end up))
  5768. (setq element up
  5769. mode (org-element--next-mode (org-element-property :mode element) (org-element-type element) nil)
  5770. up (org-element-property :parent up)
  5771. next (point)))
  5772. (when up (setq element up)))))
  5773. ;; Parse successively each element until we reach POS.
  5774. (let ((end (or (org-element-property :end element) (point-max)))
  5775. (parent (org-element-property :parent element)))
  5776. (while t
  5777. (when (org-element--cache-interrupt-p time-limit)
  5778. (throw 'org-element--cache-interrupt nil))
  5779. (when (and inhibit-quit org-element--cache-interrupt-C-g quit-flag)
  5780. (when quit-flag
  5781. (cl-incf org-element--cache-interrupt-C-g-count)
  5782. (setq quit-flag nil))
  5783. (when (>= org-element--cache-interrupt-C-g-count
  5784. org-element--cache-interrupt-C-g-max-count)
  5785. (setq quit-flag t)
  5786. (setq org-element--cache-interrupt-C-g-count 0)
  5787. (org-element-cache-reset)
  5788. (error "org-element: Parsing aborted by user. Cache has been cleared.
  5789. If you observe Emacs hangs frequently, please report this to Org mode mailing list (M-x org-submit-bug-report)."))
  5790. (message (substitute-command-keys
  5791. "`org-element--parse-buffer': Suppressed `\\[keyboard-quit]'. Press `\\[keyboard-quit]' %d more times to force interruption.")
  5792. (- org-element--cache-interrupt-C-g-max-count
  5793. org-element--cache-interrupt-C-g-count)))
  5794. (unless element
  5795. ;; Do not try to parse within blank at EOB.
  5796. (unless (save-excursion
  5797. (org-skip-whitespace)
  5798. (eobp))
  5799. (org-element-with-disabled-cache
  5800. (setq element (org-element--current-element
  5801. end 'element mode
  5802. (org-element-property :structure parent)))))
  5803. ;; Make sure that we return referenced element in cache
  5804. ;; that can be altered directly.
  5805. (if element
  5806. (setq element (or (org-element--cache-put element) element))
  5807. ;; Nothing to parse (i.e. empty file).
  5808. (throw 'exit parent))
  5809. (unless (or (not (org-element--cache-active-p)) parent)
  5810. (org-element--cache-warn "Got empty parent while parsing. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n Backtrace:\n%S"
  5811. (when (and (fboundp 'backtrace-get-frames)
  5812. (fboundp 'backtrace-to-string))
  5813. (backtrace-to-string (backtrace-get-frames 'backtrace))
  5814. (org-element-cache-reset)
  5815. (error "org-element--cache: Emergency exit"))))
  5816. (org-element-put-property element :parent parent))
  5817. (let ((elem-end (org-element-property :end element))
  5818. (type (org-element-type element)))
  5819. (cond
  5820. ;; Skip any element ending before point. Also skip
  5821. ;; element ending at point (unless it is also the end of
  5822. ;; buffer) since we're sure that another element begins
  5823. ;; after it.
  5824. ((and (<= elem-end pos) (/= (point-max) elem-end))
  5825. ;; Avoid parsing headline siblings above.
  5826. (goto-char elem-end)
  5827. (when (eq type 'headline)
  5828. (save-match-data
  5829. (unless (when (and (/= 1 (org-element-property :level element))
  5830. (re-search-forward
  5831. (rx-to-string
  5832. `(and bol (repeat 1 ,(1- (let ((level (org-element-property :level element)))
  5833. (if org-odd-levels-only (1- (* level 2)) level)))
  5834. "*")
  5835. " "))
  5836. pos t))
  5837. (beginning-of-line)
  5838. t)
  5839. ;; There are headings with lower level than
  5840. ;; ELEMENT between ELEM-END and POS. Siblings
  5841. ;; may exist though. Parse starting from the
  5842. ;; last sibling or from ELEM-END if there are
  5843. ;; no other siblings.
  5844. (goto-char pos)
  5845. (unless
  5846. (re-search-backward
  5847. (rx-to-string
  5848. `(and bol (repeat ,(let ((level (org-element-property :level element)))
  5849. (if org-odd-levels-only (1- (* level 2)) level))
  5850. "*")
  5851. " "))
  5852. elem-end t)
  5853. ;; Roll-back to normal parsing.
  5854. (goto-char elem-end)))))
  5855. (setq mode (org-element--next-mode mode type nil)))
  5856. ;; A non-greater element contains point: return it.
  5857. ((not (memq type org-element-greater-elements))
  5858. (throw 'exit (if syncp parent element)))
  5859. ;; Otherwise, we have to decide if ELEMENT really
  5860. ;; contains POS. In that case we start parsing from
  5861. ;; contents' beginning.
  5862. ;;
  5863. ;; If POS is at contents' beginning but it is also at
  5864. ;; the beginning of the first item in a list or a table.
  5865. ;; In that case, we need to create an anchor for that
  5866. ;; list or table, so return it.
  5867. ;;
  5868. ;; Also, if POS is at the end of the buffer, no element
  5869. ;; can start after it, but more than one may end there.
  5870. ;; Arbitrarily, we choose to return the innermost of
  5871. ;; such elements.
  5872. ((let ((cbeg (org-element-property :contents-begin element))
  5873. (cend (org-element-property :contents-end element)))
  5874. (when (and cbeg cend
  5875. (or (< cbeg pos)
  5876. (and (= cbeg pos)
  5877. (not (memq type '(plain-list table)))))
  5878. (or (> cend pos)
  5879. ;; When we are at cend or within blank
  5880. ;; lines after, it is a special case:
  5881. ;; 1. At the end of buffer we return
  5882. ;; the innermost element.
  5883. ;; 2. At cend of element with return
  5884. ;; that element.
  5885. ;; 3. At the end of element, we would
  5886. ;; return in the earlier cond form.
  5887. ;; 4. Within blank lines after cend,
  5888. ;; when element does not have a
  5889. ;; closing keyword, we return that
  5890. ;; outermost element, unless the
  5891. ;; outermost element is a non-empty
  5892. ;; headline. In the latter case, we
  5893. ;; return the outermost element inside
  5894. ;; the headline section.
  5895. (and (org-element--open-end-p element)
  5896. (or (= (org-element-property :end element) (point-max))
  5897. (and (>= pos (org-element-property :contents-end element))
  5898. (memq (org-element-type element) '(org-data section headline)))))))
  5899. (goto-char (or next cbeg))
  5900. (setq mode (if next mode (org-element--next-mode mode type t))
  5901. next nil
  5902. parent element
  5903. end (if (org-element--open-end-p element)
  5904. (org-element-property :end element)
  5905. (org-element-property :contents-end element))))))
  5906. ;; Otherwise, return ELEMENT as it is the smallest
  5907. ;; element containing POS.
  5908. (t (throw 'exit (if syncp parent element)))))
  5909. (setq element nil))))))))
  5910. ;;;; Staging Buffer Changes
  5911. (defconst org-element--cache-sensitive-re
  5912. (concat
  5913. "^\\*+ " "\\|"
  5914. "\\\\end{[A-Za-z0-9*]+}[ \t]*$" "\\|"
  5915. "^[ \t]*\\(?:"
  5916. "#\\+END\\(?:_\\|:?[ \t]*$\\)" "\\|"
  5917. org-list-full-item-re "\\|"
  5918. ":\\(?: \\|$\\)" "\\|"
  5919. ":\\(?:\\w\\|[-_]\\)+:[ \t]*$"
  5920. "\\)")
  5921. "Regexp matching a sensitive line, structure wise.
  5922. A sensitive line is a headline, inlinetask, block, drawer, or
  5923. latex-environment boundary. When such a line is modified,
  5924. structure changes in the document may propagate in the whole
  5925. section, possibly making cache invalid.")
  5926. (defun org-element--cache-before-change (beg end)
  5927. "Detect modifications in sensitive parts of Org buffer.
  5928. BEG and END are the beginning and end of the range of changed
  5929. text. See `before-change-functions' for more information.
  5930. The function returns the new value of `org-element--cache-change-warning'."
  5931. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  5932. (current-buffer))
  5933. (when (org-element--cache-active-p t)
  5934. (org-with-wide-buffer
  5935. (setq org-element--cache-change-tic (buffer-chars-modified-tick))
  5936. (goto-char beg)
  5937. (beginning-of-line)
  5938. (let ((bottom (save-excursion
  5939. (goto-char end)
  5940. (if (and (bolp)
  5941. ;; When beg == end, still extent to eol.
  5942. (> (point) beg))
  5943. ;; FIXME: Potential pitfall.
  5944. ;; We are appending to an element end.
  5945. ;; Unless the last inserted char is not
  5946. ;; newline, the next element is not broken
  5947. ;; and does not need to be purged from the
  5948. ;; cache.
  5949. end
  5950. (line-end-position)))))
  5951. (prog1
  5952. ;; Use the worst change warning to not miss important edits.
  5953. ;; This function is called before edit and after edit by
  5954. ;; `org-element--cache-after-change'. Before the edit, we still
  5955. ;; want to use the old value if it comes from previous
  5956. ;; not yet processed edit (they may be merged by
  5957. ;; `org-element--cache-submit-request'). After the edit, we want to
  5958. ;; look if there was a sensitive removed during edit.
  5959. ;; FIXME: This is not the most efficient way and we now
  5960. ;; have to delete more elemetns than needed in some
  5961. ;; cases. A better approach may be storing the warning
  5962. ;; in the modification request itself.
  5963. (let ((org-element--cache-change-warning-before org-element--cache-change-warning)
  5964. (org-element--cache-change-warning-after))
  5965. (setq org-element--cache-change-warning-after
  5966. (save-match-data
  5967. (let ((case-fold-search t))
  5968. (when (re-search-forward
  5969. org-element--cache-sensitive-re bottom t)
  5970. (goto-char beg)
  5971. (beginning-of-line)
  5972. (let (min-level)
  5973. (cl-loop while (re-search-forward
  5974. (rx-to-string
  5975. (if (and min-level
  5976. (> min-level 1))
  5977. `(and bol (repeat 1 ,(1- min-level) "*") " ")
  5978. `(and bol (+ "*") " ")))
  5979. bottom t)
  5980. do (setq min-level (1- (length (match-string 0))))
  5981. until (= min-level 1))
  5982. (goto-char beg)
  5983. (beginning-of-line)
  5984. (or (and min-level (org-reduced-level min-level))
  5985. (when (looking-at-p "^[ \t]*#\\+CATEGORY:")
  5986. 'org-data)
  5987. t))))))
  5988. (setq org-element--cache-change-warning
  5989. (cond
  5990. ((and (numberp org-element--cache-change-warning-before)
  5991. (numberp org-element--cache-change-warning-after))
  5992. (min org-element--cache-change-warning-after
  5993. org-element--cache-change-warning-before))
  5994. ((numberp org-element--cache-change-warning-before)
  5995. org-element--cache-change-warning-before)
  5996. ((numberp org-element--cache-change-warning-after)
  5997. org-element--cache-change-warning-after)
  5998. (t (or org-element--cache-change-warning-after
  5999. org-element--cache-change-warning-before)))))
  6000. (org-element--cache-log-message "%S is about to modify text: warning %S"
  6001. this-command
  6002. org-element--cache-change-warning)))))))
  6003. (defun org-element--cache-after-change (beg end pre)
  6004. "Update buffer modifications for current buffer.
  6005. BEG and END are the beginning and end of the range of changed
  6006. text, and the length in bytes of the pre-change text replaced by
  6007. that range. See `after-change-functions' for more information."
  6008. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6009. (current-buffer))
  6010. (when (org-element--cache-active-p t)
  6011. (when (not (eq org-element--cache-change-tic (buffer-chars-modified-tick)))
  6012. (org-element--cache-log-message "After change")
  6013. (setq org-element--cache-change-warning (org-element--cache-before-change beg end))
  6014. ;; If beg is right after spaces in front of an element, we
  6015. ;; risk affecting previous element, so move beg to bol, making
  6016. ;; sure that we capture preceding element.
  6017. (setq beg (save-excursion
  6018. (goto-char beg)
  6019. (cl-incf pre (- beg (line-beginning-position)))
  6020. (line-beginning-position)))
  6021. ;; Store synchronization request.
  6022. (let ((offset (- end beg pre)))
  6023. (save-match-data
  6024. (org-element--cache-submit-request beg (- end offset) offset)))
  6025. ;; Activate a timer to process the request during idle time.
  6026. (org-element--cache-set-timer (current-buffer))))))
  6027. (defvar org-element--cache-avoid-synchronous-headline-re-parsing nil
  6028. "This variable controls how buffer changes are handled by the cache.
  6029. By default (when this variable is nil), cache re-parses modified
  6030. headlines immidiately after modification preserving all the unaffected
  6031. elements inside the headline.
  6032. The default behaviour works best when users types inside Org buffer of
  6033. when buffer modifications are mixed with cache requests. However,
  6034. large automated edits inserting/deleting many headlines are somewhat
  6035. slower by default (as in `org-archive-subtree'). Let-binding this
  6036. variable to non-nil will reduce cache latency after every singular edit
  6037. (`after-change-functions') at the cost of slower cache queries.")
  6038. (defun org-element--cache-for-removal (beg end offset)
  6039. "Return first element to remove from cache.
  6040. BEG and END are buffer positions delimiting buffer modifications.
  6041. OFFSET is the size of the changes.
  6042. Returned element is usually the first element in cache containing
  6043. any position between BEG and END. As an exception, greater
  6044. elements around the changes that are robust to contents
  6045. modifications are preserved and updated according to the
  6046. changes. In the latter case, the returned element is the outermost
  6047. non-robust element affected by the changes. Note that the returned
  6048. element may end before END position in which case some cached element
  6049. starting after the returned may still be affected by the changes.
  6050. Also, when there are no elements in cache before BEG, return first
  6051. known element in cache (it may start after END)."
  6052. (let* ((elements (org-element--cache-find (1- beg) 'both))
  6053. (before (car elements))
  6054. (after (cdr elements)))
  6055. (if (not before) after
  6056. ;; If BEFORE is a keyword, it may need to be removed to become
  6057. ;; an affiliated keyword.
  6058. (when (eq 'keyword (org-element-type before))
  6059. (let ((prev before))
  6060. (while (eq 'keyword (org-element-type prev))
  6061. (setq before prev
  6062. beg (org-element-property :begin prev))
  6063. (setq prev (org-element--cache-find (1- (org-element-property :begin before)))))))
  6064. (let ((up before)
  6065. (robust-flag t))
  6066. (while up
  6067. (if (let ((type (org-element-type up)))
  6068. (or (and (memq type '( center-block dynamic-block
  6069. quote-block special-block
  6070. drawer))
  6071. (or (not (eq type 'drawer))
  6072. (not (string= "PROPERTIES" (org-element-property :drawer-name up))))
  6073. ;; Sensitive change. This is
  6074. ;; unconditionally non-robust change.
  6075. (not org-element--cache-change-warning)
  6076. (let ((cbeg (org-element-property :contents-begin up))
  6077. (cend (org-element-property :contents-end up)))
  6078. (and cbeg
  6079. (<= cbeg beg)
  6080. (or (> cend end)
  6081. (and (= cend end)
  6082. (= (+ end offset) (point-max)))))))
  6083. (and (memq type '(headline section org-data))
  6084. (let ((rbeg (org-element-property :robust-begin up))
  6085. (rend (org-element-property :robust-end up)))
  6086. (and rbeg rend
  6087. (<= rbeg beg)
  6088. (or (> rend end)
  6089. (and (= rend end)
  6090. (= (+ end offset) (point-max))))))
  6091. (pcase type
  6092. ;; Sensitive change in section. Need to
  6093. ;; re-parse.
  6094. (`section (not org-element--cache-change-warning))
  6095. ;; Headline might be inserted. This is non-robust
  6096. ;; change when `up' is a `headline' or `section'
  6097. ;; with `>' level compared to the inserted headline.
  6098. ;;
  6099. ;; Also, planning info/property drawer
  6100. ;; could have been inserted. It is not
  6101. ;; robust change then.
  6102. (`headline
  6103. (and
  6104. (or (not (numberp org-element--cache-change-warning))
  6105. (> org-element--cache-change-warning
  6106. (org-element-property :level up)))
  6107. (org-with-point-at (org-element-property :contents-begin up)
  6108. (unless
  6109. (save-match-data
  6110. (when (looking-at-p org-element-planning-line-re)
  6111. (forward-line))
  6112. (when (looking-at org-property-drawer-re)
  6113. (< beg (match-end 0))))
  6114. 'robust))))
  6115. (`org-data (and (not (eq org-element--cache-change-warning 'org-data))
  6116. ;; Property drawer could
  6117. ;; have been inserted. It
  6118. ;; is not robust change
  6119. ;; then.
  6120. (org-with-wide-buffer
  6121. (goto-char (point-min))
  6122. (while (and (org-at-comment-p) (bolp)) (forward-line))
  6123. ;; Should not see property
  6124. ;; drawer within changed
  6125. ;; region.
  6126. (save-match-data
  6127. (or (not (looking-at org-property-drawer-re))
  6128. (> beg (match-end 0)))))))
  6129. (_ 'robust)))))
  6130. ;; UP is a robust greater element containing changes.
  6131. ;; We only need to extend its ending boundaries.
  6132. (progn
  6133. (org-element--cache-shift-positions
  6134. up offset
  6135. (if (and (org-element-property :robust-begin up)
  6136. (org-element-property :robust-end up))
  6137. '(:contents-end :end :robust-end)
  6138. '(:contents-end :end)))
  6139. (org-element--cache-log-message "Shifting end positions of robust parent: %S"
  6140. (org-element--format-element up)))
  6141. (unless (or
  6142. ;; UP is non-robust. Yet, if UP is headline, flagging
  6143. ;; everything inside for removal may be to
  6144. ;; costly. Instead, we should better re-parse only the
  6145. ;; headline itself when possible. If a headline is still
  6146. ;; starting from old :begin position, we do not care that
  6147. ;; its boundaries could have extended to shrinked - we
  6148. ;; will re-parent and shift them anyway.
  6149. (and (eq 'headline (org-element-type up))
  6150. (not org-element--cache-avoid-synchronous-headline-re-parsing)
  6151. ;; The change is not inside headline. Not
  6152. ;; updating here.
  6153. (not (<= beg (org-element-property :begin up)))
  6154. (not (> end (org-element-property :end up)))
  6155. (let ((current (org-with-point-at (org-element-property :begin up)
  6156. (org-element-with-disabled-cache
  6157. (org-element--current-element (point-max))))))
  6158. (when (eq 'headline (org-element-type current))
  6159. (org-element--cache-log-message "Found non-robust headline that can be updated individually: %S"
  6160. (org-element--format-element current))
  6161. (org-element-set-element up current)
  6162. t)))
  6163. ;; If UP is org-data, the situation is similar to
  6164. ;; headline case. We just need to re-parse the
  6165. ;; org-data itself, unless the change is made
  6166. ;; within blank lines at BOB (that could
  6167. ;; potentially alter first-section).
  6168. (when (and (eq 'org-data (org-element-type up))
  6169. (>= beg (org-element-property :contents-begin up)))
  6170. (org-element-set-element up (org-with-point-at 1 (org-element-org-data-parser)))
  6171. (org-element--cache-log-message "Found non-robust change invalidating org-data. Re-parsing: %S"
  6172. (org-element--format-element up))
  6173. t))
  6174. (org-element--cache-log-message "Found non-robust element: %S"
  6175. (org-element--format-element up))
  6176. (setq before up)
  6177. (when robust-flag (setq robust-flag nil))))
  6178. (unless (or (org-element-property :parent up)
  6179. (eq 'org-data (org-element-type up)))
  6180. (org-element--cache-warn "Got element without parent. Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" up)
  6181. (org-element-cache-reset)
  6182. (error "org-element--cache: Emergency exit"))
  6183. (setq up (org-element-property :parent up)))
  6184. ;; We're at top level element containing ELEMENT: if it's
  6185. ;; altered by buffer modifications, it is first element in
  6186. ;; cache to be removed. Otherwise, that first element is the
  6187. ;; following one.
  6188. ;;
  6189. ;; As a special case, do not remove BEFORE if it is a robust
  6190. ;; container for current changes.
  6191. (if (or (< (org-element-property :end before) beg) robust-flag) after
  6192. before)))))
  6193. (defun org-element--cache-submit-request (beg end offset)
  6194. "Submit a new cache synchronization request for current buffer.
  6195. BEG and END are buffer positions delimiting the minimal area
  6196. where cache data should be removed. OFFSET is the size of the
  6197. change, as an integer."
  6198. (org-element--cache-log-message "Submitting new synchronization request for [%S..%S]𝝙%S"
  6199. beg end offset)
  6200. (with-current-buffer (or (buffer-base-buffer (current-buffer))
  6201. (current-buffer))
  6202. (let ((next (car org-element--cache-sync-requests))
  6203. delete-to delete-from)
  6204. (if (and next
  6205. ;; First existing sync request is in phase 0.
  6206. (= 0 (org-element--request-phase next))
  6207. ;; Current changes intersect with the first sync request.
  6208. (> (setq delete-to (+ (org-element--request-end next)
  6209. (org-element--request-offset next)))
  6210. end)
  6211. (<= (setq delete-from (org-element--request-beg next))
  6212. end))
  6213. ;; Current changes can be merged with first sync request: we
  6214. ;; can save a partial cache synchronization.
  6215. (progn
  6216. (org-element--cache-log-message "Found another phase 0 request intersecting with current")
  6217. ;; Update OFFSET of the existing request.
  6218. (cl-incf (org-element--request-offset next) offset)
  6219. ;; If last change happened within area to be removed, extend
  6220. ;; boundaries of robust parents, if any. Otherwise, find
  6221. ;; first element to remove and update request accordingly.
  6222. (if (> beg delete-from)
  6223. ;; The current modification is completely inside NEXT.
  6224. ;; We already added the current OFFSET to the NEXT
  6225. ;; request. However, the robust elements around
  6226. ;; modifications also need to be shifted. Moreover, the
  6227. ;; new modification may also have non-nil
  6228. ;; `org-element--cache-change-warning'. In the latter case, we
  6229. ;; also need to update the request.
  6230. (let ((first (org-element--cache-for-removal delete-from end offset) ; Shift as needed.
  6231. ))
  6232. (org-element--cache-log-message "Current request is inside next. Candidate parent: %S"
  6233. (org-element--format-element first))
  6234. (when
  6235. ;; Non-robust element is now before NEXT. Need to
  6236. ;; update.
  6237. (and first
  6238. (org-element--cache-key-less-p (org-element--cache-key first)
  6239. (org-element--request-key next)))
  6240. (org-element--cache-log-message "Current request is inside next. New parent: %S"
  6241. (org-element--format-element first))
  6242. (setf (org-element--request-key next) (org-element--cache-key first))
  6243. (setf (org-element--request-beg next) (org-element-property :begin first))
  6244. (setf (org-element--request-end next) (max (org-element-property :end first)
  6245. (org-element--request-end next)))
  6246. (setf (org-element--request-parent next) (org-element-property :parent first))))
  6247. ;; The current and NEXT modifications are intersecting
  6248. ;; with current modification starting before NEXT and NEXT
  6249. ;; ending after current. We need to update the common
  6250. ;; non-robust parent for the new extended modification
  6251. ;; region.
  6252. (let ((first (org-element--cache-for-removal beg delete-to offset)))
  6253. (org-element--cache-log-message "Current request intersects with next. Candidate parent: %S"
  6254. (org-element--format-element first))
  6255. (when (and first
  6256. (org-element--cache-key-less-p (org-element--cache-key first)
  6257. (org-element--request-key next)))
  6258. (org-element--cache-log-message "Current request intersects with next. Updating. New parent: %S"
  6259. (org-element--format-element first))
  6260. (setf (org-element--request-key next) (org-element--cache-key first))
  6261. (setf (org-element--request-beg next) (org-element-property :begin first))
  6262. (setf (org-element--request-end next) (max (org-element-property :end first)
  6263. (org-element--request-end next)))
  6264. (setf (org-element--request-parent next) (org-element-property :parent first))))))
  6265. ;; Ensure cache is correct up to END. Also make sure that NEXT,
  6266. ;; if any, is no longer a 0-phase request, thus ensuring that
  6267. ;; phases are properly ordered. We need to provide OFFSET as
  6268. ;; optional parameter since current modifications are not known
  6269. ;; yet to the otherwise correct part of the cache (i.e, before
  6270. ;; the first request).
  6271. (org-element--cache-log-message "Adding new phase 0 request")
  6272. (when next (org-element--cache-sync (current-buffer) end beg offset))
  6273. (let ((first (org-element--cache-for-removal beg end offset)))
  6274. (if first
  6275. (push (let ((first-beg (org-element-property :begin first))
  6276. (key (org-element--cache-key first)))
  6277. (cond
  6278. ;; When changes happen before the first known
  6279. ;; element, re-parent and shift the rest of the
  6280. ;; cache.
  6281. ((> first-beg end)
  6282. (org-element--cache-log-message "Changes are before first known element. Submitting phase 1 request")
  6283. (vector key first-beg nil offset nil 1))
  6284. ;; Otherwise, we find the first non robust
  6285. ;; element containing END. All elements between
  6286. ;; FIRST and this one are to be removed.
  6287. ;;
  6288. ;; The current modification is completely inside
  6289. ;; FIRST. Clear and update cached elements in
  6290. ;; region containing FIRST.
  6291. ((let ((first-end (org-element-property :end first)))
  6292. (when (> first-end end)
  6293. (org-element--cache-log-message "Extending to non-robust element %S" (org-element--format-element first))
  6294. (vector key first-beg first-end offset (org-element-property :parent first) 0))))
  6295. (t
  6296. ;; Now, FIRST is the first element after BEG or
  6297. ;; non-robust element containing BEG. However,
  6298. ;; FIRST ends before END and there might be
  6299. ;; another ELEMENT before END that spans beyond
  6300. ;; END. If there is such element, we need to
  6301. ;; extend the region down to end of the common
  6302. ;; parent of FIRST and everything inside
  6303. ;; BEG..END.
  6304. (let* ((element (org-element--cache-find end))
  6305. (element-end (org-element-property :end element))
  6306. (up element))
  6307. (while (and (not (eq up first))
  6308. (setq up (org-element-property :parent up))
  6309. (>= (org-element-property :begin up) first-beg))
  6310. ;; Note that UP might have been already
  6311. ;; shifted if it is a robust element. After
  6312. ;; deletion, it can put it's end before yet
  6313. ;; unprocessed ELEMENT.
  6314. (setq element-end (max (org-element-property :end up) element-end)
  6315. element up))
  6316. ;; Extend region to remove elements between
  6317. ;; beginning of first and the end of outermost
  6318. ;; element starting before END but after
  6319. ;; beginning of first.
  6320. ;; of the FIRST.
  6321. (org-element--cache-log-message "Extending to all elements between:\n 1: %S\n 2: %S"
  6322. (org-element--format-element first)
  6323. (org-element--format-element element))
  6324. (vector key first-beg element-end offset up 0)))))
  6325. org-element--cache-sync-requests)
  6326. ;; No element to remove. No need to re-parent either.
  6327. ;; Simply shift additional elements, if any, by OFFSET.
  6328. (if org-element--cache-sync-requests
  6329. (progn
  6330. (org-element--cache-log-message "Nothing to remove. Updating offset of the next request by 𝝙%S: %S"
  6331. offset
  6332. (let ((print-level 3))
  6333. (car org-element--cache-sync-requests)))
  6334. (cl-incf (org-element--request-offset (car org-element--cache-sync-requests))
  6335. offset))
  6336. (org-element--cache-log-message "Nothing to remove. No elements in cache after %S. Terminating."
  6337. end))))))
  6338. (setq org-element--cache-change-warning nil)))
  6339. (defun org-element--cache-verify-element (element)
  6340. "Verify correctness of ELEMENT when `org-element--cache-self-verify' is non-nil.
  6341. Return non-nil when verification failed."
  6342. ;; Verify correct parent for the element.
  6343. (unless (or (org-element-property :parent element)
  6344. (eq 'org-data (org-element-type element)))
  6345. (org-element--cache-warn "Got element without parent (cache active?: %S). Please report it to Org mode mailing list (M-x org-submit-bug-report).\n%S" (org-element--cache-active-p) element)
  6346. (org-element-cache-reset))
  6347. (let ((org-element--cache-self-verify (or org-element--cache-self-verify
  6348. (and (boundp 'org-batch-test) org-batch-test)))
  6349. (org-element--cache-self-verify-frequency (if (and (boundp 'org-batch-test) org-batch-test)
  6350. 1
  6351. org-element--cache-self-verify-frequency)))
  6352. (when (and org-element--cache-self-verify
  6353. (org-element--cache-active-p)
  6354. (derived-mode-p 'org-mode)
  6355. (org-element-property :parent element)
  6356. (eq 'headline (org-element-type element))
  6357. ;; Avoid too much slowdown
  6358. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6359. (org-with-point-at (org-element-property :begin element)
  6360. (org-element-with-disabled-cache (org-up-heading-or-point-min))
  6361. (unless (or (= (point) (org-element-property :begin (org-element-property :parent element)))
  6362. (eq (point) (point-min)))
  6363. (org-element--cache-warn "Cached element has wrong parent in %s. Resetting.
  6364. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6365. The element is: %S\n The parent is: %S\n The real parent is: %S"
  6366. (buffer-name (current-buffer))
  6367. (org-element--format-element element)
  6368. (org-element--format-element (org-element-property :parent element))
  6369. (org-element--format-element (org-element--current-element (org-element-property :end (org-element-property :parent element)))))
  6370. (org-element-cache-reset))
  6371. (org-element--cache-verify-element (org-element-property :parent element))))
  6372. ;; Verify the element itself.
  6373. (when (and org-element--cache-self-verify
  6374. (org-element--cache-active-p)
  6375. element
  6376. (not (memq (org-element-type element) '(section org-data)))
  6377. ;; Avoid too much slowdown
  6378. (< (random 1000) (* 1000 org-element--cache-self-verify-frequency)))
  6379. (let ((real-element (let (org-element-use-cache)
  6380. (org-element--parse-to
  6381. (if (memq (org-element-type element) '(table-row item))
  6382. (1+ (org-element-property :begin element))
  6383. (org-element-property :begin element))))))
  6384. (unless (and (eq (org-element-type real-element) (org-element-type element))
  6385. (eq (org-element-property :begin real-element) (org-element-property :begin element))
  6386. (eq (org-element-property :end real-element) (org-element-property :end element))
  6387. (eq (org-element-property :contents-begin real-element) (org-element-property :contents-begin element))
  6388. (eq (org-element-property :contents-end real-element) (org-element-property :contents-end element))
  6389. (or (not (org-element-property :ID real-element))
  6390. (string= (org-element-property :ID real-element) (org-element-property :ID element))))
  6391. (org-element--cache-warn "(%S) Cached element is incorrect in %s. (Cache tic up to date: %S) Resetting.
  6392. If this warning appears regularly, please report the warning text to Org mode mailing list (M-x org-submit-bug-report).
  6393. The element is: %S\n The real element is: %S\n Cache around :begin:\n%S\n%S\n%S"
  6394. this-command
  6395. (buffer-name (current-buffer))
  6396. (if (/= org-element--cache-change-tic
  6397. (buffer-chars-modified-tick))
  6398. "no" "yes")
  6399. (org-element--format-element element)
  6400. (org-element--format-element real-element)
  6401. (org-element--cache-find (1- (org-element-property :begin real-element)))
  6402. (car (org-element--cache-find (org-element-property :begin real-element) 'both))
  6403. (cdr (org-element--cache-find (org-element-property :begin real-element) 'both)))
  6404. (org-element-cache-reset))))))
  6405. ;;; Cache persistance
  6406. (defun org-element--cache-persist-before-write (container &optional associated)
  6407. "Sync cache before saving."
  6408. (when (equal container '(elisp org-element--cache))
  6409. (if (and org-element-use-cache
  6410. (plist-get associated :file)
  6411. (get-file-buffer (plist-get associated :file))
  6412. org-element-cache-persistent)
  6413. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6414. (if (and (derived-mode-p 'org-mode)
  6415. org-element--cache)
  6416. (progn
  6417. ;; Cleanup cache request keys to avoid collisions during next
  6418. ;; Emacs session.
  6419. (avl-tree-mapc
  6420. (lambda (el)
  6421. (org-element-put-property el :org-element--cache-sync-key nil))
  6422. org-element--cache)
  6423. (org-with-wide-buffer
  6424. (org-element-at-point (point-max)))
  6425. nil)
  6426. 'forbid))
  6427. 'forbid)))
  6428. (defun org-element--cache-persist-before-read (container &optional associated)
  6429. "Avoid reading cache before Org mode is loaded."
  6430. (when (equal container '(elisp org-element--cache))
  6431. (if (not (and (plist-get associated :file)
  6432. (get-file-buffer (plist-get associated :file))))
  6433. 'forbid
  6434. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6435. (unless (and org-element-use-cache
  6436. org-element-cache-persistent
  6437. (derived-mode-p 'org-mode)
  6438. (equal (secure-hash 'md5 (current-buffer))
  6439. (plist-get associated :hash)))
  6440. 'forbid)))))
  6441. (defun org-element--cache-persist-after-read (container &optional associated)
  6442. "Setup restored cache."
  6443. (when (and (plist-get associated :file)
  6444. (get-file-buffer (plist-get associated :file)))
  6445. (with-current-buffer (get-file-buffer (plist-get associated :file))
  6446. (when (and org-element-use-cache org-element-cache-persistent)
  6447. (when (and (equal container '(elisp org-element--cache)) org-element--cache)
  6448. (setq-local org-element--cache-size (avl-tree-size org-element--cache)))
  6449. (when (and (equal container '(elisp org-element--headline-cache)) org-element--headline-cache)
  6450. (setq-local org-element--headline-cache-size (avl-tree-size org-element--headline-cache)))))))
  6451. (add-hook 'org-persist-before-write-hook #'org-element--cache-persist-before-write)
  6452. (add-hook 'org-persist-before-read-hook #'org-element--cache-persist-before-read)
  6453. (add-hook 'org-persist-after-read-hook #'org-element--cache-persist-after-read)
  6454. ;;;; Public Functions
  6455. (defvar-local org-element--cache-gapless nil
  6456. "An alist containing (granularity . `org-element--cache-change-tic') elements.
  6457. Each element indicates the latest `org-element--cache-change-tic' when
  6458. change did not contain gaps.")
  6459. ;;;###autoload
  6460. (defun org-element-cache-reset (&optional all)
  6461. "Reset cache in current buffer.
  6462. When optional argument ALL is non-nil, reset cache in all Org
  6463. buffers."
  6464. (interactive "P")
  6465. (dolist (buffer (if all (buffer-list) (list (current-buffer))))
  6466. (with-current-buffer (or (buffer-base-buffer buffer) buffer)
  6467. (when (and org-element-use-cache (derived-mode-p 'org-mode))
  6468. (when (not org-element-cache-persistent)
  6469. (org-persist-unregister 'org-element--headline-cache (current-buffer))
  6470. (org-persist-unregister 'org-element--cache (current-buffer)))
  6471. (when (and org-element-cache-persistent
  6472. (buffer-file-name (current-buffer)))
  6473. (org-persist-register 'org-element--cache (current-buffer))
  6474. (org-persist-register 'org-element--headline-cache
  6475. (current-buffer)
  6476. :inherit 'org-element--cache))
  6477. (setq-local org-element--cache-change-tic (buffer-chars-modified-tick))
  6478. (setq-local org-element--cache-gapless nil)
  6479. (setq-local org-element--cache
  6480. (avl-tree-create #'org-element--cache-compare))
  6481. (setq-local org-element--headline-cache
  6482. (avl-tree-create #'org-element--cache-compare))
  6483. (setq-local org-element--cache-size 0)
  6484. (setq-local org-element--headline-cache-size 0)
  6485. (setq-local org-element--cache-sync-keys-value 0)
  6486. (setq-local org-element--cache-change-warning nil)
  6487. (setq-local org-element--cache-sync-requests nil)
  6488. (setq-local org-element--cache-sync-timer nil)
  6489. (add-hook 'before-change-functions
  6490. #'org-element--cache-before-change nil t)
  6491. (add-hook 'after-change-functions
  6492. #'org-element--cache-after-change nil t)))))
  6493. ;;;###autoload
  6494. (defun org-element-cache-refresh (pos)
  6495. "Refresh cache at position POS."
  6496. (when (org-element--cache-active-p)
  6497. (org-element--cache-sync (current-buffer) pos)
  6498. (org-element--cache-submit-request pos pos 0)
  6499. (org-element--cache-set-timer (current-buffer))))
  6500. (defvar warning-minimum-log-level) ; Defined in warning.el
  6501. (defvar org-element-cache-map--recurse nil)
  6502. (defvar org-element-cache-map-continue-from nil
  6503. "Position from where mapping should continue.
  6504. This variable can be set by called function, especially when the
  6505. function modified the buffer.")
  6506. ;;;###autoload
  6507. (cl-defun org-element-cache-map (func &key (granularity 'headline+inlinetask) restrict-elements
  6508. next-re fail-re from-pos (to-pos (point-max-marker)) after-element limit-count
  6509. narrow)
  6510. "Map all elements in current buffer with FUNC according to
  6511. GRANULARITY. Collect non-nil return values into result list.
  6512. FUNC should accept a single argument - the element.
  6513. FUNC can modify the buffer, but doing so may reduce performance. If
  6514. buffer is modified, the mapping will continue from an element starting
  6515. after the last mapped element. If the last mapped element is deleted,
  6516. the subsequent element will be skipped as it cannot be distinguished
  6517. deterministically from a changed element. If FUNC is expected to
  6518. delete the element, it should directly set the value of
  6519. `org-element-cache-map-continue-from' to force `org-element-cache-map'
  6520. continue from the right point in buffer.
  6521. If some elements are not yet in cache, they will be added.
  6522. GRANULARITY can be `headline', `headline+inlinetask'
  6523. `greater-element', or `element'. The default is
  6524. `headline+inlinetask'. `object' granularity is not supported.
  6525. RESTRICT-ELEMENTS is a list of element types to be mapped over.
  6526. NEXT-RE is a regexp used to search next candidate match when FUNC
  6527. returns non-nil and to search the first candidate match. FAIL-RE is a
  6528. regexp used to search next candidate match when FUNC returns nil. The
  6529. mapping will continue starting from headline at the RE match.
  6530. FROM-POS and TO-POS are buffer positions. When non-nil, they bound the
  6531. mapped elements to elements starting at of after FROM-POS but before
  6532. TO-POS.
  6533. AFTER-ELEMENT, when non-nil, bounds the mapping to all the elements
  6534. after AFTER-ELEMENT (i.e. if AFTER-ELEMENT is a headline section, we
  6535. map all the elements starting from first element inside section, but
  6536. not including the section).
  6537. LIMIT-COUNT limits mapping to that many first matches where FUNC
  6538. returns non-nil.
  6539. NARROW controls whether current buffer narrowing should be preserved.
  6540. This function does a subset of what `org-element-map' does, but with
  6541. much better performance. Cached elements are supplied as the single
  6542. argument of FUNC. Changes to elements made in FUNC will also alter
  6543. the cache."
  6544. (unless (org-element--cache-active-p)
  6545. (error "Cache must be active."))
  6546. (unless (memq granularity '( headline headline+inlinetask
  6547. greater-element element))
  6548. (error "Unsupported granularity: %S" granularity))
  6549. ;; Make TO-POS marker. Otherwise, buffer edits may garble the the
  6550. ;; process.
  6551. (unless (markerp to-pos)
  6552. (let ((mk (make-marker)))
  6553. (set-marker mk to-pos)
  6554. (setq to-pos mk)))
  6555. ;; Make sure that garbage collector does not stand on the way to
  6556. ;; maximum performance.
  6557. (let ((gc-cons-threshold #x40000000)
  6558. ;; Bind variables used inside loop to avoid memory
  6559. ;; re-allocation on every iteration.
  6560. ;; See https://emacsconf.org/2021/talks/faster/
  6561. tmpnext-start tmpparent tmpelement)
  6562. (save-excursion
  6563. (save-restriction
  6564. (unless narrow (widen))
  6565. ;; Synchronise cache up to the end of mapped region.
  6566. (org-element-at-point to-pos)
  6567. (cl-macrolet ((cache-root
  6568. ;; Use the most optimal version of cache available.
  6569. () `(if (memq granularity '(headline headline+inlinetask))
  6570. (org-element--headline-cache-root)
  6571. (org-element--cache-root)))
  6572. (cache-size
  6573. ;; Use the most optimal version of cache available.
  6574. () `(if (memq granularity '(headline headline+inlinetask))
  6575. org-element--headline-cache-size
  6576. org-element--cache-size))
  6577. (cache-walk-restart
  6578. ;; Restart tree traversal after AVL tree re-balance.
  6579. () `(when node
  6580. (org-element-at-point (point-max))
  6581. (setq node (cache-root)
  6582. stack (list nil)
  6583. leftp t
  6584. continue-flag t)))
  6585. (cache-walk-abort
  6586. ;; Abort tree traversal.
  6587. () `(setq continue-flag t
  6588. node nil))
  6589. (element-match-at-point
  6590. ;; Returning the first element to match around point.
  6591. ;; For example, if point is inside headline and
  6592. ;; granularity is restricted to headlines only, skip
  6593. ;; over all the child elements inside the headline
  6594. ;; and return the first parent headline.
  6595. ;; When we are inside a cache gap, calling
  6596. ;; `org-element-at-point' also fills the cache gap down to
  6597. ;; point.
  6598. () `(progn
  6599. ;; Parsing is one of the performance
  6600. ;; bottlenecks. Make sure to optimise it as
  6601. ;; much as possible.
  6602. ;;
  6603. ;; Avoid extra staff like timer cancels et al
  6604. ;; and only call `org-element--cache-sync-requests' when
  6605. ;; there are pending requests.
  6606. (when org-element--cache-sync-requests
  6607. (org-element--cache-sync (current-buffer)))
  6608. ;; Call `org-element--parse-to' directly avoiding any
  6609. ;; kind of `org-element-at-point' overheads.
  6610. (if restrict-elements
  6611. ;; Search directly instead of calling
  6612. ;; `org-element-lineage' to avoid funcall overheads
  6613. ;; and making sure that we do not go all
  6614. ;; the way to `org-data' as `org-element-lineage'
  6615. ;; does.
  6616. (progn
  6617. (setq tmpelement (org-element--parse-to (point)))
  6618. (while (and tmpelement (not (memq (org-element-type tmpelement) restrict-elements)))
  6619. (setq tmpelement (org-element-property :parent tmpelement)))
  6620. tmpelement)
  6621. (org-element--parse-to (point)))))
  6622. ;; Starting from (point), search RE and move START to
  6623. ;; the next valid element to be matched according to
  6624. ;; restriction. Abort cache walk if no next element
  6625. ;; can be found. When RE is nil, just find element at
  6626. ;; point.
  6627. (move-start-to-next-match
  6628. (re) `(save-match-data
  6629. (if (or (not ,re) (if org-element--cache-map-statistics
  6630. (progn
  6631. (setq before-time (float-time))
  6632. (re-search-forward (or (car-safe ,re) ,re) nil 'move)
  6633. (cl-incf re-search-time
  6634. (- (float-time)
  6635. before-time)))
  6636. (re-search-forward (or (car-safe ,re) ,re) nil 'move)))
  6637. (unless (or (< (point) (or start -1))
  6638. (and data
  6639. (< (point) (org-element-property :begin data))))
  6640. (if (cdr-safe ,re)
  6641. ;; Avoid parsing when we are 100%
  6642. ;; sure that regexp is good enough
  6643. ;; to find new START.
  6644. (setq start (match-beginning 0))
  6645. (setq start (max (or start -1)
  6646. (or (org-element-property :begin data) -1)
  6647. (or (org-element-property :begin (element-match-at-point)) -1))))
  6648. (when (>= start to-pos) (cache-walk-abort))
  6649. (when (eq start -1) (setq start nil)))
  6650. (cache-walk-abort))))
  6651. ;; Find expected begin position of an element after
  6652. ;; DATA.
  6653. (next-element-start
  6654. () `(progn
  6655. (setq tmpnext-start nil)
  6656. (if (memq granularity '(headline headline+inlinetask))
  6657. (setq tmpnext-start (or (when (memq (org-element-type data) '(headline org-data))
  6658. (org-element-property :contents-begin data))
  6659. (org-element-property :end data)))
  6660. (setq tmpnext-start (or (when (memq (org-element-type data) org-element-greater-elements)
  6661. (org-element-property :contents-begin data))
  6662. (org-element-property :end data))))
  6663. ;; DATA end may be the last element inside
  6664. ;; i.e. source block. Skip up to the end
  6665. ;; of parent in such case.
  6666. (setq tmpparent data)
  6667. (catch :exit
  6668. (when (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6669. (setq tmpnext-start (org-element-property :end tmpparent)))
  6670. (while (setq tmpparent (org-element-property :parent tmpparent))
  6671. (if (eq tmpnext-start (org-element-property :contents-end tmpparent))
  6672. (setq tmpnext-start (org-element-property :end tmpparent))
  6673. (throw :exit t))))
  6674. tmpnext-start))
  6675. ;; Check if cache does not have gaps.
  6676. (cache-gapless-p
  6677. () `(eq org-element--cache-change-tic
  6678. (alist-get granularity org-element--cache-gapless))))
  6679. ;; The core algorithm is simple walk along binary tree. However,
  6680. ;; instead of checking all the tree elements from first to last
  6681. ;; (like in `avl-tree-mapcar'), we begin from FROM-POS skipping
  6682. ;; the elements before FROM-POS efficiently: O(logN) instead of
  6683. ;; O(Nbefore).
  6684. ;;
  6685. ;; Later, we may also not check every single element in the
  6686. ;; binary tree after FROM-POS. Instead, we can find position of
  6687. ;; next candidate elements by means of regexp search and skip the
  6688. ;; binary tree branches that are before the next candidate:
  6689. ;; again, O(logN) instead of O(Nbetween).
  6690. ;;
  6691. ;; Some elements might not yet be in the tree. So, we also parse
  6692. ;; the empty gaps in cache as needed making sure that we do not
  6693. ;; miss anything.
  6694. (let* (;; START is always beginning of an element. When there is
  6695. ;; no element in cache at START, we are inside cache gap
  6696. ;; and need to fill it.
  6697. (start (and from-pos
  6698. (progn
  6699. (goto-char from-pos)
  6700. (org-element-property :begin (element-match-at-point)))))
  6701. ;; Some elements may start at the same position, so we
  6702. ;; also keep track of the last processed element and make
  6703. ;; sure that we do not try to search it again.
  6704. (prev after-element)
  6705. (node (cache-root))
  6706. data
  6707. (stack (list nil))
  6708. (leftp t)
  6709. result
  6710. ;; Whether previous element matched FUNC (FUNC
  6711. ;; returned non-nil).
  6712. (last-match t)
  6713. continue-flag
  6714. ;; Generic regexp to search next potential match. If it
  6715. ;; is a cons of (regexp . 'match-beg), we are 100% sure
  6716. ;; that the match beginning is the existing element
  6717. ;; beginning.
  6718. (next-element-re (pcase granularity
  6719. ((or `headline
  6720. (guard (eq '(headline)
  6721. restrict-elements)))
  6722. (cons
  6723. (org-with-limited-levels
  6724. org-element-headline-re)
  6725. 'match-beg))
  6726. (`headline+inlinetask
  6727. (cons
  6728. (if (eq '(inlinetask) restrict-elements)
  6729. (org-inlinetask-outline-regexp)
  6730. org-element-headline-re)
  6731. 'match-beg))
  6732. ;; TODO: May add other commonly
  6733. ;; searched elements as needed.
  6734. (_)))
  6735. ;; Make sure that we are not checking the same regexp twice.
  6736. (next-re (unless (and next-re
  6737. (string= next-re
  6738. (or (car-safe next-element-re)
  6739. next-element-re)))
  6740. next-re))
  6741. (fail-re (unless (and fail-re
  6742. (string= fail-re
  6743. (or (car-safe next-element-re)
  6744. next-element-re)))
  6745. fail-re))
  6746. (restrict-elements (or restrict-elements
  6747. (pcase granularity
  6748. (`headline
  6749. '(headline))
  6750. (`headline+inlinetask
  6751. '(headline inlinetask))
  6752. (`greater-element
  6753. org-element-greater-elements)
  6754. (_ nil))))
  6755. ;; Statistics
  6756. (time (float-time))
  6757. (predicate-time 0)
  6758. (pre-process-time 0)
  6759. (re-search-time 0)
  6760. (count-predicate-calls-match 0)
  6761. (count-predicate-calls-fail 0)
  6762. ;; Bind variables used inside loop to avoid memory
  6763. ;; re-allocation on every iteration.
  6764. ;; See https://emacsconf.org/2021/talks/faster/
  6765. cache-size before-time modified-tic)
  6766. ;; Skip to first element within region.
  6767. (goto-char (or start (point-min)))
  6768. (move-start-to-next-match next-element-re)
  6769. (unless (and start (>= start to-pos))
  6770. ;; Pre-process cache filling all the gaps.
  6771. (unless (or org-element-cache-map--recurse
  6772. (cache-gapless-p)
  6773. ;; Pre-processing all the elements in large
  6774. ;; buffers when NEXT-RE/FAIL-RE are provided
  6775. ;; may be much slower compared to using
  6776. ;; regexp.
  6777. (and (eq granularity 'element)
  6778. (or next-re fail-re)))
  6779. (let ((org-element-cache-map--recurse t))
  6780. (setq before-time (float-time))
  6781. (org-element-cache-map
  6782. #'ignore
  6783. :granularity granularity)
  6784. (cl-incf pre-process-time
  6785. (- (float-time)
  6786. before-time))
  6787. ;; Re-assign the cache root after filling the cache
  6788. ;; gaps.
  6789. (setq node (cache-root)))
  6790. (setf (alist-get granularity org-element--cache-gapless)
  6791. org-element--cache-change-tic))
  6792. (while node
  6793. (setq data (avl-tree--node-data node))
  6794. (if (and leftp (avl-tree--node-left node) ; Left branch.
  6795. ;; Do not move to left branch when we are before
  6796. ;; PREV.
  6797. (or (not prev)
  6798. (not (org-element--cache-key-less-p
  6799. (org-element--cache-key data)
  6800. (org-element--cache-key prev))))
  6801. ;; ... or when we are before START.
  6802. (or (not start)
  6803. (not (> start (org-element-property :begin data)))))
  6804. (progn (push node stack)
  6805. (setq node (avl-tree--node-left node)))
  6806. ;; The whole tree left to DATA is before START and
  6807. ;; PREV. DATA may still be before START (i.e. when
  6808. ;; DATA is the root or when START moved), at START, or
  6809. ;; after START.
  6810. ;;
  6811. ;; If DATA is before start, skip it over and move to
  6812. ;; subsequent elements.
  6813. ;; If DATA is at start, run FUNC if necessary and
  6814. ;; update START according and NEXT-RE, FAIL-RE,
  6815. ;; NEXT-ELEMENT-RE.
  6816. ;; If DATA is after start, we have found a cache gap
  6817. ;; and need to fill it.
  6818. (unless (or (and start (< (org-element-property :begin data) start))
  6819. (and prev (not (org-element--cache-key-less-p
  6820. (org-element--cache-key prev)
  6821. (org-element--cache-key data)))))
  6822. ;; DATA is at of after START and PREV.
  6823. (if (or (not start) (= (org-element-property :begin data) start))
  6824. ;; DATA is at START. Match it.
  6825. ;; In the process, we may alter the buffer,
  6826. ;; so also keep track of the cache state.
  6827. (progn
  6828. (setq modified-tic org-element--cache-change-tic)
  6829. (setq cache-size (cache-size))
  6830. ;; When NEXT-RE/FAIL-RE is provided, skip to
  6831. ;; next regexp match after :begin of the current
  6832. ;; element.
  6833. (when (if last-match next-re fail-re)
  6834. (goto-char (org-element-property :begin data))
  6835. (move-start-to-next-match
  6836. (if last-match next-re fail-re)))
  6837. (when (and (or (not start) (eq (org-element-property :begin data) start))
  6838. (< (org-element-property :begin data) to-pos))
  6839. ;; Calculate where next possible element
  6840. ;; starts and update START if needed.
  6841. (setq start (next-element-start))
  6842. (goto-char start)
  6843. ;; Move START further if possible.
  6844. (when (and next-element-re
  6845. ;; Do not move if we know for
  6846. ;; sure that cache does not
  6847. ;; contain gaps. Regexp
  6848. ;; searches are not cheap.
  6849. (not (cache-gapless-p)))
  6850. (move-start-to-next-match next-element-re)
  6851. ;; Make sure that point is at START
  6852. ;; before running FUNC.
  6853. (goto-char start))
  6854. ;; Try FUNC if DATA matches all the
  6855. ;; restrictions. Calculate new START.
  6856. (when (or (not restrict-elements)
  6857. (memq (org-element-type data) restrict-elements))
  6858. ;; DATA matches restriction. FUNC may
  6859. ;;
  6860. ;; Call FUNC. FUNC may move point.
  6861. (setq org-element-cache-map-continue-from nil)
  6862. (if org-element--cache-map-statistics
  6863. (progn
  6864. (setq before-time (float-time))
  6865. (push (funcall func data) result)
  6866. (cl-incf predicate-time
  6867. (- (float-time)
  6868. before-time))
  6869. (if (car result)
  6870. (cl-incf count-predicate-calls-match)
  6871. (cl-incf count-predicate-calls-fail)))
  6872. (push (funcall func data) result)
  6873. (when (car result) (cl-incf count-predicate-calls-match)))
  6874. ;; Set `last-match'.
  6875. (setq last-match (car result))
  6876. ;; If FUNC moved point forward, update
  6877. ;; START.
  6878. (when org-element-cache-map-continue-from
  6879. (goto-char org-element-cache-map-continue-from))
  6880. (when (> (point) start)
  6881. (move-start-to-next-match nil))
  6882. ;; Drop nil.
  6883. (unless (car result) (pop result)))
  6884. ;; If FUNC did not move the point and we
  6885. ;; know for sure that cache does not contain
  6886. ;; gaps, do not try to calculate START in
  6887. ;; advance but simply loop to the next cache
  6888. ;; element.
  6889. (when (and (cache-gapless-p)
  6890. (eq (next-element-start)
  6891. start))
  6892. (setq start nil))
  6893. ;; Check if the buffer has been modified.
  6894. (unless (and (eq modified-tic org-element--cache-change-tic)
  6895. (eq cache-size (cache-size)))
  6896. ;; START may no longer be valid, update
  6897. ;; it to beginning of real element.
  6898. ;; Upon modification, START may lay
  6899. ;; inside an element. We want to move
  6900. ;; it to real beginning then despite
  6901. ;; START being larger.
  6902. (setq start nil)
  6903. (move-start-to-next-match nil)
  6904. ;; The new element may now start before
  6905. ;; or at already processed position.
  6906. ;; Make sure that we continue from an
  6907. ;; element past already processed
  6908. ;; place.
  6909. (when (and start
  6910. (<= start (org-element-property :begin data))
  6911. (not org-element-cache-map-continue-from))
  6912. (goto-char start)
  6913. (setq data (element-match-at-point))
  6914. ;; If DATA is nil, buffer is
  6915. ;; empty. Abort.
  6916. (when data
  6917. (goto-char (next-element-start))
  6918. (move-start-to-next-match next-element-re)))
  6919. (org-element-at-point to-pos)
  6920. (cache-walk-restart))
  6921. ;; Reached LIMIT-COUNT. Abort.
  6922. (when (and limit-count
  6923. (>= count-predicate-calls-match
  6924. limit-count))
  6925. (cache-walk-abort))
  6926. (if (org-element-property :cached data)
  6927. (setq prev data)
  6928. (setq prev nil))))
  6929. ;; DATA is after START. Fill the gap.
  6930. (if (memq (org-element-type (org-element--parse-to start)) '(plain-list table))
  6931. ;; Tables and lists are special, we need a
  6932. ;; trickery to make items/rows be populated
  6933. ;; into cache.
  6934. (org-element--parse-to (1+ start)))
  6935. ;; Restart tree traversal as AVL tree is
  6936. ;; re-balanced upon adding elements. We can no
  6937. ;; longer trust STACK.
  6938. (cache-walk-restart)))
  6939. ;; Second, move to the right branch of the tree or skip
  6940. ;; it alltogether.
  6941. (if continue-flag
  6942. (setq continue-flag nil)
  6943. (setq node (if (and (car stack)
  6944. ;; If START advanced beyond stack parent, skip the right branch.
  6945. (or (and start (< (org-element-property :begin (avl-tree--node-data (car stack))) start))
  6946. (and prev (org-element--cache-key-less-p
  6947. (org-element--cache-key (avl-tree--node-data (car stack)))
  6948. (org-element--cache-key prev)))))
  6949. (progn
  6950. (setq leftp nil)
  6951. (pop stack))
  6952. ;; Otherwise, move ahead into the right
  6953. ;; branch when it exists.
  6954. (if (setq leftp (avl-tree--node-right node))
  6955. (avl-tree--node-right node)
  6956. (pop stack))))))))
  6957. (when (and org-element--cache-map-statistics
  6958. (or (not org-element--cache-map-statistics-threshold)
  6959. (> (- (float-time) time) org-element--cache-map-statistics-threshold)))
  6960. (message "Mapped over elements in %S. %d/%d predicate matches. Total time: %f sec. Pre-process time: %f sec. Predicate time: %f sec. Re-search time: %f sec.
  6961. Calling parameters: :granularity %S :restrict-elements %S :next-re %S :fail-re %S :from-pos %S :to-pos %S :limit-count %S :after-element %S"
  6962. (current-buffer)
  6963. count-predicate-calls-match
  6964. (+ count-predicate-calls-match
  6965. count-predicate-calls-fail)
  6966. (- (float-time) time)
  6967. pre-process-time
  6968. predicate-time
  6969. re-search-time
  6970. granularity restrict-elements next-re fail-re from-pos to-pos limit-count after-element))
  6971. ;; Return result.
  6972. (nreverse result)))))))
  6973. ;;; The Toolbox
  6974. ;;
  6975. ;; The first move is to implement a way to obtain the smallest element
  6976. ;; containing point. This is the job of `org-element-at-point'. It
  6977. ;; basically jumps back to the beginning of section containing point
  6978. ;; and proceed, one element after the other, with
  6979. ;; `org-element--current-element' until the container is found. Note:
  6980. ;; When using `org-element-at-point', secondary values are never
  6981. ;; parsed since the function focuses on elements, not on objects.
  6982. ;;
  6983. ;; At a deeper level, `org-element-context' lists all elements and
  6984. ;; objects containing point.
  6985. ;;
  6986. ;; `org-element-nested-p' and `org-element-swap-A-B' may be used
  6987. ;; internally by navigation and manipulation tools.
  6988. ;;;###autoload
  6989. (defun org-element-at-point (&optional pom cached-only)
  6990. "Determine closest element around point or POM.
  6991. Only check cached element when CACHED-ONLY is non-nil and return nil
  6992. unconditionally when element at POM is not in cache.
  6993. Return value is a list like (TYPE PROPS) where TYPE is the type
  6994. of the element and PROPS a plist of properties associated to the
  6995. element.
  6996. Possible types are defined in `org-element-all-elements'.
  6997. Properties depend on element or object type, but always include
  6998. `:begin', `:end', and `:post-blank' properties.
  6999. As a special case, if point is at the very beginning of the first
  7000. item in a list or sub-list, returned element will be that list
  7001. instead of the item. Likewise, if point is at the beginning of
  7002. the first row of a table, returned element will be the table
  7003. instead of the first row.
  7004. When point is at the end of the buffer, return the innermost
  7005. element ending there."
  7006. (setq pom (or pom (point)))
  7007. ;; Allow re-parsing when the command can benefit from it.
  7008. (when (and cached-only
  7009. (memq this-command org-element--cache-non-modifying-commands))
  7010. (setq cached-only nil))
  7011. (let (element)
  7012. (when (org-element--cache-active-p)
  7013. (if (not org-element--cache) (org-element-cache-reset)
  7014. (unless cached-only (org-element--cache-sync (current-buffer) pom))))
  7015. (setq element (if cached-only
  7016. (and (org-element--cache-active-p)
  7017. (or (not org-element--cache-sync-requests)
  7018. (org-element--cache-key-less-p pom (org-element--request-key (car org-element--cache-sync-requests))))
  7019. (org-element--cache-find pom))
  7020. (condition-case err
  7021. (org-element--parse-to pom)
  7022. (error
  7023. (org-element--cache-warn "Org parser error in %s::%S. Resetting.\n The error was: %S\n Backtrace:\n%S\n Please report this to Org mode mailing list (M-x org-submit-bug-report)."
  7024. (buffer-name (current-buffer))
  7025. pom
  7026. err
  7027. (when (and (fboundp 'backtrace-get-frames)
  7028. (fboundp 'backtrace-to-string))
  7029. (backtrace-to-string (backtrace-get-frames 'backtrace))))
  7030. (org-element-cache-reset)
  7031. (org-element--parse-to pom)))))
  7032. (when (and (org-element--cache-active-p)
  7033. element
  7034. (org-element--cache-verify-element element))
  7035. (setq element (org-element--parse-to pom)))
  7036. (unless (eq 'org-data (org-element-type element))
  7037. (unless (and cached-only
  7038. (not (and element
  7039. (or (= pom (org-element-property :begin element))
  7040. (and (not (memq (org-element-type element) org-element-greater-elements))
  7041. (>= pom (org-element-property :begin element))
  7042. (< pom (org-element-property :end element)))
  7043. (and (org-element-property :contents-begin element)
  7044. (>= pom (org-element-property :begin element))
  7045. (< pom (org-element-property :contents-begin element)))
  7046. (and (not (org-element-property :contents-end element))
  7047. (>= pom (org-element-property :begin element))
  7048. (< pom (org-element-property :end element)))))))
  7049. (if (not (eq (org-element-type element) 'section))
  7050. element
  7051. (org-element-at-point (1+ pom) cached-only))))))
  7052. ;;;###autoload
  7053. (defsubst org-element-at-point-no-context (&optional pom)
  7054. "Quickly find element at point or POM.
  7055. It is a faster version of `org-element-at-point' that is not
  7056. guaranteed to return correct `:parent' properties even when cache is
  7057. enabled."
  7058. (or (org-element-at-point pom 'cached-only)
  7059. (let (org-element-use-cache) (org-element-at-point pom))))
  7060. ;;;###autoload
  7061. (defun org-element-context (&optional element)
  7062. "Return smallest element or object around point.
  7063. Return value is a list like (TYPE PROPS) where TYPE is the type
  7064. of the element or object and PROPS a plist of properties
  7065. associated to it.
  7066. Possible types are defined in `org-element-all-elements' and
  7067. `org-element-all-objects'. Properties depend on element or
  7068. object type, but always include `:begin', `:end', `:parent' and
  7069. `:post-blank'.
  7070. As a special case, if point is right after an object and not at
  7071. the beginning of any other object, return that object.
  7072. Optional argument ELEMENT, when non-nil, is the closest element
  7073. containing point, as returned by `org-element-at-point'.
  7074. Providing it allows for quicker computation."
  7075. (catch 'objects-forbidden
  7076. (org-with-wide-buffer
  7077. (let* ((pos (point))
  7078. (element (or element (org-element-at-point)))
  7079. (type (org-element-type element))
  7080. (post (org-element-property :post-affiliated element)))
  7081. ;; If point is inside an element containing objects or
  7082. ;; a secondary string, narrow buffer to the container and
  7083. ;; proceed with parsing. Otherwise, return ELEMENT.
  7084. (cond
  7085. ;; At a parsed affiliated keyword, check if we're inside main
  7086. ;; or dual value.
  7087. ((and post (< pos post))
  7088. (beginning-of-line)
  7089. (let ((case-fold-search t)) (looking-at org-element--affiliated-re))
  7090. (cond
  7091. ((not (member-ignore-case (match-string 1)
  7092. org-element-parsed-keywords))
  7093. (throw 'objects-forbidden element))
  7094. ((< (match-end 0) pos)
  7095. (narrow-to-region (match-end 0) (line-end-position)))
  7096. ((and (match-beginning 2)
  7097. (>= pos (match-beginning 2))
  7098. (< pos (match-end 2)))
  7099. (narrow-to-region (match-beginning 2) (match-end 2)))
  7100. (t (throw 'objects-forbidden element)))
  7101. ;; Also change type to retrieve correct restrictions.
  7102. (setq type 'keyword))
  7103. ;; At an item, objects can only be located within tag, if any.
  7104. ((eq type 'item)
  7105. (let ((tag (org-element-property :tag element)))
  7106. (if (or (not tag) (/= (line-beginning-position) post))
  7107. (throw 'objects-forbidden element)
  7108. (beginning-of-line)
  7109. (search-forward tag (line-end-position))
  7110. (goto-char (match-beginning 0))
  7111. (if (and (>= pos (point)) (< pos (match-end 0)))
  7112. (narrow-to-region (point) (match-end 0))
  7113. (throw 'objects-forbidden element)))))
  7114. ;; At an headline or inlinetask, objects are in title.
  7115. ((memq type '(headline inlinetask))
  7116. (let ((case-fold-search nil))
  7117. (goto-char (org-element-property :begin element))
  7118. (looking-at org-complex-heading-regexp)
  7119. (let ((end (match-end 4)))
  7120. (if (not end) (throw 'objects-forbidden element)
  7121. (goto-char (match-beginning 4))
  7122. (when (looking-at org-element-comment-string)
  7123. (goto-char (match-end 0)))
  7124. (if (>= (point) end) (throw 'objects-forbidden element)
  7125. (narrow-to-region (point) end))))))
  7126. ;; At a paragraph, a table-row or a verse block, objects are
  7127. ;; located within their contents.
  7128. ((memq type '(paragraph table-row verse-block))
  7129. (let ((cbeg (org-element-property :contents-begin element))
  7130. (cend (org-element-property :contents-end element)))
  7131. ;; CBEG is nil for table rules.
  7132. (if (and cbeg cend (>= pos cbeg)
  7133. (or (< pos cend) (and (= pos cend) (eobp))))
  7134. (narrow-to-region cbeg cend)
  7135. (throw 'objects-forbidden element))))
  7136. (t (throw 'objects-forbidden element)))
  7137. (goto-char (point-min))
  7138. (let ((restriction (org-element-restriction type))
  7139. (parent element)
  7140. last)
  7141. (catch 'exit
  7142. (while t
  7143. (let ((next (org-element--object-lex restriction)))
  7144. (when next (org-element-put-property next :parent parent))
  7145. ;; Process NEXT, if any, in order to know if we need to
  7146. ;; skip it, return it or move into it.
  7147. (if (or (not next) (> (org-element-property :begin next) pos))
  7148. (throw 'exit (or last parent))
  7149. (let ((end (org-element-property :end next))
  7150. (cbeg (org-element-property :contents-begin next))
  7151. (cend (org-element-property :contents-end next)))
  7152. (cond
  7153. ;; Skip objects ending before point. Also skip
  7154. ;; objects ending at point unless it is also the
  7155. ;; end of buffer, since we want to return the
  7156. ;; innermost object.
  7157. ((and (<= end pos) (/= (point-max) end))
  7158. (goto-char end)
  7159. ;; For convenience, when object ends at POS,
  7160. ;; without any space, store it in LAST, as we
  7161. ;; will return it if no object starts here.
  7162. (when (and (= end pos)
  7163. (not (memq (char-before) '(?\s ?\t))))
  7164. (setq last next)))
  7165. ;; If POS is within a container object, move into
  7166. ;; that object.
  7167. ((and cbeg cend
  7168. (>= pos cbeg)
  7169. (or (< pos cend)
  7170. ;; At contents' end, if there is no
  7171. ;; space before point, also move into
  7172. ;; object, for consistency with
  7173. ;; convenience feature above.
  7174. (and (= pos cend)
  7175. (or (= (point-max) pos)
  7176. (not (memq (char-before pos)
  7177. '(?\s ?\t)))))))
  7178. (goto-char cbeg)
  7179. (narrow-to-region (point) cend)
  7180. (setq parent next)
  7181. (setq restriction (org-element-restriction next)))
  7182. ;; Otherwise, return NEXT.
  7183. (t (throw 'exit next)))))))))))))
  7184. (defun org-element-lineage (datum &optional types with-self)
  7185. "List all ancestors of a given element or object.
  7186. DATUM is an object or element.
  7187. Return ancestors from the closest to the farthest. When optional
  7188. argument TYPES is a list of symbols, return the first element or
  7189. object in the lineage whose type belongs to that list instead.
  7190. When optional argument WITH-SELF is non-nil, lineage includes
  7191. DATUM itself as the first element, and TYPES, if provided, also
  7192. apply to it.
  7193. When DATUM is obtained through `org-element-context' or
  7194. `org-element-at-point', only ancestors from its section can be
  7195. found. There is no such limitation when DATUM belongs to a full
  7196. parse tree."
  7197. (let ((up (if with-self datum (org-element-property :parent datum)))
  7198. ancestors)
  7199. (while (and up (not (memq (org-element-type up) types)))
  7200. (unless types (push up ancestors))
  7201. (setq up (org-element-property :parent up)))
  7202. (if types up (nreverse ancestors))))
  7203. (defun org-element-nested-p (elem-A elem-B)
  7204. "Non-nil when elements ELEM-A and ELEM-B are nested."
  7205. (let ((beg-A (org-element-property :begin elem-A))
  7206. (beg-B (org-element-property :begin elem-B))
  7207. (end-A (org-element-property :end elem-A))
  7208. (end-B (org-element-property :end elem-B)))
  7209. (or (and (>= beg-A beg-B) (<= end-A end-B))
  7210. (and (>= beg-B beg-A) (<= end-B end-A)))))
  7211. (defun org-element-swap-A-B (elem-A elem-B)
  7212. "Swap elements ELEM-A and ELEM-B.
  7213. Assume ELEM-B is after ELEM-A in the buffer. Leave point at the
  7214. end of ELEM-A."
  7215. (goto-char (org-element-property :begin elem-A))
  7216. ;; There are two special cases when an element doesn't start at bol:
  7217. ;; the first paragraph in an item or in a footnote definition.
  7218. (let ((specialp (not (bolp))))
  7219. ;; Only a paragraph without any affiliated keyword can be moved at
  7220. ;; ELEM-A position in such a situation. Note that the case of
  7221. ;; a footnote definition is impossible: it cannot contain two
  7222. ;; paragraphs in a row because it cannot contain a blank line.
  7223. (when (and specialp
  7224. (or (not (eq (org-element-type elem-B) 'paragraph))
  7225. (/= (org-element-property :begin elem-B)
  7226. (org-element-property :contents-begin elem-B))))
  7227. (error "Cannot swap elements"))
  7228. ;; In a special situation, ELEM-A will have no indentation. We'll
  7229. ;; give it ELEM-B's (which will in, in turn, have no indentation).
  7230. (let* ((ind-B (when specialp
  7231. (goto-char (org-element-property :begin elem-B))
  7232. (current-indentation)))
  7233. (beg-A (org-element-property :begin elem-A))
  7234. (end-A (save-excursion
  7235. (goto-char (org-element-property :end elem-A))
  7236. (skip-chars-backward " \r\t\n")
  7237. (point-at-eol)))
  7238. (beg-B (org-element-property :begin elem-B))
  7239. (end-B (save-excursion
  7240. (goto-char (org-element-property :end elem-B))
  7241. (skip-chars-backward " \r\t\n")
  7242. (point-at-eol)))
  7243. ;; Store inner overlays responsible for visibility status.
  7244. ;; We also need to store their boundaries as they will be
  7245. ;; removed from buffer.
  7246. (overlays
  7247. (cons
  7248. (delq nil
  7249. (mapcar (lambda (o)
  7250. (and (>= (overlay-start o) beg-A)
  7251. (<= (overlay-end o) end-A)
  7252. (list o (overlay-start o) (overlay-end o))))
  7253. (overlays-in beg-A end-A)))
  7254. (delq nil
  7255. (mapcar (lambda (o)
  7256. (and (>= (overlay-start o) beg-B)
  7257. (<= (overlay-end o) end-B)
  7258. (list o (overlay-start o) (overlay-end o))))
  7259. (overlays-in beg-B end-B)))))
  7260. ;; Get contents.
  7261. (body-A (buffer-substring beg-A end-A))
  7262. (body-B (delete-and-extract-region beg-B end-B)))
  7263. (goto-char beg-B)
  7264. (when specialp
  7265. (setq body-B (replace-regexp-in-string "\\`[ \t]*" "" body-B))
  7266. (indent-to-column ind-B))
  7267. (insert body-A)
  7268. ;; Restore ex ELEM-A overlays.
  7269. (let ((offset (- beg-B beg-A)))
  7270. (dolist (o (car overlays))
  7271. (move-overlay (car o) (+ (nth 1 o) offset) (+ (nth 2 o) offset)))
  7272. (goto-char beg-A)
  7273. (delete-region beg-A end-A)
  7274. (insert body-B)
  7275. ;; Restore ex ELEM-B overlays.
  7276. (dolist (o (cdr overlays))
  7277. (move-overlay (car o) (- (nth 1 o) offset) (- (nth 2 o) offset))))
  7278. (goto-char (org-element-property :end elem-B)))))
  7279. (provide 'org-element)
  7280. ;; Local variables:
  7281. ;; generated-autoload-file: "org-loaddefs.el"
  7282. ;; End:
  7283. ;;; org-element.el ends here