org-element.el 314 KB

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