org-element.el 329 KB

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