org-element.el 305 KB

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