org.el 804 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; Homepage: https://orgmode.org
  9. ;; Package-Requires: ((emacs "25.1"))
  10. ;; Version: 9.6-dev
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'oc)
  86. (require 'org-table)
  87. (require 'org-fold)
  88. (require 'org-cycle)
  89. (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
  90. (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
  91. (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
  92. (defalias 'org-global-cycle #'org-cycle-global)
  93. (defalias 'org-overview #'org-cycle-overview)
  94. (defalias 'org-content #'org-cycle-content)
  95. (defalias 'org-reveal #'org-fold-reveal)
  96. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  97. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  98. (defvar org-outline-regexp "\\*+ "
  99. "Regexp to match Org headlines.")
  100. (defvar org-outline-regexp-bol "^\\*+ "
  101. "Regexp to match Org headlines.
  102. This is similar to `org-outline-regexp' but additionally makes
  103. sure that we are at the beginning of the line.")
  104. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  105. "Matches a headline, putting stars and text into groups.
  106. Stars are put in group 1 and the trimmed body in group 2.")
  107. (declare-function calendar-check-holidays "holidays" (date))
  108. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  109. (declare-function cdlatex-math-symbol "ext:cdlatex")
  110. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  111. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  112. (declare-function org-add-archive-files "org-archive" (files))
  113. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  114. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  115. (declare-function org-agenda-redo "org-agenda" (&optional all))
  116. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  117. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  118. (declare-function org-archive-subtree-default "org-archive" ())
  119. (declare-function org-archive-to-archive-sibling "org-archive" ())
  120. (declare-function org-attach "org-attach" ())
  121. (declare-function org-attach-dir "org-attach"
  122. (&optional create-if-not-exists-p no-fs-check))
  123. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  124. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  125. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  126. (declare-function org-clock-auto-clockout "org-clock" ())
  127. (declare-function org-clock-cancel "org-clock" ())
  128. (declare-function org-clock-display "org-clock" (&optional arg))
  129. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  130. (declare-function org-clock-goto "org-clock" (&optional select))
  131. (declare-function org-clock-in "org-clock" (&optional select start-time))
  132. (declare-function org-clock-in-last "org-clock" (&optional arg))
  133. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  134. (declare-function org-clock-out-if-current "org-clock" ())
  135. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  136. (declare-function org-clock-report "org-clock" (&optional arg))
  137. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  138. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  139. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  140. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  141. (declare-function org-clock-update-time-maybe "org-clock" ())
  142. (declare-function org-clocktable-shift "org-clock" (dir n))
  143. (declare-function org-columns-quit "org-colview" ())
  144. (declare-function org-columns-insert-dblock "org-colview" ())
  145. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  146. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  147. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  148. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  149. (declare-function org-element-cache-refresh "org-element" (pos))
  150. (declare-function org-element-cache-reset "org-element" (&optional all))
  151. (declare-function org-element-cache-map "org-element" (func &rest keys))
  152. (declare-function org-element-contents "org-element" (element))
  153. (declare-function org-element-context "org-element" (&optional element))
  154. (declare-function org-element-copy "org-element" (datum))
  155. (declare-function org-element-create "org-element" (type &optional props &rest children))
  156. (declare-function org-element-extract-element "org-element" (element))
  157. (declare-function org-element-insert-before "org-element" (element location))
  158. (declare-function org-element-interpret-data "org-element" (data))
  159. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  160. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  161. (declare-function org-element-link-parser "org-element" ())
  162. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  163. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  164. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  165. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  166. (declare-function org-element-property "org-element" (property element))
  167. (declare-function org-element-put-property "org-element" (element property value))
  168. (declare-function org-element-restriction "org-element" (element))
  169. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  170. (declare-function org-element-timestamp-parser "org-element" ())
  171. (declare-function org-element-type "org-element" (element))
  172. (declare-function org-element--cache-active-p "org-element" ())
  173. (declare-function org-export-dispatch "ox" (&optional arg))
  174. (declare-function org-export-get-backend "ox" (name))
  175. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  176. (declare-function org-feed-goto-inbox "org-feed" (feed))
  177. (declare-function org-feed-update-all "org-feed" ())
  178. (declare-function org-goto "org-goto" (&optional alternative-interface))
  179. (declare-function org-id-find-id-file "org-id" (id))
  180. (declare-function org-id-get-create "org-id" (&optional force))
  181. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  182. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  183. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  184. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  185. (declare-function org-num-mode "org-num" (&optional arg))
  186. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  187. (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
  188. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  189. (declare-function org-timer "org-timer" (&optional restart no-insert))
  190. (declare-function org-timer-item "org-timer" (&optional arg))
  191. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  192. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  193. (declare-function org-timer-start "org-timer" (&optional offset))
  194. (declare-function org-timer-stop "org-timer" ())
  195. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  196. (declare-function org-update-radio-target-regexp "ol" ())
  197. (defvar org-agenda-buffer-name)
  198. (defvar org-element-paragraph-separate)
  199. (defvar org-element-cache-map-continue-from)
  200. (defvar org-element--timestamp-regexp)
  201. (defvar org-indent-indentation-per-level)
  202. (defvar org-radio-target-regexp)
  203. (defvar org-target-link-regexp)
  204. (defvar org-target-regexp)
  205. (defvar org-id-overriding-file-name)
  206. ;; load languages based on value of `org-babel-load-languages'
  207. (defvar org-babel-load-languages)
  208. (defvar crm-separator) ; dynamically scoped param
  209. ;;;###autoload
  210. (defun org-babel-do-load-languages (sym value)
  211. "Load the languages defined in `org-babel-load-languages'."
  212. (set-default sym value)
  213. (dolist (pair org-babel-load-languages)
  214. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  215. (if active
  216. (require (intern (concat "ob-" lang)))
  217. (fmakunbound
  218. (intern (concat "org-babel-execute:" lang)))
  219. (fmakunbound
  220. (intern (concat "org-babel-expand-body:" lang)))))))
  221. ;;;###autoload
  222. (defun org-babel-load-file (file &optional compile)
  223. "Load Emacs Lisp source code blocks in the Org FILE.
  224. This function exports the source code using `org-babel-tangle'
  225. and then loads the resulting file using `load-file'. With
  226. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  227. byte-compiled before it is loaded."
  228. (interactive "fFile to load: \nP")
  229. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  230. ;; Tangle only if the Org file is newer than the Elisp file.
  231. (unless (org-file-newer-than-p
  232. tangled-file
  233. (file-attribute-modification-time
  234. (file-attributes (file-truename file))))
  235. (org-babel-tangle-file file
  236. tangled-file
  237. (rx string-start
  238. (or "emacs-lisp" "elisp")
  239. string-end)))
  240. (if compile
  241. (progn
  242. (byte-compile-file tangled-file)
  243. (load tangled-file)
  244. (message "Compiled and loaded %s" tangled-file))
  245. (load-file tangled-file)
  246. (message "Loaded %s" tangled-file))))
  247. (defcustom org-babel-load-languages '((emacs-lisp . t))
  248. "Languages which can be evaluated in Org buffers.
  249. \\<org-mode-map>
  250. This list can be used to load support for any of the languages
  251. below. Each language will depend on a different set of system
  252. executables and/or Emacs modes.
  253. When a language is \"loaded\", code blocks in that language can
  254. be evaluated with `org-babel-execute-src-block', which is bound
  255. by default to \\[org-ctrl-c-ctrl-c].
  256. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  257. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  258. default, only Emacs Lisp is loaded, since it has no specific
  259. requirement."
  260. :group 'org-babel
  261. :set 'org-babel-do-load-languages
  262. :version "24.1"
  263. :type '(alist :tag "Babel Languages"
  264. :key-type
  265. (choice
  266. (const :tag "Awk" awk)
  267. (const :tag "C" C)
  268. (const :tag "R" R)
  269. (const :tag "Calc" calc)
  270. (const :tag "Clojure" clojure)
  271. (const :tag "CSS" css)
  272. (const :tag "Ditaa" ditaa)
  273. (const :tag "Dot" dot)
  274. (const :tag "Emacs Lisp" emacs-lisp)
  275. (const :tag "Forth" forth)
  276. (const :tag "Fortran" fortran)
  277. (const :tag "Gnuplot" gnuplot)
  278. (const :tag "Haskell" haskell)
  279. (const :tag "Java" java)
  280. (const :tag "Javascript" js)
  281. (const :tag "LaTeX" latex)
  282. (const :tag "Lilypond" lilypond)
  283. (const :tag "Lisp" lisp)
  284. (const :tag "Makefile" makefile)
  285. (const :tag "Maxima" maxima)
  286. (const :tag "Matlab" matlab)
  287. (const :tag "Ocaml" ocaml)
  288. (const :tag "Octave" octave)
  289. (const :tag "Org" org)
  290. (const :tag "Perl" perl)
  291. (const :tag "Pico Lisp" picolisp)
  292. (const :tag "PlantUML" plantuml)
  293. (const :tag "Python" python)
  294. (const :tag "Ruby" ruby)
  295. (const :tag "Sass" sass)
  296. (const :tag "Scala" scala)
  297. (const :tag "Scheme" scheme)
  298. (const :tag "Screen" screen)
  299. (const :tag "Shell Script" shell)
  300. (const :tag "Sql" sql)
  301. (const :tag "Sqlite" sqlite)
  302. (const :tag "Stan" stan))
  303. :value-type (boolean :tag "Activate" :value t)))
  304. ;;;; Customization variables
  305. (defcustom org-clone-delete-id nil
  306. "Remove ID property of clones of a subtree.
  307. When non-nil, clones of a subtree don't inherit the ID property.
  308. Otherwise they inherit the ID property with a new unique
  309. identifier."
  310. :type 'boolean
  311. :version "24.1"
  312. :group 'org-id)
  313. ;;; Version
  314. (org-check-version)
  315. ;;;###autoload
  316. (defun org-version (&optional here full message)
  317. "Show the Org version.
  318. Interactively, or when MESSAGE is non-nil, show it in echo area.
  319. With prefix argument, or when HERE is non-nil, insert it at point.
  320. In non-interactive uses, a reduced version string is output unless
  321. FULL is given."
  322. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  323. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  324. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  325. (load-suffixes (list ".el"))
  326. (org-install-dir
  327. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  328. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  329. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  330. (let* ((load-suffixes save-load-suffixes)
  331. (release (org-release))
  332. (git-version (org-git-version))
  333. (version (format "Org mode version %s (%s @ %s)"
  334. release
  335. git-version
  336. (if org-install-dir
  337. (if (string= org-dir org-install-dir)
  338. org-install-dir
  339. (concat "mixed installation! "
  340. org-install-dir
  341. " and "
  342. org-dir))
  343. "org-loaddefs.el can not be found!")))
  344. (version1 (if full version release)))
  345. (when here (insert version1))
  346. (when message (message "%s" version1))
  347. version1)))
  348. (defconst org-version (org-version))
  349. ;;; Syntax Constants
  350. ;;;; Comments
  351. (defconst org-comment-regexp
  352. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  353. "Regular expression for comment lines.")
  354. ;;;; Keyword
  355. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  356. "Regular expression for keyword-lines.")
  357. ;;;; Block
  358. (defconst org-block-regexp
  359. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  360. "Regular expression for hiding blocks.")
  361. (defconst org-dblock-start-re
  362. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  363. "Matches the start line of a dynamic block, with parameters.")
  364. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  365. "Matches the end of a dynamic block.")
  366. ;;;; Timestamp
  367. (defconst org-ts--internal-regexp
  368. (rx (seq
  369. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  370. (optional " " (*? nonl))))
  371. "Regular expression matching the innards of a time stamp.")
  372. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  373. "Regular expression for fast time stamp matching.")
  374. (defconst org-ts-regexp-inactive
  375. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  376. "Regular expression for fast inactive time stamp matching.")
  377. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  378. "Regular expression for fast time stamp matching.")
  379. (defconst org-ts-regexp0
  380. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  381. "Regular expression matching time strings for analysis.
  382. This one does not require the space after the date, so it can be used
  383. on a string that terminates immediately after the date.")
  384. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  385. "Regular expression matching time strings for analysis.")
  386. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  387. "Regular expression matching time stamps, with groups.")
  388. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  389. "Regular expression matching time stamps (also [..]), with groups.")
  390. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  391. "Regular expression matching a time stamp range.")
  392. (defconst org-tr-regexp-both
  393. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  394. "Regular expression matching a time stamp range.")
  395. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  396. org-ts-regexp "\\)?")
  397. "Regular expression matching a time stamp or time stamp range.")
  398. (defconst org-tsr-regexp-both
  399. (concat org-ts-regexp-both "\\(--?-?"
  400. org-ts-regexp-both "\\)?")
  401. "Regular expression matching a time stamp or time stamp range.
  402. The time stamps may be either active or inactive.")
  403. (defconst org-repeat-re
  404. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  405. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  406. "Regular expression for specifying repeated events.
  407. After a match, group 1 contains the repeat expression.")
  408. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  409. "Formats for `format-time-string' which are used for time stamps.")
  410. ;;;; Clock and Planning
  411. (defconst org-clock-string "CLOCK:"
  412. "String used as prefix for timestamps clocking work hours on an item.")
  413. (defvar org-closed-string "CLOSED:"
  414. "String used as the prefix for timestamps logging closing a TODO entry.")
  415. (defvar org-deadline-string "DEADLINE:"
  416. "String to mark deadline entries.
  417. \\<org-mode-map>
  418. A deadline is this string, followed by a time stamp. It must be
  419. a word, terminated by a colon. You can insert a schedule keyword
  420. and a timestamp with `\\[org-deadline]'.")
  421. (defvar org-scheduled-string "SCHEDULED:"
  422. "String to mark scheduled TODO entries.
  423. \\<org-mode-map>
  424. A schedule is this string, followed by a time stamp. It must be
  425. a word, terminated by a colon. You can insert a schedule keyword
  426. and a timestamp with `\\[org-schedule]'.")
  427. (defconst org-ds-keyword-length
  428. (+ 2
  429. (apply #'max
  430. (mapcar #'length
  431. (list org-deadline-string org-scheduled-string
  432. org-clock-string org-closed-string))))
  433. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  434. (defconst org-planning-line-re
  435. (concat "^[ \t]*"
  436. (regexp-opt
  437. (list org-closed-string org-deadline-string org-scheduled-string)
  438. t))
  439. "Matches a line with planning info.
  440. Matched keyword is in group 1.")
  441. (defconst org-clock-line-re
  442. (concat "^[ \t]*" org-clock-string)
  443. "Matches a line with clock info.")
  444. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  445. "Matches the DEADLINE keyword.")
  446. (defconst org-deadline-time-regexp
  447. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  448. "Matches the DEADLINE keyword together with a time stamp.")
  449. (defconst org-deadline-time-hour-regexp
  450. (concat "\\<" org-deadline-string
  451. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  452. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  453. (defconst org-deadline-line-regexp
  454. (concat "\\<\\(" org-deadline-string "\\).*")
  455. "Matches the DEADLINE keyword and the rest of the line.")
  456. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  457. "Matches the SCHEDULED keyword.")
  458. (defconst org-scheduled-time-regexp
  459. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  460. "Matches the SCHEDULED keyword together with a time stamp.")
  461. (defconst org-scheduled-time-hour-regexp
  462. (concat "\\<" org-scheduled-string
  463. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  464. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  465. (defconst org-closed-time-regexp
  466. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  467. "Matches the CLOSED keyword together with a time stamp.")
  468. (defconst org-keyword-time-regexp
  469. (concat "\\<"
  470. (regexp-opt
  471. (list org-scheduled-string org-deadline-string org-closed-string
  472. org-clock-string)
  473. t)
  474. " *[[<]\\([^]>]+\\)[]>]")
  475. "Matches any of the 4 keywords, together with the time stamp.")
  476. (defconst org-keyword-time-not-clock-regexp
  477. (concat
  478. "\\<"
  479. (regexp-opt
  480. (list org-scheduled-string org-deadline-string org-closed-string) t)
  481. " *[[<]\\([^]>]+\\)[]>]")
  482. "Matches any of the 3 keywords, together with the time stamp.")
  483. (defconst org-all-time-keywords
  484. (mapcar (lambda (w) (substring w 0 -1))
  485. (list org-scheduled-string org-deadline-string
  486. org-clock-string org-closed-string))
  487. "List of time keywords.")
  488. ;;;; Drawer
  489. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  490. "Matches first or last line of a hidden block.
  491. Group 1 contains drawer's name or \"END\".")
  492. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  493. "Regular expression matching the first line of a property drawer.")
  494. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  495. "Regular expression matching the last line of a property drawer.")
  496. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  497. "Regular expression matching the first line of a clock drawer.")
  498. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  499. "Regular expression matching the last line of a clock drawer.")
  500. (defconst org-logbook-drawer-re
  501. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  502. (*? (0+ nonl) "\n")
  503. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  504. "Matches an entire LOGBOOK drawer.")
  505. (defconst org-property-drawer-re
  506. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  507. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  508. "[ \t]*:END:[ \t]*$")
  509. "Matches an entire property drawer.")
  510. (defconst org-clock-drawer-re
  511. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  512. org-clock-drawer-end-re "\\)\n?")
  513. "Matches an entire clock drawer.")
  514. ;;;; Headline
  515. (defconst org-heading-keyword-regexp-format
  516. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  517. "Printf format for a regexp matching a headline with some keyword.
  518. This regexp will match the headline of any node which has the
  519. exact keyword that is put into the format. The keyword isn't in
  520. any group by default, but the stars and the body are.")
  521. (defconst org-heading-keyword-maybe-regexp-format
  522. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  523. "Printf format for a regexp matching a headline, possibly with some keyword.
  524. This regexp can match any headline with the specified keyword, or
  525. without a keyword. The keyword isn't in any group by default,
  526. but the stars and the body are.")
  527. (defconst org-archive-tag "ARCHIVE"
  528. "The tag that marks a subtree as archived.
  529. An archived subtree does not open during visibility cycling, and does
  530. not contribute to the agenda listings.")
  531. (defconst org-tag-re "[[:alnum:]_@#%]+"
  532. "Regexp matching a single tag.")
  533. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  534. "Regexp matching the tag group at the end of a line, with leading spaces.
  535. Tags are stored in match group 1. Match group 2 stores the tags
  536. without the enclosing colons.")
  537. (defconst org-tag-line-re
  538. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  539. "Regexp matching tags in a headline.
  540. Tags are stored in match group 1. Match group 2 stores the tags
  541. without the enclosing colons.")
  542. (eval-and-compile
  543. (defconst org-comment-string "COMMENT"
  544. "Entries starting with this keyword will never be exported.
  545. \\<org-mode-map>
  546. An entry can be toggled between COMMENT and normal with
  547. `\\[org-toggle-comment]'."))
  548. ;;;; LaTeX Environments and Fragments
  549. (defconst org-latex-regexps
  550. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  551. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  552. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  553. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  554. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  555. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  556. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  557. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  558. "Regular expressions for matching embedded LaTeX.")
  559. ;;;; Node Property
  560. (defconst org-effort-property "Effort"
  561. "The property that is being used to keep track of effort estimates.
  562. Effort estimates given in this property need to be in the format
  563. defined in org-duration.el.")
  564. ;;; The custom variables
  565. (defgroup org nil
  566. "Outline-based notes management and organizer."
  567. :tag "Org"
  568. :group 'outlines
  569. :group 'calendar)
  570. (defcustom org-mode-hook nil
  571. "Mode hook for Org mode, run after the mode was turned on."
  572. :group 'org
  573. :type 'hook)
  574. (defcustom org-load-hook nil
  575. "Hook that is run after org.el has been loaded."
  576. :group 'org
  577. :type 'hook)
  578. (make-obsolete-variable
  579. 'org-load-hook
  580. "use `with-eval-after-load' instead." "9.5")
  581. (defcustom org-log-buffer-setup-hook nil
  582. "Hook that is run after an Org log buffer is created."
  583. :group 'org
  584. :version "24.1"
  585. :type 'hook)
  586. (defvar org-modules) ; defined below
  587. (defvar org-modules-loaded nil
  588. "Have the modules been loaded already?")
  589. ;;;###autoload
  590. (defun org-load-modules-maybe (&optional force)
  591. "Load all extensions listed in `org-modules'."
  592. (when (or force (not org-modules-loaded))
  593. (dolist (ext org-modules)
  594. (condition-case nil (require ext)
  595. (error (message "Problems while trying to load feature `%s'" ext))))
  596. (setq org-modules-loaded t)))
  597. (defun org-set-modules (var value)
  598. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  599. (set var value)
  600. (when (featurep 'org)
  601. (org-load-modules-maybe 'force)
  602. (org-element-cache-reset 'all)))
  603. (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  604. "Modules that should always be loaded together with org.el.
  605. If a description starts with <C>, the file is not part of Emacs and Org mode,
  606. so loading it will require that you have properly installed org-contrib
  607. package from NonGNU Emacs Lisp Package Archive
  608. https://elpa.nongnu.org/nongnu/org-contrib.html
  609. You can also use this system to load external packages (i.e. neither Org
  610. core modules, nor org-contrib modules). Just add symbols
  611. to the end of the list. If the package is called org-xyz.el, then you need
  612. to add the symbol `xyz', and the package must have a call to:
  613. (provide \\='org-xyz)
  614. For export specific modules, see also `org-export-backends'."
  615. :group 'org
  616. :set 'org-set-modules
  617. :package-version '(Org . "9.5")
  618. :type
  619. '(set :greedy t
  620. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  621. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  622. (const :tag " crypt: Encryption of subtrees" org-crypt)
  623. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  624. (const :tag " docview: Links to Docview buffers" ol-docview)
  625. (const :tag " doi: Links to DOI references" ol-doi)
  626. (const :tag " eww: Store link to URL of Eww" ol-eww)
  627. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  628. (const :tag " habit: Track your consistency with habits" org-habit)
  629. (const :tag " id: Global IDs for identifying entries" org-id)
  630. (const :tag " info: Links to Info nodes" ol-info)
  631. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  632. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  633. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  634. (const :tag " mouse: Additional mouse support" org-mouse)
  635. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  636. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  637. (const :tag " tempo: Fast completion for structures" org-tempo)
  638. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  639. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  640. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  641. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  642. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  643. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  644. (const :tag "C collector: Collect properties into tables" org-collector)
  645. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  646. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  647. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  648. (const :tag "C eval: Include command output as text" org-eval)
  649. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  650. (const :tag "C git-link: Links to specific file version" ol-git-link)
  651. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  652. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  653. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  654. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  655. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  656. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  657. (const :tag "C man: Links to man pages in Org mode" ol-man)
  658. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  659. (const :tag "C notify: Notifications for Org mode" org-notify)
  660. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  661. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  662. (const :tag "C registry: A registry for Org links" org-registry)
  663. (const :tag "C screen: Visit screen sessions through links" org-screen)
  664. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  665. (const :tag "C secretary: Team management with Org" org-secretary)
  666. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  667. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  668. (const :tag "C track: Keep up with Org mode development" org-track)
  669. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  670. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  671. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  672. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  673. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  674. (defvar org-export-registered-backends) ; From ox.el.
  675. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  676. (declare-function org-export-backend-name "ox" (backend) t)
  677. (defcustom org-export-backends '(ascii html icalendar latex odt)
  678. "List of export back-ends that should be always available.
  679. If a description starts with <C>, the file is not part of Emacs and Org mode,
  680. so loading it will require that you have properly installed org-contrib
  681. package from NonGNU Emacs Lisp Package Archive
  682. https://elpa.nongnu.org/nongnu/org-contrib.html
  683. Unlike to `org-modules', libraries in this list will not be
  684. loaded along with Org, but only once the export framework is
  685. needed.
  686. This variable needs to be set before org.el is loaded. If you
  687. need to make a change while Emacs is running, use the customize
  688. interface or run the following code, where VAL stands for the new
  689. value of the variable, after updating it:
  690. (progn
  691. (setq org-export-registered-backends
  692. (cl-remove-if-not
  693. (lambda (backend)
  694. (let ((name (org-export-backend-name backend)))
  695. (or (memq name val)
  696. (catch \\='parentp
  697. (dolist (b val)
  698. (and (org-export-derived-backend-p b name)
  699. (throw \\='parentp t)))))))
  700. org-export-registered-backends))
  701. (let ((new-list (mapcar #\\='org-export-backend-name
  702. org-export-registered-backends)))
  703. (dolist (backend val)
  704. (cond
  705. ((not (load (format \"ox-%s\" backend) t t))
  706. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  707. backend))
  708. ((not (memq backend new-list)) (push backend new-list))))
  709. (set-default \\='org-export-backends new-list)))
  710. Adding a back-end to this list will also pull the back-end it
  711. depends on, if any."
  712. :group 'org
  713. :group 'org-export
  714. :version "26.1"
  715. :package-version '(Org . "9.0")
  716. :initialize 'custom-initialize-set
  717. :set (lambda (var val)
  718. (if (not (featurep 'ox)) (set-default var val)
  719. ;; Any back-end not required anymore (not present in VAL and not
  720. ;; a parent of any back-end in the new value) is removed from the
  721. ;; list of registered back-ends.
  722. (setq org-export-registered-backends
  723. (cl-remove-if-not
  724. (lambda (backend)
  725. (let ((name (org-export-backend-name backend)))
  726. (or (memq name val)
  727. (catch 'parentp
  728. (dolist (b val)
  729. (and (org-export-derived-backend-p b name)
  730. (throw 'parentp t)))))))
  731. org-export-registered-backends))
  732. ;; Now build NEW-LIST of both new back-ends and required
  733. ;; parents.
  734. (let ((new-list (mapcar #'org-export-backend-name
  735. org-export-registered-backends)))
  736. (dolist (backend val)
  737. (cond
  738. ((not (load (format "ox-%s" backend) t t))
  739. (message "Problems while trying to load export back-end `%s'"
  740. backend))
  741. ((not (memq backend new-list)) (push backend new-list))))
  742. ;; Set VAR to that list with fixed dependencies.
  743. (set-default var new-list))))
  744. :type '(set :greedy t
  745. (const :tag " ascii Export buffer to ASCII format" ascii)
  746. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  747. (const :tag " html Export buffer to HTML format" html)
  748. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  749. (const :tag " latex Export buffer to LaTeX format" latex)
  750. (const :tag " man Export buffer to MAN format" man)
  751. (const :tag " md Export buffer to Markdown format" md)
  752. (const :tag " odt Export buffer to ODT format" odt)
  753. (const :tag " org Export buffer to Org format" org)
  754. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  755. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  756. (const :tag "C deck Export buffer to deck.js presentations" deck)
  757. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  758. (const :tag "C groff Export buffer to Groff format" groff)
  759. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  760. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  761. (const :tag "C s5 Export buffer to s5 presentations" s5)
  762. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  763. (eval-after-load 'ox
  764. '(dolist (backend org-export-backends)
  765. (condition-case nil (require (intern (format "ox-%s" backend)))
  766. (error (message "Problems while trying to load export back-end `%s'"
  767. backend)))))
  768. (defcustom org-support-shift-select nil
  769. "Non-nil means make shift-cursor commands select text when possible.
  770. \\<org-mode-map>
  771. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  772. start selecting a region, or enlarge regions started in this way.
  773. In Org mode, in special contexts, these same keys are used for
  774. other purposes, important enough to compete with shift selection.
  775. Org tries to balance these needs by supporting `shift-select-mode'
  776. outside these special contexts, under control of this variable.
  777. The default of this variable is nil, to avoid confusing behavior. Shifted
  778. cursor keys will then execute Org commands in the following contexts:
  779. - on a headline, changing TODO state (left/right) and priority (up/down)
  780. - on a time stamp, changing the time
  781. - in a plain list item, changing the bullet type
  782. - in a property definition line, switching between allowed values
  783. - in the BEGIN line of a clock table (changing the time block).
  784. - in a table, moving the cell in the specified direction.
  785. Outside these contexts, the commands will throw an error.
  786. When this variable is t and the cursor is not in a special
  787. context, Org mode will support shift-selection for making and
  788. enlarging regions. To make this more effective, the bullet
  789. cycling will no longer happen anywhere in an item line, but only
  790. if the cursor is exactly on the bullet.
  791. If you set this variable to the symbol `always', then the keys
  792. will not be special in headlines, property lines, item lines, and
  793. table cells, to make shift selection work there as well. If this is
  794. what you want, you can use the following alternative commands:
  795. `\\[org-todo]' and `\\[org-priority]' \
  796. to change TODO state and priority,
  797. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  798. can be used to switch TODO sets,
  799. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  800. and properties can be edited by hand or in column view.
  801. However, when the cursor is on a timestamp, shift-cursor commands
  802. will still edit the time stamp - this is just too good to give up."
  803. :group 'org
  804. :type '(choice
  805. (const :tag "Never" nil)
  806. (const :tag "When outside special context" t)
  807. (const :tag "Everywhere except timestamps" always)))
  808. (defcustom org-loop-over-headlines-in-active-region t
  809. "Shall some commands act upon headlines in the active region?
  810. When set to t, some commands will be performed in all headlines
  811. within the active region.
  812. When set to `start-level', some commands will be performed in all
  813. headlines within the active region, provided that these headlines
  814. are of the same level than the first one.
  815. When set to a string, those commands will be performed on the
  816. matching headlines within the active region. Such string must be
  817. a tags/property/todo match as it is used in the agenda tags view.
  818. The list of commands is: `org-schedule', `org-deadline',
  819. `org-todo', `org-set-tags-command', `org-archive-subtree',
  820. `org-archive-set-tag', `org-toggle-archive-tag' and
  821. `org-archive-to-archive-sibling'. The archiving commands skip
  822. already archived entries.
  823. See `org-agenda-loop-over-headlines-in-active-region' for the
  824. equivalent option for agenda views."
  825. :type '(choice (const :tag "Don't loop" nil)
  826. (const :tag "All headlines in active region" t)
  827. (const :tag "In active region, headlines at the same level than the first one" start-level)
  828. (string :tag "Tags/Property/Todo matcher"))
  829. :package-version '(Org . "9.4")
  830. :group 'org-todo
  831. :group 'org-archive)
  832. (defcustom org-startup-folded 'showeverything
  833. "Non-nil means entering Org mode will switch to OVERVIEW.
  834. This can also be configured on a per-file basis by adding one of
  835. the following lines anywhere in the buffer:
  836. #+STARTUP: fold (or `overview', this is equivalent)
  837. #+STARTUP: nofold (or `showall', this is equivalent)
  838. #+STARTUP: content
  839. #+STARTUP: show<n>levels (<n> = 2..5)
  840. #+STARTUP: showeverything
  841. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  842. to ignore this option when Org opens agenda files for the first
  843. time."
  844. :group 'org-startup
  845. :package-version '(Org . "9.4")
  846. :type '(choice
  847. (const :tag "nofold: show all" nil)
  848. (const :tag "fold: overview" t)
  849. (const :tag "fold: show two levels" show2levels)
  850. (const :tag "fold: show three levels" show3levels)
  851. (const :tag "fold: show four levels" show4evels)
  852. (const :tag "fold: show five levels" show5levels)
  853. (const :tag "content: all headlines" content)
  854. (const :tag "show everything, even drawers" showeverything)))
  855. (defcustom org-startup-truncated t
  856. "Non-nil means entering Org mode will set `truncate-lines'.
  857. This is useful since some lines containing links can be very long and
  858. uninteresting. Also tables look terrible when wrapped.
  859. The variable `org-startup-truncated' allows to configure
  860. truncation for Org mode different to the other modes that use the
  861. variable `truncate-lines' and as a shortcut instead of putting
  862. the variable `truncate-lines' into the `org-mode-hook'. If one
  863. wants to configure truncation for Org mode not statically but
  864. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  865. the variable `truncate-lines' has to be used because in such a
  866. case it is too late to set the variable `org-startup-truncated'."
  867. :group 'org-startup
  868. :type 'boolean)
  869. (defcustom org-startup-indented nil
  870. "Non-nil means turn on `org-indent-mode' on startup.
  871. This can also be configured on a per-file basis by adding one of
  872. the following lines anywhere in the buffer:
  873. #+STARTUP: indent
  874. #+STARTUP: noindent"
  875. :group 'org-structure
  876. :type '(choice
  877. (const :tag "Not" nil)
  878. (const :tag "Globally (slow on startup in large files)" t)))
  879. (defcustom org-startup-numerated nil
  880. "Non-nil means turn on `org-num-mode' on startup.
  881. This can also be configured on a per-file basis by adding one of
  882. the following lines anywhere in the buffer:
  883. #+STARTUP: num
  884. #+STARTUP: nonum"
  885. :group 'org-structure
  886. :package-version '(Org . "9.4")
  887. :type '(choice
  888. (const :tag "Not" nil)
  889. (const :tag "Globally" t)))
  890. (defcustom org-use-sub-superscripts t
  891. "Non-nil means interpret \"_\" and \"^\" for display.
  892. If you want to control how Org exports those characters, see
  893. `org-export-with-sub-superscripts'.
  894. When this option is turned on, you can use TeX-like syntax for
  895. sub- and superscripts within the buffer. Several characters after
  896. \"_\" or \"^\" will be considered as a single item - so grouping
  897. with {} is normally not needed. For example, the following things
  898. will be parsed as single sub- or superscripts:
  899. 10^24 or 10^tau several digits will be considered 1 item.
  900. 10^-12 or 10^-tau a leading sign with digits or a word
  901. x^2-y^3 will be read as x^2 - y^3, because items are
  902. terminated by almost any nonword/nondigit char.
  903. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  904. Still, ambiguity is possible. So when in doubt, use {} to enclose
  905. the sub/superscript. If you set this variable to the symbol `{}',
  906. the braces are *required* in order to trigger interpretations as
  907. sub/superscript. This can be helpful in documents that need \"_\"
  908. frequently in plain text."
  909. :group 'org-startup
  910. :version "24.4"
  911. :package-version '(Org . "8.0")
  912. :type '(choice
  913. (const :tag "Always interpret" t)
  914. (const :tag "Only with braces" {})
  915. (const :tag "Never interpret" nil)))
  916. (defcustom org-startup-with-beamer-mode nil
  917. "Non-nil means turn on `org-beamer-mode' on startup.
  918. This can also be configured on a per-file basis by adding one of
  919. the following lines anywhere in the buffer:
  920. #+STARTUP: beamer"
  921. :group 'org-startup
  922. :version "24.1"
  923. :type 'boolean)
  924. (defcustom org-startup-align-all-tables nil
  925. "Non-nil means align all tables when visiting a file.
  926. This can also be configured on a per-file basis by adding one of
  927. the following lines anywhere in the buffer:
  928. #+STARTUP: align
  929. #+STARTUP: noalign"
  930. :group 'org-startup
  931. :type 'boolean)
  932. (defcustom org-startup-shrink-all-tables nil
  933. "Non-nil means shrink all table columns with a width cookie.
  934. This can also be configured on a per-file basis by adding one of
  935. the following lines anywhere in the buffer:
  936. #+STARTUP: shrink"
  937. :group 'org-startup
  938. :type 'boolean
  939. :version "27.1"
  940. :package-version '(Org . "9.2")
  941. :safe #'booleanp)
  942. (defcustom org-startup-with-inline-images nil
  943. "Non-nil means show inline images when loading a new Org file.
  944. This can also be configured on a per-file basis by adding one of
  945. the following lines anywhere in the buffer:
  946. #+STARTUP: inlineimages
  947. #+STARTUP: noinlineimages"
  948. :group 'org-startup
  949. :version "24.1"
  950. :type 'boolean)
  951. (defcustom org-startup-with-latex-preview nil
  952. "Non-nil means preview LaTeX fragments when loading a new Org file.
  953. This can also be configured on a per-file basis by adding one of
  954. the following lines anywhere in the buffer:
  955. #+STARTUP: latexpreview
  956. #+STARTUP: nolatexpreview"
  957. :group 'org-startup
  958. :version "24.4"
  959. :package-version '(Org . "8.0")
  960. :type 'boolean)
  961. (defcustom org-insert-mode-line-in-empty-file nil
  962. "Non-nil means insert the first line setting Org mode in empty files.
  963. When the function `org-mode' is called interactively in an empty file, this
  964. normally means that the file name does not automatically trigger Org mode.
  965. To ensure that the file will always be in Org mode in the future, a
  966. line enforcing Org mode will be inserted into the buffer, if this option
  967. has been set."
  968. :group 'org-startup
  969. :type 'boolean)
  970. (defcustom org-ellipsis nil
  971. "The ellipsis to use in the Org mode outline.
  972. When nil, just use the standard three dots. When a non-empty string,
  973. use that string instead.
  974. The change affects only Org mode (which will then use its own display table).
  975. Changing this requires executing `\\[org-mode]' in a buffer to become
  976. effective. It cannot be set as a local variable."
  977. :group 'org-startup
  978. :type '(choice (const :tag "Default" nil)
  979. (string :tag "String" :value "...#")))
  980. (defvar org-display-table nil
  981. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  982. (defcustom org-directory "~/org"
  983. "Directory with Org files.
  984. This is just a default location to look for Org files. There is no need
  985. at all to put your files into this directory. It is used in the
  986. following situations:
  987. 1. When a capture template specifies a target file that is not an
  988. absolute path. The path will then be interpreted relative to
  989. `org-directory'
  990. 2. When the value of variable `org-agenda-files' is a single file, any
  991. relative paths in this file will be taken as relative to
  992. `org-directory'."
  993. :group 'org-refile
  994. :group 'org-capture
  995. :type 'directory)
  996. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  997. "Default target for storing notes.
  998. Used as a fall back file for org-capture.el, for templates that
  999. do not specify a target file."
  1000. :group 'org-refile
  1001. :group 'org-capture
  1002. :type 'file)
  1003. (defcustom org-reverse-note-order nil
  1004. "Non-nil means store new notes at the beginning of a file or entry.
  1005. When nil, new notes will be filed to the end of a file or entry.
  1006. This can also be a list with cons cells of regular expressions that
  1007. are matched against file names, and values."
  1008. :group 'org-capture
  1009. :group 'org-refile
  1010. :type '(choice
  1011. (const :tag "Reverse always" t)
  1012. (const :tag "Reverse never" nil)
  1013. (repeat :tag "By file name regexp"
  1014. (cons regexp boolean))))
  1015. (defgroup org-keywords nil
  1016. "Keywords in Org mode."
  1017. :tag "Org Keywords"
  1018. :group 'org)
  1019. (defcustom org-closed-keep-when-no-todo nil
  1020. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1021. :group 'org-todo
  1022. :group 'org-keywords
  1023. :version "24.4"
  1024. :package-version '(Org . "8.0")
  1025. :type 'boolean)
  1026. (defgroup org-structure nil
  1027. "Options concerning the general structure of Org files."
  1028. :tag "Org Structure"
  1029. :group 'org)
  1030. (defcustom org-indirect-buffer-display 'other-window
  1031. "How should indirect tree buffers be displayed?
  1032. This applies to indirect buffers created with the commands
  1033. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1034. Valid values are:
  1035. current-window Display in the current window
  1036. other-window Just display in another window.
  1037. dedicated-frame Create one new frame, and re-use it each time.
  1038. new-frame Make a new frame each time. Note that in this case
  1039. previously-made indirect buffers are kept, and you need to
  1040. kill these buffers yourself."
  1041. :group 'org-structure
  1042. :group 'org-agenda-windows
  1043. :type '(choice
  1044. (const :tag "In current window" current-window)
  1045. (const :tag "In current frame, other window" other-window)
  1046. (const :tag "Each time a new frame" new-frame)
  1047. (const :tag "One dedicated frame" dedicated-frame)))
  1048. (defconst org-file-apps-gnu
  1049. '((remote . emacs)
  1050. (system . mailcap)
  1051. (t . mailcap))
  1052. "Default file applications on a UNIX or GNU/Linux system.
  1053. See `org-file-apps'.")
  1054. (defconst org-file-apps-macos
  1055. '((remote . emacs)
  1056. (system . "open %s")
  1057. ("ps.gz" . "gv %s")
  1058. ("eps.gz" . "gv %s")
  1059. ("dvi" . "xdvi %s")
  1060. ("fig" . "xfig %s")
  1061. (t . "open %s"))
  1062. "Default file applications on a macOS system.
  1063. The system \"open\" is known as a default, but we use X11 applications
  1064. for some files for which the OS does not have a good default.
  1065. See `org-file-apps'.")
  1066. (defconst org-file-apps-windowsnt
  1067. (list '(remote . emacs)
  1068. (cons 'system (lambda (file _path)
  1069. (with-no-warnings (w32-shell-execute "open" file))))
  1070. (cons t (lambda (file _path)
  1071. (with-no-warnings (w32-shell-execute "open" file)))))
  1072. "Default file applications on a Windows NT system.
  1073. The system \"open\" is used for most files.
  1074. See `org-file-apps'.")
  1075. (defcustom org-file-apps
  1076. '((auto-mode . emacs)
  1077. (directory . emacs)
  1078. ("\\.mm\\'" . default)
  1079. ("\\.x?html?\\'" . default)
  1080. ("\\.pdf\\'" . default))
  1081. "Applications for opening `file:path' items in a document.
  1082. \\<org-mode-map>
  1083. Org mode uses system defaults for different file types, but you
  1084. can use this variable to set the application for a given file
  1085. extension. The entries in this list are cons cells where the car
  1086. identifies files and the cdr the corresponding command.
  1087. Possible values for the file identifier are:
  1088. \"string\" A string as a file identifier can be interpreted in different
  1089. ways, depending on its contents:
  1090. - Alphanumeric characters only:
  1091. Match links with this file extension.
  1092. Example: (\"pdf\" . \"evince %s\")
  1093. to open PDFs with evince.
  1094. - Regular expression: Match links where the
  1095. filename matches the regexp. If you want to
  1096. use groups here, use shy groups.
  1097. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1098. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1099. to open *.html and *.xhtml with firefox.
  1100. - Regular expression which contains (non-shy) groups:
  1101. Match links where the whole link, including \"::\", and
  1102. anything after that, matches the regexp.
  1103. In a custom command string, %1, %2, etc. are replaced with
  1104. the parts of the link that were matched by the groups.
  1105. For backwards compatibility, if a command string is given
  1106. that does not use any of the group matches, this case is
  1107. handled identically to the second one (i.e. match against
  1108. file name only).
  1109. In a custom function, you can access the group matches with
  1110. (match-string n link).
  1111. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1112. \"evince -p %1 %s\")
  1113. to open [[file:document.pdf::5]] with evince at page 5.
  1114. `directory' Matches a directory
  1115. `remote' Matches a remote file, accessible through tramp or efs.
  1116. Remote files most likely should be visited through Emacs
  1117. because external applications cannot handle such paths.
  1118. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1119. so all files Emacs knows how to handle. Using this with
  1120. command `emacs' will open most files in Emacs. Beware that this
  1121. will also open html files inside Emacs, unless you add
  1122. (\"html\" . default) to the list as well.
  1123. `system' The system command to open files, like `open' on Windows
  1124. and macOS, and mailcap under GNU/Linux. This is the command
  1125. that will be selected if you call `org-open-at-point' with a
  1126. double prefix argument (`\\[universal-argument] \
  1127. \\[universal-argument] \\[org-open-at-point]').
  1128. t Default for files not matched by any of the other options.
  1129. Possible values for the command are:
  1130. `emacs' The file will be visited by the current Emacs process.
  1131. `default' Use the default application for this file type, which is the
  1132. association for t in the list, most likely in the system-specific
  1133. part. This can be used to overrule an unwanted setting in the
  1134. system-specific variable.
  1135. `system' Use the system command for opening files, like \"open\".
  1136. This command is specified by the entry whose car is `system'.
  1137. Most likely, the system-specific version of this variable
  1138. does define this command, but you can overrule/replace it
  1139. here.
  1140. `mailcap' Use command specified in the mailcaps.
  1141. string A command to be executed by a shell; %s will be replaced
  1142. by the path to the file.
  1143. function A Lisp function, which will be called with two arguments:
  1144. the file path and the original link string, without the
  1145. \"file:\" prefix.
  1146. For more examples, see the system specific constants
  1147. `org-file-apps-macos'
  1148. `org-file-apps-windowsnt'
  1149. `org-file-apps-gnu'."
  1150. :group 'org
  1151. :package-version '(Org . "9.4")
  1152. :type '(repeat
  1153. (cons (choice :value ""
  1154. (string :tag "Extension")
  1155. (const :tag "System command to open files" system)
  1156. (const :tag "Default for unrecognized files" t)
  1157. (const :tag "Remote file" remote)
  1158. (const :tag "Links to a directory" directory)
  1159. (const :tag "Any files that have Emacs modes"
  1160. auto-mode))
  1161. (choice :value ""
  1162. (const :tag "Visit with Emacs" emacs)
  1163. (const :tag "Use default" default)
  1164. (const :tag "Use the system command" system)
  1165. (string :tag "Command")
  1166. (function :tag "Function")))))
  1167. (defcustom org-open-non-existing-files nil
  1168. "Non-nil means `org-open-file' opens non-existing files.
  1169. When nil, an error is thrown.
  1170. This variable applies only to external applications because they
  1171. might choke on non-existing files. If the link is to a file that
  1172. will be opened in Emacs, the variable is ignored."
  1173. :group 'org
  1174. :type 'boolean
  1175. :safe #'booleanp)
  1176. (defcustom org-open-directory-means-index-dot-org nil
  1177. "When non-nil a link to a directory really means to \"index.org\".
  1178. When nil, following a directory link runs Dired or opens
  1179. a finder/explorer window on that directory."
  1180. :group 'org
  1181. :type 'boolean
  1182. :safe #'booleanp)
  1183. (defcustom org-bookmark-names-plist
  1184. '(:last-capture "org-capture-last-stored"
  1185. :last-refile "org-refile-last-stored"
  1186. :last-capture-marker "org-capture-last-stored-marker")
  1187. "Names for bookmarks automatically set by some Org commands.
  1188. This can provide strings as names for a number of bookmarks Org sets
  1189. automatically. The following keys are currently implemented:
  1190. :last-capture
  1191. :last-capture-marker
  1192. :last-refile
  1193. When a key does not show up in the property list, the corresponding bookmark
  1194. is not set."
  1195. :group 'org-structure
  1196. :type 'plist)
  1197. (defgroup org-edit-structure nil
  1198. "Options concerning structure editing in Org mode."
  1199. :tag "Org Edit Structure"
  1200. :group 'org-structure)
  1201. (defcustom org-odd-levels-only nil
  1202. "Non-nil means skip even levels and only use odd levels for the outline.
  1203. This has the effect that two stars are being added/taken away in
  1204. promotion/demotion commands. It also influences how levels are
  1205. handled by the exporters.
  1206. Changing it requires restart of `font-lock-mode' to become effective
  1207. for fontification also in regions already fontified.
  1208. You may also set this on a per-file basis by adding one of the following
  1209. lines to the buffer:
  1210. #+STARTUP: odd
  1211. #+STARTUP: oddeven"
  1212. :group 'org-edit-structure
  1213. :group 'org-appearance
  1214. :type 'boolean)
  1215. (defcustom org-adapt-indentation nil
  1216. "Non-nil means adapt indentation to outline node level.
  1217. When set to t, Org assumes that you write outlines by indenting
  1218. text in each node to align with the headline, after the stars.
  1219. When this variable is set to `headline-data', Org only adapts the
  1220. indentation of the data lines right below the headline, such as
  1221. planning/clock lines and property/logbook drawers.
  1222. The following issues are influenced by this variable:
  1223. - The indentation is increased by one space in a demotion
  1224. command, and decreased by one in a promotion command. However,
  1225. in the latter case, if shifting some line in the entry body
  1226. would alter document structure (e.g., insert a new headline),
  1227. indentation is not changed at all.
  1228. - Property drawers and planning information is inserted indented
  1229. when this variable is set. When nil, they will not be indented.
  1230. - TAB indents a line relative to current level. The lines below
  1231. a headline will be indented when this variable is set to t.
  1232. Note that this is all about true indentation, by adding and
  1233. removing space characters. See also \"org-indent.el\" which does
  1234. level-dependent indentation in a virtual way, i.e. at display
  1235. time in Emacs."
  1236. :group 'org-edit-structure
  1237. :type '(choice
  1238. (const :tag "Adapt indentation for all lines" t)
  1239. (const :tag "Adapt indentation for headline data lines"
  1240. headline-data)
  1241. (const :tag "Do not adapt indentation at all" nil))
  1242. :safe (lambda (x) (memq x '(t nil headline-data))))
  1243. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1244. (defcustom org-special-ctrl-a/e nil
  1245. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1246. When t, `C-a' will bring back the cursor to the beginning of the
  1247. headline text, i.e. after the stars and after a possible TODO
  1248. keyword. In an item, this will be the position after bullet and
  1249. check-box, if any. When the cursor is already at that position,
  1250. another `C-a' will bring it to the beginning of the line.
  1251. `C-e' will jump to the end of the headline, ignoring the presence
  1252. of tags in the headline. A second `C-e' will then jump to the
  1253. true end of the line, after any tags. This also means that, when
  1254. this variable is non-nil, `C-e' also will never jump beyond the
  1255. end of the heading of a folded section, i.e. not after the
  1256. ellipses.
  1257. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1258. normally, going to the true line boundary first. Only a directly
  1259. following, identical keypress will bring the cursor to the
  1260. special positions.
  1261. This may also be a cons cell where the behavior for `C-a' and
  1262. `C-e' is set separately."
  1263. :group 'org-edit-structure
  1264. :type '(choice
  1265. (const :tag "off" nil)
  1266. (const :tag "on: after stars/bullet and before tags first" t)
  1267. (const :tag "reversed: true line boundary first" reversed)
  1268. (cons :tag "Set C-a and C-e separately"
  1269. (choice :tag "Special C-a"
  1270. (const :tag "off" nil)
  1271. (const :tag "on: after stars/bullet first" t)
  1272. (const :tag "reversed: before stars/bullet first" reversed))
  1273. (choice :tag "Special C-e"
  1274. (const :tag "off" nil)
  1275. (const :tag "on: before tags first" t)
  1276. (const :tag "reversed: after tags first" reversed)))))
  1277. (defcustom org-special-ctrl-k nil
  1278. "Non-nil means `C-k' will behave specially in headlines.
  1279. When nil, `C-k' will call the default `kill-line' command.
  1280. When t, the following will happen while the cursor is in the headline:
  1281. - When at the beginning of a headline, kill the entire subtree.
  1282. - When in the middle of the headline text, kill the text up to the tags.
  1283. - When after the headline text and before the tags, kill all the tags."
  1284. :group 'org-edit-structure
  1285. :type 'boolean)
  1286. (defcustom org-ctrl-k-protect-subtree nil
  1287. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1288. When set to the symbol `error', simply throw an error when `C-k' is
  1289. used to kill (part-of) a headline that has hidden text behind it.
  1290. Any other non-nil value will result in a query to the user, if it is
  1291. OK to kill that hidden subtree. When nil, kill without remorse."
  1292. :group 'org-edit-structure
  1293. :version "24.1"
  1294. :type '(choice
  1295. (const :tag "Do not protect hidden subtrees" nil)
  1296. (const :tag "Protect hidden subtrees with a security query" t)
  1297. (const :tag "Never kill a hidden subtree with C-k" error)))
  1298. (defcustom org-special-ctrl-o t
  1299. "Non-nil means, make `C-o' insert a row in tables."
  1300. :group 'org-edit-structure
  1301. :type 'boolean)
  1302. (defcustom org-yank-folded-subtrees t
  1303. "Non-nil means when yanking subtrees, fold them.
  1304. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1305. it starts with a heading and all other headings in it are either children
  1306. or siblings, then fold all the subtrees. However, do this only if no
  1307. text after the yank would be swallowed into a folded tree by this action."
  1308. :group 'org-edit-structure
  1309. :type 'boolean)
  1310. (defcustom org-yank-adjusted-subtrees nil
  1311. "Non-nil means when yanking subtrees, adjust the level.
  1312. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1313. this function for details."
  1314. :group 'org-edit-structure
  1315. :type 'boolean)
  1316. (defcustom org-M-RET-may-split-line '((default . t))
  1317. "Non-nil means M-RET will split the line at the cursor position.
  1318. When nil, it will go to the end of the line before making a
  1319. new line.
  1320. You may also set this option in a different way for different
  1321. contexts. Valid contexts are:
  1322. headline when creating a new headline
  1323. item when creating a new item
  1324. table in a table field
  1325. default the value to be used for all contexts not explicitly
  1326. customized"
  1327. :group 'org-structure
  1328. :group 'org-table
  1329. :type '(choice
  1330. (const :tag "Always" t)
  1331. (const :tag "Never" nil)
  1332. (repeat :greedy t :tag "Individual contexts"
  1333. (cons
  1334. (choice :tag "Context"
  1335. (const headline)
  1336. (const item)
  1337. (const table)
  1338. (const default))
  1339. (boolean)))))
  1340. (defcustom org-insert-heading-respect-content nil
  1341. "Non-nil means insert new headings after the current subtree.
  1342. \\<org-mode-map>
  1343. When nil, the new heading is created directly after the current line.
  1344. The commands `\\[org-insert-heading-respect-content]' and \
  1345. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1346. for the duration of the command."
  1347. :group 'org-structure
  1348. :type 'boolean)
  1349. (defcustom org-blank-before-new-entry '((heading . auto)
  1350. (plain-list-item . auto))
  1351. "Should `org-insert-heading' leave a blank line before new heading/item?
  1352. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1353. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1354. which case Org will look at the surrounding headings/items and try to
  1355. make an intelligent decision whether to insert a blank line or not."
  1356. :group 'org-edit-structure
  1357. :type '(list
  1358. (cons (const heading)
  1359. (choice (const :tag "Never" nil)
  1360. (const :tag "Always" t)
  1361. (const :tag "Auto" auto)))
  1362. (cons (const plain-list-item)
  1363. (choice (const :tag "Never" nil)
  1364. (const :tag "Always" t)
  1365. (const :tag "Auto" auto)))))
  1366. (defcustom org-insert-heading-hook nil
  1367. "Hook being run after inserting a new heading."
  1368. :group 'org-edit-structure
  1369. :type 'hook)
  1370. (defgroup org-sparse-trees nil
  1371. "Options concerning sparse trees in Org mode."
  1372. :tag "Org Sparse Trees"
  1373. :group 'org-structure)
  1374. (defcustom org-highlight-sparse-tree-matches t
  1375. "Non-nil means highlight all matches that define a sparse tree.
  1376. The highlights will automatically disappear the next time the buffer is
  1377. changed by an edit command."
  1378. :group 'org-sparse-trees
  1379. :type 'boolean)
  1380. (defcustom org-remove-highlights-with-change t
  1381. "Non-nil means any change to the buffer will remove temporary highlights.
  1382. \\<org-mode-map>\
  1383. Such highlights are created by `org-occur' and `org-clock-display'.
  1384. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1385. to get rid of the highlights.
  1386. The highlights created by `org-latex-preview' always need
  1387. `\\[org-latex-preview]' to be removed."
  1388. :group 'org-sparse-trees
  1389. :group 'org-time
  1390. :type 'boolean)
  1391. (defcustom org-occur-case-fold-search t
  1392. "Non-nil means `org-occur' should be case-insensitive.
  1393. If set to `smart' the search will be case-insensitive only if it
  1394. doesn't specify any upper case character."
  1395. :group 'org-sparse-trees
  1396. :version "26.1"
  1397. :type '(choice
  1398. (const :tag "Case-sensitive" nil)
  1399. (const :tag "Case-insensitive" t)
  1400. (const :tag "Case-insensitive for lower case searches only" smart)))
  1401. (defcustom org-occur-hook '(org-first-headline-recenter)
  1402. "Hook that is run after `org-occur' has constructed a sparse tree.
  1403. This can be used to recenter the window to show as much of the structure
  1404. as possible."
  1405. :group 'org-sparse-trees
  1406. :type 'hook)
  1407. (defcustom org-self-insert-cluster-for-undo nil
  1408. "Non-nil means cluster self-insert commands for undo when possible.
  1409. If this is set, then, like in the Emacs command loop, 20 consecutive
  1410. characters will be undone together.
  1411. This is configurable, because there is some impact on typing performance."
  1412. :group 'org-table
  1413. :type 'boolean)
  1414. (defvaralias 'org-activate-links 'org-highlight-links)
  1415. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1416. "Types of links that should be highlighted in Org files.
  1417. This is a list of symbols, each one of them leading to the
  1418. highlighting of a certain link type.
  1419. You can still open links that are not highlighted.
  1420. In principle, it does not hurt to turn on highlighting for all
  1421. link types. There may be a small gain when turning off unused
  1422. link types. The types are:
  1423. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1424. angle Links in angular brackets that may contain whitespace like
  1425. <bbdb:Carsten Dominik>.
  1426. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1427. radio Text that is matched by a radio target, see manual for details.
  1428. tag Tag settings in a headline (link to tag search).
  1429. date Time stamps (link to calendar).
  1430. footnote Footnote labels.
  1431. If you set this variable during an Emacs session, use `org-mode-restart'
  1432. in the Org buffer so that the change takes effect."
  1433. :group 'org-appearance
  1434. :type '(set :greedy t
  1435. (const :tag "Double bracket links" bracket)
  1436. (const :tag "Angular bracket links" angle)
  1437. (const :tag "Plain text links" plain)
  1438. (const :tag "Radio target matches" radio)
  1439. (const :tag "Tags" tag)
  1440. (const :tag "Timestamps" date)
  1441. (const :tag "Footnotes" footnote)))
  1442. (defcustom org-mark-ring-length 4
  1443. "Number of different positions to be recorded in the ring.
  1444. Changing this requires a restart of Emacs to work correctly."
  1445. :group 'org-link-follow
  1446. :type 'integer)
  1447. (defgroup org-todo nil
  1448. "Options concerning TODO items in Org mode."
  1449. :tag "Org TODO"
  1450. :group 'org)
  1451. (defgroup org-progress nil
  1452. "Options concerning Progress logging in Org mode."
  1453. :tag "Org Progress"
  1454. :group 'org-time)
  1455. (defvar org-todo-interpretation-widgets
  1456. '((:tag "Sequence (cycling hits every state)" sequence)
  1457. (:tag "Type (cycling directly to DONE)" type))
  1458. "The available interpretation symbols for customizing `org-todo-keywords'.
  1459. Interested libraries should add to this list.")
  1460. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1461. "List of TODO entry keyword sequences and their interpretation.
  1462. \\<org-mode-map>This is a list of sequences.
  1463. Each sequence starts with a symbol, either `sequence' or `type',
  1464. indicating if the keywords should be interpreted as a sequence of
  1465. action steps, or as different types of TODO items. The first
  1466. keywords are states requiring action - these states will select a headline
  1467. for inclusion into the global TODO list Org produces. If one of the
  1468. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1469. signify that no further action is necessary. If \"|\" is not found,
  1470. the last keyword is treated as the only DONE state of the sequence.
  1471. The command `\\[org-todo]' cycles an entry through these states, and one
  1472. additional state where no keyword is present. For details about this
  1473. cycling, see the manual.
  1474. TODO keywords and interpretation can also be set on a per-file basis with
  1475. the special #+SEQ_TODO and #+TYP_TODO lines.
  1476. Each keyword can optionally specify a character for fast state selection
  1477. \(in combination with the variable `org-use-fast-todo-selection')
  1478. and specifiers for state change logging, using the same syntax that
  1479. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1480. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1481. indicates to record a time stamp each time this state is selected.
  1482. Each keyword may also specify if a timestamp or a note should be
  1483. recorded when entering or leaving the state, by adding additional
  1484. characters in the parenthesis after the keyword. This looks like this:
  1485. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1486. record only the time of the state change. With X and Y being either
  1487. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1488. Y when leaving the state if and only if the *target* state does not
  1489. define X. You may omit any of the fast-selection key or X or /Y,
  1490. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1491. For backward compatibility, this variable may also be just a list
  1492. of keywords. In this case the interpretation (sequence or type) will be
  1493. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1494. :group 'org-todo
  1495. :group 'org-keywords
  1496. :type '(choice
  1497. (repeat :tag "Old syntax, just keywords"
  1498. (string :tag "Keyword"))
  1499. (repeat :tag "New syntax"
  1500. (cons
  1501. (choice
  1502. :tag "Interpretation"
  1503. ;;Quick and dirty way to see
  1504. ;;`org-todo-interpretation'. This takes the
  1505. ;;place of item arguments
  1506. :convert-widget
  1507. (lambda (widget)
  1508. (widget-put widget
  1509. :args (mapcar
  1510. (lambda (x)
  1511. (widget-convert
  1512. (cons 'const x)))
  1513. org-todo-interpretation-widgets))
  1514. widget))
  1515. (repeat
  1516. (string :tag "Keyword"))))))
  1517. (defvar-local org-todo-keywords-1 nil
  1518. "All TODO and DONE keywords active in a buffer.")
  1519. (defvar org-todo-keywords-for-agenda nil)
  1520. (defvar org-done-keywords-for-agenda nil)
  1521. (defvar org-todo-keyword-alist-for-agenda nil)
  1522. (defvar org-tag-alist-for-agenda nil
  1523. "Alist of all tags from all agenda files.")
  1524. (defvar org-tag-groups-alist-for-agenda nil
  1525. "Alist of all groups tags from all current agenda files.")
  1526. (defvar-local org-tag-groups-alist nil)
  1527. (defvar org-agenda-contributing-files nil)
  1528. (defvar-local org-current-tag-alist nil
  1529. "Alist of all tag groups in current buffer.
  1530. This variable takes into consideration `org-tag-alist',
  1531. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1532. (defvar-local org-not-done-keywords nil)
  1533. (defvar-local org-done-keywords nil)
  1534. (defvar-local org-todo-heads nil)
  1535. (defvar-local org-todo-sets nil)
  1536. (defvar-local org-todo-log-states nil)
  1537. (defvar-local org-todo-kwd-alist nil)
  1538. (defvar-local org-todo-key-alist nil)
  1539. (defvar-local org-todo-key-trigger nil)
  1540. (defcustom org-todo-interpretation 'sequence
  1541. "Controls how TODO keywords are interpreted.
  1542. This variable is in principle obsolete and is only used for
  1543. backward compatibility, if the interpretation of todo keywords is
  1544. not given already in `org-todo-keywords'. See that variable for
  1545. more information."
  1546. :group 'org-todo
  1547. :group 'org-keywords
  1548. :type '(choice (const sequence)
  1549. (const type)))
  1550. (defcustom org-use-fast-todo-selection 'auto
  1551. "\\<org-mode-map>\
  1552. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1553. This variable describes if and under what circumstances the cycling
  1554. mechanism for TODO keywords will be replaced by a single-key, direct
  1555. selection scheme, where the choices are displayed in a little window.
  1556. When nil, fast selection is never used. This means that the command
  1557. will always switch to the next state.
  1558. When it is the symbol `auto', fast selection is whenever selection
  1559. keys have been defined.
  1560. `expert' is like `auto', but no special window with the keyword
  1561. will be shown, choices will only be listed in the prompt.
  1562. In all cases, the special interface is only used if access keys have
  1563. actually been assigned by the user, i.e. if keywords in the configuration
  1564. are followed by a letter in parenthesis, like TODO(t)."
  1565. :group 'org-todo
  1566. :set (lambda (var val)
  1567. (cond
  1568. ((eq var t) (set var 'auto))
  1569. ((eq var 'prefix) (set var nil))
  1570. (t (set var val))))
  1571. :type '(choice
  1572. (const :tag "Never" nil)
  1573. (const :tag "Automatically, when key letter have been defined" auto)
  1574. (const :tag "Automatically, but don't show the selection window" expert)))
  1575. (defcustom org-provide-todo-statistics t
  1576. "Non-nil means update todo statistics after insert and toggle.
  1577. ALL-HEADLINES means update todo statistics by including headlines
  1578. with no TODO keyword as well, counting them as not done.
  1579. A list of TODO keywords means the same, but skip keywords that are
  1580. not in this list.
  1581. When set to a list of two lists, the first list contains keywords
  1582. to consider as TODO keywords, the second list contains keywords
  1583. to consider as DONE keywords.
  1584. When this is set, todo statistics is updated in the parent of the
  1585. current entry each time a todo state is changed."
  1586. :group 'org-todo
  1587. :type '(choice
  1588. (const :tag "Yes, only for TODO entries" t)
  1589. (const :tag "Yes, including all entries" all-headlines)
  1590. (repeat :tag "Yes, for TODOs in this list"
  1591. (string :tag "TODO keyword"))
  1592. (list :tag "Yes, for TODOs and DONEs in these lists"
  1593. (repeat (string :tag "TODO keyword"))
  1594. (repeat (string :tag "DONE keyword")))
  1595. (other :tag "No TODO statistics" nil)))
  1596. (defcustom org-hierarchical-todo-statistics t
  1597. "Non-nil means TODO statistics covers just direct children.
  1598. When nil, all entries in the subtree are considered.
  1599. This has only an effect if `org-provide-todo-statistics' is set.
  1600. To set this to nil for only a single subtree, use a COOKIE_DATA
  1601. property and include the word \"recursive\" into the value."
  1602. :group 'org-todo
  1603. :type 'boolean)
  1604. (defcustom org-after-todo-state-change-hook nil
  1605. "Hook which is run after the state of a TODO item was changed.
  1606. The new state (a string with a TODO keyword, or nil) is available in the
  1607. Lisp variable `org-state'."
  1608. :group 'org-todo
  1609. :type 'hook)
  1610. (defvar org-blocker-hook nil
  1611. "Hook for functions that are allowed to block a state change.
  1612. Functions in this hook should not modify the buffer.
  1613. Each function gets as its single argument a property list,
  1614. see `org-trigger-hook' for more information about this list.
  1615. If any of the functions in this hook returns nil, the state change
  1616. is blocked.")
  1617. (defvar org-trigger-hook nil
  1618. "Hook for functions that are triggered by a state change.
  1619. Each function gets as its single argument a property list with at
  1620. least the following elements:
  1621. (:type type-of-change :position pos-at-entry-start
  1622. :from old-state :to new-state)
  1623. Depending on the type, more properties may be present.
  1624. This mechanism is currently implemented for:
  1625. TODO state changes
  1626. ------------------
  1627. :type todo-state-change
  1628. :from previous state (keyword as a string), or nil, or a symbol
  1629. `todo' or `done', to indicate the general type of state.
  1630. :to new state, like in :from")
  1631. (defcustom org-enforce-todo-dependencies nil
  1632. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1633. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1634. be blocked if any prior sibling is not yet done.
  1635. Finally, if the parent is blocked because of ordered siblings of its own,
  1636. the child will also be blocked."
  1637. :set (lambda (var val)
  1638. (set var val)
  1639. (if val
  1640. (add-hook 'org-blocker-hook
  1641. 'org-block-todo-from-children-or-siblings-or-parent)
  1642. (remove-hook 'org-blocker-hook
  1643. 'org-block-todo-from-children-or-siblings-or-parent)))
  1644. :group 'org-todo
  1645. :type 'boolean)
  1646. (defcustom org-enforce-todo-checkbox-dependencies nil
  1647. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1648. When this is nil, checkboxes have no influence on switching TODO states.
  1649. When non-nil, you first need to check off all check boxes before the TODO
  1650. entry can be switched to DONE.
  1651. This variable needs to be set before org.el is loaded, and you need to
  1652. restart Emacs after a change to make the change effective. The only way
  1653. to change it while Emacs is running is through the customize interface."
  1654. :set (lambda (var val)
  1655. (set var val)
  1656. (if val
  1657. (add-hook 'org-blocker-hook
  1658. 'org-block-todo-from-checkboxes)
  1659. (remove-hook 'org-blocker-hook
  1660. 'org-block-todo-from-checkboxes)))
  1661. :group 'org-todo
  1662. :type 'boolean)
  1663. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1664. "Non-nil means inserting a TODO heading is treated as state change.
  1665. So when the command `\\[org-insert-todo-heading]' is used, state change
  1666. logging will apply if appropriate. When nil, the new TODO item will
  1667. be inserted directly, and no logging will take place."
  1668. :group 'org-todo
  1669. :type 'boolean)
  1670. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1671. "Non-nil means switching TODO states with S-cursor counts as state change.
  1672. This is the default behavior. However, setting this to nil allows a
  1673. convenient way to select a TODO state and bypass any logging associated
  1674. with that."
  1675. :group 'org-todo
  1676. :type 'boolean)
  1677. (defcustom org-todo-state-tags-triggers nil
  1678. "Tag changes that should be triggered by TODO state changes.
  1679. This is a list. Each entry is
  1680. (state-change (tag . flag) .......)
  1681. State-change can be a string with a state, and empty string to indicate the
  1682. state that has no TODO keyword, or it can be one of the symbols `todo'
  1683. or `done', meaning any not-done or done state, respectively."
  1684. :group 'org-todo
  1685. :group 'org-tags
  1686. :type '(repeat
  1687. (cons (choice :tag "When changing to"
  1688. (const :tag "Not-done state" todo)
  1689. (const :tag "Done state" done)
  1690. (string :tag "State"))
  1691. (repeat
  1692. (cons :tag "Tag action"
  1693. (string :tag "Tag")
  1694. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1695. (defcustom org-log-done nil
  1696. "Information to record when a task moves to the DONE state.
  1697. Possible values are:
  1698. nil Don't add anything, just change the keyword
  1699. time Add a time stamp to the task
  1700. note Prompt for a note and add it with template `org-log-note-headings'
  1701. This option can also be set with on a per-file-basis with
  1702. #+STARTUP: nologdone
  1703. #+STARTUP: logdone
  1704. #+STARTUP: lognotedone
  1705. You can have local logging settings for a subtree by setting the LOGGING
  1706. property to one or more of these keywords."
  1707. :group 'org-todo
  1708. :group 'org-progress
  1709. :type '(choice
  1710. (const :tag "No logging" nil)
  1711. (const :tag "Record CLOSED timestamp" time)
  1712. (const :tag "Record CLOSED timestamp with note." note)))
  1713. ;; Normalize old uses of org-log-done.
  1714. (cond
  1715. ((eq org-log-done t) (setq org-log-done 'time))
  1716. ((and (listp org-log-done) (memq 'done org-log-done))
  1717. (setq org-log-done 'note)))
  1718. (defcustom org-log-reschedule nil
  1719. "Information to record when the scheduling date of a task is modified.
  1720. Possible values are:
  1721. nil Don't add anything, just change the date
  1722. time Add a time stamp to the task
  1723. note Prompt for a note and add it with template `org-log-note-headings'
  1724. This option can also be set with on a per-file-basis with
  1725. #+STARTUP: nologreschedule
  1726. #+STARTUP: logreschedule
  1727. #+STARTUP: lognotereschedule
  1728. You can have local logging settings for a subtree by setting the LOGGING
  1729. property to one or more of these keywords.
  1730. This variable has an effect when calling `org-schedule' or
  1731. `org-agenda-schedule' only."
  1732. :group 'org-todo
  1733. :group 'org-progress
  1734. :type '(choice
  1735. (const :tag "No logging" nil)
  1736. (const :tag "Record timestamp" time)
  1737. (const :tag "Record timestamp with note" note)))
  1738. (defcustom org-log-redeadline nil
  1739. "Information to record when the deadline date of a task is modified.
  1740. Possible values are:
  1741. nil Don't add anything, just change the date
  1742. time Add a time stamp to the task
  1743. note Prompt for a note and add it with template `org-log-note-headings'
  1744. This option can also be set with on a per-file-basis with
  1745. #+STARTUP: nologredeadline
  1746. #+STARTUP: logredeadline
  1747. #+STARTUP: lognoteredeadline
  1748. You can have local logging settings for a subtree by setting the LOGGING
  1749. property to one or more of these keywords.
  1750. This variable has an effect when calling `org-deadline' or
  1751. `org-agenda-deadline' only."
  1752. :group 'org-todo
  1753. :group 'org-progress
  1754. :type '(choice
  1755. (const :tag "No logging" nil)
  1756. (const :tag "Record timestamp" time)
  1757. (const :tag "Record timestamp with note." note)))
  1758. (defcustom org-log-note-clock-out nil
  1759. "Non-nil means record a note when clocking out of an item.
  1760. This can also be configured on a per-file basis by adding one of
  1761. the following lines anywhere in the buffer:
  1762. #+STARTUP: lognoteclock-out
  1763. #+STARTUP: nolognoteclock-out"
  1764. :group 'org-todo
  1765. :group 'org-progress
  1766. :type 'boolean)
  1767. (defcustom org-log-done-with-time t
  1768. "Non-nil means the CLOSED time stamp will contain date and time.
  1769. When nil, only the date will be recorded."
  1770. :group 'org-progress
  1771. :type 'boolean)
  1772. (defcustom org-log-note-headings
  1773. '((done . "CLOSING NOTE %t")
  1774. (state . "State %-12s from %-12S %t")
  1775. (note . "Note taken on %t")
  1776. (reschedule . "Rescheduled from %S on %t")
  1777. (delschedule . "Not scheduled, was %S on %t")
  1778. (redeadline . "New deadline from %S on %t")
  1779. (deldeadline . "Removed deadline, was %S on %t")
  1780. (refile . "Refiled on %t")
  1781. (clock-out . ""))
  1782. "Headings for notes added to entries.
  1783. The value is an alist, with the car being a symbol indicating the
  1784. note context, and the cdr is the heading to be used. The heading
  1785. may also be the empty string. The following placeholders can be
  1786. used:
  1787. %t a time stamp.
  1788. %T an active time stamp instead the default inactive one
  1789. %d a short-format time stamp.
  1790. %D an active short-format time stamp.
  1791. %s the new TODO state or time stamp (inactive), in double quotes.
  1792. %S the old TODO state or time stamp (inactive), in double quotes.
  1793. %u the user name.
  1794. %U full user name.
  1795. In fact, it is not a good idea to change the `state' entry,
  1796. because Agenda Log mode depends on the format of these entries."
  1797. :group 'org-todo
  1798. :group 'org-progress
  1799. :type '(list :greedy t
  1800. (cons (const :tag "Heading when closing an item" done) string)
  1801. (cons (const :tag
  1802. "Heading when changing todo state (todo sequence only)"
  1803. state) string)
  1804. (cons (const :tag "Heading when just taking a note" note) string)
  1805. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1806. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1807. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1808. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1809. (cons (const :tag "Heading when refiling" refile) string)
  1810. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1811. (unless (assq 'note org-log-note-headings)
  1812. (push '(note . "%t") org-log-note-headings))
  1813. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1814. (defcustom org-log-into-drawer nil
  1815. "Non-nil means insert state change notes and time stamps into a drawer.
  1816. When nil, state changes notes will be inserted after the headline and
  1817. any scheduling and clock lines, but not inside a drawer.
  1818. The value of this variable should be the name of the drawer to use.
  1819. LOGBOOK is proposed as the default drawer for this purpose, you can
  1820. also set this to a string to define the drawer of your choice.
  1821. A value of t is also allowed, representing \"LOGBOOK\".
  1822. A value of t or nil can also be set with on a per-file-basis with
  1823. #+STARTUP: logdrawer
  1824. #+STARTUP: nologdrawer
  1825. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1826. will be ignored.
  1827. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1828. a subtree.
  1829. Do not check directly this variable in a Lisp program. Call
  1830. function `org-log-into-drawer' instead."
  1831. :group 'org-todo
  1832. :group 'org-progress
  1833. :type '(choice
  1834. (const :tag "Not into a drawer" nil)
  1835. (const :tag "LOGBOOK" t)
  1836. (string :tag "Other")))
  1837. (defun org-log-into-drawer ()
  1838. "Name of the log drawer, as a string, or nil.
  1839. This is the value of `org-log-into-drawer'. However, if the
  1840. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1841. be used instead of the default value."
  1842. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1843. (cond ((equal p "nil") nil)
  1844. ((equal p "t") "LOGBOOK")
  1845. ((stringp p) p)
  1846. (p "LOGBOOK")
  1847. ((stringp org-log-into-drawer) org-log-into-drawer)
  1848. (org-log-into-drawer "LOGBOOK"))))
  1849. (defcustom org-log-state-notes-insert-after-drawers nil
  1850. "Non-nil means insert state change notes after any drawers in entry.
  1851. Only the drawers that *immediately* follow the headline and the
  1852. deadline/scheduled line are skipped.
  1853. When nil, insert notes right after the heading and perhaps the line
  1854. with deadline/scheduling if present.
  1855. This variable will have no effect if `org-log-into-drawer' is
  1856. set."
  1857. :group 'org-todo
  1858. :group 'org-progress
  1859. :type 'boolean)
  1860. (defcustom org-log-states-order-reversed t
  1861. "Non-nil means the latest state note will be directly after heading.
  1862. When nil, the state change notes will be ordered according to time.
  1863. This option can also be set with on a per-file-basis with
  1864. #+STARTUP: logstatesreversed
  1865. #+STARTUP: nologstatesreversed"
  1866. :group 'org-todo
  1867. :group 'org-progress
  1868. :type 'boolean)
  1869. (defcustom org-todo-repeat-to-state nil
  1870. "The TODO state to which a repeater should return the repeating task.
  1871. By default this is the first task of a TODO sequence or the
  1872. previous state of a TYPE_TODO set. But you can specify to use
  1873. the previous state in a TODO sequence or a string.
  1874. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1875. entry, which has precedence over this option."
  1876. :group 'org-todo
  1877. :version "24.1"
  1878. :type '(choice (const :tag "Use the previous TODO state" t)
  1879. (const :tag "Use the head of the TODO sequence" nil)
  1880. (string :tag "Use a specific TODO state")))
  1881. (defcustom org-log-repeat 'time
  1882. "Non-nil means record moving through the DONE state when triggering repeat.
  1883. An auto-repeating task is immediately switched back to TODO when
  1884. marked DONE. If you are not logging state changes (by adding \"@\"
  1885. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1886. record a closing note, there will be no record of the task moving
  1887. through DONE. This variable forces taking a note anyway.
  1888. nil Don't force a record
  1889. time Record a time stamp
  1890. note Prompt for a note and add it with template `org-log-note-headings'
  1891. This option can also be set with on a per-file-basis with
  1892. #+STARTUP: nologrepeat
  1893. #+STARTUP: logrepeat
  1894. #+STARTUP: lognoterepeat
  1895. You can have local logging settings for a subtree by setting the LOGGING
  1896. property to one or more of these keywords."
  1897. :group 'org-todo
  1898. :group 'org-progress
  1899. :type '(choice
  1900. (const :tag "Don't force a record" nil)
  1901. (const :tag "Force recording the DONE state" time)
  1902. (const :tag "Force recording a note with the DONE state" note)))
  1903. (defcustom org-todo-repeat-hook nil
  1904. "Hook that is run after a task has been repeated."
  1905. :package-version '(Org . "9.2")
  1906. :group 'org-todo
  1907. :type 'hook)
  1908. (defgroup org-priorities nil
  1909. "Priorities in Org mode."
  1910. :tag "Org Priorities"
  1911. :group 'org-todo)
  1912. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1913. (defcustom org-priority-enable-commands t
  1914. "Non-nil means priority commands are active.
  1915. When nil, these commands will be disabled, so that you never accidentally
  1916. set a priority."
  1917. :group 'org-priorities
  1918. :type 'boolean)
  1919. (defvaralias 'org-highest-priority 'org-priority-highest)
  1920. (defcustom org-priority-highest ?A
  1921. "The highest priority of TODO items.
  1922. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1923. The default is the character ?A, which is 65 as a numeric value.
  1924. If you set `org-priority-highest' to a numeric value inferior to
  1925. 65, Org assumes you want to use digits for the priority cookie.
  1926. If you set it to >=65, Org assumes you want to use alphabetical
  1927. characters.
  1928. In both cases, the value of `org-priority-highest' must be
  1929. smaller than `org-priority-lowest': for example, if \"A\" is the
  1930. highest priority, it is smaller than the lowest \"C\" priority:
  1931. 65 < 67."
  1932. :group 'org-priorities
  1933. :type '(choice
  1934. (character :tag "Character")
  1935. (integer :tag "Integer (< 65)")))
  1936. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1937. (defcustom org-priority-lowest ?C
  1938. "The lowest priority of TODO items.
  1939. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1940. The default is the character ?C, which is 67 as a numeric value.
  1941. If you set `org-priority-lowest' to a numeric value inferior to
  1942. 65, Org assumes you want to use digits for the priority cookie.
  1943. If you set it to >=65, Org assumes you want to use alphabetical
  1944. characters.
  1945. In both cases, the value of `org-priority-lowest' must be greater
  1946. than `org-priority-highest': for example, if \"C\" is the lowest
  1947. priority, it is greater than the highest \"A\" priority: 67 >
  1948. 65."
  1949. :group 'org-priorities
  1950. :type '(choice
  1951. (character :tag "Character")
  1952. (integer :tag "Integer (< 65)")))
  1953. (defvaralias 'org-default-priority 'org-priority-default)
  1954. (defcustom org-priority-default ?B
  1955. "The default priority of TODO items.
  1956. This is the priority an item gets if no explicit priority is given.
  1957. When starting to cycle on an empty priority the first step in the cycle
  1958. depends on `org-priority-start-cycle-with-default'. The resulting first
  1959. step priority must not exceed the range from `org-priority-highest' to
  1960. `org-priority-lowest' which means that `org-priority-default' has to be
  1961. in this range exclusive or inclusive to the range boundaries. Else the
  1962. first step refuses to set the default and the second will fall back on
  1963. \(depending on the command used) the highest or lowest priority."
  1964. :group 'org-priorities
  1965. :type '(choice
  1966. (character :tag "Character")
  1967. (integer :tag "Integer (< 65)")))
  1968. (defcustom org-priority-start-cycle-with-default t
  1969. "Non-nil means start with default priority when starting to cycle.
  1970. When this is nil, the first step in the cycle will be (depending on the
  1971. command used) one higher or lower than the default priority.
  1972. See also `org-priority-default'."
  1973. :group 'org-priorities
  1974. :type 'boolean)
  1975. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  1976. (defcustom org-priority-get-priority-function nil
  1977. "Function to extract the priority from a string.
  1978. The string is normally the headline. If this is nil, Org
  1979. computes the priority from the priority cookie like [#A] in the
  1980. headline. It returns an integer, increasing by 1000 for each
  1981. priority level.
  1982. The user can set a different function here, which should take a
  1983. string as an argument and return the numeric priority."
  1984. :group 'org-priorities
  1985. :version "24.1"
  1986. :type '(choice
  1987. (const nil)
  1988. (function)))
  1989. (defgroup org-time nil
  1990. "Options concerning time stamps and deadlines in Org mode."
  1991. :tag "Org Time"
  1992. :group 'org)
  1993. (defcustom org-time-stamp-rounding-minutes '(0 5)
  1994. "Number of minutes to round time stamps to.
  1995. \\<org-mode-map>\
  1996. These are two values, the first applies when first creating a time stamp.
  1997. The second applies when changing it with the commands `S-up' and `S-down'.
  1998. When changing the time stamp, this means that it will change in steps
  1999. of N minutes, as given by the second value.
  2000. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2001. numbers should be factors of 60, so for example 5, 10, 15.
  2002. When this is larger than 1, you can still force an exact time stamp by using
  2003. a double prefix argument to a time stamp command like \
  2004. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2005. and by using a prefix arg to `S-up/down' to specify the exact number
  2006. of minutes to shift."
  2007. :group 'org-time
  2008. :get (lambda (var) ; Make sure both elements are there
  2009. (if (integerp (default-value var))
  2010. (list (default-value var) 5)
  2011. (default-value var)))
  2012. :type '(list
  2013. (integer :tag "when inserting times")
  2014. (integer :tag "when modifying times")))
  2015. ;; Normalize old customizations of this variable.
  2016. (when (integerp org-time-stamp-rounding-minutes)
  2017. (setq org-time-stamp-rounding-minutes
  2018. (list org-time-stamp-rounding-minutes
  2019. org-time-stamp-rounding-minutes)))
  2020. (defcustom org-display-custom-times nil
  2021. "Non-nil means overlay custom formats over all time stamps.
  2022. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2023. To turn this on on a per-file basis, insert anywhere in the file:
  2024. #+STARTUP: customtime"
  2025. :group 'org-time
  2026. :set 'set-default
  2027. :type 'sexp)
  2028. (make-variable-buffer-local 'org-display-custom-times)
  2029. (defcustom org-time-stamp-custom-formats
  2030. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2031. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2032. These are overlaid over the default ISO format if the variable
  2033. `org-display-custom-times' is set. Time like %H:%M should be at the
  2034. end of the second format. The custom formats are also honored by export
  2035. commands, if custom time display is turned on at the time of export."
  2036. :group 'org-time
  2037. :type 'sexp)
  2038. (defun org-time-stamp-format (&optional long inactive)
  2039. "Get the right format for a time string."
  2040. (let ((f (if long (cdr org-time-stamp-formats)
  2041. (car org-time-stamp-formats))))
  2042. (if inactive
  2043. (concat "[" (substring f 1 -1) "]")
  2044. f)))
  2045. (defcustom org-deadline-warning-days 14
  2046. "Number of days before expiration during which a deadline becomes active.
  2047. This variable governs the display in sparse trees and in the agenda.
  2048. When 0 or negative, it means use this number (the absolute value of it)
  2049. even if a deadline has a different individual lead time specified.
  2050. Custom commands can set this variable in the options section."
  2051. :group 'org-time
  2052. :group 'org-agenda-daily/weekly
  2053. :type 'integer)
  2054. (defcustom org-scheduled-delay-days 0
  2055. "Number of days before a scheduled item becomes active.
  2056. This variable governs the display in sparse trees and in the agenda.
  2057. The default value (i.e. 0) means: don't delay scheduled item.
  2058. When negative, it means use this number (the absolute value of it)
  2059. even if a scheduled item has a different individual delay time
  2060. specified.
  2061. Custom commands can set this variable in the options section."
  2062. :group 'org-time
  2063. :group 'org-agenda-daily/weekly
  2064. :version "24.4"
  2065. :package-version '(Org . "8.0")
  2066. :type 'integer)
  2067. (defcustom org-read-date-prefer-future t
  2068. "Non-nil means assume future for incomplete date input from user.
  2069. This affects the following situations:
  2070. 1. The user gives a month but not a year.
  2071. For example, if it is April and you enter \"feb 2\", this will be read
  2072. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2073. 2. The user gives a day, but no month.
  2074. For example, if today is the 15th, and you enter \"3\", Org will read
  2075. this as the third of *next* month. However, if you enter \"17\",
  2076. it will be considered as *this* month.
  2077. If you set this variable to the symbol `time', then also the following
  2078. will work:
  2079. 3. If the user gives a time.
  2080. If the time is before now, it will be interpreted as tomorrow.
  2081. Currently none of this works for ISO week specifications.
  2082. When this option is nil, the current day, month and year will always be
  2083. used as defaults.
  2084. See also `org-agenda-jump-prefer-future'."
  2085. :group 'org-time
  2086. :type '(choice
  2087. (const :tag "Never" nil)
  2088. (const :tag "Check month and day" t)
  2089. (const :tag "Check month, day, and time" time)))
  2090. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2091. "Should the agenda jump command prefer the future for incomplete dates?
  2092. The default is to do the same as configured in `org-read-date-prefer-future'.
  2093. But you can also set a deviating value here.
  2094. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2095. :group 'org-agenda
  2096. :group 'org-time
  2097. :version "24.1"
  2098. :type '(choice
  2099. (const :tag "Use org-read-date-prefer-future"
  2100. org-read-date-prefer-future)
  2101. (const :tag "Never" nil)
  2102. (const :tag "Always" t)))
  2103. (defcustom org-read-date-force-compatible-dates t
  2104. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2105. Depending on the system Emacs is running on, certain dates cannot
  2106. be represented with the type used internally to represent time.
  2107. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2108. correctly. Some systems allow for earlier dates, some for later,
  2109. some for both. One way to find out is to insert any date into an
  2110. Org buffer, putting the cursor on the year and hitting S-up and
  2111. S-down to test the range.
  2112. When this variable is set to t, the date/time prompt will not let
  2113. you specify dates outside the 1970-2037 range, so it is certain that
  2114. these dates will work in whatever version of Emacs you are
  2115. running, and also that you can move a file from one Emacs implementation
  2116. to another. Whenever Org is forcing the year for you, it will display
  2117. a message and beep.
  2118. When this variable is nil, Org will check if the date is
  2119. representable in the specific Emacs implementation you are using.
  2120. If not, it will force a year, usually the current year, and beep
  2121. to remind you. Currently this setting is not recommended because
  2122. the likelihood that you will open your Org files in an Emacs that
  2123. has limited date range is not negligible.
  2124. A workaround for this problem is to use diary sexp dates for time
  2125. stamps outside of this range."
  2126. :group 'org-time
  2127. :version "24.1"
  2128. :type 'boolean)
  2129. (defcustom org-read-date-display-live t
  2130. "Non-nil means display current interpretation of date prompt live.
  2131. This display will be in an overlay, in the minibuffer. Note that
  2132. live display is only active when `org-read-date-popup-calendar'
  2133. is non-nil."
  2134. :group 'org-time
  2135. :type 'boolean)
  2136. (defvaralias 'org-popup-calendar-for-date-prompt
  2137. 'org-read-date-popup-calendar)
  2138. (defcustom org-read-date-popup-calendar t
  2139. "Non-nil means pop up a calendar when prompting for a date.
  2140. In the calendar, the date can be selected with mouse-1. However, the
  2141. minibuffer will also be active, and you can simply enter the date as well.
  2142. When nil, only the minibuffer will be available."
  2143. :group 'org-time
  2144. :type 'boolean)
  2145. (defcustom org-extend-today-until 0
  2146. "The hour when your day really ends. Must be an integer.
  2147. This has influence for the following applications:
  2148. - When switching the agenda to \"today\". If it is still earlier than
  2149. the time given here, the day recognized as TODAY is actually yesterday.
  2150. - When a date is read from the user and it is still before the time given
  2151. here, the current date and time will be assumed to be yesterday, 23:59.
  2152. Also, timestamps inserted in capture templates follow this rule.
  2153. IMPORTANT: This is a feature whose implementation is and likely will
  2154. remain incomplete. Really, it is only here because past midnight seems to
  2155. be the favorite working time of John Wiegley :-)"
  2156. :group 'org-time
  2157. :type 'integer)
  2158. (defcustom org-use-effective-time nil
  2159. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2160. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2161. \"effective time\" of any timestamps between midnight and 8am will be
  2162. 23:59 of the previous day."
  2163. :group 'org-time
  2164. :version "24.1"
  2165. :type 'boolean)
  2166. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2167. "When non-nil, use the last clock out time for `org-todo'.
  2168. Note that this option has precedence over the combined use of
  2169. `org-use-effective-time' and `org-extend-today-until'."
  2170. :group 'org-time
  2171. :version "24.4"
  2172. :package-version '(Org . "8.0")
  2173. :type 'boolean)
  2174. (defcustom org-edit-timestamp-down-means-later nil
  2175. "Non-nil means S-down will increase the time in a time stamp.
  2176. When nil, S-up will increase."
  2177. :group 'org-time
  2178. :type 'boolean)
  2179. (defcustom org-calendar-follow-timestamp-change t
  2180. "Non-nil means make the calendar window follow timestamp changes.
  2181. When a timestamp is modified and the calendar window is visible, it will be
  2182. moved to the new date."
  2183. :group 'org-time
  2184. :type 'boolean)
  2185. (defgroup org-tags nil
  2186. "Options concerning tags in Org mode."
  2187. :tag "Org Tags"
  2188. :group 'org)
  2189. (defcustom org-tag-alist nil
  2190. "Default tags available in Org files.
  2191. The value of this variable is an alist. Associations either:
  2192. (TAG)
  2193. (TAG . SELECT)
  2194. (SPECIAL)
  2195. where TAG is a tag as a string, SELECT is character, used to
  2196. select that tag through the fast tag selection interface, and
  2197. SPECIAL is one of the following keywords: `:startgroup',
  2198. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2199. `:newline'. These keywords are used to define a hierarchy of
  2200. tags. See manual for details.
  2201. When this variable is nil, Org mode bases tag input on what is
  2202. already in the buffer. The value can be overridden locally by
  2203. using a TAGS keyword, e.g.,
  2204. #+TAGS: tag1 tag2
  2205. See also `org-tag-persistent-alist' to sidestep this behavior."
  2206. :group 'org-tags
  2207. :type '(repeat
  2208. (choice
  2209. (cons :tag "Tag with key"
  2210. (string :tag "Tag name")
  2211. (character :tag "Access char"))
  2212. (list :tag "Tag" (string :tag "Tag name"))
  2213. (const :tag "Start radio group" (:startgroup))
  2214. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2215. (const :tag "Group tags delimiter" (:grouptags))
  2216. (const :tag "End radio group" (:endgroup))
  2217. (const :tag "End tag group, non distinct" (:endgrouptag))
  2218. (const :tag "New line" (:newline)))))
  2219. (defcustom org-tag-persistent-alist nil
  2220. "Tags always available in Org files.
  2221. The value of this variable is an alist. Associations either:
  2222. (TAG)
  2223. (TAG . SELECT)
  2224. (SPECIAL)
  2225. where TAG is a tag as a string, SELECT is a character, used to
  2226. select that tag through the fast tag selection interface, and
  2227. SPECIAL is one of the following keywords: `:startgroup',
  2228. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2229. `:newline'. These keywords are used to define a hierarchy of
  2230. tags. See manual for details.
  2231. Unlike to `org-tag-alist', tags defined in this variable do not
  2232. depend on a local TAGS keyword. Instead, to disable these tags
  2233. on a per-file basis, insert anywhere in the file:
  2234. #+STARTUP: noptag"
  2235. :group 'org-tags
  2236. :type '(repeat
  2237. (choice
  2238. (cons :tag "Tag with key"
  2239. (string :tag "Tag name")
  2240. (character :tag "Access char"))
  2241. (list :tag "Tag" (string :tag "Tag name"))
  2242. (const :tag "Start radio group" (:startgroup))
  2243. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2244. (const :tag "Group tags delimiter" (:grouptags))
  2245. (const :tag "End radio group" (:endgroup))
  2246. (const :tag "End tag group, non distinct" (:endgrouptag))
  2247. (const :tag "New line" (:newline)))))
  2248. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2249. "If non-nil, always offer completion for all tags of all agenda files.
  2250. Setting this variable locally allows for dynamic generation of tag
  2251. completions in capture buffers.
  2252. (add-hook \\='org-capture-mode-hook
  2253. (lambda ()
  2254. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2255. :group 'org-tags
  2256. :version "24.1"
  2257. :type 'boolean)
  2258. (defvar org-file-tags nil
  2259. "List of tags that can be inherited by all entries in the file.
  2260. The tags will be inherited if the variable `org-use-tag-inheritance'
  2261. says they should be.
  2262. This variable is populated from #+FILETAGS lines.")
  2263. (defcustom org-use-fast-tag-selection 'auto
  2264. "Non-nil means use fast tag selection scheme.
  2265. This is a special interface to select and deselect tags with single keys.
  2266. When nil, fast selection is never used.
  2267. When the symbol `auto', fast selection is used if and only if selection
  2268. characters for tags have been configured, either through the variable
  2269. `org-tag-alist' or through a #+TAGS line in the buffer.
  2270. When t, fast selection is always used and selection keys are assigned
  2271. automatically if necessary."
  2272. :group 'org-tags
  2273. :type '(choice
  2274. (const :tag "Always" t)
  2275. (const :tag "Never" nil)
  2276. (const :tag "When selection characters are configured" auto)))
  2277. (defcustom org-fast-tag-selection-single-key nil
  2278. "Non-nil means fast tag selection exits after first change.
  2279. When nil, you have to press RET to exit it.
  2280. During fast tag selection, you can toggle this flag with `C-c'.
  2281. This variable can also have the value `expert'. In this case, the window
  2282. displaying the tags menu is not even shown, until you press `C-c' again."
  2283. :group 'org-tags
  2284. :type '(choice
  2285. (const :tag "No" nil)
  2286. (const :tag "Yes" t)
  2287. (const :tag "Expert" expert)))
  2288. (defvar org-fast-tag-selection-include-todo nil
  2289. "Non-nil means fast tags selection interface will also offer TODO states.
  2290. This is an undocumented feature, you should not rely on it.")
  2291. (defcustom org-tags-column -77
  2292. "The column to which tags should be indented in a headline.
  2293. If this number is positive, it specifies the column. If it is negative,
  2294. it means that the tags should be flushright to that column. For example,
  2295. -80 works well for a normal 80 character screen.
  2296. When 0, place tags directly after headline text, with only one space in
  2297. between."
  2298. :group 'org-tags
  2299. :type 'integer)
  2300. (defcustom org-auto-align-tags t
  2301. "Non-nil keeps tags aligned when modifying headlines.
  2302. Some operations (i.e. demoting) change the length of a headline and
  2303. therefore shift the tags around. With this option turned on, after
  2304. each such operation the tags are again aligned to `org-tags-column'."
  2305. :group 'org-tags
  2306. :type 'boolean)
  2307. (defcustom org-use-tag-inheritance t
  2308. "Non-nil means tags in levels apply also for sublevels.
  2309. When nil, only the tags directly given in a specific line apply there.
  2310. This may also be a list of tags that should be inherited, or a regexp that
  2311. matches tags that should be inherited. Additional control is possible
  2312. with the variable `org-tags-exclude-from-inheritance' which gives an
  2313. explicit list of tags to be excluded from inheritance, even if the value of
  2314. `org-use-tag-inheritance' would select it for inheritance.
  2315. If this option is t, a match early-on in a tree can lead to a large
  2316. number of matches in the subtree when constructing the agenda or creating
  2317. a sparse tree. If you only want to see the first match in a tree during
  2318. a search, check out the variable `org-tags-match-list-sublevels'."
  2319. :group 'org-tags
  2320. :type '(choice
  2321. (const :tag "Not" nil)
  2322. (const :tag "Always" t)
  2323. (repeat :tag "Specific tags" (string :tag "Tag"))
  2324. (regexp :tag "Tags matched by regexp")))
  2325. (defcustom org-tags-exclude-from-inheritance nil
  2326. "List of tags that should never be inherited.
  2327. This is a way to exclude a few tags from inheritance. For way to do
  2328. the opposite, to actively allow inheritance for selected tags,
  2329. see the variable `org-use-tag-inheritance'."
  2330. :group 'org-tags
  2331. :type '(repeat (string :tag "Tag")))
  2332. (defun org-tag-inherit-p (tag)
  2333. "Check if TAG is one that should be inherited."
  2334. (cond
  2335. ((member tag org-tags-exclude-from-inheritance) nil)
  2336. ((eq org-use-tag-inheritance t) t)
  2337. ((not org-use-tag-inheritance) nil)
  2338. ((stringp org-use-tag-inheritance)
  2339. (string-match org-use-tag-inheritance tag))
  2340. ((listp org-use-tag-inheritance)
  2341. (member tag org-use-tag-inheritance))
  2342. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2343. (defcustom org-tags-match-list-sublevels t
  2344. "Non-nil means list also sublevels of headlines matching a search.
  2345. This variable applies to tags/property searches, and also to stuck
  2346. projects because this search is based on a tags match as well.
  2347. When set to the symbol `indented', sublevels are indented with
  2348. leading dots.
  2349. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2350. the sublevels of a headline matching a tag search often also match
  2351. the same search. Listing all of them can create very long lists.
  2352. Setting this variable to nil causes subtrees of a match to be skipped.
  2353. This variable is semi-obsolete and probably should always be true. It
  2354. is better to limit inheritance to certain tags using the variables
  2355. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2356. :group 'org-tags
  2357. :type '(choice
  2358. (const :tag "No, don't list them" nil)
  2359. (const :tag "Yes, do list them" t)
  2360. (const :tag "List them, indented with leading dots" indented)))
  2361. (defcustom org-tags-sort-function nil
  2362. "When set, tags are sorted using this function as a comparator."
  2363. :group 'org-tags
  2364. :type '(choice
  2365. (const :tag "No sorting" nil)
  2366. (const :tag "Alphabetical" string-collate-lessp)
  2367. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2368. (function :tag "Custom function" nil)))
  2369. (defvar org-tags-history nil
  2370. "History of minibuffer reads for tags.")
  2371. (defvar org-last-tags-completion-table nil
  2372. "The last used completion table for tags.")
  2373. (defvar org-after-tags-change-hook nil
  2374. "Hook that is run after the tags in a line have changed.")
  2375. (defgroup org-properties nil
  2376. "Options concerning properties in Org mode."
  2377. :tag "Org Properties"
  2378. :group 'org)
  2379. (defcustom org-property-format "%-10s %s"
  2380. "How property key/value pairs should be formatted by `indent-line'.
  2381. When `indent-line' hits a property definition, it will format the line
  2382. according to this format, mainly to make sure that the values are
  2383. lined-up with respect to each other."
  2384. :group 'org-properties
  2385. :type 'string)
  2386. (defcustom org-properties-postprocess-alist nil
  2387. "Alist of properties and functions to adjust inserted values.
  2388. Elements of this alist must be of the form
  2389. ([string] [function])
  2390. where [string] must be a property name and [function] must be a
  2391. lambda expression: this lambda expression must take one argument,
  2392. the value to adjust, and return the new value as a string.
  2393. For example, this element will allow the property \"Remaining\"
  2394. to be updated wrt the relation between the \"Effort\" property
  2395. and the clock summary:
  2396. ((\"Remaining\" (lambda(value)
  2397. (let ((clocksum (org-clock-sum-current-item))
  2398. (effort (org-duration-to-minutes
  2399. (org-entry-get (point) \"Effort\"))))
  2400. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2401. :group 'org-properties
  2402. :version "24.1"
  2403. :type '(alist :key-type (string :tag "Property")
  2404. :value-type (function :tag "Function")))
  2405. (defcustom org-use-property-inheritance nil
  2406. "Non-nil means properties apply also for sublevels.
  2407. This setting is chiefly used during property searches. Turning it on can
  2408. cause significant overhead when doing a search, which is why it is not
  2409. on by default.
  2410. When nil, only the properties directly given in the current entry count.
  2411. When t, every property is inherited. The value may also be a list of
  2412. properties that should have inheritance, or a regular expression matching
  2413. properties that should be inherited.
  2414. However, note that some special properties use inheritance under special
  2415. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2416. and the properties ending in \"_ALL\" when they are used as descriptor
  2417. for valid values of a property.
  2418. Note for programmers:
  2419. When querying an entry with `org-entry-get', you can control if inheritance
  2420. should be used. By default, `org-entry-get' looks only at the local
  2421. properties. You can request inheritance by setting the inherit argument
  2422. to t (to force inheritance) or to `selective' (to respect the setting
  2423. in this variable)."
  2424. :group 'org-properties
  2425. :type '(choice
  2426. (const :tag "Not" nil)
  2427. (const :tag "Always" t)
  2428. (repeat :tag "Specific properties" (string :tag "Property"))
  2429. (regexp :tag "Properties matched by regexp")))
  2430. (defun org-property-inherit-p (property)
  2431. "Return a non-nil value if PROPERTY should be inherited."
  2432. (cond
  2433. ((eq org-use-property-inheritance t) t)
  2434. ((not org-use-property-inheritance) nil)
  2435. ((stringp org-use-property-inheritance)
  2436. (string-match org-use-property-inheritance property))
  2437. ((listp org-use-property-inheritance)
  2438. (member-ignore-case property org-use-property-inheritance))
  2439. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2440. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2441. "The default column format, if no other format has been defined.
  2442. This variable can be set on the per-file basis by inserting a line
  2443. #+COLUMNS: %25ITEM ....."
  2444. :group 'org-properties
  2445. :type 'string)
  2446. (defcustom org-columns-default-format-for-agenda nil
  2447. "The default column format in an agenda buffer.
  2448. This will be used for column view in the agenda unless a format has
  2449. been set by adding `org-overriding-columns-format' to the local
  2450. settings list of a custom agenda view. When nil, the columns format
  2451. for the first item in the agenda list will be used, or as a fall-back,
  2452. `org-columns-default-format'."
  2453. :group 'org-properties
  2454. :type '(choice
  2455. (const :tag "No default" nil)
  2456. (string :tag "Format string")))
  2457. (defcustom org-columns-ellipses ".."
  2458. "The ellipses to be used when a field in column view is truncated.
  2459. When this is the empty string, as many characters as possible are shown,
  2460. but then there will be no visual indication that the field has been truncated.
  2461. When this is a string of length N, the last N characters of a truncated
  2462. field are replaced by this string. If the column is narrower than the
  2463. ellipses string, only part of the ellipses string will be shown."
  2464. :group 'org-properties
  2465. :type 'string)
  2466. (defconst org-global-properties-fixed
  2467. '(("VISIBILITY_ALL" . "folded children content all")
  2468. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2469. "List of property/value pairs that can be inherited by any entry.
  2470. These are fixed values, for the preset properties. The user variable
  2471. that can be used to add to this list is `org-global-properties'.
  2472. The entries in this list are cons cells where the car is a property
  2473. name and cdr is a string with the value. If the value represents
  2474. multiple items like an \"_ALL\" property, separate the items by
  2475. spaces.")
  2476. (defcustom org-global-properties nil
  2477. "List of property/value pairs that can be inherited by any entry.
  2478. This list will be combined with the constant `org-global-properties-fixed'.
  2479. The entries in this list are cons cells where the car is a property
  2480. name and cdr is a string with the value.
  2481. Buffer local properties are added either by a document property drawer
  2482. :PROPERTIES:
  2483. :NAME: VALUE
  2484. :END:
  2485. or by adding lines like
  2486. #+PROPERTY: NAME VALUE"
  2487. :group 'org-properties
  2488. :type '(repeat
  2489. (cons (string :tag "Property")
  2490. (string :tag "Value"))))
  2491. (defvar-local org-keyword-properties nil
  2492. "List of property/value pairs inherited by any entry.
  2493. Valid for the current buffer. This variable is populated from
  2494. PROPERTY keywords.
  2495. Note that properties are defined also in property drawers.
  2496. Properties defined there take precedence over properties defined
  2497. as keywords.")
  2498. (defgroup org-agenda nil
  2499. "Options concerning agenda views in Org mode."
  2500. :tag "Org Agenda"
  2501. :group 'org)
  2502. (defvar-local org-category nil
  2503. "Variable used by Org files to set a category for agenda display.
  2504. There are multiple ways to set the category. One way is to set
  2505. it in the document property drawer. For example:
  2506. :PROPERTIES:
  2507. :CATEGORY: ELisp
  2508. :END:
  2509. Other ways to define it is as an Emacs file variable, for example
  2510. # -*- mode: org; org-category: \"ELisp\"
  2511. or for the file to contain a special line:
  2512. #+CATEGORY: ELisp
  2513. If the file does not specify a category, then file's base name
  2514. is used instead.")
  2515. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2516. (defcustom org-agenda-files nil
  2517. "The files to be used for agenda display.
  2518. If an entry is a directory, all files in that directory that are matched
  2519. by `org-agenda-file-regexp' will be part of the file list.
  2520. If the value of the variable is not a list but a single file name, then
  2521. the list of agenda files is actually stored and maintained in that file,
  2522. one agenda file per line. In this file paths can be given relative to
  2523. `org-directory'. Tilde expansion and environment variable substitution
  2524. are also made.
  2525. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2526. and removed with `\\[org-remove-file]'."
  2527. :group 'org-agenda
  2528. :type '(choice
  2529. (repeat :tag "List of files and directories" file)
  2530. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2531. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2532. "Regular expression to match files for `org-agenda-files'.
  2533. If any element in the list in that variable contains a directory instead
  2534. of a normal file, all files in that directory that are matched by this
  2535. regular expression will be included."
  2536. :group 'org-agenda
  2537. :type 'regexp)
  2538. (defvaralias 'org-agenda-multi-occur-extra-files
  2539. 'org-agenda-text-search-extra-files)
  2540. (defcustom org-agenda-text-search-extra-files nil
  2541. "List of extra files to be searched by text search commands.
  2542. These files will be searched in addition to the agenda files by the
  2543. commands `org-search-view' (`\\[org-agenda] s') \
  2544. and `org-occur-in-agenda-files'.
  2545. Note that these files will only be searched for text search commands,
  2546. not for the other agenda views like todo lists, tag searches or the weekly
  2547. agenda. This variable is intended to list notes and possibly archive files
  2548. that should also be searched by these two commands.
  2549. In fact, if the first element in the list is the symbol `agenda-archives',
  2550. then all archive files of all agenda files will be added to the search
  2551. scope."
  2552. :group 'org-agenda
  2553. :type '(set :greedy t
  2554. (const :tag "Agenda Archives" agenda-archives)
  2555. (repeat :inline t (file))))
  2556. (defcustom org-agenda-skip-unavailable-files nil
  2557. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2558. A nil value means to remove them, after a query, from the list."
  2559. :group 'org-agenda
  2560. :type 'boolean)
  2561. (defgroup org-latex nil
  2562. "Options for embedding LaTeX code into Org mode."
  2563. :tag "Org LaTeX"
  2564. :group 'org)
  2565. (defcustom org-format-latex-options
  2566. '(:foreground default :background default :scale 1.0
  2567. :html-foreground "Black" :html-background "Transparent"
  2568. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2569. "Options for creating images from LaTeX fragments.
  2570. This is a property list with the following properties:
  2571. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2572. `default' means use the foreground of the default face.
  2573. `auto' means use the foreground from the text face.
  2574. :background the background color, or \"Transparent\".
  2575. `default' means use the background of the default face.
  2576. `auto' means use the background from the text face.
  2577. :scale a scaling factor for the size of the images, to get more pixels
  2578. :html-foreground, :html-background, :html-scale
  2579. the same numbers for HTML export.
  2580. :matchers a list indicating which matchers should be used to
  2581. find LaTeX fragments. Valid members of this list are:
  2582. \"begin\" find environments
  2583. \"$1\" find single characters surrounded by $.$
  2584. \"$\" find math expressions surrounded by $...$
  2585. \"$$\" find math expressions surrounded by $$....$$
  2586. \"\\(\" find math expressions surrounded by \\(...\\)
  2587. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2588. :group 'org-latex
  2589. :type 'plist)
  2590. (defcustom org-format-latex-signal-error t
  2591. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2592. When nil, just push out a message."
  2593. :group 'org-latex
  2594. :version "24.1"
  2595. :type 'boolean)
  2596. (defcustom org-latex-to-mathml-jar-file nil
  2597. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2598. Use this to specify additional executable file say a jar file.
  2599. When using MathToWeb as the converter, specify the full-path to
  2600. your mathtoweb.jar file."
  2601. :group 'org-latex
  2602. :version "24.1"
  2603. :type '(choice
  2604. (const :tag "None" nil)
  2605. (file :tag "JAR file" :must-match t)))
  2606. (defcustom org-latex-to-mathml-convert-command nil
  2607. "Command to convert LaTeX fragments to MathML.
  2608. Replace format-specifiers in the command as noted below and use
  2609. `shell-command' to convert LaTeX to MathML.
  2610. %j: Executable file in fully expanded form as specified by
  2611. `org-latex-to-mathml-jar-file'.
  2612. %I: Input LaTeX file in fully expanded form.
  2613. %i: The latex fragment to be converted.
  2614. %o: Output MathML file.
  2615. This command is used by `org-create-math-formula'.
  2616. When using MathToWeb as the converter, set this option to
  2617. \"java -jar %j -unicode -force -df %o %I\".
  2618. When using LaTeXML set this option to
  2619. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2620. :group 'org-latex
  2621. :version "24.1"
  2622. :type '(choice
  2623. (const :tag "None" nil)
  2624. (string :tag "\nShell command")))
  2625. (defcustom org-latex-to-html-convert-command nil
  2626. "Command to convert LaTeX fragments to HTML.
  2627. This command is very open-ended: the output of the command will
  2628. directly replace the LaTeX fragment in the resulting HTML.
  2629. Replace format-specifiers in the command as noted below and use
  2630. `shell-command' to convert LaTeX to HTML.
  2631. %i: The LaTeX fragment to be converted.
  2632. For example, this could be used with LaTeXML as
  2633. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2634. :group 'org-latex
  2635. :package-version '(Org . "9.4")
  2636. :type '(choice
  2637. (const :tag "None" nil)
  2638. (string :tag "Shell command")))
  2639. (defcustom org-preview-latex-default-process 'dvipng
  2640. "The default process to convert LaTeX fragments to image files.
  2641. All available processes and theirs documents can be found in
  2642. `org-preview-latex-process-alist', which see."
  2643. :group 'org-latex
  2644. :version "26.1"
  2645. :package-version '(Org . "9.0")
  2646. :type 'symbol)
  2647. (defcustom org-preview-latex-process-alist
  2648. '((dvipng
  2649. :programs ("latex" "dvipng")
  2650. :description "dvi > png"
  2651. :message "you need to install the programs: latex and dvipng."
  2652. :image-input-type "dvi"
  2653. :image-output-type "png"
  2654. :image-size-adjust (1.0 . 1.0)
  2655. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2656. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2657. :transparent-image-converter
  2658. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2659. (dvisvgm
  2660. :programs ("latex" "dvisvgm")
  2661. :description "dvi > svg"
  2662. :message "you need to install the programs: latex and dvisvgm."
  2663. :image-input-type "dvi"
  2664. :image-output-type "svg"
  2665. :image-size-adjust (1.7 . 1.5)
  2666. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2667. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2668. (imagemagick
  2669. :programs ("latex" "convert")
  2670. :description "pdf > png"
  2671. :message "you need to install the programs: latex and imagemagick."
  2672. :image-input-type "pdf"
  2673. :image-output-type "png"
  2674. :image-size-adjust (1.0 . 1.0)
  2675. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2676. :image-converter
  2677. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2678. "Definitions of external processes for LaTeX previewing.
  2679. Org mode can use some external commands to generate TeX snippet's images for
  2680. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2681. `org-create-formula-image' how to call them.
  2682. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2683. PROPERTIES accepts the following attributes:
  2684. :programs list of strings, required programs.
  2685. :description string, describe the process.
  2686. :message string, message it when required programs cannot be found.
  2687. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2688. :image-output-type string, output file type of image converter (e.g., \"png\").
  2689. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2690. image size showed in buffer and the cdr element is for
  2691. HTML file. This option is only useful for process
  2692. developers, users should use variable
  2693. `org-format-latex-options' instead.
  2694. :post-clean list of strings, files matched are to be cleaned up once
  2695. the image is generated. When nil, the files with \".dvi\",
  2696. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2697. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2698. be cleaned up.
  2699. :latex-header list of strings, the LaTeX header of the snippet file.
  2700. When nil, the fallback value is used instead, which is
  2701. controlled by `org-format-latex-header',
  2702. `org-latex-default-packages-alist' and
  2703. `org-latex-packages-alist', which see.
  2704. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2705. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2706. replaced with values defined below.
  2707. :image-converter list of image converter commands strings. Each of them is
  2708. given to the shell and supports any of the following
  2709. place-holders defined below.
  2710. If set, :transparent-image-converter is used instead of :image-converter to
  2711. convert an image when the background color is nil or \"Transparent\".
  2712. Place-holders used by `:image-converter' and `:latex-compiler':
  2713. %f input file name
  2714. %b base name of input file
  2715. %o base directory of input file
  2716. %O absolute output file name
  2717. Place-holders only used by `:image-converter':
  2718. %D dpi, which is used to adjust image size by some processing commands.
  2719. %S the image size scale ratio, which is used to adjust image size by some
  2720. processing commands."
  2721. :group 'org-latex
  2722. :version "26.1"
  2723. :package-version '(Org . "9.0")
  2724. :type '(alist :tag "LaTeX to image backends"
  2725. :value-type (plist)))
  2726. (defcustom org-preview-latex-image-directory "ltximg/"
  2727. "Path to store latex preview images.
  2728. A relative path here creates many directories relative to the
  2729. processed Org files paths. An absolute path puts all preview
  2730. images at the same place."
  2731. :group 'org-latex
  2732. :version "26.1"
  2733. :package-version '(Org . "9.0")
  2734. :type 'string)
  2735. (defun org-format-latex-mathml-available-p ()
  2736. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2737. (save-match-data
  2738. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2739. org-latex-to-mathml-convert-command)
  2740. (let ((executable (car (split-string
  2741. org-latex-to-mathml-convert-command))))
  2742. (when (executable-find executable)
  2743. (if (string-match
  2744. "%j" org-latex-to-mathml-convert-command)
  2745. (file-readable-p org-latex-to-mathml-jar-file)
  2746. t))))))
  2747. (defcustom org-format-latex-header "\\documentclass{article}
  2748. \\usepackage[usenames]{color}
  2749. \[PACKAGES]
  2750. \[DEFAULT-PACKAGES]
  2751. \\pagestyle{empty} % do not remove
  2752. % The settings below are copied from fullpage.sty
  2753. \\setlength{\\textwidth}{\\paperwidth}
  2754. \\addtolength{\\textwidth}{-3cm}
  2755. \\setlength{\\oddsidemargin}{1.5cm}
  2756. \\addtolength{\\oddsidemargin}{-2.54cm}
  2757. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2758. \\setlength{\\textheight}{\\paperheight}
  2759. \\addtolength{\\textheight}{-\\headheight}
  2760. \\addtolength{\\textheight}{-\\headsep}
  2761. \\addtolength{\\textheight}{-\\footskip}
  2762. \\addtolength{\\textheight}{-3cm}
  2763. \\setlength{\\topmargin}{1.5cm}
  2764. \\addtolength{\\topmargin}{-2.54cm}"
  2765. "The document header used for processing LaTeX fragments.
  2766. It is imperative that this header make sure that no page number
  2767. appears on the page. The package defined in the variables
  2768. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2769. will either replace the placeholder \"[PACKAGES]\" in this
  2770. header, or they will be appended."
  2771. :group 'org-latex
  2772. :type 'string)
  2773. (defun org-set-packages-alist (var val)
  2774. "Set the packages alist and make sure it has 3 elements per entry."
  2775. (set var (mapcar (lambda (x)
  2776. (if (and (consp x) (= (length x) 2))
  2777. (list (car x) (nth 1 x) t)
  2778. x))
  2779. val)))
  2780. (defun org-get-packages-alist (var)
  2781. "Get the packages alist and make sure it has 3 elements per entry."
  2782. (mapcar (lambda (x)
  2783. (if (and (consp x) (= (length x) 2))
  2784. (list (car x) (nth 1 x) t)
  2785. x))
  2786. (default-value var)))
  2787. (defcustom org-latex-default-packages-alist
  2788. '(("AUTO" "inputenc" t ("pdflatex"))
  2789. ("T1" "fontenc" t ("pdflatex"))
  2790. ("" "graphicx" t)
  2791. ("" "longtable" nil)
  2792. ("" "wrapfig" nil)
  2793. ("" "rotating" nil)
  2794. ("normalem" "ulem" t)
  2795. ("" "amsmath" t)
  2796. ("" "amssymb" t)
  2797. ("" "capt-of" nil)
  2798. ("" "hyperref" nil))
  2799. "Alist of default packages to be inserted in the header.
  2800. Change this only if one of the packages here causes an
  2801. incompatibility with another package you are using.
  2802. The packages in this list are needed by one part or another of
  2803. Org mode to function properly:
  2804. - inputenc, fontenc: for basic font and character selection
  2805. - graphicx: for including images
  2806. - longtable: For multipage tables
  2807. - wrapfig: for figure placement
  2808. - rotating: for sideways figures and tables
  2809. - ulem: for underline and strike-through
  2810. - amsmath: for subscript and superscript and math environments
  2811. - amssymb: for various symbols used for interpreting the entities
  2812. in `org-entities'. You can skip some of this package if you don't
  2813. use any of the symbols.
  2814. - capt-of: for captions outside of floats
  2815. - hyperref: for cross references
  2816. Therefore you should not modify this variable unless you know
  2817. what you are doing. The one reason to change it anyway is that
  2818. you might be loading some other package that conflicts with one
  2819. of the default packages. Each element is either a cell or
  2820. a string.
  2821. A cell is of the format
  2822. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2823. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2824. when compiling LaTeX snippets into images for inclusion into
  2825. non-LaTeX output.
  2826. COMPILERS is a list of compilers that should include the package,
  2827. see `org-latex-compiler'. If the document compiler is not in the
  2828. list, and the list is non-nil, the package will not be inserted
  2829. in the final document.
  2830. A string will be inserted as-is in the header of the document."
  2831. :group 'org-latex
  2832. :group 'org-export-latex
  2833. :set 'org-set-packages-alist
  2834. :get 'org-get-packages-alist
  2835. :version "26.1"
  2836. :package-version '(Org . "8.3")
  2837. :type '(repeat
  2838. (choice
  2839. (list :tag "options/package pair"
  2840. (string :tag "options")
  2841. (string :tag "package")
  2842. (boolean :tag "Snippet")
  2843. (choice
  2844. (const :tag "For all compilers" nil)
  2845. (repeat :tag "Allowed compiler" string)))
  2846. (string :tag "A line of LaTeX"))))
  2847. (defcustom org-latex-packages-alist nil
  2848. "Alist of packages to be inserted in every LaTeX header.
  2849. These will be inserted after `org-latex-default-packages-alist'.
  2850. Each element is either a cell or a string.
  2851. A cell is of the format:
  2852. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2853. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2854. needed when turning LaTeX snippets into images for inclusion into
  2855. non-LaTeX output.
  2856. COMPILERS is a list of compilers that should include the package,
  2857. see `org-latex-compiler'. If the document compiler is not in the
  2858. list, and the list is non-nil, the package will not be inserted
  2859. in the final document.
  2860. A string will be inserted as-is in the header of the document.
  2861. Make sure that you only list packages here which:
  2862. - you want in every file;
  2863. - do not conflict with the setup in `org-format-latex-header';
  2864. - do not conflict with the default packages in
  2865. `org-latex-default-packages-alist'."
  2866. :group 'org-latex
  2867. :group 'org-export-latex
  2868. :set 'org-set-packages-alist
  2869. :get 'org-get-packages-alist
  2870. :type '(repeat
  2871. (choice
  2872. (list :tag "options/package pair"
  2873. (string :tag "options")
  2874. (string :tag "package")
  2875. (boolean :tag "Snippet"))
  2876. (string :tag "A line of LaTeX"))))
  2877. (defgroup org-appearance nil
  2878. "Settings for Org mode appearance."
  2879. :tag "Org Appearance"
  2880. :group 'org)
  2881. (defcustom org-level-color-stars-only nil
  2882. "Non-nil means fontify only the stars in each headline.
  2883. When nil, the entire headline is fontified.
  2884. Changing it requires restart of `font-lock-mode' to become effective
  2885. also in regions already fontified."
  2886. :group 'org-appearance
  2887. :type 'boolean)
  2888. (defcustom org-hide-leading-stars nil
  2889. "Non-nil means hide the first N-1 stars in a headline.
  2890. This works by using the face `org-hide' for these stars. This
  2891. face is white for a light background, and black for a dark
  2892. background. You may have to customize the face `org-hide' to
  2893. make this work.
  2894. Changing it requires restart of `font-lock-mode' to become effective
  2895. also in regions already fontified.
  2896. You may also set this on a per-file basis by adding one of the following
  2897. lines to the buffer:
  2898. #+STARTUP: hidestars
  2899. #+STARTUP: showstars"
  2900. :group 'org-appearance
  2901. :type 'boolean)
  2902. (defcustom org-hidden-keywords nil
  2903. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2904. For example, a value \\='(title) for this list makes the document's title
  2905. appear in the buffer without the initial \"#+TITLE:\" part."
  2906. :group 'org-appearance
  2907. :package-version '(Org . "9.5")
  2908. :type '(set (const :tag "#+AUTHOR" author)
  2909. (const :tag "#+DATE" date)
  2910. (const :tag "#+EMAIL" email)
  2911. (const :tag "#+SUBTITLE" subtitle)
  2912. (const :tag "#+TITLE" title)))
  2913. (defcustom org-custom-properties nil
  2914. "List of properties (as strings) with a special meaning.
  2915. The default use of these custom properties is to let the user
  2916. hide them with `org-toggle-custom-properties-visibility'."
  2917. :group 'org-properties
  2918. :group 'org-appearance
  2919. :version "24.3"
  2920. :type '(repeat (string :tag "Property Name")))
  2921. (defcustom org-fontify-todo-headline nil
  2922. "Non-nil means change the face of a headline if it is marked as TODO.
  2923. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2924. When this is non-nil, the headline after the keyword is set to the
  2925. `org-headline-todo' as an additional indication."
  2926. :group 'org-appearance
  2927. :package-version '(Org . "9.4")
  2928. :type 'boolean
  2929. :safe #'booleanp)
  2930. (defcustom org-fontify-done-headline t
  2931. "Non-nil means change the face of a headline if it is marked DONE.
  2932. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2933. When this is non-nil, the headline after the keyword is set to the
  2934. `org-headline-done' as an additional indication."
  2935. :group 'org-appearance
  2936. :package-version '(Org . "9.4")
  2937. :type 'boolean)
  2938. (defcustom org-fontify-emphasized-text t
  2939. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  2940. Changing this variable requires a restart of Emacs to take effect."
  2941. :group 'org-appearance
  2942. :type 'boolean)
  2943. (defcustom org-fontify-whole-heading-line nil
  2944. "Non-nil means fontify the whole line for headings.
  2945. This is useful when setting a background color for the
  2946. org-level-* faces."
  2947. :group 'org-appearance
  2948. :type 'boolean)
  2949. (defcustom org-fontify-whole-block-delimiter-line t
  2950. "Non-nil means fontify the whole line for begin/end lines of blocks.
  2951. This is useful when setting a background color for the
  2952. org-block-begin-line and org-block-end-line faces."
  2953. :group 'org-appearance
  2954. :type 'boolean)
  2955. (defcustom org-highlight-latex-and-related nil
  2956. "Non-nil means highlight LaTeX related syntax in the buffer.
  2957. When non-nil, the value should be a list containing any of the
  2958. following symbols:
  2959. `native' Highlight LaTeX snippets and environments natively.
  2960. `latex' Highlight LaTeX snippets and environments.
  2961. `script' Highlight subscript and superscript.
  2962. `entities' Highlight entities."
  2963. :group 'org-appearance
  2964. :version "24.4"
  2965. :package-version '(Org . "8.0")
  2966. :type '(choice
  2967. (const :tag "No highlighting" nil)
  2968. (set :greedy t :tag "Highlight"
  2969. (const :tag "LaTeX snippets and environments (native)" native)
  2970. (const :tag "LaTeX snippets and environments" latex)
  2971. (const :tag "Subscript and superscript" script)
  2972. (const :tag "Entities" entities))))
  2973. (defcustom org-hide-emphasis-markers nil
  2974. "Non-nil mean font-lock should hide the emphasis marker characters."
  2975. :group 'org-appearance
  2976. :type 'boolean
  2977. :safe #'booleanp)
  2978. (defcustom org-hide-macro-markers nil
  2979. "Non-nil mean font-lock should hide the brackets marking macro calls."
  2980. :group 'org-appearance
  2981. :type 'boolean)
  2982. (defcustom org-pretty-entities nil
  2983. "Non-nil means show entities as UTF8 characters.
  2984. When nil, the \\name form remains in the buffer."
  2985. :group 'org-appearance
  2986. :version "24.1"
  2987. :type 'boolean)
  2988. (defcustom org-pretty-entities-include-sub-superscripts t
  2989. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  2990. :group 'org-appearance
  2991. :version "24.1"
  2992. :type 'boolean)
  2993. (defvar org-emph-re nil
  2994. "Regular expression for matching emphasis.
  2995. After a match, the match groups contain these elements:
  2996. 0 The match of the full regular expression, including the characters
  2997. before and after the proper match
  2998. 1 The character before the proper match, or empty at beginning of line
  2999. 2 The proper match, including the leading and trailing markers
  3000. 3 The leading marker like * or /, indicating the type of highlighting
  3001. 4 The text between the emphasis markers, not including the markers
  3002. 5 The character after the match, empty at the end of a line")
  3003. (defvar org-verbatim-re nil
  3004. "Regular expression for matching verbatim text.")
  3005. (defvar org-emphasis-regexp-components) ; defined just below
  3006. (defvar org-emphasis-alist) ; defined just below
  3007. (defun org-set-emph-re (var val)
  3008. "Set variable and compute the emphasis regular expression."
  3009. (set var val)
  3010. (when (and (boundp 'org-emphasis-alist)
  3011. (boundp 'org-emphasis-regexp-components)
  3012. org-emphasis-alist org-emphasis-regexp-components)
  3013. (pcase-let*
  3014. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3015. (body (if (<= nl 0) body
  3016. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3017. (template
  3018. (format (concat "\\([%s]\\|^\\)" ;before markers
  3019. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3020. "\\([%s]\\|$\\)") ;after markers
  3021. pre border border body border post)))
  3022. (setq org-emph-re (format template "*/_+"))
  3023. (setq org-verbatim-re (format template "=~")))))
  3024. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3025. ;; set this option proved cumbersome. See this message/thread:
  3026. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3027. (defvar org-emphasis-regexp-components
  3028. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3029. "Components used to build the regular expression for emphasis.
  3030. This is a list with five entries. Terminology: In an emphasis string
  3031. like \" *strong word* \", we call the initial space PREMATCH, the final
  3032. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3033. and \"trong wor\" is the body. The different components in this variable
  3034. specify what is allowed/forbidden in each part:
  3035. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3036. post Chars allowed as postmatch. End of line will be allowed too.
  3037. border The chars *forbidden* as border characters.
  3038. body-regexp A regexp like \".\" to match a body character. Don't use
  3039. non-shy groups here, and don't allow newline here.
  3040. newline The maximum number of newlines allowed in an emphasis exp.
  3041. You need to reload Org or to restart Emacs after setting this.")
  3042. (defcustom org-emphasis-alist
  3043. '(("*" bold)
  3044. ("/" italic)
  3045. ("_" underline)
  3046. ("=" org-verbatim verbatim)
  3047. ("~" org-code verbatim)
  3048. ("+" (:strike-through t)))
  3049. "Alist of characters and faces to emphasize text.
  3050. Text starting and ending with a special character will be emphasized,
  3051. for example *bold*, _underlined_ and /italic/. This variable sets the
  3052. marker characters and the face to be used by font-lock for highlighting
  3053. in Org buffers.
  3054. You need to reload Org or to restart Emacs after customizing this."
  3055. :group 'org-appearance
  3056. :set 'org-set-emph-re
  3057. :version "24.4"
  3058. :package-version '(Org . "8.0")
  3059. :type '(repeat
  3060. (list
  3061. (string :tag "Marker character")
  3062. (choice
  3063. (face :tag "Font-lock-face")
  3064. (plist :tag "Face property list"))
  3065. (option (const verbatim)))))
  3066. (defvar org-protecting-blocks '("src" "example" "export")
  3067. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3068. This is needed for font-lock setup.")
  3069. ;;; Functions and variables from their packages
  3070. ;; Declared here to avoid compiler warnings
  3071. (defvar mark-active)
  3072. ;; Various packages
  3073. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3074. (declare-function calendar-forward-day "cal-move" (arg))
  3075. (declare-function calendar-goto-date "cal-move" (date))
  3076. (declare-function calendar-goto-today "cal-move" ())
  3077. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3078. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3079. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3080. (declare-function cdlatex-tab "ext:cdlatex" ())
  3081. (declare-function dired-get-filename
  3082. "dired"
  3083. (&optional localp no-error-if-not-filep))
  3084. (declare-function iswitchb-read-buffer
  3085. "iswitchb"
  3086. (prompt &optional
  3087. default require-match _predicate start matches-set))
  3088. (declare-function org-agenda-change-all-lines
  3089. "org-agenda"
  3090. (newhead hdmarker &optional fixface just-this))
  3091. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3092. "org-agenda"
  3093. (&optional end))
  3094. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3095. (declare-function org-agenda-format-item
  3096. "org-agenda"
  3097. (extra txt &optional level category tags dotime
  3098. remove-re habitp))
  3099. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3100. (declare-function org-agenda-save-markers-for-cut-and-paste
  3101. "org-agenda"
  3102. (beg end))
  3103. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3104. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3105. (declare-function org-attach-expand "org-attach" (file))
  3106. (declare-function org-attach-reveal "org-attach" ())
  3107. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3108. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3109. (declare-function org-indent-mode "org-indent" (&optional arg))
  3110. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3111. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3112. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3113. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3114. (declare-function parse-time-string "parse-time" (string))
  3115. (defvar align-mode-rules-list)
  3116. (defvar calc-embedded-close-formula)
  3117. (defvar calc-embedded-open-formula)
  3118. (defvar calc-embedded-open-mode)
  3119. (defvar font-lock-unfontify-region-function)
  3120. (defvar iswitchb-temp-buflist)
  3121. (defvar org-agenda-tags-todo-honor-ignore-options)
  3122. (defvar remember-data-file)
  3123. (defvar texmathp-why)
  3124. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3125. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3126. (declare-function org-resolve-clocks "org-clock"
  3127. (&optional also-non-dangling-p prompt last-valid))
  3128. (defvar org-clock-start-time)
  3129. (defvar org-clock-marker (make-marker)
  3130. "Marker recording the last clock-in.")
  3131. (defvar org-clock-hd-marker (make-marker)
  3132. "Marker recording the last clock-in, but the headline position.")
  3133. (defvar org-clock-heading ""
  3134. "The heading of the current clock entry.")
  3135. (defun org-clocking-buffer ()
  3136. "Return the buffer where the clock is currently running.
  3137. Return nil if no clock is running."
  3138. (marker-buffer org-clock-marker))
  3139. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3140. (defun org-check-running-clock ()
  3141. "Check if the current buffer contains the running clock.
  3142. If yes, offer to stop it and to save the buffer with the changes."
  3143. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3144. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3145. (buffer-name))))
  3146. (org-clock-out)
  3147. (when (y-or-n-p "Save changed buffer?")
  3148. (save-buffer))))
  3149. (defun org-clocktable-try-shift (dir n)
  3150. "Check if this line starts a clock table, if yes, shift the time block."
  3151. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3152. (org-clocktable-shift dir n)))
  3153. ;;;###autoload
  3154. (defun org-clock-persistence-insinuate ()
  3155. "Set up hooks for clock persistence."
  3156. (require 'org-clock)
  3157. (add-hook 'org-mode-hook 'org-clock-load)
  3158. (add-hook 'kill-emacs-hook 'org-clock-save))
  3159. (defun org-clock-auto-clockout-insinuate ()
  3160. "Set up hook for auto clocking out when Emacs is idle.
  3161. See `org-clock-auto-clockout-timer'.
  3162. This function is meant to be added to the user configuration."
  3163. (require 'org-clock)
  3164. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3165. (defgroup org-archive nil
  3166. "Options concerning archiving in Org mode."
  3167. :tag "Org Archive"
  3168. :group 'org-structure)
  3169. (defcustom org-archive-location "%s_archive::"
  3170. "The location where subtrees should be archived.
  3171. The value of this variable is a string, consisting of two parts,
  3172. separated by a double-colon. The first part is a filename and
  3173. the second part is a headline.
  3174. When the filename is omitted, archiving happens in the same file.
  3175. %s in the filename will be replaced by the current file
  3176. name (without the directory part). Archiving to a different file
  3177. is useful to keep archived entries from contributing to the
  3178. Org Agenda.
  3179. The archived entries will be filed as subtrees of the specified
  3180. headline. When the headline is omitted, the subtrees are simply
  3181. filed away at the end of the file, as top-level entries. Also in
  3182. the heading you can use %s to represent the file name, this can be
  3183. useful when using the same archive for a number of different files.
  3184. Here are a few examples:
  3185. \"%s_archive::\"
  3186. If the current file is Projects.org, archive in file
  3187. Projects.org_archive, as top-level trees. This is the default.
  3188. \"::* Archived Tasks\"
  3189. Archive in the current file, under the top-level headline
  3190. \"* Archived Tasks\".
  3191. \"~/org/archive.org::\"
  3192. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3193. \"~/org/archive.org::* From %s\"
  3194. Archive in file ~/org/archive.org (absolute path), under headlines
  3195. \"From FILENAME\" where file name is the current file name.
  3196. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3197. The \"datetree/\" string is special, signifying to archive
  3198. items to the datetree. Items are placed in either the CLOSED
  3199. date of the item, or the current date if there is no CLOSED date.
  3200. The heading will be a subentry to the current date. There doesn't
  3201. need to be a heading, but there always needs to be a slash after
  3202. datetree. For example, to store archived items directly in the
  3203. datetree, use \"~/org/datetree.org::datetree/\".
  3204. \"basement::** Finished Tasks\"
  3205. Archive in file ./basement (relative path), as level 3 trees
  3206. below the level 2 heading \"** Finished Tasks\".
  3207. You may define it locally by setting an ARCHIVE property. If
  3208. such a property is found in the file or in an entry, and anywhere
  3209. up the hierarchy, it will be used.
  3210. You can also set it for the whole file using the keyword-syntax:
  3211. #+ARCHIVE: basement::** Finished Tasks"
  3212. :group 'org-archive
  3213. :type 'string)
  3214. (defcustom org-agenda-skip-archived-trees t
  3215. "Non-nil means the agenda will skip any items located in archived trees.
  3216. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3217. variable is no longer recommended, you should leave it at the value t.
  3218. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3219. :group 'org-archive
  3220. :group 'org-agenda-skip
  3221. :type 'boolean)
  3222. (defcustom org-columns-skip-archived-trees t
  3223. "Non-nil means ignore archived trees when creating column view."
  3224. :group 'org-archive
  3225. :group 'org-properties
  3226. :type 'boolean)
  3227. (defcustom org-sparse-tree-open-archived-trees nil
  3228. "Non-nil means sparse tree construction shows matches in archived trees.
  3229. When nil, matches in these trees are highlighted, but the trees are kept in
  3230. collapsed state."
  3231. :group 'org-archive
  3232. :group 'org-sparse-trees
  3233. :type 'boolean)
  3234. (defcustom org-sparse-tree-default-date-type nil
  3235. "The default date type when building a sparse tree.
  3236. When this is nil, a date is a scheduled or a deadline timestamp.
  3237. Otherwise, these types are allowed:
  3238. all: all timestamps
  3239. active: only active timestamps (<...>)
  3240. inactive: only inactive timestamps ([...])
  3241. scheduled: only scheduled timestamps
  3242. deadline: only deadline timestamps"
  3243. :type '(choice (const :tag "Scheduled or deadline" nil)
  3244. (const :tag "All timestamps" all)
  3245. (const :tag "Only active timestamps" active)
  3246. (const :tag "Only inactive timestamps" inactive)
  3247. (const :tag "Only scheduled timestamps" scheduled)
  3248. (const :tag "Only deadline timestamps" deadline)
  3249. (const :tag "Only closed timestamps" closed))
  3250. :version "26.1"
  3251. :package-version '(Org . "8.3")
  3252. :group 'org-sparse-trees)
  3253. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3254. ;; Declare Column View Code
  3255. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3256. (declare-function org-columns-compute "org-colview" (property))
  3257. ;; Declare ID code
  3258. (declare-function org-id-store-link "org-id")
  3259. (declare-function org-id-locations-load "org-id")
  3260. (declare-function org-id-locations-save "org-id")
  3261. (defvar org-id-track-globally)
  3262. ;;; Variables for pre-computed regular expressions, all buffer local
  3263. (defvar-local org-todo-regexp nil
  3264. "Matches any of the TODO state keywords.
  3265. Since TODO keywords are case-sensitive, `case-fold-search' is
  3266. expected to be bound to nil when matching against this regexp.")
  3267. (defvar-local org-not-done-regexp nil
  3268. "Matches any of the TODO state keywords except the last one.
  3269. Since TODO keywords are case-sensitive, `case-fold-search' is
  3270. expected to be bound to nil when matching against this regexp.")
  3271. (defvar-local org-not-done-heading-regexp nil
  3272. "Matches a TODO headline that is not done.
  3273. Since TODO keywords are case-sensitive, `case-fold-search' is
  3274. expected to be bound to nil when matching against this regexp.")
  3275. (defvar-local org-todo-line-regexp nil
  3276. "Matches a headline and puts TODO state into group 2 if present.
  3277. Since TODO keywords are case-sensitive, `case-fold-search' is
  3278. expected to be bound to nil when matching against this regexp.")
  3279. (defvar-local org-complex-heading-regexp nil
  3280. "Matches a headline and puts everything into groups:
  3281. group 1: Stars
  3282. group 2: The TODO keyword, maybe
  3283. group 3: Priority cookie
  3284. group 4: True headline
  3285. group 5: Tags
  3286. Since TODO keywords are case-sensitive, `case-fold-search' is
  3287. expected to be bound to nil when matching against this regexp.")
  3288. (defvar-local org-complex-heading-regexp-format nil
  3289. "Printf format to make regexp to match an exact headline.
  3290. This regexp will match the headline of any node which has the
  3291. exact headline text that is put into the format, but may have any
  3292. TODO state, priority and tags.")
  3293. (defvar-local org-todo-line-tags-regexp nil
  3294. "Matches a headline and puts TODO state into group 2 if present.
  3295. Also put tags into group 4 if tags are present.")
  3296. (defconst org-plain-time-of-day-regexp
  3297. (concat
  3298. "\\(\\<[012]?[0-9]"
  3299. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3300. "\\(--?"
  3301. "\\(\\<[012]?[0-9]"
  3302. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3303. "\\)?")
  3304. "Regular expression to match a plain time or time range.
  3305. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3306. groups carry important information:
  3307. 0 the full match
  3308. 1 the first time, range or not
  3309. 8 the second time, if it is a range.")
  3310. (defconst org-plain-time-extension-regexp
  3311. (concat
  3312. "\\(\\<[012]?[0-9]"
  3313. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3314. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3315. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3316. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3317. groups carry important information:
  3318. 0 the full match
  3319. 7 hours of duration
  3320. 9 minutes of duration")
  3321. (defconst org-stamp-time-of-day-regexp
  3322. (concat
  3323. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3324. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3325. "\\(--?"
  3326. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3327. "Regular expression to match a timestamp time or time range.
  3328. After a match, the following groups carry important information:
  3329. 0 the full match
  3330. 1 date plus weekday, for back referencing to make sure
  3331. both times are on the same day
  3332. 2 the first time, range or not
  3333. 4 the second time, if it is a range.")
  3334. (defconst org-startup-options
  3335. '(("fold" org-startup-folded t)
  3336. ("overview" org-startup-folded t)
  3337. ("nofold" org-startup-folded nil)
  3338. ("showall" org-startup-folded nil)
  3339. ("show2levels" org-startup-folded show2levels)
  3340. ("show3levels" org-startup-folded show3levels)
  3341. ("show4levels" org-startup-folded show4levels)
  3342. ("show5levels" org-startup-folded show5levels)
  3343. ("showeverything" org-startup-folded showeverything)
  3344. ("content" org-startup-folded content)
  3345. ("indent" org-startup-indented t)
  3346. ("noindent" org-startup-indented nil)
  3347. ("num" org-startup-numerated t)
  3348. ("nonum" org-startup-numerated nil)
  3349. ("hidestars" org-hide-leading-stars t)
  3350. ("showstars" org-hide-leading-stars nil)
  3351. ("odd" org-odd-levels-only t)
  3352. ("oddeven" org-odd-levels-only nil)
  3353. ("align" org-startup-align-all-tables t)
  3354. ("noalign" org-startup-align-all-tables nil)
  3355. ("shrink" org-startup-shrink-all-tables t)
  3356. ("inlineimages" org-startup-with-inline-images t)
  3357. ("noinlineimages" org-startup-with-inline-images nil)
  3358. ("latexpreview" org-startup-with-latex-preview t)
  3359. ("nolatexpreview" org-startup-with-latex-preview nil)
  3360. ("customtime" org-display-custom-times t)
  3361. ("logdone" org-log-done time)
  3362. ("lognotedone" org-log-done note)
  3363. ("nologdone" org-log-done nil)
  3364. ("lognoteclock-out" org-log-note-clock-out t)
  3365. ("nolognoteclock-out" org-log-note-clock-out nil)
  3366. ("logrepeat" org-log-repeat state)
  3367. ("lognoterepeat" org-log-repeat note)
  3368. ("logdrawer" org-log-into-drawer t)
  3369. ("nologdrawer" org-log-into-drawer nil)
  3370. ("logstatesreversed" org-log-states-order-reversed t)
  3371. ("nologstatesreversed" org-log-states-order-reversed nil)
  3372. ("nologrepeat" org-log-repeat nil)
  3373. ("logreschedule" org-log-reschedule time)
  3374. ("lognotereschedule" org-log-reschedule note)
  3375. ("nologreschedule" org-log-reschedule nil)
  3376. ("logredeadline" org-log-redeadline time)
  3377. ("lognoteredeadline" org-log-redeadline note)
  3378. ("nologredeadline" org-log-redeadline nil)
  3379. ("logrefile" org-log-refile time)
  3380. ("lognoterefile" org-log-refile note)
  3381. ("nologrefile" org-log-refile nil)
  3382. ("fninline" org-footnote-define-inline t)
  3383. ("nofninline" org-footnote-define-inline nil)
  3384. ("fnlocal" org-footnote-section nil)
  3385. ("fnauto" org-footnote-auto-label t)
  3386. ("fnprompt" org-footnote-auto-label nil)
  3387. ("fnconfirm" org-footnote-auto-label confirm)
  3388. ("fnplain" org-footnote-auto-label plain)
  3389. ("fnadjust" org-footnote-auto-adjust t)
  3390. ("nofnadjust" org-footnote-auto-adjust nil)
  3391. ("constcgs" constants-unit-system cgs)
  3392. ("constSI" constants-unit-system SI)
  3393. ("noptag" org-tag-persistent-alist nil)
  3394. ("hideblocks" org-hide-block-startup t)
  3395. ("nohideblocks" org-hide-block-startup nil)
  3396. ("beamer" org-startup-with-beamer-mode t)
  3397. ("entitiespretty" org-pretty-entities t)
  3398. ("entitiesplain" org-pretty-entities nil))
  3399. "Variable associated with STARTUP options for Org.
  3400. Each element is a list of three items: the startup options (as written
  3401. in the #+STARTUP line), the corresponding variable, and the value to set
  3402. this variable to if the option is found. An optional fourth element PUSH
  3403. means to push this value onto the list in the variable.")
  3404. (defcustom org-group-tags t
  3405. "When non-nil (the default), use group tags.
  3406. This can be turned on/off through `org-toggle-tags-groups'."
  3407. :group 'org-tags
  3408. :group 'org-startup
  3409. :type 'boolean)
  3410. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3411. (defun org-toggle-tags-groups ()
  3412. "Toggle support for group tags.
  3413. Support for group tags is controlled by the option
  3414. `org-group-tags', which is non-nil by default."
  3415. (interactive)
  3416. (setq org-group-tags (not org-group-tags))
  3417. (cond ((and (derived-mode-p 'org-agenda-mode)
  3418. org-group-tags)
  3419. (org-agenda-redo))
  3420. ((derived-mode-p 'org-mode)
  3421. (let ((org-inhibit-startup t)) (org-mode))))
  3422. (message "Groups tags support has been turned %s"
  3423. (if org-group-tags "on" "off")))
  3424. (defun org--tag-add-to-alist (alist1 alist2)
  3425. "Merge tags from ALIST1 into ALIST2.
  3426. Duplicates tags outside a group are removed. Keywords and order
  3427. are preserved.
  3428. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3429. See `org-tag-alist' for their structure."
  3430. (cond
  3431. ((null alist2) alist1)
  3432. ((null alist1) alist2)
  3433. (t
  3434. (let ((to-add nil)
  3435. (group-flag nil))
  3436. (dolist (tag-pair alist1)
  3437. (pcase tag-pair
  3438. (`(,(or :startgrouptag :startgroup))
  3439. (setq group-flag t)
  3440. (push tag-pair to-add))
  3441. (`(,(or :endgrouptag :endgroup))
  3442. (setq group-flag nil)
  3443. (push tag-pair to-add))
  3444. (`(,(or :grouptags :newline))
  3445. (push tag-pair to-add))
  3446. (`(,tag . ,_)
  3447. ;; Remove duplicates from ALIST1, unless they are in
  3448. ;; a group. Indeed, it makes sense to have a tag appear in
  3449. ;; multiple groups.
  3450. (when (or group-flag (not (assoc tag alist2)))
  3451. (push tag-pair to-add)))
  3452. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3453. ;; Preserve order of ALIST1.
  3454. (append (nreverse to-add) alist2)))))
  3455. (defun org-priority-to-value (s)
  3456. "Convert priority string S to its numeric value."
  3457. (or (save-match-data
  3458. (and (string-match "\\([0-9]+\\)" s)
  3459. (string-to-number (match-string 1 s))))
  3460. (string-to-char s)))
  3461. (defun org-set-regexps-and-options (&optional tags-only)
  3462. "Precompute regular expressions used in the current buffer.
  3463. When optional argument TAGS-ONLY is non-nil, only compute tags
  3464. related expressions."
  3465. (when (derived-mode-p 'org-mode)
  3466. (let ((alist (org-collect-keywords
  3467. (append '("FILETAGS" "TAGS")
  3468. (and (not tags-only)
  3469. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3470. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3471. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3472. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3473. ;; Startup options. Get this early since it does change
  3474. ;; behavior for other options (e.g., tags).
  3475. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3476. (cdr (assoc "STARTUP" alist)))))
  3477. (dolist (option startup)
  3478. (pcase (assoc-string option org-startup-options t)
  3479. (`(,_ ,variable ,value t)
  3480. (unless (listp (symbol-value variable))
  3481. (set (make-local-variable variable) nil))
  3482. (add-to-list variable value))
  3483. (`(,_ ,variable ,value . ,_)
  3484. (set (make-local-variable variable) value))
  3485. (_ nil))))
  3486. (setq-local org-file-tags
  3487. (mapcar #'org-add-prop-inherited
  3488. (cl-mapcan (lambda (value)
  3489. (cl-mapcan
  3490. (lambda (k) (org-split-string k ":"))
  3491. (split-string value)))
  3492. (cdr (assoc "FILETAGS" alist)))))
  3493. (setq org-current-tag-alist
  3494. (org--tag-add-to-alist
  3495. org-tag-persistent-alist
  3496. (let ((tags (cdr (assoc "TAGS" alist))))
  3497. (if tags
  3498. (org-tag-string-to-alist
  3499. (mapconcat #'identity tags "\n"))
  3500. org-tag-alist))))
  3501. (setq org-tag-groups-alist
  3502. (org-tag-alist-to-groups org-current-tag-alist))
  3503. (unless tags-only
  3504. ;; Properties.
  3505. (let ((properties nil))
  3506. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3507. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3508. (setq properties (org--update-property-plist
  3509. (match-string-no-properties 1 value)
  3510. (match-string-no-properties 2 value)
  3511. properties))))
  3512. (setq-local org-keyword-properties properties))
  3513. ;; Archive location.
  3514. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3515. (when archive (setq-local org-archive-location archive)))
  3516. ;; Category.
  3517. (let ((category (cdr (assoc "CATEGORY" alist))))
  3518. (when category
  3519. (setq-local org-category (intern category))
  3520. (setq-local org-keyword-properties
  3521. (org--update-property-plist
  3522. "CATEGORY" category org-keyword-properties))))
  3523. ;; Columns.
  3524. (let ((column (cdr (assoc "COLUMNS" alist))))
  3525. (when column (setq-local org-columns-default-format column)))
  3526. ;; Constants.
  3527. (let ((store nil))
  3528. (dolist (pair (cl-mapcan #'split-string
  3529. (cdr (assoc "CONSTANTS" alist))))
  3530. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3531. (let* ((name (match-string 1 pair))
  3532. (value (match-string 2 pair))
  3533. (old (assoc name store)))
  3534. (if old (setcdr old value)
  3535. (push (cons name value) store)))))
  3536. (setq org-table-formula-constants-local store))
  3537. ;; Link abbreviations.
  3538. (let ((links
  3539. (delq nil
  3540. (mapcar
  3541. (lambda (value)
  3542. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3543. (cons (match-string-no-properties 1 value)
  3544. (match-string-no-properties 2 value))))
  3545. (cdr (assoc "LINK" alist))))))
  3546. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3547. ;; Priorities.
  3548. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3549. (pcase (and value (split-string value))
  3550. (`(,high ,low ,default . ,_)
  3551. (setq-local org-priority-highest (org-priority-to-value high))
  3552. (setq-local org-priority-lowest (org-priority-to-value low))
  3553. (setq-local org-priority-default (org-priority-to-value default)))))
  3554. ;; Scripts.
  3555. (let ((value (cdr (assoc "OPTIONS" alist))))
  3556. (dolist (option value)
  3557. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3558. (setq-local org-use-sub-superscripts
  3559. (read (match-string 1 option))))))
  3560. ;; TODO keywords.
  3561. (setq-local org-todo-kwd-alist nil)
  3562. (setq-local org-todo-key-alist nil)
  3563. (setq-local org-todo-key-trigger nil)
  3564. (setq-local org-todo-keywords-1 nil)
  3565. (setq-local org-done-keywords nil)
  3566. (setq-local org-todo-heads nil)
  3567. (setq-local org-todo-sets nil)
  3568. (setq-local org-todo-log-states nil)
  3569. (let ((todo-sequences
  3570. (or (append (mapcar (lambda (value)
  3571. (cons 'type (split-string value)))
  3572. (cdr (assoc "TYP_TODO" alist)))
  3573. (mapcar (lambda (value)
  3574. (cons 'sequence (split-string value)))
  3575. (append (cdr (assoc "TODO" alist))
  3576. (cdr (assoc "SEQ_TODO" alist)))))
  3577. (let ((d (default-value 'org-todo-keywords)))
  3578. (if (not (stringp (car d))) d
  3579. ;; XXX: Backward compatibility code.
  3580. (list (cons org-todo-interpretation d)))))))
  3581. (dolist (sequence todo-sequences)
  3582. (let* ((sequence (or (run-hook-with-args-until-success
  3583. 'org-todo-setup-filter-hook sequence)
  3584. sequence))
  3585. (sequence-type (car sequence))
  3586. (keywords (cdr sequence))
  3587. (sep (member "|" keywords))
  3588. names alist)
  3589. (dolist (k (remove "|" keywords))
  3590. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3591. k)
  3592. (error "Invalid TODO keyword %s" k))
  3593. (let ((name (match-string 1 k))
  3594. (key (match-string 2 k))
  3595. (log (org-extract-log-state-settings k)))
  3596. (push name names)
  3597. (push (cons name (and key (string-to-char key))) alist)
  3598. (when log (push log org-todo-log-states))))
  3599. (let* ((names (nreverse names))
  3600. (done (if sep (org-remove-keyword-keys (cdr sep))
  3601. (last names)))
  3602. (head (car names))
  3603. (tail (list sequence-type head (car done) (org-last done))))
  3604. (add-to-list 'org-todo-heads head 'append)
  3605. (push names org-todo-sets)
  3606. (setq org-done-keywords (append org-done-keywords done nil))
  3607. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3608. (setq org-todo-key-alist
  3609. (append org-todo-key-alist
  3610. (and alist
  3611. (append '((:startgroup))
  3612. (nreverse alist)
  3613. '((:endgroup))))))
  3614. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3615. (setq org-todo-sets (nreverse org-todo-sets)
  3616. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3617. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3618. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3619. ;; Compute the regular expressions and other local variables.
  3620. ;; Using `org-outline-regexp-bol' would complicate them much,
  3621. ;; because of the fixed white space at the end of that string.
  3622. (unless org-done-keywords
  3623. (setq org-done-keywords
  3624. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3625. (setq org-not-done-keywords
  3626. (org-delete-all org-done-keywords
  3627. (copy-sequence org-todo-keywords-1))
  3628. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3629. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3630. org-not-done-heading-regexp
  3631. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3632. org-todo-line-regexp
  3633. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3634. org-complex-heading-regexp
  3635. (concat "^\\(\\*+\\)"
  3636. "\\(?: +" org-todo-regexp "\\)?"
  3637. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3638. "\\(?: +\\(.*?\\)\\)??"
  3639. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3640. "[ \t]*$")
  3641. org-complex-heading-regexp-format
  3642. (concat "^\\(\\*+\\)"
  3643. "\\(?: +" org-todo-regexp "\\)?"
  3644. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3645. "\\(?: +"
  3646. ;; Stats cookies can be stuck to body.
  3647. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3648. "\\(%s\\)"
  3649. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3650. "\\)"
  3651. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3652. "[ \t]*$")
  3653. org-todo-line-tags-regexp
  3654. (concat "^\\(\\*+\\)"
  3655. "\\(?: +" org-todo-regexp "\\)?"
  3656. "\\(?: +\\(.*?\\)\\)??"
  3657. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3658. "[ \t]*$"))
  3659. (org-compute-latex-and-related-regexp)))))
  3660. (defun org-collect-keywords (keywords &optional unique directory)
  3661. "Return values for KEYWORDS in current buffer, as an alist.
  3662. KEYWORDS is a list of strings. Return value is a list of
  3663. elements with the pattern:
  3664. (NAME . LIST-OF-VALUES)
  3665. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3666. is a list of non-empty values, as strings, in order of appearance
  3667. in the buffer.
  3668. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3669. value, empty or not, appearing in the buffer, as a string.
  3670. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3671. (VALUE . DIRECTORY)
  3672. where VALUE is the regular value, and DIRECTORY is the variable
  3673. `default-directory' for the buffer containing the keyword. This
  3674. is important for values containing relative file names, since the
  3675. function follows SETUPFILE keywords, and may change its working
  3676. directory."
  3677. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3678. (unique (mapcar #'upcase unique))
  3679. (alist (org--collect-keywords-1
  3680. keywords unique directory
  3681. (and buffer-file-name (list buffer-file-name))
  3682. nil)))
  3683. ;; Re-order results.
  3684. (dolist (entry alist)
  3685. (pcase entry
  3686. (`(,_ . ,(and value (pred consp)))
  3687. (setcdr entry (nreverse value)))))
  3688. (nreverse alist)))
  3689. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3690. (org-with-point-at 1
  3691. (let ((case-fold-search t)
  3692. (regexp (org-make-options-regexp keywords)))
  3693. (while (and keywords (re-search-forward regexp nil t))
  3694. (let ((element (org-element-at-point)))
  3695. (when (eq 'keyword (org-element-type element))
  3696. (let ((value (org-element-property :value element)))
  3697. (pcase (org-element-property :key element)
  3698. ("SETUPFILE"
  3699. (when (and (org-string-nw-p value)
  3700. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3701. (let* ((uri (org-strip-quotes value))
  3702. (uri-is-url (org-url-p uri))
  3703. (uri (if uri-is-url
  3704. uri
  3705. (expand-file-name uri))))
  3706. (unless (member uri files)
  3707. (with-temp-buffer
  3708. (unless uri-is-url
  3709. (setq default-directory (file-name-directory uri)))
  3710. (let ((contents (org-file-contents uri :noerror)))
  3711. (when contents
  3712. (insert contents)
  3713. ;; Fake Org mode: `org-element-at-point'
  3714. ;; doesn't need full set-up.
  3715. (let ((major-mode 'org-mode))
  3716. (setq alist
  3717. (org--collect-keywords-1
  3718. keywords unique directory
  3719. (cons uri files)
  3720. alist))))))))))
  3721. (keyword
  3722. (let ((entry (assoc keyword alist))
  3723. (final
  3724. (cond ((not (member keyword directory)) value)
  3725. (buffer-file-name
  3726. (cons value
  3727. (file-name-directory buffer-file-name)))
  3728. (t (cons value default-directory)))))
  3729. (cond ((member keyword unique)
  3730. (push (cons keyword final) alist)
  3731. (setq keywords (remove keyword keywords))
  3732. (setq regexp (org-make-options-regexp keywords)))
  3733. ((null entry) (push (list keyword final) alist))
  3734. (t (push final (cdr entry)))))))))))
  3735. alist)))
  3736. (defun org-tag-string-to-alist (s)
  3737. "Return tag alist associated to string S.
  3738. S is a value for TAGS keyword or produced with
  3739. `org-tag-alist-to-string'. Return value is an alist suitable for
  3740. `org-tag-alist' or `org-tag-persistent-alist'."
  3741. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3742. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3743. "\\(?:(\\(.\\))\\)?\\'"))
  3744. alist group-flag)
  3745. (dolist (tokens lines (cdr (nreverse alist)))
  3746. (push '(:newline) alist)
  3747. (while tokens
  3748. (let ((token (pop tokens)))
  3749. (pcase token
  3750. ("{"
  3751. (push '(:startgroup) alist)
  3752. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3753. ("}"
  3754. (push '(:endgroup) alist)
  3755. (setq group-flag nil))
  3756. ("["
  3757. (push '(:startgrouptag) alist)
  3758. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3759. ("]"
  3760. (push '(:endgrouptag) alist)
  3761. (setq group-flag nil))
  3762. (":"
  3763. (push '(:grouptags) alist))
  3764. ((guard (string-match tag-re token))
  3765. (let ((tag (match-string 1 token))
  3766. (key (and (match-beginning 2)
  3767. (string-to-char (match-string 2 token)))))
  3768. ;; Push all tags in groups, no matter if they already
  3769. ;; appear somewhere else in the list.
  3770. (when (or group-flag (not (assoc tag alist)))
  3771. (push (cons tag key) alist))))))))))
  3772. (defun org-tag-alist-to-string (alist &optional skip-key)
  3773. "Return tag string associated to ALIST.
  3774. ALIST is an alist, as defined in `org-tag-alist' or
  3775. `org-tag-persistent-alist', or produced with
  3776. `org-tag-string-to-alist'.
  3777. Return value is a string suitable as a value for \"TAGS\"
  3778. keyword.
  3779. When optional argument SKIP-KEY is non-nil, skip selection keys
  3780. next to tags."
  3781. (mapconcat (lambda (token)
  3782. (pcase token
  3783. (`(:startgroup) "{")
  3784. (`(:endgroup) "}")
  3785. (`(:startgrouptag) "[")
  3786. (`(:endgrouptag) "]")
  3787. (`(:grouptags) ":")
  3788. (`(:newline) "\\n")
  3789. ((and
  3790. (guard (not skip-key))
  3791. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3792. (format "%s(%c)" tag key))
  3793. (`(,(and tag (pred stringp)) . ,_) tag)
  3794. (_ (user-error "Invalid tag token: %S" token))))
  3795. alist
  3796. " "))
  3797. (defun org-tag-alist-to-groups (alist)
  3798. "Return group alist from tag ALIST.
  3799. ALIST is an alist, as defined in `org-tag-alist' or
  3800. `org-tag-persistent-alist', or produced with
  3801. `org-tag-string-to-alist'. Return value is an alist following
  3802. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3803. a string, summarizing TAGS, as a list of strings."
  3804. (let (groups group-status current-group)
  3805. (dolist (token alist (nreverse groups))
  3806. (pcase token
  3807. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3808. (`(,(or :endgroup :endgrouptag))
  3809. (when (eq group-status 'append)
  3810. (push (nreverse current-group) groups))
  3811. (setq group-status nil current-group nil))
  3812. (`(:grouptags) (setq group-status 'append))
  3813. ((and `(,tag . ,_) (guard group-status))
  3814. (if (eq group-status 'append) (push tag current-group)
  3815. (setq current-group (list tag))))
  3816. (_ nil)))))
  3817. (defvar org--file-cache (make-hash-table :test #'equal)
  3818. "Hash table to store contents of files referenced via a URL.
  3819. This is the cache of file URLs read using `org-file-contents'.")
  3820. (defun org-reset-file-cache ()
  3821. "Reset the cache of files downloaded by `org-file-contents'."
  3822. (clrhash org--file-cache))
  3823. (defun org-file-contents (file &optional noerror nocache)
  3824. "Return the contents of FILE, as a string.
  3825. FILE can be a file name or URL.
  3826. If FILE is a URL, download the contents. If the URL contents are
  3827. already cached in the `org--file-cache' hash table, the download step
  3828. is skipped.
  3829. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3830. from file or URL, and return nil.
  3831. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3832. is available. This option applies only if FILE is a URL."
  3833. (let* ((is-url (org-url-p file))
  3834. (cache (and is-url
  3835. (not nocache)
  3836. (gethash file org--file-cache))))
  3837. (cond
  3838. (cache)
  3839. (is-url
  3840. (with-current-buffer (url-retrieve-synchronously file)
  3841. (goto-char (point-min))
  3842. ;; Move point to after the url-retrieve header.
  3843. (search-forward "\n\n" nil :move)
  3844. ;; Search for the success code only in the url-retrieve header.
  3845. (if (save-excursion
  3846. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3847. ;; Update the cache `org--file-cache' and return contents.
  3848. (puthash file
  3849. (buffer-substring-no-properties (point) (point-max))
  3850. org--file-cache)
  3851. (funcall (if noerror #'message #'user-error)
  3852. "Unable to fetch file from %S"
  3853. file)
  3854. nil)))
  3855. (t
  3856. (with-temp-buffer
  3857. (condition-case nil
  3858. (progn
  3859. (insert-file-contents file)
  3860. (buffer-string))
  3861. (file-error
  3862. (funcall (if noerror #'message #'user-error)
  3863. "Unable to read file %S"
  3864. file)
  3865. nil)))))))
  3866. (defun org-extract-log-state-settings (x)
  3867. "Extract the log state setting from a TODO keyword string.
  3868. This will extract info from a string like \"WAIT(w@/!)\"."
  3869. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  3870. (let ((kw (match-string 1 x))
  3871. (log1 (and (match-end 3) (match-string 3 x)))
  3872. (log2 (and (match-end 4) (match-string 4 x))))
  3873. (and (or log1 log2)
  3874. (list kw
  3875. (and log1 (if (equal log1 "!") 'time 'note))
  3876. (and log2 (if (equal log2 "!") 'time 'note)))))))
  3877. (defun org-remove-keyword-keys (list)
  3878. "Remove a pair of parenthesis at the end of each string in LIST."
  3879. (mapcar (lambda (x)
  3880. (if (string-match "(.*)$" x)
  3881. (substring x 0 (match-beginning 0))
  3882. x))
  3883. list))
  3884. (defun org-assign-fast-keys (alist)
  3885. "Assign fast keys to a keyword-key alist.
  3886. Respect keys that are already there."
  3887. (let (new e (alt ?0))
  3888. (while (setq e (pop alist))
  3889. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  3890. (cdr e)) ;; Key already assigned.
  3891. (push e new)
  3892. (let ((clist (string-to-list (downcase (car e))))
  3893. (used (append new alist)))
  3894. (when (= (car clist) ?@)
  3895. (pop clist))
  3896. (while (and clist (rassoc (car clist) used))
  3897. (pop clist))
  3898. (unless clist
  3899. (while (rassoc alt used)
  3900. (cl-incf alt)))
  3901. (push (cons (car e) (or (car clist) alt)) new))))
  3902. (nreverse new)))
  3903. ;;; Some variables used in various places
  3904. (defvar org-window-configuration nil
  3905. "Used in various places to store a window configuration.")
  3906. (defvar org-selected-window nil
  3907. "Used in various places to store a window configuration.")
  3908. (defvar org-finish-function nil
  3909. "Function to be called when `C-c C-c' is used.
  3910. This is for getting out of special buffers like capture.")
  3911. (defvar org-last-state)
  3912. ;; Defined somewhere in this file, but used before definition.
  3913. (defvar org-entities) ;; defined in org-entities.el
  3914. (defvar org-struct-menu)
  3915. (defvar org-org-menu)
  3916. (defvar org-tbl-menu)
  3917. ;;;; Define the Org mode
  3918. (defun org-before-change-function (_beg _end)
  3919. "Every change indicates that a table might need an update."
  3920. (setq org-table-may-need-update t))
  3921. (defvar org-mode-map)
  3922. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  3923. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  3924. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  3925. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  3926. (defvar bidi-paragraph-direction)
  3927. (defvar buffer-face-mode-face)
  3928. (require 'outline)
  3929. ;; Other stuff we need.
  3930. (require 'time-date)
  3931. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  3932. (require 'easymenu))
  3933. (require 'org-entities)
  3934. (require 'org-faces)
  3935. (require 'org-list)
  3936. (require 'org-pcomplete)
  3937. (require 'org-src)
  3938. (require 'org-footnote)
  3939. (require 'org-macro)
  3940. ;; babel
  3941. (require 'ob)
  3942. (defvar org-element-cache-persistent); Defined in org-element.el
  3943. (defvar org-element-use-cache); Defined in org-element.el
  3944. (defvar org-mode-loading nil
  3945. "Non-nil during Org mode initialisation.")
  3946. ;;;###autoload
  3947. (define-derived-mode org-mode outline-mode "Org"
  3948. "Outline-based notes management and organizer, alias
  3949. \"Carsten's outline-mode for keeping track of everything.\"
  3950. Org mode develops organizational tasks around a NOTES file which
  3951. contains information about projects as plain text. Org mode is
  3952. implemented on top of Outline mode, which is ideal to keep the content
  3953. of large files well structured. It supports ToDo items, deadlines and
  3954. time stamps, which magically appear in the diary listing of the Emacs
  3955. calendar. Tables are easily created with a built-in table editor.
  3956. Plain text URL-like links connect to websites, emails (VM), Usenet
  3957. messages (Gnus), BBDB entries, and any files related to the project.
  3958. For printing and sharing of notes, an Org file (or a part of it)
  3959. can be exported as a structured ASCII or HTML file.
  3960. The following commands are available:
  3961. \\{org-mode-map}"
  3962. (setq-local org-mode-loading t)
  3963. (org-load-modules-maybe)
  3964. (org-install-agenda-files-menu)
  3965. (when (and org-link-descriptive
  3966. (eq org-fold-core-style 'overlays))
  3967. (add-to-invisibility-spec '(org-link)))
  3968. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  3969. "..."))
  3970. (make-local-variable 'org-link-descriptive)
  3971. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  3972. (if org-link-descriptive
  3973. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  3974. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  3975. (setq-local outline-regexp org-outline-regexp)
  3976. (setq-local outline-level 'org-outline-level)
  3977. (setq bidi-paragraph-direction 'left-to-right)
  3978. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  3979. (unless org-display-table
  3980. (setq org-display-table (make-display-table)))
  3981. (set-display-table-slot
  3982. org-display-table 4
  3983. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  3984. org-ellipsis)))
  3985. (setq buffer-display-table org-display-table))
  3986. (org-set-regexps-and-options)
  3987. (org-set-font-lock-defaults)
  3988. (when (and org-tag-faces (not org-tags-special-faces-re))
  3989. ;; tag faces set outside customize.... force initialization.
  3990. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  3991. ;; Calc embedded
  3992. (setq-local calc-embedded-open-mode "# ")
  3993. ;; Modify a few syntax entries
  3994. (modify-syntax-entry ?\" "\"")
  3995. (modify-syntax-entry ?\\ "_")
  3996. (modify-syntax-entry ?~ "_")
  3997. (modify-syntax-entry ?< "(>")
  3998. (modify-syntax-entry ?> ")<")
  3999. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4000. ;; Activate before-change-function
  4001. (setq-local org-table-may-need-update t)
  4002. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4003. ;; Check for running clock before killing a buffer
  4004. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4005. ;; Initialize cache.
  4006. (org-element-cache-reset)
  4007. (when (and org-element-cache-persistent
  4008. org-element-use-cache)
  4009. (org-persist-load 'org-element--cache (current-buffer) t))
  4010. ;; Initialize macros templates.
  4011. (org-macro-initialize-templates)
  4012. ;; Initialize radio targets.
  4013. (org-update-radio-target-regexp)
  4014. ;; Indentation.
  4015. (setq-local indent-line-function 'org-indent-line)
  4016. (setq-local indent-region-function 'org-indent-region)
  4017. ;; Filling and auto-filling.
  4018. (org-setup-filling)
  4019. ;; Comments.
  4020. (org-setup-comments-handling)
  4021. ;; Beginning/end of defun
  4022. (setq-local beginning-of-defun-function 'org-backward-element)
  4023. (setq-local end-of-defun-function
  4024. (lambda ()
  4025. (if (not (org-at-heading-p))
  4026. (org-forward-element)
  4027. (org-forward-element)
  4028. (forward-char -1))))
  4029. ;; Next error for sparse trees
  4030. (setq-local next-error-function 'org-occur-next-match)
  4031. ;; Make commit log messages from Org documents easier.
  4032. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4033. ;; Make sure dependence stuff works reliably, even for users who set it
  4034. ;; too late :-(
  4035. (if org-enforce-todo-dependencies
  4036. (add-hook 'org-blocker-hook
  4037. 'org-block-todo-from-children-or-siblings-or-parent)
  4038. (remove-hook 'org-blocker-hook
  4039. 'org-block-todo-from-children-or-siblings-or-parent))
  4040. (if org-enforce-todo-checkbox-dependencies
  4041. (add-hook 'org-blocker-hook
  4042. 'org-block-todo-from-checkboxes)
  4043. (remove-hook 'org-blocker-hook
  4044. 'org-block-todo-from-checkboxes))
  4045. ;; Align options lines
  4046. (setq-local
  4047. align-mode-rules-list
  4048. '((org-in-buffer-settings
  4049. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4050. (modes . '(org-mode)))))
  4051. ;; Setup the pcomplete hooks
  4052. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4053. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4054. (setq-local pcomplete-default-completion-function #'ignore)
  4055. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4056. (setq-local pcomplete-termination-string "")
  4057. (add-hook 'completion-at-point-functions
  4058. #'pcomplete-completions-at-point nil t)
  4059. (setq-local buffer-face-mode-face 'org-default)
  4060. ;; If empty file that did not turn on Org mode automatically, make
  4061. ;; it to.
  4062. (when (and org-insert-mode-line-in-empty-file
  4063. (called-interactively-p 'any)
  4064. (= (point-min) (point-max)))
  4065. (insert "# -*- mode: org -*-\n\n"))
  4066. (unless org-inhibit-startup
  4067. (org-unmodified
  4068. (when org-startup-with-beamer-mode (org-beamer-mode))
  4069. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4070. (org-table-map-tables
  4071. (cond ((and org-startup-align-all-tables
  4072. org-startup-shrink-all-tables)
  4073. (lambda () (org-table-align) (org-table-shrink)))
  4074. (org-startup-align-all-tables #'org-table-align)
  4075. (t #'org-table-shrink))
  4076. t))
  4077. (when org-startup-with-inline-images (org-display-inline-images))
  4078. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4079. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4080. (when org-startup-truncated (setq truncate-lines t))
  4081. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4082. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4083. ;; Add a custom keymap for `visual-line-mode' so that activating
  4084. ;; this minor mode does not override Org's keybindings.
  4085. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4086. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4087. (newmap (make-sparse-keymap)))
  4088. (set-keymap-parent newmap oldmap)
  4089. (define-key newmap [remap move-beginning-of-line] nil)
  4090. (define-key newmap [remap move-end-of-line] nil)
  4091. (define-key newmap [remap kill-line] nil)
  4092. (make-local-variable 'minor-mode-overriding-map-alist)
  4093. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4094. ;; Activate `org-table-header-line-mode'
  4095. (when org-table-header-line-p
  4096. (org-table-header-line-mode 1))
  4097. ;; Try to set `org-hide' face correctly.
  4098. (let ((foreground (org-find-invisible-foreground)))
  4099. (when foreground
  4100. (set-face-foreground 'org-hide foreground)))
  4101. ;; Set face extension as requested.
  4102. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4103. org-fontify-whole-block-delimiter-line)
  4104. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4105. (setq-local org-mode-loading nil))
  4106. ;; Update `customize-package-emacs-version-alist'
  4107. (add-to-list 'customize-package-emacs-version-alist
  4108. '(Org ("8.0" . "24.4")
  4109. ("8.1" . "24.4")
  4110. ("8.2" . "24.4")
  4111. ("8.2.7" . "24.4")
  4112. ("8.3" . "26.1")
  4113. ("9.0" . "26.1")
  4114. ("9.1" . "26.1")
  4115. ("9.2" . "27.1")
  4116. ("9.3" . "27.1")
  4117. ("9.4" . "27.2")
  4118. ("9.5" . "28.1")
  4119. ("9.6" . "29.1")))
  4120. (defvar org-mode-transpose-word-syntax-table
  4121. (let ((st (make-syntax-table text-mode-syntax-table)))
  4122. (dolist (c org-emphasis-alist st)
  4123. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4124. (when (fboundp 'abbrev-table-put)
  4125. (abbrev-table-put org-mode-abbrev-table
  4126. :parents (list text-mode-abbrev-table)))
  4127. (defun org-find-invisible-foreground ()
  4128. (let ((candidates (remove
  4129. "unspecified-bg"
  4130. (nconc
  4131. (list (face-background 'default)
  4132. (face-background 'org-default))
  4133. (mapcar
  4134. (lambda (alist)
  4135. (when (boundp alist)
  4136. (cdr (assq 'background-color (symbol-value alist)))))
  4137. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4138. (list (face-foreground 'org-hide))))))
  4139. (car (remove nil candidates))))
  4140. (defun org-current-time (&optional rounding-minutes past)
  4141. "Current time, possibly rounded to ROUNDING-MINUTES.
  4142. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4143. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4144. the rounding returns a past time."
  4145. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4146. (car org-time-stamp-rounding-minutes)))
  4147. (now (current-time)))
  4148. (if (< r 1)
  4149. now
  4150. (let* ((time (decode-time now))
  4151. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4152. (nthcdr 2 time))))
  4153. (if (or (not past) (time-less-p res now))
  4154. res
  4155. (time-subtract res (* r 60)))))))
  4156. (defun org-today ()
  4157. "Return today date, considering `org-extend-today-until'."
  4158. (time-to-days
  4159. (time-since (* 3600 org-extend-today-until))))
  4160. ;;;; Font-Lock stuff, including the activators
  4161. (defconst org-match-sexp-depth 3
  4162. "Number of stacked braces for sub/superscript matching.")
  4163. (defun org-create-multibrace-regexp (left right n)
  4164. "Create a regular expression which will match a balanced sexp.
  4165. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4166. as single character strings.
  4167. The regexp returned will match the entire expression including the
  4168. delimiters. It will also define a single group which contains the
  4169. match except for the outermost delimiters. The maximum depth of
  4170. stacked delimiters is N. Escaping delimiters is not possible."
  4171. (let* ((nothing (concat "[^" left right "]*?"))
  4172. (or "\\|")
  4173. (re nothing)
  4174. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4175. (while (> n 1)
  4176. (setq n (1- n)
  4177. re (concat re or next)
  4178. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4179. (concat left "\\(" re "\\)" right)))
  4180. (defconst org-match-substring-regexp
  4181. (concat
  4182. "\\(\\S-\\)\\([_^]\\)\\("
  4183. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4184. "\\|"
  4185. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4186. "\\|"
  4187. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4188. "The regular expression matching a sub- or superscript.")
  4189. (defconst org-match-substring-with-braces-regexp
  4190. (concat
  4191. "\\(\\S-\\)\\([_^]\\)"
  4192. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4193. "The regular expression matching a sub- or superscript, forcing braces.")
  4194. (defvar org-emph-face nil)
  4195. (defun org-do-emphasis-faces (limit)
  4196. "Run through the buffer and emphasize strings."
  4197. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4198. (car org-emphasis-regexp-components))))
  4199. (catch :exit
  4200. (while (re-search-forward quick-re limit t)
  4201. (let* ((marker (match-string 2))
  4202. (verbatim? (member marker '("~" "="))))
  4203. (when (save-excursion
  4204. (goto-char (match-beginning 0))
  4205. (and
  4206. ;; Do not match table hlines.
  4207. (not (and (equal marker "+")
  4208. (org-match-line
  4209. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4210. ;; Do not match headline stars. Do not consider
  4211. ;; stars of a headline as closing marker for bold
  4212. ;; markup either.
  4213. (not (and (equal marker "*")
  4214. (save-excursion
  4215. (forward-char)
  4216. (skip-chars-backward "*")
  4217. (looking-at-p org-outline-regexp-bol))))
  4218. ;; Match full emphasis markup regexp.
  4219. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4220. ;; Do not span over paragraph boundaries.
  4221. (not (string-match-p org-element-paragraph-separate
  4222. (match-string 2)))
  4223. ;; Do not span over cells in table rows.
  4224. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4225. (string-match-p "|" (match-string 4))))))
  4226. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4227. (m (if org-hide-emphasis-markers 4 2)))
  4228. (font-lock-prepend-text-property
  4229. (match-beginning m) (match-end m) 'face face)
  4230. (when verbatim?
  4231. (org-remove-flyspell-overlays-in
  4232. (match-beginning 0) (match-end 0))
  4233. (remove-text-properties (match-beginning 2) (match-end 2)
  4234. '(display t invisible t intangible t)))
  4235. (add-text-properties (match-beginning 2) (match-end 2)
  4236. '(font-lock-multiline t org-emphasis t))
  4237. (when (and org-hide-emphasis-markers
  4238. (not (org-at-comment-p)))
  4239. (add-text-properties (match-end 4) (match-beginning 5)
  4240. '(invisible t))
  4241. (add-text-properties (match-beginning 3) (match-end 3)
  4242. '(invisible t)))
  4243. (throw :exit t))))))))
  4244. (defun org-emphasize (&optional char)
  4245. "Insert or change an emphasis, i.e. a font like bold or italic.
  4246. If there is an active region, change that region to a new emphasis.
  4247. If there is no region, just insert the marker characters and position
  4248. the cursor between them.
  4249. CHAR should be the marker character. If it is a space, it means to
  4250. remove the emphasis of the selected region.
  4251. If CHAR is not given (for example in an interactive call) it will be
  4252. prompted for."
  4253. (interactive)
  4254. (let ((erc org-emphasis-regexp-components)
  4255. (string "") beg end move s)
  4256. (if (org-region-active-p)
  4257. (setq beg (region-beginning)
  4258. end (region-end)
  4259. string (buffer-substring beg end))
  4260. (setq move t))
  4261. (unless char
  4262. (message "Emphasis marker or tag: [%s]"
  4263. (mapconcat #'car org-emphasis-alist ""))
  4264. (setq char (read-char-exclusive)))
  4265. (if (equal char ?\s)
  4266. (setq s ""
  4267. move nil)
  4268. (unless (assoc (char-to-string char) org-emphasis-alist)
  4269. (user-error "No such emphasis marker: \"%c\"" char))
  4270. (setq s (char-to-string char)))
  4271. (while (and (> (length string) 1)
  4272. (equal (substring string 0 1) (substring string -1))
  4273. (assoc (substring string 0 1) org-emphasis-alist))
  4274. (setq string (substring string 1 -1)))
  4275. (setq string (concat s string s))
  4276. (when beg (delete-region beg end))
  4277. (unless (or (bolp)
  4278. (string-match (concat "[" (nth 0 erc) "\n]")
  4279. (char-to-string (char-before (point)))))
  4280. (insert " "))
  4281. (unless (or (eobp)
  4282. (string-match (concat "[" (nth 1 erc) "\n]")
  4283. (char-to-string (char-after (point)))))
  4284. (insert " ") (backward-char 1))
  4285. (insert string)
  4286. (and move (backward-char 1))))
  4287. (defconst org-nonsticky-props
  4288. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4289. (defsubst org-rear-nonsticky-at (pos)
  4290. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4291. (defun org-activate-links--overlays (limit)
  4292. "Add link properties to links.
  4293. This includes angle, plain, and bracket links."
  4294. (catch :exit
  4295. (while (re-search-forward org-link-any-re limit t)
  4296. (let* ((start (match-beginning 0))
  4297. (end (match-end 0))
  4298. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4299. (visible-end (or (match-end 3) (match-end 2)))
  4300. (style (cond ((eq ?< (char-after start)) 'angle)
  4301. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4302. (t 'plain))))
  4303. (when (and (memq style org-highlight-links)
  4304. ;; Do not span over paragraph boundaries.
  4305. (not (string-match-p org-element-paragraph-separate
  4306. (match-string 0)))
  4307. ;; Do not confuse plain links with tags.
  4308. (not (and (eq style 'plain)
  4309. (let ((face (get-text-property
  4310. (max (1- start) (point-min)) 'face)))
  4311. (if (consp face) (memq 'org-tag face)
  4312. (eq 'org-tag face))))))
  4313. (let* ((link-object (save-excursion
  4314. (goto-char start)
  4315. (save-match-data (org-element-link-parser))))
  4316. (link (org-element-property :raw-link link-object))
  4317. (type (org-element-property :type link-object))
  4318. (path (org-element-property :path link-object))
  4319. (face-property (pcase (org-link-get-parameter type :face)
  4320. ((and (pred functionp) face) (funcall face path))
  4321. ((and (pred facep) face) face)
  4322. ((and (pred consp) face) face) ;anonymous
  4323. (_ 'org-link)))
  4324. (properties ;for link's visible part
  4325. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4326. 'highlight)
  4327. 'keymap (or (org-link-get-parameter type :keymap)
  4328. org-mouse-map)
  4329. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4330. ((and (pred stringp) echo) echo)
  4331. ((and (pred functionp) echo) echo)
  4332. (_ (concat "LINK: " link)))
  4333. 'htmlize-link (pcase (org-link-get-parameter type
  4334. :htmlize-link)
  4335. ((and (pred functionp) f) (funcall f))
  4336. (_ `(:uri ,link)))
  4337. 'font-lock-multiline t)))
  4338. (org-remove-flyspell-overlays-in start end)
  4339. (org-rear-nonsticky-at end)
  4340. (if (not (eq 'bracket style))
  4341. (progn
  4342. (add-face-text-property start end face-property)
  4343. (add-text-properties start end properties))
  4344. ;; Handle invisible parts in bracket links.
  4345. (remove-text-properties start end '(invisible nil))
  4346. (let ((hidden
  4347. (append `(invisible
  4348. ,(or (org-link-get-parameter type :display)
  4349. 'org-link))
  4350. properties)))
  4351. (add-text-properties start visible-start hidden)
  4352. (add-face-text-property start end face-property)
  4353. (add-text-properties visible-start visible-end properties)
  4354. (add-text-properties visible-end end hidden)
  4355. (org-rear-nonsticky-at visible-start)
  4356. (org-rear-nonsticky-at visible-end)))
  4357. (let ((f (org-link-get-parameter type :activate-func)))
  4358. (when (functionp f)
  4359. (funcall f start end path (eq style 'bracket))))
  4360. (throw :exit t))))) ;signal success
  4361. nil))
  4362. (defun org-activate-links--text-properties (limit)
  4363. "Add link properties to links.
  4364. This includes angle, plain, and bracket links."
  4365. (catch :exit
  4366. (while (re-search-forward org-link-any-re limit t)
  4367. (let* ((start (match-beginning 0))
  4368. (end (match-end 0))
  4369. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4370. (visible-end (or (match-end 3) (match-end 2)))
  4371. (style (cond ((eq ?< (char-after start)) 'angle)
  4372. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4373. (t 'plain))))
  4374. (when (and (memq style org-highlight-links)
  4375. ;; Do not span over paragraph boundaries.
  4376. (not (string-match-p org-element-paragraph-separate
  4377. (match-string 0)))
  4378. ;; Do not confuse plain links with tags.
  4379. (not (and (eq style 'plain)
  4380. (let ((face (get-text-property
  4381. (max (1- start) (point-min)) 'face)))
  4382. (if (consp face) (memq 'org-tag face)
  4383. (eq 'org-tag face))))))
  4384. (let* ((link-object (save-excursion
  4385. (goto-char start)
  4386. (save-match-data (org-element-link-parser))))
  4387. (link (org-element-property :raw-link link-object))
  4388. (type (org-element-property :type link-object))
  4389. (path (org-element-property :path link-object))
  4390. (face-property (pcase (org-link-get-parameter type :face)
  4391. ((and (pred functionp) face) (funcall face path))
  4392. ((and (pred facep) face) face)
  4393. ((and (pred consp) face) face) ;anonymous
  4394. (_ 'org-link)))
  4395. (properties ;for link's visible part
  4396. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4397. 'highlight)
  4398. 'keymap (or (org-link-get-parameter type :keymap)
  4399. org-mouse-map)
  4400. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4401. ((and (pred stringp) echo) echo)
  4402. ((and (pred functionp) echo) echo)
  4403. (_ (concat "LINK: " link)))
  4404. 'htmlize-link (pcase (org-link-get-parameter type
  4405. :htmlize-link)
  4406. ((and (pred functionp) f) (funcall f))
  4407. (_ `(:uri ,link)))
  4408. 'font-lock-multiline t)))
  4409. (org-remove-flyspell-overlays-in start end)
  4410. (org-rear-nonsticky-at end)
  4411. (if (not (eq 'bracket style))
  4412. (progn
  4413. (add-face-text-property start end face-property)
  4414. (add-text-properties start end properties))
  4415. ;; Initialise folding when used ouside org-mode.
  4416. (unless (or (derived-mode-p 'org-mode)
  4417. (and (org-fold-folding-spec-p 'org-link-description)
  4418. (org-fold-folding-spec-p 'org-link)))
  4419. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4420. "...")))
  4421. ;; Handle invisible parts in bracket links.
  4422. (let ((spec (or (org-link-get-parameter type :display)
  4423. 'org-link)))
  4424. (unless (org-fold-folding-spec-p spec)
  4425. (org-fold-add-folding-spec spec
  4426. (cdr org-link--link-folding-spec)
  4427. nil
  4428. 'append)
  4429. (org-fold-core-set-folding-spec-property spec :visible t))
  4430. (org-fold-region start end nil 'org-link)
  4431. (org-fold-region start end nil 'org-link-description)
  4432. ;; We are folding the whole emphasised text with SPEC
  4433. ;; first. It makes everything invisible (or whatever
  4434. ;; the user wants).
  4435. (org-fold-region start end t spec)
  4436. ;; The visible part of the text is folded using
  4437. ;; 'org-link-description, which is forcing this part of
  4438. ;; the text to be visible.
  4439. (org-fold-region visible-start visible-end t 'org-link-description)
  4440. (add-text-properties start end properties)
  4441. (add-face-text-property start end face-property)
  4442. (org-rear-nonsticky-at visible-start)
  4443. (org-rear-nonsticky-at visible-end)))
  4444. (let ((f (org-link-get-parameter type :activate-func)))
  4445. (when (functionp f)
  4446. (funcall f start end path (eq style 'bracket))))
  4447. (throw :exit t))))) ;signal success
  4448. nil))
  4449. (defsubst org-activate-links (limit)
  4450. "Add link properties to links.
  4451. This includes angle, plain, and bracket links."
  4452. (if (eq org-fold-core-style 'text-properties)
  4453. (org-activate-links--text-properties limit)
  4454. (org-activate-links--overlays limit)))
  4455. (defun org-activate-code (limit)
  4456. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4457. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4458. (remove-text-properties (match-beginning 0) (match-end 0)
  4459. '(display t invisible t intangible t))
  4460. t))
  4461. (defcustom org-src-fontify-natively t
  4462. "When non-nil, fontify code in code blocks.
  4463. See also the `org-block' face."
  4464. :type 'boolean
  4465. :version "26.1"
  4466. :package-version '(Org . "8.3")
  4467. :group 'org-appearance
  4468. :group 'org-babel)
  4469. (defcustom org-allow-promoting-top-level-subtree nil
  4470. "When non-nil, allow promoting a top level subtree.
  4471. The leading star of the top level headline will be replaced
  4472. by a #."
  4473. :type 'boolean
  4474. :version "24.1"
  4475. :group 'org-appearance)
  4476. (defun org-fontify-meta-lines-and-blocks (limit)
  4477. (condition-case nil
  4478. (org-fontify-meta-lines-and-blocks-1 limit)
  4479. (error (message "Org mode fontification error in %S at %d"
  4480. (current-buffer)
  4481. (line-number-at-pos)))))
  4482. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4483. "Fontify #+ lines and blocks."
  4484. (let ((case-fold-search t))
  4485. (when (re-search-forward
  4486. (rx bol (group (zero-or-more (any " \t")) "#"
  4487. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4488. (any " \t")
  4489. eol))
  4490. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4491. (zero-or-more (any " \t"))
  4492. (group (group (zero-or-more (not (any " \t\n"))))
  4493. (zero-or-more (any " \t"))
  4494. (group (zero-or-more any)))))
  4495. limit t)
  4496. (let ((beg (match-beginning 0))
  4497. (end-of-beginline (match-end 0))
  4498. ;; Including \n at end of #+begin line will include \n
  4499. ;; after the end of block content.
  4500. (block-start (match-end 0))
  4501. (block-end nil)
  4502. (lang (match-string 7)) ; The language, if it is a source block.
  4503. (bol-after-beginline (line-beginning-position 2))
  4504. (dc1 (downcase (match-string 2)))
  4505. (dc3 (downcase (match-string 3)))
  4506. (whole-blockline org-fontify-whole-block-delimiter-line)
  4507. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4508. (cond
  4509. ((and (match-end 4) (equal dc3 "+begin"))
  4510. ;; Truly a block
  4511. (setq block-type (downcase (match-string 5))
  4512. ;; Src, example, export, maybe more.
  4513. quoting (member block-type org-protecting-blocks))
  4514. (when (re-search-forward
  4515. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4516. (seq (zero-or-more (any " \t"))
  4517. "#+end"
  4518. ,(match-string 4)
  4519. word-end
  4520. (zero-or-more any)))))
  4521. ;; We look further than LIMIT on purpose.
  4522. nil t)
  4523. ;; We do have a matching #+end line.
  4524. (setq beg-of-endline (match-beginning 0)
  4525. end-of-endline (match-end 0)
  4526. nl-before-endline (1- (match-beginning 0)))
  4527. (setq block-end (match-beginning 0)) ; Include the final newline.
  4528. (when quoting
  4529. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4530. (remove-text-properties beg end-of-endline
  4531. '(display t invisible t intangible t)))
  4532. (add-text-properties
  4533. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4534. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4535. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4536. (cond
  4537. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4538. (save-match-data
  4539. (org-src-font-lock-fontify-block lang block-start block-end))
  4540. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4541. (quoting
  4542. (add-text-properties
  4543. bol-after-beginline beg-of-endline
  4544. (list 'face
  4545. (list :inherit
  4546. (let ((face-name
  4547. (intern (format "org-block-%s" lang))))
  4548. (append (and (facep face-name) (list face-name))
  4549. '(org-block)))))))
  4550. ((not org-fontify-quote-and-verse-blocks))
  4551. ((string= block-type "quote")
  4552. (add-face-text-property
  4553. bol-after-beginline beg-of-endline 'org-quote t))
  4554. ((string= block-type "verse")
  4555. (add-face-text-property
  4556. bol-after-beginline beg-of-endline 'org-verse t)))
  4557. ;; Fontify the #+begin and #+end lines of the blocks
  4558. (add-text-properties
  4559. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4560. '(face org-block-begin-line))
  4561. (unless (eq (char-after beg-of-endline) ?*)
  4562. (add-text-properties
  4563. beg-of-endline
  4564. (if whole-blockline
  4565. (let ((beg-of-next-line (1+ end-of-endline)))
  4566. (min (point-max) beg-of-next-line))
  4567. (min (point-max) end-of-endline))
  4568. '(face org-block-end-line)))
  4569. t))
  4570. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4571. (org-remove-flyspell-overlays-in
  4572. (match-beginning 0)
  4573. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4574. (add-text-properties
  4575. beg (match-end 3)
  4576. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4577. '(font-lock-fontified t invisible t)
  4578. '(font-lock-fontified t face org-document-info-keyword)))
  4579. (add-text-properties
  4580. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4581. (if (string-equal dc1 "+title:")
  4582. '(font-lock-fontified t face org-document-title)
  4583. '(font-lock-fontified t face org-document-info))))
  4584. ((string-prefix-p "+caption" dc1)
  4585. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4586. (remove-text-properties (match-beginning 0) (match-end 0)
  4587. '(display t invisible t intangible t))
  4588. ;; Handle short captions
  4589. (save-excursion
  4590. (beginning-of-line)
  4591. (looking-at (rx (group (zero-or-more (any " \t"))
  4592. "#+caption"
  4593. (optional "[" (zero-or-more any) "]")
  4594. ":")
  4595. (zero-or-more (any " \t")))))
  4596. (add-text-properties (line-beginning-position) (match-end 1)
  4597. '(font-lock-fontified t face org-meta-line))
  4598. (add-text-properties (match-end 0) (line-end-position)
  4599. '(font-lock-fontified t face org-block))
  4600. t)
  4601. ((member dc3 '(" " ""))
  4602. ;; Just a comment, the plus was not there
  4603. (org-remove-flyspell-overlays-in beg (match-end 0))
  4604. (add-text-properties
  4605. beg (match-end 0)
  4606. '(font-lock-fontified t face font-lock-comment-face)))
  4607. (t ;; Just any other in-buffer setting, but not indented
  4608. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4609. (remove-text-properties (match-beginning 0) (match-end 0)
  4610. '(display t invisible t intangible t))
  4611. (add-text-properties beg (match-end 0)
  4612. '(font-lock-fontified t face org-meta-line))
  4613. t))))))
  4614. (defun org-fontify-drawers (limit)
  4615. "Fontify drawers."
  4616. (when (re-search-forward org-drawer-regexp limit t)
  4617. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4618. '(font-lock-fontified t face org-drawer))
  4619. (org-remove-flyspell-overlays-in
  4620. (line-beginning-position) (line-beginning-position 2))
  4621. t))
  4622. (defun org-fontify-macros (limit)
  4623. "Fontify macros."
  4624. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4625. (let ((begin (match-beginning 0))
  4626. (opening-end (match-beginning 1)))
  4627. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4628. (match-string 1))
  4629. (let ((end (match-end 1))
  4630. (closing-start (match-beginning 1)))
  4631. (add-text-properties
  4632. begin end
  4633. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4634. (org-remove-flyspell-overlays-in begin end)
  4635. (when org-hide-macro-markers
  4636. (add-text-properties begin opening-end '(invisible t))
  4637. (add-text-properties closing-start end '(invisible t)))
  4638. t)))))
  4639. (defun org-fontify-extend-region (beg end _old-len)
  4640. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4641. (1+ end) end))
  4642. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4643. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4644. (extend
  4645. (lambda (r1 r2 dir)
  4646. (let ((re (replace-regexp-in-string
  4647. "\\(begin\\|end\\)" r1
  4648. (replace-regexp-in-string
  4649. "[][]" r2
  4650. (match-string-no-properties 0)))))
  4651. (re-search-forward (regexp-quote re) nil t dir)))))
  4652. (goto-char beg)
  4653. (back-to-indentation)
  4654. (save-match-data
  4655. (cond ((looking-at end-re)
  4656. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4657. ((looking-at begin-re)
  4658. (cons beg (or (funcall extend "end" "]" 1) end)))
  4659. (t (cons beg end))))))
  4660. (defun org-activate-footnote-links (limit)
  4661. "Add text properties for footnotes."
  4662. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4663. (when fn
  4664. (let* ((beg (nth 1 fn))
  4665. (end (nth 2 fn))
  4666. (label (car fn))
  4667. (referencep (/= (line-beginning-position) beg)))
  4668. (when (and referencep (nth 3 fn))
  4669. (save-excursion
  4670. (goto-char beg)
  4671. (search-forward (or label "fn:"))
  4672. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4673. (add-text-properties beg end
  4674. (list 'mouse-face 'highlight
  4675. 'keymap org-mouse-map
  4676. 'help-echo
  4677. (if referencep "Footnote reference"
  4678. "Footnote definition")
  4679. 'font-lock-fontified t
  4680. 'font-lock-multiline t
  4681. 'face 'org-footnote))))))
  4682. (defun org-activate-dates (limit)
  4683. "Add text properties for dates."
  4684. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4685. (not (equal (char-before (match-beginning 0)) 91)))
  4686. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4687. (add-text-properties (match-beginning 0) (match-end 0)
  4688. (list 'mouse-face 'highlight
  4689. 'keymap org-mouse-map))
  4690. (org-rear-nonsticky-at (match-end 0))
  4691. (when org-display-custom-times
  4692. ;; If it's a date range, activate custom time for second date.
  4693. (when (match-end 3)
  4694. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4695. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4696. t))
  4697. (defun org-activate-target-links (limit)
  4698. "Add text properties for target matches."
  4699. (when org-target-link-regexp
  4700. (let ((case-fold-search t))
  4701. ;; `org-target-link-regexp' matches one character before the
  4702. ;; actual target.
  4703. (unless (bolp) (forward-char -1))
  4704. (when (re-search-forward org-target-link-regexp limit t)
  4705. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4706. (add-text-properties (match-beginning 1) (match-end 1)
  4707. (list 'mouse-face 'highlight
  4708. 'keymap org-mouse-map
  4709. 'help-echo "Radio target link"
  4710. 'org-linked-text t))
  4711. (org-rear-nonsticky-at (match-end 1))
  4712. t))))
  4713. (defvar org-latex-and-related-regexp nil
  4714. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4715. (defun org-compute-latex-and-related-regexp ()
  4716. "Compute regular expression for LaTeX, entities and sub/superscript.
  4717. Result depends on variable `org-highlight-latex-and-related'."
  4718. (let ((re-sub
  4719. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4720. ((eq org-use-sub-superscripts '{})
  4721. (list org-match-substring-with-braces-regexp))
  4722. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4723. (re-latex
  4724. (when (or (memq 'latex org-highlight-latex-and-related)
  4725. (memq 'native org-highlight-latex-and-related))
  4726. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4727. (delq nil
  4728. (mapcar (lambda (x)
  4729. (and (member (car x) matchers) (nth 1 x)))
  4730. org-latex-regexps)))))
  4731. (re-entities
  4732. (when (memq 'entities org-highlight-latex-and-related)
  4733. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4734. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4735. (setq-local org-latex-and-related-regexp
  4736. (mapconcat #'identity
  4737. (append re-latex re-entities re-sub)
  4738. "\\|"))))
  4739. (defun org-do-latex-and-related (limit)
  4740. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4741. Stop at first highlighted object, if any. Return t if some
  4742. highlighting was done, nil otherwise."
  4743. (when (org-string-nw-p org-latex-and-related-regexp)
  4744. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4745. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4746. (catch 'found
  4747. (while (and (< (point) limit)
  4748. (re-search-forward org-latex-and-related-regexp nil t))
  4749. (cond
  4750. ((>= (match-beginning 0) limit)
  4751. (throw 'found nil))
  4752. ((cl-some (lambda (f)
  4753. (memq f '(org-code org-verbatim underline
  4754. org-special-keyword)))
  4755. (save-excursion
  4756. (goto-char (1+ (match-beginning 0)))
  4757. (face-at-point nil t))))
  4758. ;; Try to limit false positives. In this case, ignore
  4759. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4760. ;; contain an empty line.
  4761. ((save-excursion
  4762. (goto-char (match-beginning 0))
  4763. (and (looking-at-p latex-prefix-re)
  4764. (save-match-data
  4765. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4766. (t
  4767. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4768. '(?_ ?^))
  4769. 1
  4770. 0))
  4771. (start (+ offset (match-beginning 0)))
  4772. (end (match-end 0)))
  4773. (if (memq 'native org-highlight-latex-and-related)
  4774. (org-src-font-lock-fontify-block "latex" start end)
  4775. (font-lock-prepend-text-property start end
  4776. 'face 'org-latex-and-related))
  4777. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4778. '(font-lock-multiline t))
  4779. (throw 'found t)))))
  4780. nil))))
  4781. (defun org-restart-font-lock ()
  4782. "Restart `font-lock-mode', to force refontification."
  4783. (when font-lock-mode
  4784. (font-lock-mode -1)
  4785. (font-lock-mode 1)))
  4786. (defun org-activate-tags (limit)
  4787. (when (re-search-forward org-tag-line-re limit t)
  4788. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4789. (add-text-properties (match-beginning 1) (match-end 1)
  4790. (list 'mouse-face 'highlight
  4791. 'keymap org-mouse-map))
  4792. (org-rear-nonsticky-at (match-end 1))
  4793. t))
  4794. (defun org-outline-level ()
  4795. "Compute the outline level of the heading at point.
  4796. If this is called at a normal headline, the level is the number
  4797. of stars. Use `org-reduced-level' to remove the effect of
  4798. `org-odd-levels'. Unlike to `org-current-level', this function
  4799. takes into consideration inlinetasks."
  4800. (org-with-wide-buffer
  4801. (end-of-line)
  4802. (if (re-search-backward org-outline-regexp-bol nil t)
  4803. (1- (- (match-end 0) (match-beginning 0)))
  4804. 0)))
  4805. (defvar org-font-lock-keywords nil)
  4806. (defsubst org-re-property (property &optional literal allow-null value)
  4807. "Return a regexp matching a PROPERTY line.
  4808. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4809. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4810. non-nil, match properties even without a value.
  4811. Match group 3 is set to the value when it exists. If there is no
  4812. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4813. With optional argument VALUE, match only property lines with
  4814. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4815. unless LITERAL is non-nil."
  4816. (concat
  4817. "^\\(?4:[ \t]*\\)"
  4818. (format "\\(?1::\\(?2:%s\\):\\)"
  4819. (if literal property (regexp-quote property)))
  4820. (cond (value
  4821. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4822. (if literal value (regexp-quote value))))
  4823. (allow-null
  4824. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4825. (t
  4826. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4827. (defconst org-property-re
  4828. (org-re-property "\\S-+" 'literal t)
  4829. "Regular expression matching a property line.
  4830. There are four matching groups:
  4831. 1: :PROPKEY: including the leading and trailing colon,
  4832. 2: PROPKEY without the leading and trailing colon,
  4833. 3: PROPVAL without leading or trailing spaces,
  4834. 4: the indentation of the current line,
  4835. 5: trailing whitespace.")
  4836. (defvar org-font-lock-hook nil
  4837. "Functions to be called for special font lock stuff.")
  4838. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4839. (defvar org-font-lock-set-keywords-hook nil
  4840. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4841. This is called after `org-font-lock-extra-keywords' is defined, but before
  4842. it is installed to be used by font lock. This can be useful if something
  4843. needs to be inserted at a specific position in the font-lock sequence.")
  4844. (defun org-font-lock-hook (limit)
  4845. "Run `org-font-lock-hook' within LIMIT."
  4846. (run-hook-with-args 'org-font-lock-hook limit))
  4847. (defun org-set-font-lock-defaults ()
  4848. "Set font lock defaults for the current buffer."
  4849. (let ((org-font-lock-extra-keywords
  4850. (list
  4851. ;; Call the hook
  4852. '(org-font-lock-hook)
  4853. ;; Headlines
  4854. `(,(if org-fontify-whole-heading-line
  4855. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4856. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4857. (1 (org-get-level-face 1))
  4858. (2 (org-get-level-face 2))
  4859. (3 (org-get-level-face 3)))
  4860. ;; Table lines
  4861. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4862. (1 'org-table t))
  4863. ;; Table internals
  4864. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4865. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4866. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4867. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4868. ;; Properties
  4869. (list org-property-re
  4870. '(1 'org-special-keyword t)
  4871. '(3 'org-property-value t))
  4872. ;; Drawers
  4873. '(org-fontify-drawers)
  4874. ;; Link related fontification.
  4875. '(org-activate-links)
  4876. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  4877. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  4878. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  4879. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  4880. ;; Targets.
  4881. (list org-radio-target-regexp '(0 'org-target t))
  4882. (list org-target-regexp '(0 'org-target t))
  4883. ;; Diary sexps.
  4884. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4885. ;; Macro
  4886. '(org-fontify-macros)
  4887. ;; TODO keyword
  4888. (list (format org-heading-keyword-regexp-format
  4889. org-todo-regexp)
  4890. '(2 (org-get-todo-face 2) prepend))
  4891. ;; TODO
  4892. (when org-fontify-todo-headline
  4893. (list (format org-heading-keyword-regexp-format
  4894. (concat
  4895. "\\(?:"
  4896. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4897. "\\)"))
  4898. '(2 'org-headline-todo prepend)))
  4899. ;; DONE
  4900. (when org-fontify-done-headline
  4901. (list (format org-heading-keyword-regexp-format
  4902. (concat
  4903. "\\(?:"
  4904. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4905. "\\)"))
  4906. '(2 'org-headline-done prepend)))
  4907. ;; Priorities
  4908. '(org-font-lock-add-priority-faces)
  4909. ;; Tags
  4910. '(org-font-lock-add-tag-faces)
  4911. ;; Tags groups
  4912. (when (and org-group-tags org-tag-groups-alist)
  4913. (list (concat org-outline-regexp-bol ".+\\(:"
  4914. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4915. ":\\).*$")
  4916. '(1 'org-tag-group prepend)))
  4917. ;; Special keywords
  4918. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4919. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4920. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4921. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4922. ;; Emphasis
  4923. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  4924. ;; Checkboxes
  4925. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4926. 1 'org-checkbox prepend)
  4927. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4928. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4929. (0 (org-get-checkbox-statistics-face) prepend)))
  4930. ;; Description list items
  4931. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4932. 1 'org-list-dt prepend)
  4933. ;; Inline export snippets
  4934. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  4935. (1 'font-lock-comment-face t)
  4936. (2 'org-tag t)
  4937. (3 'font-lock-comment-face t))
  4938. ;; ARCHIVEd headings
  4939. (list (concat
  4940. org-outline-regexp-bol
  4941. "\\(.*:" org-archive-tag ":.*\\)")
  4942. '(1 'org-archived prepend))
  4943. ;; Specials
  4944. '(org-do-latex-and-related)
  4945. '(org-fontify-entities)
  4946. '(org-raise-scripts)
  4947. ;; Code
  4948. '(org-activate-code (1 'org-code t))
  4949. ;; COMMENT
  4950. (list (format
  4951. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  4952. org-todo-regexp
  4953. org-comment-string)
  4954. '(9 'org-special-keyword t))
  4955. ;; Blocks and meta lines
  4956. '(org-fontify-meta-lines-and-blocks)
  4957. '(org-fontify-inline-src-blocks)
  4958. ;; Citations. When an activate processor is specified, if
  4959. ;; specified, try loading it beforehand.
  4960. (progn
  4961. (unless (null org-cite-activate-processor)
  4962. (org-cite-try-load-processor org-cite-activate-processor))
  4963. '(org-cite-activate)))))
  4964. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  4965. (run-hooks 'org-font-lock-set-keywords-hook)
  4966. ;; Now set the full font-lock-keywords
  4967. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  4968. (setq-local font-lock-defaults
  4969. '(org-font-lock-keywords t nil nil backward-paragraph))
  4970. (setq-local font-lock-extend-after-change-region-function
  4971. #'org-fontify-extend-region)
  4972. (kill-local-variable 'font-lock-keywords)
  4973. nil))
  4974. (defun org-toggle-pretty-entities ()
  4975. "Toggle the composition display of entities as UTF8 characters."
  4976. (interactive)
  4977. (setq-local org-pretty-entities (not org-pretty-entities))
  4978. (org-restart-font-lock)
  4979. (if org-pretty-entities
  4980. (message "Entities are now displayed as UTF8 characters")
  4981. (save-restriction
  4982. (widen)
  4983. (decompose-region (point-min) (point-max))
  4984. (message "Entities are now displayed as plain text"))))
  4985. (defvar-local org-custom-properties-overlays nil
  4986. "List of overlays used for custom properties.")
  4987. (defun org-toggle-custom-properties-visibility ()
  4988. "Display or hide properties in `org-custom-properties'."
  4989. (interactive)
  4990. (if org-custom-properties-overlays
  4991. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  4992. (setq org-custom-properties-overlays nil))
  4993. (when org-custom-properties
  4994. (org-with-wide-buffer
  4995. (goto-char (point-min))
  4996. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  4997. (while (re-search-forward regexp nil t)
  4998. (let ((end (cdr (save-match-data (org-get-property-block)))))
  4999. (when (and end (< (point) end))
  5000. ;; Hide first custom property in current drawer.
  5001. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5002. (overlay-put o 'invisible t)
  5003. (overlay-put o 'org-custom-property t)
  5004. (push o org-custom-properties-overlays))
  5005. ;; Hide additional custom properties in the same drawer.
  5006. (while (re-search-forward regexp end t)
  5007. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5008. (overlay-put o 'invisible t)
  5009. (overlay-put o 'org-custom-property t)
  5010. (push o org-custom-properties-overlays)))))
  5011. ;; Each entry is limited to a single property drawer.
  5012. (outline-next-heading)))))))
  5013. (defun org-fontify-entities (limit)
  5014. "Find an entity to fontify."
  5015. (let (ee)
  5016. (when org-pretty-entities
  5017. (catch 'match
  5018. ;; "\_ "-family is left out on purpose. Only the first one,
  5019. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5020. ;; confusing when adding a second white space character.
  5021. (while (re-search-forward
  5022. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5023. limit t)
  5024. (when (and (not (org-at-comment-p))
  5025. (setq ee (org-entity-get (match-string 1)))
  5026. (= (length (nth 6 ee)) 1))
  5027. (let* ((end (if (equal (match-string 2) "{}")
  5028. (match-end 2)
  5029. (match-end 1))))
  5030. (add-text-properties
  5031. (match-beginning 0) end
  5032. (list 'font-lock-fontified t))
  5033. (compose-region (match-beginning 0) end
  5034. (nth 6 ee) nil)
  5035. (backward-char 1)
  5036. (throw 'match t))))
  5037. nil))))
  5038. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5039. "Fontify string S like in Org mode."
  5040. (with-temp-buffer
  5041. (insert s)
  5042. (let ((org-odd-levels-only odd-levels))
  5043. (org-mode)
  5044. (org-font-lock-ensure)
  5045. (if org-link-descriptive
  5046. (org-link-display-format
  5047. (buffer-string))
  5048. (buffer-string)))))
  5049. (defun org-get-level-face (n)
  5050. "Get the right face for match N in font-lock matching of headlines."
  5051. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5052. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5053. (org-f (if org-cycle-level-faces
  5054. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5055. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5056. (cond
  5057. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5058. ((eq n 2) org-f)
  5059. (t (unless org-level-color-stars-only org-f)))))
  5060. (defun org-face-from-face-or-color (context inherit face-or-color)
  5061. "Create a face list that inherits INHERIT, but sets the foreground color.
  5062. When FACE-OR-COLOR is not a string, just return it."
  5063. (if (stringp face-or-color)
  5064. (list :inherit inherit
  5065. (cdr (assoc context org-faces-easy-properties))
  5066. face-or-color)
  5067. face-or-color))
  5068. (defun org-get-todo-face (kwd)
  5069. "Get the right face for a TODO keyword KWD.
  5070. If KWD is a number, get the corresponding match group."
  5071. (when (numberp kwd) (setq kwd (match-string kwd)))
  5072. (or (org-face-from-face-or-color
  5073. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5074. (and (member kwd org-done-keywords) 'org-done)
  5075. 'org-todo))
  5076. (defun org-get-priority-face (priority)
  5077. "Get the right face for PRIORITY.
  5078. PRIORITY is a character."
  5079. (or (org-face-from-face-or-color
  5080. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5081. 'org-priority))
  5082. (defun org-get-tag-face (tag)
  5083. "Get the right face for TAG.
  5084. If TAG is a number, get the corresponding match group."
  5085. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5086. (or (org-face-from-face-or-color
  5087. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5088. 'org-tag)))
  5089. (defvar org-priority-regexp) ; defined later in the file
  5090. (defun org-font-lock-add-priority-faces (limit)
  5091. "Add the special priority faces."
  5092. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5093. (let ((beg (match-beginning 1))
  5094. (end (1+ (match-end 2))))
  5095. (add-face-text-property
  5096. beg end
  5097. (org-get-priority-face (string-to-char (match-string 2))))
  5098. (add-text-properties
  5099. beg end
  5100. (list 'font-lock-fontified t)))))
  5101. (defun org-font-lock-add-tag-faces (limit)
  5102. "Add the special tag faces."
  5103. (when (and org-tag-faces org-tags-special-faces-re)
  5104. (while (re-search-forward org-tags-special-faces-re limit t)
  5105. (add-face-text-property
  5106. (match-beginning 1)
  5107. (match-end 1)
  5108. (org-get-tag-face 1))
  5109. (add-text-properties (match-beginning 1) (match-end 1)
  5110. (list 'font-lock-fontified t))
  5111. (backward-char 1))))
  5112. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5113. "Remove fontification and activation overlays from links."
  5114. (font-lock-default-unfontify-region beg end)
  5115. (let* ((buffer-undo-list t)
  5116. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5117. (inhibit-modification-hooks t)
  5118. deactivate-mark buffer-file-name buffer-file-truename)
  5119. (decompose-region beg end)
  5120. (remove-text-properties beg end
  5121. '(mouse-face t keymap t org-linked-text t
  5122. invisible t intangible t
  5123. org-emphasis t))
  5124. (org-fold-core-update-optimisation beg end)
  5125. (org-remove-font-lock-display-properties beg end)))
  5126. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5127. ((raise 0.3) (height 0.7))
  5128. ((raise -0.5))
  5129. ((raise 0.5)))
  5130. "Display properties for showing superscripts and subscripts.")
  5131. (defun org-remove-font-lock-display-properties (beg end)
  5132. "Remove specific display properties that have been added by font lock.
  5133. The will remove the raise properties that are used to show superscripts
  5134. and subscripts."
  5135. (let (next prop)
  5136. (while (< beg end)
  5137. (setq next (next-single-property-change beg 'display nil end)
  5138. prop (get-text-property beg 'display))
  5139. (when (member prop org-script-display)
  5140. (put-text-property beg next 'display nil))
  5141. (setq beg next))))
  5142. (defun org-raise-scripts (limit)
  5143. "Add raise properties to sub/superscripts."
  5144. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5145. (re-search-forward
  5146. (if (eq org-use-sub-superscripts t)
  5147. org-match-substring-regexp
  5148. org-match-substring-with-braces-regexp)
  5149. limit t))
  5150. (let* ((pos (point)) table-p comment-p
  5151. (mpos (match-beginning 3))
  5152. (emph-p (get-text-property mpos 'org-emphasis))
  5153. (link-p (get-text-property mpos 'mouse-face))
  5154. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5155. (goto-char (point-at-bol))
  5156. (setq table-p (looking-at-p org-table-dataline-regexp)
  5157. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5158. (goto-char pos)
  5159. ;; Handle a_b^c
  5160. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5161. (unless (or comment-p emph-p link-p keyw-p)
  5162. (put-text-property (match-beginning 3) (match-end 0)
  5163. 'display
  5164. (if (equal (char-after (match-beginning 2)) ?^)
  5165. (nth (if table-p 3 1) org-script-display)
  5166. (nth (if table-p 2 0) org-script-display)))
  5167. (put-text-property (match-beginning 2) (match-end 3)
  5168. 'org-emphasis t)
  5169. (add-text-properties (match-beginning 2) (match-end 2)
  5170. (list 'invisible t))
  5171. (when (and (eq (char-after (match-beginning 3)) ?{)
  5172. (eq (char-before (match-end 3)) ?}))
  5173. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5174. (list 'invisible t))
  5175. (add-text-properties (1- (match-end 3)) (match-end 3)
  5176. (list 'invisible t))))
  5177. t)))
  5178. (defun org-remove-empty-overlays-at (pos)
  5179. "Remove outline overlays that do not contain non-white stuff."
  5180. (dolist (o (overlays-at pos))
  5181. (and (eq 'outline (overlay-get o 'invisible))
  5182. (not (string-match-p
  5183. "\\S-" (buffer-substring (overlay-start o)
  5184. (overlay-end o))))
  5185. (delete-overlay o))))
  5186. ;; FIXME: This function is unused.
  5187. (defun org-show-empty-lines-in-parent ()
  5188. "Move to the parent and re-show empty lines before visible headlines."
  5189. (save-excursion
  5190. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5191. (org-cycle-show-empty-lines context))))
  5192. (defun org-files-list ()
  5193. "Return `org-agenda-files' list, plus all open Org files.
  5194. This is useful for operations that need to scan all of a user's
  5195. open and agenda-wise Org files."
  5196. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5197. (dolist (buf (buffer-list))
  5198. (with-current-buffer buf
  5199. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5200. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5201. :test #'equal))))
  5202. files))
  5203. (defsubst org-entry-beginning-position ()
  5204. "Return the beginning position of the current entry."
  5205. (save-excursion (org-back-to-heading t) (point)))
  5206. (defsubst org-entry-end-position ()
  5207. "Return the end position of the current entry."
  5208. (save-excursion (outline-next-heading) (point)))
  5209. (defun org-subtree-end-visible-p ()
  5210. "Is the end of the current subtree visible?"
  5211. (pos-visible-in-window-p
  5212. (save-excursion (org-end-of-subtree t) (point))))
  5213. (defun org-first-headline-recenter ()
  5214. "Move cursor to the first headline and recenter the headline."
  5215. (let ((window (get-buffer-window)))
  5216. (when window
  5217. (goto-char (point-min))
  5218. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5219. (set-window-start window (line-beginning-position))))))
  5220. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5221. (defvar org-called-with-limited-levels nil
  5222. "Non-nil when `org-with-limited-levels' is currently active.")
  5223. ;;; Indirect buffer display of subtrees
  5224. (defvar org-indirect-dedicated-frame nil
  5225. "This is the frame being used for indirect tree display.")
  5226. (defvar org-last-indirect-buffer nil)
  5227. (defun org-tree-to-indirect-buffer (&optional arg)
  5228. "Create indirect buffer and narrow it to current subtree.
  5229. With a numerical prefix ARG, go up to this level and then take that tree.
  5230. If ARG is negative, go up that many levels.
  5231. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5232. indirect buffer previously made with this command, to avoid proliferation of
  5233. indirect buffers. However, when you call the command with a \
  5234. `\\[universal-argument]' prefix, or
  5235. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5236. so that you can work with several indirect buffers at the same time. If
  5237. `org-indirect-buffer-display' is `dedicated-frame', the \
  5238. `\\[universal-argument]' prefix also
  5239. requests that a new frame be made for the new buffer, so that the dedicated
  5240. frame is not changed."
  5241. (interactive "P")
  5242. (let ((cbuf (current-buffer))
  5243. (cwin (selected-window))
  5244. (pos (point))
  5245. beg end level heading ibuf)
  5246. (save-excursion
  5247. (org-back-to-heading t)
  5248. (when (numberp arg)
  5249. (setq level (org-outline-level))
  5250. (when (< arg 0) (setq arg (+ level arg)))
  5251. (while (> (setq level (org-outline-level)) arg)
  5252. (org-up-heading-safe)))
  5253. (setq beg (point)
  5254. heading (org-get-heading 'no-tags))
  5255. (org-end-of-subtree t t)
  5256. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5257. (setq end (point)))
  5258. (when (and (buffer-live-p org-last-indirect-buffer)
  5259. (not (eq org-indirect-buffer-display 'new-frame))
  5260. (not arg))
  5261. (kill-buffer org-last-indirect-buffer))
  5262. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5263. org-last-indirect-buffer ibuf)
  5264. (cond
  5265. ((or (eq org-indirect-buffer-display 'new-frame)
  5266. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5267. (select-frame (make-frame))
  5268. (delete-other-windows)
  5269. (pop-to-buffer-same-window ibuf)
  5270. (org-set-frame-title heading))
  5271. ((eq org-indirect-buffer-display 'dedicated-frame)
  5272. (raise-frame
  5273. (select-frame (or (and org-indirect-dedicated-frame
  5274. (frame-live-p org-indirect-dedicated-frame)
  5275. org-indirect-dedicated-frame)
  5276. (setq org-indirect-dedicated-frame (make-frame)))))
  5277. (delete-other-windows)
  5278. (pop-to-buffer-same-window ibuf)
  5279. (org-set-frame-title (concat "Indirect: " heading)))
  5280. ((eq org-indirect-buffer-display 'current-window)
  5281. (pop-to-buffer-same-window ibuf))
  5282. ((eq org-indirect-buffer-display 'other-window)
  5283. (pop-to-buffer ibuf))
  5284. (t (error "Invalid value")))
  5285. (narrow-to-region beg end)
  5286. (org-fold-show-all '(headings drawers blocks))
  5287. (goto-char pos)
  5288. (run-hook-with-args 'org-cycle-hook 'all)
  5289. (and (window-live-p cwin) (select-window cwin))))
  5290. (defun org-get-indirect-buffer (&optional buffer heading)
  5291. (setq buffer (or buffer (current-buffer)))
  5292. (let ((n 1) (base (buffer-name buffer)) bname)
  5293. (while (buffer-live-p
  5294. (get-buffer
  5295. (setq bname
  5296. (concat base "-"
  5297. (if heading (concat heading "-" (number-to-string n))
  5298. (number-to-string n))))))
  5299. (setq n (1+ n)))
  5300. (condition-case nil
  5301. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5302. ;; Decouple folding state. We need to do it manually since
  5303. ;; `make-indirect-buffer' does not run
  5304. ;; `clone-indirect-buffer-hook'.
  5305. (org-fold-core-decouple-indirect-buffer-folds)
  5306. ;; Return the buffer.
  5307. indirect-buffer)
  5308. (error (make-indirect-buffer buffer bname)))))
  5309. (defun org-set-frame-title (title)
  5310. "Set the title of the current frame to the string TITLE."
  5311. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5312. ;;;; Structure editing
  5313. ;;; Inserting headlines
  5314. (defun org--blank-before-heading-p (&optional parent)
  5315. "Non-nil when an empty line should precede a new heading here.
  5316. When optional argument PARENT is non-nil, consider parent
  5317. headline instead of current one."
  5318. (pcase (assq 'heading org-blank-before-new-entry)
  5319. (`(heading . auto)
  5320. (save-excursion
  5321. (org-with-limited-levels
  5322. (unless (and (org-before-first-heading-p)
  5323. (not (outline-next-heading)))
  5324. (org-back-to-heading t)
  5325. (when parent (org-up-heading-safe))
  5326. (cond ((not (bobp))
  5327. (org-previous-line-empty-p))
  5328. ((outline-next-heading)
  5329. (org-previous-line-empty-p))
  5330. ;; Ignore trailing spaces on last buffer line.
  5331. ((progn (skip-chars-backward " \t") (bolp))
  5332. (org-previous-line-empty-p))
  5333. (t nil))))))
  5334. (`(heading . ,value) value)
  5335. (_ nil)))
  5336. (defun org-insert-heading (&optional arg invisible-ok top)
  5337. "Insert a new heading or an item with the same depth at point.
  5338. If point is at the beginning of a heading, insert a new heading
  5339. or a new headline above the current one. When at the beginning
  5340. of a regular line of text, turn it into a heading.
  5341. If point is in the middle of a line, split it and create a new
  5342. headline with the text in the current line after point (see
  5343. `org-M-RET-may-split-line' on how to modify this behavior). As
  5344. a special case, on a headline, splitting can only happen on the
  5345. title itself. E.g., this excludes breaking stars or tags.
  5346. With a `\\[universal-argument]' prefix, set \
  5347. `org-insert-heading-respect-content' to
  5348. a non-nil value for the duration of the command. This forces the
  5349. insertion of a heading after the current subtree, independently
  5350. on the location of point.
  5351. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5352. insert the heading at the end of the tree
  5353. above the current heading. For example, if point is within a
  5354. 2nd-level heading, then it will insert a 2nd-level heading at
  5355. the end of the 1st-level parent subtree.
  5356. When INVISIBLE-OK is set, stop at invisible headlines when going
  5357. back. This is important for non-interactive uses of the
  5358. command.
  5359. When optional argument TOP is non-nil, insert a level 1 heading,
  5360. unconditionally."
  5361. (interactive "P")
  5362. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5363. (level (org-current-level))
  5364. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5365. (cond
  5366. ((or org-insert-heading-respect-content
  5367. (member arg '((4) (16)))
  5368. (and (not invisible-ok)
  5369. (invisible-p (max (1- (point)) (point-min)))))
  5370. ;; Position point at the location of insertion. Make sure we
  5371. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5372. (org-with-limited-levels
  5373. (if (not level) (outline-next-heading) ;before first headline
  5374. (org-back-to-heading invisible-ok)
  5375. (when (equal arg '(16)) (org-up-heading-safe))
  5376. (org-end-of-subtree)))
  5377. (unless (bolp) (insert "\n"))
  5378. (when (and blank? (save-excursion
  5379. (backward-char)
  5380. (org-before-first-heading-p)))
  5381. (insert "\n")
  5382. (backward-char))
  5383. (when (and (not level) (not (eobp)) (not (bobp)))
  5384. (when (org-at-heading-p) (insert "\n"))
  5385. (backward-char))
  5386. (unless (and blank? (org-previous-line-empty-p))
  5387. (org-N-empty-lines-before-current (if blank? 1 0)))
  5388. (insert stars " ")
  5389. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5390. ;; is visible.
  5391. (unless invisible-ok
  5392. (if (eq org-fold-core-style 'text-properties)
  5393. (cond
  5394. ((org-fold-folded-p (line-beginning-position) 'headline)
  5395. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5396. (t nil))
  5397. (pcase (get-char-property-and-overlay (point) 'invisible)
  5398. (`(outline . ,o)
  5399. (move-overlay o (overlay-start o) (line-end-position 0)))
  5400. (_ nil)))))
  5401. ;; At a headline...
  5402. ((org-at-heading-p)
  5403. (cond ((bolp)
  5404. (when blank? (save-excursion (insert "\n")))
  5405. (save-excursion (insert stars " \n"))
  5406. (unless (and blank? (org-previous-line-empty-p))
  5407. (org-N-empty-lines-before-current (if blank? 1 0)))
  5408. (end-of-line))
  5409. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5410. (org-match-line org-complex-heading-regexp)
  5411. (org-pos-in-match-range (point) 4))
  5412. ;; Grab the text that should moved to the new headline.
  5413. ;; Preserve tags.
  5414. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5415. (if (looking-at "[ \t]*$") (replace-match "")
  5416. (org-align-tags))
  5417. (end-of-line)
  5418. (when blank? (insert "\n"))
  5419. (insert "\n" stars " ")
  5420. (when (org-string-nw-p split) (insert split))))
  5421. (t
  5422. (end-of-line)
  5423. (when blank? (insert "\n"))
  5424. (insert "\n" stars " "))))
  5425. ;; On regular text, turn line into a headline or split, if
  5426. ;; appropriate.
  5427. ((bolp)
  5428. (insert stars " ")
  5429. (unless (and blank? (org-previous-line-empty-p))
  5430. (org-N-empty-lines-before-current (if blank? 1 0))))
  5431. (t
  5432. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5433. (end-of-line))
  5434. (insert "\n" stars " ")
  5435. (unless (and blank? (org-previous-line-empty-p))
  5436. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5437. (run-hooks 'org-insert-heading-hook))
  5438. (defun org-N-empty-lines-before-current (n)
  5439. "Make the number of empty lines before current exactly N.
  5440. So this will delete or add empty lines."
  5441. (let ((column (current-column)))
  5442. (beginning-of-line)
  5443. (unless (bobp)
  5444. (let ((start (save-excursion
  5445. (skip-chars-backward " \r\t\n")
  5446. (line-end-position))))
  5447. (delete-region start (line-end-position 0))))
  5448. (insert (make-string n ?\n))
  5449. (move-to-column column)))
  5450. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5451. "Return the heading of the current entry, without the stars.
  5452. When NO-TAGS is non-nil, don't include tags.
  5453. When NO-TODO is non-nil, don't include TODO keywords.
  5454. When NO-PRIORITY is non-nil, don't include priority cookie.
  5455. When NO-COMMENT is non-nil, don't include COMMENT string.
  5456. Return nil before first heading."
  5457. (unless (org-before-first-heading-p)
  5458. (save-excursion
  5459. (org-back-to-heading t)
  5460. (let ((case-fold-search nil))
  5461. (looking-at org-complex-heading-regexp)
  5462. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5463. ;; returned text may be invisible. Clear it up.
  5464. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5465. (let ((todo (and (not no-todo) (match-string 2)))
  5466. (priority (and (not no-priority) (match-string 3)))
  5467. (headline (pcase (match-string 4)
  5468. (`nil "")
  5469. ((and (guard no-comment) h)
  5470. (replace-regexp-in-string
  5471. (eval-when-compile
  5472. (format "\\`%s[ \t]+" org-comment-string))
  5473. "" h))
  5474. (h h)))
  5475. (tags (and (not no-tags) (match-string 5))))
  5476. ;; Restore cleared optimisation.
  5477. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5478. (mapconcat #'identity
  5479. (delq nil (list todo priority headline tags))
  5480. " "))))))
  5481. (defun org-heading-components ()
  5482. "Return the components of the current heading.
  5483. This is a list with the following elements:
  5484. - the level as an integer
  5485. - the reduced level, different if `org-odd-levels-only' is set.
  5486. - the TODO keyword, or nil
  5487. - the priority character, like ?A, or nil if no priority is given
  5488. - the headline text itself, or the tags string if no headline text
  5489. - the tags string, or nil."
  5490. (save-excursion
  5491. (org-back-to-heading t)
  5492. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5493. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5494. (prog1
  5495. (list (length (match-string 1))
  5496. (org-reduced-level (length (match-string 1)))
  5497. (match-string-no-properties 2)
  5498. (and (match-end 3) (aref (match-string 3) 2))
  5499. (match-string-no-properties 4)
  5500. (match-string-no-properties 5))
  5501. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5502. (defun org-get-entry ()
  5503. "Get the entry text, after heading, entire subtree."
  5504. (save-excursion
  5505. (org-back-to-heading t)
  5506. (filter-buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  5507. (defun org-edit-headline (&optional heading)
  5508. "Edit the current headline.
  5509. Set it to HEADING when provided."
  5510. (interactive)
  5511. (org-with-wide-buffer
  5512. (org-back-to-heading t)
  5513. (let ((case-fold-search nil))
  5514. (when (looking-at org-complex-heading-regexp)
  5515. (let* ((old (match-string-no-properties 4))
  5516. (new (save-match-data
  5517. (org-trim (or heading (read-string "Edit: " old))))))
  5518. (unless (equal old new)
  5519. (if old (replace-match new t t nil 4)
  5520. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5521. (insert " " new))
  5522. (org-align-tags)
  5523. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5524. (defun org-insert-heading-after-current ()
  5525. "Insert a new heading with same level as current, after current subtree."
  5526. (interactive)
  5527. (org-back-to-heading)
  5528. (org-insert-heading)
  5529. (org-move-subtree-down)
  5530. (end-of-line 1))
  5531. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5532. "Insert heading with `org-insert-heading-respect-content' set to t."
  5533. (interactive)
  5534. (org-insert-heading '(4) invisible-ok))
  5535. (defun org-insert-todo-heading-respect-content (&optional force-state)
  5536. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5537. (interactive)
  5538. (org-insert-todo-heading force-state '(4)))
  5539. (defun org-insert-todo-heading (arg &optional force-heading)
  5540. "Insert a new heading with the same level and TODO state as current heading.
  5541. If the heading has no TODO state, or if the state is DONE, use
  5542. the first state (TODO by default). Also with one prefix arg,
  5543. force first state. With two prefix args, force inserting at the
  5544. end of the parent subtree.
  5545. When called at a plain list item, insert a new item with an
  5546. unchecked check box."
  5547. (interactive "P")
  5548. (when (or force-heading (not (org-insert-item 'checkbox)))
  5549. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5550. force-heading))
  5551. (save-excursion
  5552. (org-forward-heading-same-level -1)
  5553. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5554. (let* ((new-mark-x
  5555. (if (or (equal arg '(4))
  5556. (not (match-beginning 2))
  5557. (member (match-string 2) org-done-keywords))
  5558. (car org-todo-keywords-1)
  5559. (match-string 2)))
  5560. (new-mark
  5561. (or
  5562. (run-hook-with-args-until-success
  5563. 'org-todo-get-default-hook new-mark-x nil)
  5564. new-mark-x)))
  5565. (beginning-of-line 1)
  5566. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5567. (if org-treat-insert-todo-heading-as-state-change
  5568. (org-todo new-mark)
  5569. (insert new-mark " "))))
  5570. (when org-provide-todo-statistics
  5571. (org-update-parent-todo-statistics))))
  5572. (defun org-insert-subheading (arg)
  5573. "Insert a new subheading and demote it.
  5574. Works for outline headings and for plain lists alike."
  5575. (interactive "P")
  5576. (org-insert-heading arg)
  5577. (cond
  5578. ((org-at-heading-p) (org-do-demote))
  5579. ((org-at-item-p) (org-indent-item))))
  5580. (defun org-insert-todo-subheading (arg)
  5581. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5582. Works for outline headings and for plain lists alike."
  5583. (interactive "P")
  5584. (org-insert-todo-heading arg)
  5585. (cond
  5586. ((org-at-heading-p) (org-do-demote))
  5587. ((org-at-item-p) (org-indent-item))))
  5588. ;;; Promotion and Demotion
  5589. (defvar org-after-demote-entry-hook nil
  5590. "Hook run after an entry has been demoted.
  5591. The cursor will be at the beginning of the entry.
  5592. When a subtree is being demoted, the hook will be called for each node.")
  5593. (defvar org-after-promote-entry-hook nil
  5594. "Hook run after an entry has been promoted.
  5595. The cursor will be at the beginning of the entry.
  5596. When a subtree is being promoted, the hook will be called for each node.")
  5597. (defun org-promote-subtree ()
  5598. "Promote the entire subtree.
  5599. See also `org-promote'."
  5600. (interactive)
  5601. (save-excursion
  5602. (org-back-to-heading t)
  5603. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5604. (org-with-limited-levels (org-map-tree 'org-promote))))
  5605. (org-fix-position-after-promote))
  5606. (defun org-demote-subtree ()
  5607. "Demote the entire subtree.
  5608. See `org-demote' and `org-promote'."
  5609. (interactive)
  5610. (save-excursion
  5611. (org-back-to-heading t)
  5612. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5613. (org-with-limited-levels (org-map-tree 'org-demote))))
  5614. (org-fix-position-after-promote))
  5615. (defun org-do-promote ()
  5616. "Promote the current heading higher up the tree.
  5617. If the region is active in `transient-mark-mode', promote all
  5618. headings in the region."
  5619. (interactive)
  5620. (save-excursion
  5621. (if (org-region-active-p)
  5622. (org-map-region 'org-promote (region-beginning) (region-end))
  5623. (org-promote)))
  5624. (org-fix-position-after-promote))
  5625. (defun org-do-demote ()
  5626. "Demote the current heading lower down the tree.
  5627. If the region is active in `transient-mark-mode', demote all
  5628. headings in the region."
  5629. (interactive)
  5630. (save-excursion
  5631. (if (org-region-active-p)
  5632. (org-map-region 'org-demote (region-beginning) (region-end))
  5633. (org-demote)))
  5634. (org-fix-position-after-promote))
  5635. (defun org-fix-position-after-promote ()
  5636. "Fix cursor position and indentation after demoting/promoting."
  5637. (let ((pos (point)))
  5638. (when (save-excursion
  5639. (beginning-of-line)
  5640. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5641. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5642. (cond ((eobp) (insert " "))
  5643. ((eolp) (insert " "))
  5644. ((equal (char-after) ?\s) (forward-char 1))))))
  5645. (defun org-current-level ()
  5646. "Return the level of the current entry, or nil if before the first headline.
  5647. The level is the number of stars at the beginning of the
  5648. headline. Use `org-reduced-level' to remove the effect of
  5649. `org-odd-levels'. Unlike to `org-outline-level', this function
  5650. ignores inlinetasks."
  5651. (let ((level (org-with-limited-levels (org-outline-level))))
  5652. (and (> level 0) level)))
  5653. (defun org-get-previous-line-level ()
  5654. "Return the outline depth of the last headline before the current line.
  5655. Returns 0 for the first headline in the buffer, and nil if before the
  5656. first headline."
  5657. (and (org-current-level)
  5658. (or (and (/= (line-beginning-position) (point-min))
  5659. (save-excursion (beginning-of-line 0) (org-current-level)))
  5660. 0)))
  5661. (defun org-reduced-level (l)
  5662. "Compute the effective level of a heading.
  5663. This takes into account the setting of `org-odd-levels-only'."
  5664. (cond
  5665. ((zerop l) 0)
  5666. (org-odd-levels-only (1+ (floor (/ l 2))))
  5667. (t l)))
  5668. (defun org-level-increment ()
  5669. "Return the number of stars that will be added or removed at a
  5670. time to headlines when structure editing, based on the value of
  5671. `org-odd-levels-only'."
  5672. (if org-odd-levels-only 2 1))
  5673. (defun org-get-valid-level (level &optional change)
  5674. "Rectify a level change under the influence of `org-odd-levels-only'.
  5675. LEVEL is a current level, CHANGE is by how much the level should
  5676. be modified. Even if CHANGE is nil, LEVEL may be returned
  5677. modified because even level numbers will become the next higher
  5678. odd number. Returns values greater than 0."
  5679. (if org-odd-levels-only
  5680. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5681. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5682. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5683. (max 1 (+ level (or change 0)))))
  5684. (defun org-promote ()
  5685. "Promote the current heading higher up the tree."
  5686. (org-with-wide-buffer
  5687. (org-back-to-heading t)
  5688. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5689. after-change-functions))
  5690. (level (save-match-data (funcall outline-level)))
  5691. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5692. (diff (abs (- level (length up-head) -1))))
  5693. (cond
  5694. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5695. (replace-match "# " nil t))
  5696. ((= level 1)
  5697. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5698. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5699. (unless (= level 1)
  5700. (when org-auto-align-tags (org-align-tags))
  5701. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5702. (run-hooks 'org-after-promote-entry-hook))))
  5703. (defun org-demote ()
  5704. "Demote the current heading lower down the tree."
  5705. (org-with-wide-buffer
  5706. (org-back-to-heading t)
  5707. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5708. after-change-functions))
  5709. (level (save-match-data (funcall outline-level)))
  5710. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5711. (diff (abs (- level (length down-head) -1))))
  5712. (org-fold-core-ignore-fragility-checks
  5713. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5714. (when org-auto-align-tags (org-align-tags))
  5715. (when org-adapt-indentation (org-fixup-indentation diff)))
  5716. (run-hooks 'org-after-demote-entry-hook))))
  5717. (defun org-cycle-level ()
  5718. "Cycle the level of an empty headline through possible states.
  5719. This goes first to child, then to parent, level, then up the hierarchy.
  5720. After top level, it switches back to sibling level."
  5721. (interactive)
  5722. (let ((org-adapt-indentation nil))
  5723. (when (org-point-at-end-of-empty-headline)
  5724. (setq this-command 'org-cycle-level) ; Only needed for caching
  5725. (let ((cur-level (org-current-level))
  5726. (prev-level (org-get-previous-line-level)))
  5727. (cond
  5728. ;; If first headline in file, promote to top-level.
  5729. ((= prev-level 0)
  5730. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5731. do (org-do-promote)))
  5732. ;; If same level as prev, demote one.
  5733. ((= prev-level cur-level)
  5734. (org-do-demote))
  5735. ;; If parent is top-level, promote to top level if not already.
  5736. ((= prev-level 1)
  5737. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5738. do (org-do-promote)))
  5739. ;; If top-level, return to prev-level.
  5740. ((= cur-level 1)
  5741. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5742. do (org-do-demote)))
  5743. ;; If less than prev-level, promote one.
  5744. ((< cur-level prev-level)
  5745. (org-do-promote))
  5746. ;; If deeper than prev-level, promote until higher than
  5747. ;; prev-level.
  5748. ((> cur-level prev-level)
  5749. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5750. do (org-do-promote))))
  5751. t))))
  5752. (defun org-map-tree (fun)
  5753. "Call FUN for every heading underneath the current one."
  5754. (org-back-to-heading t)
  5755. (let ((level (funcall outline-level)))
  5756. (save-excursion
  5757. (funcall fun)
  5758. (while (and (progn
  5759. (outline-next-heading)
  5760. (> (funcall outline-level) level))
  5761. (not (eobp)))
  5762. (funcall fun)))))
  5763. (defun org-map-region (fun beg end)
  5764. "Call FUN for every heading between BEG and END."
  5765. (let ((org-ignore-region t))
  5766. (save-excursion
  5767. (setq end (copy-marker end))
  5768. (goto-char beg)
  5769. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5770. (< (point) end))
  5771. (funcall fun))
  5772. (while (and (progn
  5773. (outline-next-heading)
  5774. (< (point) end))
  5775. (not (eobp)))
  5776. (funcall fun)))))
  5777. (defun org-fixup-indentation (diff)
  5778. "Change the indentation in the current entry by DIFF.
  5779. DIFF is an integer. Indentation is done according to the
  5780. following rules:
  5781. - Planning information and property drawers are always indented
  5782. according to the new level of the headline;
  5783. - Footnote definitions and their contents are ignored;
  5784. - Inlinetasks' boundaries are not shifted;
  5785. - Empty lines are ignored;
  5786. - Other lines' indentation are shifted by DIFF columns, unless
  5787. it would introduce a structural change in the document, in
  5788. which case no shifting is done at all.
  5789. Assume point is at a heading or an inlinetask beginning."
  5790. (org-with-wide-buffer
  5791. (narrow-to-region (line-beginning-position)
  5792. (save-excursion
  5793. (if (org-with-limited-levels (org-at-heading-p))
  5794. (org-with-limited-levels (outline-next-heading))
  5795. (org-inlinetask-goto-end))
  5796. (point)))
  5797. (forward-line)
  5798. ;; Indent properly planning info and property drawer.
  5799. (when (looking-at-p org-planning-line-re)
  5800. (org-indent-line)
  5801. (forward-line))
  5802. (when (looking-at org-property-drawer-re)
  5803. (goto-char (match-end 0))
  5804. (forward-line)
  5805. (org-indent-region (match-beginning 0) (match-end 0)))
  5806. (when (looking-at org-logbook-drawer-re)
  5807. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5808. (col (+ (current-indentation) diff)))
  5809. (when (wholenump col)
  5810. (while (< (point) end-marker)
  5811. (if (natnump diff)
  5812. (insert (make-string diff 32))
  5813. (delete-char (abs diff)))
  5814. (forward-line)))))
  5815. (catch 'no-shift
  5816. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5817. (throw 'no-shift nil))
  5818. ;; If DIFF is negative, first check if a shift is possible at all
  5819. ;; (e.g., it doesn't break structure). This can only happen if
  5820. ;; some contents are not properly indented.
  5821. (let ((case-fold-search t))
  5822. (when (< diff 0)
  5823. (let ((diff (- diff))
  5824. (forbidden-re (concat org-outline-regexp
  5825. "\\|"
  5826. (substring org-footnote-definition-re 1))))
  5827. (save-excursion
  5828. (while (not (eobp))
  5829. (cond
  5830. ((looking-at-p "[ \t]*$") (forward-line))
  5831. ((and (looking-at-p org-footnote-definition-re)
  5832. (let ((e (org-element-at-point)))
  5833. (and (eq (org-element-type e) 'footnote-definition)
  5834. (goto-char (org-element-property :end e))))))
  5835. ((looking-at-p org-outline-regexp) (forward-line))
  5836. ;; Give up if shifting would move before column 0 or
  5837. ;; if it would introduce a headline or a footnote
  5838. ;; definition.
  5839. (t
  5840. (skip-chars-forward " \t")
  5841. (let ((ind (current-column)))
  5842. (when (or (< ind diff)
  5843. (and (= ind diff) (looking-at-p forbidden-re)))
  5844. (throw 'no-shift nil)))
  5845. ;; Ignore contents of example blocks and source
  5846. ;; blocks if their indentation is meant to be
  5847. ;; preserved. Jump to block's closing line.
  5848. (beginning-of-line)
  5849. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5850. (let ((e (org-element-at-point)))
  5851. (and (memq (org-element-type e)
  5852. '(example-block src-block))
  5853. (or org-src-preserve-indentation
  5854. (org-element-property :preserve-indent e))
  5855. (goto-char (org-element-property :end e))
  5856. (progn (skip-chars-backward " \r\t\n")
  5857. (beginning-of-line)
  5858. t))))
  5859. (forward-line))))))))
  5860. ;; Shift lines but footnote definitions, inlinetasks boundaries
  5861. ;; by DIFF. Also skip contents of source or example blocks
  5862. ;; when indentation is meant to be preserved.
  5863. (while (not (eobp))
  5864. (cond
  5865. ((and (looking-at-p org-footnote-definition-re)
  5866. (let ((e (org-element-at-point)))
  5867. (and (eq (org-element-type e) 'footnote-definition)
  5868. (goto-char (org-element-property :end e))))))
  5869. ((looking-at-p org-outline-regexp) (forward-line))
  5870. ((looking-at-p "[ \t]*$") (forward-line))
  5871. (t
  5872. (indent-line-to (+ (current-indentation) diff))
  5873. (beginning-of-line)
  5874. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5875. (let ((e (org-element-at-point)))
  5876. (and (memq (org-element-type e)
  5877. '(example-block src-block))
  5878. (or org-src-preserve-indentation
  5879. (org-element-property :preserve-indent e))
  5880. (goto-char (org-element-property :end e))
  5881. (progn (skip-chars-backward " \r\t\n")
  5882. (beginning-of-line)
  5883. t))))
  5884. (forward-line)))))))))
  5885. (defun org-convert-to-odd-levels ()
  5886. "Convert an Org file with all levels allowed to one with odd levels.
  5887. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  5888. level 5 etc."
  5889. (interactive)
  5890. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  5891. (let ((outline-level 'org-outline-level)
  5892. (org-odd-levels-only nil) n)
  5893. (save-excursion
  5894. (goto-char (point-min))
  5895. (while (re-search-forward "^\\*\\*+ " nil t)
  5896. (setq n (- (length (match-string 0)) 2))
  5897. (while (>= (setq n (1- n)) 0)
  5898. (org-demote))
  5899. (end-of-line 1))))))
  5900. (defun org-convert-to-oddeven-levels ()
  5901. "Convert an Org file with only odd levels to one with odd/even levels.
  5902. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  5903. file contains a section with an even level, conversion would
  5904. destroy the structure of the file. An error is signaled in this
  5905. case."
  5906. (interactive)
  5907. (goto-char (point-min))
  5908. ;; First check if there are no even levels
  5909. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  5910. (org-fold-show-set-visibility 'canonical)
  5911. (error "Not all levels are odd in this file. Conversion not possible"))
  5912. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  5913. (let ((outline-regexp org-outline-regexp)
  5914. (outline-level 'org-outline-level)
  5915. (org-odd-levels-only nil) n)
  5916. (save-excursion
  5917. (goto-char (point-min))
  5918. (while (re-search-forward "^\\*\\*+ " nil t)
  5919. (setq n (/ (1- (length (match-string 0))) 2))
  5920. (while (>= (setq n (1- n)) 0)
  5921. (org-promote))
  5922. (end-of-line 1))))))
  5923. (defun org-tr-level (n)
  5924. "Make N odd if required."
  5925. (if org-odd-levels-only (1+ (/ n 2)) n))
  5926. ;;; Vertical tree motion, cutting and pasting of subtrees
  5927. (defun org-move-subtree-up (&optional arg)
  5928. "Move the current subtree up past ARG headlines of the same level."
  5929. (interactive "p")
  5930. (org-move-subtree-down (- (prefix-numeric-value arg))))
  5931. (defun org-clean-visibility-after-subtree-move ()
  5932. "Fix visibility issues after moving a subtree."
  5933. ;; First, find a reasonable region to look at:
  5934. ;; Start two siblings above, end three below
  5935. (let* ((beg (save-excursion
  5936. (and (org-get-previous-sibling)
  5937. (org-get-previous-sibling))
  5938. (point)))
  5939. (end (save-excursion
  5940. (and (org-get-next-sibling)
  5941. (org-get-next-sibling)
  5942. (org-get-next-sibling))
  5943. (if (org-at-heading-p)
  5944. (point-at-eol)
  5945. (point))))
  5946. (level (looking-at "\\*+"))
  5947. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5948. (save-excursion
  5949. (save-restriction
  5950. (narrow-to-region beg end)
  5951. (when re
  5952. ;; Properly fold already folded siblings
  5953. (goto-char (point-min))
  5954. (while (re-search-forward re nil t)
  5955. (when (and (not (org-invisible-p))
  5956. (org-invisible-p (line-end-position)))
  5957. (org-fold-heading nil))))
  5958. (org-cycle-hide-drawers 'all)
  5959. (org-cycle-show-empty-lines 'overview)))))
  5960. (defun org-move-subtree-down (&optional arg)
  5961. "Move the current subtree down past ARG headlines of the same level."
  5962. (interactive "p")
  5963. (setq arg (prefix-numeric-value arg))
  5964. (org-preserve-local-variables
  5965. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  5966. 'org-get-previous-sibling))
  5967. (ins-point (make-marker))
  5968. (cnt (abs arg))
  5969. (col (current-column))
  5970. beg end txt folded)
  5971. ;; Select the tree
  5972. (org-back-to-heading)
  5973. (setq beg (point))
  5974. (save-match-data
  5975. (save-excursion (outline-end-of-heading)
  5976. (setq folded (org-invisible-p)))
  5977. (progn (org-end-of-subtree nil t)
  5978. (unless (eobp) (backward-char))))
  5979. (outline-next-heading)
  5980. (setq end (point))
  5981. (goto-char beg)
  5982. ;; Find insertion point, with error handling
  5983. (while (> cnt 0)
  5984. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  5985. (goto-char beg)
  5986. (user-error "Cannot move past superior level or buffer limit"))
  5987. (setq cnt (1- cnt)))
  5988. (when (> arg 0)
  5989. ;; Moving forward - still need to move over subtree
  5990. (org-end-of-subtree t t)
  5991. (save-excursion
  5992. (org-back-over-empty-lines)
  5993. (or (bolp) (newline))))
  5994. (move-marker ins-point (point))
  5995. (setq txt (buffer-substring beg end))
  5996. (org-save-markers-in-region beg end)
  5997. (delete-region beg end)
  5998. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  5999. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6000. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6001. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6002. (let ((bbb (point)))
  6003. (insert-before-markers txt)
  6004. (org-reinstall-markers-in-region bbb)
  6005. (move-marker ins-point bbb))
  6006. (or (bolp) (insert "\n"))
  6007. (goto-char ins-point)
  6008. (org-skip-whitespace)
  6009. (move-marker ins-point nil)
  6010. (if folded
  6011. (org-fold-subtree t)
  6012. (org-fold-show-entry)
  6013. (org-fold-show-children))
  6014. (org-clean-visibility-after-subtree-move)
  6015. ;; move back to the initial column we were at
  6016. (move-to-column col))))
  6017. (defvar org-subtree-clip ""
  6018. "Clipboard for cut and paste of subtrees.
  6019. This is actually only a copy of the kill, because we use the normal kill
  6020. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6021. (defvar org-subtree-clip-folded nil
  6022. "Was the last copied subtree folded?
  6023. This is used to fold the tree back after pasting.")
  6024. (defun org-cut-subtree (&optional n)
  6025. "Cut the current subtree into the clipboard.
  6026. With prefix arg N, cut this many sequential subtrees.
  6027. This is a short-hand for marking the subtree and then cutting it."
  6028. (interactive "p")
  6029. (org-copy-subtree n 'cut))
  6030. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6031. "Copy the current subtree into the clipboard.
  6032. With prefix arg N, copy this many sequential subtrees.
  6033. This is a short-hand for marking the subtree and then copying it.
  6034. If CUT is non-nil, actually cut the subtree.
  6035. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6036. of some markers in the region, even if CUT is non-nil. This is
  6037. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6038. (interactive "p")
  6039. (org-preserve-local-variables
  6040. (let (beg end folded (beg0 (point)))
  6041. (if (called-interactively-p 'any)
  6042. (org-back-to-heading nil) ; take what looks like a subtree
  6043. (org-back-to-heading t)) ; take what is really there
  6044. (setq beg (point))
  6045. (skip-chars-forward " \t\r\n")
  6046. (save-match-data
  6047. (if nosubtrees
  6048. (outline-next-heading)
  6049. (save-excursion (outline-end-of-heading)
  6050. (setq folded (org-invisible-p)))
  6051. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6052. (org-end-of-subtree t t)))
  6053. ;; Include the end of an inlinetask
  6054. (when (and (featurep 'org-inlinetask)
  6055. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6056. "END[ \t]*$")))
  6057. (end-of-line))
  6058. (setq end (point))
  6059. (goto-char beg0)
  6060. (when (> end beg)
  6061. (setq org-subtree-clip-folded folded)
  6062. (when (or cut force-store-markers)
  6063. (org-save-markers-in-region beg end))
  6064. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6065. (setq org-subtree-clip (current-kill 0))
  6066. (message "%s: Subtree(s) with %d characters"
  6067. (if cut "Cut" "Copied")
  6068. (length org-subtree-clip))))))
  6069. (defun org-paste-subtree (&optional level tree for-yank remove)
  6070. "Paste the clipboard as a subtree, with modification of headline level.
  6071. The entire subtree is promoted or demoted in order to match a new headline
  6072. level.
  6073. If the cursor is at the beginning of a headline, the same level as
  6074. that headline is used to paste the tree.
  6075. If not, the new level is derived from the *visible* headings
  6076. before and after the insertion point, and taken to be the inferior headline
  6077. level of the two. So if the previous visible heading is level 3 and the
  6078. next is level 4 (or vice versa), level 4 will be used for insertion.
  6079. This makes sure that the subtree remains an independent subtree and does
  6080. not swallow low level entries.
  6081. You can also force a different level, either by using a numeric prefix
  6082. argument, or by inserting the heading marker by hand. For example, if the
  6083. cursor is after \"*****\", then the tree will be shifted to level 5.
  6084. If optional TREE is given, use this text instead of the kill ring.
  6085. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6086. move back over whitespace before inserting, and move point to the end of
  6087. the inserted text when done.
  6088. When REMOVE is non-nil, remove the subtree from the clipboard."
  6089. (interactive "P")
  6090. (setq tree (or tree (and kill-ring (current-kill 0))))
  6091. (unless (org-kill-is-subtree-p tree)
  6092. (user-error
  6093. (substitute-command-keys
  6094. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6095. (org-with-limited-levels
  6096. (org-fold-core-ignore-fragility-checks
  6097. (let* ((visp (not (org-invisible-p)))
  6098. (txt tree)
  6099. (old-level (if (string-match org-outline-regexp-bol txt)
  6100. (- (match-end 0) (match-beginning 0) 1)
  6101. -1))
  6102. (force-level
  6103. (cond
  6104. (level (prefix-numeric-value level))
  6105. ;; When point is after the stars in an otherwise empty
  6106. ;; headline, use the number of stars as the forced level.
  6107. ((and (org-match-line "^\\*+[ \t]*$")
  6108. (not (eq ?* (char-after))))
  6109. (org-outline-level))
  6110. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6111. (previous-level
  6112. (save-excursion
  6113. (org-previous-visible-heading 1)
  6114. (if (org-at-heading-p) (org-outline-level) 1)))
  6115. (next-level
  6116. (save-excursion
  6117. (if (org-at-heading-p) (org-outline-level)
  6118. (org-next-visible-heading 1)
  6119. (if (org-at-heading-p) (org-outline-level) 1))))
  6120. (new-level (or force-level (max previous-level next-level)))
  6121. (shift (if (or (= old-level -1)
  6122. (= new-level -1)
  6123. (= old-level new-level))
  6124. 0
  6125. (- new-level old-level)))
  6126. (delta (if (> shift 0) -1 1))
  6127. (func (if (> shift 0) #'org-demote #'org-promote))
  6128. (org-odd-levels-only nil)
  6129. beg end newend)
  6130. ;; Remove the forced level indicator.
  6131. (when (and force-level (not level))
  6132. (delete-region (line-beginning-position) (point)))
  6133. ;; Paste before the next visible heading or at end of buffer,
  6134. ;; unless point is at the beginning of a headline.
  6135. (unless (and (bolp) (org-at-heading-p))
  6136. (org-next-visible-heading 1)
  6137. (unless (bolp) (insert "\n")))
  6138. (setq beg (point))
  6139. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6140. ;; is inserted and then promoted.
  6141. (combine-change-calls beg beg
  6142. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6143. (insert-before-markers txt)
  6144. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6145. (setq newend (point))
  6146. (org-reinstall-markers-in-region beg)
  6147. (setq end (point))
  6148. (goto-char beg)
  6149. (skip-chars-forward " \t\n\r")
  6150. (setq beg (point))
  6151. (when (and (org-invisible-p) visp)
  6152. (save-excursion (org-fold-heading nil)))
  6153. ;; Shift if necessary.
  6154. (unless (= shift 0)
  6155. (save-restriction
  6156. (narrow-to-region beg end)
  6157. (while (not (= shift 0))
  6158. (org-map-region func (point-min) (point-max))
  6159. (setq shift (+ delta shift)))
  6160. (goto-char (point-min))
  6161. (setq newend (point-max)))))
  6162. (when (or for-yank (called-interactively-p 'interactive))
  6163. (message "Clipboard pasted as level %d subtree" new-level))
  6164. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6165. kill-ring
  6166. (equal org-subtree-clip (current-kill 0))
  6167. org-subtree-clip-folded)
  6168. ;; The tree was folded before it was killed/copied
  6169. (org-fold-subtree t))
  6170. (when for-yank (goto-char newend))
  6171. (when remove (pop kill-ring))))))
  6172. (defun org-kill-is-subtree-p (&optional txt)
  6173. "Check if the current kill is an outline subtree, or a set of trees.
  6174. Returns nil if kill does not start with a headline, or if the first
  6175. headline level is not the largest headline level in the tree.
  6176. So this will actually accept several entries of equal levels as well,
  6177. which is OK for `org-paste-subtree'.
  6178. If optional TXT is given, check this string instead of the current kill."
  6179. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6180. (re (org-get-limited-outline-regexp))
  6181. (^re (concat "^" re))
  6182. (start-level (and kill
  6183. (string-match
  6184. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6185. kill)
  6186. (- (match-end 2) (match-beginning 2) 1)))
  6187. (start (1+ (or (match-beginning 2) -1))))
  6188. (if (not start-level)
  6189. (progn
  6190. nil) ;; does not even start with a heading
  6191. (catch 'exit
  6192. (while (setq start (string-match ^re kill (1+ start)))
  6193. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6194. (throw 'exit nil)))
  6195. t))))
  6196. (defvar org-markers-to-move nil
  6197. "Markers that should be moved with a cut-and-paste operation.
  6198. Those markers are stored together with their positions relative to
  6199. the start of the region.")
  6200. (defun org-save-markers-in-region (beg end)
  6201. "Check markers in region.
  6202. If these markers are between BEG and END, record their position relative
  6203. to BEG, so that after moving the block of text, we can put the markers back
  6204. into place.
  6205. This function gets called just before an entry or tree gets cut from the
  6206. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6207. called immediately, to move the markers with the entries."
  6208. (setq org-markers-to-move nil)
  6209. (when (featurep 'org-clock)
  6210. (org-clock-save-markers-for-cut-and-paste beg end))
  6211. (when (featurep 'org-agenda)
  6212. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6213. (defun org-check-and-save-marker (marker beg end)
  6214. "Check if MARKER is between BEG and END.
  6215. If yes, remember the marker and the distance to BEG."
  6216. (when (and (marker-buffer marker)
  6217. (or (equal (marker-buffer marker) (current-buffer))
  6218. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6219. (>= marker beg) (< marker end))
  6220. (push (cons marker (- marker beg)) org-markers-to-move)))
  6221. (defun org-reinstall-markers-in-region (beg)
  6222. "Move all remembered markers to their position relative to BEG."
  6223. (dolist (x org-markers-to-move)
  6224. (move-marker (car x) (+ beg (cdr x))))
  6225. (setq org-markers-to-move nil))
  6226. (defun org-narrow-to-subtree (&optional element)
  6227. "Narrow buffer to the current subtree."
  6228. (interactive)
  6229. (if (org-element--cache-active-p)
  6230. (let* ((heading (org-element-lineage
  6231. (or element (org-element-at-point))
  6232. '(headline) t))
  6233. (end (org-element-property :end heading)))
  6234. (if (and heading end)
  6235. (narrow-to-region (org-element-property :begin heading)
  6236. (if (= end (point-max))
  6237. end (1- end)))
  6238. (signal 'outline-before-first-heading nil)))
  6239. (save-excursion
  6240. (save-match-data
  6241. (org-with-limited-levels
  6242. (narrow-to-region
  6243. (progn (org-back-to-heading t) (point))
  6244. (progn (org-end-of-subtree t t)
  6245. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6246. (point))))))))
  6247. (defun org-toggle-narrow-to-subtree ()
  6248. "Narrow to the subtree at point or widen a narrowed buffer."
  6249. (interactive)
  6250. (if (buffer-narrowed-p)
  6251. (progn (widen) (message "Buffer widen"))
  6252. (org-narrow-to-subtree)
  6253. (message "Buffer narrowed to current subtree")))
  6254. (defun org-narrow-to-block ()
  6255. "Narrow buffer to the current block."
  6256. (interactive)
  6257. (let* ((case-fold-search t)
  6258. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6259. "^[ \t]*#\\+end_.*")))
  6260. (if blockp
  6261. (narrow-to-region (car blockp) (cdr blockp))
  6262. (user-error "Not in a block"))))
  6263. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6264. "Clone the task (subtree) at point N times.
  6265. The clones will be inserted as siblings.
  6266. In interactive use, the user will be prompted for the number of
  6267. clones to be produced. If the entry has a timestamp, the user
  6268. will also be prompted for a time shift, which may be a repeater
  6269. as used in time stamps, for example `+3d'. To disable this,
  6270. you can call the function with a universal prefix argument.
  6271. When a valid repeater is given and the entry contains any time
  6272. stamps, the clones will become a sequence in time, with time
  6273. stamps in the subtree shifted for each clone produced. If SHIFT
  6274. is nil or the empty string, time stamps will be left alone. The
  6275. ID property of the original subtree is removed.
  6276. In each clone, all the CLOCK entries will be removed. This
  6277. prevents Org from considering that the clocked times overlap.
  6278. If the original subtree did contain time stamps with a repeater,
  6279. the following will happen:
  6280. - the repeater will be removed in each clone
  6281. - an additional clone will be produced, with the current, unshifted
  6282. date(s) in the entry.
  6283. - the original entry will be placed *after* all the clones, with
  6284. repeater intact.
  6285. - the start days in the repeater in the original entry will be shifted
  6286. to past the last clone.
  6287. In this way you can spell out a number of instances of a repeating task,
  6288. and still retain the repeater to cover future instances of the task.
  6289. As described above, N+1 clones are produced when the original
  6290. subtree has a repeater. Setting N to 0, then, can be used to
  6291. remove the repeater from a subtree and create a shifted clone
  6292. with the original repeater."
  6293. (interactive "nNumber of clones to produce: ")
  6294. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6295. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6296. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6297. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6298. (shift
  6299. (or shift
  6300. (if (and (not (equal current-prefix-arg '(4)))
  6301. (save-excursion
  6302. (goto-char beg)
  6303. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6304. (read-from-minibuffer
  6305. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6306. ""))) ;No time shift
  6307. (doshift
  6308. (and (org-string-nw-p shift)
  6309. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6310. shift)
  6311. (user-error "Invalid shift specification %s" shift)))))
  6312. (goto-char end-of-tree)
  6313. (unless (bolp) (insert "\n"))
  6314. (let* ((end (point))
  6315. (template (buffer-substring beg end))
  6316. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6317. (shift-what (pcase (and doshift (match-string 2 shift))
  6318. (`nil nil)
  6319. ("h" 'hour)
  6320. ("d" 'day)
  6321. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6322. ("m" 'month)
  6323. ("y" 'year)
  6324. (_ (error "Unsupported time unit"))))
  6325. (nmin 1)
  6326. (nmax n)
  6327. (n-no-remove -1)
  6328. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6329. (idprop (org-entry-get beg "ID")))
  6330. (when (and doshift
  6331. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6332. template))
  6333. (delete-region beg end)
  6334. (setq end beg)
  6335. (setq nmin 0)
  6336. (setq nmax (1+ nmax))
  6337. (setq n-no-remove nmax))
  6338. (goto-char end)
  6339. (cl-loop for n from nmin to nmax do
  6340. (insert
  6341. ;; Prepare clone.
  6342. (with-temp-buffer
  6343. (insert template)
  6344. (org-mode)
  6345. (goto-char (point-min))
  6346. (org-fold-show-subtree)
  6347. (and idprop (if org-clone-delete-id
  6348. (org-entry-delete nil "ID")
  6349. (org-id-get-create t)))
  6350. (unless (= n 0)
  6351. (while (re-search-forward org-clock-line-re nil t)
  6352. (delete-region (line-beginning-position)
  6353. (line-beginning-position 2)))
  6354. (goto-char (point-min))
  6355. (while (re-search-forward org-drawer-regexp nil t)
  6356. (org-remove-empty-drawer-at (point))))
  6357. (goto-char (point-min))
  6358. (when doshift
  6359. (while (re-search-forward org-ts-regexp-both nil t)
  6360. (org-timestamp-change (* n shift-n) shift-what))
  6361. (unless (= n n-no-remove)
  6362. (goto-char (point-min))
  6363. (while (re-search-forward org-ts-regexp nil t)
  6364. (save-excursion
  6365. (goto-char (match-beginning 0))
  6366. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6367. (delete-region (match-beginning 1) (match-end 1)))))))
  6368. (buffer-string)))))
  6369. (goto-char beg)))
  6370. ;;; Outline path
  6371. (defvar org-outline-path-cache nil
  6372. "Alist between buffer positions and outline paths.
  6373. It value is an alist (POSITION . PATH) where POSITION is the
  6374. buffer position at the beginning of an entry and PATH is a list
  6375. of strings describing the outline path for that entry, in reverse
  6376. order.")
  6377. (defun org--get-outline-path-1 (&optional use-cache)
  6378. "Return outline path to current headline.
  6379. Outline path is a list of strings, in reverse order. When
  6380. optional argument USE-CACHE is non-nil, make use of a cache. See
  6381. `org-get-outline-path' for details.
  6382. Assume buffer is widened and point is on a headline."
  6383. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6384. (let ((p (point))
  6385. (heading (let ((case-fold-search nil))
  6386. (looking-at org-complex-heading-regexp)
  6387. (if (not (match-end 4)) ""
  6388. ;; Remove statistics cookies.
  6389. (org-trim
  6390. (org-link-display-format
  6391. (replace-regexp-in-string
  6392. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6393. (match-string-no-properties 4))))))))
  6394. (if (org-up-heading-safe)
  6395. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6396. (when use-cache
  6397. (push (cons p path) org-outline-path-cache))
  6398. path)
  6399. ;; This is a new root node. Since we assume we are moving
  6400. ;; forward, we can drop previous cache so as to limit number
  6401. ;; of associations there.
  6402. (let ((path (list heading)))
  6403. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6404. path)))))
  6405. (defun org-get-outline-path (&optional with-self use-cache)
  6406. "Return the outline path to the current entry.
  6407. An outline path is a list of ancestors for current headline, as
  6408. a list of strings. Statistics cookies are removed and links are
  6409. replaced with their description, if any, or their path otherwise.
  6410. When optional argument WITH-SELF is non-nil, the path also
  6411. includes the current headline.
  6412. When optional argument USE-CACHE is non-nil, cache outline paths
  6413. between calls to this function so as to avoid backtracking. This
  6414. argument is useful when planning to find more than one outline
  6415. path in the same document. In that case, there are two
  6416. conditions to satisfy:
  6417. - `org-outline-path-cache' is set to nil before starting the
  6418. process;
  6419. - outline paths are computed by increasing buffer positions."
  6420. (org-with-wide-buffer
  6421. (and (or (and with-self (org-back-to-heading t))
  6422. (org-up-heading-safe))
  6423. (reverse (org--get-outline-path-1 use-cache)))))
  6424. (defun org-format-outline-path (path &optional width prefix separator)
  6425. "Format the outline path PATH for display.
  6426. WIDTH is the maximum number of characters that is available.
  6427. PREFIX is a prefix to be included in the returned string,
  6428. such as the file name.
  6429. SEPARATOR is inserted between the different parts of the path,
  6430. the default is \"/\"."
  6431. (setq width (or width 79))
  6432. (setq path (delq nil path))
  6433. (unless (> width 0)
  6434. (user-error "Argument `width' must be positive"))
  6435. (setq separator (or separator "/"))
  6436. (let* ((org-odd-levels-only nil)
  6437. (fpath (concat
  6438. prefix (and prefix path separator)
  6439. (mapconcat
  6440. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6441. (cl-loop for head in path
  6442. for n from 0
  6443. collect (org-add-props
  6444. head nil 'face
  6445. (nth (% n org-n-level-faces) org-level-faces)))
  6446. separator))))
  6447. (when (> (length fpath) width)
  6448. (if (< width 7)
  6449. ;; It's unlikely that `width' will be this small, but don't
  6450. ;; waste characters by adding ".." if it is.
  6451. (setq fpath (substring fpath 0 width))
  6452. (setf (substring fpath (- width 2)) "..")))
  6453. fpath))
  6454. (defun org-display-outline-path (&optional file current separator just-return-string)
  6455. "Display the current outline path in the echo area.
  6456. If FILE is non-nil, prepend the output with the file name.
  6457. If CURRENT is non-nil, append the current heading to the output.
  6458. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6459. the different parts of the path and defaults to \"/\".
  6460. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6461. (interactive "P")
  6462. (let* (case-fold-search
  6463. (bfn (buffer-file-name (buffer-base-buffer)))
  6464. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6465. res)
  6466. (when current (setq path (append path
  6467. (save-excursion
  6468. (org-back-to-heading t)
  6469. (when (looking-at org-complex-heading-regexp)
  6470. (list (match-string 4)))))))
  6471. (setq res
  6472. (org-format-outline-path
  6473. path
  6474. (1- (frame-width))
  6475. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6476. separator))
  6477. (add-face-text-property 0 (length res)
  6478. `(:height ,(face-attribute 'default :height))
  6479. nil res)
  6480. (if just-return-string
  6481. res
  6482. (org-unlogged-message "%s" res))))
  6483. ;;; Outline Sorting
  6484. (defun org-sort (&optional with-case)
  6485. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6486. Optional argument WITH-CASE means sort case-sensitively."
  6487. (interactive "P")
  6488. (org-call-with-arg
  6489. (cond ((org-at-table-p) #'org-table-sort-lines)
  6490. ((org-at-item-p) #'org-sort-list)
  6491. (t #'org-sort-entries))
  6492. with-case))
  6493. (defun org-sort-remove-invisible (s)
  6494. "Remove emphasis markers and any invisible property from string S.
  6495. Assume S may contain only objects."
  6496. ;; org-element-interpret-data clears any text property, including
  6497. ;; invisible part.
  6498. (org-element-interpret-data
  6499. (let ((tree (org-element-parse-secondary-string
  6500. s (org-element-restriction 'paragraph))))
  6501. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6502. (lambda (o)
  6503. (pcase (org-element-type o)
  6504. ;; Terminal object. Replace it with its value.
  6505. ((or `code `verbatim)
  6506. (let ((new (org-element-property :value o)))
  6507. (org-element-insert-before new o)
  6508. (org-element-put-property
  6509. new :post-blank (org-element-property :post-blank o))))
  6510. ;; Non-terminal objects. Splice contents.
  6511. (type
  6512. (let ((contents
  6513. (or (org-element-contents o)
  6514. (and (eq type 'link)
  6515. (list (org-element-property :raw-link o)))))
  6516. (c nil))
  6517. (while contents
  6518. (setq c (pop contents))
  6519. (org-element-insert-before c o))
  6520. (org-element-put-property
  6521. c :post-blank (org-element-property :post-blank o)))))
  6522. (org-element-extract-element o)))
  6523. ;; Return modified tree.
  6524. tree)))
  6525. (defvar org-after-sorting-entries-or-items-hook nil
  6526. "Hook that is run after a bunch of entries or items have been sorted.
  6527. When children are sorted, the cursor is in the parent line when this
  6528. hook gets called. When a region or a plain list is sorted, the cursor
  6529. will be in the first entry of the sorted region/list.")
  6530. (defun org-sort-entries
  6531. (&optional with-case sorting-type getkey-func compare-func property
  6532. interactive?)
  6533. "Sort entries on a certain level of an outline tree.
  6534. If there is an active region, the entries in the region are sorted.
  6535. Else, if the cursor is before the first entry, sort the top-level items.
  6536. Else, the children of the entry at point are sorted.
  6537. Sorting can be alphabetically, numerically, by date/time as given by
  6538. a time stamp, by a property, by priority order, or by a custom function.
  6539. The command prompts for the sorting type unless it has been given to the
  6540. function through the SORTING-TYPE argument, which needs to be a character,
  6541. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6542. the precise meaning of each character:
  6543. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6544. c By creation time, which is assumed to be the first inactive time stamp
  6545. at the beginning of a line.
  6546. d By deadline date/time.
  6547. k By clocking time.
  6548. n Numerically, by converting the beginning of the entry/item to a number.
  6549. o By order of TODO keywords.
  6550. p By priority according to the cookie.
  6551. r By the value of a property.
  6552. s By scheduled date/time.
  6553. t By date/time, either the first active time stamp in the entry, or, if
  6554. none exist, by the first inactive one.
  6555. Capital letters will reverse the sort order.
  6556. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6557. called with point at the beginning of the record. It must return a
  6558. value that is compatible with COMPARE-FUNC, the function used to
  6559. compare entries.
  6560. Comparing entries ignores case by default. However, with an optional argument
  6561. WITH-CASE, the sorting considers case as well.
  6562. Sorting is done against the visible part of the headlines, it ignores hidden
  6563. links.
  6564. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6565. A non-nil value for INTERACTIVE? is used to signal that this
  6566. function is being called interactively."
  6567. (interactive (list current-prefix-arg nil nil nil nil t))
  6568. (let ((case-func (if with-case 'identity 'downcase))
  6569. start beg end stars re re2
  6570. txt what tmp)
  6571. ;; Find beginning and end of region to sort
  6572. (cond
  6573. ((org-region-active-p)
  6574. ;; we will sort the region
  6575. (setq end (region-end)
  6576. what "region")
  6577. (goto-char (region-beginning))
  6578. (unless (org-at-heading-p) (outline-next-heading))
  6579. (setq start (point)))
  6580. ((or (org-at-heading-p)
  6581. (ignore-errors (progn (org-back-to-heading) t)))
  6582. ;; we will sort the children of the current headline
  6583. (org-back-to-heading)
  6584. (setq start (point)
  6585. end (progn (org-end-of-subtree t t)
  6586. (or (bolp) (insert "\n"))
  6587. (when (>= (org-back-over-empty-lines) 1)
  6588. (forward-line 1))
  6589. (point))
  6590. what "children")
  6591. (goto-char start)
  6592. (org-fold-show-subtree)
  6593. (outline-next-heading))
  6594. (t
  6595. ;; we will sort the top-level entries in this file
  6596. (goto-char (point-min))
  6597. (or (org-at-heading-p) (outline-next-heading))
  6598. (setq start (point))
  6599. (goto-char (point-max))
  6600. (beginning-of-line 1)
  6601. (when (looking-at ".*?\\S-")
  6602. ;; File ends in a non-white line
  6603. (end-of-line 1)
  6604. (insert "\n"))
  6605. (setq end (point-max))
  6606. (setq what "top-level")
  6607. (goto-char start)
  6608. (org-fold-show-all '(headings drawers blocks))))
  6609. (setq beg (point))
  6610. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6611. (looking-at "\\(\\*+\\)")
  6612. (setq stars (match-string 1)
  6613. re (concat "^" (regexp-quote stars) " +")
  6614. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6615. txt (buffer-substring beg end))
  6616. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6617. (when (and (not (equal stars "*")) (string-match re2 txt))
  6618. (user-error "Region to sort contains a level above the first entry"))
  6619. (unless sorting-type
  6620. (message
  6621. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6622. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6623. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6624. what)
  6625. (setq sorting-type (read-char-exclusive)))
  6626. (unless getkey-func
  6627. (and (= (downcase sorting-type) ?f)
  6628. (setq getkey-func
  6629. (or (and interactive?
  6630. (org-read-function
  6631. "Function for extracting keys: "))
  6632. (error "Missing key extractor")))))
  6633. (and (= (downcase sorting-type) ?r)
  6634. (not property)
  6635. (setq property
  6636. (completing-read "Property: "
  6637. (mapcar #'list (org-buffer-property-keys t))
  6638. nil t)))
  6639. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6640. (message "Sorting entries...")
  6641. (save-restriction
  6642. (narrow-to-region start end)
  6643. (let ((restore-clock?
  6644. ;; The clock marker is lost when using `sort-subr'; mark
  6645. ;; the clock with temporary `:org-clock-marker-backup'
  6646. ;; text property.
  6647. (when (and (eq (org-clocking-buffer) (current-buffer))
  6648. (<= start (marker-position org-clock-marker))
  6649. (>= end (marker-position org-clock-marker)))
  6650. (with-silent-modifications
  6651. (put-text-property (1- org-clock-marker) org-clock-marker
  6652. :org-clock-marker-backup t))
  6653. t))
  6654. (dcst (downcase sorting-type))
  6655. (case-fold-search nil)
  6656. (now (current-time)))
  6657. (org-preserve-local-variables
  6658. (sort-subr
  6659. (/= dcst sorting-type)
  6660. ;; This function moves to the beginning character of the
  6661. ;; "record" to be sorted.
  6662. (lambda nil
  6663. (if (re-search-forward re nil t)
  6664. (goto-char (match-beginning 0))
  6665. (goto-char (point-max))))
  6666. ;; This function moves to the last character of the "record" being
  6667. ;; sorted.
  6668. (lambda nil
  6669. (save-match-data
  6670. (condition-case nil
  6671. (outline-forward-same-level 1)
  6672. (error
  6673. (goto-char (point-max))))))
  6674. ;; This function returns the value that gets sorted against.
  6675. (lambda ()
  6676. (cond
  6677. ((= dcst ?n)
  6678. (string-to-number
  6679. (org-sort-remove-invisible (org-get-heading t t t t))))
  6680. ((= dcst ?a)
  6681. (funcall case-func
  6682. (org-sort-remove-invisible (org-get-heading t t t t))))
  6683. ((= dcst ?k)
  6684. (or (get-text-property (point) :org-clock-minutes) 0))
  6685. ((= dcst ?t)
  6686. (let ((end (save-excursion (outline-next-heading) (point))))
  6687. (if (or (re-search-forward org-ts-regexp end t)
  6688. (re-search-forward org-ts-regexp-both end t))
  6689. (org-time-string-to-seconds (match-string 0))
  6690. (float-time now))))
  6691. ((= dcst ?c)
  6692. (let ((end (save-excursion (outline-next-heading) (point))))
  6693. (if (re-search-forward
  6694. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6695. end t)
  6696. (org-time-string-to-seconds (match-string 0))
  6697. (float-time now))))
  6698. ((= dcst ?s)
  6699. (let ((end (save-excursion (outline-next-heading) (point))))
  6700. (if (re-search-forward org-scheduled-time-regexp end t)
  6701. (org-time-string-to-seconds (match-string 1))
  6702. (float-time now))))
  6703. ((= dcst ?d)
  6704. (let ((end (save-excursion (outline-next-heading) (point))))
  6705. (if (re-search-forward org-deadline-time-regexp end t)
  6706. (org-time-string-to-seconds (match-string 1))
  6707. (float-time now))))
  6708. ((= dcst ?p)
  6709. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  6710. (string-to-char (match-string 2))
  6711. org-priority-default))
  6712. ((= dcst ?r)
  6713. (or (org-entry-get nil property) ""))
  6714. ((= dcst ?o)
  6715. (when (looking-at org-complex-heading-regexp)
  6716. (let* ((m (match-string 2))
  6717. (s (if (member m org-done-keywords) '- '+)))
  6718. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6719. ((= dcst ?f)
  6720. (if getkey-func
  6721. (progn
  6722. (setq tmp (funcall getkey-func))
  6723. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6724. tmp)
  6725. (error "Invalid key function `%s'" getkey-func)))
  6726. (t (error "Invalid sorting type `%c'" sorting-type))))
  6727. nil
  6728. (cond
  6729. ((= dcst ?a) 'string-collate-lessp)
  6730. ((= dcst ?f)
  6731. (or compare-func
  6732. (and interactive?
  6733. (org-read-function
  6734. (concat "Function for comparing keys "
  6735. "(empty for default `sort-subr' predicate): ")
  6736. 'allow-empty))))
  6737. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6738. (org-cycle-hide-drawers 'all)
  6739. (when restore-clock?
  6740. (move-marker org-clock-marker
  6741. (1+ (next-single-property-change
  6742. start :org-clock-marker-backup)))
  6743. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6744. '(:org-clock-marker-backup t)))))
  6745. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6746. (message "Sorting entries...done")))
  6747. (defun org-contextualize-keys (alist contexts)
  6748. "Return valid elements in ALIST depending on CONTEXTS.
  6749. `org-agenda-custom-commands' or `org-capture-templates' are the
  6750. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6751. or `org-capture-templates-contexts' are the associated contexts
  6752. definitions."
  6753. (let ((contexts
  6754. ;; normalize contexts
  6755. (mapcar
  6756. (lambda(c) (cond ((listp (cadr c))
  6757. (list (car c) (car c) (nth 1 c)))
  6758. ((string= "" (cadr c))
  6759. (list (car c) (car c) (nth 2 c)))
  6760. (t c)))
  6761. contexts))
  6762. (a alist) r s)
  6763. ;; loop over all commands or templates
  6764. (dolist (c a)
  6765. (let (vrules repl)
  6766. (cond
  6767. ((not (assoc (car c) contexts))
  6768. (push c r))
  6769. ((and (assoc (car c) contexts)
  6770. (setq vrules (org-contextualize-validate-key
  6771. (car c) contexts)))
  6772. (mapc (lambda (vr)
  6773. (unless (equal (car vr) (cadr vr))
  6774. (setq repl vr)))
  6775. vrules)
  6776. (if (not repl) (push c r)
  6777. (push (cadr repl) s)
  6778. (push
  6779. (cons (car c)
  6780. (cdr (or (assoc (cadr repl) alist)
  6781. (error "Undefined key `%s' as contextual replacement for `%s'"
  6782. (cadr repl) (car c)))))
  6783. r))))))
  6784. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6785. (delq
  6786. nil
  6787. (delete-dups
  6788. (mapcar (lambda (x)
  6789. (let ((tpl (car x)))
  6790. (unless (delq
  6791. nil
  6792. (mapcar (lambda (y)
  6793. (equal y tpl))
  6794. s))
  6795. x)))
  6796. (reverse r))))))
  6797. (defun org-contextualize-validate-key (key contexts)
  6798. "Check CONTEXTS for agenda or capture KEY."
  6799. (let (res)
  6800. (dolist (r contexts)
  6801. (dolist (rr (car (last r)))
  6802. (when
  6803. (and (equal key (car r))
  6804. (if (functionp rr) (funcall rr)
  6805. (or (and (eq (car rr) 'in-file)
  6806. (buffer-file-name)
  6807. (string-match (cdr rr) (buffer-file-name)))
  6808. (and (eq (car rr) 'in-mode)
  6809. (string-match (cdr rr) (symbol-name major-mode)))
  6810. (and (eq (car rr) 'in-buffer)
  6811. (string-match (cdr rr) (buffer-name)))
  6812. (when (and (eq (car rr) 'not-in-file)
  6813. (buffer-file-name))
  6814. (not (string-match (cdr rr) (buffer-file-name))))
  6815. (when (eq (car rr) 'not-in-mode)
  6816. (not (string-match (cdr rr) (symbol-name major-mode))))
  6817. (when (eq (car rr) 'not-in-buffer)
  6818. (not (string-match (cdr rr) (buffer-name)))))))
  6819. (push r res))))
  6820. (delete-dups (delq nil res))))
  6821. ;; Defined to provide a value for defcustom, since there is no
  6822. ;; string-collate-greaterp in Emacs.
  6823. (defun org-string-collate-greaterp (s1 s2)
  6824. "Return non-nil if S1 is greater than S2 in collation order."
  6825. (not (string-collate-lessp s1 s2)))
  6826. ;;;###autoload
  6827. (defun org-run-like-in-org-mode (cmd)
  6828. "Run a command, pretending that the current buffer is in Org mode.
  6829. This will temporarily bind local variables that are typically bound in
  6830. Org mode to the values they have in Org mode, and then interactively
  6831. call CMD."
  6832. (org-load-modules-maybe)
  6833. (let (vars vals)
  6834. (dolist (var (org-get-local-variables))
  6835. (when (or (not (boundp (car var)))
  6836. (eq (symbol-value (car var))
  6837. (default-value (car var))))
  6838. (push (car var) vars)
  6839. (push (cadr var) vals)))
  6840. (cl-progv vars vals
  6841. (call-interactively cmd))))
  6842. (defun org-get-category (&optional pos force-refresh)
  6843. "Get the category applying to position POS."
  6844. (save-match-data
  6845. (when force-refresh (org-refresh-category-properties))
  6846. (let ((pos (or pos (point))))
  6847. (if (org-element--cache-active-p)
  6848. ;; Sync cache.
  6849. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  6850. (or (org-entry-get-with-inheritance "CATEGORY")
  6851. "???"))
  6852. (or (get-text-property pos 'org-category)
  6853. (progn
  6854. (org-refresh-category-properties)
  6855. (get-text-property pos 'org-category)))))))
  6856. ;;; Refresh properties
  6857. (defun org-refresh-properties (dprop tprop)
  6858. "Refresh buffer text properties.
  6859. DPROP is the drawer property and TPROP is either the
  6860. corresponding text property to set, or an alist with each element
  6861. being a text property (as a symbol) and a function to apply to
  6862. the value of the drawer property."
  6863. (let* ((case-fold-search t)
  6864. (inhibit-read-only t)
  6865. (inherit? (org-property-inherit-p dprop))
  6866. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  6867. (global-or-keyword (and inherit?
  6868. (org--property-global-or-keyword-value dprop nil))))
  6869. (with-silent-modifications
  6870. (org-with-point-at 1
  6871. ;; Set global and keyword based values to the whole buffer.
  6872. (when global-or-keyword
  6873. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  6874. ;; Set values based on property-drawers throughout the document.
  6875. (while (re-search-forward property-re nil t)
  6876. (when (org-at-property-p)
  6877. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  6878. (outline-next-heading))))))
  6879. (defun org-refresh-property (tprop p &optional inherit)
  6880. "Refresh the buffer text property TPROP from the drawer property P.
  6881. The refresh happens only for the current entry, or the whole
  6882. sub-tree if optional argument INHERIT is non-nil.
  6883. If point is before first headline, the function applies to the
  6884. part before the first headline. In that particular case, when
  6885. optional argument INHERIT is non-nil, it refreshes properties for
  6886. the whole buffer."
  6887. (save-excursion
  6888. (org-back-to-heading-or-point-min t)
  6889. (let ((start (point))
  6890. (end (save-excursion
  6891. (cond ((and inherit (org-before-first-heading-p))
  6892. (point-max))
  6893. (inherit
  6894. (org-end-of-subtree t t))
  6895. ((outline-next-heading))
  6896. ((point-max))))))
  6897. (with-silent-modifications
  6898. (if (symbolp tprop)
  6899. ;; TPROP is a text property symbol.
  6900. (put-text-property start end tprop p)
  6901. ;; TPROP is an alist with (property . function) elements.
  6902. (pcase-dolist (`(,prop . ,f) tprop)
  6903. (put-text-property start end prop (funcall f p))))))))
  6904. (defun org-refresh-category-properties ()
  6905. "Refresh category text properties in the buffer."
  6906. (unless (org-element--cache-active-p)
  6907. (let ((case-fold-search t)
  6908. (inhibit-read-only t)
  6909. (default-category
  6910. (cond ((null org-category)
  6911. (if buffer-file-name
  6912. (file-name-sans-extension
  6913. (file-name-nondirectory buffer-file-name))
  6914. "???"))
  6915. ((symbolp org-category) (symbol-name org-category))
  6916. (t org-category))))
  6917. (let ((category (catch 'buffer-category
  6918. (org-with-wide-buffer
  6919. (goto-char (point-max))
  6920. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  6921. (let ((element (org-element-at-point-no-context)))
  6922. (when (eq (org-element-type element) 'keyword)
  6923. (throw 'buffer-category
  6924. (org-element-property :value element))))))
  6925. default-category)))
  6926. (with-silent-modifications
  6927. (org-with-wide-buffer
  6928. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  6929. ;; keyword. If none is found, fall-back to `org-category' or
  6930. ;; buffer file name, or set it by the document property drawer.
  6931. (put-text-property (point-min) (point-max)
  6932. 'org-category category)
  6933. ;; Set categories from the document property drawer or
  6934. ;; property drawers in the outline. If category is found in
  6935. ;; the property drawer for the whole buffer that value
  6936. ;; overrides the keyword-based value set above.
  6937. (goto-char (point-min))
  6938. (let ((regexp (org-re-property "CATEGORY")))
  6939. (while (re-search-forward regexp nil t)
  6940. (let ((value (match-string-no-properties 3)))
  6941. (when (org-at-property-p)
  6942. (put-text-property
  6943. (save-excursion (org-back-to-heading-or-point-min t))
  6944. (save-excursion (if (org-before-first-heading-p)
  6945. (point-max)
  6946. (org-end-of-subtree t t)))
  6947. 'org-category
  6948. value)))))))))))
  6949. (defun org-refresh-stats-properties ()
  6950. "Refresh stats text properties in the buffer."
  6951. (with-silent-modifications
  6952. (org-with-point-at 1
  6953. (let ((regexp (concat org-outline-regexp-bol
  6954. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  6955. (while (re-search-forward regexp nil t)
  6956. (let* ((numerator (string-to-number (match-string 1)))
  6957. (denominator (and (match-end 2)
  6958. (string-to-number (match-string 2))))
  6959. (stats (cond ((not denominator) numerator) ;percent
  6960. ((= denominator 0) 0)
  6961. (t (/ (* numerator 100) denominator)))))
  6962. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  6963. 'org-stats stats)))))))
  6964. (defun org-refresh-effort-properties ()
  6965. "Refresh effort properties."
  6966. (org-refresh-properties
  6967. org-effort-property
  6968. '((effort . identity)
  6969. (effort-minutes . org-duration-to-minutes))))
  6970. (defun org-find-file-at-mouse (ev)
  6971. "Open file link or URL at mouse."
  6972. (interactive "e")
  6973. (mouse-set-point ev)
  6974. (org-open-at-point 'in-emacs))
  6975. (defun org-open-at-mouse (ev)
  6976. "Open file link or URL at mouse.
  6977. See the docstring of `org-open-file' for details."
  6978. (interactive "e")
  6979. (mouse-set-point ev)
  6980. (when (eq major-mode 'org-agenda-mode)
  6981. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  6982. (org-open-at-point))
  6983. (defvar org-window-config-before-follow-link nil
  6984. "The window configuration before following a link.
  6985. This is saved in case the need arises to restore it.")
  6986. (defun org--file-default-apps ()
  6987. "Return the default applications for this operating system."
  6988. (pcase system-type
  6989. (`darwin org-file-apps-macos)
  6990. (`windows-nt org-file-apps-windowsnt)
  6991. (_ org-file-apps-gnu)))
  6992. (defun org--file-apps-entry-dlink-p (entry)
  6993. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  6994. It assumes that is the case when the entry uses a regular
  6995. expression which has at least one grouping construct and the
  6996. action is either a Lisp form or a command string containing
  6997. \"%1\", i.e., using at least one subexpression match as
  6998. a parameter."
  6999. (pcase entry
  7000. (`(,selector . ,action)
  7001. (and (stringp selector)
  7002. (> (regexp-opt-depth selector) 0)
  7003. (or (and (stringp action)
  7004. (string-match "%[0-9]" action))
  7005. (consp action))))
  7006. (_ nil)))
  7007. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7008. "Convert extensions to regular expressions in the cars of LIST.
  7009. Also, weed out any non-string entries, because the return value
  7010. is used only for regexp matching.
  7011. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7012. point to the symbol `emacs', indicating that the file should be
  7013. opened in Emacs."
  7014. (append
  7015. (delq nil
  7016. (mapcar (lambda (x)
  7017. (unless (not (stringp (car x)))
  7018. (if (string-match "\\W" (car x))
  7019. x
  7020. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7021. list))
  7022. (when add-auto-mode
  7023. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7024. ;;;###autoload
  7025. (defun org-open-file (path &optional in-emacs line search)
  7026. "Open the file at PATH.
  7027. First, this expands any special file name abbreviations. Then the
  7028. configuration variable `org-file-apps' is checked if it contains an
  7029. entry for this file type, and if yes, the corresponding command is launched.
  7030. If no application is found, Emacs simply visits the file.
  7031. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7032. With a double \\[universal-argument] \\[universal-argument] \
  7033. prefix arg, Org tries to avoid opening in Emacs
  7034. and to use an external application to visit the file.
  7035. Optional LINE specifies a line to go to, optional SEARCH a string
  7036. to search for. If LINE or SEARCH is given, the file will be
  7037. opened in Emacs, unless an entry from `org-file-apps' that makes
  7038. use of groups in a regexp matches.
  7039. If you want to change the way frames are used when following a
  7040. link, please customize `org-link-frame-setup'.
  7041. If the file does not exist, throw an error."
  7042. (let* ((file (if (equal path "") buffer-file-name
  7043. (substitute-in-file-name (expand-file-name path))))
  7044. (file-apps (append org-file-apps (org--file-default-apps)))
  7045. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7046. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7047. file-apps))
  7048. (remp (and (assq 'remote apps) (file-remote-p file)))
  7049. (dirp (unless remp (file-directory-p file)))
  7050. (file (if (and dirp org-open-directory-means-index-dot-org)
  7051. (concat (file-name-as-directory file) "index.org")
  7052. file))
  7053. (a-m-a-p (assq 'auto-mode apps))
  7054. (dfile (downcase file))
  7055. ;; Reconstruct the original link from the PATH, LINE and
  7056. ;; SEARCH args.
  7057. (link (cond (line (concat file "::" (number-to-string line)))
  7058. (search (concat file "::" search))
  7059. (t file)))
  7060. (dlink (downcase link))
  7061. (ext
  7062. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7063. (match-string 1 dfile)))
  7064. (save-position-maybe
  7065. (let ((old-buffer (current-buffer))
  7066. (old-pos (point))
  7067. (old-mode major-mode))
  7068. (lambda ()
  7069. (and (derived-mode-p 'org-mode)
  7070. (eq old-mode 'org-mode)
  7071. (or (not (eq old-buffer (current-buffer)))
  7072. (not (eq old-pos (point))))
  7073. (org-mark-ring-push old-pos old-buffer)))))
  7074. cmd link-match-data)
  7075. (cond
  7076. ((member in-emacs '((16) system))
  7077. (setq cmd (cdr (assq 'system apps))))
  7078. (in-emacs (setq cmd 'emacs))
  7079. (t
  7080. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7081. (and dirp (cdr (assq 'directory apps)))
  7082. ;; First, try matching against apps-dlink if we
  7083. ;; get a match here, store the match data for
  7084. ;; later.
  7085. (let ((match (assoc-default dlink apps-dlink
  7086. 'string-match)))
  7087. (if match
  7088. (progn (setq link-match-data (match-data))
  7089. match)
  7090. (progn (setq in-emacs (or in-emacs line search))
  7091. nil))) ; if we have no match in apps-dlink,
  7092. ; always open the file in emacs if line or search
  7093. ; is given (for backwards compatibility)
  7094. (assoc-default dfile
  7095. (org--file-apps-regexp-alist apps a-m-a-p)
  7096. 'string-match)
  7097. (cdr (assoc ext apps))
  7098. (cdr (assq t apps))))))
  7099. (when (eq cmd 'system)
  7100. (setq cmd (cdr (assq 'system apps))))
  7101. (when (eq cmd 'default)
  7102. (setq cmd (cdr (assoc t apps))))
  7103. (when (eq cmd 'mailcap)
  7104. (require 'mailcap)
  7105. (mailcap-parse-mailcaps)
  7106. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7107. (command (mailcap-mime-info mime-type)))
  7108. (if (stringp command)
  7109. (setq cmd command)
  7110. (setq cmd 'emacs))))
  7111. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7112. (not (file-exists-p file))
  7113. (not org-open-non-existing-files))
  7114. (user-error "No such file: %s" file))
  7115. (cond
  7116. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7117. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7118. (while (string-match "['\"]%s['\"]" cmd)
  7119. (setq cmd (replace-match "%s" t t cmd)))
  7120. (setq cmd (replace-regexp-in-string
  7121. "%s"
  7122. (shell-quote-argument (convert-standard-filename file))
  7123. cmd
  7124. nil t))
  7125. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7126. (save-match-data
  7127. (let ((match-index 1)
  7128. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7129. (set-match-data link-match-data)
  7130. (while (<= match-index number-of-groups)
  7131. (let ((regex (concat "%" (number-to-string match-index)))
  7132. (replace-with (match-string match-index dlink)))
  7133. (while (string-match regex cmd)
  7134. (setq cmd (replace-match replace-with t t cmd))))
  7135. (setq match-index (+ match-index 1)))))
  7136. (save-window-excursion
  7137. (message "Running %s...done" cmd)
  7138. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7139. ;; and exit immediately. Use pipe connection type instead of pty to
  7140. ;; avoid killing children processes with SIGHUP when temporary terminal
  7141. ;; session is finished.
  7142. ;;
  7143. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7144. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7145. ;; error messages.
  7146. (let ((process-connection-type nil))
  7147. (start-process-shell-command cmd nil cmd))
  7148. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7149. ((or (stringp cmd)
  7150. (eq cmd 'emacs))
  7151. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7152. (widen)
  7153. (cond (line (org-goto-line line)
  7154. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7155. (search (condition-case err
  7156. (org-link-search search)
  7157. ;; Save position before error-ing out so user
  7158. ;; can easily move back to the original buffer.
  7159. (error (funcall save-position-maybe)
  7160. (error (nth 1 err)))))))
  7161. ((functionp cmd)
  7162. (save-match-data
  7163. (set-match-data link-match-data)
  7164. (condition-case nil
  7165. (funcall cmd file link)
  7166. ;; FIXME: Remove this check when most default installations
  7167. ;; of Emacs have at least Org 9.0.
  7168. ((debug wrong-number-of-arguments wrong-type-argument
  7169. invalid-function)
  7170. (user-error "Please see Org News for version 9.0 about \
  7171. `org-file-apps'--Lisp error: %S" cmd)))))
  7172. ((consp cmd)
  7173. ;; FIXME: Remove this check when most default installations of
  7174. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7175. ;; fall back to `org-link-frame-setup' for an old usage of
  7176. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7177. (user-error "Please see Org News for version 9.0 about \
  7178. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7179. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7180. (funcall save-position-maybe)))
  7181. ;;;###autoload
  7182. (defun org-open-at-point-global ()
  7183. "Follow a link or a time-stamp like Org mode does.
  7184. Also follow links and emails as seen by `thing-at-point'.
  7185. This command can be called in any mode to follow an external
  7186. link or a time-stamp that has Org mode syntax. Its behavior
  7187. is undefined when called on internal links like fuzzy links.
  7188. Raise a user error when there is nothing to follow."
  7189. (interactive)
  7190. (let ((tap-url (thing-at-point 'url))
  7191. (tap-email (thing-at-point 'email)))
  7192. (cond ((org-in-regexp org-link-any-re)
  7193. (org-link-open-from-string (match-string-no-properties 0)))
  7194. ((or (org-in-regexp org-ts-regexp-both nil t)
  7195. (org-in-regexp org-tsr-regexp-both nil t))
  7196. (org-follow-timestamp-link))
  7197. (tap-url (org-link-open-from-string tap-url))
  7198. (tap-email (org-link-open-from-string
  7199. (concat "mailto:" tap-email)))
  7200. (t (user-error "No link found")))))
  7201. (defvar org-open-at-point-functions nil
  7202. "Hook that is run when following a link at point.
  7203. Functions in this hook must return t if they identify and follow
  7204. a link at point. If they don't find anything interesting at point,
  7205. they must return nil.")
  7206. (defun org-open-at-point (&optional arg)
  7207. "Open link, timestamp, footnote or tags at point.
  7208. When point is on a link, follow it. Normally, files will be
  7209. opened by an appropriate application. If the optional prefix
  7210. argument ARG is non-nil, Emacs will visit the file. With
  7211. a double prefix argument, try to open outside of Emacs, in the
  7212. application the system uses for this file type.
  7213. When point is on a timestamp, open the agenda at the day
  7214. specified.
  7215. When point is a footnote definition, move to the first reference
  7216. found. If it is on a reference, move to the associated
  7217. definition.
  7218. When point is on a headline, display a list of every link in the
  7219. entry, so it is possible to pick one, or all, of them. If point
  7220. is on a tag, call `org-tags-view' instead.
  7221. On top of syntactically correct links, this function also tries
  7222. to open links and time-stamps in comments, node properties, and
  7223. keywords if point is on something looking like a timestamp or
  7224. a link."
  7225. (interactive "P")
  7226. (org-load-modules-maybe)
  7227. (setq org-window-config-before-follow-link (current-window-configuration))
  7228. (org-remove-occur-highlights nil nil t)
  7229. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7230. (let* ((context
  7231. ;; Only consider supported types, even if they are not the
  7232. ;; closest one.
  7233. (org-element-lineage
  7234. (org-element-context)
  7235. '(citation citation-reference clock comment comment-block
  7236. footnote-definition footnote-reference headline
  7237. inline-src-block inlinetask keyword link node-property
  7238. planning src-block timestamp)
  7239. t))
  7240. (type (org-element-type context))
  7241. (value (org-element-property :value context)))
  7242. (cond
  7243. ((not type) (user-error "No link found"))
  7244. ;; No valid link at point. For convenience, look if something
  7245. ;; looks like a link under point in some specific places.
  7246. ((memq type '(comment comment-block node-property keyword))
  7247. (call-interactively #'org-open-at-point-global))
  7248. ;; On a headline or an inlinetask, but not on a timestamp,
  7249. ;; a link, a footnote reference or a citation.
  7250. ((memq type '(headline inlinetask))
  7251. (org-match-line org-complex-heading-regexp)
  7252. (let ((tags-beg (match-beginning 5))
  7253. (tags-end (match-end 5)))
  7254. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7255. ;; On tags.
  7256. (org-tags-view
  7257. arg
  7258. (save-excursion
  7259. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7260. (end-tag (search-forward ":" tags-end nil 2)))
  7261. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7262. ;; Not on tags.
  7263. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7264. (`(nil . ,_)
  7265. (require 'org-attach)
  7266. (when (org-attach-dir)
  7267. (message "Opening attachment")
  7268. (if (equal arg '(4))
  7269. (org-attach-reveal-in-emacs)
  7270. (org-attach-reveal))))
  7271. (`(,links . ,links-end)
  7272. (dolist (link (if (stringp links) (list links) links))
  7273. (search-forward link nil links-end)
  7274. (goto-char (match-beginning 0))
  7275. (org-open-at-point arg)))))))
  7276. ;; On a footnote reference or at definition's label.
  7277. ((or (eq type 'footnote-reference)
  7278. (and (eq type 'footnote-definition)
  7279. (save-excursion
  7280. ;; Do not validate action when point is on the
  7281. ;; spaces right after the footnote label, in order
  7282. ;; to be on par with behavior on links.
  7283. (skip-chars-forward " \t")
  7284. (let ((begin
  7285. (org-element-property :contents-begin context)))
  7286. (if begin (< (point) begin)
  7287. (= (org-element-property :post-affiliated context)
  7288. (line-beginning-position)))))))
  7289. (org-footnote-action))
  7290. ;; On a planning line. Check if we are really on a timestamp.
  7291. ((and (eq type 'planning)
  7292. (org-in-regexp org-ts-regexp-both nil t))
  7293. (org-follow-timestamp-link))
  7294. ;; On a clock line, make sure point is on the timestamp
  7295. ;; before opening it.
  7296. ((and (eq type 'clock)
  7297. value
  7298. (>= (point) (org-element-property :begin value))
  7299. (<= (point) (org-element-property :end value)))
  7300. (org-follow-timestamp-link))
  7301. ((eq type 'src-block) (org-babel-open-src-block-result))
  7302. ;; Do nothing on white spaces after an object.
  7303. ((>= (point)
  7304. (save-excursion
  7305. (goto-char (org-element-property :end context))
  7306. (skip-chars-backward " \t")
  7307. (point)))
  7308. (user-error "No link found"))
  7309. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7310. ((eq type 'timestamp) (org-follow-timestamp-link))
  7311. ((eq type 'link) (org-link-open context arg))
  7312. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7313. (t (user-error "No link found")))))
  7314. (run-hook-with-args 'org-follow-link-hook))
  7315. ;;;###autoload
  7316. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7317. "Offer links in the current entry and return the selected link.
  7318. If there is only one link, return it.
  7319. If NTH is an integer, return the NTH link found.
  7320. If ZERO is a string, check also this string for a link, and if
  7321. there is one, return it."
  7322. (with-current-buffer buffer
  7323. (org-with-wide-buffer
  7324. (goto-char marker)
  7325. (let ((cnt ?0)
  7326. have-zero end links link c)
  7327. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7328. (push (match-string 0 zero) links)
  7329. (setq cnt (1- cnt) have-zero t))
  7330. (save-excursion
  7331. (org-back-to-heading t)
  7332. (setq end (save-excursion (outline-next-heading) (point)))
  7333. (while (re-search-forward org-link-any-re end t)
  7334. (push (match-string 0) links))
  7335. (setq links (org-uniquify (reverse links))))
  7336. (cond
  7337. ((null links)
  7338. (message "No links"))
  7339. ((equal (length links) 1)
  7340. (setq link (car links)))
  7341. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7342. (setq link (nth (if have-zero nth (1- nth)) links)))
  7343. (t ; we have to select a link
  7344. (save-excursion
  7345. (save-window-excursion
  7346. (delete-other-windows)
  7347. (with-output-to-temp-buffer "*Select Link*"
  7348. (dolist (l links)
  7349. (cond
  7350. ((not (string-match org-link-bracket-re l))
  7351. (princ (format "[%c] %s\n" (cl-incf cnt)
  7352. (org-unbracket-string "<" ">" l))))
  7353. ((match-end 2)
  7354. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7355. (match-string 2 l) (match-string 1 l))))
  7356. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7357. (match-string 1 l)))))))
  7358. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7359. (message "Select link to open, RET to open all:")
  7360. (setq c (read-char-exclusive))
  7361. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7362. (when (equal c ?q) (user-error "Abort"))
  7363. (if (equal c ?\C-m)
  7364. (setq link links)
  7365. (setq nth (- c ?0))
  7366. (when have-zero (setq nth (1+ nth)))
  7367. (unless (and (integerp nth) (>= (length links) nth))
  7368. (user-error "Invalid link selection"))
  7369. (setq link (nth (1- nth) links)))))
  7370. (cons link end)))))
  7371. ;;; File search
  7372. (defun org-do-occur (regexp &optional cleanup)
  7373. "Call the Emacs command `occur'.
  7374. If CLEANUP is non-nil, remove the printout of the regular expression
  7375. in the *Occur* buffer. This is useful if the regex is long and not useful
  7376. to read."
  7377. (occur regexp)
  7378. (when cleanup
  7379. (let ((cwin (selected-window)) win beg end)
  7380. (when (setq win (get-buffer-window "*Occur*"))
  7381. (select-window win))
  7382. (goto-char (point-min))
  7383. (when (re-search-forward "match[a-z]+" nil t)
  7384. (setq beg (match-end 0))
  7385. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7386. (setq end (1- (match-beginning 0)))))
  7387. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7388. (goto-char (point-min))
  7389. (select-window cwin))))
  7390. ;;; The Mark Ring
  7391. (defvar org-mark-ring nil
  7392. "Mark ring for positions before jumps in Org mode.")
  7393. (defvar org-mark-ring-last-goto nil
  7394. "Last position in the mark ring used to go back.")
  7395. ;; Fill and close the ring
  7396. (setq org-mark-ring nil)
  7397. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7398. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7399. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7400. org-mark-ring)
  7401. (defun org-mark-ring-push (&optional pos buffer)
  7402. "Put the current position into the mark ring and rotate it.
  7403. Also push position into the Emacs mark ring. If optional
  7404. argument POS and BUFFER are not nil, mark this location instead."
  7405. (interactive)
  7406. (let ((pos (or pos (point)))
  7407. (buffer (or buffer (current-buffer))))
  7408. (with-current-buffer buffer
  7409. (org-with-point-at pos (push-mark nil t)))
  7410. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7411. (move-marker (car org-mark-ring) pos buffer))
  7412. (message
  7413. (substitute-command-keys
  7414. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7415. (defun org-mark-ring-goto (&optional n)
  7416. "Jump to the previous position in the mark ring.
  7417. With prefix arg N, jump back that many stored positions. When
  7418. called several times in succession, walk through the entire ring.
  7419. Org mode commands jumping to a different position in the current file,
  7420. or to another Org file, automatically push the old position onto the ring."
  7421. (interactive "p")
  7422. (let (p m)
  7423. (if (eq last-command this-command)
  7424. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7425. (setq p org-mark-ring))
  7426. (setq org-mark-ring-last-goto p)
  7427. (setq m (car p))
  7428. (pop-to-buffer-same-window (marker-buffer m))
  7429. (goto-char m)
  7430. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7431. ;;; Following specific links
  7432. (defvar org-agenda-buffer-tmp-name)
  7433. (defvar org-agenda-start-on-weekday)
  7434. (defvar org-agenda-buffer-name)
  7435. (defun org-follow-timestamp-link ()
  7436. "Open an agenda view for the time-stamp date/range at point."
  7437. ;; Avoid changing the global value.
  7438. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7439. (cond
  7440. ((org-at-date-range-p t)
  7441. (let ((org-agenda-start-on-weekday)
  7442. (t1 (match-string 1))
  7443. (t2 (match-string 2)) tt1 tt2)
  7444. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7445. tt2 (time-to-days (org-time-string-to-time t2)))
  7446. (let ((org-agenda-buffer-tmp-name
  7447. (format "*Org Agenda(a:%s)"
  7448. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7449. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7450. ((org-at-timestamp-p 'lax)
  7451. (let ((org-agenda-buffer-tmp-name
  7452. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7453. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7454. (substring (match-string 1) 0 10)))
  7455. 1)))
  7456. (t (error "This should not happen")))))
  7457. ;;; Following file links
  7458. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7459. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7460. (declare-function mailcap-mime-info
  7461. "mailcap" (string &optional request no-decode))
  7462. (defvar org-wait nil)
  7463. ;;;; Refiling
  7464. (defun org-get-org-file ()
  7465. "Read a filename, with default directory `org-directory'."
  7466. (let ((default (or org-default-notes-file remember-data-file)))
  7467. (read-file-name (format "File name [%s]: " default)
  7468. (file-name-as-directory org-directory)
  7469. default)))
  7470. (defun org-notes-order-reversed-p ()
  7471. "Check if the current file should receive notes in reversed order."
  7472. (cond
  7473. ((not org-reverse-note-order) nil)
  7474. ((eq t org-reverse-note-order) t)
  7475. ((not (listp org-reverse-note-order)) nil)
  7476. (t (catch 'exit
  7477. (dolist (entry org-reverse-note-order)
  7478. (when (string-match (car entry) buffer-file-name)
  7479. (throw 'exit (cdr entry))))))))
  7480. (defvar org-agenda-new-buffers nil
  7481. "Buffers created to visit agenda files.")
  7482. (declare-function org-string-nw-p "org-macs" (s))
  7483. ;;;; Dynamic blocks
  7484. (defun org-find-dblock (name)
  7485. "Find the first dynamic block with name NAME in the buffer.
  7486. If not found, stay at current position and return nil."
  7487. (let ((case-fold-search t) pos)
  7488. (save-excursion
  7489. (goto-char (point-min))
  7490. (setq pos (and (re-search-forward
  7491. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7492. (match-beginning 0))))
  7493. (when pos (goto-char pos))
  7494. pos))
  7495. (defun org-create-dblock (plist)
  7496. "Create a dynamic block section, with parameters taken from PLIST.
  7497. PLIST must contain a :name entry which is used as the name of the block."
  7498. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  7499. (end-of-line 1)
  7500. (newline))
  7501. (let ((col (current-column))
  7502. (name (plist-get plist :name)))
  7503. (insert "#+BEGIN: " name)
  7504. (while plist
  7505. (if (eq (car plist) :name)
  7506. (setq plist (cddr plist))
  7507. (insert " " (prin1-to-string (pop plist)))))
  7508. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7509. (beginning-of-line -2)))
  7510. (defun org-prepare-dblock ()
  7511. "Prepare dynamic block for refresh.
  7512. This empties the block, puts the cursor at the insert position and returns
  7513. the property list including an extra property :name with the block name."
  7514. (unless (looking-at org-dblock-start-re)
  7515. (user-error "Not at a dynamic block"))
  7516. (let* ((begdel (1+ (match-end 0)))
  7517. (name (org-no-properties (match-string 1)))
  7518. (params (append (list :name name)
  7519. (read (concat "(" (match-string 3) ")")))))
  7520. (save-excursion
  7521. (beginning-of-line 1)
  7522. (skip-chars-forward " \t")
  7523. (setq params (plist-put params :indentation-column (current-column))))
  7524. (unless (re-search-forward org-dblock-end-re nil t)
  7525. (error "Dynamic block not terminated"))
  7526. (setq params
  7527. (append params
  7528. (list :content (buffer-substring
  7529. begdel (match-beginning 0)))))
  7530. (delete-region begdel (match-beginning 0))
  7531. (goto-char begdel)
  7532. (open-line 1)
  7533. params))
  7534. (defun org-map-dblocks (&optional command)
  7535. "Apply COMMAND to all dynamic blocks in the current buffer.
  7536. If COMMAND is not given, use `org-update-dblock'."
  7537. (let ((cmd (or command 'org-update-dblock)))
  7538. (save-excursion
  7539. (goto-char (point-min))
  7540. (while (re-search-forward org-dblock-start-re nil t)
  7541. (goto-char (match-beginning 0))
  7542. (save-excursion
  7543. (condition-case nil
  7544. (funcall cmd)
  7545. (error (message "Error during update of dynamic block"))))
  7546. (unless (re-search-forward org-dblock-end-re nil t)
  7547. (error "Dynamic block not terminated"))))))
  7548. (defvar org-dynamic-block-alist nil
  7549. "Alist defining all the Org dynamic blocks.
  7550. The key is the dynamic block type name, as a string. The value
  7551. is the function used to insert the dynamic block.
  7552. Use `org-dynamic-block-define' to populate it.")
  7553. (defun org-dynamic-block-function (type)
  7554. "Return function associated to a given dynamic block type.
  7555. TYPE is the dynamic block type, as a string."
  7556. (cdr (assoc type org-dynamic-block-alist)))
  7557. (defun org-dynamic-block-types ()
  7558. "List all defined dynamic block types."
  7559. (mapcar #'car org-dynamic-block-alist))
  7560. (defun org-dynamic-block-define (type func)
  7561. "Define dynamic block TYPE with FUNC.
  7562. TYPE is a string. FUNC is the function creating the dynamic
  7563. block of such type."
  7564. (pcase (assoc type org-dynamic-block-alist)
  7565. (`nil (push (cons type func) org-dynamic-block-alist))
  7566. (def (setcdr def func))))
  7567. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7568. "Insert a dynamic block of type TYPE.
  7569. When used interactively, select the dynamic block types among
  7570. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7571. is non-nil, call the dynamic block function interactively."
  7572. (interactive (list (completing-read "Dynamic block: "
  7573. (org-dynamic-block-types))
  7574. t))
  7575. (pcase (org-dynamic-block-function type)
  7576. (`nil (error "No such dynamic block: %S" type))
  7577. ((and f (pred functionp))
  7578. (if interactive-p (call-interactively f) (funcall f)))
  7579. (_ (error "Invalid function for dynamic block %S" type))))
  7580. (defun org-dblock-update (&optional arg)
  7581. "User command for updating dynamic blocks.
  7582. Update the dynamic block at point. With prefix ARG, update all dynamic
  7583. blocks in the buffer."
  7584. (interactive "P")
  7585. (if arg
  7586. (org-update-all-dblocks)
  7587. (or (looking-at org-dblock-start-re)
  7588. (org-beginning-of-dblock))
  7589. (org-update-dblock)))
  7590. (defun org-update-dblock ()
  7591. "Update the dynamic block at point.
  7592. This means to empty the block, parse for parameters and then call
  7593. the correct writing function."
  7594. (interactive)
  7595. (save-excursion
  7596. (let* ((win (selected-window))
  7597. (pos (point))
  7598. (line (org-current-line))
  7599. (params (org-prepare-dblock))
  7600. (name (plist-get params :name))
  7601. (indent (plist-get params :indentation-column))
  7602. (cmd (intern (concat "org-dblock-write:" name))))
  7603. (message "Updating dynamic block `%s' at line %d..." name line)
  7604. (funcall cmd params)
  7605. (message "Updating dynamic block `%s' at line %d...done" name line)
  7606. (goto-char pos)
  7607. (when (and indent (> indent 0))
  7608. (setq indent (make-string indent ?\ ))
  7609. (save-excursion
  7610. (select-window win)
  7611. (org-beginning-of-dblock)
  7612. (forward-line 1)
  7613. (while (not (looking-at org-dblock-end-re))
  7614. (insert indent)
  7615. (beginning-of-line 2))
  7616. (when (looking-at org-dblock-end-re)
  7617. (and (looking-at "[ \t]+")
  7618. (replace-match ""))
  7619. (insert indent)))))))
  7620. (defun org-beginning-of-dblock ()
  7621. "Find the beginning of the dynamic block at point.
  7622. Error if there is no such block at point."
  7623. (let ((pos (point))
  7624. beg)
  7625. (end-of-line 1)
  7626. (if (and (re-search-backward org-dblock-start-re nil t)
  7627. (setq beg (match-beginning 0))
  7628. (re-search-forward org-dblock-end-re nil t)
  7629. (> (match-end 0) pos))
  7630. (goto-char beg)
  7631. (goto-char pos)
  7632. (error "Not in a dynamic block"))))
  7633. (defun org-update-all-dblocks ()
  7634. "Update all dynamic blocks in the buffer.
  7635. This function can be used in a hook."
  7636. (interactive)
  7637. (when (derived-mode-p 'org-mode)
  7638. (org-map-dblocks 'org-update-dblock)))
  7639. ;;;; Completion
  7640. (declare-function org-export-backend-options "ox" (cl-x) t)
  7641. (defun org-get-export-keywords ()
  7642. "Return a list of all currently understood export keywords.
  7643. Export keywords include options, block names, attributes and
  7644. keywords relative to each registered export back-end."
  7645. (let (keywords)
  7646. (dolist (backend
  7647. (bound-and-true-p org-export-registered-backends)
  7648. (delq nil keywords))
  7649. ;; Back-end name (for keywords, like #+LATEX:)
  7650. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7651. (dolist (option-entry (org-export-backend-options backend))
  7652. ;; Back-end options.
  7653. (push (nth 1 option-entry) keywords)))))
  7654. (defconst org-options-keywords
  7655. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  7656. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  7657. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  7658. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  7659. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7660. (defcustom org-structure-template-alist
  7661. '(("a" . "export ascii")
  7662. ("c" . "center")
  7663. ("C" . "comment")
  7664. ("e" . "example")
  7665. ("E" . "export")
  7666. ("h" . "export html")
  7667. ("l" . "export latex")
  7668. ("q" . "quote")
  7669. ("s" . "src")
  7670. ("v" . "verse"))
  7671. "An alist of keys and block types.
  7672. `org-insert-structure-template' will display a menu with this
  7673. list of templates to choose from. The block type is inserted,
  7674. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  7675. The menu keys are defined by the car of each entry in this alist.
  7676. If two entries have the keys \"a\" and \"aa\" respectively, the
  7677. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7678. latter will be inserted by typing \"aa\". If an entry with the
  7679. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7680. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7681. block can be inserted by pressing TAB after the string \"<KEY\"."
  7682. :group 'org-edit-structure
  7683. :type '(repeat
  7684. (cons (string :tag "Key")
  7685. (string :tag "Template")))
  7686. :package-version '(Org . "9.2"))
  7687. (defun org--check-org-structure-template-alist (&optional checklist)
  7688. "Check whether `org-structure-template-alist' is set up correctly.
  7689. In particular, check if the Org 9.2 format is used as opposed to
  7690. previous format."
  7691. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7692. (or (symbol-value checklist)
  7693. org-structure-template-alist))))
  7694. (when elm
  7695. (org-display-warning
  7696. (format "
  7697. Please update the entries of `%s'.
  7698. In Org 9.2 the format was changed from something like
  7699. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7700. to something like
  7701. (\"s\" . \"src\")
  7702. Please refer to the documentation of `org-structure-template-alist'.
  7703. The following entries must be updated:
  7704. %s"
  7705. (or checklist 'org-structure-template-alist)
  7706. (pp-to-string elm))))))
  7707. (defun org--insert-structure-template-mks ()
  7708. "Present `org-structure-template-alist' with `org-mks'.
  7709. Menus are added if keys require more than one keystroke. Tabs
  7710. are added to single key entries when more than one stroke is
  7711. needed. Keys longer than two characters are reduced to two
  7712. characters."
  7713. (org--check-org-structure-template-alist)
  7714. (let* (case-fold-search
  7715. (templates (append org-structure-template-alist
  7716. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7717. (keys (mapcar #'car templates))
  7718. (start-letters
  7719. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7720. ;; Sort each element of `org-structure-template-alist' into
  7721. ;; sublists according to the first letter.
  7722. (superlist
  7723. (mapcar (lambda (letter)
  7724. (list letter
  7725. (cl-remove-if-not
  7726. (apply-partially #'string-match-p (concat "^" letter))
  7727. templates :key #'car)))
  7728. start-letters)))
  7729. (org-mks
  7730. (apply #'append
  7731. ;; Make an `org-mks' table. If only one element is
  7732. ;; present in a sublist, make it part of the top-menu,
  7733. ;; otherwise make a submenu according to the starting
  7734. ;; letter and populate it.
  7735. (mapcar (lambda (sublist)
  7736. (if (eq 1 (length (cadr sublist)))
  7737. (mapcar (lambda (elm)
  7738. (list (substring (car elm) 0 1)
  7739. (cdr elm) ""))
  7740. (cadr sublist))
  7741. ;; Create submenu.
  7742. (let* ((topkey (car sublist))
  7743. (elms (cadr sublist))
  7744. (keys (mapcar #'car elms))
  7745. (long (> (length elms) 3)))
  7746. (append
  7747. (list
  7748. ;; Make a description of the submenu.
  7749. (list topkey
  7750. (concat
  7751. (mapconcat #'cdr
  7752. (cl-subseq elms 0 (if long 3 (length elms)))
  7753. ", ")
  7754. (when long ", ..."))))
  7755. ;; List of entries in submenu.
  7756. (cl-mapcar #'list
  7757. (org--insert-structure-template-unique-keys keys)
  7758. (mapcar #'cdr elms)
  7759. (make-list (length elms) ""))))))
  7760. superlist))
  7761. "Select a key\n============"
  7762. "Key: ")))
  7763. (defun org--insert-structure-template-unique-keys (keys)
  7764. "Make a list of unique, two characters long elements from KEYS.
  7765. Elements of length one have a tab appended. Elements of length
  7766. two are kept as is. Longer elements are truncated to length two.
  7767. If an element cannot be made unique, an error is raised."
  7768. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7769. menu-keys)
  7770. (dolist (key ordered-keys)
  7771. (let ((potential-key
  7772. (cl-case (length key)
  7773. (1 (concat key "\t"))
  7774. (2 key)
  7775. (otherwise
  7776. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  7777. (mapcar (apply-partially #'concat (substring key 0 1))
  7778. (split-string (substring key 1) "" t)))))))
  7779. (if (or (not potential-key) (assoc potential-key menu-keys))
  7780. (user-error "Could not make unique key for `%s'" key)
  7781. (push (cons potential-key key) menu-keys))))
  7782. (mapcar #'car
  7783. (cl-sort menu-keys #'<
  7784. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  7785. (defun org-insert-structure-template (type)
  7786. "Insert a block structure of the type #+begin_foo/#+end_foo.
  7787. Select a block from `org-structure-template-alist' then type
  7788. either RET, TAB or SPC to write the block type. With an active
  7789. region, wrap the region in the block. Otherwise, insert an empty
  7790. block."
  7791. (interactive
  7792. (list (pcase (org--insert-structure-template-mks)
  7793. (`("\t" . ,_) (read-string "Structure type: "))
  7794. (`(,_ ,choice . ,_) choice))))
  7795. (let* ((region? (use-region-p))
  7796. (region-start (and region? (region-beginning)))
  7797. (region-end (and region? (copy-marker (region-end))))
  7798. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  7799. (verbatim? (string-match-p
  7800. (concat "\\`" (regexp-opt '("example" "export" "src")))
  7801. type)))
  7802. (when region? (goto-char region-start))
  7803. (let ((column (current-indentation)))
  7804. (if (save-excursion (skip-chars-backward " \t") (bolp))
  7805. (beginning-of-line)
  7806. (insert "\n"))
  7807. (save-excursion
  7808. (indent-to column)
  7809. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  7810. (when region?
  7811. (when verbatim? (org-escape-code-in-region (point) region-end))
  7812. (goto-char region-end)
  7813. ;; Ignore empty lines at the end of the region.
  7814. (skip-chars-backward " \r\t\n")
  7815. (end-of-line))
  7816. (unless (bolp) (insert "\n"))
  7817. (indent-to column)
  7818. (insert (format "#+end_%s" (car (split-string type))))
  7819. (if (looking-at "[ \t]*$") (replace-match "")
  7820. (insert "\n"))
  7821. (when (and (eobp) (not (bolp))) (insert "\n")))
  7822. (if extended? (end-of-line)
  7823. (forward-line)
  7824. (skip-chars-forward " \t")))))
  7825. ;;;; TODO, DEADLINE, Comments
  7826. (defun org-toggle-comment ()
  7827. "Change the COMMENT state of an entry."
  7828. (interactive)
  7829. (save-excursion
  7830. (org-back-to-heading)
  7831. (let ((case-fold-search nil))
  7832. (looking-at org-complex-heading-regexp))
  7833. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7834. (skip-chars-forward " \t")
  7835. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  7836. (if (org-in-commented-heading-p t)
  7837. (delete-region (point)
  7838. (progn (search-forward " " (line-end-position) 'move)
  7839. (skip-chars-forward " \t")
  7840. (point)))
  7841. (insert org-comment-string)
  7842. (unless (eolp) (insert " ")))))
  7843. (defvar org-last-todo-state-is-todo nil
  7844. "This is non-nil when the last TODO state change led to a TODO state.
  7845. If the last change removed the TODO tag or switched to DONE, then
  7846. this is nil.")
  7847. (defvar org-todo-setup-filter-hook nil
  7848. "Hook for functions that pre-filter todo specs.
  7849. Each function takes a todo spec and returns either nil or the spec
  7850. transformed into canonical form." )
  7851. (defvar org-todo-get-default-hook nil
  7852. "Hook for functions that get a default item for todo.
  7853. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  7854. nil or a string to be used for the todo mark." )
  7855. (defvar org-agenda-headline-snapshot-before-repeat)
  7856. (defun org-current-effective-time ()
  7857. "Return current time adjusted for `org-extend-today-until' variable."
  7858. (let* ((ct (org-current-time))
  7859. (dct (decode-time ct))
  7860. (ct1
  7861. (cond
  7862. (org-use-last-clock-out-time-as-effective-time
  7863. (or (org-clock-get-last-clock-out-time) ct))
  7864. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  7865. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  7866. (t ct))))
  7867. ct1))
  7868. (defun org-todo-yesterday (&optional arg)
  7869. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  7870. (interactive "P")
  7871. (if (eq major-mode 'org-agenda-mode)
  7872. (apply 'org-agenda-todo-yesterday arg)
  7873. (let* ((org-use-effective-time t)
  7874. (hour (nth 2 (decode-time (org-current-time))))
  7875. (org-extend-today-until (1+ hour)))
  7876. (org-todo arg))))
  7877. (defvar org-block-entry-blocking ""
  7878. "First entry preventing the TODO state change.")
  7879. (defun org-cancel-repeater ()
  7880. "Cancel a repeater by setting its numeric value to zero."
  7881. (interactive)
  7882. (save-excursion
  7883. (org-back-to-heading t)
  7884. (let ((bound1 (point))
  7885. (bound0 (save-excursion (outline-next-heading) (point))))
  7886. (when (and (re-search-forward
  7887. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  7888. org-deadline-time-regexp "\\)\\|\\("
  7889. org-ts-regexp "\\)")
  7890. bound0 t)
  7891. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  7892. bound1 t))
  7893. (replace-match "0" t nil nil 1)))))
  7894. (defvar org-state)
  7895. (defvar org-blocked-by-checkboxes)
  7896. (defun org-todo (&optional arg)
  7897. "Change the TODO state of an item.
  7898. The state of an item is given by a keyword at the start of the heading,
  7899. like
  7900. *** TODO Write paper
  7901. *** DONE Call mom
  7902. The different keywords are specified in the variable `org-todo-keywords'.
  7903. By default the available states are \"TODO\" and \"DONE\". So, for this
  7904. example: when the item starts with TODO, it is changed to DONE.
  7905. When it starts with DONE, the DONE is removed. And when neither TODO nor
  7906. DONE are present, add TODO at the beginning of the heading.
  7907. You can set up single-character keys to fast-select the new state. See the
  7908. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  7909. With `\\[universal-argument]' prefix ARG, force logging the state change \
  7910. and take a
  7911. logging note.
  7912. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  7913. next set of TODO \
  7914. keywords (nextset).
  7915. Another way to achieve this is `S-C-<right>'.
  7916. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  7917. prefix, circumvent any state blocking.
  7918. With numeric prefix arg, switch to the Nth state.
  7919. With a numeric prefix arg of 0, inhibit note taking for the change.
  7920. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  7921. When called through ELisp, arg is also interpreted in the following way:
  7922. `none' -> empty state
  7923. \"\" -> switch to empty state
  7924. `done' -> switch to DONE
  7925. `nextset' -> switch to the next set of keywords
  7926. `previousset' -> switch to the previous set of keywords
  7927. \"WAITING\" -> switch to the specified keyword, but only if it
  7928. really is a member of `org-todo-keywords'."
  7929. (interactive "P")
  7930. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  7931. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  7932. 'region-start-level 'region))
  7933. org-loop-over-headlines-in-active-region)
  7934. (org-map-entries
  7935. (lambda () (org-todo arg))
  7936. nil cl
  7937. (when (org-invisible-p) (org-end-of-subtree nil t))))
  7938. (when (equal arg '(16)) (setq arg 'nextset))
  7939. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  7940. (let ((org-blocker-hook org-blocker-hook)
  7941. commentp
  7942. case-fold-search)
  7943. (when (equal arg '(64))
  7944. (setq arg nil org-blocker-hook nil))
  7945. (when (and org-blocker-hook
  7946. (or org-inhibit-blocking
  7947. (org-entry-get nil "NOBLOCKING")))
  7948. (setq org-blocker-hook nil))
  7949. (save-excursion
  7950. (catch 'exit
  7951. (org-back-to-heading t)
  7952. (when (org-in-commented-heading-p t)
  7953. (org-toggle-comment)
  7954. (setq commentp t))
  7955. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  7956. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  7957. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  7958. (let* ((match-data (match-data))
  7959. (startpos (copy-marker (line-beginning-position)))
  7960. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  7961. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  7962. (org-log-done org-log-done)
  7963. (org-log-repeat org-log-repeat)
  7964. (org-todo-log-states org-todo-log-states)
  7965. (org-inhibit-logging
  7966. (if (equal arg 0)
  7967. (progn (setq arg nil) 'note) org-inhibit-logging))
  7968. (this (match-string 1))
  7969. (hl-pos (match-beginning 0))
  7970. (head (org-get-todo-sequence-head this))
  7971. (ass (assoc head org-todo-kwd-alist))
  7972. (interpret (nth 1 ass))
  7973. (done-word (nth 3 ass))
  7974. (final-done-word (nth 4 ass))
  7975. (org-last-state (or this ""))
  7976. (completion-ignore-case t)
  7977. (member (member this org-todo-keywords-1))
  7978. (tail (cdr member))
  7979. (org-state (cond
  7980. ((eq arg 'right)
  7981. ;; Next state
  7982. (if this
  7983. (if tail (car tail) nil)
  7984. (car org-todo-keywords-1)))
  7985. ((eq arg 'left)
  7986. ;; Previous state
  7987. (unless (equal member org-todo-keywords-1)
  7988. (if this
  7989. (nth (- (length org-todo-keywords-1)
  7990. (length tail) 2)
  7991. org-todo-keywords-1)
  7992. (org-last org-todo-keywords-1))))
  7993. (arg
  7994. ;; User or caller requests a specific state.
  7995. (cond
  7996. ((equal arg "") nil)
  7997. ((eq arg 'none) nil)
  7998. ((eq arg 'done) (or done-word (car org-done-keywords)))
  7999. ((eq arg 'nextset)
  8000. (or (car (cdr (member head org-todo-heads)))
  8001. (car org-todo-heads)))
  8002. ((eq arg 'previousset)
  8003. (let ((org-todo-heads (reverse org-todo-heads)))
  8004. (or (car (cdr (member head org-todo-heads)))
  8005. (car org-todo-heads))))
  8006. ((car (member arg org-todo-keywords-1)))
  8007. ((stringp arg)
  8008. (user-error "State `%s' not valid in this file" arg))
  8009. ((nth (1- (prefix-numeric-value arg))
  8010. org-todo-keywords-1))))
  8011. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8012. ;; Use fast selection.
  8013. (org-fast-todo-selection this))
  8014. ((null member) (or head (car org-todo-keywords-1)))
  8015. ((equal this final-done-word) nil) ;-> make empty
  8016. ((null tail) nil) ;-> first entry
  8017. ((memq interpret '(type priority))
  8018. (if (eq this-command last-command)
  8019. (car tail)
  8020. (if (> (length tail) 0)
  8021. (or done-word (car org-done-keywords))
  8022. nil)))
  8023. (t
  8024. (car tail))))
  8025. (org-state (or
  8026. (run-hook-with-args-until-success
  8027. 'org-todo-get-default-hook org-state org-last-state)
  8028. org-state))
  8029. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8030. (change-plist (list :type 'todo-state-change :from this :to org-state
  8031. :position startpos))
  8032. dolog now-done-p)
  8033. (when org-blocker-hook
  8034. (let (org-blocked-by-checkboxes block-reason)
  8035. (setq org-last-todo-state-is-todo
  8036. (not (member this org-done-keywords)))
  8037. (unless (save-excursion
  8038. (save-match-data
  8039. (org-with-wide-buffer
  8040. (run-hook-with-args-until-failure
  8041. 'org-blocker-hook change-plist))))
  8042. (setq block-reason (if org-blocked-by-checkboxes
  8043. "contained checkboxes"
  8044. (format "\"%s\"" org-block-entry-blocking)))
  8045. (if (called-interactively-p 'interactive)
  8046. (user-error "TODO state change from %s to %s blocked (by %s)"
  8047. this org-state block-reason)
  8048. ;; Fail silently.
  8049. (message "TODO state change from %s to %s blocked (by %s)"
  8050. this org-state block-reason)
  8051. (throw 'exit nil)))))
  8052. (store-match-data match-data)
  8053. (org-fold-core-ignore-modifications
  8054. (save-excursion
  8055. (goto-char (match-beginning 0))
  8056. (setf (buffer-substring (match-beginning 0) (match-end 0)) "")
  8057. (insert-and-inherit next)
  8058. (unless (org-invisible-p (line-beginning-position))
  8059. (org-fold-region (line-beginning-position)
  8060. (line-end-position)
  8061. nil))))
  8062. (cond ((and org-state (equal this org-state))
  8063. (message "TODO state was already %s" (org-trim next)))
  8064. ((not (pos-visible-in-window-p hl-pos))
  8065. (message "TODO state changed to %s" (org-trim next))))
  8066. (unless head
  8067. (setq head (org-get-todo-sequence-head org-state)
  8068. ass (assoc head org-todo-kwd-alist)
  8069. interpret (nth 1 ass)
  8070. done-word (nth 3 ass)
  8071. final-done-word (nth 4 ass)))
  8072. (when (memq arg '(nextset previousset))
  8073. (message "Keyword-Set %d/%d: %s"
  8074. (- (length org-todo-sets) -1
  8075. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8076. (length org-todo-sets)
  8077. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8078. (setq org-last-todo-state-is-todo
  8079. (not (member org-state org-done-keywords)))
  8080. (setq now-done-p (and (member org-state org-done-keywords)
  8081. (not (member this org-done-keywords))))
  8082. (and logging (org-local-logging logging))
  8083. (when (or (and (or org-todo-log-states org-log-done)
  8084. (not (eq org-inhibit-logging t))
  8085. (not (memq arg '(nextset previousset))))
  8086. force-log)
  8087. ;; We need to look at recording a time and note.
  8088. (setq dolog (or (if force-log 'note)
  8089. (nth 1 (assoc org-state org-todo-log-states))
  8090. (nth 2 (assoc this org-todo-log-states))))
  8091. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8092. (setq dolog 'time))
  8093. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8094. (and org-state
  8095. (member org-state org-not-done-keywords)
  8096. (not (member this org-not-done-keywords))))
  8097. ;; This is now a todo state and was not one before
  8098. ;; If there was a CLOSED time stamp, get rid of it.
  8099. (org-add-planning-info nil nil 'closed))
  8100. (when (and now-done-p org-log-done)
  8101. ;; It is now done, and it was not done before.
  8102. (org-add-planning-info 'closed (org-current-effective-time))
  8103. (when (and (not dolog) (eq 'note org-log-done))
  8104. (org-add-log-setup 'done org-state this 'note)))
  8105. (when (and org-state dolog)
  8106. ;; This is a non-nil state, and we need to log it.
  8107. (org-add-log-setup 'state org-state this dolog)))
  8108. ;; Fixup tag positioning.
  8109. (org-todo-trigger-tag-changes org-state)
  8110. (when org-auto-align-tags (org-align-tags))
  8111. (when org-provide-todo-statistics
  8112. (org-update-parent-todo-statistics))
  8113. (when (bound-and-true-p org-clock-out-when-done)
  8114. (org-clock-out-if-current))
  8115. (run-hooks 'org-after-todo-state-change-hook)
  8116. (when (and arg (not (member org-state org-done-keywords)))
  8117. (setq head (org-get-todo-sequence-head org-state)))
  8118. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8119. ;; Do we need to trigger a repeat?
  8120. (when now-done-p
  8121. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8122. ;; This is for the agenda, take a snapshot of the headline.
  8123. (save-match-data
  8124. (setq org-agenda-headline-snapshot-before-repeat
  8125. (org-get-heading))))
  8126. (org-auto-repeat-maybe org-state))
  8127. ;; Fixup cursor location if close to the keyword.
  8128. (when (and (outline-on-heading-p)
  8129. (not (bolp))
  8130. (save-excursion (beginning-of-line 1)
  8131. (looking-at org-todo-line-regexp))
  8132. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8133. (goto-char (or (match-end 2) (match-end 1)))
  8134. (and (looking-at " ")
  8135. (not (looking-at " *:"))
  8136. (just-one-space)))
  8137. (when org-trigger-hook
  8138. (save-excursion
  8139. (run-hook-with-args 'org-trigger-hook change-plist)))
  8140. (when commentp (org-toggle-comment))))))))
  8141. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8142. "Block turning an entry into a TODO, using the hierarchy.
  8143. This checks whether the current task should be blocked from state
  8144. changes. Such blocking occurs when:
  8145. 1. The task has children which are not all in a completed state.
  8146. 2. A task has a parent with the property :ORDERED:, and there
  8147. are siblings prior to the current task with incomplete
  8148. status.
  8149. 3. The parent of the task is blocked because it has siblings that should
  8150. be done first, or is child of a block grandparent TODO entry."
  8151. (if (not org-enforce-todo-dependencies)
  8152. t ; if locally turned off don't block
  8153. (catch 'dont-block
  8154. ;; If this is not a todo state change, or if this entry is already DONE,
  8155. ;; do not block
  8156. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8157. (member (plist-get change-plist :from)
  8158. (cons 'done org-done-keywords))
  8159. (member (plist-get change-plist :to)
  8160. (cons 'todo org-not-done-keywords))
  8161. (not (plist-get change-plist :to)))
  8162. (throw 'dont-block t))
  8163. ;; If this task has children, and any are undone, it's blocked
  8164. (save-excursion
  8165. (org-back-to-heading t)
  8166. (let ((this-level (funcall outline-level)))
  8167. (outline-next-heading)
  8168. (let ((child-level (funcall outline-level)))
  8169. (while (and (not (eobp))
  8170. (> child-level this-level))
  8171. ;; this todo has children, check whether they are all
  8172. ;; completed
  8173. (when (and (not (org-entry-is-done-p))
  8174. (org-entry-is-todo-p))
  8175. (setq org-block-entry-blocking (org-get-heading))
  8176. (throw 'dont-block nil))
  8177. (outline-next-heading)
  8178. (setq child-level (funcall outline-level))))))
  8179. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8180. ;; any previous siblings are undone, it's blocked
  8181. (save-excursion
  8182. (org-back-to-heading t)
  8183. (let* ((pos (point))
  8184. (parent-pos (and (org-up-heading-safe) (point)))
  8185. (case-fold-search nil))
  8186. (unless parent-pos (throw 'dont-block t)) ; no parent
  8187. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8188. (forward-line 1)
  8189. (re-search-forward org-not-done-heading-regexp pos t))
  8190. (setq org-block-entry-blocking (match-string 0))
  8191. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8192. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8193. (while t
  8194. (goto-char parent-pos)
  8195. (unless (looking-at org-not-done-heading-regexp)
  8196. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8197. (setq pos (point))
  8198. (setq parent-pos (and (org-up-heading-safe) (point)))
  8199. (unless parent-pos (throw 'dont-block t)) ; no parent
  8200. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8201. (forward-line 1)
  8202. (re-search-forward org-not-done-heading-regexp pos t)
  8203. (setq org-block-entry-blocking (org-get-heading)))
  8204. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8205. (defcustom org-track-ordered-property-with-tag nil
  8206. "Should the ORDERED property also be shown as a tag?
  8207. The ORDERED property decides if an entry should require subtasks to be
  8208. completed in sequence. Since a property is not very visible, setting
  8209. this option means that toggling the ORDERED property with the command
  8210. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8211. not relevant for the behavior, but it makes things more visible.
  8212. Note that toggling the tag with tags commands will not change the property
  8213. and therefore not influence behavior!
  8214. This can be t, meaning the tag ORDERED should be used. It can also be a
  8215. string to select a different tag for this task."
  8216. :group 'org-todo
  8217. :type '(choice
  8218. (const :tag "No tracking" nil)
  8219. (const :tag "Track with ORDERED tag" t)
  8220. (string :tag "Use other tag")))
  8221. (defun org-toggle-ordered-property ()
  8222. "Toggle the ORDERED property of the current entry.
  8223. For better visibility, you can track the value of this property with a tag.
  8224. See variable `org-track-ordered-property-with-tag'."
  8225. (interactive)
  8226. (let* ((t1 org-track-ordered-property-with-tag)
  8227. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8228. (save-excursion
  8229. (org-back-to-heading)
  8230. (if (org-entry-get nil "ORDERED")
  8231. (progn
  8232. (org-delete-property "ORDERED")
  8233. (and tag (org-toggle-tag tag 'off))
  8234. (message "Subtasks can be completed in arbitrary order"))
  8235. (org-entry-put nil "ORDERED" "t")
  8236. (and tag (org-toggle-tag tag 'on))
  8237. (message "Subtasks must be completed in sequence")))))
  8238. (defun org-block-todo-from-checkboxes (change-plist)
  8239. "Block turning an entry into a TODO, using checkboxes.
  8240. This checks whether the current task should be blocked from state
  8241. changes because there are unchecked boxes in this entry."
  8242. (if (not org-enforce-todo-checkbox-dependencies)
  8243. t ; if locally turned off don't block
  8244. (catch 'dont-block
  8245. ;; If this is not a todo state change, or if this entry is already DONE,
  8246. ;; do not block
  8247. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8248. (member (plist-get change-plist :from)
  8249. (cons 'done org-done-keywords))
  8250. (member (plist-get change-plist :to)
  8251. (cons 'todo org-not-done-keywords))
  8252. (not (plist-get change-plist :to)))
  8253. (throw 'dont-block t))
  8254. ;; If this task has checkboxes that are not checked, it's blocked
  8255. (save-excursion
  8256. (org-back-to-heading t)
  8257. (let ((beg (point)) end)
  8258. (outline-next-heading)
  8259. (setq end (point))
  8260. (goto-char beg)
  8261. (when (org-list-search-forward
  8262. (concat (org-item-beginning-re)
  8263. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8264. "\\[[- ]\\]")
  8265. end t)
  8266. (when (boundp 'org-blocked-by-checkboxes)
  8267. (setq org-blocked-by-checkboxes t))
  8268. (throw 'dont-block nil))))
  8269. t))) ; do not block
  8270. (defun org-entry-blocked-p ()
  8271. "Non-nil if entry at point is blocked."
  8272. (and (not (org-entry-get nil "NOBLOCKING"))
  8273. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8274. (not (run-hook-with-args-until-failure
  8275. 'org-blocker-hook
  8276. (list :type 'todo-state-change
  8277. :position (point)
  8278. :from 'todo
  8279. :to 'done)))))
  8280. (defun org-update-statistics-cookies (all)
  8281. "Update the statistics cookie, either from TODO or from checkboxes.
  8282. This should be called with the cursor in a line with a statistics
  8283. cookie. When called with a \\[universal-argument] prefix, update
  8284. all statistics cookies in the buffer."
  8285. (interactive "P")
  8286. (if all
  8287. (progn
  8288. (org-update-checkbox-count 'all)
  8289. (org-map-region 'org-update-parent-todo-statistics
  8290. (point-min) (point-max)))
  8291. (if (not (org-at-heading-p))
  8292. (org-update-checkbox-count)
  8293. (let ((pos (point-marker))
  8294. end l1 l2)
  8295. (ignore-errors (org-back-to-heading t))
  8296. (if (not (org-at-heading-p))
  8297. (org-update-checkbox-count)
  8298. (setq l1 (org-outline-level))
  8299. (setq end
  8300. (save-excursion
  8301. (outline-next-heading)
  8302. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8303. (point)))
  8304. (if (and (save-excursion
  8305. (re-search-forward
  8306. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8307. (not (save-excursion
  8308. (re-search-forward
  8309. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8310. (org-update-checkbox-count)
  8311. (if (and l2 (> l2 l1))
  8312. (progn
  8313. (goto-char end)
  8314. (org-update-parent-todo-statistics))
  8315. (goto-char pos)
  8316. (beginning-of-line 1)
  8317. (while (re-search-forward
  8318. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8319. (point-at-eol) t)
  8320. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8321. (goto-char pos)
  8322. (move-marker pos nil)))))
  8323. (defvar org-entry-property-inherited-from) ;; defined below
  8324. (defun org-update-parent-todo-statistics ()
  8325. "Update any statistics cookie in the parent of the current headline.
  8326. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8327. the entire subtree and this will travel up the hierarchy and update
  8328. statistics everywhere."
  8329. (let* ((prop (save-excursion
  8330. (org-up-heading-safe)
  8331. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8332. (recursive (or (not org-hierarchical-todo-statistics)
  8333. (and prop (string-match "\\<recursive\\>" prop))))
  8334. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8335. 0))
  8336. (first t)
  8337. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8338. level ltoggle l1 new ndel
  8339. (cnt-all 0) (cnt-done 0) is-percent kwd
  8340. checkbox-beg cookie-present)
  8341. (catch 'exit
  8342. (save-excursion
  8343. (beginning-of-line 1)
  8344. (setq ltoggle (funcall outline-level))
  8345. ;; Three situations are to consider:
  8346. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8347. ;; to the top-level ancestor on the headline;
  8348. ;; 2. If parent has "recursive" property, repeat up to the
  8349. ;; headline setting that property, taking inheritance into
  8350. ;; account;
  8351. ;; 3. Else, move up to direct parent and proceed only once.
  8352. (while (and (setq level (org-up-heading-safe))
  8353. (or recursive first)
  8354. (>= (point) lim))
  8355. (setq first nil cookie-present nil)
  8356. (unless (and level
  8357. (not (string-match
  8358. "\\<checkbox\\>"
  8359. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8360. "")))))
  8361. (throw 'exit nil))
  8362. (while (re-search-forward box-re (point-at-eol) t)
  8363. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8364. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8365. (save-match-data
  8366. (unless (outline-next-heading) (throw 'exit nil))
  8367. (while (and (looking-at org-complex-heading-regexp)
  8368. (> (setq l1 (length (match-string 1))) level))
  8369. (setq kwd (and (or recursive (= l1 ltoggle))
  8370. (match-string 2)))
  8371. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8372. (and (eq org-provide-todo-statistics t)
  8373. (or (member kwd org-done-keywords)))
  8374. (and (listp org-provide-todo-statistics)
  8375. (stringp (car org-provide-todo-statistics))
  8376. (or (member kwd org-provide-todo-statistics)
  8377. (member kwd org-done-keywords)))
  8378. (and (listp org-provide-todo-statistics)
  8379. (listp (car org-provide-todo-statistics))
  8380. (or (member kwd (car org-provide-todo-statistics))
  8381. (and (member kwd org-done-keywords)
  8382. (member kwd (cadr org-provide-todo-statistics))))))
  8383. (setq cnt-all (1+ cnt-all))
  8384. (and (eq org-provide-todo-statistics t)
  8385. kwd
  8386. (setq cnt-all (1+ cnt-all))))
  8387. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8388. (member kwd org-done-keywords))
  8389. (and (listp org-provide-todo-statistics)
  8390. (listp (car org-provide-todo-statistics))
  8391. (member kwd org-done-keywords)
  8392. (member kwd (cadr org-provide-todo-statistics)))
  8393. (and (listp org-provide-todo-statistics)
  8394. (stringp (car org-provide-todo-statistics))
  8395. (member kwd org-done-keywords)))
  8396. (setq cnt-done (1+ cnt-done)))
  8397. (outline-next-heading)))
  8398. (setq new
  8399. (if is-percent
  8400. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8401. (max 1 cnt-all)))
  8402. (format "[%d/%d]" cnt-done cnt-all))
  8403. ndel (- (match-end 0) checkbox-beg))
  8404. (goto-char checkbox-beg)
  8405. (insert new)
  8406. (delete-region (point) (+ (point) ndel))
  8407. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8408. (when cookie-present
  8409. (run-hook-with-args 'org-after-todo-statistics-hook
  8410. cnt-done (- cnt-all cnt-done))))))
  8411. (run-hooks 'org-todo-statistics-hook)))
  8412. (defvar org-after-todo-statistics-hook nil
  8413. "Hook that is called after a TODO statistics cookie has been updated.
  8414. Each function is called with two arguments: the number of not-done entries
  8415. and the number of done entries.
  8416. For example, the following function, when added to this hook, will switch
  8417. an entry to DONE when all children are done, and back to TODO when new
  8418. entries are set to a TODO status. Note that this hook is only called
  8419. when there is a statistics cookie in the headline!
  8420. (defun org-summary-todo (n-done n-not-done)
  8421. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8422. (let (org-log-done org-log-states) ; turn off logging
  8423. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8424. (defvar org-todo-statistics-hook nil
  8425. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8426. This hook runs even if there is no statistics cookie present, in which case
  8427. `org-after-todo-statistics-hook' would not run.")
  8428. (defun org-todo-trigger-tag-changes (state)
  8429. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8430. (let ((l org-todo-state-tags-triggers)
  8431. changes)
  8432. (when (or (not state) (equal state ""))
  8433. (setq changes (append changes (cdr (assoc "" l)))))
  8434. (when (and (stringp state) (> (length state) 0))
  8435. (setq changes (append changes (cdr (assoc state l)))))
  8436. (when (member state org-not-done-keywords)
  8437. (setq changes (append changes (cdr (assq 'todo l)))))
  8438. (when (member state org-done-keywords)
  8439. (setq changes (append changes (cdr (assq 'done l)))))
  8440. (dolist (c changes)
  8441. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8442. (defun org-local-logging (value)
  8443. "Get logging settings from a property VALUE."
  8444. ;; Directly set the variables, they are already local.
  8445. (setq org-log-done nil
  8446. org-log-repeat nil
  8447. org-todo-log-states nil)
  8448. (dolist (w (split-string value))
  8449. (let (a)
  8450. (cond
  8451. ((setq a (assoc w org-startup-options))
  8452. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8453. (set (nth 1 a) (nth 2 a))))
  8454. ((setq a (org-extract-log-state-settings w))
  8455. (and (member (car a) org-todo-keywords-1)
  8456. (push a org-todo-log-states)))))))
  8457. (defun org-get-todo-sequence-head (kwd)
  8458. "Return the head of the TODO sequence to which KWD belongs.
  8459. If KWD is not set, check if there is a text property remembering the
  8460. right sequence."
  8461. (let (p)
  8462. (cond
  8463. ((not kwd)
  8464. (or (get-text-property (point-at-bol) 'org-todo-head)
  8465. (progn
  8466. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  8467. nil (point-at-eol)))
  8468. (get-text-property p 'org-todo-head))))
  8469. ((not (member kwd org-todo-keywords-1))
  8470. (car org-todo-keywords-1))
  8471. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8472. (defun org-fast-todo-selection (&optional current-state)
  8473. "Fast TODO keyword selection with single keys.
  8474. Returns the new TODO keyword, or nil if no state change should occur.
  8475. When CURRENT-STATE is given and selection letters are not unique globally,
  8476. prefer a state in the current sequence over on in another sequence."
  8477. (let* ((fulltable org-todo-key-alist)
  8478. (head (org-get-todo-sequence-head current-state))
  8479. (done-keywords org-done-keywords) ;; needed for the faces.
  8480. (maxlen (apply 'max (mapcar
  8481. (lambda (x)
  8482. (if (stringp (car x)) (string-width (car x)) 0))
  8483. fulltable)))
  8484. (expert (equal org-use-fast-todo-selection 'expert))
  8485. (prompt "")
  8486. (fwidth (+ maxlen 3 1 3))
  8487. (ncol (/ (- (window-width) 4) fwidth))
  8488. tg cnt e c tbl subtable
  8489. groups ingroup in-current-sequence)
  8490. (save-excursion
  8491. (save-window-excursion
  8492. (if expert
  8493. (set-buffer (get-buffer-create " *Org todo*"))
  8494. (delete-other-windows)
  8495. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8496. (org-switch-to-buffer-other-window " *Org todo*"))
  8497. (erase-buffer)
  8498. (setq-local org-done-keywords done-keywords)
  8499. (setq tbl fulltable cnt 0)
  8500. (while (setq e (pop tbl))
  8501. (cond
  8502. ((equal e '(:startgroup))
  8503. (push '() groups) (setq ingroup t)
  8504. (unless (= cnt 0)
  8505. (setq cnt 0)
  8506. (insert "\n"))
  8507. (setq prompt (concat prompt "{"))
  8508. (insert "{ "))
  8509. ((equal e '(:endgroup))
  8510. (setq ingroup nil cnt 0 in-current-sequence nil)
  8511. (setq prompt (concat prompt "}"))
  8512. (insert "}\n"))
  8513. ((equal e '(:newline))
  8514. (unless (= cnt 0)
  8515. (setq cnt 0)
  8516. (insert "\n")
  8517. (setq e (car tbl))
  8518. (while (equal (car tbl) '(:newline))
  8519. (insert "\n")
  8520. (setq tbl (cdr tbl)))))
  8521. (t
  8522. (setq tg (car e) c (cdr e))
  8523. (if (equal tg head) (setq in-current-sequence t))
  8524. (when ingroup (push tg (car groups)))
  8525. (when in-current-sequence (push e subtable))
  8526. (setq tg (org-add-props tg nil 'face
  8527. (org-get-todo-face tg)))
  8528. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8529. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8530. (insert "[" c "] " tg (make-string
  8531. (- fwidth 4 (length tg)) ?\ ))
  8532. (when (and (= (setq cnt (1+ cnt)) ncol)
  8533. ;; Avoid lines with just a closing delimiter.
  8534. (not (equal (car tbl) '(:endgroup))))
  8535. (insert "\n")
  8536. (when ingroup (insert " "))
  8537. (setq cnt 0)))))
  8538. (insert "\n")
  8539. (goto-char (point-min))
  8540. (unless expert (org-fit-window-to-buffer))
  8541. (message (concat "[a-z..]:Set [SPC]:clear"
  8542. (if expert (concat "\n" prompt) "")))
  8543. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8544. (setq subtable (nreverse subtable))
  8545. (cond
  8546. ((or (= c ?\C-g)
  8547. (and (= c ?q) (not (rassoc c fulltable))))
  8548. (setq quit-flag t))
  8549. ((= c ?\ ) nil)
  8550. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8551. tg (car e))
  8552. tg)
  8553. (t (setq quit-flag t)))))))
  8554. (defun org-entry-is-todo-p ()
  8555. (member (org-get-todo-state) org-not-done-keywords))
  8556. (defun org-entry-is-done-p ()
  8557. (member (org-get-todo-state) org-done-keywords))
  8558. (defun org-get-todo-state ()
  8559. "Return the TODO keyword of the current subtree."
  8560. (save-excursion
  8561. (org-back-to-heading t)
  8562. (and (let ((case-fold-search nil))
  8563. (looking-at org-todo-line-regexp))
  8564. (match-end 2)
  8565. (match-string 2))))
  8566. (defun org-at-date-range-p (&optional inactive-ok)
  8567. "Non-nil if point is inside a date range.
  8568. When optional argument INACTIVE-OK is non-nil, also consider
  8569. inactive time ranges.
  8570. When this function returns a non-nil value, match data is set
  8571. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8572. on INACTIVE-OK."
  8573. (interactive)
  8574. (save-excursion
  8575. (catch 'exit
  8576. (let ((pos (point)))
  8577. (skip-chars-backward "^[<\r\n")
  8578. (skip-chars-backward "<[")
  8579. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8580. (>= (match-end 0) pos)
  8581. (throw 'exit t))
  8582. (skip-chars-backward "^<[\r\n")
  8583. (skip-chars-backward "<[")
  8584. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8585. (>= (match-end 0) pos)
  8586. (throw 'exit t)))
  8587. nil)))
  8588. (defun org-get-repeat (&optional timestamp)
  8589. "Check if there is a time-stamp with repeater in this entry.
  8590. Return the repeater, as a string, or nil. Also return nil when
  8591. this function is called before first heading.
  8592. When optional argument TIMESTAMP is a string, extract the
  8593. repeater from there instead."
  8594. (save-match-data
  8595. (cond
  8596. (timestamp
  8597. (and (string-match org-repeat-re timestamp)
  8598. (match-string-no-properties 1 timestamp)))
  8599. ((org-before-first-heading-p) nil)
  8600. (t
  8601. (save-excursion
  8602. (org-back-to-heading t)
  8603. (let ((end (org-entry-end-position)))
  8604. (catch :repeat
  8605. (while (re-search-forward org-repeat-re end t)
  8606. (when (save-match-data (org-at-timestamp-p 'agenda))
  8607. (throw :repeat (match-string-no-properties 1)))))))))))
  8608. (defvar org-last-changed-timestamp)
  8609. (defvar org-last-inserted-timestamp)
  8610. (defvar org-log-post-message)
  8611. (defvar org-log-note-purpose)
  8612. (defvar org-log-note-how nil)
  8613. (defvar org-log-note-extra)
  8614. (defvar org-log-setup nil)
  8615. (defun org-auto-repeat-maybe (done-word)
  8616. "Check if the current headline contains a repeated time-stamp.
  8617. If yes, set TODO state back to what it was and change the base date
  8618. of repeating deadline/scheduled time stamps to new date.
  8619. This function is run automatically after each state change to a DONE state."
  8620. (let* ((repeat (org-get-repeat))
  8621. (aa (assoc org-last-state org-todo-kwd-alist))
  8622. (interpret (nth 1 aa))
  8623. (head (nth 2 aa))
  8624. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8625. (msg "Entry repeats: ")
  8626. (org-log-done nil)
  8627. (org-todo-log-states nil)
  8628. (end (copy-marker (org-entry-end-position))))
  8629. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8630. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8631. (let ((to-state
  8632. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8633. (and (stringp org-todo-repeat-to-state)
  8634. org-todo-repeat-to-state)
  8635. (and org-todo-repeat-to-state org-last-state))))
  8636. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8637. to-state)
  8638. ((eq interpret 'type) org-last-state)
  8639. (head)
  8640. (t 'none))))
  8641. (org-back-to-heading t)
  8642. (org-add-planning-info nil nil 'closed)
  8643. ;; When `org-log-repeat' is non-nil or entry contains
  8644. ;; a clock, set LAST_REPEAT property.
  8645. (when (or org-log-repeat
  8646. (catch :clock
  8647. (save-excursion
  8648. (while (re-search-forward org-clock-line-re end t)
  8649. (when (org-at-clock-log-p) (throw :clock t))))))
  8650. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8651. (org-time-stamp-format t t))))
  8652. (when org-log-repeat
  8653. (if org-log-setup
  8654. ;; We are already setup for some record.
  8655. (when (eq org-log-repeat 'note)
  8656. ;; Make sure we take a note, not only a time stamp.
  8657. (setq org-log-note-how 'note))
  8658. ;; Set up for taking a record.
  8659. (org-add-log-setup 'state
  8660. (or done-word (car org-done-keywords))
  8661. org-last-state
  8662. org-log-repeat)))
  8663. ;; Time-stamps without a repeater are usually skipped. However,
  8664. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8665. ;; longer relevant.
  8666. (save-excursion
  8667. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8668. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8669. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8670. ;; Update every time-stamp with a repeater in the entry.
  8671. (let ((planning-re (regexp-opt
  8672. (list org-scheduled-string org-deadline-string))))
  8673. (while (re-search-forward org-repeat-re end t)
  8674. (let* ((ts (match-string 0))
  8675. (type (if (not (org-at-planning-p)) "Plain:"
  8676. (save-excursion
  8677. (re-search-backward
  8678. planning-re (line-beginning-position) t)
  8679. (match-string 0)))))
  8680. (when (and (org-at-timestamp-p 'agenda)
  8681. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8682. (let ((n (string-to-number (match-string 2 ts)))
  8683. (what (match-string 3 ts)))
  8684. (when (equal what "w") (setq n (* n 7) what "d"))
  8685. (when (and (equal what "h")
  8686. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8687. ts)))
  8688. (user-error
  8689. "Cannot repeat in %d hour(s) because no hour has been set"
  8690. n))
  8691. ;; Preparation, see if we need to modify the start
  8692. ;; date for the change.
  8693. (when (match-end 1)
  8694. (let ((time (save-match-data (org-time-string-to-time ts)))
  8695. (repeater-type (match-string 1 ts)))
  8696. (cond
  8697. ((equal "." repeater-type)
  8698. ;; Shift starting date to today, or now if
  8699. ;; repeater is by hours.
  8700. (if (equal what "h")
  8701. (org-timestamp-change
  8702. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8703. (org-timestamp-change
  8704. (- (org-today) (time-to-days time)) 'day)))
  8705. ((equal "+" repeater-type)
  8706. (let ((nshiftmax 10)
  8707. (nshift 0))
  8708. (while (or (= nshift 0)
  8709. (not (time-less-p nil time)))
  8710. (when (= nshiftmax (cl-incf nshift))
  8711. (or (y-or-n-p
  8712. (format "%d repeater intervals were not \
  8713. enough to shift date past today. Continue? "
  8714. nshift))
  8715. (user-error "Abort")))
  8716. (org-timestamp-change n (cdr (assoc what whata)))
  8717. (org-in-regexp org-ts-regexp3)
  8718. (setq ts (match-string 1))
  8719. (setq time
  8720. (save-match-data
  8721. (org-time-string-to-time ts)))))
  8722. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8723. ;; Rematch, so that we have everything in place
  8724. ;; for the real shift.
  8725. (org-in-regexp org-ts-regexp3)
  8726. (setq ts (match-string 1))
  8727. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8728. ts)))))
  8729. (save-excursion
  8730. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8731. (setq msg
  8732. (concat msg type " " org-last-changed-timestamp " ")))))))
  8733. (run-hooks 'org-todo-repeat-hook)
  8734. (setq org-log-post-message msg)
  8735. (message msg))))
  8736. (defun org-show-todo-tree (arg)
  8737. "Make a compact tree which shows all headlines marked with TODO.
  8738. The tree will show the lines where the regexp matches, and all higher
  8739. headlines above the match.
  8740. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8741. With a numeric prefix N, construct a sparse tree for the Nth element
  8742. of `org-todo-keywords-1'."
  8743. (interactive "P")
  8744. (let ((case-fold-search nil)
  8745. (kwd-re
  8746. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8747. ((equal arg '(4))
  8748. (let ((kwd
  8749. (completing-read "Keyword (or KWD1|KWD2|...): "
  8750. (mapcar #'list org-todo-keywords-1))))
  8751. (concat "\\("
  8752. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8753. "\\)\\>")))
  8754. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8755. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8756. org-todo-keywords-1)))
  8757. (t (user-error "Invalid prefix argument: %s" arg)))))
  8758. (message "%d TODO entries found"
  8759. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8760. (defun org--deadline-or-schedule (arg type time)
  8761. "Insert DEADLINE or SCHEDULE information in current entry.
  8762. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8763. `org-schedule' for information about ARG and TIME arguments."
  8764. (org-fold-core-ignore-modifications
  8765. (let* ((deadline? (eq type 'deadline))
  8766. (keyword (if deadline? org-deadline-string org-scheduled-string))
  8767. (log (if deadline? org-log-redeadline org-log-reschedule))
  8768. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  8769. (old-date-time (and old-date (org-time-string-to-time old-date)))
  8770. ;; Save repeater cookie from either TIME or current scheduled
  8771. ;; time stamp. We are going to insert it back at the end of
  8772. ;; the process.
  8773. (repeater (or (and (org-string-nw-p time)
  8774. ;; We use `org-repeat-re' because we need
  8775. ;; to tell the difference between a real
  8776. ;; repeater and a time delta, e.g. "+2d".
  8777. (string-match org-repeat-re time)
  8778. (match-string 1 time))
  8779. (and (org-string-nw-p old-date)
  8780. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8781. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8782. old-date)
  8783. (match-string 1 old-date)))))
  8784. (pcase arg
  8785. (`(4)
  8786. (if (not old-date)
  8787. (message (if deadline? "Entry had no deadline to remove"
  8788. "Entry was not scheduled"))
  8789. (when (and old-date log)
  8790. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  8791. nil old-date log))
  8792. (org-remove-timestamp-with-keyword keyword)
  8793. (message (if deadline? "Entry no longer has a deadline."
  8794. "Entry is no longer scheduled."))))
  8795. (`(16)
  8796. (save-excursion
  8797. (org-back-to-heading t)
  8798. (let ((regexp (if deadline? org-deadline-time-regexp
  8799. org-scheduled-time-regexp)))
  8800. (if (not (re-search-forward regexp (line-end-position 2) t))
  8801. (user-error (if deadline? "No deadline information to update"
  8802. "No scheduled information to update"))
  8803. (let* ((rpl0 (match-string 1))
  8804. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  8805. (msg (if deadline? "Warn starting from" "Delay until")))
  8806. (replace-match
  8807. (concat keyword
  8808. " <" rpl
  8809. (format " -%dd"
  8810. (abs (- (time-to-days
  8811. (save-match-data
  8812. (org-read-date
  8813. nil t nil msg old-date-time)))
  8814. (time-to-days old-date-time))))
  8815. ">") t t))))))
  8816. (_
  8817. (org-add-planning-info type time 'closed)
  8818. (when (and old-date
  8819. log
  8820. (not (equal old-date org-last-inserted-timestamp)))
  8821. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  8822. org-last-inserted-timestamp
  8823. old-date
  8824. log))
  8825. (when repeater
  8826. (save-excursion
  8827. (org-back-to-heading t)
  8828. (when (re-search-forward
  8829. (concat keyword " " org-last-inserted-timestamp)
  8830. (line-end-position 2)
  8831. t)
  8832. (goto-char (1- (match-end 0)))
  8833. (insert-and-inherit " " repeater)
  8834. (setq org-last-inserted-timestamp
  8835. (concat (substring org-last-inserted-timestamp 0 -1)
  8836. " " repeater
  8837. (substring org-last-inserted-timestamp -1))))))
  8838. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  8839. org-last-inserted-timestamp))))))
  8840. (defun org-deadline (arg &optional time)
  8841. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  8842. When called interactively, this command pops up the Emacs calendar to let
  8843. the user select a date.
  8844. With one universal prefix argument, remove any deadline from the item.
  8845. With two universal prefix arguments, prompt for a warning delay.
  8846. With argument TIME, set the deadline at the corresponding date. TIME
  8847. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  8848. (interactive "P")
  8849. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8850. (org-map-entries
  8851. (lambda () (org--deadline-or-schedule arg 'deadline time))
  8852. nil
  8853. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8854. 'region-start-level
  8855. 'region)
  8856. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  8857. (org--deadline-or-schedule arg 'deadline time)))
  8858. (defun org-schedule (arg &optional time)
  8859. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  8860. When called interactively, this command pops up the Emacs calendar to let
  8861. the user select a date.
  8862. With one universal prefix argument, remove any scheduling date from the item.
  8863. With two universal prefix arguments, prompt for a delay cookie.
  8864. With argument TIME, scheduled at the corresponding date. TIME can
  8865. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  8866. (interactive "P")
  8867. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8868. (org-map-entries
  8869. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  8870. nil
  8871. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8872. 'region-start-level
  8873. 'region)
  8874. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  8875. (org--deadline-or-schedule arg 'scheduled time)))
  8876. (defun org-get-scheduled-time (pom &optional inherit)
  8877. "Get the scheduled time as a time tuple, of a format suitable
  8878. for calling org-schedule with, or if there is no scheduling,
  8879. returns nil."
  8880. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  8881. (when time
  8882. (org-time-string-to-time time))))
  8883. (defun org-get-deadline-time (pom &optional inherit)
  8884. "Get the deadline as a time tuple, of a format suitable for
  8885. calling org-deadline with, or if there is no scheduling, returns
  8886. nil."
  8887. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  8888. (when time
  8889. (org-time-string-to-time time))))
  8890. (defun org-remove-timestamp-with-keyword (keyword)
  8891. "Remove all time stamps with KEYWORD in the current entry."
  8892. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  8893. beg)
  8894. (save-excursion
  8895. (org-back-to-heading t)
  8896. (setq beg (point))
  8897. (outline-next-heading)
  8898. (while (re-search-backward re beg t)
  8899. (replace-match "")
  8900. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  8901. (equal (char-before) ?\ ))
  8902. (backward-delete-char 1)
  8903. (when (string-match "^[ \t]*$" (buffer-substring
  8904. (point-at-bol) (point-at-eol)))
  8905. (delete-region (point-at-bol)
  8906. (min (point-max) (1+ (point-at-eol))))))))))
  8907. (defvar org-time-was-given) ; dynamically scoped parameter
  8908. (defvar org-end-time-was-given) ; dynamically scoped parameter
  8909. (defun org-at-planning-p ()
  8910. "Non-nil when point is on a planning info line."
  8911. ;; This is as accurate and faster than `org-element-at-point' since
  8912. ;; planning info location is fixed in the section.
  8913. (or (let ((cached (org-element-at-point nil 'cached)))
  8914. (and cached
  8915. (eq 'planning (org-element-type cached))))
  8916. (org-with-wide-buffer
  8917. (beginning-of-line)
  8918. (and (looking-at-p org-planning-line-re)
  8919. (eq (point)
  8920. (ignore-errors
  8921. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  8922. (org-back-to-heading t)
  8923. (org-with-limited-levels (org-back-to-heading t)))
  8924. (line-beginning-position 2)))))))
  8925. (defun org-add-planning-info (what &optional time &rest remove)
  8926. "Insert new timestamp with keyword in the planning line.
  8927. WHAT indicates what kind of time stamp to add. It is a symbol
  8928. among `closed', `deadline', `scheduled' and nil. TIME indicates
  8929. the time to use. If none is given, the user is prompted for
  8930. a date. REMOVE indicates what kind of entries to remove. An old
  8931. WHAT entry will also be removed."
  8932. (org-fold-core-ignore-modifications
  8933. (let (org-time-was-given org-end-time-was-given default-time default-input)
  8934. (when (and (memq what '(scheduled deadline))
  8935. (or (not time)
  8936. (and (stringp time)
  8937. (string-match "^[-+]+[0-9]" time))))
  8938. ;; Try to get a default date/time from existing timestamp
  8939. (save-excursion
  8940. (org-back-to-heading t)
  8941. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  8942. (when (re-search-forward (if (eq what 'scheduled)
  8943. org-scheduled-time-regexp
  8944. org-deadline-time-regexp)
  8945. end t)
  8946. (setq ts (match-string 1)
  8947. default-time (org-time-string-to-time ts)
  8948. default-input (and ts (org-get-compact-tod ts)))))))
  8949. (when what
  8950. (setq time
  8951. (if (stringp time)
  8952. ;; This is a string (relative or absolute), set
  8953. ;; proper date.
  8954. (apply #'encode-time
  8955. (org-read-date-analyze
  8956. time default-time (decode-time default-time)))
  8957. ;; If necessary, get the time from the user
  8958. (or time (org-read-date nil 'to-time nil
  8959. (cl-case what
  8960. (deadline "DEADLINE")
  8961. (scheduled "SCHEDULED")
  8962. (otherwise nil))
  8963. default-time default-input)))))
  8964. (org-with-wide-buffer
  8965. (org-back-to-heading t)
  8966. (let ((planning? (save-excursion
  8967. (forward-line)
  8968. (looking-at-p org-planning-line-re))))
  8969. (cond
  8970. (planning?
  8971. (forward-line)
  8972. ;; Move to current indentation.
  8973. (skip-chars-forward " \t")
  8974. ;; Check if we have to remove something.
  8975. (dolist (type (if what (cons what remove) remove))
  8976. (save-excursion
  8977. (when (re-search-forward
  8978. (cl-case type
  8979. (closed org-closed-time-regexp)
  8980. (deadline org-deadline-time-regexp)
  8981. (scheduled org-scheduled-time-regexp)
  8982. (otherwise (error "Invalid planning type: %s" type)))
  8983. (line-end-position)
  8984. t)
  8985. ;; Delete until next keyword or end of line.
  8986. (delete-region
  8987. (match-beginning 0)
  8988. (if (re-search-forward org-keyword-time-not-clock-regexp
  8989. (line-end-position)
  8990. t)
  8991. (match-beginning 0)
  8992. (line-end-position))))))
  8993. ;; If there is nothing more to add and no more keyword is
  8994. ;; left, remove the line completely.
  8995. (if (and (looking-at-p "[ \t]*$") (not what))
  8996. (delete-region (line-end-position 0)
  8997. (line-end-position))
  8998. ;; If we removed last keyword, do not leave trailing white
  8999. ;; space at the end of line.
  9000. (let ((p (point)))
  9001. (save-excursion
  9002. (end-of-line)
  9003. (unless (= (skip-chars-backward " \t" p) 0)
  9004. (delete-region (point) (line-end-position)))))))
  9005. (what
  9006. (end-of-line)
  9007. (insert-and-inherit "\n")
  9008. (when org-adapt-indentation
  9009. (indent-to-column (1+ (org-outline-level)))))
  9010. (t nil)))
  9011. (when what
  9012. ;; Insert planning keyword.
  9013. (insert-and-inherit (cl-case what
  9014. (closed org-closed-string)
  9015. (deadline org-deadline-string)
  9016. (scheduled org-scheduled-string)
  9017. (otherwise (error "Invalid planning type: %s" what)))
  9018. " ")
  9019. ;; Insert associated timestamp.
  9020. (let ((ts (org-insert-time-stamp
  9021. time
  9022. (or org-time-was-given
  9023. (and (eq what 'closed) org-log-done-with-time))
  9024. (eq what 'closed)
  9025. nil nil (list org-end-time-was-given))))
  9026. (unless (eolp) (insert " "))
  9027. ts))))))
  9028. (defvar org-log-note-marker (make-marker)
  9029. "Marker pointing at the entry where the note is to be inserted.")
  9030. (defvar org-log-note-purpose nil)
  9031. (defvar org-log-note-state nil)
  9032. (defvar org-log-note-previous-state nil)
  9033. (defvar org-log-note-extra nil)
  9034. (defvar org-log-note-window-configuration nil)
  9035. (defvar org-log-note-return-to (make-marker))
  9036. (defvar org-log-note-effective-time nil
  9037. "Remembered current time.
  9038. So that dynamically scoped `org-extend-today-until' affects
  9039. timestamps in state change log.")
  9040. (defvar org-log-post-message nil
  9041. "Message to be displayed after a log note has been stored.
  9042. The auto-repeater uses this.")
  9043. (defun org-add-note ()
  9044. "Add a note to the current entry.
  9045. This is done in the same way as adding a state change note."
  9046. (interactive)
  9047. (org-add-log-setup 'note))
  9048. (defun org-log-beginning (&optional create)
  9049. "Return expected start of log notes in current entry.
  9050. When optional argument CREATE is non-nil, the function creates
  9051. a drawer to store notes, if necessary. Returned position ignores
  9052. narrowing."
  9053. (org-with-wide-buffer
  9054. (let ((drawer (org-log-into-drawer)))
  9055. (cond
  9056. (drawer
  9057. (org-end-of-meta-data)
  9058. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9059. (end (if (org-at-heading-p) (point)
  9060. (save-excursion (outline-next-heading) (point))))
  9061. (case-fold-search t))
  9062. (catch 'exit
  9063. ;; Try to find existing drawer.
  9064. (while (re-search-forward regexp end t)
  9065. (let ((element (org-element-at-point)))
  9066. (when (eq (org-element-type element) 'drawer)
  9067. (let ((cend (org-element-property :contents-end element)))
  9068. (when (and (not org-log-states-order-reversed) cend)
  9069. (goto-char cend)))
  9070. (throw 'exit nil))))
  9071. ;; No drawer found. Create one, if permitted.
  9072. (when create
  9073. ;; Avoid situation when we insert drawer right before
  9074. ;; first "*". Otherwise, if the previous heading is
  9075. ;; folded, we are inserting after visible newline at
  9076. ;; the end of the fold, thus breaking the fold
  9077. ;; continuity.
  9078. (when (org-at-heading-p) (backward-char))
  9079. (org-fold-core-ignore-modifications
  9080. (unless (bolp) (insert-and-inherit "\n"))
  9081. (let ((beg (point)))
  9082. (insert-and-inherit ":" drawer ":\n:END:\n")
  9083. (org-indent-region beg (point))
  9084. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9085. (end-of-line -1))))
  9086. (t
  9087. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9088. (skip-chars-forward " \t\n")
  9089. (beginning-of-line)
  9090. (unless org-log-states-order-reversed
  9091. (org-skip-over-state-notes)
  9092. (skip-chars-backward " \t\n")
  9093. (beginning-of-line 2)))))
  9094. (if (bolp) (point) (line-beginning-position 2))))
  9095. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9096. "Set up the post command hook to take a note.
  9097. If this is about to TODO state change, the new state is expected in STATE.
  9098. HOW is an indicator what kind of note should be created.
  9099. EXTRA is additional text that will be inserted into the notes buffer."
  9100. (move-marker org-log-note-marker (point))
  9101. (setq org-log-note-purpose purpose
  9102. org-log-note-state state
  9103. org-log-note-previous-state prev-state
  9104. org-log-note-how how
  9105. org-log-note-extra extra
  9106. org-log-note-effective-time (org-current-effective-time)
  9107. org-log-setup t)
  9108. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9109. (defun org-skip-over-state-notes ()
  9110. "Skip past the list of State notes in an entry."
  9111. (when (ignore-errors (goto-char (org-in-item-p)))
  9112. (let* ((struct (org-list-struct))
  9113. (prevs (org-list-prevs-alist struct))
  9114. (regexp
  9115. (concat "[ \t]*- +"
  9116. (replace-regexp-in-string
  9117. " +" " +"
  9118. (org-replace-escapes
  9119. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9120. `(("%d" . ,org-ts-regexp-inactive)
  9121. ("%D" . ,org-ts-regexp)
  9122. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9123. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9124. ("%t" . ,org-ts-regexp-inactive)
  9125. ("%T" . ,org-ts-regexp)
  9126. ("%u" . ".*?")
  9127. ("%U" . ".*?")))))))
  9128. (while (looking-at-p regexp)
  9129. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9130. (org-list-get-item-end (point) struct)))))))
  9131. (defun org-add-log-note (&optional _purpose)
  9132. "Pop up a window for taking a note, and add this note later."
  9133. (remove-hook 'post-command-hook 'org-add-log-note)
  9134. (setq org-log-setup nil)
  9135. (setq org-log-note-window-configuration (current-window-configuration))
  9136. (delete-other-windows)
  9137. (move-marker org-log-note-return-to (point))
  9138. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9139. (goto-char org-log-note-marker)
  9140. (org-switch-to-buffer-other-window "*Org Note*")
  9141. (erase-buffer)
  9142. (if (memq org-log-note-how '(time state))
  9143. (org-store-log-note)
  9144. (let ((org-inhibit-startup t)) (org-mode))
  9145. (insert (format "# Insert note for %s.
  9146. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9147. (cl-case org-log-note-purpose
  9148. (clock-out "stopped clock")
  9149. (done "closed todo item")
  9150. (reschedule "rescheduling")
  9151. (delschedule "no longer scheduled")
  9152. (redeadline "changing deadline")
  9153. (deldeadline "removing deadline")
  9154. (refile "refiling")
  9155. (note "this entry")
  9156. (state
  9157. (format "state change from \"%s\" to \"%s\""
  9158. (or org-log-note-previous-state "")
  9159. (or org-log-note-state "")))
  9160. (t (error "This should not happen")))))
  9161. (when org-log-note-extra (insert org-log-note-extra))
  9162. (setq-local org-finish-function 'org-store-log-note)
  9163. (run-hooks 'org-log-buffer-setup-hook)))
  9164. (defvar org-note-abort nil) ; dynamically scoped
  9165. (defun org-store-log-note ()
  9166. "Finish taking a log note, and insert it to where it belongs."
  9167. (let ((txt (prog1 (buffer-string)
  9168. (kill-buffer)))
  9169. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9170. lines)
  9171. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9172. (setq txt (replace-match "" t t txt)))
  9173. (when (string-match "\\s-+\\'" txt)
  9174. (setq txt (replace-match "" t t txt)))
  9175. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9176. (when (org-string-nw-p note)
  9177. (setq note
  9178. (org-replace-escapes
  9179. note
  9180. (list (cons "%u" (user-login-name))
  9181. (cons "%U" user-full-name)
  9182. (cons "%t" (format-time-string
  9183. (org-time-stamp-format 'long 'inactive)
  9184. org-log-note-effective-time))
  9185. (cons "%T" (format-time-string
  9186. (org-time-stamp-format 'long nil)
  9187. org-log-note-effective-time))
  9188. (cons "%d" (format-time-string
  9189. (org-time-stamp-format nil 'inactive)
  9190. org-log-note-effective-time))
  9191. (cons "%D" (format-time-string
  9192. (org-time-stamp-format nil nil)
  9193. org-log-note-effective-time))
  9194. (cons "%s" (cond
  9195. ((not org-log-note-state) "")
  9196. ((string-match-p org-ts-regexp
  9197. org-log-note-state)
  9198. (format "\"[%s]\""
  9199. (substring org-log-note-state 1 -1)))
  9200. (t (format "\"%s\"" org-log-note-state))))
  9201. (cons "%S"
  9202. (cond
  9203. ((not org-log-note-previous-state) "")
  9204. ((string-match-p org-ts-regexp
  9205. org-log-note-previous-state)
  9206. (format "\"[%s]\""
  9207. (substring
  9208. org-log-note-previous-state 1 -1)))
  9209. (t (format "\"%s\""
  9210. org-log-note-previous-state)))))))
  9211. (when lines (setq note (concat note " \\\\")))
  9212. (push note lines))
  9213. (when (and lines (not org-note-abort))
  9214. (with-current-buffer (marker-buffer org-log-note-marker)
  9215. (org-fold-core-ignore-modifications
  9216. (org-with-wide-buffer
  9217. ;; Find location for the new note.
  9218. (goto-char org-log-note-marker)
  9219. (set-marker org-log-note-marker nil)
  9220. ;; Note associated to a clock is to be located right after
  9221. ;; the clock. Do not move point.
  9222. (unless (eq org-log-note-purpose 'clock-out)
  9223. (goto-char (org-log-beginning t)))
  9224. ;; Make sure point is at the beginning of an empty line.
  9225. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9226. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9227. ;; In an existing list, add a new item at the top level.
  9228. ;; Otherwise, indent line like a regular one.
  9229. (let ((itemp (org-in-item-p)))
  9230. (if itemp
  9231. (indent-line-to
  9232. (let ((struct (save-excursion
  9233. (goto-char itemp) (org-list-struct))))
  9234. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9235. (org-indent-line)))
  9236. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9237. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9238. (dolist (line lines)
  9239. (insert-and-inherit "\n")
  9240. (indent-line-to ind)
  9241. (insert-and-inherit line)))
  9242. (message "Note stored")
  9243. (org-back-to-heading t))))))
  9244. ;; Don't add undo information when called from `org-agenda-todo'.
  9245. (set-window-configuration org-log-note-window-configuration)
  9246. (with-current-buffer (marker-buffer org-log-note-return-to)
  9247. (goto-char org-log-note-return-to))
  9248. (move-marker org-log-note-return-to nil)
  9249. (when org-log-post-message (message "%s" org-log-post-message)))
  9250. (defun org-remove-empty-drawer-at (pos)
  9251. "Remove an empty drawer at position POS.
  9252. POS may also be a marker."
  9253. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9254. (org-with-wide-buffer
  9255. (goto-char pos)
  9256. (let ((drawer (org-element-at-point)))
  9257. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9258. (not (org-element-property :contents-begin drawer)))
  9259. (delete-region (org-element-property :begin drawer)
  9260. (progn (goto-char (org-element-property :end drawer))
  9261. (skip-chars-backward " \r\t\n")
  9262. (forward-line)
  9263. (point))))))))
  9264. (defvar org-ts-type nil)
  9265. (defun org-sparse-tree (&optional arg type)
  9266. "Create a sparse tree, prompt for the details.
  9267. This command can create sparse trees. You first need to select the type
  9268. of match used to create the tree:
  9269. t Show all TODO entries.
  9270. T Show entries with a specific TODO keyword.
  9271. m Show entries selected by a tags/property match.
  9272. p Enter a property name and its value (both with completion on existing
  9273. names/values) and show entries with that property.
  9274. r Show entries matching a regular expression (`/' can be used as well).
  9275. b Show deadlines and scheduled items before a date.
  9276. a Show deadlines and scheduled items after a date.
  9277. d Show deadlines due within `org-deadline-warning-days'.
  9278. D Show deadlines and scheduled items between a date range."
  9279. (interactive "P")
  9280. (setq type (or type org-sparse-tree-default-date-type))
  9281. (setq org-ts-type type)
  9282. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9283. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9284. [c]ycle through date types: %s"
  9285. (cl-case type
  9286. (all "all timestamps")
  9287. (scheduled "only scheduled")
  9288. (deadline "only deadline")
  9289. (active "only active timestamps")
  9290. (inactive "only inactive timestamps")
  9291. (closed "with a closed time-stamp")
  9292. (otherwise "scheduled/deadline")))
  9293. (let ((answer (read-char-exclusive)))
  9294. (cl-case answer
  9295. (?c
  9296. (org-sparse-tree
  9297. arg
  9298. (cadr
  9299. (memq type '(nil all scheduled deadline active inactive closed)))))
  9300. (?d (call-interactively 'org-check-deadlines))
  9301. (?b (call-interactively 'org-check-before-date))
  9302. (?a (call-interactively 'org-check-after-date))
  9303. (?D (call-interactively 'org-check-dates-range))
  9304. (?t (call-interactively 'org-show-todo-tree))
  9305. (?T (org-show-todo-tree '(4)))
  9306. (?m (call-interactively 'org-match-sparse-tree))
  9307. ((?p ?P)
  9308. (let* ((kwd (completing-read
  9309. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9310. (value (completing-read
  9311. "Value: " (mapcar #'list (org-property-values kwd)))))
  9312. (unless (string-match "\\`{.*}\\'" value)
  9313. (setq value (concat "\"" value "\"")))
  9314. (org-match-sparse-tree arg (concat kwd "=" value))))
  9315. ((?r ?R ?/) (call-interactively 'org-occur))
  9316. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9317. (defvar-local org-occur-highlights nil
  9318. "List of overlays used for occur matches.")
  9319. (defvar-local org-occur-parameters nil
  9320. "Parameters of the active org-occur calls.
  9321. This is a list, each call to org-occur pushes as cons cell,
  9322. containing the regular expression and the callback, onto the list.
  9323. The list can contain several entries if `org-occur' has been called
  9324. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9325. will only contain one set of parameters. When the highlights are
  9326. removed (for example with `C-c C-c', or with the next edit (depending
  9327. on `org-remove-highlights-with-change'), this variable is emptied
  9328. as well.")
  9329. (defun org-occur (regexp &optional keep-previous callback)
  9330. "Make a compact tree showing all matches of REGEXP.
  9331. The tree will show the lines where the regexp matches, and any other context
  9332. defined in `org-fold-show-context-detail', which see.
  9333. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9334. done by a previous call to `org-occur' will be kept, to allow stacking of
  9335. calls to this command.
  9336. Optional argument CALLBACK can be a function of no argument. In this case,
  9337. it is called with point at the end of the match, match data being set
  9338. accordingly. Current match is shown only if the return value is non-nil.
  9339. The function must neither move point nor alter narrowing."
  9340. (interactive "sRegexp: \nP")
  9341. (when (equal regexp "")
  9342. (user-error "Regexp cannot be empty"))
  9343. (unless keep-previous
  9344. (org-remove-occur-highlights nil nil t))
  9345. (push (cons regexp callback) org-occur-parameters)
  9346. (let ((cnt 0))
  9347. (save-excursion
  9348. (goto-char (point-min))
  9349. (when (or (not keep-previous) ; do not want to keep
  9350. (not org-occur-highlights)) ; no previous matches
  9351. ;; hide everything
  9352. (org-cycle-overview))
  9353. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9354. (isearch-no-upper-case-p regexp t)
  9355. org-occur-case-fold-search)))
  9356. (while (re-search-forward regexp nil t)
  9357. (when (or (not callback)
  9358. (save-match-data (funcall callback)))
  9359. (setq cnt (1+ cnt))
  9360. (when org-highlight-sparse-tree-matches
  9361. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9362. (org-fold-show-context 'occur-tree)))))
  9363. (when org-remove-highlights-with-change
  9364. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9365. nil 'local))
  9366. (unless org-sparse-tree-open-archived-trees
  9367. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9368. (run-hooks 'org-occur-hook)
  9369. (when (called-interactively-p 'interactive)
  9370. (message "%d match(es) for regexp %s" cnt regexp))
  9371. cnt))
  9372. (defun org-occur-next-match (&optional n _reset)
  9373. "Function for `next-error-function' to find sparse tree matches.
  9374. N is the number of matches to move, when negative move backwards.
  9375. This function always goes back to the starting point when no
  9376. match is found."
  9377. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9378. (search-func (if (< n 0)
  9379. 'previous-single-char-property-change
  9380. 'next-single-char-property-change))
  9381. (n (abs n))
  9382. (pos (point))
  9383. p1)
  9384. (catch 'exit
  9385. (while (setq p1 (funcall search-func (point) 'org-type))
  9386. (when (equal p1 limit)
  9387. (goto-char pos)
  9388. (user-error "No more matches"))
  9389. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9390. (setq n (1- n))
  9391. (when (= n 0)
  9392. (goto-char p1)
  9393. (throw 'exit (point))))
  9394. (goto-char p1))
  9395. (goto-char p1)
  9396. (user-error "No more matches"))))
  9397. (defun org-highlight-new-match (beg end)
  9398. "Highlight from BEG to END and mark the highlight is an occur headline."
  9399. (let ((ov (make-overlay beg end)))
  9400. (overlay-put ov 'face 'secondary-selection)
  9401. (overlay-put ov 'org-type 'org-occur)
  9402. (push ov org-occur-highlights)))
  9403. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9404. "Remove the occur highlights from the buffer.
  9405. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9406. from the `before-change-functions' in the current buffer."
  9407. (interactive)
  9408. (unless org-inhibit-highlight-removal
  9409. (mapc #'delete-overlay org-occur-highlights)
  9410. (setq org-occur-highlights nil)
  9411. (setq org-occur-parameters nil)
  9412. (unless noremove
  9413. (remove-hook 'before-change-functions
  9414. 'org-remove-occur-highlights 'local))))
  9415. ;;;; Priorities
  9416. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9417. "Regular expression matching the priority indicator.
  9418. A priority indicator can be e.g. [#A] or [#1].
  9419. This regular expression matches these groups:
  9420. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9421. 1 : the priority cookie, e.g. \"[#A]\"
  9422. 2 : the value of the priority cookie, e.g. \"A\".")
  9423. (defun org-priority-up ()
  9424. "Increase the priority of the current item."
  9425. (interactive)
  9426. (org-priority 'up))
  9427. (defun org-priority-down ()
  9428. "Decrease the priority of the current item."
  9429. (interactive)
  9430. (org-priority 'down))
  9431. (defun org-priority (&optional action show)
  9432. "Change the priority of an item.
  9433. When called interactively with a `\\[universal-argument]' prefix,
  9434. show the priority in the minibuffer instead of changing it.
  9435. When called programmatically, ACTION can be `set', `up', `down',
  9436. or a character."
  9437. (interactive "P")
  9438. (when show
  9439. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9440. ;; passed the SHOW argument should be removed.
  9441. (warn "`org-priority' called with deprecated SHOW argument"))
  9442. (if (equal action '(4))
  9443. (org-priority-show)
  9444. (unless org-priority-enable-commands
  9445. (user-error "Priority commands are disabled"))
  9446. (setq action (or action 'set))
  9447. (let ((nump (< org-priority-lowest 65))
  9448. current new news have remove)
  9449. (save-excursion
  9450. (org-back-to-heading t)
  9451. (when (looking-at org-priority-regexp)
  9452. (let ((ms (match-string 2)))
  9453. (setq current (org-priority-to-value ms)
  9454. have t)))
  9455. (cond
  9456. ((eq action 'remove)
  9457. (setq remove t new ?\ ))
  9458. ((or (eq action 'set)
  9459. (integerp action))
  9460. (if (not (eq action 'set))
  9461. (setq new action)
  9462. (setq
  9463. new
  9464. (if nump
  9465. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9466. (number-to-string org-priority-highest)
  9467. (number-to-string org-priority-lowest)))
  9468. (s (if (< 9 org-priority-lowest)
  9469. (read-string msg)
  9470. (message msg)
  9471. (char-to-string (read-char-exclusive)))))
  9472. (if (equal s " ") ?\s (string-to-number s)))
  9473. (progn (message "Priority %c-%c, SPC to remove: "
  9474. org-priority-highest org-priority-lowest)
  9475. (save-match-data
  9476. (setq new (read-char-exclusive)))))))
  9477. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9478. (= (upcase org-priority-lowest) org-priority-lowest))
  9479. (setq new (upcase new)))
  9480. (cond ((equal new ?\s) (setq remove t))
  9481. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9482. (user-error
  9483. (if nump
  9484. "Priority must be between `%s' and `%s'"
  9485. "Priority must be between `%c' and `%c'")
  9486. org-priority-highest org-priority-lowest))))
  9487. ((eq action 'up)
  9488. (setq new (if have
  9489. (1- current) ; normal cycling
  9490. ;; last priority was empty
  9491. (if (eq last-command this-command)
  9492. org-priority-lowest ; wrap around empty to lowest
  9493. ;; default
  9494. (if org-priority-start-cycle-with-default
  9495. org-priority-default
  9496. (1- org-priority-default))))))
  9497. ((eq action 'down)
  9498. (setq new (if have
  9499. (1+ current) ; normal cycling
  9500. ;; last priority was empty
  9501. (if (eq last-command this-command)
  9502. org-priority-highest ; wrap around empty to highest
  9503. ;; default
  9504. (if org-priority-start-cycle-with-default
  9505. org-priority-default
  9506. (1+ org-priority-default))))))
  9507. (t (user-error "Invalid action")))
  9508. (when (or (< (upcase new) org-priority-highest)
  9509. (> (upcase new) org-priority-lowest))
  9510. (if (and (memq action '(up down))
  9511. (not have) (not (eq last-command this-command)))
  9512. ;; `new' is from default priority
  9513. (error
  9514. "The default can not be set, see `org-priority-default' why")
  9515. ;; normal cycling: `new' is beyond highest/lowest priority
  9516. ;; and is wrapped around to the empty priority
  9517. (setq remove t)))
  9518. ;; Numerical priorities are limited to 64, beyond that number,
  9519. ;; assume the priority cookie is a character.
  9520. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9521. (if have
  9522. (if remove
  9523. (replace-match "" t t nil 1)
  9524. (replace-match news t t nil 2))
  9525. (if remove
  9526. (user-error "No priority cookie found in line")
  9527. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9528. (if (match-end 2)
  9529. (progn
  9530. (goto-char (match-end 2))
  9531. (insert " [#" news "]"))
  9532. (goto-char (match-beginning 3))
  9533. (insert "[#" news "] "))))
  9534. (org-align-tags))
  9535. (if remove
  9536. (message "Priority removed")
  9537. (message "Priority of current item set to %s" news)))))
  9538. (defalias 'org-show-priority 'org-priority-show)
  9539. (defun org-priority-show ()
  9540. "Show the priority of the current item.
  9541. This priority is composed of the main priority given with the [#A] cookies,
  9542. and by additional input from the age of a schedules or deadline entry."
  9543. (interactive)
  9544. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9545. (org-get-at-bol 'priority)
  9546. (save-excursion
  9547. (save-match-data
  9548. (beginning-of-line)
  9549. (and (looking-at org-heading-regexp)
  9550. (org-get-priority (match-string 0))))))))
  9551. (message "Priority is %d" (if pri pri -1000))))
  9552. (defun org-get-priority (s)
  9553. "Find priority cookie and return priority.
  9554. S is a string against which you can match `org-priority-regexp'.
  9555. If `org-priority-get-priority-function' is set to a custom
  9556. function, use it. Otherwise process S and output the priority
  9557. value, an integer."
  9558. (save-match-data
  9559. (if (functionp org-priority-get-priority-function)
  9560. (funcall org-priority-get-priority-function s)
  9561. (if (not (string-match org-priority-regexp s))
  9562. (* 1000 (- org-priority-lowest org-priority-default))
  9563. (* 1000 (- org-priority-lowest
  9564. (org-priority-to-value (match-string 2 s))))))))
  9565. ;;;; Tags
  9566. (defvar org-agenda-archives-mode)
  9567. (defvar org-map-continue-from nil
  9568. "Position from where mapping should continue.
  9569. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9570. (defvar org-scanner-tags nil
  9571. "The current tag list while the tags scanner is running.")
  9572. (defvar org-trust-scanner-tags nil
  9573. "Should `org-get-tags' use the tags for the scanner.
  9574. This is for internal dynamical scoping only.
  9575. When this is non-nil, the function `org-get-tags' will return the value
  9576. of `org-scanner-tags' instead of building the list by itself. This
  9577. can lead to large speed-ups when the tags scanner is used in a file with
  9578. many entries, and when the list of tags is retrieved, for example to
  9579. obtain a list of properties. Building the tags list for each entry in such
  9580. a file becomes an N^2 operation - but with this variable set, it scales
  9581. as N.")
  9582. (defvar org--matcher-tags-todo-only nil)
  9583. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9584. "Scan headline tags with inheritance and produce output ACTION.
  9585. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9586. or `agenda' to produce an entry list for an agenda view. It can also be
  9587. a Lisp form or a function that should be called at each matched headline, in
  9588. this case the return value is a list of all return values from these calls.
  9589. MATCHER is a function accepting three arguments, returning
  9590. a non-nil value whenever a given set of tags qualifies a headline
  9591. for inclusion. See `org-make-tags-matcher' for more information.
  9592. As a special case, it can also be set to t (respectively nil) in
  9593. order to match all (respectively none) headline.
  9594. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9595. included in the output.
  9596. START-LEVEL can be a string with asterisks, reducing the scope to
  9597. headlines matching this string."
  9598. (require 'org-agenda)
  9599. (let* ((re (concat "^"
  9600. (if start-level
  9601. ;; Get the correct level to match
  9602. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9603. org-outline-regexp)
  9604. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  9605. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9606. (props (list 'face 'default
  9607. 'done-face 'org-agenda-done
  9608. 'undone-face 'default
  9609. 'mouse-face 'highlight
  9610. 'org-not-done-regexp org-not-done-regexp
  9611. 'org-todo-regexp org-todo-regexp
  9612. 'org-complex-heading-regexp org-complex-heading-regexp
  9613. 'help-echo
  9614. (format "mouse-2 or RET jump to Org file %S"
  9615. (abbreviate-file-name
  9616. (or (buffer-file-name (buffer-base-buffer))
  9617. (buffer-name (buffer-base-buffer)))))))
  9618. (org-map-continue-from nil)
  9619. lspos tags tags-list
  9620. (tags-alist (list (cons 0 org-file-tags)))
  9621. (llast 0) rtn rtn1 level category i txt
  9622. todo marker entry priority
  9623. ts-date ts-date-type ts-date-pair)
  9624. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9625. (setq action (list 'lambda nil action)))
  9626. (save-excursion
  9627. (goto-char (point-min))
  9628. (when (eq action 'sparse-tree)
  9629. (org-cycle-overview)
  9630. (org-remove-occur-highlights))
  9631. (if (org-element--cache-active-p)
  9632. (let ((fast-re (concat "^"
  9633. (if start-level
  9634. ;; Get the correct level to match
  9635. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9636. org-outline-regexp))))
  9637. (org-element-cache-map
  9638. (lambda (el)
  9639. (goto-char (org-element-property :begin el))
  9640. (setq todo (org-element-property :todo-keyword el)
  9641. level (org-element-property :level el)
  9642. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9643. tags-list (org-get-tags el)
  9644. org-scanner-tags tags-list)
  9645. (when (eq action 'agenda)
  9646. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9647. ts-date (car ts-date-pair)
  9648. ts-date-type (cdr ts-date-pair)))
  9649. (catch :skip
  9650. (when (and
  9651. ;; eval matcher only when the todo condition is OK
  9652. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9653. (if (functionp matcher)
  9654. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9655. (funcall matcher todo tags-list level))
  9656. matcher))
  9657. ;; Call the skipper, but return t if it does not
  9658. ;; skip, so that the `and' form continues evaluating.
  9659. (progn
  9660. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9661. t)
  9662. ;; Check if timestamps are deselecting this entry
  9663. (or (not todo-only)
  9664. (and (member todo org-todo-keywords-1)
  9665. (or (not org-agenda-tags-todo-honor-ignore-options)
  9666. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9667. ;; select this headline
  9668. (cond
  9669. ((eq action 'sparse-tree)
  9670. (and org-highlight-sparse-tree-matches
  9671. (org-get-heading) (match-end 0)
  9672. (org-highlight-new-match
  9673. (match-beginning 1) (match-end 1)))
  9674. (org-fold-show-context 'tags-tree))
  9675. ((eq action 'agenda)
  9676. (let* ((effort (org-entry-get (point) org-effort-property))
  9677. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9678. (setq txt (org-agenda-format-item
  9679. ""
  9680. ;; Add `effort' and `effort-minutes'
  9681. ;; properties for prefix format.
  9682. (org-add-props
  9683. (concat
  9684. (if (eq org-tags-match-list-sublevels 'indented)
  9685. (make-string (1- level) ?.) "")
  9686. (org-get-heading))
  9687. nil
  9688. 'effort effort
  9689. 'effort-minutes effort-minutes)
  9690. (make-string level ?\s)
  9691. category
  9692. tags-list)
  9693. priority (org-get-priority txt))
  9694. ;; Now add `effort' and `effort-minutes' to
  9695. ;; full agenda line.
  9696. (setq txt (org-add-props txt nil
  9697. 'effort effort
  9698. 'effort-minutes effort-minutes)))
  9699. (goto-char (org-element-property :begin el))
  9700. (setq marker (org-agenda-new-marker))
  9701. (org-add-props txt props
  9702. 'org-marker marker 'org-hd-marker marker 'org-category category
  9703. 'todo-state todo
  9704. 'ts-date ts-date
  9705. 'priority priority
  9706. 'type (concat "tagsmatch" ts-date-type))
  9707. (push txt rtn))
  9708. ((functionp action)
  9709. (setq org-map-continue-from nil)
  9710. (save-excursion
  9711. (setq rtn1 (funcall action))
  9712. (push rtn1 rtn)))
  9713. (t (user-error "Invalid action")))
  9714. ;; if we are to skip sublevels, jump to end of subtree
  9715. (unless org-tags-match-list-sublevels
  9716. (goto-char (1- (org-element-property :end el))))))
  9717. ;; Get the correct position from where to continue
  9718. (when org-map-continue-from
  9719. (setq org-element-cache-map-continue-from org-map-continue-from)
  9720. (goto-char org-map-continue-from))
  9721. ;; Return nil.
  9722. nil)
  9723. :next-re fast-re
  9724. :fail-re fast-re
  9725. :narrow t))
  9726. (while (let (case-fold-search)
  9727. (re-search-forward re nil t))
  9728. (setq org-map-continue-from nil)
  9729. (catch :skip
  9730. ;; Ignore closing parts of inline tasks.
  9731. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9732. (throw :skip t))
  9733. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9734. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9735. (goto-char (setq lspos (match-beginning 0)))
  9736. (setq level (org-reduced-level (org-outline-level))
  9737. category (org-get-category))
  9738. (when (eq action 'agenda)
  9739. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9740. ts-date (car ts-date-pair)
  9741. ts-date-type (cdr ts-date-pair)))
  9742. (setq i llast llast level)
  9743. ;; remove tag lists from same and sublevels
  9744. (while (>= i level)
  9745. (when (setq entry (assoc i tags-alist))
  9746. (setq tags-alist (delete entry tags-alist)))
  9747. (setq i (1- i)))
  9748. ;; add the next tags
  9749. (when tags
  9750. (setq tags (org-split-string tags ":")
  9751. tags-alist
  9752. (cons (cons level tags) tags-alist)))
  9753. ;; compile tags for current headline
  9754. (setq tags-list
  9755. (if org-use-tag-inheritance
  9756. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  9757. tags)
  9758. org-scanner-tags tags-list)
  9759. (when org-use-tag-inheritance
  9760. (setcdr (car tags-alist)
  9761. (mapcar (lambda (x)
  9762. (setq x (copy-sequence x))
  9763. (org-add-prop-inherited x))
  9764. (cdar tags-alist))))
  9765. (when (and tags org-use-tag-inheritance
  9766. (or (not (eq t org-use-tag-inheritance))
  9767. org-tags-exclude-from-inheritance))
  9768. ;; Selective inheritance, remove uninherited ones.
  9769. (setcdr (car tags-alist)
  9770. (org-remove-uninherited-tags (cdar tags-alist))))
  9771. (when (and
  9772. ;; eval matcher only when the todo condition is OK
  9773. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9774. (if (functionp matcher)
  9775. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9776. (funcall matcher todo tags-list level))
  9777. matcher))
  9778. ;; Call the skipper, but return t if it does not
  9779. ;; skip, so that the `and' form continues evaluating.
  9780. (progn
  9781. (unless (eq action 'sparse-tree) (org-agenda-skip))
  9782. t)
  9783. ;; Check if timestamps are deselecting this entry
  9784. (or (not todo-only)
  9785. (and (member todo org-todo-keywords-1)
  9786. (or (not org-agenda-tags-todo-honor-ignore-options)
  9787. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9788. ;; select this headline
  9789. (cond
  9790. ((eq action 'sparse-tree)
  9791. (and org-highlight-sparse-tree-matches
  9792. (org-get-heading) (match-end 0)
  9793. (org-highlight-new-match
  9794. (match-beginning 1) (match-end 1)))
  9795. (org-fold-show-context 'tags-tree))
  9796. ((eq action 'agenda)
  9797. (setq txt (org-agenda-format-item
  9798. ""
  9799. (concat
  9800. (if (eq org-tags-match-list-sublevels 'indented)
  9801. (make-string (1- level) ?.) "")
  9802. (org-get-heading))
  9803. (make-string level ?\s)
  9804. category
  9805. tags-list)
  9806. priority (org-get-priority txt))
  9807. (goto-char lspos)
  9808. (setq marker (org-agenda-new-marker))
  9809. (org-add-props txt props
  9810. 'org-marker marker 'org-hd-marker marker 'org-category category
  9811. 'todo-state todo
  9812. 'ts-date ts-date
  9813. 'priority priority
  9814. 'type (concat "tagsmatch" ts-date-type))
  9815. (push txt rtn))
  9816. ((functionp action)
  9817. (setq org-map-continue-from nil)
  9818. (save-excursion
  9819. (setq rtn1 (funcall action))
  9820. (push rtn1 rtn)))
  9821. (t (user-error "Invalid action")))
  9822. ;; if we are to skip sublevels, jump to end of subtree
  9823. (unless org-tags-match-list-sublevels
  9824. (org-end-of-subtree t)
  9825. (backward-char 1))))
  9826. ;; Get the correct position from where to continue
  9827. (if org-map-continue-from
  9828. (goto-char org-map-continue-from)
  9829. (and (= (point) lspos) (end-of-line 1))))))
  9830. (when (and (eq action 'sparse-tree)
  9831. (not org-sparse-tree-open-archived-trees))
  9832. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9833. (nreverse rtn)))
  9834. (defun org-remove-uninherited-tags (tags)
  9835. "Remove all tags that are not inherited from the list TAGS."
  9836. (cond
  9837. ((eq org-use-tag-inheritance t)
  9838. (if org-tags-exclude-from-inheritance
  9839. (org-delete-all org-tags-exclude-from-inheritance tags)
  9840. tags))
  9841. ((not org-use-tag-inheritance) nil)
  9842. ((stringp org-use-tag-inheritance)
  9843. (delq nil (mapcar
  9844. (lambda (x)
  9845. (if (and (string-match org-use-tag-inheritance x)
  9846. (not (member x org-tags-exclude-from-inheritance)))
  9847. x nil))
  9848. tags)))
  9849. ((listp org-use-tag-inheritance)
  9850. (delq nil (mapcar
  9851. (lambda (x)
  9852. (if (member x org-use-tag-inheritance) x nil))
  9853. tags)))))
  9854. (defun org-match-sparse-tree (&optional todo-only match)
  9855. "Create a sparse tree according to tags string MATCH.
  9856. MATCH is a string with match syntax. It can contain a selection
  9857. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  9858. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  9859. those. See the manual for details.
  9860. If optional argument TODO-ONLY is non-nil, only select lines that
  9861. are also TODO tasks."
  9862. (interactive "P")
  9863. (org-agenda-prepare-buffers (list (current-buffer)))
  9864. (let ((org--matcher-tags-todo-only todo-only))
  9865. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  9866. org--matcher-tags-todo-only)))
  9867. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  9868. (defvar org-cached-props nil)
  9869. (defun org-cached-entry-get (pom property)
  9870. (if (or (eq t org-use-property-inheritance)
  9871. (and (stringp org-use-property-inheritance)
  9872. (let ((case-fold-search t))
  9873. (string-match-p org-use-property-inheritance property)))
  9874. (and (listp org-use-property-inheritance)
  9875. (member-ignore-case property org-use-property-inheritance)))
  9876. ;; Caching is not possible, check it directly.
  9877. (org-entry-get pom property 'inherit)
  9878. ;; Get all properties, so we can do complicated checks easily.
  9879. (cdr (assoc-string property
  9880. (or org-cached-props
  9881. (setq org-cached-props (org-entry-properties pom)))
  9882. t))))
  9883. (defun org-global-tags-completion-table (&optional files)
  9884. "Return the list of all tags in all agenda buffer/files.
  9885. Optional FILES argument is a list of files which can be used
  9886. instead of the agenda files."
  9887. (save-excursion
  9888. (org-uniquify
  9889. (delq nil
  9890. (apply #'append
  9891. (mapcar
  9892. (lambda (file)
  9893. (set-buffer (find-file-noselect file))
  9894. (org--tag-add-to-alist
  9895. (org-get-buffer-tags)
  9896. (mapcar (lambda (x)
  9897. (and (stringp (car-safe x))
  9898. (list (car-safe x))))
  9899. org-current-tag-alist)))
  9900. (if (car-safe files) files
  9901. (org-agenda-files))))))))
  9902. (defun org-make-tags-matcher (match &optional only-local-tags)
  9903. "Create the TAGS/TODO matcher form for the selection string MATCH.
  9904. Returns a cons of the selection string MATCH and a function
  9905. implementing the matcher.
  9906. The matcher is to be called at an Org entry, with point on the
  9907. headline, and returns non-nil if the entry matches the selection
  9908. string MATCH. It must be called with three arguments: the TODO
  9909. keyword at the entry (or nil if none), the list of all tags at
  9910. the entry including inherited ones and the reduced level of the
  9911. headline. Additionally, the category of the entry, if any, must
  9912. be specified as the text property `org-category' on the headline.
  9913. This function sets the variable `org--matcher-tags-todo-only' to
  9914. a non-nil value if the matcher restricts matching to TODO
  9915. entries, otherwise it is not touched.
  9916. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  9917. table, only get buffer tags.
  9918. See also `org-scan-tags'."
  9919. (unless match
  9920. ;; Get a new match request, with completion against the global
  9921. ;; tags table and the local tags in current buffer.
  9922. (let ((org-last-tags-completion-table
  9923. (org--tag-add-to-alist
  9924. (org-get-buffer-tags)
  9925. (unless only-local-tags
  9926. (org-global-tags-completion-table)))))
  9927. (setq match
  9928. (completing-read
  9929. "Match: "
  9930. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  9931. (let ((match0 match)
  9932. (re (concat
  9933. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  9934. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  9935. "\\([<>=]\\{1,2\\}\\)"
  9936. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  9937. "\\|" org-tag-re "\\)"))
  9938. (start 0)
  9939. tagsmatch todomatch tagsmatcher todomatcher)
  9940. ;; Expand group tags.
  9941. (setq match (org-tags-expand match))
  9942. ;; Check if there is a TODO part of this match, which would be the
  9943. ;; part after a "/". To make sure that this slash is not part of
  9944. ;; a property value to be matched against, we also check that
  9945. ;; there is no / after that slash. First, find the last slash.
  9946. (let ((s 0))
  9947. (while (string-match "/+" match s)
  9948. (setq start (match-beginning 0))
  9949. (setq s (match-end 0))))
  9950. (if (and (string-match "/+" match start)
  9951. (not (string-match-p "\"" match start)))
  9952. ;; Match contains also a TODO-matching request.
  9953. (progn
  9954. (setq tagsmatch (substring match 0 (match-beginning 0)))
  9955. (setq todomatch (substring match (match-end 0)))
  9956. (when (string-prefix-p "!" todomatch)
  9957. (setq org--matcher-tags-todo-only t)
  9958. (setq todomatch (substring todomatch 1)))
  9959. (when (string-match "\\`\\s-*\\'" todomatch)
  9960. (setq todomatch nil)))
  9961. ;; Only matching tags.
  9962. (setq tagsmatch match)
  9963. (setq todomatch nil))
  9964. ;; Make the tags matcher.
  9965. (when (org-string-nw-p tagsmatch)
  9966. (let ((orlist nil)
  9967. (orterms (org-split-string tagsmatch "|"))
  9968. term)
  9969. (while (setq term (pop orterms))
  9970. (while (and (equal (substring term -1) "\\") orterms)
  9971. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  9972. (while (string-match re term)
  9973. (let* ((rest (substring term (match-end 0)))
  9974. (minus (and (match-end 1)
  9975. (equal (match-string 1 term) "-")))
  9976. (tag (save-match-data
  9977. (replace-regexp-in-string
  9978. "\\\\-" "-" (match-string 2 term))))
  9979. (regexp (eq (string-to-char tag) ?{))
  9980. (levelp (match-end 4))
  9981. (propp (match-end 5))
  9982. (mm
  9983. (cond
  9984. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  9985. (levelp
  9986. `(,(org-op-to-function (match-string 3 term))
  9987. level
  9988. ,(string-to-number (match-string 4 term))))
  9989. (propp
  9990. (let* ((gv (pcase (upcase (match-string 5 term))
  9991. ("CATEGORY"
  9992. '(org-get-category (point)))
  9993. ("TODO" 'todo)
  9994. (p `(org-cached-entry-get nil ,p))))
  9995. (pv (match-string 7 term))
  9996. (regexp (eq (string-to-char pv) ?{))
  9997. (strp (eq (string-to-char pv) ?\"))
  9998. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  9999. (po (org-op-to-function (match-string 6 term)
  10000. (if timep 'time strp))))
  10001. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10002. (when timep (setq pv (org-matcher-time pv)))
  10003. (cond ((and regexp (eq po '/=))
  10004. `(not (string-match ,pv (or ,gv ""))))
  10005. (regexp `(string-match ,pv (or ,gv "")))
  10006. (strp `(,po (or ,gv "") ,pv))
  10007. (t
  10008. `(,po
  10009. (string-to-number (or ,gv ""))
  10010. ,(string-to-number pv))))))
  10011. (t `(member ,tag tags-list)))))
  10012. (push (if minus `(not ,mm) mm) tagsmatcher)
  10013. (setq term rest)))
  10014. (push `(and ,@tagsmatcher) orlist)
  10015. (setq tagsmatcher nil))
  10016. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10017. ;; Make the TODO matcher.
  10018. (when (org-string-nw-p todomatch)
  10019. (let ((orlist nil))
  10020. (dolist (term (org-split-string todomatch "|"))
  10021. (while (string-match re term)
  10022. (let* ((minus (and (match-end 1)
  10023. (equal (match-string 1 term) "-")))
  10024. (kwd (match-string 2 term))
  10025. (regexp (eq (string-to-char kwd) ?{))
  10026. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10027. `(equal todo ,kwd))))
  10028. (push (if minus `(not ,mm) mm) todomatcher))
  10029. (setq term (substring term (match-end 0))))
  10030. (push (if (> (length todomatcher) 1)
  10031. (cons 'and todomatcher)
  10032. (car todomatcher))
  10033. orlist)
  10034. (setq todomatcher nil))
  10035. (setq todomatcher (cons 'or orlist))))
  10036. ;; Return the string and function of the matcher. If no
  10037. ;; tags-specific or todo-specific matcher exists, match
  10038. ;; everything.
  10039. (let ((matcher (if (and tagsmatcher todomatcher)
  10040. `(and ,tagsmatcher ,todomatcher)
  10041. (or tagsmatcher todomatcher t))))
  10042. (when org--matcher-tags-todo-only
  10043. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10044. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10045. (defun org--tags-expand-group (group tag-groups expanded)
  10046. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10047. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10048. an accumulator used in recursive calls."
  10049. (dolist (tag group)
  10050. (unless (member tag expanded)
  10051. (let ((group (assoc tag tag-groups)))
  10052. (push tag expanded)
  10053. (when group
  10054. (setq expanded
  10055. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10056. expanded)
  10057. (defun org-tags-expand (match &optional single-as-list)
  10058. "Expand group tags in MATCH.
  10059. This replaces every group tag in MATCH with a regexp tag search.
  10060. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10061. will be replaced like this:
  10062. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10063. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10064. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10065. Replacing by a regexp preserves the structure of the match.
  10066. E.g., this expansion
  10067. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10068. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10069. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10070. A group tag in MATCH can contain regular expressions of its own.
  10071. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10072. will be replaced like this:
  10073. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10074. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10075. assumed to be a single group tag, and the function will return
  10076. the list of tags in this group."
  10077. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10078. (let ((tag-groups
  10079. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10080. (cond
  10081. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10082. (org-group-tags
  10083. (let* ((case-fold-search t)
  10084. (tag-syntax org-mode-syntax-table)
  10085. (group-keys (mapcar #'car tag-groups))
  10086. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10087. (return-match match))
  10088. ;; Mark regexp-expressions in the match-expression so that we
  10089. ;; do not replace them later on.
  10090. (let ((s 0))
  10091. (while (string-match "{.+?}" return-match s)
  10092. (setq s (match-end 0))
  10093. (add-text-properties
  10094. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10095. ;; @ and _ are allowed as word-components in tags.
  10096. (modify-syntax-entry ?@ "w" tag-syntax)
  10097. (modify-syntax-entry ?_ "w" tag-syntax)
  10098. ;; For each tag token found in MATCH, compute a regexp and it
  10099. (with-syntax-table tag-syntax
  10100. (replace-regexp-in-string
  10101. key-regexp
  10102. (lambda (m)
  10103. (if (get-text-property (match-beginning 2) 'regexp m)
  10104. m ;regexp tag: ignore
  10105. (let* ((operator (match-string 1 m))
  10106. (tag-token (let ((tag (match-string 2 m)))
  10107. (list tag)))
  10108. regexp-tags regular-tags)
  10109. ;; Partition tags between regexp and regular tags.
  10110. ;; Remove curly bracket syntax from regexp tags.
  10111. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10112. (save-match-data
  10113. (if (string-match "{\\(.+?\\)}" tag)
  10114. (push (match-string 1 tag) regexp-tags)
  10115. (push tag regular-tags))))
  10116. ;; Replace tag token by the appropriate regexp.
  10117. ;; Regular tags need to be regexp-quoted, whereas
  10118. ;; regexp-tags are inserted as-is.
  10119. (let ((regular (regexp-opt regular-tags))
  10120. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10121. (concat operator
  10122. (cond
  10123. ((null regular-tags) (format "{%s}" regexp))
  10124. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10125. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10126. return-match
  10127. t t))))
  10128. (t match))))
  10129. (defun org-op-to-function (op &optional stringp)
  10130. "Turn an operator into the appropriate function."
  10131. (setq op
  10132. (cond
  10133. ((equal op "<" ) '(< org-string< org-time<))
  10134. ((equal op ">" ) '(> org-string> org-time>))
  10135. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10136. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10137. ((member op '("=" "==")) '(= string= org-time=))
  10138. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10139. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10140. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10141. (defvar org-tags-overlay (make-overlay 1 1))
  10142. (delete-overlay org-tags-overlay)
  10143. (defun org-add-prop-inherited (s)
  10144. (add-text-properties 0 (length s) '(inherited t) s)
  10145. s)
  10146. (defun org-toggle-tag (tag &optional onoff)
  10147. "Toggle the tag TAG for the current line.
  10148. If ONOFF is `on' or `off', don't toggle but set to this state."
  10149. (save-excursion
  10150. (org-back-to-heading t)
  10151. (let ((current
  10152. ;; Reverse the tags list so any new tag is appended to the
  10153. ;; current list of tags.
  10154. (nreverse (org-get-tags nil t)))
  10155. res)
  10156. (pcase onoff
  10157. (`off (setq current (delete tag current)))
  10158. ((or `on (guard (not (member tag current))))
  10159. (setq res t)
  10160. (cl-pushnew tag current :test #'equal))
  10161. (_ (setq current (delete tag current))))
  10162. (org-set-tags (nreverse current))
  10163. res)))
  10164. (defun org--align-tags-here (to-col)
  10165. "Align tags on the current headline to TO-COL.
  10166. Assume point is on a headline. Preserve point when aligning
  10167. tags."
  10168. (when (org-match-line org-tag-line-re)
  10169. (let* ((tags-start (match-beginning 1))
  10170. (blank-start (save-excursion
  10171. (goto-char tags-start)
  10172. (skip-chars-backward " \t")
  10173. (point)))
  10174. (new (max (if (>= to-col 0) to-col
  10175. (- (abs to-col) (string-width (match-string 1))))
  10176. ;; Introduce at least one space after the heading
  10177. ;; or the stars.
  10178. (save-excursion
  10179. (goto-char blank-start)
  10180. (1+ (current-column)))))
  10181. (current
  10182. (save-excursion (goto-char tags-start) (current-column)))
  10183. (origin (point-marker))
  10184. (column (current-column))
  10185. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10186. (when (/= new current)
  10187. (delete-region blank-start tags-start)
  10188. (goto-char blank-start)
  10189. (let ((indent-tabs-mode nil)) (indent-to new))
  10190. ;; Try to move back to original position. If point was in the
  10191. ;; blanks before the tags, ORIGIN marker is of no use because
  10192. ;; it now points to BLANK-START. Use COLUMN instead.
  10193. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10194. (defun org-set-tags-command (&optional arg)
  10195. "Set the tags for the current visible entry.
  10196. When called with `\\[universal-argument]' prefix argument ARG, \
  10197. realign all tags
  10198. in the current buffer.
  10199. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10200. unconditionally do not
  10201. offer the fast tag selection interface.
  10202. If a region is active, set tags in the region according to the
  10203. setting of `org-loop-over-headlines-in-active-region'.
  10204. This function is for interactive use only;
  10205. in Lisp code use `org-set-tags' instead."
  10206. (interactive "P")
  10207. (let ((org-use-fast-tag-selection
  10208. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10209. (cond
  10210. ((equal '(4) arg) (org-align-tags t))
  10211. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10212. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10213. (org-map-entries
  10214. #'org-set-tags-command
  10215. nil
  10216. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10217. 'region-start-level
  10218. 'region)
  10219. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10220. (t
  10221. (save-excursion
  10222. (org-back-to-heading)
  10223. (let* ((all-tags (org-get-tags))
  10224. (table (setq org-last-tags-completion-table
  10225. (org--tag-add-to-alist
  10226. (and org-complete-tags-always-offer-all-agenda-tags
  10227. (org-global-tags-completion-table
  10228. (org-agenda-files)))
  10229. (or org-current-tag-alist (org-get-buffer-tags)))))
  10230. (current-tags
  10231. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10232. all-tags))
  10233. (inherited-tags
  10234. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10235. all-tags))
  10236. (tags
  10237. (replace-regexp-in-string
  10238. ;; Ignore all forbidden characters in tags.
  10239. "[^[:alnum:]_@#%]+" ":"
  10240. (if (or (eq t org-use-fast-tag-selection)
  10241. (and org-use-fast-tag-selection
  10242. (delq nil (mapcar #'cdr table))))
  10243. (org-fast-tag-selection
  10244. current-tags
  10245. inherited-tags
  10246. table
  10247. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10248. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10249. (crm-separator "[ \t]*:[ \t]*"))
  10250. (mapconcat #'identity
  10251. (completing-read-multiple
  10252. "Tags: "
  10253. org-last-tags-completion-table
  10254. nil nil (org-make-tag-string current-tags)
  10255. 'org-tags-history)
  10256. ":"))))))
  10257. (org-set-tags tags)))))
  10258. ;; `save-excursion' may not replace the point at the right
  10259. ;; position.
  10260. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10261. (looking-at-p " "))
  10262. (forward-char))))
  10263. (defun org-align-tags (&optional all)
  10264. "Align tags in current entry.
  10265. When optional argument ALL is non-nil, align all tags in the
  10266. visible part of the buffer."
  10267. (let ((get-indent-column
  10268. (lambda ()
  10269. (let ((offset (if (bound-and-true-p org-indent-mode)
  10270. (* (1- org-indent-indentation-per-level)
  10271. (1- (org-current-level)))
  10272. 0)))
  10273. (+ org-tags-column
  10274. (if (> org-tags-column 0) (- offset) offset))))))
  10275. (if (and (not all) (org-at-heading-p))
  10276. (org--align-tags-here (funcall get-indent-column))
  10277. (save-excursion
  10278. (if all
  10279. (progn
  10280. (goto-char (point-min))
  10281. (while (re-search-forward org-tag-line-re nil t)
  10282. (org--align-tags-here (funcall get-indent-column))))
  10283. (org-back-to-heading t)
  10284. (org--align-tags-here (funcall get-indent-column)))))))
  10285. (defun org-set-tags (tags)
  10286. "Set the tags of the current entry to TAGS, replacing current tags.
  10287. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10288. If TAGS is nil or the empty string, all tags are removed.
  10289. This function assumes point is on a headline."
  10290. (org-with-wide-buffer
  10291. (org-fold-core-ignore-modifications
  10292. (let ((tags (pcase tags
  10293. ((pred listp) tags)
  10294. ((pred stringp) (split-string (org-trim tags) ":" t))
  10295. (_ (error "Invalid tag specification: %S" tags))))
  10296. (old-tags (org-get-tags nil t))
  10297. (tags-change? nil))
  10298. (when (functionp org-tags-sort-function)
  10299. (setq tags (sort tags org-tags-sort-function)))
  10300. (setq tags-change? (not (equal tags old-tags)))
  10301. (when tags-change?
  10302. ;; Delete previous tags and any trailing white space.
  10303. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10304. (line-end-position)))
  10305. (skip-chars-backward " \t")
  10306. (delete-region (point) (line-end-position))
  10307. ;; Deleting white spaces may break an otherwise empty headline.
  10308. ;; Re-introduce one space in this case.
  10309. (unless (org-at-heading-p) (insert " "))
  10310. (when tags
  10311. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10312. ;; When text is being inserted on an invisible region
  10313. ;; boundary, it can be inadvertently sucked into
  10314. ;; invisibility.
  10315. (unless (org-invisible-p (line-beginning-position))
  10316. (org-fold-region (point) (line-end-position) nil 'outline))))
  10317. ;; Align tags, if any.
  10318. (when tags (org-align-tags))
  10319. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10320. (defun org-change-tag-in-region (beg end tag off)
  10321. "Add or remove TAG for each entry in the region.
  10322. This works in the agenda, and also in an Org buffer."
  10323. (interactive
  10324. (list (region-beginning) (region-end)
  10325. (let ((org-last-tags-completion-table
  10326. (if (derived-mode-p 'org-mode)
  10327. (org--tag-add-to-alist
  10328. (org-get-buffer-tags)
  10329. (org-global-tags-completion-table))
  10330. (org-global-tags-completion-table))))
  10331. (completing-read
  10332. "Tag: " org-last-tags-completion-table nil nil nil
  10333. 'org-tags-history))
  10334. (progn
  10335. (message "[s]et or [r]emove? ")
  10336. (equal (read-char-exclusive) ?r))))
  10337. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10338. (let ((agendap (equal major-mode 'org-agenda-mode))
  10339. l1 l2 m buf pos newhead (cnt 0))
  10340. (goto-char end)
  10341. (setq l2 (1- (org-current-line)))
  10342. (goto-char beg)
  10343. (setq l1 (org-current-line))
  10344. (cl-loop for l from l1 to l2 do
  10345. (org-goto-line l)
  10346. (setq m (get-text-property (point) 'org-hd-marker))
  10347. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10348. (and agendap m))
  10349. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10350. pos (if agendap m (point)))
  10351. (with-current-buffer buf
  10352. (save-excursion
  10353. (save-restriction
  10354. (goto-char pos)
  10355. (setq cnt (1+ cnt))
  10356. (org-toggle-tag tag (if off 'off 'on))
  10357. (setq newhead (org-get-heading)))))
  10358. (and agendap (org-agenda-change-all-lines newhead m))))
  10359. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10360. (defun org-tags-completion-function (string _predicate &optional flag)
  10361. "Complete tag STRING.
  10362. FLAG specifies the type of completion operation to perform. This
  10363. function is passed as a collection function to `completing-read',
  10364. which see."
  10365. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10366. (confirm (lambda (x) (stringp (car x))))
  10367. (prefix ""))
  10368. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10369. (setq prefix (match-string 1 string))
  10370. (setq string (match-string 2 string)))
  10371. (pcase flag
  10372. (`t (all-completions string org-last-tags-completion-table confirm))
  10373. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10374. (`nil
  10375. (pcase (try-completion string org-last-tags-completion-table confirm)
  10376. ((and completion (pred stringp))
  10377. (concat prefix
  10378. completion
  10379. (if (and org-add-colon-after-tag-completion
  10380. (assoc completion org-last-tags-completion-table))
  10381. ":"
  10382. "")))
  10383. (completion completion)))
  10384. (_ nil))))
  10385. (defun org-fast-tag-insert (kwd tags face &optional end)
  10386. "Insert KWD, and the TAGS, the latter with face FACE.
  10387. Also insert END."
  10388. (insert (format "%-12s" (concat kwd ":"))
  10389. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10390. (or end "")))
  10391. (defun org-fast-tag-show-exit (flag)
  10392. (save-excursion
  10393. (org-goto-line 3)
  10394. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10395. (replace-match ""))
  10396. (when flag
  10397. (end-of-line 1)
  10398. (org-move-to-column (- (window-width) 19) t)
  10399. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10400. (defun org-set-current-tags-overlay (current prefix)
  10401. "Add an overlay to CURRENT tag with PREFIX."
  10402. (let ((s (org-make-tag-string current)))
  10403. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10404. (org-overlay-display org-tags-overlay (concat prefix s))))
  10405. (defvar org-last-tag-selection-key nil)
  10406. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10407. "Fast tag selection with single keys.
  10408. CURRENT is the current list of tags in the headline, INHERITED is the
  10409. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10410. possibly with grouping information. TODO-TABLE is a similar table with
  10411. TODO keywords, should these have keys assigned to them.
  10412. If the keys are nil, a-z are automatically assigned.
  10413. Returns the new tags string, or nil to not change the current settings."
  10414. (let* ((fulltable (append table todo-table))
  10415. (maxlen (if (null fulltable) 0
  10416. (apply #'max
  10417. (mapcar (lambda (x)
  10418. (if (stringp (car x)) (string-width (car x))
  10419. 0))
  10420. fulltable))))
  10421. (buf (current-buffer))
  10422. (expert (eq org-fast-tag-selection-single-key 'expert))
  10423. (tab-tags nil)
  10424. (fwidth (+ maxlen 3 1 3))
  10425. (ncol (/ (- (window-width) 4) fwidth))
  10426. (i-face 'org-done)
  10427. (c-face 'org-todo)
  10428. tg cnt e c char c1 c2 ntable tbl rtn
  10429. ov-start ov-end ov-prefix
  10430. (exit-after-next org-fast-tag-selection-single-key)
  10431. (done-keywords org-done-keywords)
  10432. groups ingroup intaggroup)
  10433. (save-excursion
  10434. (beginning-of-line)
  10435. (if (looking-at org-tag-line-re)
  10436. (setq ov-start (match-beginning 1)
  10437. ov-end (match-end 1)
  10438. ov-prefix "")
  10439. (setq ov-start (1- (point-at-eol))
  10440. ov-end (1+ ov-start))
  10441. (skip-chars-forward "^\n\r")
  10442. (setq ov-prefix
  10443. (concat
  10444. (buffer-substring (1- (point)) (point))
  10445. (if (> (current-column) org-tags-column)
  10446. " "
  10447. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10448. (move-overlay org-tags-overlay ov-start ov-end)
  10449. (save-excursion
  10450. (save-window-excursion
  10451. (if expert
  10452. (set-buffer (get-buffer-create " *Org tags*"))
  10453. (delete-other-windows)
  10454. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10455. (org-switch-to-buffer-other-window " *Org tags*"))
  10456. (erase-buffer)
  10457. (setq-local org-done-keywords done-keywords)
  10458. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10459. (org-fast-tag-insert "Current" current c-face "\n\n")
  10460. (org-fast-tag-show-exit exit-after-next)
  10461. (org-set-current-tags-overlay current ov-prefix)
  10462. (setq tbl fulltable char ?a cnt 0)
  10463. (while (setq e (pop tbl))
  10464. (cond
  10465. ((eq (car e) :startgroup)
  10466. (push '() groups) (setq ingroup t)
  10467. (unless (zerop cnt)
  10468. (setq cnt 0)
  10469. (insert "\n"))
  10470. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10471. ((eq (car e) :endgroup)
  10472. (setq ingroup nil cnt 0)
  10473. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10474. ((eq (car e) :startgrouptag)
  10475. (setq intaggroup t)
  10476. (unless (zerop cnt)
  10477. (setq cnt 0)
  10478. (insert "\n"))
  10479. (insert "[ "))
  10480. ((eq (car e) :endgrouptag)
  10481. (setq intaggroup nil cnt 0)
  10482. (insert "]\n"))
  10483. ((equal e '(:newline))
  10484. (unless (zerop cnt)
  10485. (setq cnt 0)
  10486. (insert "\n")
  10487. (setq e (car tbl))
  10488. (while (equal (car tbl) '(:newline))
  10489. (insert "\n")
  10490. (setq tbl (cdr tbl)))))
  10491. ((equal e '(:grouptags)) (insert " : "))
  10492. (t
  10493. (setq tg (copy-sequence (car e)) c2 nil)
  10494. (if (cdr e)
  10495. (setq c (cdr e))
  10496. ;; automatically assign a character.
  10497. (setq c1 (string-to-char
  10498. (downcase (substring
  10499. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10500. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10501. (while (or (rassoc char ntable) (rassoc char table))
  10502. (setq char (1+ char)))
  10503. (setq c2 c1))
  10504. (setq c (or c2 char)))
  10505. (when ingroup (push tg (car groups)))
  10506. (setq tg (org-add-props tg nil 'face
  10507. (cond
  10508. ((not (assoc tg table))
  10509. (org-get-todo-face tg))
  10510. ((member tg current) c-face)
  10511. ((member tg inherited) i-face))))
  10512. (when (equal (caar tbl) :grouptags)
  10513. (org-add-props tg nil 'face 'org-tag-group))
  10514. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10515. (insert "[" c "] " tg (make-string
  10516. (- fwidth 4 (length tg)) ?\ ))
  10517. (push (cons tg c) ntable)
  10518. (when (= (cl-incf cnt) ncol)
  10519. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10520. (insert "\n")
  10521. (when (or ingroup intaggroup) (insert " ")))
  10522. (setq cnt 0)))))
  10523. (setq ntable (nreverse ntable))
  10524. (insert "\n")
  10525. (goto-char (point-min))
  10526. (unless expert (org-fit-window-to-buffer))
  10527. (setq rtn
  10528. (catch 'exit
  10529. (while t
  10530. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10531. (if (not groups) "no " "")
  10532. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10533. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10534. (setq org-last-tag-selection-key c)
  10535. (cond
  10536. ((= c ?\r) (throw 'exit t))
  10537. ((= c ?!)
  10538. (setq groups (not groups))
  10539. (goto-char (point-min))
  10540. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10541. ((= c ?\C-c)
  10542. (if (not expert)
  10543. (org-fast-tag-show-exit
  10544. (setq exit-after-next (not exit-after-next)))
  10545. (setq expert nil)
  10546. (delete-other-windows)
  10547. (set-window-buffer (split-window-vertically) " *Org tags*")
  10548. (org-switch-to-buffer-other-window " *Org tags*")
  10549. (org-fit-window-to-buffer)))
  10550. ((or (= c ?\C-g)
  10551. (and (= c ?q) (not (rassoc c ntable))))
  10552. (delete-overlay org-tags-overlay)
  10553. (setq quit-flag t))
  10554. ((= c ?\ )
  10555. (setq current nil)
  10556. (when exit-after-next (setq exit-after-next 'now)))
  10557. ((= c ?\t)
  10558. (condition-case nil
  10559. (unless tab-tags
  10560. (setq tab-tags
  10561. (delq nil
  10562. (mapcar (lambda (x)
  10563. (let ((item (car-safe x)))
  10564. (and (stringp item)
  10565. (list item))))
  10566. (org--tag-add-to-alist
  10567. (with-current-buffer buf
  10568. (org-get-buffer-tags))
  10569. table))))))
  10570. (setq tg (completing-read "Tag: " tab-tags))
  10571. (when (string-match "\\S-" tg)
  10572. (cl-pushnew (list tg) tab-tags :test #'equal)
  10573. (if (member tg current)
  10574. (setq current (delete tg current))
  10575. (push tg current)))
  10576. (when exit-after-next (setq exit-after-next 'now)))
  10577. ((setq e (rassoc c todo-table) tg (car e))
  10578. (with-current-buffer buf
  10579. (save-excursion (org-todo tg)))
  10580. (when exit-after-next (setq exit-after-next 'now)))
  10581. ((setq e (rassoc c ntable) tg (car e))
  10582. (if (member tg current)
  10583. (setq current (delete tg current))
  10584. (cl-loop for g in groups do
  10585. (when (member tg g)
  10586. (dolist (x g) (setq current (delete x current)))))
  10587. (push tg current))
  10588. (when exit-after-next (setq exit-after-next 'now))))
  10589. ;; Create a sorted list
  10590. (setq current
  10591. (sort current
  10592. (lambda (a b)
  10593. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10594. (when (eq exit-after-next 'now) (throw 'exit t))
  10595. (goto-char (point-min))
  10596. (beginning-of-line 2)
  10597. (delete-region (point) (point-at-eol))
  10598. (org-fast-tag-insert "Current" current c-face)
  10599. (org-set-current-tags-overlay current ov-prefix)
  10600. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10601. (while (re-search-forward tag-re nil t)
  10602. (let ((tag (match-string 1)))
  10603. (add-text-properties
  10604. (match-beginning 1) (match-end 1)
  10605. (list 'face
  10606. (cond
  10607. ((member tag current) c-face)
  10608. ((member tag inherited) i-face)
  10609. (t (get-text-property (match-beginning 1) '
  10610. face))))))))
  10611. (goto-char (point-min)))))
  10612. (delete-overlay org-tags-overlay)
  10613. (if rtn
  10614. (mapconcat 'identity current ":")
  10615. nil)))))
  10616. (defun org-make-tag-string (tags)
  10617. "Return string associated to TAGS.
  10618. TAGS is a list of strings."
  10619. (if (null tags) ""
  10620. (format ":%s:" (mapconcat #'identity tags ":"))))
  10621. (defun org--get-local-tags ()
  10622. "Return list of tags for the current headline.
  10623. Assume point is at the beginning of the headline."
  10624. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10625. (cached-tags (org-element-property :tags cached)))
  10626. (if cached
  10627. ;; If we do not explicitly copy the result, reference would
  10628. ;; be returned and cache element might be modified directly.
  10629. (mapcar #'copy-sequence cached-tags)
  10630. ;; Parse tags manually.
  10631. (and (looking-at org-tag-line-re)
  10632. (split-string (match-string-no-properties 2) ":" t)))))
  10633. (defun org-get-tags (&optional pos-or-element local)
  10634. "Get the list of tags specified in the current headline.
  10635. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10636. POS.
  10637. According to `org-use-tag-inheritance', tags may be inherited
  10638. from parent headlines, and from the whole document, through
  10639. `org-file-tags'. In this case, the returned list of tags
  10640. contains tags in this order: file tags, tags inherited from
  10641. parent headlines, local tags. If a tag appears multiple times,
  10642. only the most local tag is returned.
  10643. However, when optional argument LOCAL is non-nil, only return
  10644. tags specified at the headline.
  10645. Inherited tags have the `inherited' text property."
  10646. (save-match-data
  10647. (if (and org-trust-scanner-tags
  10648. (or (not pos-or-element) (eq pos-or-element (point)))
  10649. (not local))
  10650. org-scanner-tags
  10651. (org-with-point-at (unless (org-element-type pos-or-element)
  10652. (or pos-or-element (point)))
  10653. (unless (or (org-element-type pos-or-element)
  10654. (org-before-first-heading-p))
  10655. (org-back-to-heading t))
  10656. (let ((ltags (if (org-element-type pos-or-element)
  10657. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10658. (org--get-local-tags)))
  10659. itags)
  10660. (if (or local (not org-use-tag-inheritance)) ltags
  10661. (let ((cached (and (org-element--cache-active-p)
  10662. (if (org-element-type pos-or-element)
  10663. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10664. (org-element-at-point nil 'cached)))))
  10665. (if cached
  10666. (while (setq cached (org-element-property :parent cached))
  10667. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10668. ;; If we do explicitly copy the result, reference would
  10669. ;; be returned and cache element might be modified directly.
  10670. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10671. itags)))
  10672. (while (org-up-heading-safe)
  10673. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10674. (org--get-local-tags))
  10675. itags)))))
  10676. (setq itags (append org-file-tags itags))
  10677. (nreverse
  10678. (delete-dups
  10679. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10680. (defun org-get-buffer-tags ()
  10681. "Get a table of all tags used in the buffer, for completion."
  10682. (if (org-element--cache-active-p)
  10683. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10684. ;; search.
  10685. (let ((tags (org-element-cache-map
  10686. (lambda (el) (org-element-property :tags el)))))
  10687. (mapcar #'list (mapcar #'substring-no-properties
  10688. (delete-dups
  10689. (append org-file-tags
  10690. (apply #'append tags))))))
  10691. (org-with-point-at 1
  10692. (let (tags)
  10693. (while (re-search-forward org-tag-line-re nil t)
  10694. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10695. tags)))
  10696. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10697. ;;;; The mapping API
  10698. (defvar org-agenda-skip-comment-trees)
  10699. (defvar org-agenda-skip-function)
  10700. (defun org-map-entries (func &optional match scope &rest skip)
  10701. "Call FUNC at each headline selected by MATCH in SCOPE.
  10702. FUNC is a function or a Lisp form. The function will be called without
  10703. arguments, with the cursor positioned at the beginning of the headline.
  10704. The return values of all calls to the function will be collected and
  10705. returned as a list.
  10706. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10707. does not need to preserve point. After evaluation, the cursor will be
  10708. moved to the end of the line (presumably of the headline of the
  10709. processed entry) and search continues from there. Under some
  10710. circumstances, this may not produce the wanted results. For example,
  10711. if you have removed (e.g. archived) the current (sub)tree it could
  10712. mean that the next entry will be skipped entirely. In such cases, you
  10713. can specify the position from where search should continue by making
  10714. FUNC set the variable `org-map-continue-from' to the desired buffer
  10715. position.
  10716. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10717. Only headlines that are matched by this query will be considered during
  10718. the iteration. When MATCH is nil or t, all headlines will be
  10719. visited by the iteration.
  10720. SCOPE determines the scope of this command. It can be any of:
  10721. nil The current buffer, respecting the restriction if any
  10722. tree The subtree started with the entry at point
  10723. region The entries within the active region, if any
  10724. region-start-level
  10725. The entries within the active region, but only those at
  10726. the same level than the first one.
  10727. file The current buffer, without restriction
  10728. file-with-archives
  10729. The current buffer, and any archives associated with it
  10730. agenda All agenda files
  10731. agenda-with-archives
  10732. All agenda files with any archive files associated with them
  10733. \(file1 file2 ...)
  10734. If this is a list, all files in the list will be scanned
  10735. The remaining args are treated as settings for the skipping facilities of
  10736. the scanner. The following items can be given here:
  10737. archive skip trees with the archive tag
  10738. comment skip trees with the COMMENT keyword
  10739. function or Emacs Lisp form:
  10740. will be used as value for `org-agenda-skip-function', so
  10741. whenever the function returns a position, FUNC will not be
  10742. called for that entry and search will continue from the
  10743. position returned
  10744. If your function needs to retrieve the tags including inherited tags
  10745. at the *current* entry, you can use the value of the variable
  10746. `org-scanner-tags' which will be much faster than getting the value
  10747. with `org-get-tags'. If your function gets properties with
  10748. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  10749. to t around the call to `org-entry-properties' to get the same speedup.
  10750. Note that if your function moves around to retrieve tags and properties at
  10751. a *different* entry, you cannot use these techniques."
  10752. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  10753. (not (org-region-active-p)))
  10754. (let* ((org-agenda-archives-mode nil) ; just to make sure
  10755. (org-agenda-skip-archived-trees (memq 'archive skip))
  10756. (org-agenda-skip-comment-trees (memq 'comment skip))
  10757. (org-agenda-skip-function
  10758. (car (org-delete-all '(comment archive) skip)))
  10759. (org-tags-match-list-sublevels t)
  10760. (start-level (eq scope 'region-start-level))
  10761. matcher res
  10762. org-todo-keywords-for-agenda
  10763. org-done-keywords-for-agenda
  10764. org-todo-keyword-alist-for-agenda
  10765. org-tag-alist-for-agenda
  10766. org--matcher-tags-todo-only)
  10767. (cond
  10768. ((eq match t) (setq matcher t))
  10769. ((eq match nil) (setq matcher t))
  10770. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  10771. (save-excursion
  10772. (save-restriction
  10773. (cond ((eq scope 'tree)
  10774. (org-back-to-heading t)
  10775. (org-narrow-to-subtree)
  10776. (setq scope nil))
  10777. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  10778. (org-region-active-p))
  10779. ;; If needed, set start-level to a string like "2"
  10780. (when start-level
  10781. (save-excursion
  10782. (goto-char (region-beginning))
  10783. (unless (org-at-heading-p) (outline-next-heading))
  10784. (setq start-level (org-current-level))))
  10785. (narrow-to-region (region-beginning)
  10786. (save-excursion
  10787. (goto-char (region-end))
  10788. (unless (and (bolp) (org-at-heading-p))
  10789. (outline-next-heading))
  10790. (point)))
  10791. (setq scope nil)))
  10792. (if (not scope)
  10793. (progn
  10794. (org-agenda-prepare-buffers
  10795. (and buffer-file-name (list buffer-file-name)))
  10796. (setq res
  10797. (org-scan-tags
  10798. func matcher org--matcher-tags-todo-only start-level)))
  10799. ;; Get the right scope
  10800. (cond
  10801. ((and scope (listp scope) (symbolp (car scope)))
  10802. (setq scope (eval scope t)))
  10803. ((eq scope 'agenda)
  10804. (setq scope (org-agenda-files t)))
  10805. ((eq scope 'agenda-with-archives)
  10806. (setq scope (org-agenda-files t))
  10807. (setq scope (org-add-archive-files scope)))
  10808. ((eq scope 'file)
  10809. (setq scope (and buffer-file-name (list buffer-file-name))))
  10810. ((eq scope 'file-with-archives)
  10811. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  10812. (org-agenda-prepare-buffers scope)
  10813. (dolist (file scope)
  10814. (with-current-buffer (org-find-base-buffer-visiting file)
  10815. (org-with-wide-buffer
  10816. (goto-char (point-min))
  10817. (setq res
  10818. (append
  10819. res
  10820. (org-scan-tags
  10821. func matcher org--matcher-tags-todo-only)))))))))
  10822. res)))
  10823. ;;; Properties API
  10824. (defconst org-special-properties
  10825. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  10826. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  10827. "The special properties valid in Org mode.
  10828. These are properties that are not defined in the property drawer,
  10829. but in some other way.")
  10830. (defconst org-default-properties
  10831. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  10832. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  10833. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  10834. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  10835. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  10836. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  10837. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  10838. "Some properties that are used by Org mode for various purposes.
  10839. Being in this list makes sure that they are offered for completion.")
  10840. (defun org--valid-property-p (property)
  10841. "Non-nil when string PROPERTY is a valid property name."
  10842. (not
  10843. (or (equal property "")
  10844. (string-match-p "\\s-" property))))
  10845. (defun org--update-property-plist (key val props)
  10846. "Associate KEY to VAL in alist PROPS.
  10847. Modifications are made by side-effect. Return new alist."
  10848. (let* ((appending (string= (substring key -1) "+"))
  10849. (key (if appending (substring key 0 -1) key))
  10850. (old (assoc-string key props t)))
  10851. (if (not old) (cons (cons key val) props)
  10852. (setcdr old (if appending (concat (cdr old) " " val) val))
  10853. props)))
  10854. (defun org-get-property-block (&optional beg force)
  10855. "Return the (beg . end) range of the body of the property drawer.
  10856. BEG is the beginning of the current subtree or the beginning of
  10857. the document if before the first headline. If it is not given,
  10858. it will be found. If the drawer does not exist, create it if
  10859. FORCE is non-nil, or return nil."
  10860. (org-with-wide-buffer
  10861. (let ((beg (cond (beg (goto-char beg))
  10862. ((or (not (featurep 'org-inlinetask))
  10863. (org-inlinetask-in-task-p))
  10864. (org-back-to-heading-or-point-min t) (point))
  10865. (t (org-with-limited-levels
  10866. (org-back-to-heading-or-point-min t))
  10867. (point)))))
  10868. ;; Move point to its position according to its positional rules.
  10869. (cond ((org-before-first-heading-p)
  10870. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  10871. (t (forward-line)
  10872. (when (looking-at-p org-planning-line-re) (forward-line))))
  10873. (cond ((looking-at org-property-drawer-re)
  10874. (forward-line)
  10875. (cons (point) (progn (goto-char (match-end 0))
  10876. (line-beginning-position))))
  10877. (force
  10878. (goto-char beg)
  10879. (org-insert-property-drawer)
  10880. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  10881. (line-beginning-position))))
  10882. (cons pos pos)))))))
  10883. (defun org-at-property-drawer-p ()
  10884. "Non-nil when point is at the first line of a property drawer."
  10885. (org-with-wide-buffer
  10886. (beginning-of-line)
  10887. (and (looking-at org-property-drawer-re)
  10888. (or (bobp)
  10889. (progn
  10890. (forward-line -1)
  10891. (cond ((org-at-heading-p))
  10892. ((looking-at org-planning-line-re)
  10893. (forward-line -1)
  10894. (org-at-heading-p))
  10895. ((looking-at org-comment-regexp)
  10896. (forward-line -1)
  10897. (while (and (not (bobp)) (looking-at org-comment-regexp))
  10898. (forward-line -1))
  10899. (looking-at org-comment-regexp))
  10900. (t nil)))))))
  10901. (defun org-at-property-p ()
  10902. "Non-nil when point is inside a property drawer.
  10903. See `org-property-re' for match data, if applicable."
  10904. (save-excursion
  10905. (beginning-of-line)
  10906. (and (looking-at org-property-re)
  10907. (let ((property-drawer (save-match-data (org-get-property-block))))
  10908. (and property-drawer
  10909. (>= (point) (car property-drawer))
  10910. (< (point) (cdr property-drawer)))))))
  10911. (defun org-property-action ()
  10912. "Do an action on properties."
  10913. (interactive)
  10914. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  10915. (let ((c (read-char-exclusive)))
  10916. (cl-case c
  10917. (?s (call-interactively #'org-set-property))
  10918. (?d (call-interactively #'org-delete-property))
  10919. (?D (call-interactively #'org-delete-property-globally))
  10920. (?c (call-interactively #'org-compute-property-at-point))
  10921. (otherwise (user-error "No such property action %c" c)))))
  10922. (defun org-inc-effort ()
  10923. "Increment the value of the effort property in the current entry."
  10924. (interactive)
  10925. (org-set-effort t))
  10926. (defvar org-clock-effort) ; Defined in org-clock.el.
  10927. (defvar org-clock-current-task) ; Defined in org-clock.el.
  10928. (defun org-set-effort (&optional increment value)
  10929. "Set the effort property of the current entry.
  10930. If INCREMENT is non-nil, set the property to the next allowed
  10931. value. Otherwise, if optional argument VALUE is provided, use
  10932. it. Eventually, prompt for the new value if none of the previous
  10933. variables is set."
  10934. (interactive "P")
  10935. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  10936. (current (org-entry-get nil org-effort-property))
  10937. (value
  10938. (cond
  10939. (increment
  10940. (unless allowed (user-error "Allowed effort values are not set"))
  10941. (or (cl-caadr (member (list current) allowed))
  10942. (user-error "Unknown value %S among allowed values" current)))
  10943. (value
  10944. (if (stringp value) value
  10945. (error "Invalid effort value: %S" value)))
  10946. (t
  10947. (let ((must-match
  10948. (and allowed
  10949. (not (get-text-property 0 'org-unrestricted
  10950. (caar allowed))))))
  10951. (completing-read "Effort: " allowed nil must-match))))))
  10952. ;; Test whether the value can be interpreted as a duration before
  10953. ;; inserting it in the buffer:
  10954. (org-duration-to-minutes value)
  10955. ;; Maybe update the effort value:
  10956. (unless (equal current value)
  10957. (org-entry-put nil org-effort-property value))
  10958. (unless (org-element--cache-active-p)
  10959. (org-refresh-property '((effort . identity)
  10960. (effort-minutes . org-duration-to-minutes))
  10961. value))
  10962. (when (equal (org-get-heading t t t t)
  10963. (bound-and-true-p org-clock-current-task))
  10964. (setq org-clock-effort value)
  10965. (org-clock-update-mode-line))
  10966. (message "%s is now %s" org-effort-property value)))
  10967. (defun org-entry-properties (&optional pom which)
  10968. "Get all properties of the current entry.
  10969. When POM is a buffer position, get all properties from the entry
  10970. there instead.
  10971. This includes the TODO keyword, the tags, time strings for
  10972. deadline, scheduled, and clocking, and any additional properties
  10973. defined in the entry.
  10974. If WHICH is nil or `all', get all properties. If WHICH is
  10975. `special' or `standard', only get that subclass. If WHICH is
  10976. a string, only get that property.
  10977. Return value is an alist. Keys are properties, as upcased
  10978. strings."
  10979. (org-with-point-at pom
  10980. (when (and (derived-mode-p 'org-mode)
  10981. (org-back-to-heading-or-point-min t))
  10982. (catch 'exit
  10983. (let* ((beg (point))
  10984. (specific (and (stringp which) (upcase which)))
  10985. (which (cond ((not specific) which)
  10986. ((member specific org-special-properties) 'special)
  10987. (t 'standard)))
  10988. props)
  10989. ;; Get the special properties, like TODO and TAGS.
  10990. (when (memq which '(nil all special))
  10991. (when (or (not specific) (string= specific "CLOCKSUM"))
  10992. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  10993. (when clocksum
  10994. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  10995. props)))
  10996. (when specific (throw 'exit props)))
  10997. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  10998. (let ((clocksumt (get-text-property (point)
  10999. :org-clock-minutes-today)))
  11000. (when clocksumt
  11001. (push (cons "CLOCKSUM_T"
  11002. (org-duration-from-minutes clocksumt))
  11003. props)))
  11004. (when specific (throw 'exit props)))
  11005. (when (or (not specific) (string= specific "ITEM"))
  11006. (let ((case-fold-search nil))
  11007. (when (looking-at org-complex-heading-regexp)
  11008. (push (cons "ITEM"
  11009. (let ((title (match-string-no-properties 4)))
  11010. (if (org-string-nw-p title)
  11011. (org-remove-tabs title)
  11012. "")))
  11013. props)))
  11014. (when specific (throw 'exit props)))
  11015. (when (or (not specific) (string= specific "TODO"))
  11016. (let ((case-fold-search nil))
  11017. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11018. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11019. (when specific (throw 'exit props)))
  11020. (when (or (not specific) (string= specific "PRIORITY"))
  11021. (push (cons "PRIORITY"
  11022. (if (looking-at org-priority-regexp)
  11023. (match-string-no-properties 2)
  11024. (char-to-string org-priority-default)))
  11025. props)
  11026. (when specific (throw 'exit props)))
  11027. (when (or (not specific) (string= specific "FILE"))
  11028. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11029. props)
  11030. (when specific (throw 'exit props)))
  11031. (when (or (not specific) (string= specific "TAGS"))
  11032. (let ((tags (org-get-tags nil t)))
  11033. (when tags
  11034. (push (cons "TAGS" (org-make-tag-string tags))
  11035. props)))
  11036. (when specific (throw 'exit props)))
  11037. (when (or (not specific) (string= specific "ALLTAGS"))
  11038. (let ((tags (org-get-tags)))
  11039. (when tags
  11040. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11041. props)))
  11042. (when specific (throw 'exit props)))
  11043. (when (or (not specific) (string= specific "BLOCKED"))
  11044. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11045. (when specific (throw 'exit props)))
  11046. (when (or (not specific)
  11047. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11048. (forward-line)
  11049. (when (looking-at-p org-planning-line-re)
  11050. (end-of-line)
  11051. (let ((bol (line-beginning-position))
  11052. ;; Backward compatibility: time keywords used to
  11053. ;; be configurable (before 8.3). Make sure we
  11054. ;; get the correct keyword.
  11055. (key-assoc `(("CLOSED" . ,org-closed-string)
  11056. ("DEADLINE" . ,org-deadline-string)
  11057. ("SCHEDULED" . ,org-scheduled-string))))
  11058. (dolist (pair (if specific (list (assoc specific key-assoc))
  11059. key-assoc))
  11060. (save-excursion
  11061. (when (search-backward (cdr pair) bol t)
  11062. (goto-char (match-end 0))
  11063. (skip-chars-forward " \t")
  11064. (and (looking-at org-ts-regexp-both)
  11065. (push (cons (car pair)
  11066. (match-string-no-properties 0))
  11067. props)))))))
  11068. (when specific (throw 'exit props)))
  11069. (when (or (not specific)
  11070. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11071. (let ((find-ts
  11072. (lambda (end ts)
  11073. ;; Fix next time-stamp before END. TS is the
  11074. ;; list of time-stamps found so far.
  11075. (let ((ts ts)
  11076. (regexp (cond
  11077. ((string= specific "TIMESTAMP")
  11078. org-ts-regexp)
  11079. ((string= specific "TIMESTAMP_IA")
  11080. org-ts-regexp-inactive)
  11081. ((assoc "TIMESTAMP_IA" ts)
  11082. org-ts-regexp)
  11083. ((assoc "TIMESTAMP" ts)
  11084. org-ts-regexp-inactive)
  11085. (t org-ts-regexp-both))))
  11086. (catch 'next
  11087. (while (re-search-forward regexp end t)
  11088. (backward-char)
  11089. (let ((object (org-element-context)))
  11090. ;; Accept to match timestamps in node
  11091. ;; properties, too.
  11092. (when (memq (org-element-type object)
  11093. '(node-property timestamp))
  11094. (let ((type
  11095. (org-element-property :type object)))
  11096. (cond
  11097. ((and (memq type '(active active-range))
  11098. (not (equal specific "TIMESTAMP_IA")))
  11099. (unless (assoc "TIMESTAMP" ts)
  11100. (push (cons "TIMESTAMP"
  11101. (org-element-property
  11102. :raw-value object))
  11103. ts)
  11104. (when specific (throw 'exit ts))))
  11105. ((and (memq type '(inactive inactive-range))
  11106. (not (string= specific "TIMESTAMP")))
  11107. (unless (assoc "TIMESTAMP_IA" ts)
  11108. (push (cons "TIMESTAMP_IA"
  11109. (org-element-property
  11110. :raw-value object))
  11111. ts)
  11112. (when specific (throw 'exit ts))))))
  11113. ;; Both timestamp types are found,
  11114. ;; move to next part.
  11115. (when (= (length ts) 2) (throw 'next ts)))))
  11116. ts)))))
  11117. (goto-char beg)
  11118. ;; First look for timestamps within headline.
  11119. (let ((ts (funcall find-ts (line-end-position) nil)))
  11120. (if (= (length ts) 2) (setq props (nconc ts props))
  11121. ;; Then find timestamps in the section, skipping
  11122. ;; planning line.
  11123. (let ((end (save-excursion (outline-next-heading))))
  11124. (forward-line)
  11125. (when (looking-at-p org-planning-line-re) (forward-line))
  11126. (setq props (nconc (funcall find-ts end ts) props))))))))
  11127. ;; Get the standard properties, like :PROP:.
  11128. (when (memq which '(nil all standard))
  11129. ;; If we are looking after a specific property, delegate
  11130. ;; to `org-entry-get', which is faster. However, make an
  11131. ;; exception for "CATEGORY", since it can be also set
  11132. ;; through keywords (i.e. #+CATEGORY).
  11133. (if (and specific (not (equal specific "CATEGORY")))
  11134. (let ((value (org-entry-get beg specific nil t)))
  11135. (throw 'exit (and value (list (cons specific value)))))
  11136. (let ((range (org-get-property-block beg)))
  11137. (when range
  11138. (let ((end (cdr range)) seen-base)
  11139. (goto-char (car range))
  11140. ;; Unlike to `org--update-property-plist', we
  11141. ;; handle the case where base values is found
  11142. ;; after its extension. We also forbid standard
  11143. ;; properties to be named as special properties.
  11144. (while (re-search-forward org-property-re end t)
  11145. (let* ((key (upcase (match-string-no-properties 2)))
  11146. (extendp (string-match-p "\\+\\'" key))
  11147. (key-base (if extendp (substring key 0 -1) key))
  11148. (value (match-string-no-properties 3)))
  11149. (cond
  11150. ((member-ignore-case key-base org-special-properties))
  11151. (extendp
  11152. (setq props
  11153. (org--update-property-plist key value props)))
  11154. ((member key seen-base))
  11155. (t (push key seen-base)
  11156. (let ((p (assoc-string key props t)))
  11157. (if p (setcdr p (concat value " " (cdr p)))
  11158. (push (cons key value) props))))))))))))
  11159. (unless (assoc "CATEGORY" props)
  11160. (push (cons "CATEGORY" (org-get-category beg)) props)
  11161. (when (string= specific "CATEGORY") (throw 'exit props)))
  11162. ;; Return value.
  11163. props)))))
  11164. (defun org--property-local-values (property literal-nil &optional element)
  11165. "Return value for PROPERTY in current entry or ELEMENT.
  11166. Value is a list whose car is the base value for PROPERTY and cdr
  11167. a list of accumulated values. Return nil if neither is found in
  11168. the entry. Also return nil when PROPERTY is set to \"nil\",
  11169. unless LITERAL-NIL is non-nil."
  11170. (let ((element (or element
  11171. (and (org-element--cache-active-p)
  11172. (org-element-at-point nil 'cached)))))
  11173. (if element
  11174. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11175. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11176. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11177. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11178. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11179. (value (cons base-value extra-value)))
  11180. (and (not (equal value '(nil))) value))
  11181. (let ((range (org-get-property-block)))
  11182. (when range
  11183. (goto-char (car range))
  11184. (let* ((case-fold-search t)
  11185. (end (cdr range))
  11186. (value
  11187. ;; Base value.
  11188. (save-excursion
  11189. (let ((v (and (re-search-forward
  11190. (org-re-property property nil t) end t)
  11191. (match-string-no-properties 3))))
  11192. (list (if literal-nil v (org-not-nil v)))))))
  11193. ;; Find additional values.
  11194. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11195. (while (re-search-forward property+ end t)
  11196. (push (match-string-no-properties 3) value)))
  11197. ;; Return final values.
  11198. (and (not (equal value '(nil))) (nreverse value))))))))
  11199. (defun org--property-global-or-keyword-value (property literal-nil)
  11200. "Return value for PROPERTY as defined by global properties or by keyword.
  11201. Return value is a string. Return nil if property is not set
  11202. globally or by keyword. Also return nil when PROPERTY is set to
  11203. \"nil\", unless LITERAL-NIL is non-nil."
  11204. (let ((global
  11205. (cdr (or (assoc-string property org-keyword-properties t)
  11206. (assoc-string property org-global-properties t)
  11207. (assoc-string property org-global-properties-fixed t)))))
  11208. (if literal-nil global (org-not-nil global))))
  11209. (defun org-entry-get (pom property &optional inherit literal-nil)
  11210. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11211. If INHERIT is non-nil and the entry does not have the property,
  11212. then also check higher levels of the hierarchy. If INHERIT is
  11213. the symbol `selective', use inheritance only if the setting in
  11214. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11215. If the property is present but empty, the return value is the
  11216. empty string. If the property is not present at all, nil is
  11217. returned. In any other case, return the value as a string.
  11218. Search is case-insensitive.
  11219. If LITERAL-NIL is set, return the string value \"nil\" as
  11220. a string, do not interpret it as the list atom nil. This is used
  11221. for inheritance when a \"nil\" value can supersede a non-nil
  11222. value higher up the hierarchy."
  11223. (org-with-point-at pom
  11224. (cond
  11225. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11226. ;; We need a special property. Use `org-entry-properties' to
  11227. ;; retrieve it, but specify the wanted property.
  11228. (cdr (assoc-string property (org-entry-properties nil property))))
  11229. ((and inherit
  11230. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11231. (org-entry-get-with-inheritance property literal-nil))
  11232. (t
  11233. (let* ((local (org--property-local-values property literal-nil))
  11234. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11235. (if literal-nil value (org-not-nil value)))))))
  11236. (defun org-property-or-variable-value (var &optional inherit)
  11237. "Check if there is a property fixing the value of VAR.
  11238. If yes, return this value. If not, return the current value of the variable."
  11239. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11240. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11241. (read prop)
  11242. (symbol-value var))))
  11243. (defun org-entry-delete (pom property)
  11244. "Delete PROPERTY from entry at point-or-marker POM.
  11245. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11246. non-nil when a property was removed."
  11247. (org-with-point-at pom
  11248. (pcase (org-get-property-block)
  11249. (`(,begin . ,origin)
  11250. (let* ((end (copy-marker origin))
  11251. (re (org-re-property
  11252. (concat (regexp-quote property) "\\+?") t t)))
  11253. (goto-char begin)
  11254. (while (re-search-forward re end t)
  11255. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11256. ;; If drawer is empty, remove it altogether.
  11257. (when (= begin end)
  11258. (delete-region (line-beginning-position 0)
  11259. (line-beginning-position 2)))
  11260. ;; Return non-nil if some property was removed.
  11261. (prog1 (/= end origin) (set-marker end nil))))
  11262. (_ nil))))
  11263. ;; Multi-values properties are properties that contain multiple values
  11264. ;; These values are assumed to be single words, separated by whitespace.
  11265. (defun org-entry-add-to-multivalued-property (pom property value)
  11266. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11267. (let* ((old (org-entry-get pom property))
  11268. (values (and old (split-string old))))
  11269. (setq value (org-entry-protect-space value))
  11270. (unless (member value values)
  11271. (setq values (append values (list value)))
  11272. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11273. (defun org-entry-remove-from-multivalued-property (pom property value)
  11274. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11275. (let* ((old (org-entry-get pom property))
  11276. (values (and old (split-string old))))
  11277. (setq value (org-entry-protect-space value))
  11278. (when (member value values)
  11279. (setq values (delete value values))
  11280. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11281. (defun org-entry-member-in-multivalued-property (pom property value)
  11282. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11283. (let* ((old (org-entry-get pom property))
  11284. (values (and old (split-string old))))
  11285. (setq value (org-entry-protect-space value))
  11286. (member value values)))
  11287. (defun org-entry-get-multivalued-property (pom property)
  11288. "Return a list of values in a multivalued property."
  11289. (let* ((value (org-entry-get pom property))
  11290. (values (and value (split-string value))))
  11291. (mapcar #'org-entry-restore-space values)))
  11292. (defun org-entry-put-multivalued-property (pom property &rest values)
  11293. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11294. VALUES should be a list of strings. Spaces will be protected."
  11295. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11296. (let* ((value (org-entry-get pom property))
  11297. (values (and value (split-string value))))
  11298. (mapcar #'org-entry-restore-space values)))
  11299. (defun org-entry-protect-space (s)
  11300. "Protect spaces and newline in string S."
  11301. (while (string-match " " s)
  11302. (setq s (replace-match "%20" t t s)))
  11303. (while (string-match "\n" s)
  11304. (setq s (replace-match "%0A" t t s)))
  11305. s)
  11306. (defun org-entry-restore-space (s)
  11307. "Restore spaces and newline in string S."
  11308. (while (string-match "%20" s)
  11309. (setq s (replace-match " " t t s)))
  11310. (while (string-match "%0A" s)
  11311. (setq s (replace-match "\n" t t s)))
  11312. s)
  11313. (defvar org-entry-property-inherited-from (make-marker)
  11314. "Marker pointing to the entry from where a property was inherited.
  11315. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11316. location of the entry where the inheritance search matched. If there was
  11317. no match, the marker will point nowhere.
  11318. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11319. is set.")
  11320. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11321. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11322. The search will stop at the first ancestor which has the property defined.
  11323. If the value found is \"nil\", return nil to show that the property
  11324. should be considered as undefined (this is the meaning of nil here).
  11325. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11326. (move-marker org-entry-property-inherited-from nil)
  11327. (org-with-wide-buffer
  11328. (let (value at-bob-no-heading)
  11329. (catch 'exit
  11330. (let ((element (or element
  11331. (and (org-element--cache-active-p)
  11332. (org-element-at-point nil 'cached)))))
  11333. (if element
  11334. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11335. (while t
  11336. (let* ((v (org--property-local-values property literal-nil element))
  11337. (v (if (listp v) v (list v))))
  11338. (when v
  11339. (setq value
  11340. (concat (mapconcat #'identity (delq nil v) " ")
  11341. (and value " ")
  11342. value)))
  11343. (cond
  11344. ((car v)
  11345. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11346. (throw 'exit nil))
  11347. ((org-element-property :parent element)
  11348. (setq element (org-element-property :parent element)))
  11349. (t
  11350. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11351. (cond ((not global))
  11352. (value (setq value (concat global " " value)))
  11353. (t (setq value global))))
  11354. (throw 'exit nil))))))
  11355. (while t
  11356. (let ((v (org--property-local-values property literal-nil)))
  11357. (when v
  11358. (setq value
  11359. (concat (mapconcat #'identity (delq nil v) " ")
  11360. (and value " ")
  11361. value)))
  11362. (cond
  11363. ((car v)
  11364. (org-back-to-heading-or-point-min t)
  11365. (move-marker org-entry-property-inherited-from (point))
  11366. (throw 'exit nil))
  11367. ((or (org-up-heading-safe)
  11368. (and (not (bobp))
  11369. (goto-char (point-min))
  11370. nil)
  11371. ;; `org-up-heading-safe' returned nil. We are at low
  11372. ;; level heading or bob. If there is headline
  11373. ;; there, do not try to fetch its properties.
  11374. (and (bobp)
  11375. (not at-bob-no-heading)
  11376. (not (org-at-heading-p))
  11377. (setq at-bob-no-heading t))))
  11378. (t
  11379. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11380. (cond ((not global))
  11381. (value (setq value (concat global " " value)))
  11382. (t (setq value global))))
  11383. (throw 'exit nil))))))))
  11384. (if literal-nil value (org-not-nil value)))))
  11385. (defvar org-property-changed-functions nil
  11386. "Hook called when the value of a property has changed.
  11387. Each hook function should accept two arguments, the name of the property
  11388. and the new value.")
  11389. (defun org-entry-put (pom property value)
  11390. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11391. If the value is nil, it is converted to the empty string. If it
  11392. is not a string, an error is raised. Also raise an error on
  11393. invalid property names.
  11394. PROPERTY can be any regular property (see
  11395. `org-special-properties'). It can also be \"TODO\",
  11396. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11397. For the last two properties, VALUE may have any of the special
  11398. values \"earlier\" and \"later\". The function then increases or
  11399. decreases scheduled or deadline date by one day."
  11400. (cond ((null value) (setq value ""))
  11401. ((not (stringp value)) (error "Properties values should be strings"))
  11402. ((not (org--valid-property-p property))
  11403. (user-error "Invalid property name: \"%s\"" property)))
  11404. (org-no-read-only
  11405. (org-with-point-at pom
  11406. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11407. (org-back-to-heading-or-point-min t)
  11408. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11409. (let ((beg (point)))
  11410. (cond
  11411. ((equal property "TODO")
  11412. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11413. ((not (member value org-todo-keywords-1))
  11414. (user-error "\"%s\" is not a valid TODO state" value)))
  11415. (org-todo value)
  11416. (org-align-tags))
  11417. ((equal property "PRIORITY")
  11418. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11419. (org-align-tags))
  11420. ((equal property "SCHEDULED")
  11421. (forward-line)
  11422. (if (and (looking-at-p org-planning-line-re)
  11423. (re-search-forward
  11424. org-scheduled-time-regexp (line-end-position) t))
  11425. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11426. ((string= value "later") (org-timestamp-change 1 'day))
  11427. ((string= value "") (org-schedule '(4)))
  11428. (t (org-schedule nil value)))
  11429. (if (member value '("earlier" "later" ""))
  11430. (call-interactively #'org-schedule)
  11431. (org-schedule nil value))))
  11432. ((equal property "DEADLINE")
  11433. (forward-line)
  11434. (if (and (looking-at-p org-planning-line-re)
  11435. (re-search-forward
  11436. org-deadline-time-regexp (line-end-position) t))
  11437. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11438. ((string= value "later") (org-timestamp-change 1 'day))
  11439. ((string= value "") (org-deadline '(4)))
  11440. (t (org-deadline nil value)))
  11441. (if (member value '("earlier" "later" ""))
  11442. (call-interactively #'org-deadline)
  11443. (org-deadline nil value))))
  11444. ((member property org-special-properties)
  11445. (error "The %s property cannot be set with `org-entry-put'" property))
  11446. (t
  11447. (org-fold-core-ignore-modifications
  11448. (let* ((range (org-get-property-block beg 'force))
  11449. (end (cdr range))
  11450. (case-fold-search t))
  11451. (goto-char (car range))
  11452. (if (re-search-forward (org-re-property property nil t) end t)
  11453. (progn (delete-region (match-beginning 0) (match-end 0))
  11454. (goto-char (match-beginning 0)))
  11455. (goto-char end)
  11456. (insert-and-inherit "\n")
  11457. (backward-char))
  11458. (insert-and-inherit ":" property ":")
  11459. (when value (insert-and-inherit " " value))
  11460. (org-indent-line))))))
  11461. (run-hook-with-args 'org-property-changed-functions property value))))
  11462. (defun org-buffer-property-keys (&optional specials defaults columns)
  11463. "Get all property keys in the current buffer.
  11464. When SPECIALS is non-nil, also list the special properties that
  11465. reflect things like tags and TODO state.
  11466. When DEFAULTS is non-nil, also include properties that has
  11467. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11468. DESCRIPTION, LOCATION, and LOGGING and others.
  11469. When COLUMNS in non-nil, also include property names given in
  11470. COLUMN formats in the current buffer."
  11471. (let ((case-fold-search t)
  11472. (props (append
  11473. (and specials org-special-properties)
  11474. (and defaults (cons org-effort-property org-default-properties))
  11475. ;; Get property names from #+PROPERTY keywords as well
  11476. (mapcar (lambda (s)
  11477. (nth 0 (split-string s)))
  11478. (cdar (org-collect-keywords '("PROPERTY")))))))
  11479. (org-with-wide-buffer
  11480. (goto-char (point-min))
  11481. (while (re-search-forward org-property-start-re nil t)
  11482. (catch :skip
  11483. (let ((range (org-get-property-block)))
  11484. (unless range (throw :skip nil))
  11485. (goto-char (car range))
  11486. (let ((begin (car range))
  11487. (end (cdr range)))
  11488. ;; Make sure that found property block is not located
  11489. ;; before current point, as it would generate an infloop.
  11490. ;; It can happen, for example, in the following
  11491. ;; situation:
  11492. ;;
  11493. ;; * Headline
  11494. ;; :PROPERTIES:
  11495. ;; ...
  11496. ;; :END:
  11497. ;; *************** Inlinetask
  11498. ;; #+BEGIN_EXAMPLE
  11499. ;; :PROPERTIES:
  11500. ;; #+END_EXAMPLE
  11501. ;;
  11502. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11503. (while (< (point) end)
  11504. (let ((p (progn (looking-at org-property-re)
  11505. (match-string-no-properties 2))))
  11506. ;; Only add true property name, not extension symbol.
  11507. (push (if (not (string-match-p "\\+\\'" p)) p
  11508. (substring p 0 -1))
  11509. props))
  11510. (forward-line))))
  11511. (outline-next-heading)))
  11512. (when columns
  11513. (goto-char (point-min))
  11514. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11515. (let ((element (org-element-at-point)))
  11516. (when (memq (org-element-type element) '(keyword node-property))
  11517. (let ((value (org-element-property :value element))
  11518. (start 0))
  11519. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11520. \\(?:{[^}]+}\\)?"
  11521. value start)
  11522. (setq start (match-end 0))
  11523. (let ((p (match-string-no-properties 1 value)))
  11524. (unless (member-ignore-case p org-special-properties)
  11525. (push p props))))))))))
  11526. (sort (delete-dups
  11527. (append props
  11528. ;; for each xxx_ALL property, make sure the bare
  11529. ;; xxx property is also included
  11530. (delq nil (mapcar (lambda (p)
  11531. (and (string-match-p "._ALL\\'" p)
  11532. (substring p 0 -4)))
  11533. props))))
  11534. (lambda (a b) (string< (upcase a) (upcase b))))))
  11535. (defun org-property-values (key)
  11536. "List all non-nil values of property KEY in current buffer."
  11537. (org-with-wide-buffer
  11538. (goto-char (point-min))
  11539. (let ((case-fold-search t)
  11540. (re (org-re-property key))
  11541. values)
  11542. (while (re-search-forward re nil t)
  11543. (push (org-entry-get (point) key) values))
  11544. (delete-dups values))))
  11545. (defun org-insert-property-drawer ()
  11546. "Insert a property drawer into the current entry.
  11547. Do nothing if the drawer already exists. The newly created
  11548. drawer is immediately hidden."
  11549. (org-with-wide-buffer
  11550. ;; Set point to the position where the drawer should be inserted.
  11551. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11552. (org-back-to-heading-or-point-min t)
  11553. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11554. (if (org-before-first-heading-p)
  11555. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11556. (forward-line)
  11557. (when (looking-at-p org-planning-line-re) (forward-line)))
  11558. (unless (looking-at-p org-property-drawer-re)
  11559. ;; Make sure we start editing a line from current entry, not from
  11560. ;; next one. It prevents extending text properties or overlays
  11561. ;; belonging to the latter.
  11562. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11563. (let ((begin (if (bobp) (point) (1+ (point))))
  11564. (inhibit-read-only t))
  11565. (unless (bobp) (insert "\n"))
  11566. (insert ":PROPERTIES:\n:END:")
  11567. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11568. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11569. (org-indent-region begin (point))))))
  11570. (defun org-insert-drawer (&optional arg drawer)
  11571. "Insert a drawer at point.
  11572. When optional argument ARG is non-nil, insert a property drawer.
  11573. Optional argument DRAWER, when non-nil, is a string representing
  11574. drawer's name. Otherwise, the user is prompted for a name.
  11575. If a region is active, insert the drawer around that region
  11576. instead.
  11577. Point is left between drawer's boundaries."
  11578. (interactive "P")
  11579. (let* ((drawer (if arg "PROPERTIES"
  11580. (or drawer (read-from-minibuffer "Drawer: ")))))
  11581. (cond
  11582. ;; With C-u, fall back on `org-insert-property-drawer'
  11583. (arg (org-insert-property-drawer))
  11584. ;; Check validity of suggested drawer's name.
  11585. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11586. (user-error "Invalid drawer name"))
  11587. ;; With an active region, insert a drawer at point.
  11588. ((not (org-region-active-p))
  11589. (progn
  11590. (unless (bolp) (insert "\n"))
  11591. (insert (format ":%s:\n\n:END:\n" drawer))
  11592. (forward-line -2)))
  11593. ;; Otherwise, insert the drawer at point
  11594. (t
  11595. (let ((rbeg (region-beginning))
  11596. (rend (copy-marker (region-end))))
  11597. (unwind-protect
  11598. (progn
  11599. (goto-char rbeg)
  11600. (beginning-of-line)
  11601. (when (save-excursion
  11602. (re-search-forward org-outline-regexp-bol rend t))
  11603. (user-error "Drawers cannot contain headlines"))
  11604. ;; Position point at the beginning of the first
  11605. ;; non-blank line in region. Insert drawer's opening
  11606. ;; there, then indent it.
  11607. (org-skip-whitespace)
  11608. (beginning-of-line)
  11609. (insert ":" drawer ":\n")
  11610. (forward-line -1)
  11611. (indent-for-tab-command)
  11612. ;; Move point to the beginning of the first blank line
  11613. ;; after the last non-blank line in region. Insert
  11614. ;; drawer's closing, then indent it.
  11615. (goto-char rend)
  11616. (skip-chars-backward " \r\t\n")
  11617. (insert "\n:END:")
  11618. (deactivate-mark t)
  11619. (indent-for-tab-command)
  11620. (unless (eolp) (insert "\n")))
  11621. ;; Clear marker, whatever the outcome of insertion is.
  11622. (set-marker rend nil)))))))
  11623. (defvar org-property-set-functions-alist nil
  11624. "Property set function alist.
  11625. Each entry should have the following format:
  11626. (PROPERTY . READ-FUNCTION)
  11627. The read function will be called with the same argument as
  11628. `org-completing-read'.")
  11629. (defun org-set-property-function (property)
  11630. "Get the function that should be used to set PROPERTY.
  11631. This is computed according to `org-property-set-functions-alist'."
  11632. (or (cdr (assoc property org-property-set-functions-alist))
  11633. 'org-completing-read))
  11634. (defun org-read-property-value (property &optional pom default)
  11635. "Read value for PROPERTY, as a string.
  11636. When optional argument POM is non-nil, completion uses additional
  11637. information, i.e., allowed or existing values at point or marker
  11638. POM.
  11639. Optional argument DEFAULT provides a default value for PROPERTY."
  11640. (let* ((completion-ignore-case t)
  11641. (allowed
  11642. (or (org-property-get-allowed-values nil property 'table)
  11643. (and pom (org-property-get-allowed-values pom property 'table))))
  11644. (current (org-entry-get nil property))
  11645. (prompt (format "%s value%s: "
  11646. property
  11647. (if (org-string-nw-p current)
  11648. (format " [%s]" current)
  11649. "")))
  11650. (set-function (org-set-property-function property)))
  11651. (org-trim
  11652. (if allowed
  11653. (funcall set-function
  11654. prompt allowed nil
  11655. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11656. default nil default)
  11657. (let ((all (mapcar #'list
  11658. (append (org-property-values property)
  11659. (and pom
  11660. (org-with-point-at pom
  11661. (org-property-values property)))))))
  11662. (funcall set-function prompt all nil nil "" nil current))))))
  11663. (defvar org-last-set-property nil)
  11664. (defvar org-last-set-property-value nil)
  11665. (defun org-read-property-name ()
  11666. "Read a property name."
  11667. (let ((completion-ignore-case t)
  11668. (default-prop (or (and (org-at-property-p)
  11669. (match-string-no-properties 2))
  11670. org-last-set-property)))
  11671. (org-completing-read
  11672. (concat "Property"
  11673. (if default-prop (concat " [" default-prop "]") "")
  11674. ": ")
  11675. (mapcar #'list (org-buffer-property-keys nil t t))
  11676. nil nil nil nil default-prop)))
  11677. (defun org-set-property-and-value (use-last)
  11678. "Allow to set [PROPERTY]: [value] direction from prompt.
  11679. When use-default, don't even ask, just use the last
  11680. \"[PROPERTY]: [value]\" string from the history."
  11681. (interactive "P")
  11682. (let* ((completion-ignore-case t)
  11683. (pv (or (and use-last org-last-set-property-value)
  11684. (org-completing-read
  11685. "Enter a \"[Property]: [value]\" pair: "
  11686. nil nil nil nil nil
  11687. org-last-set-property-value)))
  11688. prop val)
  11689. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11690. (setq prop (match-string 1 pv)
  11691. val (match-string 2 pv))
  11692. (org-set-property prop val))))
  11693. (defun org-set-property (property value)
  11694. "In the current entry, set PROPERTY to VALUE.
  11695. When called interactively, this will prompt for a property name, offering
  11696. completion on existing and default properties. And then it will prompt
  11697. for a value, offering completion either on allowed values (via an inherited
  11698. xxx_ALL property) or on existing values in other instances of this property
  11699. in the current file.
  11700. Throw an error when trying to set a property with an invalid name."
  11701. (interactive (list nil nil))
  11702. (let ((property (or property (org-read-property-name))))
  11703. ;; `org-entry-put' also makes the following check, but this one
  11704. ;; avoids polluting `org-last-set-property' and
  11705. ;; `org-last-set-property-value' needlessly.
  11706. (unless (org--valid-property-p property)
  11707. (user-error "Invalid property name: \"%s\"" property))
  11708. (let ((value (or value (org-read-property-value property)))
  11709. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11710. (setq org-last-set-property property)
  11711. (setq org-last-set-property-value (concat property ": " value))
  11712. ;; Possibly postprocess the inserted value:
  11713. (when fn (setq value (funcall fn value)))
  11714. (unless (equal (org-entry-get nil property) value)
  11715. (org-entry-put nil property value)))))
  11716. (defun org-find-property (property &optional value)
  11717. "Find first entry in buffer that sets PROPERTY.
  11718. When optional argument VALUE is non-nil, only consider an entry
  11719. if it contains PROPERTY set to this value. If PROPERTY should be
  11720. explicitly set to nil, use string \"nil\" for VALUE.
  11721. Return position where the entry begins, or nil if there is no
  11722. such entry. If narrowing is in effect, only search the visible
  11723. part of the buffer."
  11724. (save-excursion
  11725. (goto-char (point-min))
  11726. (let ((case-fold-search t)
  11727. (re (org-re-property property nil (not value) value)))
  11728. (catch 'exit
  11729. (while (re-search-forward re nil t)
  11730. (when (if value (org-at-property-p)
  11731. (org-entry-get (point) property nil t))
  11732. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  11733. (point)))))))))
  11734. (defun org-delete-property (property)
  11735. "In the current entry, delete PROPERTY."
  11736. (interactive
  11737. (let* ((completion-ignore-case t)
  11738. (cat (org-entry-get (point) "CATEGORY"))
  11739. (props0 (org-entry-properties nil 'standard))
  11740. (props (if cat props0
  11741. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  11742. (prop (if (< 1 (length props))
  11743. (completing-read "Property: " props nil t)
  11744. (caar props))))
  11745. (list prop)))
  11746. (if (not property)
  11747. (message "No property to delete in this entry")
  11748. (org-entry-delete nil property)
  11749. (message "Property \"%s\" deleted" property)))
  11750. (defun org-delete-property-globally (property)
  11751. "Remove PROPERTY globally, from all entries.
  11752. This function ignores narrowing, if any."
  11753. (interactive
  11754. (let* ((completion-ignore-case t)
  11755. (prop (completing-read
  11756. "Globally remove property: "
  11757. (mapcar #'list (org-buffer-property-keys)))))
  11758. (list prop)))
  11759. (org-with-wide-buffer
  11760. (goto-char (point-min))
  11761. (let ((count 0)
  11762. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  11763. (while (re-search-forward re nil t)
  11764. (when (org-entry-delete (point) property) (cl-incf count)))
  11765. (message "Property \"%s\" removed from %d entries" property count))))
  11766. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  11767. (defun org-compute-property-at-point ()
  11768. "Compute the property at point.
  11769. This looks for an enclosing column format, extracts the operator and
  11770. then applies it to the property in the column format's scope."
  11771. (interactive)
  11772. (unless (org-at-property-p)
  11773. (user-error "Not at a property"))
  11774. (let ((prop (match-string-no-properties 2)))
  11775. (org-columns-get-format-and-top-level)
  11776. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  11777. (user-error "No operator defined for property %s" prop))
  11778. (org-columns-compute prop)))
  11779. (defvar org-property-allowed-value-functions nil
  11780. "Hook for functions supplying allowed values for a specific property.
  11781. The functions must take a single argument, the name of the property, and
  11782. return a flat list of allowed values. If \":ETC\" is one of
  11783. the values, this means that these values are intended as defaults for
  11784. completion, but that other values should be allowed too.
  11785. The functions must return nil if they are not responsible for this
  11786. property.")
  11787. (defun org-property-get-allowed-values (pom property &optional table)
  11788. "Get allowed values for the property PROPERTY.
  11789. When TABLE is non-nil, return an alist that can directly be used for
  11790. completion."
  11791. (let (vals)
  11792. (cond
  11793. ((equal property "TODO")
  11794. (setq vals (org-with-point-at pom
  11795. (append org-todo-keywords-1 '("")))))
  11796. ((equal property "PRIORITY")
  11797. (let ((n org-priority-lowest))
  11798. (while (>= n org-priority-highest)
  11799. (push (char-to-string n) vals)
  11800. (setq n (1- n)))))
  11801. ((equal property "CATEGORY"))
  11802. ((member property org-special-properties))
  11803. ((setq vals (run-hook-with-args-until-success
  11804. 'org-property-allowed-value-functions property)))
  11805. (t
  11806. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  11807. (when (and vals (string-match "\\S-" vals))
  11808. (setq vals (car (read-from-string (concat "(" vals ")"))))
  11809. (setq vals (mapcar (lambda (x)
  11810. (cond ((stringp x) x)
  11811. ((numberp x) (number-to-string x))
  11812. ((symbolp x) (symbol-name x))
  11813. (t "???")))
  11814. vals)))))
  11815. (when (member ":ETC" vals)
  11816. (setq vals (remove ":ETC" vals))
  11817. (org-add-props (car vals) '(org-unrestricted t)))
  11818. (if table (mapcar 'list vals) vals)))
  11819. (defun org-property-previous-allowed-value (&optional _previous)
  11820. "Switch to the next allowed value for this property."
  11821. (interactive)
  11822. (org-property-next-allowed-value t))
  11823. (defun org-property-next-allowed-value (&optional previous)
  11824. "Switch to the next allowed value for this property."
  11825. (interactive)
  11826. (unless (org-at-property-p)
  11827. (user-error "Not at a property"))
  11828. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  11829. (key (match-string 2))
  11830. (value (match-string 3))
  11831. (allowed (or (org-property-get-allowed-values (point) key)
  11832. (and (member value '("[ ]" "[-]" "[X]"))
  11833. '("[ ]" "[X]"))))
  11834. (heading (save-match-data (nth 4 (org-heading-components))))
  11835. nval)
  11836. (unless allowed
  11837. (user-error "Allowed values for this property have not been defined"))
  11838. (when previous (setq allowed (reverse allowed)))
  11839. (when (member value allowed)
  11840. (setq nval (car (cdr (member value allowed)))))
  11841. (setq nval (or nval (car allowed)))
  11842. (when (equal nval value)
  11843. (user-error "Only one allowed value for this property"))
  11844. (org-at-property-p)
  11845. (replace-match (concat " :" key ": " nval) t t)
  11846. (org-indent-line)
  11847. (beginning-of-line 1)
  11848. (skip-chars-forward " \t")
  11849. (when (equal prop org-effort-property)
  11850. (unless (org-element--cache-active-p)
  11851. (org-refresh-property
  11852. '((effort . identity)
  11853. (effort-minutes . org-duration-to-minutes))
  11854. nval))
  11855. (when (string= org-clock-current-task heading)
  11856. (setq org-clock-effort nval)
  11857. (org-clock-update-mode-line)))
  11858. (run-hook-with-args 'org-property-changed-functions key nval)))
  11859. (defun org-find-olp (path &optional this-buffer)
  11860. "Return a marker pointing to the entry at outline path OLP.
  11861. If anything goes wrong, throw an error, and if you need to do
  11862. something based on this error, you can catch it with
  11863. `condition-case'.
  11864. If THIS-BUFFER is set, the outline path does not contain a file,
  11865. only headings."
  11866. (let* ((file (if this-buffer buffer-file-name (pop path)))
  11867. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  11868. (level 1)
  11869. (lmin 1)
  11870. (lmax 1)
  11871. end found flevel)
  11872. (unless buffer (error "File not found :%s" file))
  11873. (with-current-buffer buffer
  11874. (unless (derived-mode-p 'org-mode)
  11875. (error "Buffer %s needs to be in Org mode" buffer))
  11876. (org-with-wide-buffer
  11877. (goto-char (point-min))
  11878. (dolist (heading path)
  11879. (let ((re (format org-complex-heading-regexp-format
  11880. (regexp-quote heading)))
  11881. (cnt 0))
  11882. (while (re-search-forward re end t)
  11883. (setq level (- (match-end 1) (match-beginning 1)))
  11884. (when (and (>= level lmin) (<= level lmax))
  11885. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  11886. (when (= cnt 0)
  11887. (error "Heading not found on level %d: %s" lmax heading))
  11888. (when (> cnt 1)
  11889. (error "Heading not unique on level %d: %s" lmax heading))
  11890. (goto-char found)
  11891. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  11892. (setq end (save-excursion (org-end-of-subtree t t)))))
  11893. (when (org-at-heading-p)
  11894. (point-marker))))))
  11895. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  11896. "Find node HEADING in BUFFER.
  11897. Return a marker to the heading if it was found, or nil if not.
  11898. If POS-ONLY is set, return just the position instead of a marker.
  11899. The heading text must match exact, but it may have a TODO keyword,
  11900. a priority cookie and tags in the standard locations."
  11901. (with-current-buffer (or buffer (current-buffer))
  11902. (org-with-wide-buffer
  11903. (goto-char (point-min))
  11904. (let (case-fold-search)
  11905. (when (re-search-forward
  11906. (format org-complex-heading-regexp-format
  11907. (regexp-quote heading)) nil t)
  11908. (if pos-only
  11909. (match-beginning 0)
  11910. (move-marker (make-marker) (match-beginning 0))))))))
  11911. (defun org-find-exact-heading-in-directory (heading &optional dir)
  11912. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  11913. When the target headline is found, return a marker to this location."
  11914. (let ((files (directory-files (or dir default-directory)
  11915. t "\\`[^.#].*\\.org\\'"))
  11916. visiting m buffer)
  11917. (catch 'found
  11918. (dolist (file files)
  11919. (message "trying %s" file)
  11920. (setq visiting (org-find-base-buffer-visiting file))
  11921. (setq buffer (or visiting (find-file-noselect file)))
  11922. (setq m (org-find-exact-headline-in-buffer
  11923. heading buffer))
  11924. (when (and (not m) (not visiting)) (kill-buffer buffer))
  11925. (and m (throw 'found m))))))
  11926. (defun org-find-entry-with-id (ident)
  11927. "Locate the entry that contains the ID property with exact value IDENT.
  11928. IDENT can be a string, a symbol or a number, this function will search for
  11929. the string representation of it.
  11930. Return the position where this entry starts, or nil if there is no such entry."
  11931. (interactive "sID: ")
  11932. (let ((id (cond
  11933. ((stringp ident) ident)
  11934. ((symbolp ident) (symbol-name ident))
  11935. ((numberp ident) (number-to-string ident))
  11936. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  11937. (org-with-wide-buffer (org-find-property "ID" id))))
  11938. ;;;; Timestamps
  11939. (defvar org-last-changed-timestamp nil)
  11940. (defvar org-last-inserted-timestamp nil
  11941. "The last time stamp inserted with `org-insert-time-stamp'.")
  11942. (defun org-time-stamp (arg &optional inactive)
  11943. "Prompt for a date/time and insert a time stamp.
  11944. If the user specifies a time like HH:MM or if this command is
  11945. called with at least one prefix argument, the time stamp contains
  11946. the date and the time. Otherwise, only the date is included.
  11947. All parts of a date not specified by the user are filled in from
  11948. the timestamp at point, if any, or the current date/time
  11949. otherwise.
  11950. If there is already a timestamp at the cursor, it is replaced.
  11951. With two universal prefix arguments, insert an active timestamp
  11952. with the current time without prompting the user.
  11953. When called from Lisp, the timestamp is inactive if INACTIVE is
  11954. non-nil."
  11955. (interactive "P")
  11956. (let* ((ts (cond
  11957. ((org-at-date-range-p t)
  11958. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  11959. ((org-at-timestamp-p 'lax) (match-string 0))))
  11960. ;; Default time is either the timestamp at point or today.
  11961. ;; When entering a range, only the range start is considered.
  11962. (default-time (and ts (org-time-string-to-time ts)))
  11963. (default-input (and ts (org-get-compact-tod ts)))
  11964. (repeater (and ts
  11965. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  11966. (match-string 0 ts)))
  11967. org-time-was-given
  11968. org-end-time-was-given
  11969. (time
  11970. (if (equal arg '(16)) (current-time)
  11971. ;; Preserve `this-command' and `last-command'.
  11972. (let ((this-command this-command)
  11973. (last-command last-command))
  11974. (org-read-date
  11975. arg 'totime nil nil default-time default-input
  11976. inactive)))))
  11977. (cond
  11978. ((and ts
  11979. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  11980. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  11981. (insert "--")
  11982. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  11983. (ts
  11984. ;; Make sure we're on a timestamp. When in the middle of a date
  11985. ;; range, move arbitrarily to range end.
  11986. (unless (org-at-timestamp-p 'lax)
  11987. (skip-chars-forward "-")
  11988. (org-at-timestamp-p 'lax))
  11989. (replace-match "")
  11990. (setq org-last-changed-timestamp
  11991. (org-insert-time-stamp
  11992. time (or org-time-was-given arg)
  11993. inactive nil nil (list org-end-time-was-given)))
  11994. (when repeater
  11995. (backward-char)
  11996. (insert " " repeater)
  11997. (setq org-last-changed-timestamp
  11998. (concat (substring org-last-inserted-timestamp 0 -1)
  11999. " " repeater ">")))
  12000. (message "Timestamp updated"))
  12001. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12002. (t (org-insert-time-stamp
  12003. time (or org-time-was-given arg) inactive nil nil
  12004. (list org-end-time-was-given))))))
  12005. ;; FIXME: can we use this for something else, like computing time differences?
  12006. (defun org-get-compact-tod (s)
  12007. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12008. (let* ((t1 (match-string 1 s))
  12009. (h1 (string-to-number (match-string 2 s)))
  12010. (m1 (string-to-number (match-string 3 s)))
  12011. (t2 (and (match-end 4) (match-string 5 s)))
  12012. (h2 (and t2 (string-to-number (match-string 6 s))))
  12013. (m2 (and t2 (string-to-number (match-string 7 s))))
  12014. dh dm)
  12015. (if (not t2)
  12016. t1
  12017. (setq dh (- h2 h1) dm (- m2 m1))
  12018. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12019. (concat t1 "+" (number-to-string dh)
  12020. (and (/= 0 dm) (format ":%02d" dm)))))))
  12021. (defun org-time-stamp-inactive (&optional arg)
  12022. "Insert an inactive time stamp.
  12023. An inactive time stamp is enclosed in square brackets instead of
  12024. angle brackets. It is inactive in the sense that it does not
  12025. trigger agenda entries. So these are more for recording a
  12026. certain time/date.
  12027. If the user specifies a time like HH:MM or if this command is called with
  12028. at least one prefix argument, the time stamp contains the date and the time.
  12029. Otherwise, only the date is included.
  12030. When called with two universal prefix arguments, insert an inactive time stamp
  12031. with the current time without prompting the user."
  12032. (interactive "P")
  12033. (org-time-stamp arg 'inactive))
  12034. (defvar org-date-ovl (make-overlay 1 1))
  12035. (overlay-put org-date-ovl 'face 'org-date-selected)
  12036. (delete-overlay org-date-ovl)
  12037. (defvar org-ans1) ; dynamically scoped parameter
  12038. (defvar org-ans2) ; dynamically scoped parameter
  12039. (defvar org-plain-time-of-day-regexp) ; defined below
  12040. (defvar org-overriding-default-time nil) ; dynamically scoped
  12041. (defvar org-read-date-overlay nil)
  12042. (defvar org-read-date-history nil)
  12043. (defvar org-read-date-final-answer nil)
  12044. (defvar org-read-date-analyze-futurep nil)
  12045. (defvar org-read-date-analyze-forced-year nil)
  12046. (defvar org-read-date-inactive)
  12047. (defvar org-def)
  12048. (defvar org-defdecode)
  12049. (defvar org-with-time)
  12050. (defvar calendar-setup) ; Dynamically scoped.
  12051. (defun org-read-date (&optional with-time to-time from-string prompt
  12052. default-time default-input inactive)
  12053. "Read a date, possibly a time, and make things smooth for the user.
  12054. The prompt will suggest to enter an ISO date, but you can also enter anything
  12055. which will at least partially be understood by `parse-time-string'.
  12056. Unrecognized parts of the date will default to the current day, month, year,
  12057. hour and minute. If this command is called to replace a timestamp at point,
  12058. or to enter the second timestamp of a range, the default time is taken
  12059. from the existing stamp. Furthermore, the command prefers the future,
  12060. so if you are giving a date where the year is not given, and the day-month
  12061. combination is already past in the current year, it will assume you
  12062. mean next year. For details, see the manual. A few examples:
  12063. 3-2-5 --> 2003-02-05
  12064. feb 15 --> currentyear-02-15
  12065. 2/15 --> currentyear-02-15
  12066. sep 12 9 --> 2009-09-12
  12067. 12:45 --> today 12:45
  12068. 22 sept 0:34 --> currentyear-09-22 0:34
  12069. 12 --> currentyear-currentmonth-12
  12070. Fri --> nearest Friday after today
  12071. -Tue --> last Tuesday
  12072. etc.
  12073. Furthermore you can specify a relative date by giving, as the *first* thing
  12074. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12075. change in days weeks, months, years.
  12076. With a single plus or minus, the date is relative to today. With a double
  12077. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12078. +4d --> four days from today
  12079. +4 --> same as above
  12080. +2w --> two weeks from today
  12081. ++5 --> five days from default date
  12082. The function understands only English month and weekday abbreviations.
  12083. While prompting, a calendar is popped up - you can also select the
  12084. date with the mouse (button 1). The calendar shows a period of three
  12085. months. To scroll it to other months, use the keys `>' and `<'.
  12086. If you don't like the calendar, turn it off with
  12087. (setq org-read-date-popup-calendar nil)
  12088. With optional argument TO-TIME, the date will immediately be converted
  12089. to an internal time.
  12090. With an optional argument WITH-TIME, the prompt will suggest to
  12091. also insert a time. Note that when WITH-TIME is not set, you can
  12092. still enter a time, and this function will inform the calling routine
  12093. about this change. The calling routine may then choose to change the
  12094. format used to insert the time stamp into the buffer to include the time.
  12095. With optional argument FROM-STRING, read from this string instead from
  12096. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12097. the time/date that is used for everything that is not specified by the
  12098. user."
  12099. (require 'parse-time)
  12100. (let* ((org-with-time with-time)
  12101. (org-time-stamp-rounding-minutes
  12102. (if (equal org-with-time '(16))
  12103. '(0 0)
  12104. org-time-stamp-rounding-minutes))
  12105. (ct (org-current-time))
  12106. (org-def (or org-overriding-default-time default-time ct))
  12107. (org-defdecode (decode-time org-def))
  12108. (cur-frame (selected-frame))
  12109. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12110. (calendar-setup
  12111. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12112. (calendar-move-hook nil)
  12113. (calendar-view-diary-initially-flag nil)
  12114. (calendar-view-holidays-initially-flag nil)
  12115. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12116. ;; Rationalize `org-def' and `org-defdecode', if required.
  12117. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12118. (setf (nth 2 org-defdecode) -1)
  12119. (setf (nth 1 org-defdecode) 59)
  12120. (setq org-def (apply #'encode-time org-defdecode))
  12121. (setq org-defdecode (decode-time org-def)))
  12122. (let* ((timestr (format-time-string
  12123. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12124. org-def))
  12125. (prompt (concat (if prompt (concat prompt " ") "")
  12126. (format "Date+time [%s]: " timestr))))
  12127. (cond
  12128. (from-string (setq ans from-string))
  12129. (org-read-date-popup-calendar
  12130. (save-excursion
  12131. (save-window-excursion
  12132. (calendar)
  12133. (when (eq calendar-setup 'calendar-only)
  12134. (setq cal-frame
  12135. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12136. (select-frame cal-frame))
  12137. (org-eval-in-calendar '(setq cursor-type nil) t)
  12138. (unwind-protect
  12139. (progn
  12140. (calendar-forward-day (- (time-to-days org-def)
  12141. (calendar-absolute-from-gregorian
  12142. (calendar-current-date))))
  12143. (org-eval-in-calendar nil t)
  12144. (let* ((old-map (current-local-map))
  12145. (map (copy-keymap calendar-mode-map))
  12146. (minibuffer-local-map
  12147. (copy-keymap org-read-date-minibuffer-local-map)))
  12148. (org-defkey map (kbd "RET") 'org-calendar-select)
  12149. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12150. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12151. (unwind-protect
  12152. (progn
  12153. (use-local-map map)
  12154. (setq org-read-date-inactive inactive)
  12155. (add-hook 'post-command-hook 'org-read-date-display)
  12156. (setq org-ans0
  12157. (read-string prompt
  12158. default-input
  12159. 'org-read-date-history
  12160. nil))
  12161. ;; org-ans0: from prompt
  12162. ;; org-ans1: from mouse click
  12163. ;; org-ans2: from calendar motion
  12164. (setq ans
  12165. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12166. (remove-hook 'post-command-hook 'org-read-date-display)
  12167. (use-local-map old-map)
  12168. (when org-read-date-overlay
  12169. (delete-overlay org-read-date-overlay)
  12170. (setq org-read-date-overlay nil)))))
  12171. (bury-buffer "*Calendar*")
  12172. (when cal-frame
  12173. (delete-frame cal-frame)
  12174. (select-frame-set-input-focus cur-frame))))))
  12175. (t ; Naked prompt only
  12176. (unwind-protect
  12177. (setq ans (read-string prompt default-input
  12178. 'org-read-date-history timestr))
  12179. (when org-read-date-overlay
  12180. (delete-overlay org-read-date-overlay)
  12181. (setq org-read-date-overlay nil))))))
  12182. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12183. (when org-read-date-analyze-forced-year
  12184. (message "Year was forced into %s"
  12185. (if org-read-date-force-compatible-dates
  12186. "compatible range (1970-2037)"
  12187. "range representable on this machine"))
  12188. (ding))
  12189. (setq final (apply #'encode-time final))
  12190. (setq org-read-date-final-answer ans)
  12191. (if to-time
  12192. final
  12193. ;; This round-trip gets rid of 34th of August and stuff like that....
  12194. (setq final (decode-time final))
  12195. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12196. (format "%04d-%02d-%02d %02d:%02d"
  12197. (nth 5 final) (nth 4 final) (nth 3 final)
  12198. (nth 2 final) (nth 1 final))
  12199. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12200. (defun org-read-date-display ()
  12201. "Display the current date prompt interpretation in the minibuffer."
  12202. (when org-read-date-display-live
  12203. (when org-read-date-overlay
  12204. (delete-overlay org-read-date-overlay))
  12205. (when (minibufferp (current-buffer))
  12206. (save-excursion
  12207. (end-of-line 1)
  12208. (while (not (equal (buffer-substring
  12209. (max (point-min) (- (point) 4)) (point))
  12210. " "))
  12211. (insert " ")))
  12212. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12213. " " (or org-ans1 org-ans2)))
  12214. (org-end-time-was-given nil)
  12215. (f (org-read-date-analyze ans org-def org-defdecode))
  12216. (fmts (if org-display-custom-times
  12217. org-time-stamp-custom-formats
  12218. org-time-stamp-formats))
  12219. (fmt (if (or org-with-time
  12220. (and (boundp 'org-time-was-given) org-time-was-given))
  12221. (cdr fmts)
  12222. (car fmts)))
  12223. (txt (format-time-string fmt (apply #'encode-time f)))
  12224. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12225. (txt (concat "=> " txt)))
  12226. (when (and org-end-time-was-given
  12227. (string-match org-plain-time-of-day-regexp txt))
  12228. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12229. org-end-time-was-given
  12230. (substring txt (match-end 0)))))
  12231. (when org-read-date-analyze-futurep
  12232. (setq txt (concat txt " (=>F)")))
  12233. (setq org-read-date-overlay
  12234. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12235. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12236. (defun org-read-date-analyze (ans def defdecode)
  12237. "Analyze the combined answer of the date prompt."
  12238. ;; FIXME: cleanup and comment
  12239. (let ((org-def def)
  12240. (org-defdecode defdecode)
  12241. (nowdecode (decode-time))
  12242. delta deltan deltaw deltadef year month day
  12243. hour minute second wday pm h2 m2 tl wday1
  12244. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12245. (setq org-read-date-analyze-futurep nil
  12246. org-read-date-analyze-forced-year nil)
  12247. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12248. (setq ans "+0"))
  12249. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12250. (setq ans (replace-match "" t t ans)
  12251. deltan (car delta)
  12252. deltaw (nth 1 delta)
  12253. deltadef (nth 2 delta)))
  12254. ;; Check if there is an iso week date in there. If yes, store the
  12255. ;; info and postpone interpreting it until the rest of the parsing
  12256. ;; is done.
  12257. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12258. (setq iso-year (when (match-end 1)
  12259. (org-small-year-to-year
  12260. (string-to-number (match-string 1 ans))))
  12261. iso-weekday (when (match-end 3)
  12262. (string-to-number (match-string 3 ans)))
  12263. iso-week (string-to-number (match-string 2 ans)))
  12264. (setq ans (replace-match "" t t ans)))
  12265. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12266. (when (string-match
  12267. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12268. (setq year (if (match-end 2)
  12269. (string-to-number (match-string 2 ans))
  12270. (progn (setq kill-year t)
  12271. (string-to-number (format-time-string "%Y"))))
  12272. month (string-to-number (match-string 3 ans))
  12273. day (string-to-number (match-string 4 ans)))
  12274. (setq year (org-small-year-to-year year))
  12275. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12276. t nil ans)))
  12277. ;; Help matching dotted european dates
  12278. (when (string-match
  12279. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12280. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12281. (setq kill-year t)
  12282. (string-to-number (format-time-string "%Y")))
  12283. day (string-to-number (match-string 1 ans))
  12284. month (string-to-number (match-string 2 ans))
  12285. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12286. t nil ans)))
  12287. ;; Help matching american dates, like 5/30 or 5/30/7
  12288. (when (string-match
  12289. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12290. (setq year (if (match-end 4)
  12291. (string-to-number (match-string 4 ans))
  12292. (progn (setq kill-year t)
  12293. (string-to-number (format-time-string "%Y"))))
  12294. month (string-to-number (match-string 1 ans))
  12295. day (string-to-number (match-string 2 ans)))
  12296. (setq year (org-small-year-to-year year))
  12297. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12298. t nil ans)))
  12299. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12300. ;; If there is a time with am/pm, and *no* time without it, we convert
  12301. ;; so that matching will be successful.
  12302. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12303. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12304. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12305. (setq hour (string-to-number (match-string 1 ans))
  12306. minute (if (match-end 3)
  12307. (string-to-number (match-string 3 ans))
  12308. 0)
  12309. pm (equal ?p
  12310. (string-to-char (downcase (match-string 4 ans)))))
  12311. (if (and (= hour 12) (not pm))
  12312. (setq hour 0)
  12313. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12314. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12315. t t ans))))
  12316. ;; Help matching HHhMM times, similarly as for am/pm times.
  12317. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12318. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12319. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12320. (setq hour (if (match-end 1)
  12321. (string-to-number (match-string 1 ans))
  12322. 0)
  12323. minute (if (match-end 2)
  12324. (string-to-number (match-string 2 ans))
  12325. 0))
  12326. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12327. t t ans))))
  12328. ;; Check if a time range is given as a duration
  12329. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12330. (setq hour (string-to-number (match-string 1 ans))
  12331. h2 (+ hour (string-to-number (match-string 3 ans)))
  12332. minute (string-to-number (match-string 2 ans))
  12333. m2 (+ minute (if (match-end 5) (string-to-number
  12334. (match-string 5 ans))0)))
  12335. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12336. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12337. t t ans)))
  12338. ;; Check if there is a time range
  12339. (when (boundp 'org-end-time-was-given)
  12340. (setq org-time-was-given nil)
  12341. (when (and (string-match org-plain-time-of-day-regexp ans)
  12342. (match-end 8))
  12343. (setq org-end-time-was-given (match-string 8 ans))
  12344. (setq ans (concat (substring ans 0 (match-beginning 7))
  12345. (substring ans (match-end 7))))))
  12346. (setq tl (parse-time-string ans)
  12347. day (or (nth 3 tl) (nth 3 org-defdecode))
  12348. month
  12349. (cond ((nth 4 tl))
  12350. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12351. ;; Day was specified. Make sure DAY+MONTH
  12352. ;; combination happens in the future.
  12353. ((nth 3 tl)
  12354. (setq futurep t)
  12355. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12356. (nth 4 nowdecode)))
  12357. (t (nth 4 org-defdecode)))
  12358. year
  12359. (cond ((and (not kill-year) (nth 5 tl)))
  12360. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12361. ;; Month was guessed in the future and is at least
  12362. ;; equal to NOWDECODE's. Fix year accordingly.
  12363. (futurep
  12364. (if (or (> month (nth 4 nowdecode))
  12365. (>= day (nth 3 nowdecode)))
  12366. (nth 5 nowdecode)
  12367. (1+ (nth 5 nowdecode))))
  12368. ;; Month was specified. Make sure MONTH+YEAR
  12369. ;; combination happens in the future.
  12370. ((nth 4 tl)
  12371. (setq futurep t)
  12372. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12373. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12374. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12375. (t (nth 5 nowdecode))))
  12376. (t (nth 5 org-defdecode)))
  12377. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12378. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12379. second (or (nth 0 tl) 0)
  12380. wday (nth 6 tl))
  12381. (when (and (eq org-read-date-prefer-future 'time)
  12382. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12383. (equal day (nth 3 nowdecode))
  12384. (equal month (nth 4 nowdecode))
  12385. (equal year (nth 5 nowdecode))
  12386. (nth 2 tl)
  12387. (or (< (nth 2 tl) (nth 2 nowdecode))
  12388. (and (= (nth 2 tl) (nth 2 nowdecode))
  12389. (nth 1 tl)
  12390. (< (nth 1 tl) (nth 1 nowdecode)))))
  12391. (setq day (1+ day)
  12392. futurep t))
  12393. ;; Special date definitions below
  12394. (cond
  12395. (iso-week
  12396. ;; There was an iso week
  12397. (require 'cal-iso)
  12398. (setq futurep nil)
  12399. (setq year (or iso-year year)
  12400. day (or iso-weekday wday 1)
  12401. wday nil ; to make sure that the trigger below does not match
  12402. iso-date (calendar-gregorian-from-absolute
  12403. (calendar-iso-to-absolute
  12404. (list iso-week day year))))
  12405. ; FIXME: Should we also push ISO weeks into the future?
  12406. ; (when (and org-read-date-prefer-future
  12407. ; (not iso-year)
  12408. ; (< (calendar-absolute-from-gregorian iso-date)
  12409. ; (time-to-days nil)))
  12410. ; (setq year (1+ year)
  12411. ; iso-date (calendar-gregorian-from-absolute
  12412. ; (calendar-iso-to-absolute
  12413. ; (list iso-week day year)))))
  12414. (setq month (car iso-date)
  12415. year (nth 2 iso-date)
  12416. day (nth 1 iso-date)))
  12417. (deltan
  12418. (setq futurep nil)
  12419. (unless deltadef
  12420. (let ((now (decode-time)))
  12421. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12422. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12423. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12424. ((equal deltaw "m") (setq month (+ month deltan)))
  12425. ((equal deltaw "y") (setq year (+ year deltan)))))
  12426. ((and wday (not (nth 3 tl)))
  12427. ;; Weekday was given, but no day, so pick that day in the week
  12428. ;; on or after the derived date.
  12429. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12430. (unless (equal wday wday1)
  12431. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12432. (when (and (boundp 'org-time-was-given)
  12433. (nth 2 tl))
  12434. (setq org-time-was-given t))
  12435. (when (< year 100) (setq year (+ 2000 year)))
  12436. ;; Check of the date is representable
  12437. (if org-read-date-force-compatible-dates
  12438. (progn
  12439. (when (< year 1970)
  12440. (setq year 1970 org-read-date-analyze-forced-year t))
  12441. (when (> year 2037)
  12442. (setq year 2037 org-read-date-analyze-forced-year t)))
  12443. (condition-case nil
  12444. (ignore (encode-time second minute hour day month year))
  12445. (error
  12446. (setq year (nth 5 org-defdecode))
  12447. (setq org-read-date-analyze-forced-year t))))
  12448. (setq org-read-date-analyze-futurep futurep)
  12449. (list second minute hour day month year)))
  12450. (defvar parse-time-weekdays)
  12451. (defun org-read-date-get-relative (s today default)
  12452. "Check string S for special relative date string.
  12453. TODAY and DEFAULT are internal times, for today and for a default.
  12454. Return shift list (N what def-flag)
  12455. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12456. N is the number of WHATs to shift.
  12457. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12458. the DEFAULT date rather than TODAY."
  12459. (require 'parse-time)
  12460. (when (and
  12461. (string-match
  12462. (concat
  12463. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12464. "\\([0-9]+\\)?"
  12465. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12466. "\\([ \t]\\|$\\)") s)
  12467. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12468. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12469. (string-to-char (substring (match-string 1 s) -1))
  12470. ?+))
  12471. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12472. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12473. (what (if (match-end 3) (match-string 3 s) "d"))
  12474. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12475. (date (if rel default today))
  12476. (wday (nth 6 (decode-time date)))
  12477. delta)
  12478. (if wday1
  12479. (progn
  12480. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12481. (when (= delta 0) (setq delta 7))
  12482. (when (= dir ?-)
  12483. (setq delta (- delta 7))
  12484. (when (= delta 0) (setq delta -7)))
  12485. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12486. (list delta "d" rel))
  12487. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12488. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12489. "Turn a user-specified date into the internal representation.
  12490. The internal representation needed by the calendar is (month day year).
  12491. This is a wrapper to handle the brain-dead convention in calendar that
  12492. user function argument order change dependent on argument order."
  12493. (pcase calendar-date-style
  12494. (`american (list arg1 arg2 arg3))
  12495. (`european (list arg2 arg1 arg3))
  12496. (`iso (list arg2 arg3 arg1))))
  12497. (defun org-eval-in-calendar (form &optional keepdate)
  12498. "Eval FORM in the calendar window and return to current window.
  12499. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12500. (let ((sf (selected-frame))
  12501. (sw (selected-window)))
  12502. (select-window (get-buffer-window "*Calendar*" t))
  12503. (eval form t)
  12504. (when (and (not keepdate) (calendar-cursor-to-date))
  12505. (let* ((date (calendar-cursor-to-date))
  12506. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12507. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12508. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12509. (select-window sw)
  12510. (select-frame-set-input-focus sf)))
  12511. (defun org-calendar-select ()
  12512. "Return to `org-read-date' with the date currently selected.
  12513. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12514. (interactive)
  12515. (when (calendar-cursor-to-date)
  12516. (let* ((date (calendar-cursor-to-date))
  12517. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12518. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12519. (when (active-minibuffer-window) (exit-minibuffer))))
  12520. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12521. "Insert a date stamp for the date given by the internal TIME.
  12522. See `format-time-string' for the format of TIME.
  12523. WITH-HM means use the stamp format that includes the time of the day.
  12524. INACTIVE means use square brackets instead of angular ones, so that the
  12525. stamp will not contribute to the agenda.
  12526. PRE and POST are optional strings to be inserted before and after the
  12527. stamp.
  12528. The command returns the inserted time stamp."
  12529. (org-fold-core-ignore-modifications
  12530. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12531. stamp)
  12532. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12533. (insert-before-markers-and-inherit (or pre ""))
  12534. (when (listp extra)
  12535. (setq extra (car extra))
  12536. (if (and (stringp extra)
  12537. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12538. (setq extra (format "-%02d:%02d"
  12539. (string-to-number (match-string 1 extra))
  12540. (string-to-number (match-string 2 extra))))
  12541. (setq extra nil)))
  12542. (when extra
  12543. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12544. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12545. (insert-before-markers-and-inherit (or post ""))
  12546. (setq org-last-inserted-timestamp stamp))))
  12547. (defun org-toggle-time-stamp-overlays ()
  12548. "Toggle the use of custom time stamp formats."
  12549. (interactive)
  12550. (setq org-display-custom-times (not org-display-custom-times))
  12551. (unless org-display-custom-times
  12552. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12553. (while (setq p (next-single-property-change p 'display))
  12554. (when (and (get-text-property p 'display)
  12555. (eq (get-text-property p 'face) 'org-date))
  12556. (remove-text-properties
  12557. p (setq p (next-single-property-change p 'display))
  12558. '(display t))))
  12559. (set-buffer-modified-p bmp)))
  12560. (org-restart-font-lock)
  12561. (setq org-table-may-need-update t)
  12562. (if org-display-custom-times
  12563. (message "Time stamps are overlaid with custom format")
  12564. (message "Time stamp overlays removed")))
  12565. (defun org-display-custom-time (beg end)
  12566. "Overlay modified time stamp format over timestamp between BEG and END."
  12567. (let* ((ts (buffer-substring beg end))
  12568. t1 with-hm tf time str (off 0))
  12569. (save-match-data
  12570. (setq t1 (org-parse-time-string ts t))
  12571. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12572. (setq off (- (match-end 0) (match-beginning 0)))))
  12573. (setq end (- end off))
  12574. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12575. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12576. time (org-fix-decoded-time t1)
  12577. str (org-add-props
  12578. (format-time-string
  12579. (substring tf 1 -1) (apply 'encode-time time))
  12580. nil 'mouse-face 'highlight))
  12581. (put-text-property beg end 'display str)))
  12582. (defun org-fix-decoded-time (time)
  12583. "Set 0 instead of nil for the first 6 elements of time.
  12584. Don't touch the rest."
  12585. (let ((n 0))
  12586. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12587. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12588. "Difference between TIMESTAMP-STRING and now in days.
  12589. If SECONDS is non-nil, return the difference in seconds."
  12590. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12591. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12592. (funcall fdiff nil))))
  12593. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12594. "Is the time in TIMESTAMP-STRING close to the current date?"
  12595. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12596. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12597. (not (org-entry-is-done-p))))
  12598. (defun org-get-wdays (ts &optional delay zero-delay)
  12599. "Get the deadline lead time appropriate for timestring TS.
  12600. When DELAY is non-nil, get the delay time for scheduled items
  12601. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12602. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12603. don't try to find the delay cookie in the scheduled timestamp."
  12604. (let ((tv (if delay org-scheduled-delay-days
  12605. org-deadline-warning-days)))
  12606. (cond
  12607. ((or (and delay (< tv 0))
  12608. (and delay zero-delay (<= tv 0))
  12609. (and (not delay) (<= tv 0)))
  12610. ;; Enforce this value no matter what
  12611. (- tv))
  12612. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12613. ;; lead time is specified.
  12614. (floor (* (string-to-number (match-string 1 ts))
  12615. (cdr (assoc (match-string 2 ts)
  12616. '(("d" . 1) ("w" . 7)
  12617. ("m" . 30.4) ("y" . 365.25)
  12618. ("h" . 0.041667)))))))
  12619. ;; go for the default.
  12620. (t tv))))
  12621. (defun org-calendar-select-mouse (ev)
  12622. "Return to `org-read-date' with the date currently selected.
  12623. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12624. (interactive "e")
  12625. (mouse-set-point ev)
  12626. (when (calendar-cursor-to-date)
  12627. (let* ((date (calendar-cursor-to-date))
  12628. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12629. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12630. (when (active-minibuffer-window) (exit-minibuffer))))
  12631. (defun org-check-deadlines (ndays)
  12632. "Check if there are any deadlines due or past due.
  12633. A deadline is considered due if it happens within `org-deadline-warning-days'
  12634. days from today's date. If the deadline appears in an entry marked DONE,
  12635. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12636. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12637. are shown."
  12638. (interactive "P")
  12639. (let* ((org-warn-days
  12640. (cond
  12641. ((equal ndays '(4)) 100000)
  12642. (ndays (prefix-numeric-value ndays))
  12643. (t (abs org-deadline-warning-days))))
  12644. (case-fold-search nil)
  12645. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12646. (callback
  12647. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12648. (message "%d deadlines past-due or due within %d days"
  12649. (org-occur regexp nil callback)
  12650. org-warn-days)))
  12651. (defsubst org-re-timestamp (type)
  12652. "Return a regexp for timestamp TYPE.
  12653. Allowed values for TYPE are:
  12654. all: all timestamps
  12655. active: only active timestamps (<...>)
  12656. inactive: only inactive timestamps ([...])
  12657. scheduled: only scheduled timestamps
  12658. deadline: only deadline timestamps
  12659. closed: only closed time-stamps
  12660. When TYPE is nil, fall back on returning a regexp that matches
  12661. both scheduled and deadline timestamps."
  12662. (cl-case type
  12663. (all org-ts-regexp-both)
  12664. (active org-ts-regexp)
  12665. (inactive org-ts-regexp-inactive)
  12666. (scheduled org-scheduled-time-regexp)
  12667. (deadline org-deadline-time-regexp)
  12668. (closed org-closed-time-regexp)
  12669. (otherwise
  12670. (concat "\\<"
  12671. (regexp-opt (list org-deadline-string org-scheduled-string))
  12672. " *<\\([^>]+\\)>"))))
  12673. (defun org-check-before-date (d)
  12674. "Check if there are deadlines or scheduled entries before date D."
  12675. (interactive (list (org-read-date)))
  12676. (let* ((case-fold-search nil)
  12677. (regexp (org-re-timestamp org-ts-type))
  12678. (ts-type org-ts-type)
  12679. (callback
  12680. (lambda ()
  12681. (let ((match (match-string 1)))
  12682. (and (if (memq ts-type '(active inactive all))
  12683. (eq (org-element-type (save-excursion
  12684. (backward-char)
  12685. (org-element-context)))
  12686. 'timestamp)
  12687. (org-at-planning-p))
  12688. (time-less-p
  12689. (org-time-string-to-time match)
  12690. (org-time-string-to-time d)))))))
  12691. (message "%d entries before %s"
  12692. (org-occur regexp nil callback)
  12693. d)))
  12694. (defun org-check-after-date (d)
  12695. "Check if there are deadlines or scheduled entries after date D."
  12696. (interactive (list (org-read-date)))
  12697. (let* ((case-fold-search nil)
  12698. (regexp (org-re-timestamp org-ts-type))
  12699. (ts-type org-ts-type)
  12700. (callback
  12701. (lambda ()
  12702. (let ((match (match-string 1)))
  12703. (and (if (memq ts-type '(active inactive all))
  12704. (eq (org-element-type (save-excursion
  12705. (backward-char)
  12706. (org-element-context)))
  12707. 'timestamp)
  12708. (org-at-planning-p))
  12709. (not (time-less-p
  12710. (org-time-string-to-time match)
  12711. (org-time-string-to-time d))))))))
  12712. (message "%d entries after %s"
  12713. (org-occur regexp nil callback)
  12714. d)))
  12715. (defun org-check-dates-range (start-date end-date)
  12716. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12717. (interactive (list (org-read-date nil nil nil "Range starts")
  12718. (org-read-date nil nil nil "Range end")))
  12719. (let ((case-fold-search nil)
  12720. (regexp (org-re-timestamp org-ts-type))
  12721. (callback
  12722. (let ((type org-ts-type))
  12723. (lambda ()
  12724. (let ((match (match-string 1)))
  12725. (and
  12726. (if (memq type '(active inactive all))
  12727. (eq (org-element-type (save-excursion
  12728. (backward-char)
  12729. (org-element-context)))
  12730. 'timestamp)
  12731. (org-at-planning-p))
  12732. (not (time-less-p
  12733. (org-time-string-to-time match)
  12734. (org-time-string-to-time start-date)))
  12735. (time-less-p
  12736. (org-time-string-to-time match)
  12737. (org-time-string-to-time end-date))))))))
  12738. (message "%d entries between %s and %s"
  12739. (org-occur regexp nil callback) start-date end-date)))
  12740. (defun org-evaluate-time-range (&optional to-buffer)
  12741. "Evaluate a time range by computing the difference between start and end.
  12742. Normally the result is just printed in the echo area, but with prefix arg
  12743. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  12744. If the time range is actually in a table, the result is inserted into the
  12745. next column.
  12746. For time difference computation, a year is assumed to be exactly 365
  12747. days in order to avoid rounding problems."
  12748. (interactive "P")
  12749. (or
  12750. (org-clock-update-time-maybe)
  12751. (save-excursion
  12752. (unless (org-at-date-range-p t)
  12753. (goto-char (point-at-bol))
  12754. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  12755. (unless (org-at-date-range-p t)
  12756. (user-error "Not at a time-stamp range, and none found in current line")))
  12757. (let* ((ts1 (match-string 1))
  12758. (ts2 (match-string 2))
  12759. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  12760. (match-end (match-end 0))
  12761. (time1 (org-time-string-to-time ts1))
  12762. (time2 (org-time-string-to-time ts2))
  12763. (diff (abs (float-time (time-subtract time2 time1))))
  12764. (negative (time-less-p time2 time1))
  12765. ;; (ys (floor (* 365 24 60 60)))
  12766. (ds (* 24 60 60))
  12767. (hs (* 60 60))
  12768. (fy "%dy %dd %02d:%02d")
  12769. (fy1 "%dy %dd")
  12770. (fd "%dd %02d:%02d")
  12771. (fd1 "%dd")
  12772. (fh "%02d:%02d")
  12773. y d h m align)
  12774. (if havetime
  12775. (setq ; y (floor diff ys) diff (mod diff ys)
  12776. y 0
  12777. d (floor diff ds) diff (mod diff ds)
  12778. h (floor diff hs) diff (mod diff hs)
  12779. m (floor diff 60))
  12780. (setq ; y (floor diff ys) diff (mod diff ys)
  12781. y 0
  12782. d (round diff ds)
  12783. h 0 m 0))
  12784. (if (not to-buffer)
  12785. (message "%s" (org-make-tdiff-string y d h m))
  12786. (if (org-at-table-p)
  12787. (progn
  12788. (goto-char match-end)
  12789. (setq align t)
  12790. (and (looking-at " *|") (goto-char (match-end 0))))
  12791. (goto-char match-end))
  12792. (when (looking-at
  12793. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  12794. (replace-match ""))
  12795. (when negative (insert " -"))
  12796. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  12797. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  12798. (insert " " (format fh h m))))
  12799. (when align (org-table-align))
  12800. (message "Time difference inserted")))))
  12801. (defun org-make-tdiff-string (y d h m)
  12802. (let ((fmt "")
  12803. (l nil))
  12804. (when (> y 0)
  12805. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  12806. (push y l))
  12807. (when (> d 0)
  12808. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  12809. (push d l))
  12810. (when (> h 0)
  12811. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  12812. (push h l))
  12813. (when (> m 0)
  12814. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  12815. (push m l))
  12816. (apply 'format fmt (nreverse l))))
  12817. (defun org-time-string-to-time (s)
  12818. "Convert timestamp string S into internal time."
  12819. (apply #'encode-time (org-parse-time-string s)))
  12820. (defun org-time-string-to-seconds (s)
  12821. "Convert a timestamp string S into a number of seconds."
  12822. (float-time (org-time-string-to-time s)))
  12823. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  12824. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  12825. "Convert time stamp S to an absolute day number.
  12826. If DAYNR in non-nil, and there is a specifier for a cyclic time
  12827. stamp, get the closest date to DAYNR. If PREFER is
  12828. `past' (respectively `future') return a date past (respectively
  12829. after) or equal to DAYNR.
  12830. POS is the location of time stamp S, as a buffer position in
  12831. BUFFER.
  12832. Diary sexp timestamps are matched against DAYNR, when non-nil.
  12833. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  12834. signaled."
  12835. (cond
  12836. ((string-match "\\`%%\\((.*)\\)" s)
  12837. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  12838. ;; only able to match individual dates. If it fails, raise an
  12839. ;; error.
  12840. (if (and daynr
  12841. (org-diary-sexp-entry
  12842. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  12843. daynr
  12844. (signal 'org-diary-sexp-no-match (list s))))
  12845. (daynr (org-closest-date s daynr prefer))
  12846. (t (time-to-days
  12847. (condition-case errdata
  12848. (org-time-string-to-time s)
  12849. (error (error "Bad timestamp `%s'%s\nError was: %s"
  12850. s
  12851. (if (not (and buffer pos)) ""
  12852. (format-message " at %d in buffer `%s'" pos buffer))
  12853. (cdr errdata))))))))
  12854. (defun org-days-to-iso-week (days)
  12855. "Return the ISO week number."
  12856. (require 'cal-iso)
  12857. (car (calendar-iso-from-absolute days)))
  12858. (defun org-small-year-to-year (year)
  12859. "Convert 2-digit years into 4-digit years.
  12860. YEAR is expanded into one of the 30 next years, if possible, or
  12861. into a past one. Any year larger than 99 is returned unchanged."
  12862. (if (>= year 100) year
  12863. (let* ((current (string-to-number (format-time-string "%Y")))
  12864. (century (/ current 100))
  12865. (offset (- year (% current 100))))
  12866. (cond ((> offset 30) (+ (* (1- century) 100) year))
  12867. ((> offset -70) (+ (* century 100) year))
  12868. (t (+ (* (1+ century) 100) year))))))
  12869. (defun org-time-from-absolute (d)
  12870. "Return the time corresponding to date D.
  12871. D may be an absolute day number, or a calendar-type list (month day year)."
  12872. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  12873. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  12874. (defvar org-agenda-current-date)
  12875. (defun org-calendar-holiday ()
  12876. "List of holidays, for Diary display in Org mode."
  12877. (require 'holidays)
  12878. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  12879. (and hl (mapconcat #'identity hl "; "))))
  12880. (defun org-diary-sexp-entry (sexp entry d)
  12881. "Process a SEXP diary ENTRY for date D."
  12882. (require 'diary-lib)
  12883. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  12884. ;; dynamically.
  12885. (let* ((sexp `(let ((entry ,entry)
  12886. (date ',d))
  12887. ,(car (read-from-string sexp))))
  12888. ;; FIXME: Do not use (eval ... t) in the following sexp as
  12889. ;; diary vars are still using dynamic scope.
  12890. (result (if calendar-debug-sexp (eval sexp)
  12891. (condition-case nil
  12892. (eval sexp)
  12893. (error
  12894. (beep)
  12895. (message "Bad sexp at line %d in %s: %s"
  12896. (org-current-line)
  12897. (buffer-file-name) sexp)
  12898. (sleep-for 2))))))
  12899. (cond ((stringp result) (split-string result "; "))
  12900. ((and (consp result)
  12901. (not (consp (cdr result)))
  12902. (stringp (cdr result))) (cdr result))
  12903. ((and (consp result)
  12904. (stringp (car result))) result)
  12905. (result entry))))
  12906. (defun org-diary-to-ical-string (frombuf)
  12907. "Get iCalendar entries from diary entries in buffer FROMBUF.
  12908. This uses the icalendar.el library."
  12909. (let* ((tmpdir temporary-file-directory)
  12910. (tmpfile (make-temp-name
  12911. (expand-file-name "orgics" tmpdir)))
  12912. buf rtn b e)
  12913. (with-current-buffer frombuf
  12914. (icalendar-export-region (point-min) (point-max) tmpfile)
  12915. (setq buf (find-buffer-visiting tmpfile))
  12916. (set-buffer buf)
  12917. (goto-char (point-min))
  12918. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  12919. (setq b (match-beginning 0)))
  12920. (goto-char (point-max))
  12921. (when (re-search-backward "^END:VEVENT" nil t)
  12922. (setq e (match-end 0)))
  12923. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  12924. (kill-buffer buf)
  12925. (delete-file tmpfile)
  12926. rtn))
  12927. (defun org-closest-date (start current prefer)
  12928. "Return closest date to CURRENT starting from START.
  12929. CURRENT and START are both time stamps.
  12930. When PREFER is `past', return a date that is either CURRENT or
  12931. past. When PREFER is `future', return a date that is either
  12932. CURRENT or future.
  12933. Only time stamps with a repeater are modified. Any other time
  12934. stamp stay unchanged. In any case, return value is an absolute
  12935. day number."
  12936. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  12937. ;; No repeater. Do not shift time stamp.
  12938. (time-to-days (org-time-string-to-time start))
  12939. (let ((value (string-to-number (match-string 1 start)))
  12940. (type (match-string 2 start)))
  12941. (if (= 0 value)
  12942. ;; Repeater with a 0-value is considered as void.
  12943. (time-to-days (org-time-string-to-time start))
  12944. (let* ((base (org-date-to-gregorian start))
  12945. (target (org-date-to-gregorian current))
  12946. (sday (calendar-absolute-from-gregorian base))
  12947. (cday (calendar-absolute-from-gregorian target))
  12948. n1 n2)
  12949. ;; If START is already past CURRENT, just return START.
  12950. (if (<= cday sday) sday
  12951. ;; Compute closest date before (N1) and closest date past
  12952. ;; (N2) CURRENT.
  12953. (pcase type
  12954. ("h"
  12955. (let ((missing-hours
  12956. (mod (+ (- (* 24 (- cday sday))
  12957. (nth 2 (org-parse-time-string start)))
  12958. org-extend-today-until)
  12959. value)))
  12960. (setf n1 (if (= missing-hours 0) cday
  12961. (- cday (1+ (/ missing-hours 24)))))
  12962. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  12963. ((or "d" "w")
  12964. (let ((value (if (equal type "w") (* 7 value) value)))
  12965. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  12966. (setf n2 (+ n1 value))))
  12967. ("m"
  12968. (let* ((add-months
  12969. (lambda (d n)
  12970. ;; Add N months to gregorian date D, i.e.,
  12971. ;; a list (MONTH DAY YEAR). Return a valid
  12972. ;; gregorian date.
  12973. (let ((m (+ (nth 0 d) n)))
  12974. (list (mod m 12)
  12975. (nth 1 d)
  12976. (+ (/ m 12) (nth 2 d))))))
  12977. (months ; Complete months to TARGET.
  12978. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  12979. (- (nth 0 target) (nth 0 base))
  12980. ;; If START's day is greater than
  12981. ;; TARGET's, remove incomplete month.
  12982. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  12983. value)
  12984. value))
  12985. (before (funcall add-months base months)))
  12986. (setf n1 (calendar-absolute-from-gregorian before))
  12987. (setf n2
  12988. (calendar-absolute-from-gregorian
  12989. (funcall add-months before value)))))
  12990. (_
  12991. (let* ((d (nth 1 base))
  12992. (m (nth 0 base))
  12993. (y (nth 2 base))
  12994. (years ; Complete years to TARGET.
  12995. (* (/ (- (nth 2 target)
  12996. y
  12997. ;; If START's month and day are
  12998. ;; greater than TARGET's, remove
  12999. ;; incomplete year.
  13000. (if (or (> (nth 0 target) m)
  13001. (and (= (nth 0 target) m)
  13002. (> (nth 1 target) d)))
  13003. 0
  13004. 1))
  13005. value)
  13006. value))
  13007. (before (list m d (+ y years))))
  13008. (setf n1 (calendar-absolute-from-gregorian before))
  13009. (setf n2 (calendar-absolute-from-gregorian
  13010. (list m d (+ (nth 2 before) value)))))))
  13011. ;; Handle PREFER parameter, if any.
  13012. (cond
  13013. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13014. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13015. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13016. (defun org-date-to-gregorian (d)
  13017. "Turn any specification of date D into a Gregorian date for the calendar."
  13018. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13019. ((and (listp d) (= (length d) 3)) d)
  13020. ((stringp d)
  13021. (let ((d (org-parse-time-string d)))
  13022. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13023. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13024. (defun org-timestamp-up (&optional arg)
  13025. "Increase the date item at the cursor by one.
  13026. If the cursor is on the year, change the year. If it is on the month,
  13027. the day or the time, change that. If the cursor is on the enclosing
  13028. bracket, change the timestamp type.
  13029. With prefix ARG, change by that many units."
  13030. (interactive "p")
  13031. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13032. (defun org-timestamp-down (&optional arg)
  13033. "Decrease the date item at the cursor by one.
  13034. If the cursor is on the year, change the year. If it is on the month,
  13035. the day or the time, change that. If the cursor is on the enclosing
  13036. bracket, change the timestamp type.
  13037. With prefix ARG, change by that many units."
  13038. (interactive "p")
  13039. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13040. (defun org-timestamp-up-day (&optional arg)
  13041. "Increase the date in the time stamp by one day.
  13042. With prefix ARG, change that many days."
  13043. (interactive "p")
  13044. (if (and (not (org-at-timestamp-p 'lax))
  13045. (org-at-heading-p))
  13046. (org-todo 'up)
  13047. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13048. (defun org-timestamp-down-day (&optional arg)
  13049. "Decrease the date in the time stamp by one day.
  13050. With prefix ARG, change that many days."
  13051. (interactive "p")
  13052. (if (and (not (org-at-timestamp-p 'lax))
  13053. (org-at-heading-p))
  13054. (org-todo 'down)
  13055. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13056. (defun org-at-timestamp-p (&optional extended)
  13057. "Non-nil if point is inside a timestamp.
  13058. By default, the function only consider syntactically valid active
  13059. timestamps. However, the caller may have a broader definition
  13060. for timestamps. As a consequence, optional argument EXTENDED can
  13061. be set to the following values
  13062. `inactive'
  13063. Include also syntactically valid inactive timestamps.
  13064. `agenda'
  13065. Include timestamps allowed in Agenda, i.e., those in
  13066. properties drawers, planning lines and clock lines.
  13067. `lax'
  13068. Ignore context. The function matches any part of the
  13069. document looking like a timestamp. This includes comments,
  13070. example blocks...
  13071. For backward-compatibility with Org 9.0, every other non-nil
  13072. value is equivalent to `inactive'.
  13073. When at a timestamp, return the position of the point as a symbol
  13074. among `bracket', `after', `year', `month', `hour', `minute',
  13075. `day' or a number of character from the last know part of the
  13076. time stamp. If diary sexp timestamps, any point inside the timestamp
  13077. is considered `day' (i.e. only `bracket', `day', and `after' return
  13078. values are possible).
  13079. When matching, the match groups are the following:
  13080. group 1: year, if any
  13081. group 2: month, if any
  13082. group 3: day number, if any
  13083. group 4: day name, if any
  13084. group 5: hours, if any
  13085. group 6: minutes, if any"
  13086. (let* ((regexp
  13087. (if extended
  13088. (if (eq extended 'agenda)
  13089. (rx-to-string
  13090. `(or (regexp ,org-ts-regexp3)
  13091. (regexp ,org-element--timestamp-regexp)))
  13092. org-ts-regexp3)
  13093. org-ts-regexp2))
  13094. (pos (point))
  13095. (match?
  13096. (let ((boundaries (org-in-regexp regexp)))
  13097. (save-match-data
  13098. (cond ((null boundaries) nil)
  13099. ((eq extended 'lax) t)
  13100. (t
  13101. (or (and (eq extended 'agenda)
  13102. (or (org-at-planning-p)
  13103. (org-at-property-p)
  13104. (and (bound-and-true-p
  13105. org-agenda-include-inactive-timestamps)
  13106. (org-at-clock-log-p))))
  13107. (eq 'timestamp
  13108. (save-excursion
  13109. (when (= pos (cdr boundaries)) (forward-char -1))
  13110. (org-element-type (org-element-context)))))))))))
  13111. (cond
  13112. ((not match?) nil)
  13113. ((= pos (match-beginning 0)) 'bracket)
  13114. ;; Distinguish location right before the closing bracket from
  13115. ;; right after it.
  13116. ((= pos (1- (match-end 0))) 'bracket)
  13117. ((= pos (match-end 0)) 'after)
  13118. ((org-pos-in-match-range pos 2) 'year)
  13119. ((org-pos-in-match-range pos 3) 'month)
  13120. ((org-pos-in-match-range pos 7) 'hour)
  13121. ((org-pos-in-match-range pos 8) 'minute)
  13122. ((or (org-pos-in-match-range pos 4)
  13123. (org-pos-in-match-range pos 5)) 'day)
  13124. ((and (or (match-end 8) (match-end 5))
  13125. (> pos (or (match-end 8) (match-end 5)))
  13126. (< pos (match-end 0)))
  13127. (- pos (or (match-end 8) (match-end 5))))
  13128. (t 'day))))
  13129. (defun org-toggle-timestamp-type ()
  13130. "Toggle the type (<active> or [inactive]) of a time stamp."
  13131. (interactive)
  13132. (when (org-at-timestamp-p 'lax)
  13133. (let ((beg (match-beginning 0)) (end (match-end 0))
  13134. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13135. (save-excursion
  13136. (goto-char beg)
  13137. (while (re-search-forward "[][<>]" end t)
  13138. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13139. t t)))
  13140. (message "Timestamp is now %sactive"
  13141. (if (equal (char-after beg) ?<) "" "in")))))
  13142. (defun org-at-clock-log-p ()
  13143. "Non-nil if point is on a clock log line."
  13144. (and (org-match-line org-clock-line-re)
  13145. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13146. (defvar org-clock-history) ; defined in org-clock.el
  13147. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13148. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13149. "Change the date in the time stamp at point.
  13150. The date is changed by N times WHAT. WHAT can be `day', `month',
  13151. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13152. position in the timestamp determines what is changed.
  13153. When optional argument UPDOWN is non-nil, minutes are rounded
  13154. according to `org-time-stamp-rounding-minutes'.
  13155. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13156. \"--2d\"."
  13157. (let ((origin (point))
  13158. (timestamp? (org-at-timestamp-p 'lax))
  13159. origin-cat
  13160. with-hm inactive
  13161. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13162. extra rem
  13163. ts time time0 fixnext clrgx)
  13164. (unless timestamp? (user-error "Not at a timestamp"))
  13165. (if (and (not what) (eq timestamp? 'bracket))
  13166. (org-toggle-timestamp-type)
  13167. ;; Point isn't on brackets. Remember the part of the time-stamp
  13168. ;; the point was in. Indeed, size of time-stamps may change,
  13169. ;; but point must be kept in the same category nonetheless.
  13170. (setq origin-cat timestamp?)
  13171. (when (and (not what) (not (eq timestamp? 'day))
  13172. org-display-custom-times
  13173. (get-text-property (point) 'display)
  13174. (not (get-text-property (1- (point)) 'display)))
  13175. (setq timestamp? 'day))
  13176. (setq timestamp? (or what timestamp?)
  13177. inactive (= (char-after (match-beginning 0)) ?\[)
  13178. ts (match-string 0))
  13179. (replace-match "")
  13180. (when (string-match
  13181. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13182. ts)
  13183. (setq extra (match-string 1 ts))
  13184. (when suppress-tmp-delay
  13185. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13186. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13187. (setq with-hm t))
  13188. (setq time0 (org-parse-time-string ts))
  13189. (when (and updown
  13190. (eq timestamp? 'minute)
  13191. (not current-prefix-arg))
  13192. ;; This looks like s-up and s-down. Change by one rounding step.
  13193. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13194. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13195. (setcar (cdr time0) (+ (nth 1 time0)
  13196. (if (> n 0) (- rem) (- dm rem))))))
  13197. (setq time
  13198. (apply #'encode-time
  13199. (or (car time0) 0)
  13200. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13201. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13202. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13203. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13204. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13205. (nthcdr 6 time0)))
  13206. (when (and (memq timestamp? '(hour minute))
  13207. extra
  13208. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13209. (setq extra (org-modify-ts-extra
  13210. extra
  13211. (if (eq timestamp? 'hour) 2 5)
  13212. n dm)))
  13213. (when (integerp timestamp?)
  13214. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13215. (when (eq what 'calendar)
  13216. (let ((cal-date (org-get-date-from-calendar)))
  13217. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13218. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13219. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13220. (setcar time0 (or (car time0) 0))
  13221. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13222. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13223. (setq time (apply 'encode-time time0))))
  13224. ;; Insert the new time-stamp, and ensure point stays in the same
  13225. ;; category as before (i.e. not after the last position in that
  13226. ;; category).
  13227. (let ((pos (point)))
  13228. ;; Stay before inserted string. `save-excursion' is of no use.
  13229. (setq org-last-changed-timestamp
  13230. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13231. (goto-char pos))
  13232. (save-match-data
  13233. (looking-at org-ts-regexp3)
  13234. (goto-char
  13235. (pcase origin-cat
  13236. ;; `day' category ends before `hour' if any, or at the end
  13237. ;; of the day name.
  13238. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13239. (`hour (min (match-end 7) origin))
  13240. (`minute (min (1- (match-end 8)) origin))
  13241. ((pred integerp) (min (1- (match-end 0)) origin))
  13242. ;; Point was right after the time-stamp. However, the
  13243. ;; time-stamp length might have changed, so refer to
  13244. ;; (match-end 0) instead.
  13245. (`after (match-end 0))
  13246. ;; `year' and `month' have both fixed size: point couldn't
  13247. ;; have moved into another part.
  13248. (_ origin))))
  13249. ;; Update clock if on a CLOCK line.
  13250. (org-clock-update-time-maybe)
  13251. ;; Maybe adjust the closest clock in `org-clock-history'
  13252. (when org-clock-adjust-closest
  13253. (if (not (and (org-at-clock-log-p)
  13254. (< 1 (length (delq nil (mapcar 'marker-position
  13255. org-clock-history))))))
  13256. (message "No clock to adjust")
  13257. (cond ((save-excursion ; fix previous clock?
  13258. (re-search-backward org-ts-regexp0 nil t)
  13259. (looking-back (concat org-clock-string " \\[")
  13260. (line-beginning-position)))
  13261. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13262. ((save-excursion ; fix next clock?
  13263. (re-search-backward org-ts-regexp0 nil t)
  13264. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13265. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13266. (save-window-excursion
  13267. ;; Find closest clock to point, adjust the previous/next one in history
  13268. (let* ((p (save-excursion (org-back-to-heading t)))
  13269. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13270. (clfixnth
  13271. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13272. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13273. (if (not clfixpos)
  13274. (message "No clock to adjust")
  13275. (save-excursion
  13276. (org-goto-marker-or-bmk clfixpos)
  13277. (org-fold-show-subtree)
  13278. (when (re-search-forward clrgx nil t)
  13279. (goto-char (match-beginning 1))
  13280. (let (org-clock-adjust-closest)
  13281. (org-timestamp-change n timestamp? updown))
  13282. (message "Clock adjusted in %s for heading: %s"
  13283. (file-name-nondirectory (buffer-file-name))
  13284. (org-get-heading t t)))))))))
  13285. ;; Try to recenter the calendar window, if any.
  13286. (when (and org-calendar-follow-timestamp-change
  13287. (get-buffer-window "*Calendar*" t)
  13288. (memq timestamp? '(day month year)))
  13289. (org-recenter-calendar (time-to-days time))))))
  13290. (defun org-modify-ts-extra (s pos n dm)
  13291. "Change the different parts of the lead-time and repeat fields in timestamp."
  13292. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13293. ng h m new rem)
  13294. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13295. (cond
  13296. ((or (org-pos-in-match-range pos 2)
  13297. (org-pos-in-match-range pos 3))
  13298. (setq m (string-to-number (match-string 3 s))
  13299. h (string-to-number (match-string 2 s)))
  13300. (if (org-pos-in-match-range pos 2)
  13301. (setq h (+ h n))
  13302. (setq n (* dm (with-no-warnings (cl-signum n))))
  13303. (unless (= 0 (setq rem (% m dm)))
  13304. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13305. (setq m (+ m n)))
  13306. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13307. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13308. (setq h (mod h 24))
  13309. (setq ng 1 new (format "-%02d:%02d" h m)))
  13310. ((org-pos-in-match-range pos 6)
  13311. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13312. ((org-pos-in-match-range pos 5)
  13313. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13314. ((org-pos-in-match-range pos 9)
  13315. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13316. ((org-pos-in-match-range pos 8)
  13317. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13318. (when ng
  13319. (setq s (concat
  13320. (substring s 0 (match-beginning ng))
  13321. new
  13322. (substring s (match-end ng))))))
  13323. s))
  13324. (defun org-recenter-calendar (d)
  13325. "If the calendar is visible, recenter it to date D."
  13326. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13327. (when cwin
  13328. (let ((calendar-move-hook nil))
  13329. (with-selected-window cwin
  13330. (calendar-goto-date
  13331. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13332. (defun org-goto-calendar (&optional arg)
  13333. "Go to the Emacs calendar at the current date.
  13334. If there is a time stamp in the current line, go to that date.
  13335. A prefix ARG can be used to force the current date."
  13336. (interactive "P")
  13337. (let ((calendar-move-hook nil)
  13338. (calendar-view-holidays-initially-flag nil)
  13339. (calendar-view-diary-initially-flag nil)
  13340. diff)
  13341. (when (or (org-at-timestamp-p 'lax)
  13342. (org-match-line (concat ".*" org-ts-regexp)))
  13343. (let ((d1 (time-to-days nil))
  13344. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13345. (setq diff (- d2 d1))))
  13346. (calendar)
  13347. (calendar-goto-today)
  13348. (when (and diff (not arg)) (calendar-forward-day diff))))
  13349. (defun org-get-date-from-calendar ()
  13350. "Return a list (month day year) of date at point in calendar."
  13351. (with-current-buffer "*Calendar*"
  13352. (save-match-data
  13353. (calendar-cursor-to-date))))
  13354. (defun org-date-from-calendar ()
  13355. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13356. If there is already a time stamp at the cursor position, update it."
  13357. (interactive)
  13358. (if (org-at-timestamp-p 'lax)
  13359. (org-timestamp-change 0 'calendar)
  13360. (let ((cal-date (org-get-date-from-calendar)))
  13361. (org-insert-time-stamp
  13362. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13363. (defcustom org-image-actual-width t
  13364. "When non-nil, use the actual width of images when inlining them.
  13365. When set to a number, use imagemagick (when available) to set the
  13366. image's width to this value.
  13367. When set to a number in a list, try to get the width from any
  13368. #+ATTR.* keyword if it matches a width specification like
  13369. #+ATTR_HTML: :width 300px
  13370. and fall back on that number if none is found.
  13371. When set to nil, try to get the width from an #+ATTR.* keyword
  13372. and fall back on the original width if none is found.
  13373. When set to any other non-nil value, always use the image width.
  13374. This requires Emacs >= 24.1, built with imagemagick support."
  13375. :group 'org-appearance
  13376. :version "24.4"
  13377. :package-version '(Org . "8.0")
  13378. :type '(choice
  13379. (const :tag "Use the image width" t)
  13380. (integer :tag "Use a number of pixels")
  13381. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13382. (const :tag "Use #+ATTR* or don't resize" nil)))
  13383. (defcustom org-agenda-inhibit-startup nil
  13384. "Inhibit startup when preparing agenda buffers.
  13385. When this variable is t, the initialization of the Org agenda
  13386. buffers is inhibited: e.g. the visibility state is not set, the
  13387. tables are not re-aligned, etc."
  13388. :type 'boolean
  13389. :version "24.3"
  13390. :group 'org-agenda)
  13391. (defcustom org-agenda-ignore-properties nil
  13392. "Avoid updating text properties when building the agenda.
  13393. Properties are used to prepare buffers for effort estimates,
  13394. appointments, statistics and subtree-local categories.
  13395. If you don't use these in the agenda, you can add them to this
  13396. list and agenda building will be a bit faster.
  13397. The value is a list, with zero or more of the symbols `effort', `appt',
  13398. `stats' or `category'."
  13399. :type '(set :greedy t
  13400. (const effort)
  13401. (const appt)
  13402. (const stats)
  13403. (const category))
  13404. :version "26.1"
  13405. :package-version '(Org . "8.3")
  13406. :group 'org-agenda)
  13407. ;;;; Files
  13408. (defun org-save-all-org-buffers ()
  13409. "Save all Org buffers without user confirmation."
  13410. (interactive)
  13411. (message "Saving all Org buffers...")
  13412. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13413. (when (featurep 'org-id) (org-id-locations-save))
  13414. (message "Saving all Org buffers... done"))
  13415. (defun org-revert-all-org-buffers ()
  13416. "Revert all Org buffers.
  13417. Prompt for confirmation when there are unsaved changes.
  13418. Be sure you know what you are doing before letting this function
  13419. overwrite your changes.
  13420. This function is useful in a setup where one tracks Org files
  13421. with a version control system, to revert on one machine after pulling
  13422. changes from another. I believe the procedure must be like this:
  13423. 1. \\[org-save-all-org-buffers]
  13424. 2. Pull changes from the other machine, resolve conflicts
  13425. 3. \\[org-revert-all-org-buffers]"
  13426. (interactive)
  13427. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13428. (user-error "Abort"))
  13429. (save-excursion
  13430. (save-window-excursion
  13431. (dolist (b (buffer-list))
  13432. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13433. (with-current-buffer b buffer-file-name))
  13434. (pop-to-buffer-same-window b)
  13435. (revert-buffer t 'no-confirm)))
  13436. (when (and (featurep 'org-id) org-id-track-globally)
  13437. (org-id-locations-load)))))
  13438. ;;;; Agenda files
  13439. ;;;###autoload
  13440. (defun org-switchb (&optional arg)
  13441. "Switch between Org buffers.
  13442. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13443. With `\\[universal-argument] \\[universal-argument]' \
  13444. prefix, restrict available buffers to agenda files."
  13445. (interactive "P")
  13446. (let ((blist (org-buffer-list
  13447. (cond ((equal arg '(4)) 'files)
  13448. ((equal arg '(16)) 'agenda)))))
  13449. (pop-to-buffer-same-window
  13450. (completing-read "Org buffer: "
  13451. (mapcar #'list (mapcar #'buffer-name blist))
  13452. nil t))))
  13453. (defun org-agenda-files (&optional unrestricted archives)
  13454. "Get the list of agenda files.
  13455. Optional UNRESTRICTED means return the full list even if a restriction
  13456. is currently in place.
  13457. When ARCHIVES is t, include all archive files that are really being
  13458. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13459. `org-agenda-archives-mode' is t."
  13460. (let ((files
  13461. (cond
  13462. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13463. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13464. ((listp org-agenda-files) org-agenda-files)
  13465. (t (error "Invalid value of `org-agenda-files'")))))
  13466. (setq files (apply 'append
  13467. (mapcar (lambda (f)
  13468. (if (file-directory-p f)
  13469. (directory-files
  13470. f t org-agenda-file-regexp)
  13471. (list (expand-file-name f org-directory))))
  13472. files)))
  13473. (when org-agenda-skip-unavailable-files
  13474. (setq files (delq nil
  13475. (mapcar (lambda (file)
  13476. (and (file-readable-p file) file))
  13477. files))))
  13478. (when (or (eq archives t)
  13479. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13480. (setq files (org-add-archive-files files)))
  13481. files))
  13482. (defun org-agenda-file-p (&optional file)
  13483. "Return non-nil, if FILE is an agenda file.
  13484. If FILE is omitted, use the file associated with the current
  13485. buffer."
  13486. (let ((fname (or file (buffer-file-name))))
  13487. (and fname
  13488. (member (file-truename fname)
  13489. (mapcar #'file-truename (org-agenda-files t))))))
  13490. (defun org-edit-agenda-file-list ()
  13491. "Edit the list of agenda files.
  13492. Depending on setup, this either uses customize to edit the variable
  13493. `org-agenda-files', or it visits the file that is holding the list. In the
  13494. latter case, the buffer is set up in a way that saving it automatically kills
  13495. the buffer and restores the previous window configuration."
  13496. (interactive)
  13497. (if (stringp org-agenda-files)
  13498. (let ((cw (current-window-configuration)))
  13499. (find-file org-agenda-files)
  13500. (setq-local org-window-configuration cw)
  13501. (add-hook 'after-save-hook
  13502. (lambda ()
  13503. (set-window-configuration
  13504. (prog1 org-window-configuration
  13505. (kill-buffer (current-buffer))))
  13506. (org-install-agenda-files-menu)
  13507. (message "New agenda file list installed"))
  13508. nil 'local)
  13509. (message "%s" (substitute-command-keys
  13510. "Edit list and finish with \\[save-buffer]")))
  13511. (customize-variable 'org-agenda-files)))
  13512. (defun org-store-new-agenda-file-list (list)
  13513. "Set new value for the agenda file list and save it correctly."
  13514. (if (stringp org-agenda-files)
  13515. (let ((fe (org-read-agenda-file-list t)) b u)
  13516. (while (setq b (find-buffer-visiting org-agenda-files))
  13517. (kill-buffer b))
  13518. (with-temp-file org-agenda-files
  13519. (insert
  13520. (mapconcat
  13521. (lambda (f) ;; Keep un-expanded entries.
  13522. (if (setq u (assoc f fe))
  13523. (cdr u)
  13524. f))
  13525. list "\n")
  13526. "\n")))
  13527. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13528. (org-insert-mode-line-in-empty-file nil))
  13529. (setq org-agenda-files list)
  13530. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13531. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13532. "Read the list of agenda files from a file.
  13533. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13534. filenames, used by `org-store-new-agenda-file-list' to write back
  13535. un-expanded file names."
  13536. (when (file-directory-p org-agenda-files)
  13537. (error "`org-agenda-files' cannot be a single directory"))
  13538. (when (stringp org-agenda-files)
  13539. (with-temp-buffer
  13540. (insert-file-contents org-agenda-files)
  13541. (mapcar
  13542. (lambda (f)
  13543. (let ((e (expand-file-name (substitute-in-file-name f)
  13544. org-directory)))
  13545. (if pair-with-expansion
  13546. (cons e f)
  13547. e)))
  13548. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13549. ;;;###autoload
  13550. (defun org-cycle-agenda-files ()
  13551. "Cycle through the files in `org-agenda-files'.
  13552. If the current buffer visits an agenda file, find the next one in the list.
  13553. If the current buffer does not, find the first agenda file."
  13554. (interactive)
  13555. (let* ((fs (or (org-agenda-files t)
  13556. (user-error "No agenda files")))
  13557. (files (copy-sequence fs))
  13558. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13559. file)
  13560. (when tcf
  13561. (while (and (setq file (pop files))
  13562. (not (equal (file-truename file) tcf)))))
  13563. (find-file (car (or files fs)))
  13564. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13565. (defun org-agenda-file-to-front (&optional to-end)
  13566. "Move/add the current file to the top of the agenda file list.
  13567. If the file is not present in the list, it is added to the front. If it is
  13568. present, it is moved there. With optional argument TO-END, add/move to the
  13569. end of the list."
  13570. (interactive "P")
  13571. (let ((org-agenda-skip-unavailable-files nil)
  13572. (file-alist (mapcar (lambda (x)
  13573. (cons (file-truename x) x))
  13574. (org-agenda-files t)))
  13575. (ctf (file-truename
  13576. (or buffer-file-name
  13577. (user-error "Please save the current buffer to a file"))))
  13578. x had)
  13579. (setq x (assoc ctf file-alist) had x)
  13580. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13581. (if to-end
  13582. (setq file-alist (append (delq x file-alist) (list x)))
  13583. (setq file-alist (cons x (delq x file-alist))))
  13584. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13585. (org-install-agenda-files-menu)
  13586. (message "File %s to %s of agenda file list"
  13587. (if had "moved" "added") (if to-end "end" "front"))))
  13588. (defun org-remove-file (&optional file)
  13589. "Remove current file from the list of files in variable `org-agenda-files'.
  13590. These are the files which are being checked for agenda entries.
  13591. Optional argument FILE means use this file instead of the current."
  13592. (interactive)
  13593. (let* ((org-agenda-skip-unavailable-files nil)
  13594. (file (or file buffer-file-name
  13595. (user-error "Current buffer does not visit a file")))
  13596. (true-file (file-truename file))
  13597. (afile (abbreviate-file-name file))
  13598. (files (delq nil (mapcar
  13599. (lambda (x)
  13600. (unless (equal true-file
  13601. (file-truename x))
  13602. x))
  13603. (org-agenda-files t)))))
  13604. (if (not (= (length files) (length (org-agenda-files t))))
  13605. (progn
  13606. (org-store-new-agenda-file-list files)
  13607. (org-install-agenda-files-menu)
  13608. (message "Removed from Org Agenda list: %s" afile))
  13609. (message "File was not in list: %s (not removed)" afile))))
  13610. (defun org-file-menu-entry (file)
  13611. (vector file (list 'find-file file) t))
  13612. (defun org-check-agenda-file (file)
  13613. "Make sure FILE exists. If not, ask user what to do."
  13614. (unless (file-exists-p file)
  13615. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13616. (abbreviate-file-name file))
  13617. (let ((r (downcase (read-char-exclusive))))
  13618. (cond
  13619. ((equal r ?r)
  13620. (org-remove-file file)
  13621. (throw 'nextfile t))
  13622. (t (user-error "Abort"))))))
  13623. (defun org-get-agenda-file-buffer (file)
  13624. "Get an agenda buffer visiting FILE.
  13625. If the buffer needs to be created, add it to the list of buffers
  13626. which might be released later."
  13627. (let ((buf (org-find-base-buffer-visiting file)))
  13628. (if buf
  13629. buf ; just return it
  13630. ;; Make a new buffer and remember it
  13631. (setq buf (find-file-noselect file))
  13632. (when buf (push buf org-agenda-new-buffers))
  13633. buf)))
  13634. (defun org-release-buffers (blist)
  13635. "Release all buffers in list, asking the user for confirmation when needed.
  13636. When a buffer is unmodified, it is just killed. When modified, it is saved
  13637. \(if the user agrees) and then killed."
  13638. (let (file)
  13639. (dolist (buf blist)
  13640. (setq file (buffer-file-name buf))
  13641. (when (and (buffer-modified-p buf)
  13642. file
  13643. (y-or-n-p (format "Save file %s? " file)))
  13644. (with-current-buffer buf (save-buffer)))
  13645. (kill-buffer buf))))
  13646. (defun org-agenda-prepare-buffers (files)
  13647. "Create buffers for all agenda files, protect archived trees and comments."
  13648. (interactive)
  13649. (let ((inhibit-read-only t)
  13650. (org-inhibit-startup org-agenda-inhibit-startup)
  13651. pos)
  13652. (setq org-tag-alist-for-agenda nil
  13653. org-tag-groups-alist-for-agenda nil)
  13654. (save-excursion
  13655. (save-restriction
  13656. (dolist (file files)
  13657. (catch 'nextfile
  13658. (if (bufferp file)
  13659. (set-buffer file)
  13660. (org-check-agenda-file file)
  13661. (set-buffer (org-get-agenda-file-buffer file)))
  13662. (widen)
  13663. (org-set-regexps-and-options 'tags-only)
  13664. (setq pos (point))
  13665. (or (memq 'category org-agenda-ignore-properties)
  13666. (org-refresh-category-properties))
  13667. (or (memq 'stats org-agenda-ignore-properties)
  13668. (org-refresh-stats-properties))
  13669. (or (memq 'effort org-agenda-ignore-properties)
  13670. (unless org-element-use-cache
  13671. (org-refresh-effort-properties)))
  13672. (or (memq 'appt org-agenda-ignore-properties)
  13673. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13674. (setq org-todo-keywords-for-agenda
  13675. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  13676. (setq org-done-keywords-for-agenda
  13677. (append org-done-keywords-for-agenda org-done-keywords))
  13678. (setq org-todo-keyword-alist-for-agenda
  13679. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  13680. (setq org-tag-alist-for-agenda
  13681. (org--tag-add-to-alist
  13682. org-tag-alist-for-agenda
  13683. org-current-tag-alist))
  13684. ;; Merge current file's tag groups into global
  13685. ;; `org-tag-groups-alist-for-agenda'.
  13686. (when org-group-tags
  13687. (dolist (alist org-tag-groups-alist)
  13688. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13689. (if old
  13690. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13691. (push alist org-tag-groups-alist-for-agenda)))))
  13692. (goto-char pos)))))
  13693. (setq org-todo-keywords-for-agenda
  13694. (org-uniquify org-todo-keywords-for-agenda))
  13695. (setq org-todo-keyword-alist-for-agenda
  13696. (org-uniquify org-todo-keyword-alist-for-agenda))))
  13697. ;;;; CDLaTeX minor mode
  13698. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13699. "Keymap for the minor `org-cdlatex-mode'.")
  13700. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13701. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13702. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13703. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13704. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13705. (defvar org-cdlatex-texmathp-advice-is-done nil
  13706. "Flag remembering if we have applied the advice to texmathp already.")
  13707. (define-minor-mode org-cdlatex-mode
  13708. "Toggle the minor `org-cdlatex-mode'.
  13709. This mode supports entering LaTeX environment and math in LaTeX fragments
  13710. in Org mode.
  13711. \\{org-cdlatex-mode-map}"
  13712. :lighter " OCDL"
  13713. (when org-cdlatex-mode
  13714. (require 'cdlatex)
  13715. (run-hooks 'cdlatex-mode-hook)
  13716. (cdlatex-compute-tables))
  13717. (unless org-cdlatex-texmathp-advice-is-done
  13718. (setq org-cdlatex-texmathp-advice-is-done t)
  13719. (advice-add 'texmathp :around #'org--math-always-on)))
  13720. (defun org--math-always-on (orig-fun &rest args)
  13721. "Always return t in Org buffers.
  13722. This is because we want to insert math symbols without dollars even outside
  13723. the LaTeX math segments. If Org mode thinks that point is actually inside
  13724. an embedded LaTeX fragment, let `texmathp' do its job.
  13725. `\\[org-cdlatex-mode-map]'"
  13726. (interactive)
  13727. (cond
  13728. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  13729. ((eq this-command 'cdlatex-math-symbol)
  13730. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  13731. t)
  13732. (t
  13733. (let ((p (org-inside-LaTeX-fragment-p)))
  13734. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  13735. (if (member (car p)
  13736. (plist-get org-format-latex-options :matchers))
  13737. (progn
  13738. (setq texmathp-why '("Org mode embedded math" . 0))
  13739. t)
  13740. (apply orig-fun args)))))))
  13741. (defun turn-on-org-cdlatex ()
  13742. "Unconditionally turn on `org-cdlatex-mode'."
  13743. (org-cdlatex-mode 1))
  13744. (defun org-try-cdlatex-tab ()
  13745. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  13746. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  13747. - inside a LaTeX fragment, or
  13748. - after the first word in a line, where an abbreviation expansion could
  13749. insert a LaTeX environment."
  13750. (when org-cdlatex-mode
  13751. (cond
  13752. ;; Before any word on the line: No expansion possible.
  13753. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  13754. ;; Just after first word on the line: Expand it. Make sure it
  13755. ;; cannot happen on headlines, though.
  13756. ((save-excursion
  13757. (skip-chars-backward "a-zA-Z0-9*")
  13758. (skip-chars-backward " \t")
  13759. (and (bolp) (not (org-at-heading-p))))
  13760. (cdlatex-tab) t)
  13761. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  13762. (defun org-cdlatex-underscore-caret (&optional _arg)
  13763. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  13764. Revert to the normal definition outside of these fragments."
  13765. (interactive "P")
  13766. (if (org-inside-LaTeX-fragment-p)
  13767. (call-interactively 'cdlatex-sub-superscript)
  13768. (let (org-cdlatex-mode)
  13769. (call-interactively (key-binding (vector last-input-event))))))
  13770. (defun org-cdlatex-math-modify (&optional _arg)
  13771. "Execute `cdlatex-math-modify' in LaTeX fragments.
  13772. Revert to the normal definition outside of these fragments."
  13773. (interactive "P")
  13774. (if (org-inside-LaTeX-fragment-p)
  13775. (call-interactively 'cdlatex-math-modify)
  13776. (let (org-cdlatex-mode)
  13777. (call-interactively (key-binding (vector last-input-event))))))
  13778. (defun org-cdlatex-environment-indent (&optional environment item)
  13779. "Execute `cdlatex-environment' and indent the inserted environment.
  13780. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  13781. The inserted environment is indented to current indentation
  13782. unless point is at the beginning of the line, in which the
  13783. environment remains unintended."
  13784. (interactive)
  13785. ;; cdlatex-environment always return nil. Therefore, capture output
  13786. ;; first and determine if an environment was selected.
  13787. (let* ((beg (point-marker))
  13788. (end (copy-marker (point) t))
  13789. (inserted (progn
  13790. (ignore-errors (cdlatex-environment environment item))
  13791. (< beg end)))
  13792. ;; Figure out how many lines to move forward after the
  13793. ;; environment has been inserted.
  13794. (lines (when inserted
  13795. (save-excursion
  13796. (- (cl-loop while (< beg (point))
  13797. with x = 0
  13798. do (forward-line -1)
  13799. (cl-incf x)
  13800. finally return x)
  13801. (if (progn (goto-char beg)
  13802. (and (progn (skip-chars-forward " \t") (eolp))
  13803. (progn (skip-chars-backward " \t") (bolp))))
  13804. 1 0)))))
  13805. (env (org-trim (delete-and-extract-region beg end))))
  13806. (when inserted
  13807. ;; Get indentation of next line unless at column 0.
  13808. (let ((ind (if (bolp) 0
  13809. (save-excursion
  13810. (org-return t)
  13811. (prog1 (current-indentation)
  13812. (when (progn (skip-chars-forward " \t") (eolp))
  13813. (delete-region beg (point)))))))
  13814. (bol (progn (skip-chars-backward " \t") (bolp))))
  13815. ;; Insert a newline before environment unless at column zero
  13816. ;; to "escape" the current line. Insert a newline if
  13817. ;; something is one the same line as \end{ENVIRONMENT}.
  13818. (insert
  13819. (concat (unless bol "\n") env
  13820. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  13821. (unless (zerop ind)
  13822. (save-excursion
  13823. (goto-char beg)
  13824. (while (< (point) end)
  13825. (unless (eolp) (indent-line-to ind))
  13826. (forward-line))))
  13827. (goto-char beg)
  13828. (forward-line lines)
  13829. (indent-line-to ind)))
  13830. (set-marker beg nil)
  13831. (set-marker end nil)))
  13832. ;;;; LaTeX fragments
  13833. (defun org-inside-LaTeX-fragment-p ()
  13834. "Test if point is inside a LaTeX fragment.
  13835. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  13836. sequence appearing also before point.
  13837. Even though the matchers for math are configurable, this function assumes
  13838. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  13839. delimiters are skipped when they have been removed by customization.
  13840. The return value is nil, or a cons cell with the delimiter and the
  13841. position of this delimiter.
  13842. This function does a reasonably good job, but can locally be fooled by
  13843. for example currency specifications. For example it will assume being in
  13844. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  13845. fragments that are properly closed, but during editing, we have to live
  13846. with the uncertainty caused by missing closing delimiters. This function
  13847. looks only before point, not after."
  13848. (catch 'exit
  13849. (let ((pos (point))
  13850. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  13851. (lim (progn
  13852. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  13853. 'move)
  13854. (point)))
  13855. dd-on str (start 0) m re)
  13856. (goto-char pos)
  13857. (when dodollar
  13858. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  13859. re (nth 1 (assoc "$" org-latex-regexps)))
  13860. (while (string-match re str start)
  13861. (cond
  13862. ((= (match-end 0) (length str))
  13863. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  13864. ((= (match-end 0) (- (length str) 5))
  13865. (throw 'exit nil))
  13866. (t (setq start (match-end 0))))))
  13867. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  13868. (goto-char pos)
  13869. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  13870. (and (match-beginning 2) (throw 'exit nil))
  13871. ;; count $$
  13872. (while (re-search-backward "\\$\\$" lim t)
  13873. (setq dd-on (not dd-on)))
  13874. (goto-char pos)
  13875. (when dd-on (cons "$$" m))))))
  13876. (defun org-inside-latex-macro-p ()
  13877. "Is point inside a LaTeX macro or its arguments?"
  13878. (save-match-data
  13879. (org-in-regexp
  13880. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  13881. (defun org--make-preview-overlay (beg end image &optional imagetype)
  13882. "Build an overlay between BEG and END using IMAGE file.
  13883. Argument IMAGETYPE is the extension of the displayed image,
  13884. as a string. It defaults to \"png\"."
  13885. (let ((ov (make-overlay beg end))
  13886. (imagetype (or (intern imagetype) 'png)))
  13887. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  13888. (overlay-put ov 'evaporate t)
  13889. (overlay-put ov
  13890. 'modification-hooks
  13891. (list (lambda (o _flag _beg _end &optional _l)
  13892. (delete-overlay o))))
  13893. (overlay-put ov
  13894. 'display
  13895. (list 'image :type imagetype :file image :ascent 'center))))
  13896. (defun org-clear-latex-preview (&optional beg end)
  13897. "Remove all overlays with LaTeX fragment images in current buffer.
  13898. When optional arguments BEG and END are non-nil, remove all
  13899. overlays between them instead. Return a non-nil value when some
  13900. overlays were removed, nil otherwise."
  13901. (let ((overlays
  13902. (cl-remove-if-not
  13903. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  13904. (overlays-in (or beg (point-min)) (or end (point-max))))))
  13905. (mapc #'delete-overlay overlays)
  13906. overlays))
  13907. (defun org--latex-preview-region (beg end)
  13908. "Preview LaTeX fragments between BEG and END.
  13909. BEG and END are buffer positions."
  13910. (let ((file (buffer-file-name (buffer-base-buffer))))
  13911. (save-excursion
  13912. (org-format-latex
  13913. (concat org-preview-latex-image-directory "org-ltximg")
  13914. beg end
  13915. ;; Emacs cannot overlay images from remote hosts. Create it in
  13916. ;; `temporary-file-directory' instead.
  13917. (if (or (not file) (file-remote-p file))
  13918. temporary-file-directory
  13919. default-directory)
  13920. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  13921. (defun org-latex-preview (&optional arg)
  13922. "Toggle preview of the LaTeX fragment at point.
  13923. If the cursor is on a LaTeX fragment, create the image and
  13924. overlay it over the source code, if there is none. Remove it
  13925. otherwise. If there is no fragment at point, display images for
  13926. all fragments in the current section.
  13927. With a `\\[universal-argument]' prefix argument ARG, clear images \
  13928. for all fragments
  13929. in the current section.
  13930. With a `\\[universal-argument] \\[universal-argument]' prefix \
  13931. argument ARG, display image for all
  13932. fragments in the buffer.
  13933. With a `\\[universal-argument] \\[universal-argument] \
  13934. \\[universal-argument]' prefix argument ARG, clear image for all
  13935. fragments in the buffer."
  13936. (interactive "P")
  13937. (cond
  13938. ((not (display-graphic-p)) nil)
  13939. ;; Clear whole buffer.
  13940. ((equal arg '(64))
  13941. (org-clear-latex-preview (point-min) (point-max))
  13942. (message "LaTeX previews removed from buffer"))
  13943. ;; Preview whole buffer.
  13944. ((equal arg '(16))
  13945. (message "Creating LaTeX previews in buffer...")
  13946. (org--latex-preview-region (point-min) (point-max))
  13947. (message "Creating LaTeX previews in buffer... done."))
  13948. ;; Clear current section.
  13949. ((equal arg '(4))
  13950. (org-clear-latex-preview
  13951. (if (org-before-first-heading-p) (point-min)
  13952. (save-excursion
  13953. (org-with-limited-levels (org-back-to-heading t) (point))))
  13954. (org-with-limited-levels (org-entry-end-position))))
  13955. ;; Toggle preview on LaTeX code at point.
  13956. ((let ((datum (org-element-context)))
  13957. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  13958. (let ((beg (org-element-property :begin datum))
  13959. (end (org-element-property :end datum)))
  13960. (if (org-clear-latex-preview beg end)
  13961. (message "LaTeX preview removed")
  13962. (message "Creating LaTeX preview...")
  13963. (org--latex-preview-region beg end)
  13964. (message "Creating LaTeX preview... done."))
  13965. t))))
  13966. ;; Preview current section.
  13967. (t
  13968. (let ((beg (if (org-before-first-heading-p) (point-min)
  13969. (save-excursion
  13970. (org-with-limited-levels (org-back-to-heading t) (point)))))
  13971. (end (org-with-limited-levels (org-entry-end-position))))
  13972. (message "Creating LaTeX previews in section...")
  13973. (org--latex-preview-region beg end)
  13974. (message "Creating LaTeX previews in section... done.")))))
  13975. (defun org-format-latex
  13976. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  13977. "Replace LaTeX fragments with links to an image.
  13978. The function takes care of creating the replacement image.
  13979. Only consider fragments between BEG and END when those are
  13980. provided.
  13981. When optional argument OVERLAYS is non-nil, display the image on
  13982. top of the fragment instead of replacing it.
  13983. PROCESSING-TYPE is the conversion method to use, as a symbol.
  13984. Some of the options can be changed using the variable
  13985. `org-format-latex-options', which see."
  13986. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  13987. (unless (eq processing-type 'verbatim)
  13988. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  13989. (cnt 0)
  13990. checkdir-flag)
  13991. (goto-char (or beg (point-min)))
  13992. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  13993. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  13994. (overlay-recenter (or end (point-max))))
  13995. (while (re-search-forward math-regexp end t)
  13996. (unless (and overlays
  13997. (eq (get-char-property (point) 'org-overlay-type)
  13998. 'org-latex-overlay))
  13999. (let* ((context (org-element-context))
  14000. (type (org-element-type context)))
  14001. (when (memq type '(latex-environment latex-fragment))
  14002. (let ((block-type (eq type 'latex-environment))
  14003. (value (org-element-property :value context))
  14004. (beg (org-element-property :begin context))
  14005. (end (save-excursion
  14006. (goto-char (org-element-property :end context))
  14007. (skip-chars-backward " \r\t\n")
  14008. (point))))
  14009. (cond
  14010. ((eq processing-type 'mathjax)
  14011. ;; Prepare for MathJax processing.
  14012. (if (not (string-match "\\`\\$\\$?" value))
  14013. (goto-char end)
  14014. (delete-region beg end)
  14015. (if (string= (match-string 0 value) "$$")
  14016. (insert "\\[" (substring value 2 -2) "\\]")
  14017. (insert "\\(" (substring value 1 -1) "\\)"))))
  14018. ((eq processing-type 'html)
  14019. (goto-char beg)
  14020. (delete-region beg end)
  14021. (insert (org-format-latex-as-html value)))
  14022. ((assq processing-type org-preview-latex-process-alist)
  14023. ;; Process to an image.
  14024. (cl-incf cnt)
  14025. (goto-char beg)
  14026. (let* ((processing-info
  14027. (cdr (assq processing-type org-preview-latex-process-alist)))
  14028. (face (face-at-point))
  14029. ;; Get the colors from the face at point.
  14030. (fg
  14031. (let ((color (plist-get org-format-latex-options
  14032. :foreground)))
  14033. (if forbuffer
  14034. (cond
  14035. ((eq color 'auto)
  14036. (face-attribute face :foreground nil 'default))
  14037. ((eq color 'default)
  14038. (face-attribute 'default :foreground nil))
  14039. (t color))
  14040. color)))
  14041. (bg
  14042. (let ((color (plist-get org-format-latex-options
  14043. :background)))
  14044. (if forbuffer
  14045. (cond
  14046. ((eq color 'auto)
  14047. (face-attribute face :background nil 'default))
  14048. ((eq color 'default)
  14049. (face-attribute 'default :background nil))
  14050. (t color))
  14051. color)))
  14052. (hash (sha1 (prin1-to-string
  14053. (list org-format-latex-header
  14054. org-latex-default-packages-alist
  14055. org-latex-packages-alist
  14056. org-format-latex-options
  14057. forbuffer value fg bg))))
  14058. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14059. (absprefix (expand-file-name prefix dir))
  14060. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14061. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14062. (sep (and block-type "\n\n"))
  14063. (link (concat sep "[[file:" linkfile "]]" sep))
  14064. (options
  14065. (org-combine-plists
  14066. org-format-latex-options
  14067. `(:foreground ,fg :background ,bg))))
  14068. (when msg (message msg cnt))
  14069. (unless checkdir-flag ; Ensure the directory exists.
  14070. (setq checkdir-flag t)
  14071. (let ((todir (file-name-directory absprefix)))
  14072. (unless (file-directory-p todir)
  14073. (make-directory todir t))))
  14074. (unless (file-exists-p movefile)
  14075. (org-create-formula-image
  14076. value movefile options forbuffer processing-type))
  14077. (if overlays
  14078. (progn
  14079. (dolist (o (overlays-in beg end))
  14080. (when (eq (overlay-get o 'org-overlay-type)
  14081. 'org-latex-overlay)
  14082. (delete-overlay o)))
  14083. (org--make-preview-overlay beg end movefile imagetype)
  14084. (goto-char end))
  14085. (delete-region beg end)
  14086. (insert
  14087. (org-add-props link
  14088. (list 'org-latex-src
  14089. (replace-regexp-in-string "\"" "" value)
  14090. 'org-latex-src-embed-type
  14091. (if block-type 'paragraph 'character)))))))
  14092. ((eq processing-type 'mathml)
  14093. ;; Process to MathML.
  14094. (unless (org-format-latex-mathml-available-p)
  14095. (user-error "LaTeX to MathML converter not configured"))
  14096. (cl-incf cnt)
  14097. (when msg (message msg cnt))
  14098. (goto-char beg)
  14099. (delete-region beg end)
  14100. (insert (org-format-latex-as-mathml
  14101. value block-type prefix dir)))
  14102. (t
  14103. (error "Unknown conversion process %s for LaTeX fragments"
  14104. processing-type)))))))))))
  14105. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14106. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14107. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14108. successful, return the portion between \"<math...> </math>\"
  14109. elements otherwise return nil. When MATHML-FILE is specified,
  14110. write the results in to that file. When invoked as an
  14111. interactive command, prompt for LATEX-FRAG, with initial value
  14112. set to the current active region and echo the results for user
  14113. inspection."
  14114. (interactive (list (let ((frag (when (org-region-active-p)
  14115. (buffer-substring-no-properties
  14116. (region-beginning) (region-end)))))
  14117. (read-string "LaTeX Fragment: " frag nil frag))))
  14118. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14119. (let* ((tmp-in-file
  14120. (let ((file (file-relative-name
  14121. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14122. (write-region latex-frag nil file)
  14123. file))
  14124. (tmp-out-file (file-relative-name
  14125. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14126. (cmd (format-spec
  14127. org-latex-to-mathml-convert-command
  14128. `((?j . ,(and org-latex-to-mathml-jar-file
  14129. (shell-quote-argument
  14130. (expand-file-name
  14131. org-latex-to-mathml-jar-file))))
  14132. (?I . ,(shell-quote-argument tmp-in-file))
  14133. (?i . ,latex-frag)
  14134. (?o . ,(shell-quote-argument tmp-out-file)))))
  14135. mathml shell-command-output)
  14136. (when (called-interactively-p 'any)
  14137. (unless (org-format-latex-mathml-available-p)
  14138. (user-error "LaTeX to MathML converter not configured")))
  14139. (message "Running %s" cmd)
  14140. (setq shell-command-output (shell-command-to-string cmd))
  14141. (setq mathml
  14142. (when (file-readable-p tmp-out-file)
  14143. (with-current-buffer (find-file-noselect tmp-out-file t)
  14144. (goto-char (point-min))
  14145. (when (re-search-forward
  14146. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14147. (regexp-quote
  14148. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14149. nil t)
  14150. (prog1 (match-string 0) (kill-buffer))))))
  14151. (cond
  14152. (mathml
  14153. (setq mathml
  14154. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14155. (when mathml-file
  14156. (write-region mathml nil mathml-file))
  14157. (when (called-interactively-p 'any)
  14158. (message mathml)))
  14159. ((warn "LaTeX to MathML conversion failed")
  14160. (message shell-command-output)))
  14161. (delete-file tmp-in-file)
  14162. (when (file-exists-p tmp-out-file)
  14163. (delete-file tmp-out-file))
  14164. mathml))
  14165. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14166. prefix &optional dir)
  14167. "Use `org-create-math-formula' but check local cache first."
  14168. (let* ((absprefix (expand-file-name prefix dir))
  14169. (print-length nil) (print-level nil)
  14170. (formula-id (concat
  14171. "formula-"
  14172. (sha1
  14173. (prin1-to-string
  14174. (list latex-frag
  14175. org-latex-to-mathml-convert-command)))))
  14176. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14177. (formula-cache-dir (file-name-directory formula-cache)))
  14178. (unless (file-directory-p formula-cache-dir)
  14179. (make-directory formula-cache-dir t))
  14180. (unless (file-exists-p formula-cache)
  14181. (org-create-math-formula latex-frag formula-cache))
  14182. (if (file-exists-p formula-cache)
  14183. ;; Successful conversion. Return the link to MathML file.
  14184. (org-add-props
  14185. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14186. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14187. 'org-latex-src-embed-type (if latex-frag-type
  14188. 'paragraph 'character)))
  14189. ;; Failed conversion. Return the LaTeX fragment verbatim
  14190. latex-frag)))
  14191. (defun org-format-latex-as-html (latex-fragment)
  14192. "Convert LATEX-FRAGMENT to HTML.
  14193. This uses `org-latex-to-html-convert-command', which see."
  14194. (let ((cmd (format-spec org-latex-to-html-convert-command
  14195. `((?i . ,latex-fragment)))))
  14196. (message "Running %s" cmd)
  14197. (shell-command-to-string cmd)))
  14198. (defun org--get-display-dpi ()
  14199. "Get the DPI of the display.
  14200. The function assumes that the display has the same pixel width in
  14201. the horizontal and vertical directions."
  14202. (if (display-graphic-p)
  14203. (round (/ (display-pixel-height)
  14204. (/ (display-mm-height) 25.4)))
  14205. (error "Attempt to calculate the dpi of a non-graphic display")))
  14206. (defun org-create-formula-image
  14207. (string tofile options buffer &optional processing-type)
  14208. "Create an image from LaTeX source using external processes.
  14209. The LaTeX STRING is saved to a temporary LaTeX file, then
  14210. converted to an image file by process PROCESSING-TYPE defined in
  14211. `org-preview-latex-process-alist'. A nil value defaults to
  14212. `org-preview-latex-default-process'.
  14213. The generated image file is eventually moved to TOFILE.
  14214. The OPTIONS argument controls the size, foreground color and
  14215. background color of the generated image.
  14216. When BUFFER non-nil, this function is used for LaTeX previewing.
  14217. Otherwise, it is used to deal with LaTeX snippets showed in
  14218. a HTML file."
  14219. (let* ((processing-type (or processing-type
  14220. org-preview-latex-default-process))
  14221. (processing-info
  14222. (cdr (assq processing-type org-preview-latex-process-alist)))
  14223. (programs (plist-get processing-info :programs))
  14224. (error-message (or (plist-get processing-info :message) ""))
  14225. (image-input-type (plist-get processing-info :image-input-type))
  14226. (image-output-type (plist-get processing-info :image-output-type))
  14227. (post-clean (or (plist-get processing-info :post-clean)
  14228. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14229. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14230. (latex-header
  14231. (or (plist-get processing-info :latex-header)
  14232. (org-latex-make-preamble
  14233. (org-export-get-environment (org-export-get-backend 'latex))
  14234. org-format-latex-header
  14235. 'snippet)))
  14236. (latex-compiler (plist-get processing-info :latex-compiler))
  14237. (tmpdir temporary-file-directory)
  14238. (texfilebase (make-temp-name
  14239. (expand-file-name "orgtex" tmpdir)))
  14240. (texfile (concat texfilebase ".tex"))
  14241. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14242. '(1.0 . 1.0)))
  14243. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14244. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14245. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14246. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14247. "Black"))
  14248. (bg (or (plist-get options (if buffer :background :html-background))
  14249. "Transparent"))
  14250. (image-converter
  14251. (or (and (string= bg "Transparent")
  14252. (plist-get processing-info :transparent-image-converter))
  14253. (plist-get processing-info :image-converter)))
  14254. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14255. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14256. (dolist (program programs)
  14257. (org-check-external-command program error-message))
  14258. (if (eq fg 'default)
  14259. (setq fg (org-latex-color :foreground))
  14260. (setq fg (org-latex-color-format fg)))
  14261. (setq bg (cond
  14262. ((eq bg 'default) (org-latex-color :background))
  14263. ((string= bg "Transparent") nil)
  14264. (t (org-latex-color-format bg))))
  14265. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14266. (if (string-suffix-p string "\n")
  14267. (aset string (1- (length string)) ?%)
  14268. (setq string (concat string "%")))
  14269. (with-temp-file texfile
  14270. (insert latex-header)
  14271. (insert "\n\\begin{document}\n"
  14272. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14273. (if bg
  14274. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14275. "\n\\pagecolor{bg}%\n")
  14276. "")
  14277. "\n{\\color{fg}\n"
  14278. string
  14279. "\n}\n"
  14280. "\n\\end{document}\n"))
  14281. (let* ((err-msg (format "Please adjust `%s' part of \
  14282. `org-preview-latex-process-alist'."
  14283. processing-type))
  14284. (image-input-file
  14285. (org-compile-file
  14286. texfile latex-compiler image-input-type err-msg log-buf))
  14287. (image-output-file
  14288. (org-compile-file
  14289. image-input-file image-converter image-output-type err-msg log-buf
  14290. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14291. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14292. (copy-file image-output-file tofile 'replace)
  14293. (dolist (e post-clean)
  14294. (when (file-exists-p (concat texfilebase e))
  14295. (delete-file (concat texfilebase e))))
  14296. image-output-file)))
  14297. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14298. "Fill a LaTeX header template TPL.
  14299. In the template, the following place holders will be recognized:
  14300. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14301. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14302. [PACKAGES] \\usepackage statements for PKG
  14303. [NO-PACKAGES] do not include PKG
  14304. [EXTRA] the string EXTRA
  14305. [NO-EXTRA] do not include EXTRA
  14306. For backward compatibility, if both the positive and the negative place
  14307. holder is missing, the positive one (without the \"NO-\") will be
  14308. assumed to be present at the end of the template.
  14309. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14310. EXTRA is a string.
  14311. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14312. (let (rpl (end ""))
  14313. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14314. (setq rpl (if (or (match-end 1) (not def-pkg))
  14315. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14316. tpl (replace-match rpl t t tpl))
  14317. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14318. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14319. (setq rpl (if (or (match-end 1) (not pkg))
  14320. "" (org-latex-packages-to-string pkg snippets-p t))
  14321. tpl (replace-match rpl t t tpl))
  14322. (when pkg (setq end
  14323. (concat end "\n"
  14324. (org-latex-packages-to-string pkg snippets-p)))))
  14325. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14326. (setq rpl (if (or (match-end 1) (not extra))
  14327. "" (concat extra "\n"))
  14328. tpl (replace-match rpl t t tpl))
  14329. (when (and extra (string-match "\\S-" extra))
  14330. (setq end (concat end "\n" extra))))
  14331. (if (string-match "\\S-" end)
  14332. (concat tpl "\n" end)
  14333. tpl)))
  14334. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14335. "Turn an alist of packages into a string with the \\usepackage macros."
  14336. (setq pkg (mapconcat (lambda(p)
  14337. (cond
  14338. ((stringp p) p)
  14339. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14340. (format "%% Package %s omitted" (cadr p)))
  14341. ((equal "" (car p))
  14342. (format "\\usepackage{%s}" (cadr p)))
  14343. (t
  14344. (format "\\usepackage[%s]{%s}"
  14345. (car p) (cadr p)))))
  14346. pkg
  14347. "\n"))
  14348. (if newline (concat pkg "\n") pkg))
  14349. (defun org-dvipng-color (attr)
  14350. "Return a RGB color specification for dvipng."
  14351. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14352. (defun org-dvipng-color-format (color-name)
  14353. "Convert COLOR-NAME to a RGB color value for dvipng."
  14354. (apply #'format "rgb %s %s %s"
  14355. (mapcar 'org-normalize-color
  14356. (color-values color-name))))
  14357. (defun org-latex-color (attr)
  14358. "Return a RGB color for the LaTeX color package."
  14359. (org-latex-color-format (face-attribute 'default attr nil)))
  14360. (defun org-latex-color-format (color-name)
  14361. "Convert COLOR-NAME to a RGB color value."
  14362. (apply #'format "%s,%s,%s"
  14363. (mapcar 'org-normalize-color
  14364. (color-values color-name))))
  14365. (defun org-normalize-color (value)
  14366. "Return string to be used as color value for an RGB component."
  14367. (format "%g" (/ value 65535.0)))
  14368. ;; Image display
  14369. (defvar-local org-inline-image-overlays nil)
  14370. (defun org-toggle-inline-images (&optional include-linked)
  14371. "Toggle the display of inline images.
  14372. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14373. (interactive "P")
  14374. (if org-inline-image-overlays
  14375. (progn
  14376. (org-remove-inline-images)
  14377. (when (called-interactively-p 'interactive)
  14378. (message "Inline image display turned off")))
  14379. (org-display-inline-images include-linked)
  14380. (when (called-interactively-p 'interactive)
  14381. (message (if org-inline-image-overlays
  14382. (format "%d images displayed inline"
  14383. (length org-inline-image-overlays))
  14384. "No images to display inline")))))
  14385. (defun org-redisplay-inline-images ()
  14386. "Assure display of inline images and refresh them."
  14387. (interactive)
  14388. (org-toggle-inline-images)
  14389. (unless org-inline-image-overlays
  14390. (org-toggle-inline-images)))
  14391. ;; For without-x builds.
  14392. (declare-function image-refresh "image" (spec &optional frame))
  14393. (defcustom org-display-remote-inline-images 'skip
  14394. "How to display remote inline images.
  14395. Possible values of this option are:
  14396. skip Don't display remote images.
  14397. download Always download and display remote images.
  14398. cache Display remote images, and open them in separate buffers
  14399. for caching. Silently update the image buffer when a file
  14400. change is detected."
  14401. :group 'org-appearance
  14402. :package-version '(Org . "9.4")
  14403. :type '(choice
  14404. (const :tag "Ignore remote images" skip)
  14405. (const :tag "Always display remote images" download)
  14406. (const :tag "Display and silently update remote images" cache))
  14407. :safe #'symbolp)
  14408. (defun org--create-inline-image (file width)
  14409. "Create image located at FILE, or return nil.
  14410. WIDTH is the width of the image. The image may not be created
  14411. according to the value of `org-display-remote-inline-images'."
  14412. (let* ((remote? (file-remote-p file))
  14413. (file-or-data
  14414. (pcase org-display-remote-inline-images
  14415. ((guard (not remote?)) file)
  14416. (`download (with-temp-buffer
  14417. (set-buffer-multibyte nil)
  14418. (insert-file-contents-literally file)
  14419. (buffer-string)))
  14420. (`cache (let ((revert-without-query '(".")))
  14421. (with-current-buffer (find-file-noselect file)
  14422. (buffer-string))))
  14423. (`skip nil)
  14424. (other
  14425. (message "Invalid value of `org-display-remote-inline-images': %S"
  14426. other)
  14427. nil))))
  14428. (when file-or-data
  14429. (create-image file-or-data
  14430. (and (image-type-available-p 'imagemagick)
  14431. width
  14432. 'imagemagick)
  14433. remote?
  14434. :width width :scale 1))))
  14435. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14436. "Display inline images.
  14437. An inline image is a link which follows either of these
  14438. conventions:
  14439. 1. Its path is a file with an extension matching return value
  14440. from `image-file-name-regexp' and it has no contents.
  14441. 2. Its description consists in a single link of the previous
  14442. type. In this case, that link must be a well-formed plain
  14443. or angle link, i.e., it must have an explicit \"file\" type.
  14444. Equip each image with the key-map `image-map'.
  14445. When optional argument INCLUDE-LINKED is non-nil, also links with
  14446. a text description part will be inlined. This can be nice for
  14447. a quick look at those images, but it does not reflect what
  14448. exported files will look like.
  14449. When optional argument REFRESH is non-nil, refresh existing
  14450. images between BEG and END. This will create new image displays
  14451. only if necessary.
  14452. BEG and END define the considered part. They default to the
  14453. buffer boundaries with possible narrowing."
  14454. (interactive "P")
  14455. (when (display-graphic-p)
  14456. (unless refresh
  14457. (org-remove-inline-images)
  14458. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14459. (let ((end (or end (point-max))))
  14460. (org-with-point-at (or beg (point-min))
  14461. (let* ((case-fold-search t)
  14462. (file-extension-re (image-file-name-regexp))
  14463. (link-abbrevs (mapcar #'car
  14464. (append org-link-abbrev-alist-local
  14465. org-link-abbrev-alist)))
  14466. ;; Check absolute, relative file names and explicit
  14467. ;; "file:" links. Also check link abbreviations since
  14468. ;; some might expand to "file" links.
  14469. (file-types-re
  14470. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14471. (if (not link-abbrevs) ""
  14472. (concat "\\|" (regexp-opt link-abbrevs))))))
  14473. (while (re-search-forward file-types-re end t)
  14474. (let* ((link (org-element-lineage
  14475. (save-match-data (org-element-context))
  14476. '(link) t))
  14477. (linktype (org-element-property :type link))
  14478. (inner-start (match-beginning 1))
  14479. (path
  14480. (cond
  14481. ;; No link at point; no inline image.
  14482. ((not link) nil)
  14483. ;; File link without a description. Also handle
  14484. ;; INCLUDE-LINKED here since it should have
  14485. ;; precedence over the next case. I.e., if link
  14486. ;; contains filenames in both the path and the
  14487. ;; description, prioritize the path only when
  14488. ;; INCLUDE-LINKED is non-nil.
  14489. ((or (not (org-element-property :contents-begin link))
  14490. include-linked)
  14491. (and (or (equal "file" linktype)
  14492. (equal "attachment" linktype))
  14493. (org-element-property :path link)))
  14494. ;; Link with a description. Check if description
  14495. ;; is a filename. Even if Org doesn't have syntax
  14496. ;; for those -- clickable image -- constructs, fake
  14497. ;; them, as in `org-export-insert-image-links'.
  14498. ((not inner-start) nil)
  14499. (t
  14500. (org-with-point-at inner-start
  14501. (and (looking-at
  14502. (if (char-equal ?< (char-after inner-start))
  14503. org-link-angle-re
  14504. org-link-plain-re))
  14505. ;; File name must fill the whole
  14506. ;; description.
  14507. (= (org-element-property :contents-end link)
  14508. (match-end 0))
  14509. (match-string 2)))))))
  14510. (when (and path (string-match-p file-extension-re path))
  14511. (let ((file (if (equal "attachment" linktype)
  14512. (progn
  14513. (require 'org-attach)
  14514. (ignore-errors (org-attach-expand path)))
  14515. (expand-file-name path))))
  14516. (when (and file (file-exists-p file))
  14517. (let ((width (org-display-inline-image--width link))
  14518. (old (get-char-property-and-overlay
  14519. (org-element-property :begin link)
  14520. 'org-image-overlay)))
  14521. (if (and (car-safe old) refresh)
  14522. (image-refresh (overlay-get (cdr old) 'display))
  14523. (let ((image (org--create-inline-image file width)))
  14524. (when image
  14525. (let ((ov (make-overlay
  14526. (org-element-property :begin link)
  14527. (progn
  14528. (goto-char
  14529. (org-element-property :end link))
  14530. (skip-chars-backward " \t")
  14531. (point)))))
  14532. (overlay-put ov 'display image)
  14533. (overlay-put ov 'face 'default)
  14534. (overlay-put ov 'org-image-overlay t)
  14535. (overlay-put
  14536. ov 'modification-hooks
  14537. (list 'org-display-inline-remove-overlay))
  14538. (when (boundp 'image-map)
  14539. (overlay-put ov 'keymap image-map))
  14540. (push ov org-inline-image-overlays))))))))))))))))
  14541. (defvar visual-fill-column-width) ; Silence compiler warning
  14542. (defun org-display-inline-image--width (link)
  14543. "Determine the display width of the image LINK, in pixels.
  14544. - When `org-image-actual-width' is t, the image's pixel width is used.
  14545. - When `org-image-actual-width' is a number, that value will is used.
  14546. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14547. set (if it exists) is used to set the image width. A width of X% is
  14548. divided by 100.
  14549. If no :width attribute is given and `org-image-actual-width' is a list with
  14550. a number as the car, then that number is used as the default value.
  14551. If the value is a float between 0 and 2, it interpreted as that proportion
  14552. of the text width in the buffer."
  14553. ;; Apply `org-image-actual-width' specifications.
  14554. (cond
  14555. ((eq org-image-actual-width t) nil)
  14556. ((listp org-image-actual-width)
  14557. (let* ((case-fold-search t)
  14558. (par (org-element-lineage link '(paragraph)))
  14559. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14560. (par-end (org-element-property :post-affiliated par))
  14561. ;; Try to find an attribute providing a :width.
  14562. (attr-width
  14563. (when (and par (org-with-point-at
  14564. (org-element-property :begin par)
  14565. (re-search-forward attr-re par-end t)))
  14566. (match-string 1)))
  14567. (width
  14568. (cond
  14569. ;; Treat :width t as if `org-image-actual-width' were t.
  14570. ((string= attr-width "t") nil)
  14571. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14572. ((or (null attr-width)
  14573. (string-match-p "\\`[^0-9]" attr-width))
  14574. (car org-image-actual-width))
  14575. ;; Convert numeric widths to numbers, converting percentages.
  14576. ((string-match-p "\\`[0-9.]+%" attr-width)
  14577. (/ (string-to-number attr-width) 100.0))
  14578. (t (string-to-number attr-width)))))
  14579. (if (and (floatp width) (<= 0.0 width 2.0))
  14580. ;; A float in [0,2] should be interpereted as this portion of
  14581. ;; the text width in the window. This works well with cases like
  14582. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14583. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14584. ;; bound as cases such as 1.2\linewidth are feasible.
  14585. (round (* width
  14586. (window-pixel-width)
  14587. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14588. (or visual-fill-column-width auto-fill-function))
  14589. (when auto-fill-function fill-column)
  14590. (- (window-text-width) (line-number-display-width)))
  14591. (float (window-total-width)))))
  14592. width)))
  14593. ((numberp org-image-actual-width)
  14594. org-image-actual-width)
  14595. (t nil)))
  14596. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14597. "Remove inline-display overlay if a corresponding region is modified."
  14598. (let ((inhibit-modification-hooks t))
  14599. (when (and ov after)
  14600. (delete ov org-inline-image-overlays)
  14601. (delete-overlay ov))))
  14602. (defun org-remove-inline-images ()
  14603. "Remove inline display of images."
  14604. (interactive)
  14605. (mapc #'delete-overlay org-inline-image-overlays)
  14606. (setq org-inline-image-overlays nil))
  14607. (defvar org-self-insert-command-undo-counter 0)
  14608. (defvar org-speed-command nil)
  14609. (defun org-fix-tags-on-the-fly ()
  14610. "Align tags in headline at point.
  14611. Unlike `org-align-tags', this function does nothing if point is
  14612. either not currently on a tagged headline or on a tag."
  14613. (when (and (org-match-line org-tag-line-re)
  14614. (< (point) (match-beginning 1)))
  14615. (org-align-tags)))
  14616. (defun org-self-insert-command (N)
  14617. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14618. If the cursor is in a table looking at whitespace, the whitespace is
  14619. overwritten, and the table is not marked as requiring realignment."
  14620. (interactive "p")
  14621. (org-fold-check-before-invisible-edit 'insert)
  14622. (cond
  14623. ((and org-use-speed-commands
  14624. (let ((kv (this-command-keys-vector)))
  14625. (setq org-speed-command
  14626. (run-hook-with-args-until-success
  14627. 'org-speed-command-hook
  14628. (make-string 1 (aref kv (1- (length kv))))))))
  14629. (cond
  14630. ((commandp org-speed-command)
  14631. (setq this-command org-speed-command)
  14632. (call-interactively org-speed-command))
  14633. ((functionp org-speed-command)
  14634. (funcall org-speed-command))
  14635. ((consp org-speed-command)
  14636. (eval org-speed-command t))
  14637. (t (let (org-use-speed-commands)
  14638. (call-interactively 'org-self-insert-command)))))
  14639. ((and
  14640. (= N 1)
  14641. (not (org-region-active-p))
  14642. (org-at-table-p)
  14643. (progn
  14644. ;; Check if we blank the field, and if that triggers align.
  14645. (and (featurep 'org-table)
  14646. org-table-auto-blank-field
  14647. (memq last-command
  14648. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14649. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14650. ;; Got extra space, this field does not determine
  14651. ;; column width.
  14652. (let (org-table-may-need-update) (org-table-blank-field))
  14653. ;; No extra space, this field may determine column
  14654. ;; width.
  14655. (org-table-blank-field)))
  14656. t)
  14657. (looking-at "[^|\n]* |"))
  14658. ;; There is room for insertion without re-aligning the table.
  14659. (self-insert-command N)
  14660. (org-table-with-shrunk-field
  14661. (save-excursion
  14662. (skip-chars-forward "^|")
  14663. ;; Do not delete last space, which is
  14664. ;; `org-table-separator-space', but the regular space before
  14665. ;; it.
  14666. (delete-region (- (point) 2) (1- (point))))))
  14667. (t
  14668. (setq org-table-may-need-update t)
  14669. (self-insert-command N)
  14670. (org-fix-tags-on-the-fly)
  14671. (when org-self-insert-cluster-for-undo
  14672. (if (not (eq last-command 'org-self-insert-command))
  14673. (setq org-self-insert-command-undo-counter 1)
  14674. (if (>= org-self-insert-command-undo-counter 20)
  14675. (setq org-self-insert-command-undo-counter 1)
  14676. (and (> org-self-insert-command-undo-counter 0)
  14677. buffer-undo-list (listp buffer-undo-list)
  14678. (not (cadr buffer-undo-list)) ; remove nil entry
  14679. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14680. (setq org-self-insert-command-undo-counter
  14681. (1+ org-self-insert-command-undo-counter))))))))
  14682. (defun org-delete-backward-char (N)
  14683. "Like `delete-backward-char', insert whitespace at field end in tables.
  14684. When deleting backwards, in tables this function will insert whitespace in
  14685. front of the next \"|\" separator, to keep the table aligned. The table will
  14686. still be marked for re-alignment if the field did fill the entire column,
  14687. because, in this case the deletion might narrow the column."
  14688. (interactive "p")
  14689. (save-match-data
  14690. (org-fold-check-before-invisible-edit 'delete-backward)
  14691. (if (and (= N 1)
  14692. (not overwrite-mode)
  14693. (not (org-region-active-p))
  14694. (not (eq (char-before) ?|))
  14695. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14696. (looking-at-p ".*?|")
  14697. (org-at-table-p))
  14698. (progn (forward-char -1) (org-delete-char 1))
  14699. (backward-delete-char N)
  14700. (org-fix-tags-on-the-fly))))
  14701. (defun org-delete-char (N)
  14702. "Like `delete-char', but insert whitespace at field end in tables.
  14703. When deleting characters, in tables this function will insert whitespace in
  14704. front of the next \"|\" separator, to keep the table aligned. The table will
  14705. still be marked for re-alignment if the field did fill the entire column,
  14706. because, in this case the deletion might narrow the column."
  14707. (interactive "p")
  14708. (save-match-data
  14709. (org-fold-check-before-invisible-edit 'delete)
  14710. (cond
  14711. ((or (/= N 1)
  14712. (eq (char-after) ?|)
  14713. (save-excursion (skip-chars-backward " \t") (bolp))
  14714. (not (org-at-table-p)))
  14715. (delete-char N)
  14716. (org-fix-tags-on-the-fly))
  14717. ((looking-at ".\\(.*?\\)|")
  14718. (let* ((update? org-table-may-need-update)
  14719. (noalign (looking-at-p ".*? |")))
  14720. (delete-char 1)
  14721. (org-table-with-shrunk-field
  14722. (save-excursion
  14723. ;; Last space is `org-table-separator-space', so insert
  14724. ;; a regular one before it instead.
  14725. (goto-char (- (match-end 0) 2))
  14726. (insert " ")))
  14727. ;; If there were two spaces at the end, this field does not
  14728. ;; determine the width of the column.
  14729. (when noalign (setq org-table-may-need-update update?))))
  14730. (t
  14731. (delete-char N)))))
  14732. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  14733. (put 'org-self-insert-command 'delete-selection
  14734. (lambda ()
  14735. (not (run-hook-with-args-until-success
  14736. 'self-insert-uses-region-functions))))
  14737. (put 'orgtbl-self-insert-command 'delete-selection
  14738. (lambda ()
  14739. (not (run-hook-with-args-until-success
  14740. 'self-insert-uses-region-functions))))
  14741. (put 'org-delete-char 'delete-selection 'supersede)
  14742. (put 'org-delete-backward-char 'delete-selection 'supersede)
  14743. (put 'org-yank 'delete-selection 'yank)
  14744. (put 'org-return 'delete-selection t)
  14745. ;; Make `flyspell-mode' delay after some commands
  14746. (put 'org-self-insert-command 'flyspell-delayed t)
  14747. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  14748. (put 'org-delete-char 'flyspell-delayed t)
  14749. (put 'org-delete-backward-char 'flyspell-delayed t)
  14750. ;; Make pabbrev-mode expand after Org mode commands
  14751. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  14752. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  14753. (defun org-transpose-words ()
  14754. "Transpose words for Org.
  14755. This uses the `org-mode-transpose-word-syntax-table' syntax
  14756. table, which interprets characters in `org-emphasis-alist' as
  14757. word constituents."
  14758. (interactive)
  14759. (with-syntax-table org-mode-transpose-word-syntax-table
  14760. (call-interactively 'transpose-words)))
  14761. (defvar org-ctrl-c-ctrl-c-hook nil
  14762. "Hook for functions attaching themselves to `C-c C-c'.
  14763. This can be used to add additional functionality to the `C-c C-c'
  14764. key which executes context-dependent commands. This hook is run
  14765. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  14766. run after the last test.
  14767. Each function will be called with no arguments. The function
  14768. must check if the context is appropriate for it to act. If yes,
  14769. it should do its thing and then return a non-nil value. If the
  14770. context is wrong, just do nothing and return nil.")
  14771. (defvar org-ctrl-c-ctrl-c-final-hook nil
  14772. "Hook for functions attaching themselves to `C-c C-c'.
  14773. This can be used to add additional functionality to the `C-c C-c'
  14774. key which executes context-dependent commands. This hook is run
  14775. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  14776. before the first test.
  14777. Each function will be called with no arguments. The function
  14778. must check if the context is appropriate for it to act. If yes,
  14779. it should do its thing and then return a non-nil value. If the
  14780. context is wrong, just do nothing and return nil.")
  14781. (defvar org-tab-after-check-for-table-hook nil
  14782. "Hook for functions to attach themselves to TAB.
  14783. See `org-ctrl-c-ctrl-c-hook' for more information.
  14784. This hook runs after it has been established that the cursor is not in a
  14785. table, but before checking if the cursor is in a headline or if global cycling
  14786. should be done.
  14787. If any function in this hook returns t, not other actions like visibility
  14788. cycling will be done.")
  14789. (defvar org-tab-after-check-for-cycling-hook nil
  14790. "Hook for functions to attach themselves to TAB.
  14791. See `org-ctrl-c-ctrl-c-hook' for more information.
  14792. This hook runs after it has been established that not table field motion and
  14793. not visibility should be done because of current context. This is probably
  14794. the place where a package like yasnippets can hook in.")
  14795. (defvar org-tab-before-tab-emulation-hook nil
  14796. "Hook for functions to attach themselves to TAB.
  14797. See `org-ctrl-c-ctrl-c-hook' for more information.
  14798. This hook runs after every other options for TAB have been exhausted, but
  14799. before indentation and \t insertion takes place.")
  14800. (defvar org-metaleft-hook nil
  14801. "Hook for functions attaching themselves to `M-left'.
  14802. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14803. (defvar org-metaright-hook nil
  14804. "Hook for functions attaching themselves to `M-right'.
  14805. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14806. (defvar org-metaup-hook nil
  14807. "Hook for functions attaching themselves to `M-up'.
  14808. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14809. (defvar org-metadown-hook nil
  14810. "Hook for functions attaching themselves to `M-down'.
  14811. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14812. (defvar org-shiftmetaleft-hook nil
  14813. "Hook for functions attaching themselves to `M-S-left'.
  14814. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14815. (defvar org-shiftmetaright-hook nil
  14816. "Hook for functions attaching themselves to `M-S-right'.
  14817. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14818. (defvar org-shiftmetaup-hook nil
  14819. "Hook for functions attaching themselves to `M-S-up'.
  14820. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14821. (defvar org-shiftmetadown-hook nil
  14822. "Hook for functions attaching themselves to `M-S-down'.
  14823. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14824. (defvar org-metareturn-hook nil
  14825. "Hook for functions attaching themselves to `M-RET'.
  14826. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14827. (defvar org-shiftup-hook nil
  14828. "Hook for functions attaching themselves to `S-up'.
  14829. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14830. (defvar org-shiftup-final-hook nil
  14831. "Hook for functions attaching themselves to `S-up'.
  14832. This one runs after all other options except shift-select have been excluded.
  14833. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14834. (defvar org-shiftdown-hook nil
  14835. "Hook for functions attaching themselves to `S-down'.
  14836. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14837. (defvar org-shiftdown-final-hook nil
  14838. "Hook for functions attaching themselves to `S-down'.
  14839. This one runs after all other options except shift-select have been excluded.
  14840. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14841. (defvar org-shiftleft-hook nil
  14842. "Hook for functions attaching themselves to `S-left'.
  14843. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14844. (defvar org-shiftleft-final-hook nil
  14845. "Hook for functions attaching themselves to `S-left'.
  14846. This one runs after all other options except shift-select have been excluded.
  14847. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14848. (defvar org-shiftright-hook nil
  14849. "Hook for functions attaching themselves to `S-right'.
  14850. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14851. (defvar org-shiftright-final-hook nil
  14852. "Hook for functions attaching themselves to `S-right'.
  14853. This one runs after all other options except shift-select have been excluded.
  14854. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14855. (defun org-modifier-cursor-error ()
  14856. "Throw an error, a modified cursor command was applied in wrong context."
  14857. (user-error "This command is active in special context like tables, headlines or items"))
  14858. (defun org-shiftselect-error ()
  14859. "Throw an error because Shift-Cursor command was applied in wrong context."
  14860. (if (and (boundp 'shift-select-mode) shift-select-mode)
  14861. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  14862. (user-error "This command works only in special context like headlines or timestamps")))
  14863. (defun org-call-for-shift-select (cmd)
  14864. (let ((this-command-keys-shift-translated t))
  14865. (call-interactively cmd)))
  14866. (defun org-shifttab (&optional arg)
  14867. "Global visibility cycling or move to previous table field.
  14868. Call `org-table-previous-field' within a table.
  14869. When ARG is nil, cycle globally through visibility states.
  14870. When ARG is a numeric prefix, show contents of this level."
  14871. (interactive "P")
  14872. (cond
  14873. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  14874. ((integerp arg)
  14875. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  14876. (message "Content view to level: %d" arg)
  14877. (org-cycle-content (prefix-numeric-value arg2))
  14878. (org-cycle-show-empty-lines t)
  14879. (setq org-cycle-global-status 'overview)
  14880. (run-hook-with-args 'org-cycle-hook 'overview)))
  14881. (t (call-interactively 'org-cycle-global))))
  14882. (defun org-shiftmetaleft ()
  14883. "Promote subtree or delete table column.
  14884. Calls `org-promote-subtree', `org-outdent-item-tree', or
  14885. `org-table-delete-column', depending on context. See the
  14886. individual commands for more information."
  14887. (interactive)
  14888. (cond
  14889. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  14890. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  14891. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  14892. ((if (not (org-region-active-p)) (org-at-item-p)
  14893. (save-excursion (goto-char (region-beginning))
  14894. (org-at-item-p)))
  14895. (call-interactively 'org-outdent-item-tree))
  14896. (t (org-modifier-cursor-error))))
  14897. (defun org-shiftmetaright ()
  14898. "Demote subtree or insert table column.
  14899. Calls `org-demote-subtree', `org-indent-item-tree', or
  14900. `org-table-insert-column', depending on context. See the
  14901. individual commands for more information."
  14902. (interactive)
  14903. (cond
  14904. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  14905. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  14906. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  14907. ((if (not (org-region-active-p)) (org-at-item-p)
  14908. (save-excursion (goto-char (region-beginning))
  14909. (org-at-item-p)))
  14910. (call-interactively 'org-indent-item-tree))
  14911. (t (org-modifier-cursor-error))))
  14912. (defun org-shiftmetaup (&optional _arg)
  14913. "Drag the line at point up.
  14914. In a table, kill the current row.
  14915. On a clock timestamp, update the value of the timestamp like `S-<up>'
  14916. but also adjust the previous clocked item in the clock history.
  14917. Everywhere else, drag the line at point up."
  14918. (interactive "P")
  14919. (cond
  14920. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  14921. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  14922. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  14923. (call-interactively 'org-timestamp-up)))
  14924. (t (call-interactively 'org-drag-line-backward))))
  14925. (defun org-shiftmetadown (&optional _arg)
  14926. "Drag the line at point down.
  14927. In a table, insert an empty row at the current line.
  14928. On a clock timestamp, update the value of the timestamp like `S-<down>'
  14929. but also adjust the previous clocked item in the clock history.
  14930. Everywhere else, drag the line at point down."
  14931. (interactive "P")
  14932. (cond
  14933. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  14934. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  14935. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  14936. (call-interactively 'org-timestamp-down)))
  14937. (t (call-interactively 'org-drag-line-forward))))
  14938. (defsubst org-hidden-tree-error ()
  14939. (user-error
  14940. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  14941. (defun org-metaleft (&optional _arg)
  14942. "Promote heading, list item at point or move table column left.
  14943. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  14944. depending on context. With no specific context, calls the Emacs
  14945. default `backward-word'. See the individual commands for more
  14946. information.
  14947. This function runs the hook `org-metaleft-hook' as a first step,
  14948. and returns at first non-nil value."
  14949. (interactive "P")
  14950. (cond
  14951. ((run-hook-with-args-until-success 'org-metaleft-hook))
  14952. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  14953. ((org-with-limited-levels
  14954. (or (org-at-heading-p)
  14955. (and (org-region-active-p)
  14956. (save-excursion
  14957. (goto-char (region-beginning))
  14958. (org-at-heading-p)))))
  14959. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  14960. (call-interactively 'org-do-promote))
  14961. ;; At an inline task.
  14962. ((org-at-heading-p)
  14963. (call-interactively 'org-inlinetask-promote))
  14964. ((or (org-at-item-p)
  14965. (and (org-region-active-p)
  14966. (save-excursion
  14967. (goto-char (region-beginning))
  14968. (org-at-item-p))))
  14969. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  14970. (call-interactively 'org-outdent-item))
  14971. (t (call-interactively 'backward-word))))
  14972. (defun org-metaright (&optional _arg)
  14973. "Demote heading, list item at point or move table column right.
  14974. In front of a drawer or a block keyword, indent it correctly.
  14975. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  14976. `org-indent-drawer' or `org-indent-block' depending on context.
  14977. With no specific context, calls the Emacs default `forward-word'.
  14978. See the individual commands for more information.
  14979. This function runs the hook `org-metaright-hook' as a first step,
  14980. and returns at first non-nil value."
  14981. (interactive "P")
  14982. (cond
  14983. ((run-hook-with-args-until-success 'org-metaright-hook))
  14984. ((org-at-table-p) (call-interactively 'org-table-move-column))
  14985. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  14986. ((org-at-block-p) (call-interactively 'org-indent-block))
  14987. ((org-with-limited-levels
  14988. (or (org-at-heading-p)
  14989. (and (org-region-active-p)
  14990. (save-excursion
  14991. (goto-char (region-beginning))
  14992. (org-at-heading-p)))))
  14993. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  14994. (call-interactively 'org-do-demote))
  14995. ;; At an inline task.
  14996. ((org-at-heading-p)
  14997. (call-interactively 'org-inlinetask-demote))
  14998. ((or (org-at-item-p)
  14999. (and (org-region-active-p)
  15000. (save-excursion
  15001. (goto-char (region-beginning))
  15002. (org-at-item-p))))
  15003. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15004. (call-interactively 'org-indent-item))
  15005. (t (call-interactively 'forward-word))))
  15006. (defun org-check-for-hidden (what)
  15007. "Check if there are hidden headlines/items in the current visual line.
  15008. WHAT can be either `headlines' or `items'. If the current line is
  15009. an outline or item heading and it has a folded subtree below it,
  15010. this function returns t, nil otherwise."
  15011. (let ((re (cond
  15012. ((eq what 'headlines) org-outline-regexp-bol)
  15013. ((eq what 'items) (org-item-beginning-re))
  15014. (t (error "This should not happen"))))
  15015. beg end)
  15016. (save-excursion
  15017. (catch 'exit
  15018. (unless (org-region-active-p)
  15019. (setq beg (point-at-bol))
  15020. (beginning-of-line 2)
  15021. (while (and (not (eobp)) ;; this is like `next-line'
  15022. (org-invisible-p (1- (point))))
  15023. (beginning-of-line 2))
  15024. (setq end (point))
  15025. (goto-char beg)
  15026. (goto-char (point-at-eol))
  15027. (setq end (max end (point)))
  15028. (while (re-search-forward re end t)
  15029. (when (org-invisible-p (match-beginning 0))
  15030. (throw 'exit t))))
  15031. nil))))
  15032. (defun org-metaup (&optional _arg)
  15033. "Move subtree up or move table row up.
  15034. Calls `org-move-subtree-up' or `org-table-move-row' or
  15035. `org-move-item-up', depending on context. See the individual commands
  15036. for more information."
  15037. (interactive "P")
  15038. (cond
  15039. ((run-hook-with-args-until-success 'org-metaup-hook))
  15040. ((org-region-active-p)
  15041. (let* ((a (save-excursion
  15042. (goto-char (region-beginning))
  15043. (line-beginning-position)))
  15044. (b (save-excursion
  15045. (goto-char (region-end))
  15046. (if (bolp) (1- (point)) (line-end-position))))
  15047. (c (save-excursion
  15048. (goto-char a)
  15049. (move-beginning-of-line 0)
  15050. (point)))
  15051. (d (save-excursion
  15052. (goto-char a)
  15053. (move-end-of-line 0)
  15054. (point))))
  15055. (transpose-regions a b c d)
  15056. (goto-char c)))
  15057. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15058. ((and (featurep 'org-inlinetask)
  15059. (org-inlinetask-in-task-p))
  15060. (org-drag-element-backward))
  15061. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15062. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15063. (t (org-drag-element-backward))))
  15064. (defun org-metadown (&optional _arg)
  15065. "Move subtree down or move table row down.
  15066. Calls `org-move-subtree-down' or `org-table-move-row' or
  15067. `org-move-item-down', depending on context. See the individual
  15068. commands for more information."
  15069. (interactive "P")
  15070. (cond
  15071. ((run-hook-with-args-until-success 'org-metadown-hook))
  15072. ((org-region-active-p)
  15073. (let* ((a (save-excursion
  15074. (goto-char (region-beginning))
  15075. (line-beginning-position)))
  15076. (b (save-excursion
  15077. (goto-char (region-end))
  15078. (if (bolp) (1- (point)) (line-end-position))))
  15079. (c (save-excursion
  15080. (goto-char b)
  15081. (move-beginning-of-line (if (bolp) 1 2))
  15082. (point)))
  15083. (d (save-excursion
  15084. (goto-char b)
  15085. (move-end-of-line (if (bolp) 1 2))
  15086. (point))))
  15087. (transpose-regions a b c d)
  15088. (goto-char d)))
  15089. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15090. ((and (featurep 'org-inlinetask)
  15091. (org-inlinetask-in-task-p))
  15092. (org-drag-element-forward))
  15093. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15094. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15095. (t (org-drag-element-forward))))
  15096. (defun org-shiftup (&optional arg)
  15097. "Act on current element according to context.
  15098. Call `org-timestamp-up' or `org-priority-up', or
  15099. `org-previous-item', or `org-table-move-cell-up'. See the
  15100. individual commands for more information."
  15101. (interactive "P")
  15102. (cond
  15103. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15104. ((and org-support-shift-select (org-region-active-p))
  15105. (org-call-for-shift-select 'previous-line))
  15106. ((org-at-timestamp-p 'lax)
  15107. (call-interactively (if org-edit-timestamp-down-means-later
  15108. 'org-timestamp-down 'org-timestamp-up)))
  15109. ((and (not (eq org-support-shift-select 'always))
  15110. org-priority-enable-commands
  15111. (org-at-heading-p))
  15112. (call-interactively 'org-priority-up))
  15113. ((and (not org-support-shift-select) (org-at-item-p))
  15114. (call-interactively 'org-previous-item))
  15115. ((org-clocktable-try-shift 'up arg))
  15116. ((and (not (eq org-support-shift-select 'always))
  15117. (org-at-table-p))
  15118. (org-table-move-cell-up))
  15119. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15120. (org-support-shift-select
  15121. (org-call-for-shift-select 'previous-line))
  15122. (t (org-shiftselect-error))))
  15123. (defun org-shiftdown (&optional arg)
  15124. "Act on current element according to context.
  15125. Call `org-timestamp-down' or `org-priority-down', or
  15126. `org-next-item', or `org-table-move-cell-down'. See the
  15127. individual commands for more information."
  15128. (interactive "P")
  15129. (cond
  15130. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15131. ((and org-support-shift-select (org-region-active-p))
  15132. (org-call-for-shift-select 'next-line))
  15133. ((org-at-timestamp-p 'lax)
  15134. (call-interactively (if org-edit-timestamp-down-means-later
  15135. 'org-timestamp-up 'org-timestamp-down)))
  15136. ((and (not (eq org-support-shift-select 'always))
  15137. org-priority-enable-commands
  15138. (org-at-heading-p))
  15139. (call-interactively 'org-priority-down))
  15140. ((and (not org-support-shift-select) (org-at-item-p))
  15141. (call-interactively 'org-next-item))
  15142. ((org-clocktable-try-shift 'down arg))
  15143. ((and (not (eq org-support-shift-select 'always))
  15144. (org-at-table-p))
  15145. (org-table-move-cell-down))
  15146. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15147. (org-support-shift-select
  15148. (org-call-for-shift-select 'next-line))
  15149. (t (org-shiftselect-error))))
  15150. (defun org-shiftright (&optional arg)
  15151. "Act on the current element according to context.
  15152. This does one of the following:
  15153. - switch a timestamp at point one day into the future
  15154. - on a headline, switch to the next TODO keyword
  15155. - on an item, switch entire list to the next bullet type
  15156. - on a property line, switch to the next allowed value
  15157. - on a clocktable definition line, move time block into the future
  15158. - in a table, move a single cell right"
  15159. (interactive "P")
  15160. (cond
  15161. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15162. ((and org-support-shift-select (org-region-active-p))
  15163. (org-call-for-shift-select 'forward-char))
  15164. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15165. ((and (not (eq org-support-shift-select 'always))
  15166. (org-at-heading-p))
  15167. (let ((org-inhibit-logging
  15168. (not org-treat-S-cursor-todo-selection-as-state-change))
  15169. (org-inhibit-blocking
  15170. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15171. (org-call-with-arg 'org-todo 'right)))
  15172. ((or (and org-support-shift-select
  15173. (not (eq org-support-shift-select 'always))
  15174. (org-at-item-bullet-p))
  15175. (and (not org-support-shift-select) (org-at-item-p)))
  15176. (org-call-with-arg 'org-cycle-list-bullet nil))
  15177. ((and (not (eq org-support-shift-select 'always))
  15178. (org-at-property-p))
  15179. (call-interactively 'org-property-next-allowed-value))
  15180. ((org-clocktable-try-shift 'right arg))
  15181. ((and (not (eq org-support-shift-select 'always))
  15182. (org-at-table-p))
  15183. (org-table-move-cell-right))
  15184. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15185. (org-support-shift-select
  15186. (org-call-for-shift-select 'forward-char))
  15187. (t (org-shiftselect-error))))
  15188. (defun org-shiftleft (&optional arg)
  15189. "Act on current element according to context.
  15190. This does one of the following:
  15191. - switch a timestamp at point one day into the past
  15192. - on a headline, switch to the previous TODO keyword.
  15193. - on an item, switch entire list to the previous bullet type
  15194. - on a property line, switch to the previous allowed value
  15195. - on a clocktable definition line, move time block into the past
  15196. - in a table, move a single cell left"
  15197. (interactive "P")
  15198. (cond
  15199. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15200. ((and org-support-shift-select (org-region-active-p))
  15201. (org-call-for-shift-select 'backward-char))
  15202. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15203. ((and (not (eq org-support-shift-select 'always))
  15204. (org-at-heading-p))
  15205. (let ((org-inhibit-logging
  15206. (not org-treat-S-cursor-todo-selection-as-state-change))
  15207. (org-inhibit-blocking
  15208. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15209. (org-call-with-arg 'org-todo 'left)))
  15210. ((or (and org-support-shift-select
  15211. (not (eq org-support-shift-select 'always))
  15212. (org-at-item-bullet-p))
  15213. (and (not org-support-shift-select) (org-at-item-p)))
  15214. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15215. ((and (not (eq org-support-shift-select 'always))
  15216. (org-at-property-p))
  15217. (call-interactively 'org-property-previous-allowed-value))
  15218. ((org-clocktable-try-shift 'left arg))
  15219. ((and (not (eq org-support-shift-select 'always))
  15220. (org-at-table-p))
  15221. (org-table-move-cell-left))
  15222. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15223. (org-support-shift-select
  15224. (org-call-for-shift-select 'backward-char))
  15225. (t (org-shiftselect-error))))
  15226. (defun org-shiftcontrolright ()
  15227. "Switch to next TODO set."
  15228. (interactive)
  15229. (cond
  15230. ((and org-support-shift-select (org-region-active-p))
  15231. (org-call-for-shift-select 'forward-word))
  15232. ((and (not (eq org-support-shift-select 'always))
  15233. (org-at-heading-p))
  15234. (org-call-with-arg 'org-todo 'nextset))
  15235. (org-support-shift-select
  15236. (org-call-for-shift-select 'forward-word))
  15237. (t (org-shiftselect-error))))
  15238. (defun org-shiftcontrolleft ()
  15239. "Switch to previous TODO set."
  15240. (interactive)
  15241. (cond
  15242. ((and org-support-shift-select (org-region-active-p))
  15243. (org-call-for-shift-select 'backward-word))
  15244. ((and (not (eq org-support-shift-select 'always))
  15245. (org-at-heading-p))
  15246. (org-call-with-arg 'org-todo 'previousset))
  15247. (org-support-shift-select
  15248. (org-call-for-shift-select 'backward-word))
  15249. (t (org-shiftselect-error))))
  15250. (defun org-shiftcontrolup (&optional n)
  15251. "Change timestamps synchronously up in CLOCK log lines.
  15252. Optional argument N tells to change by that many units."
  15253. (interactive "P")
  15254. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15255. (let (org-support-shift-select)
  15256. (org-clock-timestamps-up n))
  15257. (user-error "Not at a clock log")))
  15258. (defun org-shiftcontroldown (&optional n)
  15259. "Change timestamps synchronously down in CLOCK log lines.
  15260. Optional argument N tells to change by that many units."
  15261. (interactive "P")
  15262. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15263. (let (org-support-shift-select)
  15264. (org-clock-timestamps-down n))
  15265. (user-error "Not at a clock log")))
  15266. (defun org-increase-number-at-point (&optional inc)
  15267. "Increment the number at point.
  15268. With an optional prefix numeric argument INC, increment using
  15269. this numeric value."
  15270. (interactive "p")
  15271. (if (not (number-at-point))
  15272. (user-error "Not on a number")
  15273. (unless inc (setq inc 1))
  15274. (let ((pos (point))
  15275. (beg (skip-chars-backward "-+^/*0-9eE."))
  15276. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15277. (setq nap (buffer-substring-no-properties
  15278. (+ pos beg) (+ pos beg end)))
  15279. (delete-region (+ pos beg) (+ pos beg end))
  15280. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15281. (when (org-at-table-p)
  15282. (org-table-align)
  15283. (org-table-end-of-field 1))))
  15284. (defun org-decrease-number-at-point (&optional inc)
  15285. "Decrement the number at point.
  15286. With an optional prefix numeric argument INC, decrement using
  15287. this numeric value."
  15288. (interactive "p")
  15289. (org-increase-number-at-point (- (or inc 1))))
  15290. (defun org-ctrl-c-ret ()
  15291. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15292. (interactive)
  15293. (cond
  15294. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15295. (t (call-interactively 'org-insert-heading))))
  15296. (defun org-copy-visible (beg end)
  15297. "Copy the visible parts of the region."
  15298. (interactive "r")
  15299. (let ((result ""))
  15300. (while (/= beg end)
  15301. (if (eq org-fold-core-style 'text-properties)
  15302. (progn
  15303. (while (org-invisible-p beg)
  15304. (setq beg (org-fold-next-visibility-change beg end)))
  15305. (let ((next (org-fold-next-visibility-change beg end)))
  15306. (setq result (concat result (buffer-substring beg next)))
  15307. (setq beg next)))
  15308. (when (invisible-p beg)
  15309. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15310. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15311. (setq result (concat result (buffer-substring beg next)))
  15312. (setq beg next))))
  15313. (setq deactivate-mark t)
  15314. (kill-new result)
  15315. (message "Visible strings have been copied to the kill ring.")))
  15316. (defun org-copy-special ()
  15317. "Copy region in table or copy current subtree.
  15318. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15319. context. See the individual commands for more information."
  15320. (interactive)
  15321. (call-interactively
  15322. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15323. (defun org-cut-special ()
  15324. "Cut region in table or cut current subtree.
  15325. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15326. context. See the individual commands for more information."
  15327. (interactive)
  15328. (call-interactively
  15329. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15330. (defun org-paste-special (arg)
  15331. "Paste rectangular region into table, or past subtree relative to level.
  15332. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15333. See the individual commands for more information."
  15334. (interactive "P")
  15335. (if (org-at-table-p)
  15336. (org-table-paste-rectangle)
  15337. (org-paste-subtree arg)))
  15338. (defun org-edit-special (&optional arg)
  15339. "Call a special editor for the element at point.
  15340. When at a table, call the formula editor with `org-table-edit-formulas'.
  15341. When in a source code block, call `org-edit-src-code'.
  15342. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15343. When in an export block, call `org-edit-export-block'.
  15344. When in a LaTeX environment, call `org-edit-latex-environment'.
  15345. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15346. When at a footnote reference, call `org-edit-footnote-reference'.
  15347. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15348. When at an active timestamp, call `org-time-stamp'.
  15349. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15350. On a link, call `ffap' to visit the link at point.
  15351. Otherwise, return a user error."
  15352. (interactive "P")
  15353. (let ((element (org-element-at-point)))
  15354. (barf-if-buffer-read-only)
  15355. (pcase (org-element-type element)
  15356. (`src-block
  15357. (if (not arg) (org-edit-src-code)
  15358. (let* ((info (org-babel-get-src-block-info))
  15359. (lang (nth 0 info))
  15360. (params (nth 2 info))
  15361. (session (cdr (assq :session params))))
  15362. (if (not session) (org-edit-src-code)
  15363. ;; At a source block with a session and function called
  15364. ;; with an ARG: switch to the buffer related to the
  15365. ;; inferior process.
  15366. (switch-to-buffer
  15367. (funcall (intern (concat "org-babel-prep-session:" lang))
  15368. session params))))))
  15369. (`keyword
  15370. (unless (member (org-element-property :key element)
  15371. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15372. (user-error "No special environment to edit here"))
  15373. (let ((value (org-element-property :value element)))
  15374. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15375. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15376. (or (match-string 1 value)
  15377. (match-string 0 value)))))
  15378. (when (org-url-p file)
  15379. (user-error "Files located with a URL cannot be edited"))
  15380. (org-link-open-from-string
  15381. (format "[[%s]]" (expand-file-name file))))))
  15382. (`table
  15383. (if (eq (org-element-property :type element) 'table.el)
  15384. (org-edit-table.el)
  15385. (call-interactively 'org-table-edit-formulas)))
  15386. ;; Only Org tables contain `table-row' type elements.
  15387. (`table-row (call-interactively 'org-table-edit-formulas))
  15388. (`example-block (org-edit-src-code))
  15389. (`export-block (org-edit-export-block))
  15390. (`fixed-width (org-edit-fixed-width-region))
  15391. (`latex-environment (org-edit-latex-environment))
  15392. (`planning
  15393. (let ((proplist (cadr element)))
  15394. (mapc #'call-interactively
  15395. (remq nil
  15396. (list
  15397. (when (plist-get proplist :deadline) #'org-deadline)
  15398. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15399. (_
  15400. ;; No notable element at point. Though, we may be at a link or
  15401. ;; a footnote reference, which are objects. Thus, scan deeper.
  15402. (let ((context (org-element-context element)))
  15403. (pcase (org-element-type context)
  15404. (`footnote-reference (org-edit-footnote-reference))
  15405. (`inline-src-block (org-edit-inline-src-code))
  15406. (`latex-fragment (org-edit-latex-fragment))
  15407. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15408. (call-interactively #'org-time-stamp-inactive)
  15409. (call-interactively #'org-time-stamp)))
  15410. (`link (call-interactively #'ffap))
  15411. (_ (user-error "No special environment to edit here"))))))))
  15412. (defun org-ctrl-c-ctrl-c (&optional arg)
  15413. "Set tags in headline, or update according to changed information at point.
  15414. This command does many different things, depending on context:
  15415. - If column view is active, in agenda or org buffers, quit it.
  15416. - If there are highlights, remove them.
  15417. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15418. this is what we do.
  15419. - If the cursor is on a statistics cookie, update it.
  15420. - If the cursor is in a headline, in an agenda or an org buffer,
  15421. prompt for tags and insert them into the current line, aligned
  15422. to `org-tags-column'. When called with prefix arg, realign all
  15423. tags in the current buffer.
  15424. - If the cursor is in one of the special #+KEYWORD lines, this
  15425. triggers scanning the buffer for these lines and updating the
  15426. information.
  15427. - If the cursor is inside a table, realign the table. This command
  15428. works even if the automatic table editor has been turned off.
  15429. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15430. the entire table.
  15431. - If the cursor is at a footnote reference or definition, jump to
  15432. the corresponding definition or references, respectively.
  15433. - If the cursor is a the beginning of a dynamic block, update it.
  15434. - If the current buffer is a capture buffer, close note and file it.
  15435. - If the cursor is on a <<<target>>>, update radio targets and
  15436. corresponding links in this buffer.
  15437. - If the cursor is on a numbered item in a plain list, renumber the
  15438. ordered list.
  15439. - If the cursor is on a checkbox, toggle it.
  15440. - If the cursor is on a code block, evaluate it. The variable
  15441. `org-confirm-babel-evaluate' can be used to control prompting
  15442. before code block evaluation, by default every code block
  15443. evaluation requires confirmation. Code block evaluation can be
  15444. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15445. (interactive "P")
  15446. (cond
  15447. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15448. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15449. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15450. (org-remove-occur-highlights)
  15451. (message "Temporary highlights/overlays removed from current buffer"))
  15452. ((and (local-variable-p 'org-finish-function)
  15453. (fboundp org-finish-function))
  15454. (funcall org-finish-function))
  15455. ((org-babel-hash-at-point))
  15456. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15457. (t
  15458. (let* ((context
  15459. (org-element-lineage
  15460. (org-element-context)
  15461. ;; Limit to supported contexts.
  15462. '(babel-call clock dynamic-block footnote-definition
  15463. footnote-reference inline-babel-call inline-src-block
  15464. inlinetask item keyword node-property paragraph
  15465. plain-list planning property-drawer radio-target
  15466. src-block statistics-cookie table table-cell table-row
  15467. timestamp)
  15468. t))
  15469. (radio-list-p (org-at-radio-list-p))
  15470. (type (org-element-type context)))
  15471. ;; For convenience: at the first line of a paragraph on the same
  15472. ;; line as an item, apply function on that item instead.
  15473. (when (eq type 'paragraph)
  15474. (let ((parent (org-element-property :parent context)))
  15475. (when (and (eq (org-element-type parent) 'item)
  15476. (= (line-beginning-position)
  15477. (org-element-property :begin parent)))
  15478. (setq context parent)
  15479. (setq type 'item))))
  15480. ;; Act according to type of element or object at point.
  15481. ;;
  15482. ;; Do nothing on a blank line, except if it is contained in
  15483. ;; a source block. Hence, we first check if point is in such
  15484. ;; a block and then if it is at a blank line.
  15485. (pcase type
  15486. ((or `inline-src-block `src-block)
  15487. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15488. (org-babel-eval-wipe-error-buffer)
  15489. (org-babel-execute-src-block
  15490. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15491. ((guard (org-match-line "[ \t]*$"))
  15492. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15493. (user-error
  15494. (substitute-command-keys
  15495. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15496. ((or `babel-call `inline-babel-call)
  15497. (let ((info (org-babel-lob-get-info context)))
  15498. (when info (org-babel-execute-src-block nil info))))
  15499. (`clock (org-clock-update-time-maybe))
  15500. (`dynamic-block
  15501. (save-excursion
  15502. (goto-char (org-element-property :post-affiliated context))
  15503. (org-update-dblock)))
  15504. (`footnote-definition
  15505. (goto-char (org-element-property :post-affiliated context))
  15506. (call-interactively 'org-footnote-action))
  15507. (`footnote-reference (call-interactively #'org-footnote-action))
  15508. ((or `headline `inlinetask)
  15509. (save-excursion (goto-char (org-element-property :begin context))
  15510. (call-interactively #'org-set-tags-command)))
  15511. (`item
  15512. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15513. ;; unconditionally, whereas `C-u' will toggle its presence.
  15514. ;; Without a universal argument, if the item has a checkbox,
  15515. ;; toggle it. Otherwise repair the list.
  15516. (if (or radio-list-p
  15517. (and (boundp org-list-checkbox-radio-mode)
  15518. org-list-checkbox-radio-mode))
  15519. (org-toggle-radio-button arg)
  15520. (let* ((box (org-element-property :checkbox context))
  15521. (struct (org-element-property :structure context))
  15522. (old-struct (copy-tree struct))
  15523. (parents (org-list-parents-alist struct))
  15524. (prevs (org-list-prevs-alist struct))
  15525. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15526. (org-list-set-checkbox
  15527. (org-element-property :begin context) struct
  15528. (cond ((equal arg '(16)) "[-]")
  15529. ((and (not box) (equal arg '(4))) "[ ]")
  15530. ((or (not box) (equal arg '(4))) nil)
  15531. ((eq box 'on) "[ ]")
  15532. (t "[X]")))
  15533. ;; Mimic `org-list-write-struct' but with grabbing a return
  15534. ;; value from `org-list-struct-fix-box'.
  15535. (org-list-struct-fix-ind struct parents 2)
  15536. (org-list-struct-fix-item-end struct)
  15537. (org-list-struct-fix-bul struct prevs)
  15538. (org-list-struct-fix-ind struct parents)
  15539. (let ((block-item
  15540. (org-list-struct-fix-box struct parents prevs orderedp)))
  15541. (if (and box (equal struct old-struct))
  15542. (if (equal arg '(16))
  15543. (message "Checkboxes already reset")
  15544. (user-error "Cannot toggle this checkbox: %s"
  15545. (if (eq box 'on)
  15546. "all subitems checked"
  15547. "unchecked subitems")))
  15548. (org-list-struct-apply-struct struct old-struct)
  15549. (org-update-checkbox-count-maybe))
  15550. (when block-item
  15551. (message "Checkboxes were removed due to empty box at line %d"
  15552. (org-current-line block-item)))))))
  15553. (`plain-list
  15554. ;; At a plain list, with a double C-u argument, set
  15555. ;; checkboxes of each item to "[-]", whereas a single one
  15556. ;; will toggle their presence according to the state of the
  15557. ;; first item in the list. Without an argument, repair the
  15558. ;; list.
  15559. (if (or radio-list-p
  15560. (and (boundp org-list-checkbox-radio-mode)
  15561. org-list-checkbox-radio-mode))
  15562. (org-toggle-radio-button arg)
  15563. (let* ((begin (org-element-property :contents-begin context))
  15564. (struct (org-element-property :structure context))
  15565. (old-struct (copy-tree struct))
  15566. (first-box (save-excursion
  15567. (goto-char begin)
  15568. (looking-at org-list-full-item-re)
  15569. (match-string-no-properties 3)))
  15570. (new-box (cond ((equal arg '(16)) "[-]")
  15571. ((equal arg '(4)) (unless first-box "[ ]"))
  15572. ((equal first-box "[X]") "[ ]")
  15573. (t "[X]"))))
  15574. (cond
  15575. (arg
  15576. (dolist (pos
  15577. (org-list-get-all-items
  15578. begin struct (org-list-prevs-alist struct)))
  15579. (org-list-set-checkbox pos struct new-box)))
  15580. ((and first-box (eq (point) begin))
  15581. ;; For convenience, when point is at bol on the first
  15582. ;; item of the list and no argument is provided, simply
  15583. ;; toggle checkbox of that item, if any.
  15584. (org-list-set-checkbox begin struct new-box)))
  15585. (when (equal
  15586. (org-list-write-struct
  15587. struct (org-list-parents-alist struct) old-struct)
  15588. old-struct)
  15589. (message "Cannot update this checkbox"))
  15590. (org-update-checkbox-count-maybe))))
  15591. (`keyword
  15592. (let ((org-inhibit-startup-visibility-stuff t)
  15593. (org-startup-align-all-tables nil))
  15594. (when (boundp 'org-table-coordinate-overlays)
  15595. (mapc #'delete-overlay org-table-coordinate-overlays)
  15596. (setq org-table-coordinate-overlays nil))
  15597. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15598. (message "Local setup has been refreshed"))
  15599. ((or `property-drawer `node-property)
  15600. (call-interactively #'org-property-action))
  15601. (`radio-target
  15602. (call-interactively #'org-update-radio-target-regexp))
  15603. (`statistics-cookie
  15604. (call-interactively #'org-update-statistics-cookies))
  15605. ((or `table `table-cell `table-row)
  15606. ;; At a table, generate a plot if on the #+plot line,
  15607. ;; recalculate every field and align it otherwise. Also
  15608. ;; send the table if necessary.
  15609. (cond
  15610. ((and (org-match-line "[ \t]*#\\+plot:")
  15611. (< (point) (org-element-property :post-affiliated context)))
  15612. (org-plot/gnuplot))
  15613. ;; If the table has a `table.el' type, just give up.
  15614. ((eq (org-element-property :type context) 'table.el)
  15615. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15616. Use `\\[org-edit-special]' to edit table.el tables")))
  15617. ;; At a table row or cell, maybe recalculate line but always
  15618. ;; align table.
  15619. ((or (eq type 'table)
  15620. ;; Check if point is at a TBLFM line.
  15621. (and (eq type 'table-row)
  15622. (= (point) (org-element-property :end context))))
  15623. (save-excursion
  15624. (if (org-at-TBLFM-p)
  15625. (progn (require 'org-table)
  15626. (org-table-calc-current-TBLFM))
  15627. (goto-char (org-element-property :contents-begin context))
  15628. (org-call-with-arg 'org-table-recalculate (or arg t))
  15629. (orgtbl-send-table 'maybe))))
  15630. (t
  15631. (org-table-maybe-eval-formula)
  15632. (cond (arg (call-interactively #'org-table-recalculate))
  15633. ((org-table-maybe-recalculate-line))
  15634. (t (org-table-align))))))
  15635. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15636. (org-timestamp-change 0 'day))
  15637. ((and `nil (guard (org-at-heading-p)))
  15638. ;; When point is on an unsupported object type, we can miss
  15639. ;; the fact that it also is at a heading. Handle it here.
  15640. (call-interactively #'org-set-tags-command))
  15641. ((guard
  15642. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15643. (_
  15644. (user-error
  15645. (substitute-command-keys
  15646. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15647. (defun org-mode-restart ()
  15648. "Restart `org-mode'."
  15649. (interactive)
  15650. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15651. (funcall major-mode)
  15652. (hack-local-variables)
  15653. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15654. (org-indent-mode -1))
  15655. (org-reset-file-cache))
  15656. (message "%s restarted" major-mode))
  15657. (defun org-kill-note-or-show-branches ()
  15658. "Abort storing current note, or show just branches."
  15659. (interactive)
  15660. (cond (org-finish-function
  15661. (let ((org-note-abort t)) (funcall org-finish-function)))
  15662. ((org-before-first-heading-p)
  15663. (org-fold-show-branches-buffer)
  15664. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15665. (t
  15666. (let ((beg (progn (org-back-to-heading) (point)))
  15667. (end (save-excursion (org-end-of-subtree t t) (point))))
  15668. (org-fold-hide-subtree)
  15669. (org-fold-show-branches)
  15670. (org-fold-hide-archived-subtrees beg end)))))
  15671. (defun org-delete-indentation (&optional arg)
  15672. "Join current line to previous and fix whitespace at join.
  15673. If previous line is a headline add to headline title. Otherwise
  15674. the function calls `delete-indentation'.
  15675. I.e. with a non-nil optional argument, join the line with the
  15676. following one. If there is a region then join the lines in that
  15677. region."
  15678. (interactive "*P")
  15679. (if (save-excursion
  15680. (beginning-of-line (if arg 1 0))
  15681. (let ((case-fold-search nil))
  15682. (looking-at org-complex-heading-regexp)))
  15683. ;; At headline.
  15684. (let ((tags-column (when (match-beginning 5)
  15685. (save-excursion (goto-char (match-beginning 5))
  15686. (current-column))))
  15687. (string (concat " " (progn (when arg (forward-line 1))
  15688. (org-trim (delete-and-extract-region
  15689. (line-beginning-position)
  15690. (line-end-position)))))))
  15691. (unless (bobp) (delete-region (point) (1- (point))))
  15692. (goto-char (or (match-end 4)
  15693. (match-beginning 5)
  15694. (match-end 0)))
  15695. (skip-chars-backward " \t")
  15696. (save-excursion (insert string))
  15697. ;; Adjust alignment of tags.
  15698. (cond
  15699. ((not tags-column)) ;no tags
  15700. (org-auto-align-tags (org-align-tags))
  15701. (t (org--align-tags-here tags-column)))) ;preserve tags column
  15702. (let ((current-prefix-arg arg))
  15703. (call-interactively #'delete-indentation))))
  15704. (defun org-open-line (n)
  15705. "Insert a new row in tables, call `open-line' elsewhere.
  15706. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  15707. As a special case, when a document starts with a table, allow to
  15708. call `open-line' on the very first character."
  15709. (interactive "*p")
  15710. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  15711. (org-table-insert-row)
  15712. (open-line n)))
  15713. (defun org--newline (indent arg interactive)
  15714. "Call `newline-and-indent' or just `newline'.
  15715. If INDENT is non-nil, call `newline-and-indent' with ARG to
  15716. indent unconditionally; otherwise, call `newline' with ARG and
  15717. INTERACTIVE, which can trigger indentation if
  15718. `electric-indent-mode' is enabled."
  15719. (if indent
  15720. (org-newline-and-indent arg)
  15721. (newline arg interactive)))
  15722. (defun org-return (&optional indent arg interactive)
  15723. "Goto next table row or insert a newline.
  15724. Calls `org-table-next-row' or `newline', depending on context.
  15725. When optional INDENT argument is non-nil, call
  15726. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  15727. and INTERACTIVE.
  15728. When `org-return-follows-link' is non-nil and point is on
  15729. a timestamp or a link, call `org-open-at-point'. However, it
  15730. will not happen if point is in a table or on a \"dead\"
  15731. object (e.g., within a comment). In these case, you need to use
  15732. `org-open-at-point' directly."
  15733. (interactive "i\nP\np")
  15734. (let* ((context (if org-return-follows-link (org-element-context)
  15735. (org-element-at-point)))
  15736. (element-type (org-element-type context)))
  15737. (cond
  15738. ;; In a table, call `org-table-next-row'. However, before first
  15739. ;; column or after last one, split the table.
  15740. ((or (and (eq 'table element-type)
  15741. (not (eq 'table.el (org-element-property :type context)))
  15742. (>= (point) (org-element-property :contents-begin context))
  15743. (< (point) (org-element-property :contents-end context)))
  15744. (org-element-lineage context '(table-row table-cell) t))
  15745. (if (or (looking-at-p "[ \t]*$")
  15746. (save-excursion (skip-chars-backward " \t") (bolp)))
  15747. (insert "\n")
  15748. (org-table-justify-field-maybe)
  15749. (call-interactively #'org-table-next-row)))
  15750. ;; On a link or a timestamp, call `org-open-at-point' if
  15751. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  15752. ;; locations, e.g., in a comment, as `org-open-at-point'.
  15753. ((and org-return-follows-link
  15754. (or (and (eq 'link element-type)
  15755. ;; Ensure point is not on the white spaces after
  15756. ;; the link.
  15757. (let ((origin (point)))
  15758. (org-with-point-at (org-element-property :end context)
  15759. (skip-chars-backward " \t")
  15760. (> (point) origin))))
  15761. (org-in-regexp org-ts-regexp-both nil t)
  15762. (org-in-regexp org-tsr-regexp-both nil t)
  15763. (org-in-regexp org-link-any-re nil t)))
  15764. (call-interactively #'org-open-at-point))
  15765. ;; Insert newline in heading, but preserve tags.
  15766. ((and (not (bolp))
  15767. (let ((case-fold-search nil))
  15768. (org-match-line org-complex-heading-regexp)))
  15769. ;; At headline. Split line. However, if point is on keyword,
  15770. ;; priority cookie or tags, do not break any of them: add
  15771. ;; a newline after the headline instead.
  15772. (let ((tags-column (and (match-beginning 5)
  15773. (save-excursion (goto-char (match-beginning 5))
  15774. (current-column))))
  15775. (string
  15776. (when (and (match-end 4) (org-point-in-group (point) 4))
  15777. (delete-and-extract-region (point) (match-end 4)))))
  15778. ;; Adjust tag alignment.
  15779. (cond
  15780. ((not (and tags-column string)))
  15781. (org-auto-align-tags (org-align-tags))
  15782. (t (org--align-tags-here tags-column))) ;preserve tags column
  15783. (end-of-line)
  15784. (org-fold-show-entry)
  15785. (org--newline indent arg interactive)
  15786. (when string (save-excursion (insert (org-trim string))))))
  15787. ;; In a list, make sure indenting keeps trailing text within.
  15788. ((and (not (eolp))
  15789. (org-element-lineage context '(item)))
  15790. (let ((trailing-data
  15791. (delete-and-extract-region (point) (line-end-position))))
  15792. (org--newline indent arg interactive)
  15793. (save-excursion (insert trailing-data))))
  15794. (t
  15795. ;; Do not auto-fill when point is in an Org property drawer.
  15796. (let ((auto-fill-function (and (not (org-at-property-p))
  15797. auto-fill-function)))
  15798. (org--newline indent arg interactive))))))
  15799. (defun org-return-and-maybe-indent ()
  15800. "Goto next table row, or insert a newline, maybe indented.
  15801. Call `org-table-next-row' or `org-return', depending on context.
  15802. See the individual commands for more information.
  15803. When inserting a newline, if `org-adapt-indentation' is t:
  15804. indent the line if `electric-indent-mode' is disabled, don't
  15805. indent it if it is enabled."
  15806. (interactive)
  15807. (org-return (not electric-indent-mode)))
  15808. (defun org-ctrl-c-tab (&optional arg)
  15809. "Toggle columns width in a table, or show children.
  15810. Call `org-table-toggle-column-width' if point is in a table.
  15811. Otherwise provide a compact view of the children. ARG is the
  15812. level to hide."
  15813. (interactive "p")
  15814. (cond
  15815. ((org-at-table-p)
  15816. (call-interactively #'org-table-toggle-column-width))
  15817. ((org-before-first-heading-p)
  15818. (save-excursion
  15819. (org-fold-flag-above-first-heading)
  15820. (org-fold-hide-sublevels (or arg 1))))
  15821. (t
  15822. (org-fold-hide-subtree)
  15823. (org-fold-show-children arg))))
  15824. (defun org-ctrl-c-star ()
  15825. "Compute table, or change heading status of lines.
  15826. Calls `org-table-recalculate' or `org-toggle-heading',
  15827. depending on context."
  15828. (interactive)
  15829. (cond
  15830. ((org-at-table-p)
  15831. (call-interactively 'org-table-recalculate))
  15832. (t
  15833. ;; Convert all lines in region to list items
  15834. (call-interactively 'org-toggle-heading))))
  15835. (defun org-ctrl-c-minus ()
  15836. "Insert separator line in table or modify bullet status of line.
  15837. Also turns a plain line or a region of lines into list items.
  15838. Calls `org-table-insert-hline', `org-toggle-item', or
  15839. `org-cycle-list-bullet', depending on context."
  15840. (interactive)
  15841. (cond
  15842. ((org-at-table-p)
  15843. (call-interactively 'org-table-insert-hline))
  15844. ((org-region-active-p)
  15845. (call-interactively 'org-toggle-item))
  15846. ((org-in-item-p)
  15847. (call-interactively 'org-cycle-list-bullet))
  15848. (t
  15849. (call-interactively 'org-toggle-item))))
  15850. (defun org-toggle-heading (&optional nstars)
  15851. "Convert headings to normal text, or items or text to headings.
  15852. If there is no active region, only convert the current line.
  15853. With a `\\[universal-argument]' prefix, convert the whole list at
  15854. point into heading.
  15855. In a region:
  15856. - If the first non blank line is a headline, remove the stars
  15857. from all headlines in the region.
  15858. - If it is a normal line, turn each and every normal line (i.e.,
  15859. not an heading or an item) in the region into headings. If you
  15860. want to convert only the first line of this region, use one
  15861. universal prefix argument.
  15862. - If it is a plain list item, turn all plain list items into headings.
  15863. When converting a line into a heading, the number of stars is chosen
  15864. such that the lines become children of the current entry. However,
  15865. when a numeric prefix argument is given, its value determines the
  15866. number of stars to add."
  15867. (interactive "P")
  15868. (let ((skip-blanks
  15869. ;; Return beginning of first non-blank line, starting from
  15870. ;; line at POS.
  15871. (lambda (pos)
  15872. (save-excursion
  15873. (goto-char pos)
  15874. (while (org-at-comment-p) (forward-line))
  15875. (skip-chars-forward " \r\t\n")
  15876. (point-at-bol))))
  15877. beg end toggled)
  15878. ;; Determine boundaries of changes. If a universal prefix has
  15879. ;; been given, put the list in a region. If region ends at a bol,
  15880. ;; do not consider the last line to be in the region.
  15881. (when (and current-prefix-arg (org-at-item-p))
  15882. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  15883. (org-mark-element))
  15884. (if (org-region-active-p)
  15885. (setq beg (funcall skip-blanks (region-beginning))
  15886. end (copy-marker (save-excursion
  15887. (goto-char (region-end))
  15888. (if (bolp) (point) (point-at-eol)))))
  15889. (setq beg (funcall skip-blanks (point-at-bol))
  15890. end (copy-marker (point-at-eol))))
  15891. ;; Ensure inline tasks don't count as headings.
  15892. (org-with-limited-levels
  15893. (save-excursion
  15894. (goto-char beg)
  15895. (cond
  15896. ;; Case 1. Started at an heading: de-star headings.
  15897. ((org-at-heading-p)
  15898. (while (< (point) end)
  15899. (when (org-at-heading-p)
  15900. (looking-at org-outline-regexp) (replace-match "")
  15901. (setq toggled t))
  15902. (forward-line)))
  15903. ;; Case 2. Started at an item: change items into headlines.
  15904. ;; One star will be added by `org-list-to-subtree'.
  15905. ((org-at-item-p)
  15906. (while (< (point) end)
  15907. (when (org-at-item-p)
  15908. ;; Pay attention to cases when region ends before list.
  15909. (let* ((struct (org-list-struct))
  15910. (list-end
  15911. (min (org-list-get-bottom-point struct) (1+ end))))
  15912. (save-restriction
  15913. (narrow-to-region (point) list-end)
  15914. (insert (org-list-to-subtree
  15915. (org-list-to-lisp t)
  15916. (pcase (org-current-level)
  15917. (`nil 1)
  15918. (l (1+ (org-reduced-level l)))))
  15919. "\n")))
  15920. (setq toggled t))
  15921. (forward-line)))
  15922. ;; Case 3. Started at normal text: make every line an heading,
  15923. ;; skipping headlines and items.
  15924. (t (let* ((stars
  15925. (make-string
  15926. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  15927. (add-stars
  15928. (cond (nstars "") ; stars from prefix only
  15929. ((equal stars "") "*") ; before first heading
  15930. (org-odd-levels-only "**") ; inside heading, odd
  15931. (t "*"))) ; inside heading, oddeven
  15932. (rpl (concat stars add-stars " "))
  15933. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  15934. (while (< (point) (if (equal nstars '(4)) lend end))
  15935. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  15936. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  15937. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  15938. (forward-line)))))))
  15939. (unless toggled (message "Cannot toggle heading from here"))))
  15940. (defun org-meta-return (&optional arg)
  15941. "Insert a new heading or wrap a region in a table.
  15942. Calls `org-insert-heading', `org-insert-item' or
  15943. `org-table-wrap-region', depending on context. When called with
  15944. an argument, unconditionally call `org-insert-heading'."
  15945. (interactive "P")
  15946. (org-fold-check-before-invisible-edit 'insert)
  15947. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  15948. (call-interactively (cond (arg #'org-insert-heading)
  15949. ((org-at-table-p) #'org-table-wrap-region)
  15950. ((org-in-item-p) #'org-insert-item)
  15951. (t #'org-insert-heading)))))
  15952. ;;; Menu entries
  15953. (defsubst org-in-subtree-not-table-p ()
  15954. "Are we in a subtree and not in a table?"
  15955. (and (not (org-before-first-heading-p))
  15956. (not (org-at-table-p))))
  15957. ;; Define the Org mode menus
  15958. (easy-menu-define org-org-menu org-mode-map "Org menu."
  15959. `("Org"
  15960. ("Show/Hide"
  15961. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  15962. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  15963. ["Sparse Tree..." org-sparse-tree t]
  15964. ["Reveal Context" org-fold-reveal t]
  15965. ["Show All" org-fold-show-all t]
  15966. "--"
  15967. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  15968. "--"
  15969. ["New Heading" org-insert-heading t]
  15970. ("Navigate Headings"
  15971. ["Up" outline-up-heading t]
  15972. ["Next" outline-next-visible-heading t]
  15973. ["Previous" outline-previous-visible-heading t]
  15974. ["Next Same Level" outline-forward-same-level t]
  15975. ["Previous Same Level" outline-backward-same-level t]
  15976. "--"
  15977. ["Jump" org-goto t])
  15978. ("Edit Structure"
  15979. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  15980. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  15981. "--"
  15982. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  15983. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  15984. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  15985. "--"
  15986. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  15987. "--"
  15988. ["Copy visible text" org-copy-visible t]
  15989. "--"
  15990. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  15991. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  15992. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  15993. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  15994. "--"
  15995. ["Sort Region/Children" org-sort t]
  15996. "--"
  15997. ["Convert to odd levels" org-convert-to-odd-levels t]
  15998. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  15999. ("Editing"
  16000. ["Emphasis..." org-emphasize t]
  16001. ["Add block structure" org-insert-structure-template t]
  16002. ["Edit Source Example" org-edit-special t]
  16003. "--"
  16004. ["Footnote new/jump" org-footnote-action t]
  16005. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16006. ("Archive"
  16007. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16008. "--"
  16009. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16010. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16011. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16012. "--"
  16013. ("Hyperlinks"
  16014. ["Store Link (Global)" org-store-link t]
  16015. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16016. ["Insert Link" org-insert-link t]
  16017. ["Follow Link" org-open-at-point t]
  16018. "--"
  16019. ["Next link" org-next-link t]
  16020. ["Previous link" org-previous-link t]
  16021. "--"
  16022. ["Descriptive Links"
  16023. org-toggle-link-display
  16024. :style radio
  16025. :selected org-descriptive-links
  16026. ]
  16027. ["Literal Links"
  16028. org-toggle-link-display
  16029. :style radio
  16030. :selected (not org-descriptive-links)])
  16031. "--"
  16032. ("TODO Lists"
  16033. ["TODO/DONE/-" org-todo t]
  16034. ("Select keyword"
  16035. ["Next keyword" org-shiftright (org-at-heading-p)]
  16036. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16037. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16038. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16039. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16040. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16041. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16042. "--"
  16043. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16044. :selected org-enforce-todo-dependencies :style toggle :active t]
  16045. "Settings for tree at point"
  16046. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16047. :selected (org-entry-get nil "ORDERED")
  16048. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16049. ["Do Children parallel" org-toggle-ordered-property :style radio
  16050. :selected (not (org-entry-get nil "ORDERED"))
  16051. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16052. "--"
  16053. ["Set Priority" org-priority t]
  16054. ["Priority Up" org-shiftup t]
  16055. ["Priority Down" org-shiftdown t]
  16056. "--"
  16057. ["Get news from all feeds" org-feed-update-all t]
  16058. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16059. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16060. ("TAGS and Properties"
  16061. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16062. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16063. "--"
  16064. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16065. ["Column view of properties" org-columns t]
  16066. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16067. ("Dates and Scheduling"
  16068. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16069. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16070. ("Change Date"
  16071. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16072. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16073. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16074. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16075. ["Compute Time Range" org-evaluate-time-range t]
  16076. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16077. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16078. "--"
  16079. ["Custom time format" org-toggle-time-stamp-overlays
  16080. :style radio :selected org-display-custom-times]
  16081. "--"
  16082. ["Goto Calendar" org-goto-calendar t]
  16083. ["Date from Calendar" org-date-from-calendar t]
  16084. "--"
  16085. ["Start/Restart Timer" org-timer-start t]
  16086. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16087. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16088. ["Insert Timer String" org-timer t]
  16089. ["Insert Timer Item" org-timer-item t])
  16090. ("Logging work"
  16091. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16092. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16093. ["Clock out" org-clock-out t]
  16094. ["Clock cancel" org-clock-cancel t]
  16095. "--"
  16096. ["Mark as default task" org-clock-mark-default-task t]
  16097. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16098. ["Goto running clock" org-clock-goto t]
  16099. "--"
  16100. ["Display times" org-clock-display t]
  16101. ["Create clock table" org-clock-report t]
  16102. "--"
  16103. ["Record DONE time"
  16104. (progn (setq org-log-done (not org-log-done))
  16105. (message "Switching to %s will %s record a timestamp"
  16106. (car org-done-keywords)
  16107. (if org-log-done "automatically" "not")))
  16108. :style toggle :selected org-log-done])
  16109. "--"
  16110. ["Agenda Command..." org-agenda t]
  16111. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16112. ("File List for Agenda")
  16113. ("Special views current file"
  16114. ["TODO Tree" org-show-todo-tree t]
  16115. ["Check Deadlines" org-check-deadlines t]
  16116. ["Tags/Property tree" org-match-sparse-tree t])
  16117. "--"
  16118. ["Export/Publish..." org-export-dispatch t]
  16119. ("LaTeX"
  16120. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16121. :style toggle :selected org-cdlatex-mode]
  16122. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16123. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16124. ["Modify math symbol" org-cdlatex-math-modify
  16125. (org-inside-LaTeX-fragment-p)]
  16126. ["Insert citation" org-reftex-citation t])
  16127. "--"
  16128. ("Documentation"
  16129. ["Show Version" org-version t]
  16130. ["Info Documentation" org-info t]
  16131. ["Browse Org News" org-browse-news t])
  16132. ("Customize"
  16133. ["Browse Org Group" org-customize t]
  16134. "--"
  16135. ["Expand This Menu" org-create-customize-menu t])
  16136. ["Send bug report" org-submit-bug-report t]
  16137. "--"
  16138. ("Refresh/Reload"
  16139. ["Refresh setup current buffer" org-mode-restart t]
  16140. ["Reload Org (after update)" org-reload t]
  16141. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16142. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16143. '("Table"
  16144. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16145. ["Next Field" org-cycle (org-at-table-p)]
  16146. ["Previous Field" org-shifttab (org-at-table-p)]
  16147. ["Next Row" org-return (org-at-table-p)]
  16148. "--"
  16149. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16150. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16151. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16152. "--"
  16153. ("Column"
  16154. ["Move Column Left" org-metaleft (org-at-table-p)]
  16155. ["Move Column Right" org-metaright (org-at-table-p)]
  16156. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16157. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16158. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16159. ("Row"
  16160. ["Move Row Up" org-metaup (org-at-table-p)]
  16161. ["Move Row Down" org-metadown (org-at-table-p)]
  16162. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16163. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16164. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16165. "--"
  16166. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16167. ("Rectangle"
  16168. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16169. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16170. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16171. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16172. "--"
  16173. ("Calculate"
  16174. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16175. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16176. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16177. "--"
  16178. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16179. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16180. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16181. "--"
  16182. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16183. "--"
  16184. ["Sum Column/Rectangle" org-table-sum
  16185. (or (org-at-table-p) (org-region-active-p))]
  16186. ["Which Column?" org-table-current-column (org-at-table-p)])
  16187. ["Debug Formulas"
  16188. org-table-toggle-formula-debugger
  16189. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16190. ["Show Col/Row Numbers"
  16191. org-table-toggle-coordinate-overlays
  16192. :style toggle
  16193. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16194. "--"
  16195. ["Create" org-table-create (not (org-at-table-p))]
  16196. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16197. ["Import from File" org-table-import (not (org-at-table-p))]
  16198. ["Export to File" org-table-export (org-at-table-p)]
  16199. "--"
  16200. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16201. "--"
  16202. ("Plot"
  16203. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16204. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16205. (defun org-info (&optional node)
  16206. "Read documentation for Org in the info system.
  16207. With optional NODE, go directly to that node."
  16208. (interactive)
  16209. (info (format "(org)%s" (or node ""))))
  16210. (defun org-browse-news ()
  16211. "Browse the news for the latest major release."
  16212. (interactive)
  16213. (browse-url "https://orgmode.org/Changes.html"))
  16214. ;;;###autoload
  16215. (defun org-submit-bug-report ()
  16216. "Submit a bug report on Org via mail.
  16217. Don't hesitate to report any problems or inaccurate documentation.
  16218. If you don't have setup sending mail from (X)Emacs, please copy the
  16219. output buffer into your mail program, as it gives us important
  16220. information about your Org version and configuration."
  16221. (interactive)
  16222. (require 'reporter)
  16223. (defvar reporter-prompt-for-summary-p)
  16224. (org-load-modules-maybe)
  16225. (org-require-autoloaded-modules)
  16226. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16227. (reporter-submit-bug-report
  16228. "emacs-orgmode@gnu.org"
  16229. (org-version nil 'full)
  16230. (let (list)
  16231. (save-window-excursion
  16232. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16233. (delete-other-windows)
  16234. (erase-buffer)
  16235. (insert "You are about to submit a bug report to the Org mailing list.
  16236. If your report is about Org installation, please read this section:
  16237. https://orgmode.org/org.html#Installation
  16238. Please read https://orgmode.org/org.html#Feedback on how to make
  16239. a good report, it will help Org contributors fixing your problem.
  16240. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16241. if the issue you are about to raise has already been dealt with.
  16242. We also would like to add your full Org and Outline configuration
  16243. to the bug report. It will help us debugging the issue.
  16244. *HOWEVER*, some variables you have customized may contain private
  16245. information. The names of customers, colleagues, or friends, might
  16246. appear in the form of file names, tags, todo states or search strings.
  16247. If you answer \"yes\" to the prompt, you might want to check and remove
  16248. such private information before sending the email.")
  16249. (add-text-properties (point-min) (point-max) '(face org-warning))
  16250. (when (yes-or-no-p "Include your Org configuration ")
  16251. (mapatoms
  16252. (lambda (v)
  16253. (and (boundp v)
  16254. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16255. (or (and (symbol-value v)
  16256. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16257. (and
  16258. (get v 'custom-type) (get v 'standard-value)
  16259. (not (equal (symbol-value v)
  16260. (eval (car (get v 'standard-value)) t)))))
  16261. (push v list)))))
  16262. (kill-buffer (get-buffer "*Warn about privacy*"))
  16263. list))
  16264. nil nil
  16265. "Remember to cover the basics, that is, what you expected to happen and
  16266. what in fact did happen. You don't know how to make a good report? See
  16267. https://orgmode.org/manual/Feedback.html#Feedback
  16268. Your bug report will be posted to the Org mailing list.
  16269. ------------------------------------------------------------------------")
  16270. (save-excursion
  16271. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16272. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16273. (defun org-install-agenda-files-menu ()
  16274. "Install agenda file menu."
  16275. (let ((bl (buffer-list)))
  16276. (save-excursion
  16277. (while bl
  16278. (set-buffer (pop bl))
  16279. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16280. (when (derived-mode-p 'org-mode)
  16281. (easy-menu-change
  16282. '("Org") "File List for Agenda"
  16283. (append
  16284. (list
  16285. ["Edit File List" (org-edit-agenda-file-list) t]
  16286. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16287. ["Remove Current File from List" org-remove-file t]
  16288. ["Cycle through agenda files" org-cycle-agenda-files t]
  16289. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16290. "--")
  16291. (mapcar 'org-file-menu-entry
  16292. ;; Prevent initialization from failing.
  16293. (ignore-errors (org-agenda-files t)))))))))
  16294. ;;;; Documentation
  16295. (defun org-require-autoloaded-modules ()
  16296. (interactive)
  16297. (mapc #'require
  16298. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16299. org-table org-timer)))
  16300. ;;;###autoload
  16301. (defun org-reload (&optional uncompiled)
  16302. "Reload all Org Lisp files.
  16303. With prefix arg UNCOMPILED, load the uncompiled versions."
  16304. (interactive "P")
  16305. (require 'loadhist)
  16306. (let* ((org-dir (org-find-library-dir "org"))
  16307. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16308. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16309. (remove-re (format "\\`%s\\'"
  16310. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16311. (feats (delete-dups
  16312. (mapcar 'file-name-sans-extension
  16313. (mapcar 'file-name-nondirectory
  16314. (delq nil
  16315. (mapcar 'feature-file
  16316. features))))))
  16317. (lfeat (append
  16318. (sort
  16319. (setq feats
  16320. (delq nil (mapcar
  16321. (lambda (f)
  16322. (if (and (string-match feature-re f)
  16323. (not (string-match remove-re f)))
  16324. f nil))
  16325. feats)))
  16326. 'string-lessp)
  16327. (list "org-version" "org")))
  16328. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16329. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16330. load-uncore load-misses)
  16331. (setq load-misses
  16332. (delq 't
  16333. (mapcar (lambda (f)
  16334. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16335. (and (string= org-dir contrib-dir)
  16336. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16337. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16338. (push f load-uncore)
  16339. 't)
  16340. f))
  16341. lfeat)))
  16342. (when load-uncore
  16343. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16344. (if (> (length load-uncore) 1) "s were" " was")
  16345. (reverse load-uncore)))
  16346. (if load-misses
  16347. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16348. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16349. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16350. ;;;###autoload
  16351. (defun org-customize ()
  16352. "Call the customize function with org as argument."
  16353. (interactive)
  16354. (org-load-modules-maybe)
  16355. (org-require-autoloaded-modules)
  16356. (customize-browse 'org))
  16357. (defun org-create-customize-menu ()
  16358. "Create a full customization menu for Org mode, insert it into the menu."
  16359. (interactive)
  16360. (org-load-modules-maybe)
  16361. (org-require-autoloaded-modules)
  16362. (easy-menu-change
  16363. '("Org") "Customize"
  16364. `(["Browse Org group" org-customize t]
  16365. "--"
  16366. ,(customize-menu-create 'org)
  16367. ["Set" Custom-set t]
  16368. ["Save" Custom-save t]
  16369. ["Reset to Current" Custom-reset-current t]
  16370. ["Reset to Saved" Custom-reset-saved t]
  16371. ["Reset to Standard Settings" Custom-reset-standard t]))
  16372. (message "\"Org\"-menu now contains full customization menu"))
  16373. ;;;; Miscellaneous stuff
  16374. ;;; Generally useful functions
  16375. (defun org-in-clocktable-p ()
  16376. "Check if the cursor is in a clocktable."
  16377. (let ((pos (point)) start)
  16378. (save-excursion
  16379. (end-of-line 1)
  16380. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16381. (setq start (match-beginning 0))
  16382. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16383. (>= (match-end 0) pos)
  16384. start))))
  16385. (defun org-in-verbatim-emphasis ()
  16386. (save-match-data
  16387. (and (org-in-regexp org-verbatim-re 2)
  16388. (>= (point) (match-beginning 3))
  16389. (<= (point) (match-end 4)))))
  16390. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16391. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16392. (if (and marker (marker-buffer marker)
  16393. (buffer-live-p (marker-buffer marker)))
  16394. (progn
  16395. (pop-to-buffer-same-window (marker-buffer marker))
  16396. (when (or (> marker (point-max)) (< marker (point-min)))
  16397. (widen))
  16398. (goto-char marker)
  16399. (org-fold-show-context 'org-goto))
  16400. (if bookmark
  16401. (bookmark-jump bookmark)
  16402. (error "Cannot find location"))))
  16403. (defun org-quote-csv-field (s)
  16404. "Quote field for inclusion in CSV material."
  16405. (if (string-match "[\",]" s)
  16406. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16407. s))
  16408. (defun org-force-self-insert (N)
  16409. "Needed to enforce self-insert under remapping."
  16410. (interactive "p")
  16411. (self-insert-command N))
  16412. (defun org-quote-vert (s)
  16413. "Replace \"|\" with \"\\vert\"."
  16414. (while (string-match "|" s)
  16415. (setq s (replace-match "\\vert" t t s)))
  16416. s)
  16417. (defun org-uuidgen-p (s)
  16418. "Is S an ID created by UUIDGEN?"
  16419. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16420. (defun org-in-src-block-p (&optional inside element)
  16421. "Whether point is in a code source block.
  16422. When INSIDE is non-nil, don't consider we are within a source
  16423. block when point is at #+BEGIN_SRC or #+END_SRC.
  16424. When ELEMENT is provided, it is considered to be element at point."
  16425. (save-match-data (setq element (or element (org-element-at-point))))
  16426. (when (eq 'src-block (org-element-type element))
  16427. (or (not inside)
  16428. (not (or (= (line-beginning-position)
  16429. (org-element-property :post-affiliated element))
  16430. (= (1+ (line-end-position))
  16431. (- (org-element-property :end element)
  16432. (org-element-property :post-blank element))))))))
  16433. (defun org-context ()
  16434. "Return a list of contexts of the current cursor position.
  16435. If several contexts apply, all are returned.
  16436. Each context entry is a list with a symbol naming the context, and
  16437. two positions indicating start and end of the context. Possible
  16438. contexts are:
  16439. :headline anywhere in a headline
  16440. :headline-stars on the leading stars in a headline
  16441. :todo-keyword on a TODO keyword (including DONE) in a headline
  16442. :tags on the TAGS in a headline
  16443. :priority on the priority cookie in a headline
  16444. :item on the first line of a plain list item
  16445. :item-bullet on the bullet/number of a plain list item
  16446. :checkbox on the checkbox in a plain list item
  16447. :table in an Org table
  16448. :table-special on a special filed in a table
  16449. :table-table in a table.el table
  16450. :clocktable in a clocktable
  16451. :src-block in a source block
  16452. :link on a hyperlink
  16453. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16454. :latex-fragment on a LaTeX fragment
  16455. :latex-preview on a LaTeX fragment with overlaid preview image
  16456. This function expects the position to be visible because it uses font-lock
  16457. faces as a help to recognize the following contexts: :table-special, :link,
  16458. and :keyword."
  16459. (let* ((f (get-text-property (point) 'face))
  16460. (faces (if (listp f) f (list f)))
  16461. (case-fold-search t)
  16462. (p (point)) clist o)
  16463. ;; First the large context
  16464. (cond
  16465. ((org-at-heading-p)
  16466. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16467. (when (progn
  16468. (beginning-of-line 1)
  16469. (looking-at org-todo-line-tags-regexp))
  16470. (push (org-point-in-group p 1 :headline-stars) clist)
  16471. (push (org-point-in-group p 2 :todo-keyword) clist)
  16472. (push (org-point-in-group p 4 :tags) clist))
  16473. (goto-char p)
  16474. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16475. (when (looking-at "\\[#[A-Z0-9]\\]")
  16476. (push (org-point-in-group p 0 :priority) clist)))
  16477. ((org-at-item-p)
  16478. (push (org-point-in-group p 2 :item-bullet) clist)
  16479. (push (list :item (point-at-bol)
  16480. (save-excursion (org-end-of-item) (point)))
  16481. clist)
  16482. (and (org-at-item-checkbox-p)
  16483. (push (org-point-in-group p 0 :checkbox) clist)))
  16484. ((org-at-table-p)
  16485. (push (list :table (org-table-begin) (org-table-end)) clist)
  16486. (when (memq 'org-formula faces)
  16487. (push (list :table-special
  16488. (previous-single-property-change p 'face)
  16489. (next-single-property-change p 'face))
  16490. clist)))
  16491. ((org-at-table-p 'any)
  16492. (push (list :table-table) clist)))
  16493. (goto-char p)
  16494. (let ((case-fold-search t))
  16495. ;; New the "medium" contexts: clocktables, source blocks
  16496. (cond ((org-in-clocktable-p)
  16497. (push (list :clocktable
  16498. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16499. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16500. (match-beginning 1))
  16501. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16502. (match-end 0)))
  16503. clist))
  16504. ((org-in-src-block-p)
  16505. (push (list :src-block
  16506. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16507. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16508. (match-beginning 1))
  16509. (and (search-forward "#+END_SRC" nil t)
  16510. (match-beginning 0)))
  16511. clist))))
  16512. (goto-char p)
  16513. ;; Now the small context
  16514. (cond
  16515. ((org-at-timestamp-p)
  16516. (push (org-point-in-group p 0 :timestamp) clist))
  16517. ((memq 'org-link faces)
  16518. (push (list :link
  16519. (previous-single-property-change p 'face)
  16520. (next-single-property-change p 'face))
  16521. clist))
  16522. ((memq 'org-special-keyword faces)
  16523. (push (list :keyword
  16524. (previous-single-property-change p 'face)
  16525. (next-single-property-change p 'face))
  16526. clist))
  16527. ((setq o (cl-some
  16528. (lambda (o)
  16529. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16530. o))
  16531. (overlays-at (point))))
  16532. (push (list :latex-fragment
  16533. (overlay-start o) (overlay-end o))
  16534. clist)
  16535. (push (list :latex-preview
  16536. (overlay-start o) (overlay-end o))
  16537. clist))
  16538. ((org-inside-LaTeX-fragment-p)
  16539. ;; FIXME: positions wrong.
  16540. (push (list :latex-fragment (point) (point)) clist)))
  16541. (setq clist (nreverse (delq nil clist)))
  16542. clist))
  16543. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16544. "Non-nil when point is between matches of START-RE and END-RE.
  16545. Also return a non-nil value when point is on one of the matches.
  16546. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16547. buffer positions. Default values are the positions of headlines
  16548. surrounding the point.
  16549. The functions returns a cons cell whose car (resp. cdr) is the
  16550. position before START-RE (resp. after END-RE)."
  16551. (save-match-data
  16552. (let ((pos (point))
  16553. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16554. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16555. beg end)
  16556. (save-excursion
  16557. ;; Point is on a block when on START-RE or if START-RE can be
  16558. ;; found before it...
  16559. (and (or (org-in-regexp start-re)
  16560. (re-search-backward start-re limit-up t))
  16561. (setq beg (match-beginning 0))
  16562. ;; ... and END-RE after it...
  16563. (goto-char (match-end 0))
  16564. (re-search-forward end-re limit-down t)
  16565. (> (setq end (match-end 0)) pos)
  16566. ;; ... without another START-RE in-between.
  16567. (goto-char (match-beginning 0))
  16568. (not (re-search-backward start-re (1+ beg) t))
  16569. ;; Return value.
  16570. (cons beg end))))))
  16571. (defun org-in-block-p (names)
  16572. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16573. NAMES is a list of strings containing names of blocks.
  16574. Return first block name matched, or nil. Beware that in case of
  16575. nested blocks, the returned name may not belong to the closest
  16576. block from point."
  16577. (save-match-data
  16578. (catch 'exit
  16579. (let ((case-fold-search t)
  16580. (lim-up (save-excursion (outline-previous-heading)))
  16581. (lim-down (save-excursion (outline-next-heading))))
  16582. (dolist (name names)
  16583. (let ((n (regexp-quote name)))
  16584. (when (org-between-regexps-p
  16585. (concat "^[ \t]*#\\+begin_" n)
  16586. (concat "^[ \t]*#\\+end_" n)
  16587. lim-up lim-down)
  16588. (throw 'exit n)))))
  16589. nil)))
  16590. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16591. "Call `multi-occur' with buffers for all agenda files."
  16592. (interactive "sOrg-files matching: ")
  16593. (let* ((files (org-agenda-files))
  16594. (tnames (mapcar #'file-truename files))
  16595. (extra org-agenda-text-search-extra-files))
  16596. (when (eq (car extra) 'agenda-archives)
  16597. (setq extra (cdr extra))
  16598. (setq files (org-add-archive-files files)))
  16599. (dolist (f extra)
  16600. (unless (member (file-truename f) tnames)
  16601. (unless (member f files) (setq files (append files (list f))))
  16602. (setq tnames (append tnames (list (file-truename f))))))
  16603. (multi-occur
  16604. (mapcar (lambda (x)
  16605. (with-current-buffer
  16606. ;; FIXME: Why not just (find-file-noselect x)?
  16607. ;; Is it to avoid the "revert buffer" prompt?
  16608. (or (get-file-buffer x) (find-file-noselect x))
  16609. (widen)
  16610. (current-buffer)))
  16611. files)
  16612. regexp)))
  16613. (add-hook 'occur-mode-find-occurrence-hook
  16614. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16615. (defun org-occur-link-in-agenda-files ()
  16616. "Create a link and search for it in the agendas.
  16617. The link is not stored in `org-stored-links', it is just created
  16618. for the search purpose."
  16619. (interactive)
  16620. (let ((link (condition-case nil
  16621. (org-store-link nil)
  16622. (error "Unable to create a link to here"))))
  16623. (org-occur-in-agenda-files (regexp-quote link))))
  16624. (defun org-back-over-empty-lines ()
  16625. "Move backwards over whitespace, to the beginning of the first empty line.
  16626. Returns the number of empty lines passed."
  16627. (let ((pos (point)))
  16628. (if (cdr (assq 'heading org-blank-before-new-entry))
  16629. (skip-chars-backward " \t\n\r")
  16630. (unless (eobp)
  16631. (forward-line -1)))
  16632. (beginning-of-line 2)
  16633. (goto-char (min (point) pos))
  16634. (count-lines (point) pos)))
  16635. ;;; TODO: Only called once, from ox-odt which should probably use
  16636. ;;; org-export-inline-image-p or something.
  16637. (defun org-file-image-p (file)
  16638. "Return non-nil if FILE is an image."
  16639. (save-match-data
  16640. (string-match (image-file-name-regexp) file)))
  16641. (defun org-get-cursor-date (&optional with-time)
  16642. "Return the date at cursor in as a time.
  16643. This works in the calendar and in the agenda, anywhere else it just
  16644. returns the current time.
  16645. If WITH-TIME is non-nil, returns the time of the event at point (in
  16646. the agenda) or the current time of the day; otherwise returns the
  16647. earliest time on the cursor date that Org treats as that date
  16648. (bearing in mind `org-extend-today-until')."
  16649. (let (date day defd tp hod mod)
  16650. (when with-time
  16651. (setq tp (get-text-property (point) 'time))
  16652. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16653. (setq hod (string-to-number (match-string 1 tp))
  16654. mod (string-to-number (match-string 2 tp))))
  16655. (or tp (let ((now (decode-time)))
  16656. (setq hod (nth 2 now)
  16657. mod (nth 1 now)))))
  16658. (cond
  16659. ((eq major-mode 'calendar-mode)
  16660. (setq date (calendar-cursor-to-date)
  16661. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16662. (nth 1 date) (nth 0 date) (nth 2 date))))
  16663. ((eq major-mode 'org-agenda-mode)
  16664. (setq day (get-text-property (point) 'day))
  16665. (when day
  16666. (setq date (calendar-gregorian-from-absolute day)
  16667. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16668. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16669. (or defd (current-time))))
  16670. (defun org-mark-subtree (&optional up)
  16671. "Mark the current subtree.
  16672. This puts point at the start of the current subtree, and mark at
  16673. the end. If a numeric prefix UP is given, move up into the
  16674. hierarchy of headlines by UP levels before marking the subtree."
  16675. (interactive "P")
  16676. (org-with-limited-levels
  16677. (cond ((org-at-heading-p) (beginning-of-line))
  16678. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16679. (t (outline-previous-visible-heading 1))))
  16680. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16681. (if (called-interactively-p 'any)
  16682. (call-interactively 'org-mark-element)
  16683. (org-mark-element)))
  16684. ;;; Indentation
  16685. (defvar org-element-greater-elements)
  16686. (defun org--get-expected-indentation (element contentsp)
  16687. "Expected indentation column for current line, according to ELEMENT.
  16688. ELEMENT is an element containing point. CONTENTSP is non-nil
  16689. when indentation is to be computed according to contents of
  16690. ELEMENT."
  16691. (let ((type (org-element-type element))
  16692. (start (org-element-property :begin element))
  16693. (post-affiliated (org-element-property :post-affiliated element)))
  16694. (org-with-wide-buffer
  16695. (cond
  16696. (contentsp
  16697. (cl-case type
  16698. ((diary-sexp footnote-definition) 0)
  16699. (section
  16700. (org--get-expected-indentation
  16701. (org-element-property :parent element)
  16702. t))
  16703. ((headline inlinetask nil)
  16704. (if (not org-adapt-indentation) 0
  16705. (let ((level (org-current-level)))
  16706. (if level (1+ level) 0))))
  16707. ((item plain-list) (org-list-item-body-column post-affiliated))
  16708. (t
  16709. (goto-char start)
  16710. (current-indentation))))
  16711. ((memq type '(headline inlinetask nil))
  16712. (if (org-match-line "[ \t]*$")
  16713. (org--get-expected-indentation element t)
  16714. 0))
  16715. ((memq type '(diary-sexp footnote-definition)) 0)
  16716. ;; First paragraph of a footnote definition or an item.
  16717. ;; Indent like parent.
  16718. ((< (line-beginning-position) start)
  16719. (org--get-expected-indentation
  16720. (org-element-property :parent element) t))
  16721. ;; At first line: indent according to previous sibling, if any,
  16722. ;; ignoring footnote definitions and inline tasks, or parent's
  16723. ;; contents.
  16724. ((and ( = (line-beginning-position) start)
  16725. (eq org-adapt-indentation t))
  16726. (catch 'exit
  16727. (while t
  16728. (if (= (point-min) start) (throw 'exit 0)
  16729. (goto-char (1- start))
  16730. (let* ((previous (org-element-at-point))
  16731. (parent previous))
  16732. (while (and parent (<= (org-element-property :end parent) start))
  16733. (setq previous parent
  16734. parent (org-element-property :parent parent)))
  16735. (cond
  16736. ((not previous) (throw 'exit 0))
  16737. ((> (org-element-property :end previous) start)
  16738. (throw 'exit (org--get-expected-indentation previous t)))
  16739. ((memq (org-element-type previous)
  16740. '(footnote-definition inlinetask))
  16741. (setq start (org-element-property :begin previous)))
  16742. (t (goto-char (org-element-property :begin previous))
  16743. (throw 'exit
  16744. (if (bolp) (current-indentation)
  16745. ;; At first paragraph in an item or
  16746. ;; a footnote definition.
  16747. (org--get-expected-indentation
  16748. (org-element-property :parent previous) t))))))))))
  16749. ;; Otherwise, move to the first non-blank line above.
  16750. (t
  16751. (beginning-of-line)
  16752. (let ((pos (point)))
  16753. (skip-chars-backward " \r\t\n")
  16754. (cond
  16755. ;; Two blank lines end a footnote definition or a plain
  16756. ;; list. When we indent an empty line after them, the
  16757. ;; containing list or footnote definition is over, so it
  16758. ;; qualifies as a previous sibling. Therefore, we indent
  16759. ;; like its first line.
  16760. ((and (memq type '(footnote-definition plain-list))
  16761. (> (count-lines (point) pos) 2))
  16762. (goto-char start)
  16763. (current-indentation))
  16764. ;; Line above is the first one of a paragraph at the
  16765. ;; beginning of an item or a footnote definition. Indent
  16766. ;; like parent.
  16767. ((< (line-beginning-position) start)
  16768. (org--get-expected-indentation
  16769. (org-element-property :parent element) t))
  16770. ;; Line above is the beginning of an element, i.e., point
  16771. ;; was originally on the blank lines between element's start
  16772. ;; and contents.
  16773. ((= (line-beginning-position) post-affiliated)
  16774. (org--get-expected-indentation element t))
  16775. ;; POS is after contents in a greater element. Indent like
  16776. ;; the beginning of the element.
  16777. ((and (memq type org-element-greater-elements)
  16778. (let ((cend (org-element-property :contents-end element)))
  16779. (and cend (<= cend pos))))
  16780. ;; As a special case, if point is at the end of a footnote
  16781. ;; definition or an item, indent like the very last element
  16782. ;; within. If that last element is an item, indent like
  16783. ;; its contents.
  16784. (if (memq type '(footnote-definition item plain-list))
  16785. (let ((last (org-element-at-point)))
  16786. (goto-char pos)
  16787. (org--get-expected-indentation
  16788. last (eq (org-element-type last) 'item)))
  16789. (goto-char start)
  16790. (current-indentation)))
  16791. ;; In any other case, indent like the current line.
  16792. (t (current-indentation)))))
  16793. ;; Finally, no indentation is needed, fall back to 0.
  16794. (t (current-indentation))))))
  16795. (defun org--align-node-property ()
  16796. "Align node property at point.
  16797. Alignment is done according to `org-property-format', which see."
  16798. (when (save-excursion
  16799. (beginning-of-line)
  16800. (looking-at org-property-re))
  16801. (combine-change-calls (match-beginning 0) (match-end 0)
  16802. (let ((newtext (concat (match-string 4)
  16803. (org-trim
  16804. (format org-property-format (match-string 1) (match-string 3))))))
  16805. ;; Do not use `replace-match' here as we want to inherit folding
  16806. ;; properties if inside fold.
  16807. (setf (buffer-substring (match-beginning 0) (match-end 0)) "")
  16808. (insert-and-inherit newtext)))))
  16809. (defun org-indent-line ()
  16810. "Indent line depending on context.
  16811. Indentation is done according to the following rules:
  16812. - Footnote definitions, diary sexps, headlines and inline tasks
  16813. have to start at column 0.
  16814. - On the very first line of an element, consider, in order, the
  16815. next rules until one matches:
  16816. 1. If there's a sibling element before, ignoring footnote
  16817. definitions and inline tasks, indent like its first line.
  16818. 2. If element has a parent, indent like its contents. More
  16819. precisely, if parent is an item, indent after the bullet.
  16820. Else, indent like parent's first line.
  16821. 3. Otherwise, indent relatively to current level, if
  16822. `org-adapt-indentation' is t, or to left margin.
  16823. - On a blank line at the end of an element, indent according to
  16824. the type of the element. More precisely
  16825. 1. If element is a plain list, an item, or a footnote
  16826. definition, indent like the very last element within.
  16827. 2. If element is a paragraph, indent like its last non blank
  16828. line.
  16829. 3. Otherwise, indent like its very first line.
  16830. - In the code part of a source block, use language major mode
  16831. to indent current line if `org-src-tab-acts-natively' is
  16832. non-nil. If it is nil, do nothing.
  16833. - Otherwise, indent like the first non-blank line above.
  16834. The function doesn't indent an item as it could break the whole
  16835. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  16836. `\\[org-shiftmetaright]'.
  16837. Also align node properties according to `org-property-format'."
  16838. (interactive)
  16839. (unless (or (org-at-heading-p)
  16840. (and (eq org-adapt-indentation 'headline-data)
  16841. (not (or (org-at-clock-log-p)
  16842. (org-at-planning-p)))
  16843. (save-excursion
  16844. (beginning-of-line 1)
  16845. (skip-chars-backward "\n")
  16846. (or (org-at-heading-p)
  16847. (looking-back ":END:.*" (point-at-bol))))))
  16848. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  16849. (type (org-element-type element)))
  16850. (cond ((and (memq type '(plain-list item))
  16851. (= (line-beginning-position)
  16852. (org-element-property :post-affiliated element)))
  16853. nil)
  16854. ((and (eq type 'latex-environment)
  16855. (>= (point) (org-element-property :post-affiliated element))
  16856. (< (point)
  16857. (org-with-point-at (org-element-property :end element)
  16858. (skip-chars-backward " \t\n")
  16859. (line-beginning-position 2))))
  16860. nil)
  16861. ((and (eq type 'src-block)
  16862. org-src-tab-acts-natively
  16863. (> (line-beginning-position)
  16864. (org-element-property :post-affiliated element))
  16865. (< (line-beginning-position)
  16866. (org-with-point-at (org-element-property :end element)
  16867. (skip-chars-backward " \t\n")
  16868. (line-beginning-position))))
  16869. ;; At the beginning of a blank line, do some preindentation. This
  16870. ;; signals org-src--edit-element to preserve the indentation on exit
  16871. (when (and (looking-at-p "^[[:space:]]*$")
  16872. (not org-src-preserve-indentation))
  16873. (let ((element (org-element-at-point))
  16874. block-content-ind some-ind)
  16875. (org-with-point-at (org-element-property :begin element)
  16876. (setq block-content-ind (+ (current-indentation)
  16877. org-edit-src-content-indentation))
  16878. (forward-line)
  16879. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  16880. (backward-char)
  16881. (setq some-ind (if (looking-at-p "#\\+end_src")
  16882. block-content-ind (current-indentation))))
  16883. (indent-line-to (min block-content-ind some-ind))))
  16884. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  16885. (t
  16886. (let ((column (org--get-expected-indentation element nil)))
  16887. ;; Preserve current column.
  16888. (if (<= (current-column) (current-indentation))
  16889. (indent-line-to column)
  16890. (save-excursion (indent-line-to column))))
  16891. ;; Align node property. Also preserve current column.
  16892. (when (eq type 'node-property)
  16893. (let ((column (current-column)))
  16894. (org--align-node-property)
  16895. (org-move-to-column column))))))))
  16896. (defun org-indent-region (start end)
  16897. "Indent each non-blank line in the region.
  16898. Called from a program, START and END specify the region to
  16899. indent. The function will not indent contents of example blocks,
  16900. verse blocks and export blocks as leading white spaces are
  16901. assumed to be significant there."
  16902. (interactive "r")
  16903. (save-excursion
  16904. (goto-char start)
  16905. (skip-chars-forward " \r\t\n")
  16906. (unless (eobp) (beginning-of-line))
  16907. (let ((indent-to
  16908. (lambda (ind pos)
  16909. ;; Set IND as indentation for all lines between point and
  16910. ;; POS. Blank lines are ignored. Leave point after POS
  16911. ;; once done.
  16912. (let ((limit (copy-marker pos)))
  16913. (while (< (point) limit)
  16914. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  16915. (forward-line))
  16916. (set-marker limit nil))))
  16917. (end (copy-marker end)))
  16918. (while (< (point) end)
  16919. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  16920. (let* ((element (org-element-at-point-no-context))
  16921. (type (org-element-type element))
  16922. (element-end (copy-marker (org-element-property :end element)))
  16923. (ind (org--get-expected-indentation element nil)))
  16924. (cond
  16925. ;; Element indented as a single block. Example blocks
  16926. ;; preserving indentation are a special case since the
  16927. ;; "contents" must not be indented whereas the block
  16928. ;; boundaries can.
  16929. ((or (memq type '(export-block latex-environment))
  16930. (and (eq type 'example-block)
  16931. (not
  16932. (or org-src-preserve-indentation
  16933. (org-element-property :preserve-indent element)))))
  16934. (let ((offset (- ind (current-indentation))))
  16935. (unless (zerop offset)
  16936. (indent-rigidly (org-element-property :begin element)
  16937. (org-element-property :end element)
  16938. offset)))
  16939. (goto-char element-end))
  16940. ;; Elements indented line wise. Be sure to exclude
  16941. ;; example blocks (preserving indentation) and source
  16942. ;; blocks from this category as they are treated
  16943. ;; specially later.
  16944. ((or (memq type '(paragraph table table-row))
  16945. (not (or (org-element-property :contents-begin element)
  16946. (memq type '(example-block src-block)))))
  16947. (when (eq type 'node-property)
  16948. (org--align-node-property)
  16949. (beginning-of-line))
  16950. (funcall indent-to ind (min element-end end)))
  16951. ;; Elements consisting of three parts: before the
  16952. ;; contents, the contents, and after the contents. The
  16953. ;; contents are treated specially, according to the
  16954. ;; element type, or not indented at all. Other parts are
  16955. ;; indented as a single block.
  16956. (t
  16957. (let* ((post (copy-marker
  16958. (org-element-property :post-affiliated element)))
  16959. (cbeg
  16960. (copy-marker
  16961. (cond
  16962. ((not (org-element-property :contents-begin element))
  16963. ;; Fake contents for source blocks.
  16964. (org-with-wide-buffer
  16965. (goto-char post)
  16966. (line-beginning-position 2)))
  16967. ((memq type '(footnote-definition item plain-list))
  16968. ;; Contents in these elements could start on
  16969. ;; the same line as the beginning of the
  16970. ;; element. Make sure we start indenting
  16971. ;; from the second line.
  16972. (org-with-wide-buffer
  16973. (goto-char post)
  16974. (end-of-line)
  16975. (skip-chars-forward " \r\t\n")
  16976. (if (eobp) (point) (line-beginning-position))))
  16977. (t (org-element-property :contents-begin element)))))
  16978. (cend (copy-marker
  16979. (or (org-element-property :contents-end element)
  16980. ;; Fake contents for source blocks.
  16981. (org-with-wide-buffer
  16982. (goto-char element-end)
  16983. (skip-chars-backward " \r\t\n")
  16984. (line-beginning-position)))
  16985. t)))
  16986. ;; Do not change items indentation individually as it
  16987. ;; might break the list as a whole. On the other
  16988. ;; hand, when at a plain list, indent it as a whole.
  16989. (cond ((eq type 'plain-list)
  16990. (let ((offset (- ind (current-indentation))))
  16991. (unless (zerop offset)
  16992. (indent-rigidly (org-element-property :begin element)
  16993. (org-element-property :end element)
  16994. offset))
  16995. (goto-char cbeg)))
  16996. ((eq type 'item) (goto-char cbeg))
  16997. (t (funcall indent-to ind (min cbeg end))))
  16998. (when (< (point) end)
  16999. (cl-case type
  17000. ((example-block verse-block))
  17001. (src-block
  17002. ;; In a source block, indent source code
  17003. ;; according to language major mode, but only if
  17004. ;; `org-src-tab-acts-natively' is non-nil.
  17005. (when (and (< (point) end) org-src-tab-acts-natively)
  17006. (ignore-errors
  17007. (org-babel-do-in-edit-buffer
  17008. (indent-region (point-min) (point-max))))))
  17009. (t (org-indent-region (point) (min cend end))))
  17010. (goto-char (min cend end))
  17011. (when (< (point) end)
  17012. (funcall indent-to ind (min element-end end))))
  17013. (set-marker post nil)
  17014. (set-marker cbeg nil)
  17015. (set-marker cend nil))))
  17016. (set-marker element-end nil))))
  17017. (set-marker end nil))))
  17018. (defun org-indent-drawer ()
  17019. "Indent the drawer at point."
  17020. (interactive)
  17021. (unless (save-excursion
  17022. (beginning-of-line)
  17023. (looking-at-p org-drawer-regexp))
  17024. (user-error "Not at a drawer"))
  17025. (let ((element (org-element-at-point-no-context)))
  17026. (unless (memq (org-element-type element) '(drawer property-drawer))
  17027. (user-error "Not at a drawer"))
  17028. (org-with-wide-buffer
  17029. (org-indent-region (org-element-property :begin element)
  17030. (org-element-property :end element))))
  17031. (message "Drawer at point indented"))
  17032. (defun org-indent-block ()
  17033. "Indent the block at point."
  17034. (interactive)
  17035. (unless (save-excursion
  17036. (beginning-of-line)
  17037. (let ((case-fold-search t))
  17038. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17039. (user-error "Not at a block"))
  17040. (let ((element (org-element-at-point-no-context)))
  17041. (unless (memq (org-element-type element)
  17042. '(comment-block center-block dynamic-block example-block
  17043. export-block quote-block special-block
  17044. src-block verse-block))
  17045. (user-error "Not at a block"))
  17046. (org-with-wide-buffer
  17047. (org-indent-region (org-element-property :begin element)
  17048. (org-element-property :end element))))
  17049. (message "Block at point indented"))
  17050. ;;; Filling
  17051. ;; We use our own fill-paragraph and auto-fill functions.
  17052. ;; `org-fill-paragraph' relies on adaptive filling and context
  17053. ;; checking. Appropriate `fill-prefix' is computed with
  17054. ;; `org-adaptive-fill-function'.
  17055. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17056. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17057. ;; `org-adaptive-fill-function' value. Internally,
  17058. ;; `org-comment-line-break-function' breaks the line.
  17059. ;; `org-setup-filling' installs filling and auto-filling related
  17060. ;; variables during `org-mode' initialization.
  17061. (defun org-setup-filling ()
  17062. (require 'org-element)
  17063. ;; Prevent auto-fill from inserting unwanted new items.
  17064. (when (boundp 'fill-nobreak-predicate)
  17065. (setq-local
  17066. fill-nobreak-predicate
  17067. (org-uniquify
  17068. (append fill-nobreak-predicate
  17069. '(org-fill-line-break-nobreak-p
  17070. org-fill-n-macro-as-item-nobreak-p
  17071. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17072. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17073. (setq-local paragraph-start paragraph-ending)
  17074. (setq-local paragraph-separate paragraph-ending))
  17075. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17076. (setq-local auto-fill-inhibit-regexp nil)
  17077. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17078. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17079. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17080. (defun org-fill-line-break-nobreak-p ()
  17081. "Non-nil when a new line at point would create an Org line break."
  17082. (save-excursion
  17083. (skip-chars-backward " \t")
  17084. (skip-chars-backward "\\\\")
  17085. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17086. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17087. "Non-nil when a new line at point would split a timestamp."
  17088. (and (org-at-timestamp-p 'lax)
  17089. (not (looking-at org-ts-regexp-both))))
  17090. (defun org-fill-n-macro-as-item-nobreak-p ()
  17091. "Non-nil when a new line at point would create a new list."
  17092. ;; During export, a "n" macro followed by a dot or a closing
  17093. ;; parenthesis can end up being parsed as a new list item.
  17094. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17095. (defun org-adaptive-fill-function ()
  17096. "Compute a fill prefix for the current line.
  17097. Return fill prefix, as a string, or nil if current line isn't
  17098. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17099. matches in paragraphs or comments, use it."
  17100. (org-with-wide-buffer
  17101. (unless (org-at-heading-p)
  17102. (let* ((p (line-beginning-position))
  17103. (element (save-excursion
  17104. (beginning-of-line)
  17105. (org-element-at-point)))
  17106. (type (org-element-type element))
  17107. (post-affiliated (org-element-property :post-affiliated element)))
  17108. (unless (< p post-affiliated)
  17109. (cl-case type
  17110. (comment
  17111. (save-excursion
  17112. (beginning-of-line)
  17113. (looking-at "[ \t]*")
  17114. (concat (match-string 0) "# ")))
  17115. (footnote-definition "")
  17116. ((item plain-list)
  17117. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17118. (paragraph
  17119. ;; Fill prefix is usually the same as the current line,
  17120. ;; unless the paragraph is at the beginning of an item.
  17121. (let ((parent (org-element-property :parent element)))
  17122. (save-excursion
  17123. (beginning-of-line)
  17124. (cond ((eq (org-element-type parent) 'item)
  17125. (make-string (org-list-item-body-column
  17126. (org-element-property :begin parent))
  17127. ?\s))
  17128. ((and adaptive-fill-regexp
  17129. ;; Locally disable
  17130. ;; `adaptive-fill-function' to let
  17131. ;; `fill-context-prefix' handle
  17132. ;; `adaptive-fill-regexp' variable.
  17133. (let (adaptive-fill-function)
  17134. (fill-context-prefix
  17135. post-affiliated
  17136. (org-element-property :end element)))))
  17137. ((looking-at "[ \t]+") (match-string 0))
  17138. (t "")))))
  17139. (comment-block
  17140. ;; Only fill contents if P is within block boundaries.
  17141. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17142. (forward-line)
  17143. (point)))
  17144. (cend (save-excursion
  17145. (goto-char (org-element-property :end element))
  17146. (skip-chars-backward " \r\t\n")
  17147. (line-beginning-position))))
  17148. (when (and (>= p cbeg) (< p cend))
  17149. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17150. (match-string 0)
  17151. ""))))))))))
  17152. (defun org-fill-element (&optional justify)
  17153. "Fill element at point, when applicable.
  17154. This function only applies to comment blocks, comments, example
  17155. blocks and paragraphs. Also, as a special case, re-align table
  17156. when point is at one.
  17157. If JUSTIFY is non-nil (interactively, with prefix argument),
  17158. justify as well. If `sentence-end-double-space' is non-nil, then
  17159. period followed by one space does not end a sentence, so don't
  17160. break a line there. The variable `fill-column' controls the
  17161. width for filling.
  17162. For convenience, when point is at a plain list, an item or
  17163. a footnote definition, try to fill the first paragraph within."
  17164. (with-syntax-table org-mode-transpose-word-syntax-table
  17165. ;; Move to end of line in order to get the first paragraph within
  17166. ;; a plain list or a footnote definition.
  17167. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17168. ;; First check if point is in a blank line at the beginning of
  17169. ;; the buffer. In that case, ignore filling.
  17170. (cl-case (org-element-type element)
  17171. ;; Use major mode filling function is source blocks.
  17172. (src-block (org-babel-do-in-edit-buffer
  17173. (push-mark (point-min))
  17174. (goto-char (point-max))
  17175. (setq mark-active t)
  17176. (funcall-interactively #'fill-paragraph justify 'region)))
  17177. ;; Align Org tables, leave table.el tables as-is.
  17178. (table-row (org-table-align) t)
  17179. (table
  17180. (when (eq (org-element-property :type element) 'org)
  17181. (save-excursion
  17182. (goto-char (org-element-property :post-affiliated element))
  17183. (org-table-align)))
  17184. t)
  17185. (paragraph
  17186. ;; Paragraphs may contain `line-break' type objects.
  17187. (let ((beg (max (point-min)
  17188. (org-element-property :contents-begin element)))
  17189. (end (min (point-max)
  17190. (org-element-property :contents-end element))))
  17191. ;; Do nothing if point is at an affiliated keyword.
  17192. (if (< (line-end-position) beg) t
  17193. ;; Fill paragraph, taking line breaks into account.
  17194. (save-excursion
  17195. (goto-char beg)
  17196. (let ((cuts (list beg)))
  17197. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17198. (when (eq 'line-break
  17199. (org-element-type
  17200. (save-excursion (backward-char)
  17201. (org-element-context))))
  17202. (push (point) cuts)))
  17203. (dolist (c (delq end cuts))
  17204. (fill-region-as-paragraph c end justify)
  17205. (setq end c))))
  17206. t)))
  17207. ;; Contents of `comment-block' type elements should be
  17208. ;; filled as plain text, but only if point is within block
  17209. ;; markers.
  17210. (comment-block
  17211. (let* ((case-fold-search t)
  17212. (beg (save-excursion
  17213. (goto-char (org-element-property :begin element))
  17214. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17215. (forward-line)
  17216. (point)))
  17217. (end (save-excursion
  17218. (goto-char (org-element-property :end element))
  17219. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17220. (line-beginning-position))))
  17221. (if (or (< (point) beg) (> (point) end)) t
  17222. (fill-region-as-paragraph
  17223. (save-excursion (end-of-line)
  17224. (re-search-backward "^[ \t]*$" beg 'move)
  17225. (line-beginning-position))
  17226. (save-excursion (beginning-of-line)
  17227. (re-search-forward "^[ \t]*$" end 'move)
  17228. (line-beginning-position))
  17229. justify))))
  17230. ;; Fill comments.
  17231. (comment
  17232. (let ((begin (org-element-property :post-affiliated element))
  17233. (end (org-element-property :end element)))
  17234. (when (and (>= (point) begin) (<= (point) end))
  17235. (let ((begin (save-excursion
  17236. (end-of-line)
  17237. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17238. (progn (forward-line) (point))
  17239. begin)))
  17240. (end (save-excursion
  17241. (end-of-line)
  17242. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17243. (1- (line-beginning-position))
  17244. (skip-chars-backward " \r\t\n")
  17245. (line-end-position)))))
  17246. ;; Do not fill comments when at a blank line.
  17247. (when (> end begin)
  17248. (let ((fill-prefix
  17249. (save-excursion
  17250. (beginning-of-line)
  17251. (looking-at "[ \t]*#")
  17252. (let ((comment-prefix (match-string 0)))
  17253. (goto-char (match-end 0))
  17254. (if (looking-at adaptive-fill-regexp)
  17255. (concat comment-prefix (match-string 0))
  17256. (concat comment-prefix " "))))))
  17257. (save-excursion
  17258. (fill-region-as-paragraph begin end justify))))))
  17259. t))
  17260. ;; Ignore every other element.
  17261. (otherwise t)))))
  17262. (defun org-fill-paragraph (&optional justify region)
  17263. "Fill element at point, when applicable.
  17264. This function only applies to comment blocks, comments, example
  17265. blocks and paragraphs. Also, as a special case, re-align table
  17266. when point is at one.
  17267. For convenience, when point is at a plain list, an item or
  17268. a footnote definition, try to fill the first paragraph within.
  17269. If JUSTIFY is non-nil (interactively, with prefix argument),
  17270. justify as well. If `sentence-end-double-space' is non-nil, then
  17271. period followed by one space does not end a sentence, so don't
  17272. break a line there. The variable `fill-column' controls the
  17273. width for filling.
  17274. The REGION argument is non-nil if called interactively; in that
  17275. case, if Transient Mark mode is enabled and the mark is active,
  17276. fill each of the elements in the active region, instead of just
  17277. filling the current element."
  17278. (interactive (progn
  17279. (barf-if-buffer-read-only)
  17280. (list (when current-prefix-arg 'full) t)))
  17281. (let ((hash (and (not (buffer-modified-p))
  17282. (org-buffer-hash))))
  17283. (cond
  17284. ((and region transient-mark-mode mark-active
  17285. (not (eq (region-beginning) (region-end))))
  17286. (let ((origin (point-marker))
  17287. (start (region-beginning)))
  17288. (unwind-protect
  17289. (progn
  17290. (goto-char (region-end))
  17291. (skip-chars-backward " \t\n")
  17292. (while (> (point) start)
  17293. (org-fill-element justify)
  17294. (org-backward-paragraph)))
  17295. (goto-char origin)
  17296. (set-marker origin nil))))
  17297. (t
  17298. (save-excursion
  17299. (when (org-match-line "[ \t]*$")
  17300. (skip-chars-forward " \t\n"))
  17301. (org-fill-element justify))))
  17302. ;; If we didn't change anything in the buffer (and the buffer was
  17303. ;; previously unmodified), then flip the modification status back
  17304. ;; to "unchanged".
  17305. (when (and hash (equal hash (org-buffer-hash)))
  17306. (set-buffer-modified-p nil))
  17307. ;; Return non-nil.
  17308. t))
  17309. (defun org-auto-fill-function ()
  17310. "Auto-fill function."
  17311. ;; Check if auto-filling is meaningful.
  17312. (let ((fc (current-fill-column)))
  17313. (when (and fc (> (current-column) fc))
  17314. (let* ((fill-prefix (org-adaptive-fill-function))
  17315. ;; Enforce empty fill prefix, if required. Otherwise, it
  17316. ;; will be computed again.
  17317. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17318. (when fill-prefix (do-auto-fill))))))
  17319. (defun org-comment-line-break-function (&optional soft)
  17320. "Break line at point and indent, continuing comment if within one.
  17321. The inserted newline is marked hard if variable
  17322. `use-hard-newlines' is true, unless optional argument SOFT is
  17323. non-nil."
  17324. (if soft (insert-and-inherit ?\n) (newline 1))
  17325. (save-excursion (forward-char -1) (delete-horizontal-space))
  17326. (delete-horizontal-space)
  17327. (indent-to-left-margin)
  17328. (insert-before-markers-and-inherit fill-prefix))
  17329. ;;; Fixed Width Areas
  17330. (defun org-toggle-fixed-width ()
  17331. "Toggle fixed-width markup.
  17332. Add or remove fixed-width markup on current line, whenever it
  17333. makes sense. Return an error otherwise.
  17334. If a region is active and if it contains only fixed-width areas
  17335. or blank lines, remove all fixed-width markup in it. If the
  17336. region contains anything else, convert all non-fixed-width lines
  17337. to fixed-width ones.
  17338. Blank lines at the end of the region are ignored unless the
  17339. region only contains such lines."
  17340. (interactive)
  17341. (if (not (org-region-active-p))
  17342. ;; No region:
  17343. ;;
  17344. ;; Remove fixed width marker only in a fixed-with element.
  17345. ;;
  17346. ;; Add fixed width maker in paragraphs, in blank lines after
  17347. ;; elements or at the beginning of a headline or an inlinetask,
  17348. ;; and before any one-line elements (e.g., a clock).
  17349. (progn
  17350. (beginning-of-line)
  17351. (let* ((element (org-element-at-point))
  17352. (type (org-element-type element)))
  17353. (cond
  17354. ((and (eq type 'fixed-width)
  17355. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17356. (replace-match
  17357. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17358. ((and (memq type '(babel-call clock comment diary-sexp headline
  17359. horizontal-rule keyword paragraph
  17360. planning))
  17361. (<= (org-element-property :post-affiliated element) (point)))
  17362. (skip-chars-forward " \t")
  17363. (insert ": "))
  17364. ((and (looking-at-p "[ \t]*$")
  17365. (or (eq type 'inlinetask)
  17366. (save-excursion
  17367. (skip-chars-forward " \r\t\n")
  17368. (<= (org-element-property :end element) (point)))))
  17369. (delete-region (point) (line-end-position))
  17370. (org-indent-line)
  17371. (insert ": "))
  17372. (t (user-error "Cannot insert a fixed-width line here")))))
  17373. ;; Region active.
  17374. (let* ((begin (save-excursion
  17375. (goto-char (region-beginning))
  17376. (line-beginning-position)))
  17377. (end (copy-marker
  17378. (save-excursion
  17379. (goto-char (region-end))
  17380. (unless (eolp) (beginning-of-line))
  17381. (if (save-excursion (re-search-backward "\\S-" begin t))
  17382. (progn (skip-chars-backward " \r\t\n") (point))
  17383. (point)))))
  17384. (all-fixed-width-p
  17385. (catch 'not-all-p
  17386. (save-excursion
  17387. (goto-char begin)
  17388. (skip-chars-forward " \r\t\n")
  17389. (when (eobp) (throw 'not-all-p nil))
  17390. (while (< (point) end)
  17391. (let ((element (org-element-at-point)))
  17392. (if (eq (org-element-type element) 'fixed-width)
  17393. (goto-char (org-element-property :end element))
  17394. (throw 'not-all-p nil))))
  17395. t))))
  17396. (if all-fixed-width-p
  17397. (save-excursion
  17398. (goto-char begin)
  17399. (while (< (point) end)
  17400. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17401. (replace-match
  17402. "" nil nil nil
  17403. (if (= (line-end-position) (match-end 0)) 0 1)))
  17404. (forward-line)))
  17405. (let ((min-ind (point-max)))
  17406. ;; Find minimum indentation across all lines.
  17407. (save-excursion
  17408. (goto-char begin)
  17409. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17410. (setq min-ind 0)
  17411. (catch 'zerop
  17412. (while (< (point) end)
  17413. (unless (looking-at-p "[ \t]*$")
  17414. (let ((ind (current-indentation)))
  17415. (setq min-ind (min min-ind ind))
  17416. (when (zerop ind) (throw 'zerop t))))
  17417. (forward-line)))))
  17418. ;; Loop over all lines and add fixed-width markup everywhere
  17419. ;; but in fixed-width lines.
  17420. (save-excursion
  17421. (goto-char begin)
  17422. (while (< (point) end)
  17423. (cond
  17424. ((org-at-heading-p)
  17425. (insert ": ")
  17426. (forward-line)
  17427. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17428. (insert ":")
  17429. (forward-line)))
  17430. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17431. (let* ((element (org-element-at-point))
  17432. (element-end (org-element-property :end element)))
  17433. (if (eq (org-element-type element) 'fixed-width)
  17434. (progn (goto-char element-end)
  17435. (skip-chars-backward " \r\t\n")
  17436. (forward-line))
  17437. (let ((limit (min end element-end)))
  17438. (while (< (point) limit)
  17439. (org-move-to-column min-ind t)
  17440. (insert ": ")
  17441. (forward-line))))))
  17442. (t
  17443. (org-move-to-column min-ind t)
  17444. (insert ": ")
  17445. (forward-line)))))))
  17446. (set-marker end nil))))
  17447. ;;; Blocks
  17448. (defun org-block-map (function &optional start end)
  17449. "Call FUNCTION at the head of all source blocks in the current buffer.
  17450. Optional arguments START and END can be used to limit the range."
  17451. (let ((start (or start (point-min)))
  17452. (end (or end (point-max))))
  17453. (save-excursion
  17454. (goto-char start)
  17455. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17456. (save-excursion
  17457. (save-match-data
  17458. (goto-char (match-beginning 0))
  17459. (funcall function)))))))
  17460. (defun org-next-block (arg &optional backward block-regexp)
  17461. "Jump to the next block.
  17462. With a prefix argument ARG, jump forward ARG many blocks.
  17463. When BACKWARD is non-nil, jump to the previous block.
  17464. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17465. Match data is set according to this regexp when the function
  17466. returns.
  17467. Return point at beginning of the opening line of found block.
  17468. Throw an error if no block is found."
  17469. (interactive "p")
  17470. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17471. (case-fold-search t)
  17472. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17473. (count (or arg 1))
  17474. (origin (point))
  17475. last-element)
  17476. (if backward (beginning-of-line) (end-of-line))
  17477. (while (and (> count 0) (funcall search-fn re nil t))
  17478. (let ((element (save-excursion
  17479. (goto-char (match-beginning 0))
  17480. (save-match-data (org-element-at-point)))))
  17481. (when (and (memq (org-element-type element)
  17482. '(center-block comment-block dynamic-block
  17483. example-block export-block quote-block
  17484. special-block src-block verse-block))
  17485. (<= (match-beginning 0)
  17486. (org-element-property :post-affiliated element)))
  17487. (setq last-element element)
  17488. (cl-decf count))))
  17489. (if (= count 0)
  17490. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17491. (save-match-data (org-fold-show-context)))
  17492. (goto-char origin)
  17493. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17494. (defun org-previous-block (arg &optional block-regexp)
  17495. "Jump to the previous block.
  17496. With a prefix argument ARG, jump backward ARG many source blocks.
  17497. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17498. (interactive "p")
  17499. (org-next-block arg t block-regexp))
  17500. ;;; Comments
  17501. ;; Org comments syntax is quite complex. It requires the entire line
  17502. ;; to be just a comment. Also, even with the right syntax at the
  17503. ;; beginning of line, some elements (e.g., verse-block or
  17504. ;; example-block) don't accept comments. Usual Emacs comment commands
  17505. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17506. ;; Org still relies on 'comment-dwim', but cannot trust
  17507. ;; 'comment-only-p'. So, 'comment-region-function' and
  17508. ;; 'uncomment-region-function' both point
  17509. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17510. ;; 'org-insert-comment' takes care of insertion of comments at the
  17511. ;; beginning of line.
  17512. ;; 'org-setup-comments-handling' install comments related variables
  17513. ;; during 'org-mode' initialization.
  17514. (defun org-setup-comments-handling ()
  17515. (interactive)
  17516. (setq-local comment-use-syntax nil)
  17517. (setq-local comment-start "# ")
  17518. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17519. (setq-local comment-insert-comment-function 'org-insert-comment)
  17520. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17521. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17522. (defun org-insert-comment ()
  17523. "Insert an empty comment above current line.
  17524. If the line is empty, insert comment at its beginning. When
  17525. point is within a source block, comment according to the related
  17526. major mode."
  17527. (if (let ((element (org-element-at-point)))
  17528. (and (eq (org-element-type element) 'src-block)
  17529. (< (save-excursion
  17530. (goto-char (org-element-property :post-affiliated element))
  17531. (line-end-position))
  17532. (point))
  17533. (> (save-excursion
  17534. (goto-char (org-element-property :end element))
  17535. (skip-chars-backward " \r\t\n")
  17536. (line-beginning-position))
  17537. (point))))
  17538. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17539. (beginning-of-line)
  17540. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17541. (open-line 1))
  17542. (org-indent-line)
  17543. (insert "# ")))
  17544. (defvar comment-empty-lines) ; From newcomment.el.
  17545. (defun org-comment-or-uncomment-region (beg end &rest _)
  17546. "Comment or uncomment each non-blank line in the region.
  17547. Uncomment each non-blank line between BEG and END if it only
  17548. contains commented lines. Otherwise, comment them. If region is
  17549. strictly within a source block, use appropriate comment syntax."
  17550. (if (let ((element (org-element-at-point)))
  17551. (and (eq (org-element-type element) 'src-block)
  17552. (< (save-excursion
  17553. (goto-char (org-element-property :post-affiliated element))
  17554. (line-end-position))
  17555. beg)
  17556. (>= (save-excursion
  17557. (goto-char (org-element-property :end element))
  17558. (skip-chars-backward " \r\t\n")
  17559. (line-beginning-position))
  17560. end)))
  17561. ;; Translate region boundaries for the Org buffer to the source
  17562. ;; buffer.
  17563. (let ((offset (- end beg)))
  17564. (save-excursion
  17565. (goto-char beg)
  17566. (org-babel-do-in-edit-buffer
  17567. (comment-or-uncomment-region (point) (+ offset (point))))))
  17568. (save-restriction
  17569. ;; Restrict region
  17570. (narrow-to-region (save-excursion (goto-char beg)
  17571. (skip-chars-forward " \r\t\n" end)
  17572. (line-beginning-position))
  17573. (save-excursion (goto-char end)
  17574. (skip-chars-backward " \r\t\n" beg)
  17575. (line-end-position)))
  17576. (let ((uncommentp
  17577. ;; UNCOMMENTP is non-nil when every non blank line between
  17578. ;; BEG and END is a comment.
  17579. (save-excursion
  17580. (goto-char (point-min))
  17581. (while (and (not (eobp))
  17582. (let ((element (org-element-at-point)))
  17583. (and (eq (org-element-type element) 'comment)
  17584. (goto-char (min (point-max)
  17585. (org-element-property
  17586. :end element)))))))
  17587. (eobp))))
  17588. (if uncommentp
  17589. ;; Only blank lines and comments in region: uncomment it.
  17590. (save-excursion
  17591. (goto-char (point-min))
  17592. (while (not (eobp))
  17593. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17594. (replace-match "" nil nil nil 1))
  17595. (forward-line)))
  17596. ;; Comment each line in region.
  17597. (let ((min-indent (point-max)))
  17598. ;; First find the minimum indentation across all lines.
  17599. (save-excursion
  17600. (goto-char (point-min))
  17601. (while (and (not (eobp)) (not (zerop min-indent)))
  17602. (unless (looking-at "[ \t]*$")
  17603. (setq min-indent (min min-indent (current-indentation))))
  17604. (forward-line)))
  17605. ;; Then loop over all lines.
  17606. (save-excursion
  17607. (goto-char (point-min))
  17608. (while (not (eobp))
  17609. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17610. ;; Don't get fooled by invisible text (e.g. link path)
  17611. ;; when moving to column MIN-INDENT.
  17612. (let ((buffer-invisibility-spec nil))
  17613. (org-move-to-column min-indent t))
  17614. (insert comment-start))
  17615. (forward-line)))))))))
  17616. (defun org-comment-dwim (_arg)
  17617. "Call the comment command you mean.
  17618. Call `org-toggle-comment' if on a heading, otherwise call
  17619. `comment-dwim', within a source edit buffer if needed."
  17620. (interactive "*P")
  17621. (cond ((org-at-heading-p)
  17622. (call-interactively #'org-toggle-comment))
  17623. ((org-in-src-block-p)
  17624. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17625. (t (call-interactively #'comment-dwim))))
  17626. ;;; Timestamps API
  17627. ;; This section contains tools to operate on, or create, timestamp
  17628. ;; objects, as returned by, e.g. `org-element-context'.
  17629. (defun org-timestamp-from-string (s)
  17630. "Convert Org timestamp S, as a string, into a timestamp object.
  17631. Return nil if S is not a valid timestamp string."
  17632. (when (org-string-nw-p s)
  17633. (with-temp-buffer
  17634. (save-excursion (insert s))
  17635. (org-element-timestamp-parser))))
  17636. (defun org-timestamp-from-time (time &optional with-time inactive)
  17637. "Convert a time value into a timestamp object.
  17638. TIME is an Emacs internal time representation, as returned, e.g.,
  17639. by `current-time'.
  17640. When optional argument WITH-TIME is non-nil, return a timestamp
  17641. object with a time part, i.e., with hours and minutes.
  17642. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17643. return an active timestamp."
  17644. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17645. (org-element-create 'timestamp
  17646. (list :type (if inactive 'inactive 'active)
  17647. :year-start year
  17648. :month-start month
  17649. :day-start day
  17650. :hour-start (and with-time hour)
  17651. :minute-start (and with-time minute)))))
  17652. (defun org-timestamp-to-time (timestamp &optional end)
  17653. "Convert TIMESTAMP object into an Emacs internal time value.
  17654. Use end of date range or time range when END is non-nil.
  17655. Otherwise, use its start."
  17656. (apply #'encode-time 0
  17657. (mapcar
  17658. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17659. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17660. '(:minute-start :hour-start :day-start :month-start
  17661. :year-start)))))
  17662. (defun org-timestamp-has-time-p (timestamp)
  17663. "Non-nil when TIMESTAMP has a time specified."
  17664. (org-element-property :hour-start timestamp))
  17665. (defun org-timestamp-format (timestamp format &optional end utc)
  17666. "Format a TIMESTAMP object into a string.
  17667. FORMAT is a format specifier to be passed to
  17668. `format-time-string'.
  17669. When optional argument END is non-nil, use end of date-range or
  17670. time-range, if possible.
  17671. When optional argument UTC is non-nil, time is be expressed as
  17672. Universal Time."
  17673. (format-time-string format (org-timestamp-to-time timestamp end)
  17674. (and utc t)))
  17675. (defun org-timestamp-split-range (timestamp &optional end)
  17676. "Extract a TIMESTAMP object from a date or time range.
  17677. END, when non-nil, means extract the end of the range.
  17678. Otherwise, extract its start.
  17679. Return a new timestamp object."
  17680. (let ((type (org-element-property :type timestamp)))
  17681. (if (memq type '(active inactive diary)) timestamp
  17682. (let ((split-ts (org-element-copy timestamp)))
  17683. ;; Set new type.
  17684. (org-element-put-property
  17685. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  17686. ;; Copy start properties over end properties if END is
  17687. ;; non-nil. Otherwise, copy end properties over `start' ones.
  17688. (let ((p-alist '((:minute-start . :minute-end)
  17689. (:hour-start . :hour-end)
  17690. (:day-start . :day-end)
  17691. (:month-start . :month-end)
  17692. (:year-start . :year-end))))
  17693. (dolist (p-cell p-alist)
  17694. (org-element-put-property
  17695. split-ts
  17696. (funcall (if end #'car #'cdr) p-cell)
  17697. (org-element-property
  17698. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  17699. ;; Eventually refresh `:raw-value'.
  17700. (org-element-put-property split-ts :raw-value nil)
  17701. (org-element-put-property
  17702. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  17703. (defun org-timestamp-translate (timestamp &optional boundary)
  17704. "Translate TIMESTAMP object to custom format.
  17705. Format string is defined in `org-time-stamp-custom-formats',
  17706. which see.
  17707. When optional argument BOUNDARY is non-nil, it is either the
  17708. symbol `start' or `end'. In this case, only translate the
  17709. starting or ending part of TIMESTAMP if it is a date or time
  17710. range. Otherwise, translate both parts.
  17711. Return timestamp as-is if `org-display-custom-times' is nil or if
  17712. it has a `diary' type."
  17713. (let ((type (org-element-property :type timestamp)))
  17714. (if (or (not org-display-custom-times) (eq type 'diary))
  17715. (org-element-interpret-data timestamp)
  17716. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  17717. org-time-stamp-custom-formats)))
  17718. (if (and (not boundary) (memq type '(active-range inactive-range)))
  17719. (concat (org-timestamp-format timestamp fmt)
  17720. "--"
  17721. (org-timestamp-format timestamp fmt t))
  17722. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  17723. ;;; Other stuff
  17724. (defvar reftex-docstruct-symbol)
  17725. (defvar org--rds)
  17726. (defun org-reftex-citation ()
  17727. "Use `reftex-citation' to insert a citation into the buffer.
  17728. This looks for a line like
  17729. #+BIBLIOGRAPHY: foo plain option:-d
  17730. and derives from it that foo.bib is the bibliography file relevant
  17731. for this document. It then installs the necessary environment for RefTeX
  17732. to work in this buffer and calls `reftex-citation' to insert a citation
  17733. into the buffer.
  17734. Export of such citations to both LaTeX and HTML is handled by the contributed
  17735. package ox-bibtex by Taru Karttunen."
  17736. (interactive)
  17737. (let ((reftex-docstruct-symbol 'org--rds)
  17738. org--rds bib)
  17739. (org-with-wide-buffer
  17740. (let ((case-fold-search t)
  17741. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  17742. (if (not (save-excursion
  17743. (or (re-search-forward re nil t)
  17744. (re-search-backward re nil t))))
  17745. (user-error "No bibliography defined in file")
  17746. (setq bib (concat (match-string 1) ".bib")
  17747. org--rds (list (list 'bib bib))))))
  17748. (call-interactively 'reftex-citation)))
  17749. ;;;; Functions extending outline functionality
  17750. (defun org-beginning-of-line (&optional n)
  17751. "Go to the beginning of the current visible line.
  17752. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17753. symbol `reversed', on the first attempt move to where the
  17754. headline text starts, and only move to beginning of line when the
  17755. cursor is already before the start of the text of the headline.
  17756. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  17757. start of the text on the second attempt.
  17758. With argument N not nil or 1, move forward N - 1 lines first."
  17759. (interactive "^p")
  17760. (let ((origin (point))
  17761. (special (pcase org-special-ctrl-a/e
  17762. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  17763. deactivate-mark)
  17764. ;; First move to a visible line.
  17765. (if (bound-and-true-p visual-line-mode)
  17766. (beginning-of-visual-line n)
  17767. (move-beginning-of-line n)
  17768. ;; `move-beginning-of-line' may leave point after invisible
  17769. ;; characters if line starts with such of these (e.g., with
  17770. ;; a link at column 0). Really move to the beginning of the
  17771. ;; current visible line.
  17772. (beginning-of-line))
  17773. (cond
  17774. ;; No special behavior. Point is already at the beginning of
  17775. ;; a line, logical or visual.
  17776. ((not special))
  17777. ;; `beginning-of-visual-line' left point before logical beginning
  17778. ;; of line: point is at the beginning of a visual line. Bail
  17779. ;; out.
  17780. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  17781. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  17782. ;; At a headline, special position is before the title, but
  17783. ;; after any TODO keyword or priority cookie.
  17784. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  17785. (line-end-position)))
  17786. (bol (point)))
  17787. (if (eq special 'reversed)
  17788. (when (and (= origin bol) (eq last-command this-command))
  17789. (goto-char refpos))
  17790. (when (or (> origin refpos) (= origin bol))
  17791. (goto-char refpos)))))
  17792. ((and (looking-at org-list-full-item-re)
  17793. (memq (org-element-type (save-match-data (org-element-at-point)))
  17794. '(item plain-list)))
  17795. ;; Set special position at first white space character after
  17796. ;; bullet, and check-box, if any.
  17797. (let ((after-bullet
  17798. (let ((box (match-end 3)))
  17799. (cond ((not box) (match-end 1))
  17800. ((eq (char-after box) ?\s) (1+ box))
  17801. (t box)))))
  17802. (if (eq special 'reversed)
  17803. (when (and (= (point) origin) (eq last-command this-command))
  17804. (goto-char after-bullet))
  17805. (when (or (> origin after-bullet) (= (point) origin))
  17806. (goto-char after-bullet)))))
  17807. ;; No special context. Point is already at beginning of line.
  17808. (t nil))))
  17809. (defun org-end-of-line (&optional n)
  17810. "Go to the end of the line, but before ellipsis, if any.
  17811. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17812. symbol `reversed', ignore tags on the first attempt, and only
  17813. move to after the tags when the cursor is already beyond the end
  17814. of the headline.
  17815. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  17816. on the second attempt.
  17817. With argument N not nil or 1, move forward N - 1 lines first."
  17818. (interactive "^p")
  17819. (let ((origin (point))
  17820. (special (pcase org-special-ctrl-a/e
  17821. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  17822. deactivate-mark)
  17823. ;; First move to a visible line.
  17824. (if (bound-and-true-p visual-line-mode)
  17825. (beginning-of-visual-line n)
  17826. (move-beginning-of-line n))
  17827. (cond
  17828. ;; At a headline, with tags.
  17829. ((and special
  17830. (save-excursion
  17831. (beginning-of-line)
  17832. (let ((case-fold-search nil))
  17833. (looking-at org-complex-heading-regexp)))
  17834. (match-end 5))
  17835. (let ((tags (save-excursion
  17836. (goto-char (match-beginning 5))
  17837. (skip-chars-backward " \t")
  17838. (point)))
  17839. (visual-end (and (bound-and-true-p visual-line-mode)
  17840. (save-excursion
  17841. (end-of-visual-line)
  17842. (point)))))
  17843. ;; If `end-of-visual-line' brings us before end of line or
  17844. ;; even tags, i.e., the headline spans over multiple visual
  17845. ;; lines, move there.
  17846. (cond ((and visual-end
  17847. (< visual-end tags)
  17848. (<= origin visual-end))
  17849. (goto-char visual-end))
  17850. ((eq special 'reversed)
  17851. (if (and (= origin (line-end-position))
  17852. (eq this-command last-command))
  17853. (goto-char tags)
  17854. (end-of-line)))
  17855. (t
  17856. (if (or (< origin tags) (= origin (line-end-position)))
  17857. (goto-char tags)
  17858. (end-of-line))))))
  17859. ((bound-and-true-p visual-line-mode)
  17860. (let ((bol (line-beginning-position)))
  17861. (end-of-visual-line)
  17862. ;; If `end-of-visual-line' gets us past the ellipsis at the
  17863. ;; end of a line, backtrack and use `end-of-line' instead.
  17864. (when (/= bol (line-beginning-position))
  17865. (goto-char bol)
  17866. (end-of-line))))
  17867. (t (end-of-line)))))
  17868. (defun org-backward-sentence (&optional _arg)
  17869. "Go to beginning of sentence, or beginning of table field.
  17870. This will call `backward-sentence' or `org-table-beginning-of-field',
  17871. depending on context."
  17872. (interactive)
  17873. (let* ((element (org-element-at-point))
  17874. (contents-begin (org-element-property :contents-begin element))
  17875. (table (org-element-lineage element '(table) t)))
  17876. (if (and table
  17877. (> (point) contents-begin)
  17878. (<= (point) (org-element-property :contents-end table)))
  17879. (call-interactively #'org-table-beginning-of-field)
  17880. (save-restriction
  17881. (when (and contents-begin
  17882. (< (point-min) contents-begin)
  17883. (> (point) contents-begin))
  17884. (narrow-to-region contents-begin
  17885. (org-element-property :contents-end element)))
  17886. (call-interactively #'backward-sentence)))))
  17887. (defun org-forward-sentence (&optional _arg)
  17888. "Go to end of sentence, or end of table field.
  17889. This will call `forward-sentence' or `org-table-end-of-field',
  17890. depending on context."
  17891. (interactive)
  17892. (if (and (org-at-heading-p)
  17893. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  17894. (save-restriction
  17895. (narrow-to-region (line-beginning-position) (line-end-position))
  17896. (call-interactively #'forward-sentence))
  17897. (let* ((element (org-element-at-point))
  17898. (contents-end (org-element-property :contents-end element))
  17899. (table (org-element-lineage element '(table) t)))
  17900. (if (and table
  17901. (>= (point) (org-element-property :contents-begin table))
  17902. (< (point) contents-end))
  17903. (call-interactively #'org-table-end-of-field)
  17904. (save-restriction
  17905. (when (and contents-end
  17906. (> (point-max) contents-end)
  17907. ;; Skip blank lines between elements.
  17908. (< (org-element-property :end element)
  17909. (save-excursion (goto-char contents-end)
  17910. (skip-chars-forward " \r\t\n"))))
  17911. (narrow-to-region (org-element-property :contents-begin element)
  17912. contents-end))
  17913. ;; End of heading is considered as the end of a sentence.
  17914. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  17915. (call-interactively #'forward-sentence)))))))
  17916. (defun org-kill-line (&optional _arg)
  17917. "Kill line, to tags or end of line."
  17918. (interactive)
  17919. (cond
  17920. ((or (not org-special-ctrl-k)
  17921. (bolp)
  17922. (not (org-at-heading-p)))
  17923. (when (and (org-invisible-p (line-end-position))
  17924. org-ctrl-k-protect-subtree
  17925. (or (eq org-ctrl-k-protect-subtree 'error)
  17926. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  17927. (user-error
  17928. (substitute-command-keys
  17929. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  17930. (call-interactively
  17931. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  17932. ((org-match-line org-tag-line-re)
  17933. (let ((end (save-excursion
  17934. (goto-char (match-beginning 1))
  17935. (skip-chars-backward " \t")
  17936. (point))))
  17937. (if (<= end (point)) ;on tags part
  17938. (kill-region (point) (line-end-position))
  17939. (kill-region (point) end)))
  17940. ;; Only align tags when we are still on a heading:
  17941. (if (org-at-heading-p) (org-align-tags)))
  17942. (t (kill-region (point) (line-end-position)))))
  17943. (defun org-yank (&optional arg)
  17944. "Yank. If the kill is a subtree, treat it specially.
  17945. This command will look at the current kill and check if is a single
  17946. subtree, or a series of subtrees[1]. If it passes the test, and if the
  17947. cursor is at the beginning of a line or after the stars of a currently
  17948. empty headline, then the yank is handled specially. How exactly depends
  17949. on the value of the following variables.
  17950. `org-yank-folded-subtrees'
  17951. By default, this variable is non-nil, which results in
  17952. subtree(s) being folded after insertion, except if doing so
  17953. would swallow text after the yanked text.
  17954. `org-yank-adjusted-subtrees'
  17955. When non-nil (the default value is nil), the subtree will be
  17956. promoted or demoted in order to fit into the local outline tree
  17957. structure, which means that the level will be adjusted so that it
  17958. becomes the smaller one of the two *visible* surrounding headings.
  17959. Any prefix to this command will cause `yank' to be called directly with
  17960. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  17961. will just
  17962. plainly yank the text as it is.
  17963. \[1] The test checks if the first non-white line is a heading
  17964. and if there are no other headings with fewer stars."
  17965. (interactive "P")
  17966. (org-yank-generic 'yank arg))
  17967. (defun org-yank-generic (command arg)
  17968. "Perform some yank-like command.
  17969. This function implements the behavior described in the `org-yank'
  17970. documentation. However, it has been generalized to work for any
  17971. interactive command with similar behavior."
  17972. ;; pretend to be command COMMAND
  17973. (setq this-command command)
  17974. (if arg
  17975. (call-interactively command)
  17976. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  17977. (and (org-kill-is-subtree-p)
  17978. (or (bolp)
  17979. (and (looking-at "[ \t]*$")
  17980. (string-match
  17981. "\\`\\*+\\'"
  17982. (buffer-substring (point-at-bol) (point)))))))
  17983. swallowp)
  17984. (cond
  17985. ((and subtreep org-yank-folded-subtrees)
  17986. (let ((beg (point))
  17987. end)
  17988. (if (and subtreep org-yank-adjusted-subtrees)
  17989. (org-paste-subtree nil nil 'for-yank)
  17990. (call-interactively command))
  17991. (setq end (point))
  17992. (goto-char beg)
  17993. (when (and (bolp) subtreep
  17994. (not (setq swallowp
  17995. (org-yank-folding-would-swallow-text beg end))))
  17996. (org-with-limited-levels
  17997. (or (looking-at org-outline-regexp)
  17998. (re-search-forward org-outline-regexp-bol end t))
  17999. (while (and (< (point) end) (looking-at org-outline-regexp))
  18000. (org-fold-subtree t)
  18001. (org-cycle-show-empty-lines 'folded)
  18002. (condition-case nil
  18003. (outline-forward-same-level 1)
  18004. (error (goto-char end))))))
  18005. (when swallowp
  18006. (message
  18007. "Inserted text not folded because that would swallow text"))
  18008. (goto-char end)
  18009. (skip-chars-forward " \t\n\r")
  18010. (beginning-of-line 1)
  18011. (push-mark beg 'nomsg)))
  18012. ((and subtreep org-yank-adjusted-subtrees)
  18013. (let ((beg (point-at-bol)))
  18014. (org-paste-subtree nil nil 'for-yank)
  18015. (push-mark beg 'nomsg)))
  18016. (t
  18017. (call-interactively command))))))
  18018. (defun org-yank-folding-would-swallow-text (beg end)
  18019. "Would `hide-subtree' at BEG swallow any text after END?"
  18020. (let (level)
  18021. (org-with-limited-levels
  18022. (save-excursion
  18023. (goto-char beg)
  18024. (when (or (looking-at org-outline-regexp)
  18025. (re-search-forward org-outline-regexp-bol end t))
  18026. (setq level (org-outline-level)))
  18027. (goto-char end)
  18028. (skip-chars-forward " \t\r\n\v\f")
  18029. (not (or (eobp)
  18030. (and (bolp) (looking-at-p org-outline-regexp)
  18031. (<= (org-outline-level) level))))))))
  18032. (defun org-back-to-heading (&optional invisible-ok)
  18033. "Go back to beginning of heading."
  18034. (beginning-of-line)
  18035. (or (org-at-heading-p (not invisible-ok))
  18036. (let (found)
  18037. (save-excursion
  18038. ;; At inlinetask end. Move to bol, so that the following
  18039. ;; search goes to the beginning of the inlinetask.
  18040. (when (and (featurep 'org-inlinetask)
  18041. (fboundp 'org-inlinetask-end-p)
  18042. (org-inlinetask-end-p))
  18043. (goto-char (line-beginning-position)))
  18044. (while (not found)
  18045. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18046. nil t)
  18047. (user-error "Before first headline at position %d in buffer %s"
  18048. (point) (current-buffer)))
  18049. ;; Skip inlinetask end.
  18050. (if (and (featurep 'org-inlinetask)
  18051. (fboundp 'org-inlinetask-end-p)
  18052. (org-inlinetask-end-p))
  18053. (org-inlinetask-goto-beginning)
  18054. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18055. (point))))))
  18056. (goto-char found)
  18057. found)))
  18058. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18059. "Go back to heading or first point in buffer.
  18060. If point is before first heading go to first point in buffer
  18061. instead of back to heading."
  18062. (if (org-before-first-heading-p)
  18063. (goto-char (point-min))
  18064. (org-back-to-heading invisible-ok)))
  18065. (defun org-before-first-heading-p ()
  18066. "Before first heading?
  18067. Respect narrowing."
  18068. (if (org-element--cache-active-p)
  18069. (let ((cached-headline (org-element-lineage (org-element-at-point) '(headline) t)))
  18070. (or (not cached-headline)
  18071. (< (org-element-property :begin cached-headline) (point-min))))
  18072. (org-with-limited-levels
  18073. (save-excursion
  18074. (end-of-line)
  18075. (null (re-search-backward org-outline-regexp-bol nil t))))))
  18076. (defun org-at-heading-p (&optional invisible-not-ok)
  18077. "Return t if point is on a (possibly invisible) heading line.
  18078. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18079. (save-excursion
  18080. (beginning-of-line)
  18081. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18082. (looking-at outline-regexp))))
  18083. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18084. "Non-nil if point is under a commented heading.
  18085. This function also checks ancestors of the current headline,
  18086. unless optional argument NO-INHERITANCE is non-nil.
  18087. Optional argument ELEMENT contains element at point."
  18088. (save-match-data
  18089. (let ((el (or element (org-element-at-point nil 'cached))))
  18090. (if el
  18091. (catch :found
  18092. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18093. (if no-inheritance
  18094. (org-element-property :commentedp el)
  18095. (while el
  18096. (when (org-element-property :commentedp el)
  18097. (throw :found t))
  18098. (setq el (org-element-property :parent el)))))
  18099. (cond
  18100. ((org-before-first-heading-p) nil)
  18101. ((let ((headline (nth 4 (org-heading-components))))
  18102. (and headline
  18103. (let ((case-fold-search nil))
  18104. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18105. headline)))))
  18106. (no-inheritance nil)
  18107. (t
  18108. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p)))))))))
  18109. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18110. "Non-nil if point is under an archived heading.
  18111. This function also checks ancestors of the current headline,
  18112. unless optional argument NO-INHERITANCE is non-nil.
  18113. Optional argument ELEMENT contains element at point."
  18114. (cond
  18115. ((and (not element) (org-before-first-heading-p)) nil)
  18116. ((if element
  18117. (org-element-property :archivedp element)
  18118. (let ((tags (org-get-tags element 'local)))
  18119. (and tags
  18120. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18121. (no-inheritance nil)
  18122. (t
  18123. (if (org-element--cache-active-p)
  18124. (cl-some (lambda (el) (org-element-property :archivedp el))
  18125. (org-element-lineage (or element (org-element-at-point)) nil t))
  18126. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18127. (defun org-at-comment-p nil
  18128. "Return t if cursor is in a commented line."
  18129. (save-excursion
  18130. (save-match-data
  18131. (beginning-of-line)
  18132. (looking-at org-comment-regexp))))
  18133. (defun org-at-keyword-p nil
  18134. "Return t if cursor is at a keyword-line."
  18135. (save-excursion
  18136. (move-beginning-of-line 1)
  18137. (looking-at org-keyword-regexp)))
  18138. (defun org-at-drawer-p nil
  18139. "Return t if cursor is at a drawer keyword."
  18140. (save-excursion
  18141. (move-beginning-of-line 1)
  18142. (looking-at org-drawer-regexp)))
  18143. (defun org-at-block-p nil
  18144. "Return t if cursor is at a block keyword."
  18145. (save-excursion
  18146. (move-beginning-of-line 1)
  18147. (looking-at org-block-regexp)))
  18148. (defun org-point-at-end-of-empty-headline ()
  18149. "If point is at the end of an empty headline, return t, else nil.
  18150. If the heading only contains a TODO keyword, it is still considered
  18151. empty."
  18152. (let ((case-fold-search nil))
  18153. (and (looking-at "[ \t]*$")
  18154. org-todo-line-regexp
  18155. (save-excursion
  18156. (beginning-of-line)
  18157. (looking-at org-todo-line-regexp)
  18158. (string= (match-string 3) "")))))
  18159. (defun org-at-heading-or-item-p ()
  18160. (or (org-at-heading-p) (org-at-item-p)))
  18161. (defun org-up-heading-all (arg)
  18162. "Move to the heading line of which the present line is a subheading.
  18163. This function considers both visible and invisible heading lines.
  18164. With argument, move up ARG levels."
  18165. (outline-up-heading arg t))
  18166. (defvar-local org--up-heading-cache nil
  18167. "Buffer-local `org-up-heading-safe' cache.")
  18168. (defvar-local org--up-heading-cache-tick nil
  18169. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18170. (defun org-up-heading-safe ()
  18171. "Move to the heading line of which the present line is a subheading.
  18172. This version will not throw an error. It will return the level of the
  18173. headline found, or nil if no higher level is found.
  18174. Also, this function will be a lot faster than `outline-up-heading',
  18175. because it relies on stars being the outline starters. This can really
  18176. make a significant difference in outlines with very many siblings."
  18177. (let ((element (and (org-element--cache-active-p)
  18178. (org-element-at-point nil t))))
  18179. (if element
  18180. (let* ((current-heading (org-element-lineage element '(headline) 'with-self))
  18181. (parent (org-element-lineage current-heading '(headline))))
  18182. (if (and parent
  18183. (<= (point-min) (org-element-property :begin parent)))
  18184. (progn
  18185. (goto-char (org-element-property :begin parent))
  18186. (org-element-property :level parent))
  18187. (when (and current-heading
  18188. (<= (point-min) (org-element-property :begin current-heading)))
  18189. (goto-char (org-element-property :begin current-heading))
  18190. nil)))
  18191. (when (ignore-errors (org-back-to-heading t))
  18192. (let (level-cache)
  18193. (unless org--up-heading-cache
  18194. (setq org--up-heading-cache (make-hash-table)))
  18195. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18196. (setq level-cache (gethash (point) org--up-heading-cache)))
  18197. (when (<= (point-min) (car level-cache) (point-max))
  18198. ;; Parent is inside accessible part of the buffer.
  18199. (progn (goto-char (car level-cache))
  18200. (cdr level-cache)))
  18201. ;; Buffer modified. Invalidate cache.
  18202. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18203. (setq-local org--up-heading-cache-tick
  18204. (buffer-chars-modified-tick))
  18205. (clrhash org--up-heading-cache))
  18206. (let* ((level-up (1- (funcall outline-level)))
  18207. (pos (point))
  18208. (result (and (> level-up 0)
  18209. (re-search-backward
  18210. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18211. (funcall outline-level))))
  18212. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18213. result)))))))
  18214. (defun org-up-heading-or-point-min ()
  18215. "Move to the heading line of which the present is a subheading, or point-min.
  18216. This version is needed to make point-min behave like a virtual
  18217. heading of level 0 for property-inheritance. It will return the
  18218. level of the headline found (down to 0) or nil if already at a
  18219. point before the first headline or at point-min."
  18220. (when (ignore-errors (org-back-to-heading t))
  18221. (if (< 1 (funcall outline-level))
  18222. (or (org-up-heading-safe)
  18223. ;; The first heading may not be level 1 heading.
  18224. (goto-char (point-min)))
  18225. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18226. (defun org-first-sibling-p ()
  18227. "Is this heading the first child of its parents?"
  18228. (interactive)
  18229. (let ((re org-outline-regexp-bol)
  18230. level l)
  18231. (unless (org-at-heading-p t)
  18232. (user-error "Not at a heading"))
  18233. (setq level (funcall outline-level))
  18234. (save-excursion
  18235. (if (not (re-search-backward re nil t))
  18236. t
  18237. (setq l (funcall outline-level))
  18238. (< l level)))))
  18239. (defun org-goto-sibling (&optional previous)
  18240. "Goto the next sibling, even if it is invisible.
  18241. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18242. when a sibling was found. When none is found, return nil and don't
  18243. move point."
  18244. (let ((fun (if previous 're-search-backward 're-search-forward))
  18245. (pos (point))
  18246. (re org-outline-regexp-bol)
  18247. level l)
  18248. (when (ignore-errors (org-back-to-heading t))
  18249. (setq level (funcall outline-level))
  18250. (catch 'exit
  18251. (or previous (forward-char 1))
  18252. (while (funcall fun re nil t)
  18253. (setq l (funcall outline-level))
  18254. (when (< l level) (goto-char pos) (throw 'exit nil))
  18255. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18256. (goto-char pos)
  18257. nil))))
  18258. (defun org-goto-first-child (&optional element)
  18259. "Goto the first child, even if it is invisible.
  18260. Return t when a child was found. Otherwise don't move point and
  18261. return nil."
  18262. (if (org-element--cache-active-p)
  18263. (let ((heading (org-element-lineage
  18264. (or element (org-element-at-point))
  18265. '(headline inlinetask org-data)
  18266. t)))
  18267. (when heading
  18268. (unless (or (eq 'inlinetask (org-element-type heading))
  18269. (not (org-element-property :contents-begin heading)))
  18270. (let ((pos (point)))
  18271. (goto-char (org-element-property :contents-begin heading))
  18272. (if (re-search-forward
  18273. org-outline-regexp-bol
  18274. (org-element-property :end heading)
  18275. t)
  18276. (progn (goto-char (match-beginning 0)) t)
  18277. (goto-char pos) nil)))))
  18278. (let (level (pos (point)) (re org-outline-regexp-bol))
  18279. (when (org-back-to-heading-or-point-min t)
  18280. (setq level (org-outline-level))
  18281. (forward-char 1)
  18282. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18283. (progn (goto-char (match-beginning 0)) t)
  18284. (goto-char pos) nil)))))
  18285. (defun org-get-next-sibling ()
  18286. "Move to next heading of the same level, and return point.
  18287. If there is no such heading, return nil.
  18288. This is like outline-next-sibling, but invisible headings are ok."
  18289. (let ((level (funcall outline-level)))
  18290. (outline-next-heading)
  18291. (while (and (not (eobp)) (> (funcall outline-level) level))
  18292. (outline-next-heading))
  18293. (unless (or (eobp) (< (funcall outline-level) level))
  18294. (point))))
  18295. (defun org-get-previous-sibling ()
  18296. "Move to previous heading of the same level, and return point.
  18297. If there is no such heading, return nil."
  18298. (let ((opoint (point))
  18299. (level (funcall outline-level)))
  18300. (outline-previous-heading)
  18301. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18302. (while (and (> (funcall outline-level) level)
  18303. (not (bobp)))
  18304. (outline-previous-heading))
  18305. (unless (< (funcall outline-level) level)
  18306. (point)))))
  18307. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18308. "Goto to the end of a subtree at point or for ELEMENT heading."
  18309. ;; This contains an exact copy of the original function, but it uses
  18310. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18311. ;; trees and before first headline. And is uses an invisible-ok argument.
  18312. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18313. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18314. ;; with many children and grandchildren etc, this can be much faster
  18315. ;; than the outline version.
  18316. (org-back-to-heading-or-point-min invisible-ok)
  18317. (unless (and (org-element--cache-active-p)
  18318. (let ((cached (or element (org-element-at-point nil t))))
  18319. (and cached
  18320. (eq 'headline (org-element-type cached))
  18321. (goto-char (org-element-property
  18322. :end cached)))))
  18323. (let ((first t)
  18324. (level (funcall outline-level)))
  18325. (cond ((= level 0)
  18326. (goto-char (point-max)))
  18327. ((and (derived-mode-p 'org-mode) (< level 1000))
  18328. ;; A true heading (not a plain list item), in Org
  18329. ;; This means we can easily find the end by looking
  18330. ;; only for the right number of stars. Using a regexp to do
  18331. ;; this is so much faster than using a Lisp loop.
  18332. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18333. (forward-char 1)
  18334. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18335. (t
  18336. ;; something else, do it the slow way
  18337. (while (and (not (eobp))
  18338. (or first (> (funcall outline-level) level)))
  18339. (setq first nil)
  18340. (outline-next-heading))))))
  18341. (unless to-heading
  18342. (when (memq (preceding-char) '(?\n ?\^M))
  18343. ;; Go to end of line before heading
  18344. (forward-char -1)
  18345. (when (memq (preceding-char) '(?\n ?\^M))
  18346. ;; leave blank line before heading
  18347. (forward-char -1))))
  18348. (point))
  18349. (defun org-end-of-meta-data (&optional full)
  18350. "Skip planning line and properties drawer in current entry.
  18351. When optional argument FULL is t, also skip planning information,
  18352. clocking lines and any kind of drawer.
  18353. When FULL is non-nil but not t, skip planning information,
  18354. properties, clocking lines and logbook drawers."
  18355. (org-back-to-heading t)
  18356. (forward-line)
  18357. ;; Skip planning information.
  18358. (when (looking-at-p org-planning-line-re) (forward-line))
  18359. ;; Skip property drawer.
  18360. (when (looking-at org-property-drawer-re)
  18361. (goto-char (match-end 0))
  18362. (forward-line))
  18363. ;; When FULL is not nil, skip more.
  18364. (when (and full (not (org-at-heading-p)))
  18365. (catch 'exit
  18366. (let ((end (save-excursion (outline-next-heading) (point)))
  18367. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18368. (while (not (eobp))
  18369. (cond ;; Skip clock lines.
  18370. ((looking-at-p re) (forward-line))
  18371. ;; Skip logbook drawer.
  18372. ((looking-at-p org-logbook-drawer-re)
  18373. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18374. (forward-line)
  18375. (throw 'exit t)))
  18376. ;; When FULL is t, skip regular drawer too.
  18377. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18378. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18379. (forward-line)
  18380. (throw 'exit t)))
  18381. (t (throw 'exit t))))))))
  18382. (defun org--line-fully-invisible-p ()
  18383. "Return non-nil if the current line is fully invisible."
  18384. (let ((line-beg (line-beginning-position))
  18385. (line-pos (1- (line-end-position)))
  18386. (is-invisible t))
  18387. (while (and (< line-beg line-pos) is-invisible)
  18388. (setq is-invisible (org-invisible-p line-pos))
  18389. (setq line-pos (1- line-pos)))
  18390. is-invisible))
  18391. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18392. "Move forward to the ARG'th subheading at same level as this one.
  18393. Stop at the first and last subheadings of a superior heading.
  18394. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18395. non-nil it will also look at invisible ones."
  18396. (interactive "p")
  18397. (let ((backward? (and arg (< arg 0))))
  18398. (if (org-before-first-heading-p)
  18399. (if backward? (goto-char (point-min)) (outline-next-heading))
  18400. (org-back-to-heading invisible-ok)
  18401. (unless backward? (end-of-line)) ;do not match current headline
  18402. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18403. (f (if backward? #'re-search-backward #'re-search-forward))
  18404. (count (if arg (abs arg) 1))
  18405. (result (point)))
  18406. (while (and (> count 0)
  18407. (funcall f org-outline-regexp-bol nil 'move))
  18408. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18409. (cond ((< l level) (setq count 0))
  18410. ((and (= l level)
  18411. (or invisible-ok
  18412. ;; FIXME: See commit a700fadd72 and the
  18413. ;; related discussion on why using
  18414. ;; `org--line-fully-invisible-p' is needed
  18415. ;; here, which is to serve the needs of an
  18416. ;; external package. If the change is
  18417. ;; wrong regarding Org itself, it should
  18418. ;; be removed.
  18419. (not (org--line-fully-invisible-p))))
  18420. (cl-decf count)
  18421. (when (= l level) (setq result (point)))))))
  18422. (goto-char result))
  18423. (beginning-of-line))))
  18424. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18425. "Move backward to the ARG'th subheading at same level as this one.
  18426. Stop at the first and last subheadings of a superior heading."
  18427. (interactive "p")
  18428. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18429. (defun org-next-visible-heading--overlays (arg)
  18430. "Move to the next visible heading line.
  18431. With ARG, repeats or can move backward if negative."
  18432. (interactive "p")
  18433. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18434. (if (< arg 0)
  18435. (beginning-of-line)
  18436. (end-of-line))
  18437. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18438. (unless (bobp)
  18439. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18440. (`(outline . ,o)
  18441. (goto-char (overlay-start o))
  18442. (re-search-backward regexp nil :move))
  18443. (_ nil))))
  18444. (cl-incf arg))
  18445. (while (and (> arg 0) (re-search-forward regexp nil t))
  18446. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18447. (`(outline . ,o)
  18448. (goto-char (overlay-end o))
  18449. (re-search-forward regexp nil :move))
  18450. (_
  18451. (end-of-line)
  18452. nil))) ;leave the loop
  18453. (cl-decf arg))
  18454. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18455. (defun org-next-visible-heading--text-properties (arg)
  18456. "Move to the next visible heading line.
  18457. With ARG, repeats or can move backward if negative."
  18458. (interactive "p")
  18459. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18460. (if (< arg 0)
  18461. (beginning-of-line)
  18462. (end-of-line))
  18463. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18464. (unless (bobp)
  18465. (when (org-fold-folded-p)
  18466. (goto-char (org-fold-previous-visibility-change))
  18467. (unless (looking-at-p regexp)
  18468. (re-search-backward regexp nil :mode))))
  18469. (cl-incf arg))
  18470. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18471. (when (org-fold-folded-p)
  18472. (goto-char (org-fold-next-visibility-change))
  18473. (skip-chars-forward " \t\n")
  18474. (end-of-line))
  18475. (cl-decf arg))
  18476. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18477. (defun org-next-visible-heading (arg)
  18478. "Move to the next visible heading line.
  18479. With ARG, repeats or can move backward if negative."
  18480. (interactive "p")
  18481. (if (eq org-fold-core-style 'text-properties)
  18482. (org-next-visible-heading--text-properties arg)
  18483. (org-next-visible-heading--overlays arg)))
  18484. (defun org-previous-visible-heading (arg)
  18485. "Move to the previous visible heading.
  18486. With ARG, repeats or can move forward if negative."
  18487. (interactive "p")
  18488. (org-next-visible-heading (- arg)))
  18489. (defun org-forward-paragraph (&optional arg)
  18490. "Move forward by a paragraph, or equivalent, unit.
  18491. With argument ARG, do it ARG times;
  18492. a negative argument ARG = -N means move backward N paragraphs.
  18493. The function moves point between two structural
  18494. elements (paragraphs, tables, lists, etc.).
  18495. It also provides the following special moves for convenience:
  18496. - on a table or a property drawer, move to its beginning;
  18497. - on comment, example, export, source and verse blocks, stop
  18498. at blank lines;
  18499. - skip consecutive clocks, diary S-exps, and keywords."
  18500. (interactive "^p")
  18501. (unless arg (setq arg 1))
  18502. (if (< arg 0) (org-backward-paragraph (- arg))
  18503. (while (and (> arg 0) (not (eobp)))
  18504. (org--forward-paragraph-once)
  18505. (cl-decf arg))
  18506. ;; Return moves left.
  18507. arg))
  18508. (defun org-backward-paragraph (&optional arg)
  18509. "Move backward by a paragraph, or equivalent, unit.
  18510. With argument ARG, do it ARG times;
  18511. a negative argument ARG = -N means move forward N paragraphs.
  18512. The function moves point between two structural
  18513. elements (paragraphs, tables, lists, etc.).
  18514. It also provides the following special moves for convenience:
  18515. - on a table or a property drawer, move to its beginning;
  18516. - on comment, example, export, source and verse blocks, stop
  18517. at blank lines;
  18518. - skip consecutive clocks, diary S-exps, and keywords."
  18519. (interactive "^p")
  18520. (unless arg (setq arg 1))
  18521. (if (< arg 0) (org-forward-paragraph (- arg))
  18522. (while (and (> arg 0) (not (bobp)))
  18523. (org--backward-paragraph-once)
  18524. (cl-decf arg))
  18525. ;; Return moves left.
  18526. arg))
  18527. (defun org--paragraph-at-point ()
  18528. "Return paragraph, or equivalent, element at point.
  18529. Paragraph element at point is the element at point, with the
  18530. following special cases:
  18531. - treat table rows (resp. node properties) as the table
  18532. \(resp. property drawer) containing them.
  18533. - treat plain lists with an item every line as a whole.
  18534. - treat consecutive keywords, clocks, and diary-sexps as a single
  18535. block.
  18536. Function may return a real element, or a pseudo-element with type
  18537. `pseudo-paragraph'."
  18538. (let* ((e (org-element-at-point))
  18539. (type (org-element-type e))
  18540. ;; If we need to fake a new pseudo-element, triplet is
  18541. ;;
  18542. ;; (BEG END PARENT)
  18543. ;;
  18544. ;; where BEG and END are element boundaries, and PARENT the
  18545. ;; element containing it, or nil.
  18546. (triplet
  18547. (cond
  18548. ((memq type '(table property-drawer))
  18549. (list (org-element-property :begin e)
  18550. (org-element-property :end e)
  18551. (org-element-property :parent e)))
  18552. ((memq type '(node-property table-row))
  18553. (let ((e (org-element-property :parent e)))
  18554. (list (org-element-property :begin e)
  18555. (org-element-property :end e)
  18556. (org-element-property :parent e))))
  18557. ((memq type '(clock diary-sexp keyword))
  18558. (let* ((regexp (pcase type
  18559. (`clock org-clock-line-re)
  18560. (`diary-sexp "%%(")
  18561. (_ org-keyword-regexp)))
  18562. (end (if (< 0 (org-element-property :post-blank e))
  18563. (org-element-property :end e)
  18564. (org-with-wide-buffer
  18565. (forward-line)
  18566. (while (looking-at regexp) (forward-line))
  18567. (skip-chars-forward " \t\n")
  18568. (line-beginning-position))))
  18569. (begin (org-with-point-at (org-element-property :begin e)
  18570. (while (and (not (bobp)) (looking-at regexp))
  18571. (forward-line -1))
  18572. ;; We may have gotten one line too far.
  18573. (if (looking-at regexp)
  18574. (point)
  18575. (line-beginning-position 2)))))
  18576. (list begin end (org-element-property :parent e))))
  18577. ;; Find the full plain list containing point, the check it
  18578. ;; contains exactly one line per item.
  18579. ((let ((l (org-element-lineage e '(plain-list) t)))
  18580. (while (memq (org-element-type (org-element-property :parent l))
  18581. '(item plain-list))
  18582. (setq l (org-element-property :parent l)))
  18583. (and l
  18584. (org-with-point-at (org-element-property :post-affiliated l)
  18585. (forward-line (length (org-element-property :structure l)))
  18586. (= (point) (org-element-property :contents-end l)))
  18587. ;; Return value.
  18588. (list (org-element-property :begin l)
  18589. (org-element-property :end l)
  18590. (org-element-property :parent l)))))
  18591. (t nil)))) ;no triplet: return element
  18592. (pcase triplet
  18593. (`(,b ,e ,p)
  18594. (org-element-create
  18595. 'pseudo-paragraph
  18596. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18597. (_ e))))
  18598. (defun org--forward-paragraph-once--overlays ()
  18599. "Move forward to end of paragraph or equivalent, once.
  18600. See `org-forward-paragraph'."
  18601. (interactive)
  18602. (save-restriction
  18603. (widen)
  18604. (skip-chars-forward " \t\n")
  18605. (cond
  18606. ((eobp) nil)
  18607. ;; When inside a folded part, move out of it.
  18608. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18609. (`(,(or `outline `org-hide-block) . ,o)
  18610. (goto-char (overlay-end o))
  18611. (forward-line)
  18612. t)
  18613. (_ nil)))
  18614. (t
  18615. (let* ((element (org--paragraph-at-point))
  18616. (type (org-element-type element))
  18617. (contents-begin (org-element-property :contents-begin element))
  18618. (end (org-element-property :end element))
  18619. (post-affiliated (org-element-property :post-affiliated element)))
  18620. (cond
  18621. ((eq type 'plain-list)
  18622. (forward-char)
  18623. (org--forward-paragraph-once))
  18624. ;; If the element is folded, skip it altogether.
  18625. ((pcase (org-with-point-at post-affiliated
  18626. (get-char-property-and-overlay (line-end-position)
  18627. 'invisible))
  18628. (`(,(or `outline `org-hide-block) . ,o)
  18629. (goto-char (overlay-end o))
  18630. (forward-line)
  18631. t)
  18632. (_ nil)))
  18633. ;; At a greater element, move inside.
  18634. ((and contents-begin
  18635. (> contents-begin (point))
  18636. (not (eq type 'paragraph)))
  18637. (goto-char contents-begin)
  18638. ;; Items and footnote definitions contents may not start at
  18639. ;; the beginning of the line. In this case, skip until the
  18640. ;; next paragraph.
  18641. (cond
  18642. ((not (bolp)) (org--forward-paragraph-once))
  18643. ((org-previous-line-empty-p) (forward-line -1))
  18644. (t nil)))
  18645. ;; Move between empty lines in some blocks.
  18646. ((memq type '(comment-block example-block export-block src-block
  18647. verse-block))
  18648. (let ((contents-start
  18649. (org-with-point-at post-affiliated
  18650. (line-beginning-position 2))))
  18651. (if (< (point) contents-start)
  18652. (goto-char contents-start)
  18653. (let ((contents-end
  18654. (org-with-point-at end
  18655. (skip-chars-backward " \t\n")
  18656. (line-beginning-position))))
  18657. (cond
  18658. ((>= (point) contents-end)
  18659. (goto-char end)
  18660. (skip-chars-backward " \t\n")
  18661. (forward-line))
  18662. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18663. (forward-line -1))
  18664. (t nil))))))
  18665. (t
  18666. ;; Move to element's end.
  18667. (goto-char end)
  18668. (skip-chars-backward " \t\n")
  18669. (forward-line))))))))
  18670. (defun org--forward-paragraph-once--text-properties ()
  18671. "Move forward to end of paragraph or equivalent, once.
  18672. See `org-forward-paragraph'."
  18673. (interactive)
  18674. (save-restriction
  18675. (widen)
  18676. (skip-chars-forward " \t\n")
  18677. (cond
  18678. ((eobp) nil)
  18679. ;; When inside a folded part, move out of it.
  18680. ((when (org-invisible-p nil t)
  18681. (goto-char (cdr (org-fold-get-region-at-point)))
  18682. (forward-line)
  18683. t))
  18684. (t
  18685. (let* ((element (org--paragraph-at-point))
  18686. (type (org-element-type element))
  18687. (contents-begin (org-element-property :contents-begin element))
  18688. (end (org-element-property :end element))
  18689. (post-affiliated (org-element-property :post-affiliated element)))
  18690. (cond
  18691. ((eq type 'plain-list)
  18692. (forward-char)
  18693. (org--forward-paragraph-once))
  18694. ;; If the element is folded, skip it altogether.
  18695. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18696. (goto-char (cdr (org-fold-get-region-at-point
  18697. nil
  18698. (org-with-point-at post-affiliated
  18699. (line-end-position)))))
  18700. (forward-line)
  18701. t))
  18702. ;; At a greater element, move inside.
  18703. ((and contents-begin
  18704. (> contents-begin (point))
  18705. (not (eq type 'paragraph)))
  18706. (goto-char contents-begin)
  18707. ;; Items and footnote definitions contents may not start at
  18708. ;; the beginning of the line. In this case, skip until the
  18709. ;; next paragraph.
  18710. (cond
  18711. ((not (bolp)) (org--forward-paragraph-once))
  18712. ((org-previous-line-empty-p) (forward-line -1))
  18713. (t nil)))
  18714. ;; Move between empty lines in some blocks.
  18715. ((memq type '(comment-block example-block export-block src-block
  18716. verse-block))
  18717. (let ((contents-start
  18718. (org-with-point-at post-affiliated
  18719. (line-beginning-position 2))))
  18720. (if (< (point) contents-start)
  18721. (goto-char contents-start)
  18722. (let ((contents-end
  18723. (org-with-point-at end
  18724. (skip-chars-backward " \t\n")
  18725. (line-beginning-position))))
  18726. (cond
  18727. ((>= (point) contents-end)
  18728. (goto-char end)
  18729. (skip-chars-backward " \t\n")
  18730. (forward-line))
  18731. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18732. (forward-line -1))
  18733. (t nil))))))
  18734. (t
  18735. ;; Move to element's end.
  18736. (goto-char end)
  18737. (skip-chars-backward " \t\n")
  18738. (forward-line))))))))
  18739. (defun org--forward-paragraph-once ()
  18740. "Move forward to end of paragraph or equivalent, once.
  18741. See `org-forward-paragraph'."
  18742. (interactive)
  18743. (if (eq org-fold-core-style 'text-properties)
  18744. (org--forward-paragraph-once--text-properties)
  18745. (org--forward-paragraph-once--overlays)))
  18746. (defun org--backward-paragraph-once--overlays ()
  18747. "Move backward to start of paragraph or equivalent, once.
  18748. See `org-backward-paragraph'."
  18749. (interactive)
  18750. (save-restriction
  18751. (widen)
  18752. (cond
  18753. ((bobp) nil)
  18754. ;; Blank lines at the beginning of the buffer.
  18755. ((and (org-match-line "^[ \t]*$")
  18756. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18757. (goto-char (point-min)))
  18758. ;; When inside a folded part, move out of it.
  18759. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18760. (`(,(or `outline `org-hide-block) . ,o)
  18761. (goto-char (1- (overlay-start o)))
  18762. (org--backward-paragraph-once)
  18763. t)
  18764. (_ nil)))
  18765. (t
  18766. (let* ((element (org--paragraph-at-point))
  18767. (type (org-element-type element))
  18768. (begin (org-element-property :begin element))
  18769. (post-affiliated (org-element-property :post-affiliated element))
  18770. (contents-end (org-element-property :contents-end element))
  18771. (end (org-element-property :end element))
  18772. (parent (org-element-property :parent element))
  18773. (reach
  18774. ;; Move to the visible empty line above position P, or
  18775. ;; to position P. Return t.
  18776. (lambda (p)
  18777. (goto-char p)
  18778. (when (and (org-previous-line-empty-p)
  18779. (let ((end (line-end-position 0)))
  18780. (or (= end (point-min))
  18781. (not (org-invisible-p (1- end))))))
  18782. (forward-line -1))
  18783. t)))
  18784. (cond
  18785. ;; Already at the beginning of an element.
  18786. ((= begin (point))
  18787. (cond
  18788. ;; There is a blank line above. Move there.
  18789. ((and (org-previous-line-empty-p)
  18790. (let ((lep (line-end-position 0)))
  18791. ;; When the first headline start at point 2, don't choke while
  18792. ;; checking with `org-invisible-p'.
  18793. (or (= lep 1)
  18794. (not (org-invisible-p (1- (line-end-position 0)))))))
  18795. (forward-line -1))
  18796. ;; At the beginning of the first element within a greater
  18797. ;; element. Move to the beginning of the greater element.
  18798. ((and parent
  18799. (not (eq 'section (org-element-type parent)))
  18800. (= begin (org-element-property :contents-begin parent)))
  18801. (funcall reach (org-element-property :begin parent)))
  18802. ;; Since we have to move anyway, find the beginning
  18803. ;; position of the element above.
  18804. (t
  18805. (forward-char -1)
  18806. (org--backward-paragraph-once))))
  18807. ;; Skip paragraphs at the very beginning of footnote
  18808. ;; definitions or items.
  18809. ((and (eq type 'paragraph)
  18810. (org-with-point-at begin (not (bolp))))
  18811. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  18812. ;; If the element is folded, skip it altogether.
  18813. ((org-with-point-at post-affiliated
  18814. (org-invisible-p (line-end-position) t))
  18815. (funcall reach begin))
  18816. ;; At the end of a greater element, move inside.
  18817. ((and contents-end
  18818. (<= contents-end (point))
  18819. (not (eq type 'paragraph)))
  18820. (cond
  18821. ((memq type '(footnote-definition plain-list))
  18822. (skip-chars-backward " \t\n")
  18823. (org--backward-paragraph-once))
  18824. ((= contents-end (point))
  18825. (forward-char -1)
  18826. (org--backward-paragraph-once))
  18827. (t
  18828. (goto-char contents-end))))
  18829. ;; Move between empty lines in some blocks.
  18830. ((and (memq type '(comment-block example-block export-block src-block
  18831. verse-block))
  18832. (let ((contents-start
  18833. (org-with-point-at post-affiliated
  18834. (line-beginning-position 2))))
  18835. (when (> (point) contents-start)
  18836. (let ((contents-end
  18837. (org-with-point-at end
  18838. (skip-chars-backward " \t\n")
  18839. (line-beginning-position))))
  18840. (if (> (point) contents-end)
  18841. (progn (goto-char contents-end) t)
  18842. (skip-chars-backward " \t\n" begin)
  18843. (re-search-backward "^[ \t]*\n" contents-start :move)
  18844. t))))))
  18845. ;; Move to element's start.
  18846. (t
  18847. (funcall reach begin))))))))
  18848. (defun org--backward-paragraph-once--text-properties ()
  18849. "Move backward to start of paragraph or equivalent, once.
  18850. See `org-backward-paragraph'."
  18851. (interactive)
  18852. (save-restriction
  18853. (widen)
  18854. (cond
  18855. ((bobp) nil)
  18856. ;; Blank lines at the beginning of the buffer.
  18857. ((and (org-match-line "^[ \t]*$")
  18858. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18859. (goto-char (point-min)))
  18860. ;; When inside a folded part, move out of it.
  18861. ((when (org-invisible-p (1- (point)) t)
  18862. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  18863. (org--backward-paragraph-once)
  18864. t))
  18865. (t
  18866. (let* ((element (org--paragraph-at-point))
  18867. (type (org-element-type element))
  18868. (begin (org-element-property :begin element))
  18869. (post-affiliated (org-element-property :post-affiliated element))
  18870. (contents-end (org-element-property :contents-end element))
  18871. (end (org-element-property :end element))
  18872. (parent (org-element-property :parent element))
  18873. (reach
  18874. ;; Move to the visible empty line above position P, or
  18875. ;; to position P. Return t.
  18876. (lambda (p)
  18877. (goto-char p)
  18878. (when (and (org-previous-line-empty-p)
  18879. (let ((end (line-end-position 0)))
  18880. (or (= end (point-min))
  18881. (not (org-invisible-p (1- end))))))
  18882. (forward-line -1))
  18883. t)))
  18884. (cond
  18885. ;; Already at the beginning of an element.
  18886. ((= begin (point))
  18887. (cond
  18888. ;; There is a blank line above. Move there.
  18889. ((and (org-previous-line-empty-p)
  18890. (not (org-invisible-p (1- (line-end-position 0)))))
  18891. (forward-line -1))
  18892. ;; At the beginning of the first element within a greater
  18893. ;; element. Move to the beginning of the greater element.
  18894. ((and parent
  18895. (not (eq 'section (org-element-type parent)))
  18896. (= begin (org-element-property :contents-begin parent)))
  18897. (funcall reach (org-element-property :begin parent)))
  18898. ;; Since we have to move anyway, find the beginning
  18899. ;; position of the element above.
  18900. (t
  18901. (forward-char -1)
  18902. (org--backward-paragraph-once))))
  18903. ;; Skip paragraphs at the very beginning of footnote
  18904. ;; definitions or items.
  18905. ((and (eq type 'paragraph)
  18906. (org-with-point-at begin (not (bolp))))
  18907. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  18908. ;; If the element is folded, skip it altogether.
  18909. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18910. (funcall reach begin))
  18911. ;; At the end of a greater element, move inside.
  18912. ((and contents-end
  18913. (<= contents-end (point))
  18914. (not (eq type 'paragraph)))
  18915. (cond
  18916. ((memq type '(footnote-definition plain-list))
  18917. (skip-chars-backward " \t\n")
  18918. (org--backward-paragraph-once))
  18919. ((= contents-end (point))
  18920. (forward-char -1)
  18921. (org--backward-paragraph-once))
  18922. (t
  18923. (goto-char contents-end))))
  18924. ;; Move between empty lines in some blocks.
  18925. ((and (memq type '(comment-block example-block export-block src-block
  18926. verse-block))
  18927. (let ((contents-start
  18928. (org-with-point-at post-affiliated
  18929. (line-beginning-position 2))))
  18930. (when (> (point) contents-start)
  18931. (let ((contents-end
  18932. (org-with-point-at end
  18933. (skip-chars-backward " \t\n")
  18934. (line-beginning-position))))
  18935. (if (> (point) contents-end)
  18936. (progn (goto-char contents-end) t)
  18937. (skip-chars-backward " \t\n" begin)
  18938. (re-search-backward "^[ \t]*\n" contents-start :move)
  18939. t))))))
  18940. ;; Move to element's start.
  18941. (t
  18942. (funcall reach begin))))))))
  18943. (defun org--backward-paragraph-once ()
  18944. "Move backward to start of paragraph or equivalent, once.
  18945. See `org-backward-paragraph'."
  18946. (interactive)
  18947. (if (eq org-fold-core-style 'text-properties)
  18948. (org--backward-paragraph-once--text-properties)
  18949. (org--backward-paragraph-once--overlays)))
  18950. (defun org-forward-element ()
  18951. "Move forward by one element.
  18952. Move to the next element at the same level, when possible."
  18953. (interactive)
  18954. (cond ((eobp) (user-error "Cannot move further down"))
  18955. ((org-with-limited-levels (org-at-heading-p))
  18956. (let ((origin (point)))
  18957. (goto-char (org-end-of-subtree nil t))
  18958. (unless (org-with-limited-levels (org-at-heading-p))
  18959. (goto-char origin)
  18960. (user-error "Cannot move further down"))))
  18961. (t
  18962. (let* ((elem (org-element-at-point))
  18963. (end (org-element-property :end elem))
  18964. (parent (org-element-property :parent elem)))
  18965. (cond ((and parent (= (org-element-property :contents-end parent) end))
  18966. (goto-char (org-element-property :end parent)))
  18967. ((integer-or-marker-p end) (goto-char end))
  18968. (t (message "No element at point")))))))
  18969. (defun org-backward-element ()
  18970. "Move backward by one element.
  18971. Move to the previous element at the same level, when possible."
  18972. (interactive)
  18973. (cond ((bobp) (user-error "Cannot move further up"))
  18974. ((org-with-limited-levels (org-at-heading-p))
  18975. ;; At a headline, move to the previous one, if any, or stay
  18976. ;; here.
  18977. (let ((origin (point)))
  18978. (org-with-limited-levels (org-backward-heading-same-level 1))
  18979. ;; When current headline has no sibling above, move to its
  18980. ;; parent.
  18981. (when (= (point) origin)
  18982. (or (org-with-limited-levels (org-up-heading-safe))
  18983. (progn (goto-char origin)
  18984. (user-error "Cannot move further up"))))))
  18985. (t
  18986. (let* ((elem (org-element-at-point))
  18987. (beg (org-element-property :begin elem)))
  18988. (cond
  18989. ;; Move to beginning of current element if point isn't
  18990. ;; there already.
  18991. ((null beg) (message "No element at point"))
  18992. ((/= (point) beg) (goto-char beg))
  18993. (t (goto-char beg)
  18994. (skip-chars-backward " \r\t\n")
  18995. (unless (bobp)
  18996. (let ((prev (org-element-at-point)))
  18997. (goto-char (org-element-property :begin prev))
  18998. (while (and (setq prev (org-element-property :parent prev))
  18999. (<= (org-element-property :end prev) beg))
  19000. (goto-char (org-element-property :begin prev)))))))))))
  19001. (defun org-up-element ()
  19002. "Move to upper element."
  19003. (interactive)
  19004. (if (org-with-limited-levels (org-at-heading-p))
  19005. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19006. (let* ((elem (org-element-at-point))
  19007. (parent (org-element-property :parent elem)))
  19008. (if (and parent
  19009. (not (memq (org-element-type parent) '(section org-data))))
  19010. (goto-char (org-element-property :begin parent))
  19011. (if (org-with-limited-levels (org-before-first-heading-p))
  19012. (user-error "No surrounding element")
  19013. (org-with-limited-levels (org-back-to-heading)))))))
  19014. (defun org-down-element ()
  19015. "Move to inner element."
  19016. (interactive)
  19017. (let ((element (org-element-at-point)))
  19018. (cond
  19019. ((memq (org-element-type element) '(plain-list table))
  19020. (goto-char (org-element-property :contents-begin element))
  19021. (forward-char))
  19022. ((memq (org-element-type element) org-element-greater-elements)
  19023. ;; If contents are hidden, first disclose them.
  19024. (when (org-invisible-p (line-end-position)) (org-cycle))
  19025. (goto-char (or (org-element-property :contents-begin element)
  19026. (user-error "No content for this element"))))
  19027. (t (user-error "No inner element")))))
  19028. (defun org-drag-element-backward ()
  19029. "Move backward element at point."
  19030. (interactive)
  19031. (let ((elem (or (org-element-at-point)
  19032. (user-error "No element at point"))))
  19033. (if (eq (org-element-type elem) 'headline)
  19034. ;; Preserve point when moving a whole tree, even if point was
  19035. ;; on blank lines below the headline.
  19036. (let ((offset (skip-chars-backward " \t\n")))
  19037. (unwind-protect (org-move-subtree-up)
  19038. (forward-char (- offset))))
  19039. (let ((prev-elem
  19040. (save-excursion
  19041. (goto-char (org-element-property :begin elem))
  19042. (skip-chars-backward " \r\t\n")
  19043. (unless (bobp)
  19044. (let* ((beg (org-element-property :begin elem))
  19045. (prev (org-element-at-point))
  19046. (up prev))
  19047. (while (and (setq up (org-element-property :parent up))
  19048. (<= (org-element-property :end up) beg))
  19049. (setq prev up))
  19050. prev)))))
  19051. ;; Error out if no previous element or previous element is
  19052. ;; a parent of the current one.
  19053. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19054. (user-error "Cannot drag element backward")
  19055. (let ((pos (point)))
  19056. (org-element-swap-A-B prev-elem elem)
  19057. (goto-char (+ (org-element-property :begin prev-elem)
  19058. (- pos (org-element-property :begin elem))))))))))
  19059. (defun org-drag-element-forward ()
  19060. "Move forward element at point."
  19061. (interactive)
  19062. (let* ((pos (point))
  19063. (elem (or (org-element-at-point)
  19064. (user-error "No element at point"))))
  19065. (when (= (point-max) (org-element-property :end elem))
  19066. (user-error "Cannot drag element forward"))
  19067. (goto-char (org-element-property :end elem))
  19068. (let ((next-elem (org-element-at-point)))
  19069. (when (or (org-element-nested-p elem next-elem)
  19070. (and (eq (org-element-type next-elem) 'headline)
  19071. (not (eq (org-element-type elem) 'headline))))
  19072. (goto-char pos)
  19073. (user-error "Cannot drag element forward"))
  19074. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19075. ;; body's length (without final blanks) and by the length of
  19076. ;; blanks between ELEM and NEXT-ELEM.
  19077. (let ((size-next (- (save-excursion
  19078. (goto-char (org-element-property :end next-elem))
  19079. (skip-chars-backward " \r\t\n")
  19080. (forward-line)
  19081. ;; Small correction if buffer doesn't end
  19082. ;; with a newline character.
  19083. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19084. (org-element-property :begin next-elem)))
  19085. (size-blank (- (org-element-property :end elem)
  19086. (save-excursion
  19087. (goto-char (org-element-property :end elem))
  19088. (skip-chars-backward " \r\t\n")
  19089. (forward-line)
  19090. (point)))))
  19091. (org-element-swap-A-B elem next-elem)
  19092. (goto-char (+ pos size-next size-blank))))))
  19093. (defun org-drag-line-forward (arg)
  19094. "Drag the line at point ARG lines forward."
  19095. (interactive "p")
  19096. (dotimes (_ (abs arg))
  19097. (let ((c (current-column)))
  19098. (if (< 0 arg)
  19099. (progn
  19100. (beginning-of-line 2)
  19101. (transpose-lines 1)
  19102. (beginning-of-line 0))
  19103. (transpose-lines 1)
  19104. (beginning-of-line -1))
  19105. (org-move-to-column c))))
  19106. (defun org-drag-line-backward (arg)
  19107. "Drag the line at point ARG lines backward."
  19108. (interactive "p")
  19109. (org-drag-line-forward (- arg)))
  19110. (defun org-mark-element ()
  19111. "Put point at beginning of this element, mark at end.
  19112. Interactively, if this command is repeated or (in Transient Mark
  19113. mode) if the mark is active, it marks the next element after the
  19114. ones already marked."
  19115. (interactive)
  19116. (let (deactivate-mark)
  19117. (if (and (called-interactively-p 'any)
  19118. (or (and (eq last-command this-command) (mark t))
  19119. (and transient-mark-mode mark-active)))
  19120. (set-mark
  19121. (save-excursion
  19122. (goto-char (mark))
  19123. (goto-char (org-element-property :end (org-element-at-point)))
  19124. (point)))
  19125. (let ((element (org-element-at-point)))
  19126. (end-of-line)
  19127. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19128. (goto-char (org-element-property :begin element))))))
  19129. (defun org-narrow-to-element ()
  19130. "Narrow buffer to current element."
  19131. (interactive)
  19132. (let ((elem (org-element-at-point)))
  19133. (cond
  19134. ((eq (car elem) 'headline)
  19135. (narrow-to-region
  19136. (org-element-property :begin elem)
  19137. (org-element-property :end elem)))
  19138. ((memq (car elem) org-element-greater-elements)
  19139. (narrow-to-region
  19140. (org-element-property :contents-begin elem)
  19141. (org-element-property :contents-end elem)))
  19142. (t
  19143. (narrow-to-region
  19144. (org-element-property :begin elem)
  19145. (org-element-property :end elem))))))
  19146. (defun org-transpose-element ()
  19147. "Transpose current and previous elements, keeping blank lines between.
  19148. Point is moved after both elements."
  19149. (interactive)
  19150. (org-skip-whitespace)
  19151. (let ((end (org-element-property :end (org-element-at-point))))
  19152. (org-drag-element-backward)
  19153. (goto-char end)))
  19154. (defun org-unindent-buffer ()
  19155. "Un-indent the visible part of the buffer.
  19156. Relative indentation (between items, inside blocks, etc.) isn't
  19157. modified."
  19158. (interactive)
  19159. (unless (eq major-mode 'org-mode)
  19160. (user-error "Cannot un-indent a buffer not in Org mode"))
  19161. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19162. (unindent-tree
  19163. (lambda (contents)
  19164. (dolist (element (reverse contents))
  19165. (if (memq (org-element-type element) '(headline section))
  19166. (funcall unindent-tree (org-element-contents element))
  19167. (save-excursion
  19168. (save-restriction
  19169. (narrow-to-region
  19170. (org-element-property :begin element)
  19171. (org-element-property :end element))
  19172. (org-do-remove-indentation))))))))
  19173. (funcall unindent-tree (org-element-contents parse-tree))))
  19174. (defun org-make-options-regexp (kwds &optional extra)
  19175. "Make a regular expression for keyword lines.
  19176. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19177. when non-nil, is a regexp matching keywords names."
  19178. (concat "^[ \t]*#\\+\\("
  19179. (regexp-opt kwds)
  19180. (and extra (concat (and kwds "\\|") extra))
  19181. "\\):[ \t]*\\(.*\\)"))
  19182. ;;; Conveniently switch to Info nodes
  19183. (defun org-info-find-node (&optional nodename)
  19184. "Find Info documentation NODENAME or Org documentation according context.
  19185. Started from `gnus-info-find-node'."
  19186. (interactive)
  19187. (Info-goto-node
  19188. (or nodename
  19189. (let ((default-org-info-node "(org) Top"))
  19190. (cond
  19191. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19192. ((eq 'org-mode major-mode)
  19193. (let* ((context (org-element-at-point))
  19194. (element-info-nodes ; compare to `org-element-all-elements'.
  19195. `((babel-call . "(org) Evaluating Code Blocks")
  19196. (center-block . "(org) Paragraphs")
  19197. (clock . ,default-org-info-node)
  19198. (comment . "(org) Comment Lines")
  19199. (comment-block . "(org) Comment Lines")
  19200. (diary-sexp . ,default-org-info-node)
  19201. (drawer . "(org) Drawers")
  19202. (dynamic-block . "(org) Dynamic Blocks")
  19203. (example-block . "(org) Literal Examples")
  19204. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19205. (fixed-width . ,default-org-info-node)
  19206. (footnote-definition . "(org) Creating Footnotes")
  19207. (headline . "(org) Document Structure")
  19208. (horizontal-rule . "(org) Built-in Table Editor")
  19209. (inlinetask . ,default-org-info-node)
  19210. (item . "(org) Plain Lists")
  19211. (keyword . "(org) Per-file keywords")
  19212. (latex-environment . "(org) LaTeX Export")
  19213. (node-property . "(org) Properties and Columns")
  19214. (paragraph . "(org) Paragraphs")
  19215. (plain-list . "(org) Plain Lists")
  19216. (planning . "(org) Deadlines and Scheduling")
  19217. (property-drawer . "(org) Properties and Columns")
  19218. (quote-block . "(org) Paragraphs")
  19219. (section . ,default-org-info-node)
  19220. (special-block . ,default-org-info-node)
  19221. (src-block . "(org) Working with Source Code")
  19222. (table . "(org) Tables")
  19223. (table-row . "(org) Tables")
  19224. (verse-block . "(org) Paragraphs"))))
  19225. (or (cdr (assoc (car context) element-info-nodes))
  19226. default-org-info-node)))
  19227. (t default-org-info-node))))))
  19228. ;;; Finish up
  19229. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19230. (lambda () (add-hook 'change-major-mode-hook
  19231. 'org-fold-show-all 'append 'local)))
  19232. (provide 'org)
  19233. (run-hooks 'org-load-hook)
  19234. ;;; org.el ends here