org-element.el 330 KB

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