org-element.el 316 KB

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