org.el 804 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979
  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. (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
  97. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  98. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  99. (defvar org-outline-regexp "\\*+ "
  100. "Regexp to match Org headlines.")
  101. (defvar org-outline-regexp-bol "^\\*+ "
  102. "Regexp to match Org headlines.
  103. This is similar to `org-outline-regexp' but additionally makes
  104. sure that we are at the beginning of the line.")
  105. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  106. "Matches a headline, putting stars and text into groups.
  107. Stars are put in group 1 and the trimmed body in group 2.")
  108. (declare-function calendar-check-holidays "holidays" (date))
  109. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  110. (declare-function cdlatex-math-symbol "ext:cdlatex")
  111. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  112. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  113. (declare-function org-add-archive-files "org-archive" (files))
  114. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  115. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  116. (declare-function org-agenda-redo "org-agenda" (&optional all))
  117. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  118. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  119. (declare-function org-archive-subtree-default "org-archive" ())
  120. (declare-function org-archive-to-archive-sibling "org-archive" ())
  121. (declare-function org-attach "org-attach" ())
  122. (declare-function org-attach-dir "org-attach"
  123. (&optional create-if-not-exists-p no-fs-check))
  124. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  125. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  126. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  127. (declare-function org-clock-auto-clockout "org-clock" ())
  128. (declare-function org-clock-cancel "org-clock" ())
  129. (declare-function org-clock-display "org-clock" (&optional arg))
  130. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  131. (declare-function org-clock-goto "org-clock" (&optional select))
  132. (declare-function org-clock-in "org-clock" (&optional select start-time))
  133. (declare-function org-clock-in-last "org-clock" (&optional arg))
  134. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  135. (declare-function org-clock-out-if-current "org-clock" ())
  136. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  137. (declare-function org-clock-report "org-clock" (&optional arg))
  138. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  139. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  140. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  141. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  142. (declare-function org-clock-update-time-maybe "org-clock" ())
  143. (declare-function org-clocktable-shift "org-clock" (dir n))
  144. (declare-function org-columns-quit "org-colview" ())
  145. (declare-function org-columns-insert-dblock "org-colview" ())
  146. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  147. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  148. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  149. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  150. (declare-function org-element-cache-refresh "org-element" (pos))
  151. (declare-function org-element-cache-reset "org-element" (&optional all))
  152. (declare-function org-element-cache-map "org-element" (func &rest keys))
  153. (declare-function org-element-contents "org-element" (element))
  154. (declare-function org-element-context "org-element" (&optional element))
  155. (declare-function org-element-copy "org-element" (datum))
  156. (declare-function org-element-create "org-element" (type &optional props &rest children))
  157. (declare-function org-element-extract-element "org-element" (element))
  158. (declare-function org-element-insert-before "org-element" (element location))
  159. (declare-function org-element-interpret-data "org-element" (data))
  160. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  161. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  162. (declare-function org-element-link-parser "org-element" ())
  163. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  164. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  165. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  166. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  167. (declare-function org-element-property "org-element" (property element))
  168. (declare-function org-element-put-property "org-element" (element property value))
  169. (declare-function org-element-restriction "org-element" (element))
  170. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  171. (declare-function org-element-timestamp-parser "org-element" ())
  172. (declare-function org-element-type "org-element" (element))
  173. (declare-function org-element--cache-active-p "org-element" ())
  174. (declare-function org-export-dispatch "ox" (&optional arg))
  175. (declare-function org-export-get-backend "ox" (name))
  176. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  177. (declare-function org-feed-goto-inbox "org-feed" (feed))
  178. (declare-function org-feed-update-all "org-feed" ())
  179. (declare-function org-goto "org-goto" (&optional alternative-interface))
  180. (declare-function org-id-find-id-file "org-id" (id))
  181. (declare-function org-id-get-create "org-id" (&optional force))
  182. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  183. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  184. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  185. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  186. (declare-function org-num-mode "org-num" (&optional arg))
  187. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  188. (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
  189. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  190. (declare-function org-timer "org-timer" (&optional restart no-insert))
  191. (declare-function org-timer-item "org-timer" (&optional arg))
  192. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  193. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  194. (declare-function org-timer-start "org-timer" (&optional offset))
  195. (declare-function org-timer-stop "org-timer" ())
  196. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  197. (declare-function org-update-radio-target-regexp "ol" ())
  198. (defvar org-agenda-buffer-name)
  199. (defvar org-element-paragraph-separate)
  200. (defvar org-element-cache-map-continue-from)
  201. (defvar org-element--timestamp-regexp)
  202. (defvar org-indent-indentation-per-level)
  203. (defvar org-radio-target-regexp)
  204. (defvar org-target-link-regexp)
  205. (defvar org-target-regexp)
  206. (defvar org-id-overriding-file-name)
  207. ;; load languages based on value of `org-babel-load-languages'
  208. (defvar org-babel-load-languages)
  209. (defvar crm-separator) ; dynamically scoped param
  210. ;;;###autoload
  211. (defun org-babel-do-load-languages (sym value)
  212. "Load the languages defined in `org-babel-load-languages'."
  213. (set-default sym value)
  214. (dolist (pair org-babel-load-languages)
  215. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  216. (if active
  217. (require (intern (concat "ob-" lang)))
  218. (fmakunbound
  219. (intern (concat "org-babel-execute:" lang)))
  220. (fmakunbound
  221. (intern (concat "org-babel-expand-body:" lang)))))))
  222. ;;;###autoload
  223. (defun org-babel-load-file (file &optional compile)
  224. "Load Emacs Lisp source code blocks in the Org FILE.
  225. This function exports the source code using `org-babel-tangle'
  226. and then loads the resulting file using `load-file'. With
  227. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  228. byte-compiled before it is loaded."
  229. (interactive "fFile to load: \nP")
  230. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  231. ;; Tangle only if the Org file is newer than the Elisp file.
  232. (unless (org-file-newer-than-p
  233. tangled-file
  234. (file-attribute-modification-time
  235. (file-attributes (file-truename file))))
  236. (org-babel-tangle-file file
  237. tangled-file
  238. (rx string-start
  239. (or "emacs-lisp" "elisp")
  240. string-end)))
  241. (if compile
  242. (progn
  243. (byte-compile-file tangled-file)
  244. (load-file (byte-compile-dest-file tangled-file))
  245. (message "Compiled and loaded %s" tangled-file))
  246. (load-file tangled-file)
  247. (message "Loaded %s" tangled-file))))
  248. (defcustom org-babel-load-languages '((emacs-lisp . t))
  249. "Languages which can be evaluated in Org buffers.
  250. \\<org-mode-map>
  251. This list can be used to load support for any of the languages
  252. below. Each language will depend on a different set of system
  253. executables and/or Emacs modes.
  254. When a language is \"loaded\", code blocks in that language can
  255. be evaluated with `org-babel-execute-src-block', which is bound
  256. by default to \\[org-ctrl-c-ctrl-c].
  257. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  258. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  259. default, only Emacs Lisp is loaded, since it has no specific
  260. requirement."
  261. :group 'org-babel
  262. :set 'org-babel-do-load-languages
  263. :version "24.1"
  264. :type '(alist :tag "Babel Languages"
  265. :key-type
  266. (choice
  267. (const :tag "Awk" awk)
  268. (const :tag "C" C)
  269. (const :tag "R" R)
  270. (const :tag "Calc" calc)
  271. (const :tag "Clojure" clojure)
  272. (const :tag "CSS" css)
  273. (const :tag "Ditaa" ditaa)
  274. (const :tag "Dot" dot)
  275. (const :tag "Emacs Lisp" emacs-lisp)
  276. (const :tag "Forth" forth)
  277. (const :tag "Fortran" fortran)
  278. (const :tag "Gnuplot" gnuplot)
  279. (const :tag "Haskell" haskell)
  280. (const :tag "Java" java)
  281. (const :tag "Javascript" js)
  282. (const :tag "LaTeX" latex)
  283. (const :tag "Lilypond" lilypond)
  284. (const :tag "Lisp" lisp)
  285. (const :tag "Makefile" makefile)
  286. (const :tag "Maxima" maxima)
  287. (const :tag "Matlab" matlab)
  288. (const :tag "Ocaml" ocaml)
  289. (const :tag "Octave" octave)
  290. (const :tag "Org" org)
  291. (const :tag "Perl" perl)
  292. (const :tag "Pico Lisp" picolisp)
  293. (const :tag "PlantUML" plantuml)
  294. (const :tag "Python" python)
  295. (const :tag "Ruby" ruby)
  296. (const :tag "Sass" sass)
  297. (const :tag "Scala" scala)
  298. (const :tag "Scheme" scheme)
  299. (const :tag "Screen" screen)
  300. (const :tag "Shell Script" shell)
  301. (const :tag "Sql" sql)
  302. (const :tag "Sqlite" sqlite)
  303. (const :tag "Stan" stan))
  304. :value-type (boolean :tag "Activate" :value t)))
  305. ;;;; Customization variables
  306. (defcustom org-clone-delete-id nil
  307. "Remove ID property of clones of a subtree.
  308. When non-nil, clones of a subtree don't inherit the ID property.
  309. Otherwise they inherit the ID property with a new unique
  310. identifier."
  311. :type 'boolean
  312. :version "24.1"
  313. :group 'org-id)
  314. ;;; Version
  315. (org-check-version)
  316. ;;;###autoload
  317. (defun org-version (&optional here full message)
  318. "Show the Org version.
  319. Interactively, or when MESSAGE is non-nil, show it in echo area.
  320. With prefix argument, or when HERE is non-nil, insert it at point.
  321. In non-interactive uses, a reduced version string is output unless
  322. FULL is given."
  323. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  324. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  325. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  326. (load-suffixes (list ".el"))
  327. (org-install-dir
  328. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  329. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  330. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  331. (let* ((load-suffixes save-load-suffixes)
  332. (release (org-release))
  333. (git-version (org-git-version))
  334. (version (format "Org mode version %s (%s @ %s)"
  335. release
  336. git-version
  337. (if org-install-dir
  338. (if (string= org-dir org-install-dir)
  339. org-install-dir
  340. (concat "mixed installation! "
  341. org-install-dir
  342. " and "
  343. org-dir))
  344. "org-loaddefs.el can not be found!")))
  345. (version1 (if full version release)))
  346. (when here (insert version1))
  347. (when message (message "%s" version1))
  348. version1)))
  349. (defconst org-version (org-version))
  350. ;;; Syntax Constants
  351. ;;;; Comments
  352. (defconst org-comment-regexp
  353. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  354. "Regular expression for comment lines.")
  355. ;;;; Keyword
  356. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  357. "Regular expression for keyword-lines.")
  358. ;;;; Block
  359. (defconst org-block-regexp
  360. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  361. "Regular expression for hiding blocks.")
  362. (defconst org-dblock-start-re
  363. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  364. "Matches the start line of a dynamic block, with parameters.")
  365. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  366. "Matches the end of a dynamic block.")
  367. ;;;; Timestamp
  368. (defconst org-ts--internal-regexp
  369. (rx (seq
  370. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  371. (optional " " (*? nonl))))
  372. "Regular expression matching the innards of a time stamp.")
  373. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  374. "Regular expression for fast time stamp matching.")
  375. (defconst org-ts-regexp-inactive
  376. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  377. "Regular expression for fast inactive time stamp matching.")
  378. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  379. "Regular expression for fast time stamp matching.")
  380. (defconst org-ts-regexp0
  381. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  382. "Regular expression matching time strings for analysis.
  383. This one does not require the space after the date, so it can be used
  384. on a string that terminates immediately after the date.")
  385. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  386. "Regular expression matching time strings for analysis.")
  387. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  388. "Regular expression matching time stamps, with groups.")
  389. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  390. "Regular expression matching time stamps (also [..]), with groups.")
  391. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  392. "Regular expression matching a time stamp range.")
  393. (defconst org-tr-regexp-both
  394. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  395. "Regular expression matching a time stamp range.")
  396. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  397. org-ts-regexp "\\)?")
  398. "Regular expression matching a time stamp or time stamp range.")
  399. (defconst org-tsr-regexp-both
  400. (concat org-ts-regexp-both "\\(--?-?"
  401. org-ts-regexp-both "\\)?")
  402. "Regular expression matching a time stamp or time stamp range.
  403. The time stamps may be either active or inactive.")
  404. (defconst org-repeat-re
  405. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  406. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  407. "Regular expression for specifying repeated events.
  408. After a match, group 1 contains the repeat expression.")
  409. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  410. "Formats for `format-time-string' which are used for time stamps.")
  411. ;;;; Clock and Planning
  412. (defconst org-clock-string "CLOCK:"
  413. "String used as prefix for timestamps clocking work hours on an item.")
  414. (defvar org-closed-string "CLOSED:"
  415. "String used as the prefix for timestamps logging closing a TODO entry.")
  416. (defvar org-deadline-string "DEADLINE:"
  417. "String to mark deadline entries.
  418. \\<org-mode-map>
  419. A deadline is this string, followed by a time stamp. It must be
  420. a word, terminated by a colon. You can insert a schedule keyword
  421. and a timestamp with `\\[org-deadline]'.")
  422. (defvar org-scheduled-string "SCHEDULED:"
  423. "String to mark scheduled TODO entries.
  424. \\<org-mode-map>
  425. A schedule is this string, followed by a time stamp. It must be
  426. a word, terminated by a colon. You can insert a schedule keyword
  427. and a timestamp with `\\[org-schedule]'.")
  428. (defconst org-ds-keyword-length
  429. (+ 2
  430. (apply #'max
  431. (mapcar #'length
  432. (list org-deadline-string org-scheduled-string
  433. org-clock-string org-closed-string))))
  434. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  435. (defconst org-planning-line-re
  436. (concat "^[ \t]*"
  437. (regexp-opt
  438. (list org-closed-string org-deadline-string org-scheduled-string)
  439. t))
  440. "Matches a line with planning info.
  441. Matched keyword is in group 1.")
  442. (defconst org-clock-line-re
  443. (concat "^[ \t]*" org-clock-string)
  444. "Matches a line with clock info.")
  445. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  446. "Matches the DEADLINE keyword.")
  447. (defconst org-deadline-time-regexp
  448. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  449. "Matches the DEADLINE keyword together with a time stamp.")
  450. (defconst org-deadline-time-hour-regexp
  451. (concat "\\<" org-deadline-string
  452. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  453. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  454. (defconst org-deadline-line-regexp
  455. (concat "\\<\\(" org-deadline-string "\\).*")
  456. "Matches the DEADLINE keyword and the rest of the line.")
  457. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  458. "Matches the SCHEDULED keyword.")
  459. (defconst org-scheduled-time-regexp
  460. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  461. "Matches the SCHEDULED keyword together with a time stamp.")
  462. (defconst org-scheduled-time-hour-regexp
  463. (concat "\\<" org-scheduled-string
  464. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  465. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  466. (defconst org-closed-time-regexp
  467. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  468. "Matches the CLOSED keyword together with a time stamp.")
  469. (defconst org-keyword-time-regexp
  470. (concat "\\<"
  471. (regexp-opt
  472. (list org-scheduled-string org-deadline-string org-closed-string
  473. org-clock-string)
  474. t)
  475. " *[[<]\\([^]>]+\\)[]>]")
  476. "Matches any of the 4 keywords, together with the time stamp.")
  477. (defconst org-keyword-time-not-clock-regexp
  478. (concat
  479. "\\<"
  480. (regexp-opt
  481. (list org-scheduled-string org-deadline-string org-closed-string) t)
  482. " *[[<]\\([^]>]+\\)[]>]")
  483. "Matches any of the 3 keywords, together with the time stamp.")
  484. (defconst org-all-time-keywords
  485. (mapcar (lambda (w) (substring w 0 -1))
  486. (list org-scheduled-string org-deadline-string
  487. org-clock-string org-closed-string))
  488. "List of time keywords.")
  489. ;;;; Drawer
  490. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  491. "Matches first or last line of a hidden block.
  492. Group 1 contains drawer's name or \"END\".")
  493. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  494. "Regular expression matching the first line of a property drawer.")
  495. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  496. "Regular expression matching the last line of a property drawer.")
  497. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  498. "Regular expression matching the first line of a clock drawer.")
  499. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  500. "Regular expression matching the last line of a clock drawer.")
  501. (defconst org-logbook-drawer-re
  502. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  503. (*? (0+ nonl) "\n")
  504. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  505. "Matches an entire LOGBOOK drawer.")
  506. (defconst org-property-drawer-re
  507. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  508. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  509. "[ \t]*:END:[ \t]*$")
  510. "Matches an entire property drawer.")
  511. (defconst org-clock-drawer-re
  512. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  513. org-clock-drawer-end-re "\\)\n?")
  514. "Matches an entire clock drawer.")
  515. ;;;; Headline
  516. (defconst org-heading-keyword-regexp-format
  517. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  518. "Printf format for a regexp matching a headline with some keyword.
  519. This regexp will match the headline of any node which has the
  520. exact keyword that is put into the format. The keyword isn't in
  521. any group by default, but the stars and the body are.")
  522. (defconst org-heading-keyword-maybe-regexp-format
  523. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  524. "Printf format for a regexp matching a headline, possibly with some keyword.
  525. This regexp can match any headline with the specified keyword, or
  526. without a keyword. The keyword isn't in any group by default,
  527. but the stars and the body are.")
  528. (defconst org-archive-tag "ARCHIVE"
  529. "The tag that marks a subtree as archived.
  530. An archived subtree does not open during visibility cycling, and does
  531. not contribute to the agenda listings.")
  532. (defconst org-tag-re "[[:alnum:]_@#%]+"
  533. "Regexp matching a single tag.")
  534. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  535. "Regexp matching the tag group at the end of a line, with leading spaces.
  536. Tags are stored in match group 1. Match group 2 stores the tags
  537. without the enclosing colons.")
  538. (defconst org-tag-line-re
  539. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  540. "Regexp matching tags in a headline.
  541. Tags are stored in match group 1. Match group 2 stores the tags
  542. without the enclosing colons.")
  543. (eval-and-compile
  544. (defconst org-comment-string "COMMENT"
  545. "Entries starting with this keyword will never be exported.
  546. \\<org-mode-map>
  547. An entry can be toggled between COMMENT and normal with
  548. `\\[org-toggle-comment]'."))
  549. ;;;; LaTeX Environments and Fragments
  550. (defconst org-latex-regexps
  551. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  552. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  553. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  554. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  555. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  556. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  557. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  558. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  559. "Regular expressions for matching embedded LaTeX.")
  560. ;;;; Node Property
  561. (defconst org-effort-property "Effort"
  562. "The property that is being used to keep track of effort estimates.
  563. Effort estimates given in this property need to be in the format
  564. defined in org-duration.el.")
  565. ;;; The custom variables
  566. (defgroup org nil
  567. "Outline-based notes management and organizer."
  568. :tag "Org"
  569. :group 'outlines
  570. :group 'calendar)
  571. (defcustom org-mode-hook nil
  572. "Mode hook for Org mode, run after the mode was turned on."
  573. :group 'org
  574. :type 'hook)
  575. (defcustom org-load-hook nil
  576. "Hook that is run after org.el has been loaded."
  577. :group 'org
  578. :type 'hook)
  579. (make-obsolete-variable
  580. 'org-load-hook
  581. "use `with-eval-after-load' instead." "9.5")
  582. (defcustom org-log-buffer-setup-hook nil
  583. "Hook that is run after an Org log buffer is created."
  584. :group 'org
  585. :version "24.1"
  586. :type 'hook)
  587. (defvar org-modules) ; defined below
  588. (defvar org-modules-loaded nil
  589. "Have the modules been loaded already?")
  590. ;;;###autoload
  591. (defun org-load-modules-maybe (&optional force)
  592. "Load all extensions listed in `org-modules'."
  593. (when (or force (not org-modules-loaded))
  594. (dolist (ext org-modules)
  595. (condition-case nil (require ext)
  596. (error (message "Problems while trying to load feature `%s'" ext))))
  597. (setq org-modules-loaded t)))
  598. (defun org-set-modules (var value)
  599. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  600. (set var value)
  601. (when (featurep 'org)
  602. (org-load-modules-maybe 'force)
  603. (org-element-cache-reset 'all)))
  604. (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)
  605. "Modules that should always be loaded together with org.el.
  606. If a description starts with <C>, the file is not part of Emacs and Org mode,
  607. so loading it will require that you have properly installed org-contrib
  608. package from NonGNU Emacs Lisp Package Archive
  609. https://elpa.nongnu.org/nongnu/org-contrib.html
  610. You can also use this system to load external packages (i.e. neither Org
  611. core modules, nor org-contrib modules). Just add symbols
  612. to the end of the list. If the package is called org-xyz.el, then you need
  613. to add the symbol `xyz', and the package must have a call to:
  614. (provide \\='org-xyz)
  615. For export specific modules, see also `org-export-backends'."
  616. :group 'org
  617. :set 'org-set-modules
  618. :package-version '(Org . "9.5")
  619. :type
  620. '(set :greedy t
  621. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  622. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  623. (const :tag " crypt: Encryption of subtrees" org-crypt)
  624. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  625. (const :tag " docview: Links to Docview buffers" ol-docview)
  626. (const :tag " doi: Links to DOI references" ol-doi)
  627. (const :tag " eww: Store link to URL of Eww" ol-eww)
  628. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  629. (const :tag " habit: Track your consistency with habits" org-habit)
  630. (const :tag " id: Global IDs for identifying entries" org-id)
  631. (const :tag " info: Links to Info nodes" ol-info)
  632. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  633. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  634. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  635. (const :tag " mouse: Additional mouse support" org-mouse)
  636. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  637. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  638. (const :tag " tempo: Fast completion for structures" org-tempo)
  639. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  640. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  641. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  642. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  643. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  644. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  645. (const :tag "C collector: Collect properties into tables" org-collector)
  646. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  647. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  648. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  649. (const :tag "C eval: Include command output as text" org-eval)
  650. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  651. (const :tag "C git-link: Links to specific file version" ol-git-link)
  652. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  653. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  654. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  655. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  656. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  657. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  658. (const :tag "C man: Links to man pages in Org mode" ol-man)
  659. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  660. (const :tag "C notify: Notifications for Org mode" org-notify)
  661. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  662. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  663. (const :tag "C registry: A registry for Org links" org-registry)
  664. (const :tag "C screen: Visit screen sessions through links" org-screen)
  665. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  666. (const :tag "C secretary: Team management with Org" org-secretary)
  667. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  668. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  669. (const :tag "C track: Keep up with Org mode development" org-track)
  670. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  671. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  672. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  673. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  674. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  675. (defvar org-export-registered-backends) ; From ox.el.
  676. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  677. (declare-function org-export-backend-name "ox" (backend) t)
  678. (defcustom org-export-backends '(ascii html icalendar latex odt)
  679. "List of export back-ends that should be always available.
  680. If a description starts with <C>, the file is not part of Emacs and Org mode,
  681. so loading it will require that you have properly installed org-contrib
  682. package from NonGNU Emacs Lisp Package Archive
  683. https://elpa.nongnu.org/nongnu/org-contrib.html
  684. Unlike to `org-modules', libraries in this list will not be
  685. loaded along with Org, but only once the export framework is
  686. needed.
  687. This variable needs to be set before org.el is loaded. If you
  688. need to make a change while Emacs is running, use the customize
  689. interface or run the following code, where VAL stands for the new
  690. value of the variable, after updating it:
  691. (progn
  692. (setq org-export-registered-backends
  693. (cl-remove-if-not
  694. (lambda (backend)
  695. (let ((name (org-export-backend-name backend)))
  696. (or (memq name val)
  697. (catch \\='parentp
  698. (dolist (b val)
  699. (and (org-export-derived-backend-p b name)
  700. (throw \\='parentp t)))))))
  701. org-export-registered-backends))
  702. (let ((new-list (mapcar #\\='org-export-backend-name
  703. org-export-registered-backends)))
  704. (dolist (backend val)
  705. (cond
  706. ((not (load (format \"ox-%s\" backend) t t))
  707. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  708. backend))
  709. ((not (memq backend new-list)) (push backend new-list))))
  710. (set-default \\='org-export-backends new-list)))
  711. Adding a back-end to this list will also pull the back-end it
  712. depends on, if any."
  713. :group 'org
  714. :group 'org-export
  715. :version "26.1"
  716. :package-version '(Org . "9.0")
  717. :initialize 'custom-initialize-set
  718. :set (lambda (var val)
  719. (if (not (featurep 'ox)) (set-default var val)
  720. ;; Any back-end not required anymore (not present in VAL and not
  721. ;; a parent of any back-end in the new value) is removed from the
  722. ;; list of registered back-ends.
  723. (setq org-export-registered-backends
  724. (cl-remove-if-not
  725. (lambda (backend)
  726. (let ((name (org-export-backend-name backend)))
  727. (or (memq name val)
  728. (catch 'parentp
  729. (dolist (b val)
  730. (and (org-export-derived-backend-p b name)
  731. (throw 'parentp t)))))))
  732. org-export-registered-backends))
  733. ;; Now build NEW-LIST of both new back-ends and required
  734. ;; parents.
  735. (let ((new-list (mapcar #'org-export-backend-name
  736. org-export-registered-backends)))
  737. (dolist (backend val)
  738. (cond
  739. ((not (load (format "ox-%s" backend) t t))
  740. (message "Problems while trying to load export back-end `%s'"
  741. backend))
  742. ((not (memq backend new-list)) (push backend new-list))))
  743. ;; Set VAR to that list with fixed dependencies.
  744. (set-default var new-list))))
  745. :type '(set :greedy t
  746. (const :tag " ascii Export buffer to ASCII format" ascii)
  747. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  748. (const :tag " html Export buffer to HTML format" html)
  749. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  750. (const :tag " latex Export buffer to LaTeX format" latex)
  751. (const :tag " man Export buffer to MAN format" man)
  752. (const :tag " md Export buffer to Markdown format" md)
  753. (const :tag " odt Export buffer to ODT format" odt)
  754. (const :tag " org Export buffer to Org format" org)
  755. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  756. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  757. (const :tag "C deck Export buffer to deck.js presentations" deck)
  758. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  759. (const :tag "C groff Export buffer to Groff format" groff)
  760. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  761. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  762. (const :tag "C s5 Export buffer to s5 presentations" s5)
  763. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  764. (eval-after-load 'ox
  765. '(dolist (backend org-export-backends)
  766. (condition-case nil (require (intern (format "ox-%s" backend)))
  767. (error (message "Problems while trying to load export back-end `%s'"
  768. backend)))))
  769. (defcustom org-support-shift-select nil
  770. "Non-nil means make shift-cursor commands select text when possible.
  771. \\<org-mode-map>
  772. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  773. start selecting a region, or enlarge regions started in this way.
  774. In Org mode, in special contexts, these same keys are used for
  775. other purposes, important enough to compete with shift selection.
  776. Org tries to balance these needs by supporting `shift-select-mode'
  777. outside these special contexts, under control of this variable.
  778. The default of this variable is nil, to avoid confusing behavior. Shifted
  779. cursor keys will then execute Org commands in the following contexts:
  780. - on a headline, changing TODO state (left/right) and priority (up/down)
  781. - on a time stamp, changing the time
  782. - in a plain list item, changing the bullet type
  783. - in a property definition line, switching between allowed values
  784. - in the BEGIN line of a clock table (changing the time block).
  785. - in a table, moving the cell in the specified direction.
  786. Outside these contexts, the commands will throw an error.
  787. When this variable is t and the cursor is not in a special
  788. context, Org mode will support shift-selection for making and
  789. enlarging regions. To make this more effective, the bullet
  790. cycling will no longer happen anywhere in an item line, but only
  791. if the cursor is exactly on the bullet.
  792. If you set this variable to the symbol `always', then the keys
  793. will not be special in headlines, property lines, item lines, and
  794. table cells, to make shift selection work there as well. If this is
  795. what you want, you can use the following alternative commands:
  796. `\\[org-todo]' and `\\[org-priority]' \
  797. to change TODO state and priority,
  798. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  799. can be used to switch TODO sets,
  800. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  801. and properties can be edited by hand or in column view.
  802. However, when the cursor is on a timestamp, shift-cursor commands
  803. will still edit the time stamp - this is just too good to give up."
  804. :group 'org
  805. :type '(choice
  806. (const :tag "Never" nil)
  807. (const :tag "When outside special context" t)
  808. (const :tag "Everywhere except timestamps" always)))
  809. (defcustom org-loop-over-headlines-in-active-region t
  810. "Shall some commands act upon headlines in the active region?
  811. When set to t, some commands will be performed in all headlines
  812. within the active region.
  813. When set to `start-level', some commands will be performed in all
  814. headlines within the active region, provided that these headlines
  815. are of the same level than the first one.
  816. When set to a string, those commands will be performed on the
  817. matching headlines within the active region. Such string must be
  818. a tags/property/todo match as it is used in the agenda tags view.
  819. The list of commands is: `org-schedule', `org-deadline',
  820. `org-todo', `org-set-tags-command', `org-archive-subtree',
  821. `org-archive-set-tag', `org-toggle-archive-tag' and
  822. `org-archive-to-archive-sibling'. The archiving commands skip
  823. already archived entries.
  824. See `org-agenda-loop-over-headlines-in-active-region' for the
  825. equivalent option for agenda views."
  826. :type '(choice (const :tag "Don't loop" nil)
  827. (const :tag "All headlines in active region" t)
  828. (const :tag "In active region, headlines at the same level than the first one" start-level)
  829. (string :tag "Tags/Property/Todo matcher"))
  830. :package-version '(Org . "9.4")
  831. :group 'org-todo
  832. :group 'org-archive)
  833. (defcustom org-startup-folded 'showeverything
  834. "Non-nil means entering Org mode will switch to OVERVIEW.
  835. This can also be configured on a per-file basis by adding one of
  836. the following lines anywhere in the buffer:
  837. #+STARTUP: fold (or `overview', this is equivalent)
  838. #+STARTUP: nofold (or `showall', this is equivalent)
  839. #+STARTUP: content
  840. #+STARTUP: show<n>levels (<n> = 2..5)
  841. #+STARTUP: showeverything
  842. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  843. to ignore this option when Org opens agenda files for the first
  844. time."
  845. :group 'org-startup
  846. :package-version '(Org . "9.4")
  847. :type '(choice
  848. (const :tag "nofold: show all" nil)
  849. (const :tag "fold: overview" t)
  850. (const :tag "fold: show two levels" show2levels)
  851. (const :tag "fold: show three levels" show3levels)
  852. (const :tag "fold: show four levels" show4evels)
  853. (const :tag "fold: show five levels" show5levels)
  854. (const :tag "content: all headlines" content)
  855. (const :tag "show everything, even drawers" showeverything)))
  856. (defcustom org-startup-truncated t
  857. "Non-nil means entering Org mode will set `truncate-lines'.
  858. This is useful since some lines containing links can be very long and
  859. uninteresting. Also tables look terrible when wrapped.
  860. The variable `org-startup-truncated' allows to configure
  861. truncation for Org mode different to the other modes that use the
  862. variable `truncate-lines' and as a shortcut instead of putting
  863. the variable `truncate-lines' into the `org-mode-hook'. If one
  864. wants to configure truncation for Org mode not statically but
  865. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  866. the variable `truncate-lines' has to be used because in such a
  867. case it is too late to set the variable `org-startup-truncated'."
  868. :group 'org-startup
  869. :type 'boolean)
  870. (defcustom org-startup-indented nil
  871. "Non-nil means turn on `org-indent-mode' on startup.
  872. This can also be configured on a per-file basis by adding one of
  873. the following lines anywhere in the buffer:
  874. #+STARTUP: indent
  875. #+STARTUP: noindent"
  876. :group 'org-structure
  877. :type '(choice
  878. (const :tag "Not" nil)
  879. (const :tag "Globally (slow on startup in large files)" t)))
  880. (defcustom org-startup-numerated nil
  881. "Non-nil means turn on `org-num-mode' on startup.
  882. This can also be configured on a per-file basis by adding one of
  883. the following lines anywhere in the buffer:
  884. #+STARTUP: num
  885. #+STARTUP: nonum"
  886. :group 'org-structure
  887. :package-version '(Org . "9.4")
  888. :type '(choice
  889. (const :tag "Not" nil)
  890. (const :tag "Globally" t)))
  891. (defcustom org-use-sub-superscripts t
  892. "Non-nil means interpret \"_\" and \"^\" for display.
  893. If you want to control how Org exports those characters, see
  894. `org-export-with-sub-superscripts'.
  895. When this option is turned on, you can use TeX-like syntax for
  896. sub- and superscripts within the buffer. Several characters after
  897. \"_\" or \"^\" will be considered as a single item - so grouping
  898. with {} is normally not needed. For example, the following things
  899. will be parsed as single sub- or superscripts:
  900. 10^24 or 10^tau several digits will be considered 1 item.
  901. 10^-12 or 10^-tau a leading sign with digits or a word
  902. x^2-y^3 will be read as x^2 - y^3, because items are
  903. terminated by almost any nonword/nondigit char.
  904. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  905. Still, ambiguity is possible. So when in doubt, use {} to enclose
  906. the sub/superscript. If you set this variable to the symbol `{}',
  907. the braces are *required* in order to trigger interpretations as
  908. sub/superscript. This can be helpful in documents that need \"_\"
  909. frequently in plain text."
  910. :group 'org-startup
  911. :version "24.4"
  912. :package-version '(Org . "8.0")
  913. :type '(choice
  914. (const :tag "Always interpret" t)
  915. (const :tag "Only with braces" {})
  916. (const :tag "Never interpret" nil)))
  917. (defcustom org-startup-with-beamer-mode nil
  918. "Non-nil means turn on `org-beamer-mode' on startup.
  919. This can also be configured on a per-file basis by adding one of
  920. the following lines anywhere in the buffer:
  921. #+STARTUP: beamer"
  922. :group 'org-startup
  923. :version "24.1"
  924. :type 'boolean)
  925. (defcustom org-startup-align-all-tables nil
  926. "Non-nil means align all tables when visiting a file.
  927. This can also be configured on a per-file basis by adding one of
  928. the following lines anywhere in the buffer:
  929. #+STARTUP: align
  930. #+STARTUP: noalign"
  931. :group 'org-startup
  932. :type 'boolean)
  933. (defcustom org-startup-shrink-all-tables nil
  934. "Non-nil means shrink all table columns with a width cookie.
  935. This can also be configured on a per-file basis by adding one of
  936. the following lines anywhere in the buffer:
  937. #+STARTUP: shrink"
  938. :group 'org-startup
  939. :type 'boolean
  940. :version "27.1"
  941. :package-version '(Org . "9.2")
  942. :safe #'booleanp)
  943. (defcustom org-startup-with-inline-images nil
  944. "Non-nil means show inline images when loading a new Org file.
  945. This can also be configured on a per-file basis by adding one of
  946. the following lines anywhere in the buffer:
  947. #+STARTUP: inlineimages
  948. #+STARTUP: noinlineimages"
  949. :group 'org-startup
  950. :version "24.1"
  951. :type 'boolean)
  952. (defcustom org-startup-with-latex-preview nil
  953. "Non-nil means preview LaTeX fragments when loading a new Org file.
  954. This can also be configured on a per-file basis by adding one of
  955. the following lines anywhere in the buffer:
  956. #+STARTUP: latexpreview
  957. #+STARTUP: nolatexpreview"
  958. :group 'org-startup
  959. :version "24.4"
  960. :package-version '(Org . "8.0")
  961. :type 'boolean)
  962. (defcustom org-insert-mode-line-in-empty-file nil
  963. "Non-nil means insert the first line setting Org mode in empty files.
  964. When the function `org-mode' is called interactively in an empty file, this
  965. normally means that the file name does not automatically trigger Org mode.
  966. To ensure that the file will always be in Org mode in the future, a
  967. line enforcing Org mode will be inserted into the buffer, if this option
  968. has been set."
  969. :group 'org-startup
  970. :type 'boolean)
  971. (defcustom org-ellipsis nil
  972. "The ellipsis to use in the Org mode outline.
  973. When nil, just use the standard three dots. When a non-empty string,
  974. use that string instead.
  975. The change affects only Org mode (which will then use its own display table).
  976. Changing this requires executing `\\[org-mode]' in a buffer to become
  977. effective. It cannot be set as a local variable."
  978. :group 'org-startup
  979. :type '(choice (const :tag "Default" nil)
  980. (string :tag "String" :value "...#")))
  981. (defvar org-display-table nil
  982. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  983. (defcustom org-directory "~/org"
  984. "Directory with Org files.
  985. This is just a default location to look for Org files. There is no need
  986. at all to put your files into this directory. It is used in the
  987. following situations:
  988. 1. When a capture template specifies a target file that is not an
  989. absolute path. The path will then be interpreted relative to
  990. `org-directory'
  991. 2. When the value of variable `org-agenda-files' is a single file, any
  992. relative paths in this file will be taken as relative to
  993. `org-directory'."
  994. :group 'org-refile
  995. :group 'org-capture
  996. :type 'directory)
  997. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  998. "Default target for storing notes.
  999. Used as a fall back file for org-capture.el, for templates that
  1000. do not specify a target file."
  1001. :group 'org-refile
  1002. :group 'org-capture
  1003. :type 'file)
  1004. (defcustom org-reverse-note-order nil
  1005. "Non-nil means store new notes at the beginning of a file or entry.
  1006. When nil, new notes will be filed to the end of a file or entry.
  1007. This can also be a list with cons cells of regular expressions that
  1008. are matched against file names, and values."
  1009. :group 'org-capture
  1010. :group 'org-refile
  1011. :type '(choice
  1012. (const :tag "Reverse always" t)
  1013. (const :tag "Reverse never" nil)
  1014. (repeat :tag "By file name regexp"
  1015. (cons regexp boolean))))
  1016. (defgroup org-keywords nil
  1017. "Keywords in Org mode."
  1018. :tag "Org Keywords"
  1019. :group 'org)
  1020. (defcustom org-closed-keep-when-no-todo nil
  1021. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1022. :group 'org-todo
  1023. :group 'org-keywords
  1024. :version "24.4"
  1025. :package-version '(Org . "8.0")
  1026. :type 'boolean)
  1027. (defgroup org-structure nil
  1028. "Options concerning the general structure of Org files."
  1029. :tag "Org Structure"
  1030. :group 'org)
  1031. (defcustom org-indirect-buffer-display 'other-window
  1032. "How should indirect tree buffers be displayed?
  1033. This applies to indirect buffers created with the commands
  1034. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1035. Valid values are:
  1036. current-window Display in the current window
  1037. other-window Just display in another window.
  1038. dedicated-frame Create one new frame, and re-use it each time.
  1039. new-frame Make a new frame each time. Note that in this case
  1040. previously-made indirect buffers are kept, and you need to
  1041. kill these buffers yourself."
  1042. :group 'org-structure
  1043. :group 'org-agenda-windows
  1044. :type '(choice
  1045. (const :tag "In current window" current-window)
  1046. (const :tag "In current frame, other window" other-window)
  1047. (const :tag "Each time a new frame" new-frame)
  1048. (const :tag "One dedicated frame" dedicated-frame)))
  1049. (defconst org-file-apps-gnu
  1050. '((remote . emacs)
  1051. (system . mailcap)
  1052. (t . mailcap))
  1053. "Default file applications on a UNIX or GNU/Linux system.
  1054. See `org-file-apps'.")
  1055. (defconst org-file-apps-macos
  1056. '((remote . emacs)
  1057. (system . "open %s")
  1058. ("ps.gz" . "gv %s")
  1059. ("eps.gz" . "gv %s")
  1060. ("dvi" . "xdvi %s")
  1061. ("fig" . "xfig %s")
  1062. (t . "open %s"))
  1063. "Default file applications on a macOS system.
  1064. The system \"open\" is known as a default, but we use X11 applications
  1065. for some files for which the OS does not have a good default.
  1066. See `org-file-apps'.")
  1067. (defconst org-file-apps-windowsnt
  1068. (list '(remote . emacs)
  1069. (cons 'system (lambda (file _path)
  1070. (with-no-warnings (w32-shell-execute "open" file))))
  1071. (cons t (lambda (file _path)
  1072. (with-no-warnings (w32-shell-execute "open" file)))))
  1073. "Default file applications on a Windows NT system.
  1074. The system \"open\" is used for most files.
  1075. See `org-file-apps'.")
  1076. (defcustom org-file-apps
  1077. '((auto-mode . emacs)
  1078. (directory . emacs)
  1079. ("\\.mm\\'" . default)
  1080. ("\\.x?html?\\'" . default)
  1081. ("\\.pdf\\'" . default))
  1082. "Applications for opening `file:path' items in a document.
  1083. \\<org-mode-map>
  1084. Org mode uses system defaults for different file types, but you
  1085. can use this variable to set the application for a given file
  1086. extension. The entries in this list are cons cells where the car
  1087. identifies files and the cdr the corresponding command.
  1088. Possible values for the file identifier are:
  1089. \"string\" A string as a file identifier can be interpreted in different
  1090. ways, depending on its contents:
  1091. - Alphanumeric characters only:
  1092. Match links with this file extension.
  1093. Example: (\"pdf\" . \"evince %s\")
  1094. to open PDFs with evince.
  1095. - Regular expression: Match links where the
  1096. filename matches the regexp. If you want to
  1097. use groups here, use shy groups.
  1098. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1099. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1100. to open *.html and *.xhtml with firefox.
  1101. - Regular expression which contains (non-shy) groups:
  1102. Match links where the whole link, including \"::\", and
  1103. anything after that, matches the regexp.
  1104. In a custom command string, %1, %2, etc. are replaced with
  1105. the parts of the link that were matched by the groups.
  1106. For backwards compatibility, if a command string is given
  1107. that does not use any of the group matches, this case is
  1108. handled identically to the second one (i.e. match against
  1109. file name only).
  1110. In a custom function, you can access the group matches with
  1111. (match-string n link).
  1112. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1113. \"evince -p %1 %s\")
  1114. to open [[file:document.pdf::5]] with evince at page 5.
  1115. `directory' Matches a directory
  1116. `remote' Matches a remote file, accessible through tramp or efs.
  1117. Remote files most likely should be visited through Emacs
  1118. because external applications cannot handle such paths.
  1119. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1120. so all files Emacs knows how to handle. Using this with
  1121. command `emacs' will open most files in Emacs. Beware that this
  1122. will also open html files inside Emacs, unless you add
  1123. (\"html\" . default) to the list as well.
  1124. `system' The system command to open files, like `open' on Windows
  1125. and macOS, and mailcap under GNU/Linux. This is the command
  1126. that will be selected if you call `org-open-at-point' with a
  1127. double prefix argument (`\\[universal-argument] \
  1128. \\[universal-argument] \\[org-open-at-point]').
  1129. t Default for files not matched by any of the other options.
  1130. Possible values for the command are:
  1131. `emacs' The file will be visited by the current Emacs process.
  1132. `default' Use the default application for this file type, which is the
  1133. association for t in the list, most likely in the system-specific
  1134. part. This can be used to overrule an unwanted setting in the
  1135. system-specific variable.
  1136. `system' Use the system command for opening files, like \"open\".
  1137. This command is specified by the entry whose car is `system'.
  1138. Most likely, the system-specific version of this variable
  1139. does define this command, but you can overrule/replace it
  1140. here.
  1141. `mailcap' Use command specified in the mailcaps.
  1142. string A command to be executed by a shell; %s will be replaced
  1143. by the path to the file.
  1144. function A Lisp function, which will be called with two arguments:
  1145. the file path and the original link string, without the
  1146. \"file:\" prefix.
  1147. For more examples, see the system specific constants
  1148. `org-file-apps-macos'
  1149. `org-file-apps-windowsnt'
  1150. `org-file-apps-gnu'."
  1151. :group 'org
  1152. :package-version '(Org . "9.4")
  1153. :type '(repeat
  1154. (cons (choice :value ""
  1155. (string :tag "Extension")
  1156. (const :tag "System command to open files" system)
  1157. (const :tag "Default for unrecognized files" t)
  1158. (const :tag "Remote file" remote)
  1159. (const :tag "Links to a directory" directory)
  1160. (const :tag "Any files that have Emacs modes"
  1161. auto-mode))
  1162. (choice :value ""
  1163. (const :tag "Visit with Emacs" emacs)
  1164. (const :tag "Use default" default)
  1165. (const :tag "Use the system command" system)
  1166. (string :tag "Command")
  1167. (function :tag "Function")))))
  1168. (defcustom org-open-non-existing-files nil
  1169. "Non-nil means `org-open-file' opens non-existing files.
  1170. When nil, an error is thrown.
  1171. This variable applies only to external applications because they
  1172. might choke on non-existing files. If the link is to a file that
  1173. will be opened in Emacs, the variable is ignored."
  1174. :group 'org
  1175. :type 'boolean
  1176. :safe #'booleanp)
  1177. (defcustom org-open-directory-means-index-dot-org nil
  1178. "When non-nil a link to a directory really means to \"index.org\".
  1179. When nil, following a directory link runs Dired or opens
  1180. a finder/explorer window on that directory."
  1181. :group 'org
  1182. :type 'boolean
  1183. :safe #'booleanp)
  1184. (defcustom org-bookmark-names-plist
  1185. '(:last-capture "org-capture-last-stored"
  1186. :last-refile "org-refile-last-stored"
  1187. :last-capture-marker "org-capture-last-stored-marker")
  1188. "Names for bookmarks automatically set by some Org commands.
  1189. This can provide strings as names for a number of bookmarks Org sets
  1190. automatically. The following keys are currently implemented:
  1191. :last-capture
  1192. :last-capture-marker
  1193. :last-refile
  1194. When a key does not show up in the property list, the corresponding bookmark
  1195. is not set."
  1196. :group 'org-structure
  1197. :type 'plist)
  1198. (defgroup org-edit-structure nil
  1199. "Options concerning structure editing in Org mode."
  1200. :tag "Org Edit Structure"
  1201. :group 'org-structure)
  1202. (defcustom org-odd-levels-only nil
  1203. "Non-nil means skip even levels and only use odd levels for the outline.
  1204. This has the effect that two stars are being added/taken away in
  1205. promotion/demotion commands. It also influences how levels are
  1206. handled by the exporters.
  1207. Changing it requires restart of `font-lock-mode' to become effective
  1208. for fontification also in regions already fontified.
  1209. You may also set this on a per-file basis by adding one of the following
  1210. lines to the buffer:
  1211. #+STARTUP: odd
  1212. #+STARTUP: oddeven"
  1213. :group 'org-edit-structure
  1214. :group 'org-appearance
  1215. :type 'boolean)
  1216. (defcustom org-adapt-indentation nil
  1217. "Non-nil means adapt indentation to outline node level.
  1218. When set to t, Org assumes that you write outlines by indenting
  1219. text in each node to align with the headline, after the stars.
  1220. When this variable is set to `headline-data', Org only adapts the
  1221. indentation of the data lines right below the headline, such as
  1222. planning/clock lines and property/logbook drawers.
  1223. The following issues are influenced by this variable:
  1224. - The indentation is increased by one space in a demotion
  1225. command, and decreased by one in a promotion command. However,
  1226. in the latter case, if shifting some line in the entry body
  1227. would alter document structure (e.g., insert a new headline),
  1228. indentation is not changed at all.
  1229. - Property drawers and planning information is inserted indented
  1230. when this variable is set. When nil, they will not be indented.
  1231. - TAB indents a line relative to current level. The lines below
  1232. a headline will be indented when this variable is set to t.
  1233. Note that this is all about true indentation, by adding and
  1234. removing space characters. See also \"org-indent.el\" which does
  1235. level-dependent indentation in a virtual way, i.e. at display
  1236. time in Emacs."
  1237. :group 'org-edit-structure
  1238. :type '(choice
  1239. (const :tag "Adapt indentation for all lines" t)
  1240. (const :tag "Adapt indentation for headline data lines"
  1241. headline-data)
  1242. (const :tag "Do not adapt indentation at all" nil))
  1243. :safe (lambda (x) (memq x '(t nil headline-data))))
  1244. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1245. (defcustom org-special-ctrl-a/e nil
  1246. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1247. When t, `C-a' will bring back the cursor to the beginning of the
  1248. headline text, i.e. after the stars and after a possible TODO
  1249. keyword. In an item, this will be the position after bullet and
  1250. check-box, if any. When the cursor is already at that position,
  1251. another `C-a' will bring it to the beginning of the line.
  1252. `C-e' will jump to the end of the headline, ignoring the presence
  1253. of tags in the headline. A second `C-e' will then jump to the
  1254. true end of the line, after any tags. This also means that, when
  1255. this variable is non-nil, `C-e' also will never jump beyond the
  1256. end of the heading of a folded section, i.e. not after the
  1257. ellipses.
  1258. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1259. normally, going to the true line boundary first. Only a directly
  1260. following, identical keypress will bring the cursor to the
  1261. special positions.
  1262. This may also be a cons cell where the behavior for `C-a' and
  1263. `C-e' is set separately."
  1264. :group 'org-edit-structure
  1265. :type '(choice
  1266. (const :tag "off" nil)
  1267. (const :tag "on: after stars/bullet and before tags first" t)
  1268. (const :tag "reversed: true line boundary first" reversed)
  1269. (cons :tag "Set C-a and C-e separately"
  1270. (choice :tag "Special C-a"
  1271. (const :tag "off" nil)
  1272. (const :tag "on: after stars/bullet first" t)
  1273. (const :tag "reversed: before stars/bullet first" reversed))
  1274. (choice :tag "Special C-e"
  1275. (const :tag "off" nil)
  1276. (const :tag "on: before tags first" t)
  1277. (const :tag "reversed: after tags first" reversed)))))
  1278. (defcustom org-special-ctrl-k nil
  1279. "Non-nil means `C-k' will behave specially in headlines.
  1280. When nil, `C-k' will call the default `kill-line' command.
  1281. When t, the following will happen while the cursor is in the headline:
  1282. - When at the beginning of a headline, kill the entire subtree.
  1283. - When in the middle of the headline text, kill the text up to the tags.
  1284. - When after the headline text and before the tags, kill all the tags."
  1285. :group 'org-edit-structure
  1286. :type 'boolean)
  1287. (defcustom org-ctrl-k-protect-subtree nil
  1288. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1289. When set to the symbol `error', simply throw an error when `C-k' is
  1290. used to kill (part-of) a headline that has hidden text behind it.
  1291. Any other non-nil value will result in a query to the user, if it is
  1292. OK to kill that hidden subtree. When nil, kill without remorse."
  1293. :group 'org-edit-structure
  1294. :version "24.1"
  1295. :type '(choice
  1296. (const :tag "Do not protect hidden subtrees" nil)
  1297. (const :tag "Protect hidden subtrees with a security query" t)
  1298. (const :tag "Never kill a hidden subtree with C-k" error)))
  1299. (defcustom org-special-ctrl-o t
  1300. "Non-nil means, make `C-o' insert a row in tables."
  1301. :group 'org-edit-structure
  1302. :type 'boolean)
  1303. (defcustom org-yank-folded-subtrees t
  1304. "Non-nil means when yanking subtrees, fold them.
  1305. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1306. it starts with a heading and all other headings in it are either children
  1307. or siblings, then fold all the subtrees. However, do this only if no
  1308. text after the yank would be swallowed into a folded tree by this action."
  1309. :group 'org-edit-structure
  1310. :type 'boolean)
  1311. (defcustom org-yank-adjusted-subtrees nil
  1312. "Non-nil means when yanking subtrees, adjust the level.
  1313. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1314. this function for details."
  1315. :group 'org-edit-structure
  1316. :type 'boolean)
  1317. (defcustom org-M-RET-may-split-line '((default . t))
  1318. "Non-nil means M-RET will split the line at the cursor position.
  1319. When nil, it will go to the end of the line before making a
  1320. new line.
  1321. You may also set this option in a different way for different
  1322. contexts. Valid contexts are:
  1323. headline when creating a new headline
  1324. item when creating a new item
  1325. table in a table field
  1326. default the value to be used for all contexts not explicitly
  1327. customized"
  1328. :group 'org-structure
  1329. :group 'org-table
  1330. :type '(choice
  1331. (const :tag "Always" t)
  1332. (const :tag "Never" nil)
  1333. (repeat :greedy t :tag "Individual contexts"
  1334. (cons
  1335. (choice :tag "Context"
  1336. (const headline)
  1337. (const item)
  1338. (const table)
  1339. (const default))
  1340. (boolean)))))
  1341. (defcustom org-insert-heading-respect-content nil
  1342. "Non-nil means insert new headings after the current subtree.
  1343. \\<org-mode-map>
  1344. When nil, the new heading is created directly after the current line.
  1345. The commands `\\[org-insert-heading-respect-content]' and \
  1346. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1347. for the duration of the command."
  1348. :group 'org-structure
  1349. :type 'boolean)
  1350. (defcustom org-blank-before-new-entry '((heading . auto)
  1351. (plain-list-item . auto))
  1352. "Should `org-insert-heading' leave a blank line before new heading/item?
  1353. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1354. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1355. which case Org will look at the surrounding headings/items and try to
  1356. make an intelligent decision whether to insert a blank line or not."
  1357. :group 'org-edit-structure
  1358. :type '(list
  1359. (cons (const heading)
  1360. (choice (const :tag "Never" nil)
  1361. (const :tag "Always" t)
  1362. (const :tag "Auto" auto)))
  1363. (cons (const plain-list-item)
  1364. (choice (const :tag "Never" nil)
  1365. (const :tag "Always" t)
  1366. (const :tag "Auto" auto)))))
  1367. (defcustom org-insert-heading-hook nil
  1368. "Hook being run after inserting a new heading."
  1369. :group 'org-edit-structure
  1370. :type 'hook)
  1371. (defgroup org-sparse-trees nil
  1372. "Options concerning sparse trees in Org mode."
  1373. :tag "Org Sparse Trees"
  1374. :group 'org-structure)
  1375. (defcustom org-highlight-sparse-tree-matches t
  1376. "Non-nil means highlight all matches that define a sparse tree.
  1377. The highlights will automatically disappear the next time the buffer is
  1378. changed by an edit command."
  1379. :group 'org-sparse-trees
  1380. :type 'boolean)
  1381. (defcustom org-remove-highlights-with-change t
  1382. "Non-nil means any change to the buffer will remove temporary highlights.
  1383. \\<org-mode-map>\
  1384. Such highlights are created by `org-occur' and `org-clock-display'.
  1385. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1386. to get rid of the highlights.
  1387. The highlights created by `org-latex-preview' always need
  1388. `\\[org-latex-preview]' to be removed."
  1389. :group 'org-sparse-trees
  1390. :group 'org-time
  1391. :type 'boolean)
  1392. (defcustom org-occur-case-fold-search t
  1393. "Non-nil means `org-occur' should be case-insensitive.
  1394. If set to `smart' the search will be case-insensitive only if it
  1395. doesn't specify any upper case character."
  1396. :group 'org-sparse-trees
  1397. :version "26.1"
  1398. :type '(choice
  1399. (const :tag "Case-sensitive" nil)
  1400. (const :tag "Case-insensitive" t)
  1401. (const :tag "Case-insensitive for lower case searches only" smart)))
  1402. (defcustom org-occur-hook '(org-first-headline-recenter)
  1403. "Hook that is run after `org-occur' has constructed a sparse tree.
  1404. This can be used to recenter the window to show as much of the structure
  1405. as possible."
  1406. :group 'org-sparse-trees
  1407. :type 'hook)
  1408. (defcustom org-self-insert-cluster-for-undo nil
  1409. "Non-nil means cluster self-insert commands for undo when possible.
  1410. If this is set, then, like in the Emacs command loop, 20 consecutive
  1411. characters will be undone together.
  1412. This is configurable, because there is some impact on typing performance."
  1413. :group 'org-table
  1414. :type 'boolean)
  1415. (defvaralias 'org-activate-links 'org-highlight-links)
  1416. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1417. "Types of links that should be highlighted in Org files.
  1418. This is a list of symbols, each one of them leading to the
  1419. highlighting of a certain link type.
  1420. You can still open links that are not highlighted.
  1421. In principle, it does not hurt to turn on highlighting for all
  1422. link types. There may be a small gain when turning off unused
  1423. link types. The types are:
  1424. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1425. angle Links in angular brackets that may contain whitespace like
  1426. <bbdb:Carsten Dominik>.
  1427. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1428. radio Text that is matched by a radio target, see manual for details.
  1429. tag Tag settings in a headline (link to tag search).
  1430. date Time stamps (link to calendar).
  1431. footnote Footnote labels.
  1432. If you set this variable during an Emacs session, use `org-mode-restart'
  1433. in the Org buffer so that the change takes effect."
  1434. :group 'org-appearance
  1435. :type '(set :greedy t
  1436. (const :tag "Double bracket links" bracket)
  1437. (const :tag "Angular bracket links" angle)
  1438. (const :tag "Plain text links" plain)
  1439. (const :tag "Radio target matches" radio)
  1440. (const :tag "Tags" tag)
  1441. (const :tag "Timestamps" date)
  1442. (const :tag "Footnotes" footnote)))
  1443. (defcustom org-mark-ring-length 4
  1444. "Number of different positions to be recorded in the ring.
  1445. Changing this requires a restart of Emacs to work correctly."
  1446. :group 'org-link-follow
  1447. :type 'integer)
  1448. (defgroup org-todo nil
  1449. "Options concerning TODO items in Org mode."
  1450. :tag "Org TODO"
  1451. :group 'org)
  1452. (defgroup org-progress nil
  1453. "Options concerning Progress logging in Org mode."
  1454. :tag "Org Progress"
  1455. :group 'org-time)
  1456. (defvar org-todo-interpretation-widgets
  1457. '((:tag "Sequence (cycling hits every state)" sequence)
  1458. (:tag "Type (cycling directly to DONE)" type))
  1459. "The available interpretation symbols for customizing `org-todo-keywords'.
  1460. Interested libraries should add to this list.")
  1461. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1462. "List of TODO entry keyword sequences and their interpretation.
  1463. \\<org-mode-map>This is a list of sequences.
  1464. Each sequence starts with a symbol, either `sequence' or `type',
  1465. indicating if the keywords should be interpreted as a sequence of
  1466. action steps, or as different types of TODO items. The first
  1467. keywords are states requiring action - these states will select a headline
  1468. for inclusion into the global TODO list Org produces. If one of the
  1469. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1470. signify that no further action is necessary. If \"|\" is not found,
  1471. the last keyword is treated as the only DONE state of the sequence.
  1472. The command `\\[org-todo]' cycles an entry through these states, and one
  1473. additional state where no keyword is present. For details about this
  1474. cycling, see the manual.
  1475. TODO keywords and interpretation can also be set on a per-file basis with
  1476. the special #+SEQ_TODO and #+TYP_TODO lines.
  1477. Each keyword can optionally specify a character for fast state selection
  1478. \(in combination with the variable `org-use-fast-todo-selection')
  1479. and specifiers for state change logging, using the same syntax that
  1480. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1481. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1482. indicates to record a time stamp each time this state is selected.
  1483. Each keyword may also specify if a timestamp or a note should be
  1484. recorded when entering or leaving the state, by adding additional
  1485. characters in the parenthesis after the keyword. This looks like this:
  1486. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1487. record only the time of the state change. With X and Y being either
  1488. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1489. Y when leaving the state if and only if the *target* state does not
  1490. define X. You may omit any of the fast-selection key or X or /Y,
  1491. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1492. For backward compatibility, this variable may also be just a list
  1493. of keywords. In this case the interpretation (sequence or type) will be
  1494. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1495. :group 'org-todo
  1496. :group 'org-keywords
  1497. :type '(choice
  1498. (repeat :tag "Old syntax, just keywords"
  1499. (string :tag "Keyword"))
  1500. (repeat :tag "New syntax"
  1501. (cons
  1502. (choice
  1503. :tag "Interpretation"
  1504. ;;Quick and dirty way to see
  1505. ;;`org-todo-interpretation'. This takes the
  1506. ;;place of item arguments
  1507. :convert-widget
  1508. (lambda (widget)
  1509. (widget-put widget
  1510. :args (mapcar
  1511. (lambda (x)
  1512. (widget-convert
  1513. (cons 'const x)))
  1514. org-todo-interpretation-widgets))
  1515. widget))
  1516. (repeat
  1517. (string :tag "Keyword"))))))
  1518. (defvar-local org-todo-keywords-1 nil
  1519. "All TODO and DONE keywords active in a buffer.")
  1520. (defvar org-todo-keywords-for-agenda nil)
  1521. (defvar org-done-keywords-for-agenda nil)
  1522. (defvar org-todo-keyword-alist-for-agenda nil)
  1523. (defvar org-tag-alist-for-agenda nil
  1524. "Alist of all tags from all agenda files.")
  1525. (defvar org-tag-groups-alist-for-agenda nil
  1526. "Alist of all groups tags from all current agenda files.")
  1527. (defvar-local org-tag-groups-alist nil)
  1528. (defvar org-agenda-contributing-files nil)
  1529. (defvar-local org-current-tag-alist nil
  1530. "Alist of all tag groups in current buffer.
  1531. This variable takes into consideration `org-tag-alist',
  1532. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1533. (defvar-local org-not-done-keywords nil)
  1534. (defvar-local org-done-keywords nil)
  1535. (defvar-local org-todo-heads nil)
  1536. (defvar-local org-todo-sets nil)
  1537. (defvar-local org-todo-log-states nil)
  1538. (defvar-local org-todo-kwd-alist nil)
  1539. (defvar-local org-todo-key-alist nil)
  1540. (defvar-local org-todo-key-trigger nil)
  1541. (defcustom org-todo-interpretation 'sequence
  1542. "Controls how TODO keywords are interpreted.
  1543. This variable is in principle obsolete and is only used for
  1544. backward compatibility, if the interpretation of todo keywords is
  1545. not given already in `org-todo-keywords'. See that variable for
  1546. more information."
  1547. :group 'org-todo
  1548. :group 'org-keywords
  1549. :type '(choice (const sequence)
  1550. (const type)))
  1551. (defcustom org-use-fast-todo-selection 'auto
  1552. "\\<org-mode-map>\
  1553. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1554. This variable describes if and under what circumstances the cycling
  1555. mechanism for TODO keywords will be replaced by a single-key, direct
  1556. selection scheme, where the choices are displayed in a little window.
  1557. When nil, fast selection is never used. This means that the command
  1558. will always switch to the next state.
  1559. When it is the symbol `auto', fast selection is whenever selection
  1560. keys have been defined.
  1561. `expert' is like `auto', but no special window with the keyword
  1562. will be shown, choices will only be listed in the prompt.
  1563. In all cases, the special interface is only used if access keys have
  1564. actually been assigned by the user, i.e. if keywords in the configuration
  1565. are followed by a letter in parenthesis, like TODO(t)."
  1566. :group 'org-todo
  1567. :set (lambda (var val)
  1568. (cond
  1569. ((eq var t) (set var 'auto))
  1570. ((eq var 'prefix) (set var nil))
  1571. (t (set var val))))
  1572. :type '(choice
  1573. (const :tag "Never" nil)
  1574. (const :tag "Automatically, when key letter have been defined" auto)
  1575. (const :tag "Automatically, but don't show the selection window" expert)))
  1576. (defcustom org-provide-todo-statistics t
  1577. "Non-nil means update todo statistics after insert and toggle.
  1578. ALL-HEADLINES means update todo statistics by including headlines
  1579. with no TODO keyword as well, counting them as not done.
  1580. A list of TODO keywords means the same, but skip keywords that are
  1581. not in this list.
  1582. When set to a list of two lists, the first list contains keywords
  1583. to consider as TODO keywords, the second list contains keywords
  1584. to consider as DONE keywords.
  1585. When this is set, todo statistics is updated in the parent of the
  1586. current entry each time a todo state is changed."
  1587. :group 'org-todo
  1588. :type '(choice
  1589. (const :tag "Yes, only for TODO entries" t)
  1590. (const :tag "Yes, including all entries" all-headlines)
  1591. (repeat :tag "Yes, for TODOs in this list"
  1592. (string :tag "TODO keyword"))
  1593. (list :tag "Yes, for TODOs and DONEs in these lists"
  1594. (repeat (string :tag "TODO keyword"))
  1595. (repeat (string :tag "DONE keyword")))
  1596. (other :tag "No TODO statistics" nil)))
  1597. (defcustom org-hierarchical-todo-statistics t
  1598. "Non-nil means TODO statistics covers just direct children.
  1599. When nil, all entries in the subtree are considered.
  1600. This has only an effect if `org-provide-todo-statistics' is set.
  1601. To set this to nil for only a single subtree, use a COOKIE_DATA
  1602. property and include the word \"recursive\" into the value."
  1603. :group 'org-todo
  1604. :type 'boolean)
  1605. (defcustom org-after-todo-state-change-hook nil
  1606. "Hook which is run after the state of a TODO item was changed.
  1607. The new state (a string with a TODO keyword, or nil) is available in the
  1608. Lisp variable `org-state'."
  1609. :group 'org-todo
  1610. :type 'hook)
  1611. (defvar org-blocker-hook nil
  1612. "Hook for functions that are allowed to block a state change.
  1613. Functions in this hook should not modify the buffer.
  1614. Each function gets as its single argument a property list,
  1615. see `org-trigger-hook' for more information about this list.
  1616. If any of the functions in this hook returns nil, the state change
  1617. is blocked.")
  1618. (defvar org-trigger-hook nil
  1619. "Hook for functions that are triggered by a state change.
  1620. Each function gets as its single argument a property list with at
  1621. least the following elements:
  1622. (:type type-of-change :position pos-at-entry-start
  1623. :from old-state :to new-state)
  1624. Depending on the type, more properties may be present.
  1625. This mechanism is currently implemented for:
  1626. TODO state changes
  1627. ------------------
  1628. :type todo-state-change
  1629. :from previous state (keyword as a string), or nil, or a symbol
  1630. `todo' or `done', to indicate the general type of state.
  1631. :to new state, like in :from")
  1632. (defcustom org-enforce-todo-dependencies nil
  1633. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1634. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1635. be blocked if any prior sibling is not yet done.
  1636. Finally, if the parent is blocked because of ordered siblings of its own,
  1637. the child will also be blocked."
  1638. :set (lambda (var val)
  1639. (set var val)
  1640. (if val
  1641. (add-hook 'org-blocker-hook
  1642. 'org-block-todo-from-children-or-siblings-or-parent)
  1643. (remove-hook 'org-blocker-hook
  1644. 'org-block-todo-from-children-or-siblings-or-parent)))
  1645. :group 'org-todo
  1646. :type 'boolean)
  1647. (defcustom org-enforce-todo-checkbox-dependencies nil
  1648. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1649. When this is nil, checkboxes have no influence on switching TODO states.
  1650. When non-nil, you first need to check off all check boxes before the TODO
  1651. entry can be switched to DONE.
  1652. This variable needs to be set before org.el is loaded, and you need to
  1653. restart Emacs after a change to make the change effective. The only way
  1654. to change it while Emacs is running is through the customize interface."
  1655. :set (lambda (var val)
  1656. (set var val)
  1657. (if val
  1658. (add-hook 'org-blocker-hook
  1659. 'org-block-todo-from-checkboxes)
  1660. (remove-hook 'org-blocker-hook
  1661. 'org-block-todo-from-checkboxes)))
  1662. :group 'org-todo
  1663. :type 'boolean)
  1664. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1665. "Non-nil means inserting a TODO heading is treated as state change.
  1666. So when the command `\\[org-insert-todo-heading]' is used, state change
  1667. logging will apply if appropriate. When nil, the new TODO item will
  1668. be inserted directly, and no logging will take place."
  1669. :group 'org-todo
  1670. :type 'boolean)
  1671. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1672. "Non-nil means switching TODO states with S-cursor counts as state change.
  1673. This is the default behavior. However, setting this to nil allows a
  1674. convenient way to select a TODO state and bypass any logging associated
  1675. with that."
  1676. :group 'org-todo
  1677. :type 'boolean)
  1678. (defcustom org-todo-state-tags-triggers nil
  1679. "Tag changes that should be triggered by TODO state changes.
  1680. This is a list. Each entry is
  1681. (state-change (tag . flag) .......)
  1682. State-change can be a string with a state, and empty string to indicate the
  1683. state that has no TODO keyword, or it can be one of the symbols `todo'
  1684. or `done', meaning any not-done or done state, respectively."
  1685. :group 'org-todo
  1686. :group 'org-tags
  1687. :type '(repeat
  1688. (cons (choice :tag "When changing to"
  1689. (const :tag "Not-done state" todo)
  1690. (const :tag "Done state" done)
  1691. (string :tag "State"))
  1692. (repeat
  1693. (cons :tag "Tag action"
  1694. (string :tag "Tag")
  1695. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1696. (defcustom org-log-done nil
  1697. "Information to record when a task moves to the DONE state.
  1698. Possible values are:
  1699. nil Don't add anything, just change the keyword
  1700. time Add a time stamp to the task
  1701. note Prompt for a note and add it with template `org-log-note-headings'
  1702. This option can also be set with on a per-file-basis with
  1703. #+STARTUP: nologdone
  1704. #+STARTUP: logdone
  1705. #+STARTUP: lognotedone
  1706. You can have local logging settings for a subtree by setting the LOGGING
  1707. property to one or more of these keywords."
  1708. :group 'org-todo
  1709. :group 'org-progress
  1710. :type '(choice
  1711. (const :tag "No logging" nil)
  1712. (const :tag "Record CLOSED timestamp" time)
  1713. (const :tag "Record CLOSED timestamp with note." note)))
  1714. ;; Normalize old uses of org-log-done.
  1715. (cond
  1716. ((eq org-log-done t) (setq org-log-done 'time))
  1717. ((and (listp org-log-done) (memq 'done org-log-done))
  1718. (setq org-log-done 'note)))
  1719. (defcustom org-log-reschedule nil
  1720. "Information to record when the scheduling date of a task is modified.
  1721. Possible values are:
  1722. nil Don't add anything, just change the date
  1723. time Add a time stamp to the task
  1724. note Prompt for a note and add it with template `org-log-note-headings'
  1725. This option can also be set with on a per-file-basis with
  1726. #+STARTUP: nologreschedule
  1727. #+STARTUP: logreschedule
  1728. #+STARTUP: lognotereschedule
  1729. You can have local logging settings for a subtree by setting the LOGGING
  1730. property to one or more of these keywords.
  1731. This variable has an effect when calling `org-schedule' or
  1732. `org-agenda-schedule' only."
  1733. :group 'org-todo
  1734. :group 'org-progress
  1735. :type '(choice
  1736. (const :tag "No logging" nil)
  1737. (const :tag "Record timestamp" time)
  1738. (const :tag "Record timestamp with note" note)))
  1739. (defcustom org-log-redeadline nil
  1740. "Information to record when the deadline date of a task is modified.
  1741. Possible values are:
  1742. nil Don't add anything, just change the date
  1743. time Add a time stamp to the task
  1744. note Prompt for a note and add it with template `org-log-note-headings'
  1745. This option can also be set with on a per-file-basis with
  1746. #+STARTUP: nologredeadline
  1747. #+STARTUP: logredeadline
  1748. #+STARTUP: lognoteredeadline
  1749. You can have local logging settings for a subtree by setting the LOGGING
  1750. property to one or more of these keywords.
  1751. This variable has an effect when calling `org-deadline' or
  1752. `org-agenda-deadline' only."
  1753. :group 'org-todo
  1754. :group 'org-progress
  1755. :type '(choice
  1756. (const :tag "No logging" nil)
  1757. (const :tag "Record timestamp" time)
  1758. (const :tag "Record timestamp with note." note)))
  1759. (defcustom org-log-note-clock-out nil
  1760. "Non-nil means record a note when clocking out of an item.
  1761. This can also be configured on a per-file basis by adding one of
  1762. the following lines anywhere in the buffer:
  1763. #+STARTUP: lognoteclock-out
  1764. #+STARTUP: nolognoteclock-out"
  1765. :group 'org-todo
  1766. :group 'org-progress
  1767. :type 'boolean)
  1768. (defcustom org-log-done-with-time t
  1769. "Non-nil means the CLOSED time stamp will contain date and time.
  1770. When nil, only the date will be recorded."
  1771. :group 'org-progress
  1772. :type 'boolean)
  1773. (defcustom org-log-note-headings
  1774. '((done . "CLOSING NOTE %t")
  1775. (state . "State %-12s from %-12S %t")
  1776. (note . "Note taken on %t")
  1777. (reschedule . "Rescheduled from %S on %t")
  1778. (delschedule . "Not scheduled, was %S on %t")
  1779. (redeadline . "New deadline from %S on %t")
  1780. (deldeadline . "Removed deadline, was %S on %t")
  1781. (refile . "Refiled on %t")
  1782. (clock-out . ""))
  1783. "Headings for notes added to entries.
  1784. The value is an alist, with the car being a symbol indicating the
  1785. note context, and the cdr is the heading to be used. The heading
  1786. may also be the empty string. The following placeholders can be
  1787. used:
  1788. %t a time stamp.
  1789. %T an active time stamp instead the default inactive one
  1790. %d a short-format time stamp.
  1791. %D an active short-format time stamp.
  1792. %s the new TODO state or time stamp (inactive), in double quotes.
  1793. %S the old TODO state or time stamp (inactive), in double quotes.
  1794. %u the user name.
  1795. %U full user name.
  1796. In fact, it is not a good idea to change the `state' entry,
  1797. because Agenda Log mode depends on the format of these entries."
  1798. :group 'org-todo
  1799. :group 'org-progress
  1800. :type '(list :greedy t
  1801. (cons (const :tag "Heading when closing an item" done) string)
  1802. (cons (const :tag
  1803. "Heading when changing todo state (todo sequence only)"
  1804. state) string)
  1805. (cons (const :tag "Heading when just taking a note" note) string)
  1806. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1807. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1808. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1809. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1810. (cons (const :tag "Heading when refiling" refile) string)
  1811. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1812. (unless (assq 'note org-log-note-headings)
  1813. (push '(note . "%t") org-log-note-headings))
  1814. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1815. (defcustom org-log-into-drawer nil
  1816. "Non-nil means insert state change notes and time stamps into a drawer.
  1817. When nil, state changes notes will be inserted after the headline and
  1818. any scheduling and clock lines, but not inside a drawer.
  1819. The value of this variable should be the name of the drawer to use.
  1820. LOGBOOK is proposed as the default drawer for this purpose, you can
  1821. also set this to a string to define the drawer of your choice.
  1822. A value of t is also allowed, representing \"LOGBOOK\".
  1823. A value of t or nil can also be set with on a per-file-basis with
  1824. #+STARTUP: logdrawer
  1825. #+STARTUP: nologdrawer
  1826. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1827. will be ignored.
  1828. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1829. a subtree.
  1830. Do not check directly this variable in a Lisp program. Call
  1831. function `org-log-into-drawer' instead."
  1832. :group 'org-todo
  1833. :group 'org-progress
  1834. :type '(choice
  1835. (const :tag "Not into a drawer" nil)
  1836. (const :tag "LOGBOOK" t)
  1837. (string :tag "Other")))
  1838. (defun org-log-into-drawer ()
  1839. "Name of the log drawer, as a string, or nil.
  1840. This is the value of `org-log-into-drawer'. However, if the
  1841. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1842. be used instead of the default value."
  1843. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1844. (cond ((equal p "nil") nil)
  1845. ((equal p "t") "LOGBOOK")
  1846. ((stringp p) p)
  1847. (p "LOGBOOK")
  1848. ((stringp org-log-into-drawer) org-log-into-drawer)
  1849. (org-log-into-drawer "LOGBOOK"))))
  1850. (defcustom org-log-state-notes-insert-after-drawers nil
  1851. "Non-nil means insert state change notes after any drawers in entry.
  1852. Only the drawers that *immediately* follow the headline and the
  1853. deadline/scheduled line are skipped.
  1854. When nil, insert notes right after the heading and perhaps the line
  1855. with deadline/scheduling if present.
  1856. This variable will have no effect if `org-log-into-drawer' is
  1857. set."
  1858. :group 'org-todo
  1859. :group 'org-progress
  1860. :type 'boolean)
  1861. (defcustom org-log-states-order-reversed t
  1862. "Non-nil means the latest state note will be directly after heading.
  1863. When nil, the state change notes will be ordered according to time.
  1864. This option can also be set with on a per-file-basis with
  1865. #+STARTUP: logstatesreversed
  1866. #+STARTUP: nologstatesreversed"
  1867. :group 'org-todo
  1868. :group 'org-progress
  1869. :type 'boolean)
  1870. (defcustom org-todo-repeat-to-state nil
  1871. "The TODO state to which a repeater should return the repeating task.
  1872. By default this is the first task of a TODO sequence or the
  1873. previous state of a TYPE_TODO set. But you can specify to use
  1874. the previous state in a TODO sequence or a string.
  1875. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1876. entry, which has precedence over this option."
  1877. :group 'org-todo
  1878. :version "24.1"
  1879. :type '(choice (const :tag "Use the previous TODO state" t)
  1880. (const :tag "Use the head of the TODO sequence" nil)
  1881. (string :tag "Use a specific TODO state")))
  1882. (defcustom org-log-repeat 'time
  1883. "Non-nil means record moving through the DONE state when triggering repeat.
  1884. An auto-repeating task is immediately switched back to TODO when
  1885. marked DONE. If you are not logging state changes (by adding \"@\"
  1886. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1887. record a closing note, there will be no record of the task moving
  1888. through DONE. This variable forces taking a note anyway.
  1889. nil Don't force a record
  1890. time Record a time stamp
  1891. note Prompt for a note and add it with template `org-log-note-headings'
  1892. This option can also be set with on a per-file-basis with
  1893. #+STARTUP: nologrepeat
  1894. #+STARTUP: logrepeat
  1895. #+STARTUP: lognoterepeat
  1896. You can have local logging settings for a subtree by setting the LOGGING
  1897. property to one or more of these keywords."
  1898. :group 'org-todo
  1899. :group 'org-progress
  1900. :type '(choice
  1901. (const :tag "Don't force a record" nil)
  1902. (const :tag "Force recording the DONE state" time)
  1903. (const :tag "Force recording a note with the DONE state" note)))
  1904. (defcustom org-todo-repeat-hook nil
  1905. "Hook that is run after a task has been repeated."
  1906. :package-version '(Org . "9.2")
  1907. :group 'org-todo
  1908. :type 'hook)
  1909. (defgroup org-priorities nil
  1910. "Priorities in Org mode."
  1911. :tag "Org Priorities"
  1912. :group 'org-todo)
  1913. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1914. (defcustom org-priority-enable-commands t
  1915. "Non-nil means priority commands are active.
  1916. When nil, these commands will be disabled, so that you never accidentally
  1917. set a priority."
  1918. :group 'org-priorities
  1919. :type 'boolean)
  1920. (defvaralias 'org-highest-priority 'org-priority-highest)
  1921. (defcustom org-priority-highest ?A
  1922. "The highest priority of TODO items.
  1923. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1924. The default is the character ?A, which is 65 as a numeric value.
  1925. If you set `org-priority-highest' to a numeric value inferior to
  1926. 65, Org assumes you want to use digits for the priority cookie.
  1927. If you set it to >=65, Org assumes you want to use alphabetical
  1928. characters.
  1929. In both cases, the value of `org-priority-highest' must be
  1930. smaller than `org-priority-lowest': for example, if \"A\" is the
  1931. highest priority, it is smaller than the lowest \"C\" priority:
  1932. 65 < 67."
  1933. :group 'org-priorities
  1934. :type '(choice
  1935. (character :tag "Character")
  1936. (integer :tag "Integer (< 65)")))
  1937. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1938. (defcustom org-priority-lowest ?C
  1939. "The lowest priority of TODO items.
  1940. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1941. The default is the character ?C, which is 67 as a numeric value.
  1942. If you set `org-priority-lowest' to a numeric value inferior to
  1943. 65, Org assumes you want to use digits for the priority cookie.
  1944. If you set it to >=65, Org assumes you want to use alphabetical
  1945. characters.
  1946. In both cases, the value of `org-priority-lowest' must be greater
  1947. than `org-priority-highest': for example, if \"C\" is the lowest
  1948. priority, it is greater than the highest \"A\" priority: 67 >
  1949. 65."
  1950. :group 'org-priorities
  1951. :type '(choice
  1952. (character :tag "Character")
  1953. (integer :tag "Integer (< 65)")))
  1954. (defvaralias 'org-default-priority 'org-priority-default)
  1955. (defcustom org-priority-default ?B
  1956. "The default priority of TODO items.
  1957. This is the priority an item gets if no explicit priority is given.
  1958. When starting to cycle on an empty priority the first step in the cycle
  1959. depends on `org-priority-start-cycle-with-default'. The resulting first
  1960. step priority must not exceed the range from `org-priority-highest' to
  1961. `org-priority-lowest' which means that `org-priority-default' has to be
  1962. in this range exclusive or inclusive to the range boundaries. Else the
  1963. first step refuses to set the default and the second will fall back on
  1964. \(depending on the command used) the highest or lowest priority."
  1965. :group 'org-priorities
  1966. :type '(choice
  1967. (character :tag "Character")
  1968. (integer :tag "Integer (< 65)")))
  1969. (defcustom org-priority-start-cycle-with-default t
  1970. "Non-nil means start with default priority when starting to cycle.
  1971. When this is nil, the first step in the cycle will be (depending on the
  1972. command used) one higher or lower than the default priority.
  1973. See also `org-priority-default'."
  1974. :group 'org-priorities
  1975. :type 'boolean)
  1976. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  1977. (defcustom org-priority-get-priority-function nil
  1978. "Function to extract the priority from a string.
  1979. The string is normally the headline. If this is nil, Org
  1980. computes the priority from the priority cookie like [#A] in the
  1981. headline. It returns an integer, increasing by 1000 for each
  1982. priority level.
  1983. The user can set a different function here, which should take a
  1984. string as an argument and return the numeric priority."
  1985. :group 'org-priorities
  1986. :version "24.1"
  1987. :type '(choice
  1988. (const nil)
  1989. (function)))
  1990. (defgroup org-time nil
  1991. "Options concerning time stamps and deadlines in Org mode."
  1992. :tag "Org Time"
  1993. :group 'org)
  1994. (defcustom org-time-stamp-rounding-minutes '(0 5)
  1995. "Number of minutes to round time stamps to.
  1996. \\<org-mode-map>\
  1997. These are two values, the first applies when first creating a time stamp.
  1998. The second applies when changing it with the commands `S-up' and `S-down'.
  1999. When changing the time stamp, this means that it will change in steps
  2000. of N minutes, as given by the second value.
  2001. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2002. numbers should be factors of 60, so for example 5, 10, 15.
  2003. When this is larger than 1, you can still force an exact time stamp by using
  2004. a double prefix argument to a time stamp command like \
  2005. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2006. and by using a prefix arg to `S-up/down' to specify the exact number
  2007. of minutes to shift."
  2008. :group 'org-time
  2009. :get (lambda (var) ; Make sure both elements are there
  2010. (if (integerp (default-value var))
  2011. (list (default-value var) 5)
  2012. (default-value var)))
  2013. :type '(list
  2014. (integer :tag "when inserting times")
  2015. (integer :tag "when modifying times")))
  2016. ;; Normalize old customizations of this variable.
  2017. (when (integerp org-time-stamp-rounding-minutes)
  2018. (setq org-time-stamp-rounding-minutes
  2019. (list org-time-stamp-rounding-minutes
  2020. org-time-stamp-rounding-minutes)))
  2021. (defcustom org-display-custom-times nil
  2022. "Non-nil means overlay custom formats over all time stamps.
  2023. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2024. To turn this on on a per-file basis, insert anywhere in the file:
  2025. #+STARTUP: customtime"
  2026. :group 'org-time
  2027. :set 'set-default
  2028. :type 'sexp)
  2029. (make-variable-buffer-local 'org-display-custom-times)
  2030. (defcustom org-time-stamp-custom-formats
  2031. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2032. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2033. These are overlaid over the default ISO format if the variable
  2034. `org-display-custom-times' is set. Time like %H:%M should be at the
  2035. end of the second format. The custom formats are also honored by export
  2036. commands, if custom time display is turned on at the time of export."
  2037. :group 'org-time
  2038. :type 'sexp)
  2039. (defun org-time-stamp-format (&optional long inactive)
  2040. "Get the right format for a time string."
  2041. (let ((f (if long (cdr org-time-stamp-formats)
  2042. (car org-time-stamp-formats))))
  2043. (if inactive
  2044. (concat "[" (substring f 1 -1) "]")
  2045. f)))
  2046. (defcustom org-deadline-warning-days 14
  2047. "Number of days before expiration during which a deadline becomes active.
  2048. This variable governs the display in sparse trees and in the agenda.
  2049. When 0 or negative, it means use this number (the absolute value of it)
  2050. even if a deadline has a different individual lead time specified.
  2051. Custom commands can set this variable in the options section."
  2052. :group 'org-time
  2053. :group 'org-agenda-daily/weekly
  2054. :type 'integer)
  2055. (defcustom org-scheduled-delay-days 0
  2056. "Number of days before a scheduled item becomes active.
  2057. This variable governs the display in sparse trees and in the agenda.
  2058. The default value (i.e. 0) means: don't delay scheduled item.
  2059. When negative, it means use this number (the absolute value of it)
  2060. even if a scheduled item has a different individual delay time
  2061. specified.
  2062. Custom commands can set this variable in the options section."
  2063. :group 'org-time
  2064. :group 'org-agenda-daily/weekly
  2065. :version "24.4"
  2066. :package-version '(Org . "8.0")
  2067. :type 'integer)
  2068. (defcustom org-read-date-prefer-future t
  2069. "Non-nil means assume future for incomplete date input from user.
  2070. This affects the following situations:
  2071. 1. The user gives a month but not a year.
  2072. For example, if it is April and you enter \"feb 2\", this will be read
  2073. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2074. 2. The user gives a day, but no month.
  2075. For example, if today is the 15th, and you enter \"3\", Org will read
  2076. this as the third of *next* month. However, if you enter \"17\",
  2077. it will be considered as *this* month.
  2078. If you set this variable to the symbol `time', then also the following
  2079. will work:
  2080. 3. If the user gives a time.
  2081. If the time is before now, it will be interpreted as tomorrow.
  2082. Currently none of this works for ISO week specifications.
  2083. When this option is nil, the current day, month and year will always be
  2084. used as defaults.
  2085. See also `org-agenda-jump-prefer-future'."
  2086. :group 'org-time
  2087. :type '(choice
  2088. (const :tag "Never" nil)
  2089. (const :tag "Check month and day" t)
  2090. (const :tag "Check month, day, and time" time)))
  2091. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2092. "Should the agenda jump command prefer the future for incomplete dates?
  2093. The default is to do the same as configured in `org-read-date-prefer-future'.
  2094. But you can also set a deviating value here.
  2095. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2096. :group 'org-agenda
  2097. :group 'org-time
  2098. :version "24.1"
  2099. :type '(choice
  2100. (const :tag "Use org-read-date-prefer-future"
  2101. org-read-date-prefer-future)
  2102. (const :tag "Never" nil)
  2103. (const :tag "Always" t)))
  2104. (defcustom org-read-date-force-compatible-dates t
  2105. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2106. Depending on the system Emacs is running on, certain dates cannot
  2107. be represented with the type used internally to represent time.
  2108. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2109. correctly. Some systems allow for earlier dates, some for later,
  2110. some for both. One way to find out is to insert any date into an
  2111. Org buffer, putting the cursor on the year and hitting S-up and
  2112. S-down to test the range.
  2113. When this variable is set to t, the date/time prompt will not let
  2114. you specify dates outside the 1970-2037 range, so it is certain that
  2115. these dates will work in whatever version of Emacs you are
  2116. running, and also that you can move a file from one Emacs implementation
  2117. to another. Whenever Org is forcing the year for you, it will display
  2118. a message and beep.
  2119. When this variable is nil, Org will check if the date is
  2120. representable in the specific Emacs implementation you are using.
  2121. If not, it will force a year, usually the current year, and beep
  2122. to remind you. Currently this setting is not recommended because
  2123. the likelihood that you will open your Org files in an Emacs that
  2124. has limited date range is not negligible.
  2125. A workaround for this problem is to use diary sexp dates for time
  2126. stamps outside of this range."
  2127. :group 'org-time
  2128. :version "24.1"
  2129. :type 'boolean)
  2130. (defcustom org-read-date-display-live t
  2131. "Non-nil means display current interpretation of date prompt live.
  2132. This display will be in an overlay, in the minibuffer. Note that
  2133. live display is only active when `org-read-date-popup-calendar'
  2134. is non-nil."
  2135. :group 'org-time
  2136. :type 'boolean)
  2137. (defvaralias 'org-popup-calendar-for-date-prompt
  2138. 'org-read-date-popup-calendar)
  2139. (defcustom org-read-date-popup-calendar t
  2140. "Non-nil means pop up a calendar when prompting for a date.
  2141. In the calendar, the date can be selected with mouse-1. However, the
  2142. minibuffer will also be active, and you can simply enter the date as well.
  2143. When nil, only the minibuffer will be available."
  2144. :group 'org-time
  2145. :type 'boolean)
  2146. (defcustom org-extend-today-until 0
  2147. "The hour when your day really ends. Must be an integer.
  2148. This has influence for the following applications:
  2149. - When switching the agenda to \"today\". If it is still earlier than
  2150. the time given here, the day recognized as TODAY is actually yesterday.
  2151. - When a date is read from the user and it is still before the time given
  2152. here, the current date and time will be assumed to be yesterday, 23:59.
  2153. Also, timestamps inserted in capture templates follow this rule.
  2154. IMPORTANT: This is a feature whose implementation is and likely will
  2155. remain incomplete. Really, it is only here because past midnight seems to
  2156. be the favorite working time of John Wiegley :-)"
  2157. :group 'org-time
  2158. :type 'integer)
  2159. (defcustom org-use-effective-time nil
  2160. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2161. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2162. \"effective time\" of any timestamps between midnight and 8am will be
  2163. 23:59 of the previous day."
  2164. :group 'org-time
  2165. :version "24.1"
  2166. :type 'boolean)
  2167. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2168. "When non-nil, use the last clock out time for `org-todo'.
  2169. Note that this option has precedence over the combined use of
  2170. `org-use-effective-time' and `org-extend-today-until'."
  2171. :group 'org-time
  2172. :version "24.4"
  2173. :package-version '(Org . "8.0")
  2174. :type 'boolean)
  2175. (defcustom org-edit-timestamp-down-means-later nil
  2176. "Non-nil means S-down will increase the time in a time stamp.
  2177. When nil, S-up will increase."
  2178. :group 'org-time
  2179. :type 'boolean)
  2180. (defcustom org-calendar-follow-timestamp-change t
  2181. "Non-nil means make the calendar window follow timestamp changes.
  2182. When a timestamp is modified and the calendar window is visible, it will be
  2183. moved to the new date."
  2184. :group 'org-time
  2185. :type 'boolean)
  2186. (defgroup org-tags nil
  2187. "Options concerning tags in Org mode."
  2188. :tag "Org Tags"
  2189. :group 'org)
  2190. (defcustom org-tag-alist nil
  2191. "Default tags available in Org files.
  2192. The value of this variable is an alist. Associations either:
  2193. (TAG)
  2194. (TAG . SELECT)
  2195. (SPECIAL)
  2196. where TAG is a tag as a string, SELECT is character, used to
  2197. select that tag through the fast tag selection interface, and
  2198. SPECIAL is one of the following keywords: `:startgroup',
  2199. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2200. `:newline'. These keywords are used to define a hierarchy of
  2201. tags. See manual for details.
  2202. When this variable is nil, Org mode bases tag input on what is
  2203. already in the buffer. The value can be overridden locally by
  2204. using a TAGS keyword, e.g.,
  2205. #+TAGS: tag1 tag2
  2206. See also `org-tag-persistent-alist' to sidestep this behavior."
  2207. :group 'org-tags
  2208. :type '(repeat
  2209. (choice
  2210. (cons :tag "Tag with key"
  2211. (string :tag "Tag name")
  2212. (character :tag "Access char"))
  2213. (list :tag "Tag" (string :tag "Tag name"))
  2214. (const :tag "Start radio group" (:startgroup))
  2215. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2216. (const :tag "Group tags delimiter" (:grouptags))
  2217. (const :tag "End radio group" (:endgroup))
  2218. (const :tag "End tag group, non distinct" (:endgrouptag))
  2219. (const :tag "New line" (:newline)))))
  2220. (defcustom org-tag-persistent-alist nil
  2221. "Tags always available in Org files.
  2222. The value of this variable is an alist. Associations either:
  2223. (TAG)
  2224. (TAG . SELECT)
  2225. (SPECIAL)
  2226. where TAG is a tag as a string, SELECT is a character, used to
  2227. select that tag through the fast tag selection interface, and
  2228. SPECIAL is one of the following keywords: `:startgroup',
  2229. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2230. `:newline'. These keywords are used to define a hierarchy of
  2231. tags. See manual for details.
  2232. Unlike to `org-tag-alist', tags defined in this variable do not
  2233. depend on a local TAGS keyword. Instead, to disable these tags
  2234. on a per-file basis, insert anywhere in the file:
  2235. #+STARTUP: noptag"
  2236. :group 'org-tags
  2237. :type '(repeat
  2238. (choice
  2239. (cons :tag "Tag with key"
  2240. (string :tag "Tag name")
  2241. (character :tag "Access char"))
  2242. (list :tag "Tag" (string :tag "Tag name"))
  2243. (const :tag "Start radio group" (:startgroup))
  2244. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2245. (const :tag "Group tags delimiter" (:grouptags))
  2246. (const :tag "End radio group" (:endgroup))
  2247. (const :tag "End tag group, non distinct" (:endgrouptag))
  2248. (const :tag "New line" (:newline)))))
  2249. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2250. "If non-nil, always offer completion for all tags of all agenda files.
  2251. Setting this variable locally allows for dynamic generation of tag
  2252. completions in capture buffers.
  2253. (add-hook \\='org-capture-mode-hook
  2254. (lambda ()
  2255. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2256. :group 'org-tags
  2257. :version "24.1"
  2258. :type 'boolean)
  2259. (defvar org-file-tags nil
  2260. "List of tags that can be inherited by all entries in the file.
  2261. The tags will be inherited if the variable `org-use-tag-inheritance'
  2262. says they should be.
  2263. This variable is populated from #+FILETAGS lines.")
  2264. (defcustom org-use-fast-tag-selection 'auto
  2265. "Non-nil means use fast tag selection scheme.
  2266. This is a special interface to select and deselect tags with single keys.
  2267. When nil, fast selection is never used.
  2268. When the symbol `auto', fast selection is used if and only if selection
  2269. characters for tags have been configured, either through the variable
  2270. `org-tag-alist' or through a #+TAGS line in the buffer.
  2271. When t, fast selection is always used and selection keys are assigned
  2272. automatically if necessary."
  2273. :group 'org-tags
  2274. :type '(choice
  2275. (const :tag "Always" t)
  2276. (const :tag "Never" nil)
  2277. (const :tag "When selection characters are configured" auto)))
  2278. (defcustom org-fast-tag-selection-single-key nil
  2279. "Non-nil means fast tag selection exits after first change.
  2280. When nil, you have to press RET to exit it.
  2281. During fast tag selection, you can toggle this flag with `C-c'.
  2282. This variable can also have the value `expert'. In this case, the window
  2283. displaying the tags menu is not even shown, until you press `C-c' again."
  2284. :group 'org-tags
  2285. :type '(choice
  2286. (const :tag "No" nil)
  2287. (const :tag "Yes" t)
  2288. (const :tag "Expert" expert)))
  2289. (defvar org-fast-tag-selection-include-todo nil
  2290. "Non-nil means fast tags selection interface will also offer TODO states.
  2291. This is an undocumented feature, you should not rely on it.")
  2292. (defcustom org-tags-column -77
  2293. "The column to which tags should be indented in a headline.
  2294. If this number is positive, it specifies the column. If it is negative,
  2295. it means that the tags should be flushright to that column. For example,
  2296. -80 works well for a normal 80 character screen.
  2297. When 0, place tags directly after headline text, with only one space in
  2298. between."
  2299. :group 'org-tags
  2300. :type 'integer)
  2301. (defcustom org-auto-align-tags t
  2302. "Non-nil keeps tags aligned when modifying headlines.
  2303. Some operations (i.e. demoting) change the length of a headline and
  2304. therefore shift the tags around. With this option turned on, after
  2305. each such operation the tags are again aligned to `org-tags-column'."
  2306. :group 'org-tags
  2307. :type 'boolean)
  2308. (defcustom org-use-tag-inheritance t
  2309. "Non-nil means tags in levels apply also for sublevels.
  2310. When nil, only the tags directly given in a specific line apply there.
  2311. This may also be a list of tags that should be inherited, or a regexp that
  2312. matches tags that should be inherited. Additional control is possible
  2313. with the variable `org-tags-exclude-from-inheritance' which gives an
  2314. explicit list of tags to be excluded from inheritance, even if the value of
  2315. `org-use-tag-inheritance' would select it for inheritance.
  2316. If this option is t, a match early-on in a tree can lead to a large
  2317. number of matches in the subtree when constructing the agenda or creating
  2318. a sparse tree. If you only want to see the first match in a tree during
  2319. a search, check out the variable `org-tags-match-list-sublevels'."
  2320. :group 'org-tags
  2321. :type '(choice
  2322. (const :tag "Not" nil)
  2323. (const :tag "Always" t)
  2324. (repeat :tag "Specific tags" (string :tag "Tag"))
  2325. (regexp :tag "Tags matched by regexp")))
  2326. (defcustom org-tags-exclude-from-inheritance nil
  2327. "List of tags that should never be inherited.
  2328. This is a way to exclude a few tags from inheritance. For way to do
  2329. the opposite, to actively allow inheritance for selected tags,
  2330. see the variable `org-use-tag-inheritance'."
  2331. :group 'org-tags
  2332. :type '(repeat (string :tag "Tag")))
  2333. (defun org-tag-inherit-p (tag)
  2334. "Check if TAG is one that should be inherited."
  2335. (cond
  2336. ((member tag org-tags-exclude-from-inheritance) nil)
  2337. ((eq org-use-tag-inheritance t) t)
  2338. ((not org-use-tag-inheritance) nil)
  2339. ((stringp org-use-tag-inheritance)
  2340. (string-match org-use-tag-inheritance tag))
  2341. ((listp org-use-tag-inheritance)
  2342. (member tag org-use-tag-inheritance))
  2343. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2344. (defcustom org-tags-match-list-sublevels t
  2345. "Non-nil means list also sublevels of headlines matching a search.
  2346. This variable applies to tags/property searches, and also to stuck
  2347. projects because this search is based on a tags match as well.
  2348. When set to the symbol `indented', sublevels are indented with
  2349. leading dots.
  2350. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2351. the sublevels of a headline matching a tag search often also match
  2352. the same search. Listing all of them can create very long lists.
  2353. Setting this variable to nil causes subtrees of a match to be skipped.
  2354. This variable is semi-obsolete and probably should always be true. It
  2355. is better to limit inheritance to certain tags using the variables
  2356. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2357. :group 'org-tags
  2358. :type '(choice
  2359. (const :tag "No, don't list them" nil)
  2360. (const :tag "Yes, do list them" t)
  2361. (const :tag "List them, indented with leading dots" indented)))
  2362. (defcustom org-tags-sort-function nil
  2363. "When set, tags are sorted using this function as a comparator."
  2364. :group 'org-tags
  2365. :type '(choice
  2366. (const :tag "No sorting" nil)
  2367. (const :tag "Alphabetical" string-collate-lessp)
  2368. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2369. (function :tag "Custom function" nil)))
  2370. (defvar org-tags-history nil
  2371. "History of minibuffer reads for tags.")
  2372. (defvar org-last-tags-completion-table nil
  2373. "The last used completion table for tags.")
  2374. (defvar org-after-tags-change-hook nil
  2375. "Hook that is run after the tags in a line have changed.")
  2376. (defgroup org-properties nil
  2377. "Options concerning properties in Org mode."
  2378. :tag "Org Properties"
  2379. :group 'org)
  2380. (defcustom org-property-format "%-10s %s"
  2381. "How property key/value pairs should be formatted by `indent-line'.
  2382. When `indent-line' hits a property definition, it will format the line
  2383. according to this format, mainly to make sure that the values are
  2384. lined-up with respect to each other."
  2385. :group 'org-properties
  2386. :type 'string)
  2387. (defcustom org-properties-postprocess-alist nil
  2388. "Alist of properties and functions to adjust inserted values.
  2389. Elements of this alist must be of the form
  2390. ([string] [function])
  2391. where [string] must be a property name and [function] must be a
  2392. lambda expression: this lambda expression must take one argument,
  2393. the value to adjust, and return the new value as a string.
  2394. For example, this element will allow the property \"Remaining\"
  2395. to be updated wrt the relation between the \"Effort\" property
  2396. and the clock summary:
  2397. ((\"Remaining\" (lambda(value)
  2398. (let ((clocksum (org-clock-sum-current-item))
  2399. (effort (org-duration-to-minutes
  2400. (org-entry-get (point) \"Effort\"))))
  2401. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2402. :group 'org-properties
  2403. :version "24.1"
  2404. :type '(alist :key-type (string :tag "Property")
  2405. :value-type (function :tag "Function")))
  2406. (defcustom org-use-property-inheritance nil
  2407. "Non-nil means properties apply also for sublevels.
  2408. This setting is chiefly used during property searches. Turning it on can
  2409. cause significant overhead when doing a search, which is why it is not
  2410. on by default.
  2411. When nil, only the properties directly given in the current entry count.
  2412. When t, every property is inherited. The value may also be a list of
  2413. properties that should have inheritance, or a regular expression matching
  2414. properties that should be inherited.
  2415. However, note that some special properties use inheritance under special
  2416. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2417. and the properties ending in \"_ALL\" when they are used as descriptor
  2418. for valid values of a property.
  2419. Note for programmers:
  2420. When querying an entry with `org-entry-get', you can control if inheritance
  2421. should be used. By default, `org-entry-get' looks only at the local
  2422. properties. You can request inheritance by setting the inherit argument
  2423. to t (to force inheritance) or to `selective' (to respect the setting
  2424. in this variable)."
  2425. :group 'org-properties
  2426. :type '(choice
  2427. (const :tag "Not" nil)
  2428. (const :tag "Always" t)
  2429. (repeat :tag "Specific properties" (string :tag "Property"))
  2430. (regexp :tag "Properties matched by regexp")))
  2431. (defun org-property-inherit-p (property)
  2432. "Return a non-nil value if PROPERTY should be inherited."
  2433. (cond
  2434. ((eq org-use-property-inheritance t) t)
  2435. ((not org-use-property-inheritance) nil)
  2436. ((stringp org-use-property-inheritance)
  2437. (string-match org-use-property-inheritance property))
  2438. ((listp org-use-property-inheritance)
  2439. (member-ignore-case property org-use-property-inheritance))
  2440. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2441. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2442. "The default column format, if no other format has been defined.
  2443. This variable can be set on the per-file basis by inserting a line
  2444. #+COLUMNS: %25ITEM ....."
  2445. :group 'org-properties
  2446. :type 'string)
  2447. (defcustom org-columns-default-format-for-agenda nil
  2448. "The default column format in an agenda buffer.
  2449. This will be used for column view in the agenda unless a format has
  2450. been set by adding `org-overriding-columns-format' to the local
  2451. settings list of a custom agenda view. When nil, the columns format
  2452. for the first item in the agenda list will be used, or as a fall-back,
  2453. `org-columns-default-format'."
  2454. :group 'org-properties
  2455. :type '(choice
  2456. (const :tag "No default" nil)
  2457. (string :tag "Format string")))
  2458. (defcustom org-columns-ellipses ".."
  2459. "The ellipses to be used when a field in column view is truncated.
  2460. When this is the empty string, as many characters as possible are shown,
  2461. but then there will be no visual indication that the field has been truncated.
  2462. When this is a string of length N, the last N characters of a truncated
  2463. field are replaced by this string. If the column is narrower than the
  2464. ellipses string, only part of the ellipses string will be shown."
  2465. :group 'org-properties
  2466. :type 'string)
  2467. (defconst org-global-properties-fixed
  2468. '(("VISIBILITY_ALL" . "folded children content all")
  2469. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2470. "List of property/value pairs that can be inherited by any entry.
  2471. These are fixed values, for the preset properties. The user variable
  2472. that can be used to add to this list is `org-global-properties'.
  2473. The entries in this list are cons cells where the car is a property
  2474. name and cdr is a string with the value. If the value represents
  2475. multiple items like an \"_ALL\" property, separate the items by
  2476. spaces.")
  2477. (defcustom org-global-properties nil
  2478. "List of property/value pairs that can be inherited by any entry.
  2479. This list will be combined with the constant `org-global-properties-fixed'.
  2480. The entries in this list are cons cells where the car is a property
  2481. name and cdr is a string with the value.
  2482. Buffer local properties are added either by a document property drawer
  2483. :PROPERTIES:
  2484. :NAME: VALUE
  2485. :END:
  2486. or by adding lines like
  2487. #+PROPERTY: NAME VALUE"
  2488. :group 'org-properties
  2489. :type '(repeat
  2490. (cons (string :tag "Property")
  2491. (string :tag "Value"))))
  2492. (defvar-local org-keyword-properties nil
  2493. "List of property/value pairs inherited by any entry.
  2494. Valid for the current buffer. This variable is populated from
  2495. PROPERTY keywords.
  2496. Note that properties are defined also in property drawers.
  2497. Properties defined there take precedence over properties defined
  2498. as keywords.")
  2499. (defgroup org-agenda nil
  2500. "Options concerning agenda views in Org mode."
  2501. :tag "Org Agenda"
  2502. :group 'org)
  2503. (defvar-local org-category nil
  2504. "Variable used by Org files to set a category for agenda display.
  2505. There are multiple ways to set the category. One way is to set
  2506. it in the document property drawer. For example:
  2507. :PROPERTIES:
  2508. :CATEGORY: ELisp
  2509. :END:
  2510. Other ways to define it is as an Emacs file variable, for example
  2511. # -*- mode: org; org-category: \"ELisp\"
  2512. or for the file to contain a special line:
  2513. #+CATEGORY: ELisp
  2514. If the file does not specify a category, then file's base name
  2515. is used instead.")
  2516. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2517. (defcustom org-agenda-files nil
  2518. "The files to be used for agenda display.
  2519. If an entry is a directory, all files in that directory that are matched
  2520. by `org-agenda-file-regexp' will be part of the file list.
  2521. If the value of the variable is not a list but a single file name, then
  2522. the list of agenda files is actually stored and maintained in that file,
  2523. one agenda file per line. In this file paths can be given relative to
  2524. `org-directory'. Tilde expansion and environment variable substitution
  2525. are also made.
  2526. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2527. and removed with `\\[org-remove-file]'."
  2528. :group 'org-agenda
  2529. :type '(choice
  2530. (repeat :tag "List of files and directories" file)
  2531. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2532. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2533. "Regular expression to match files for `org-agenda-files'.
  2534. If any element in the list in that variable contains a directory instead
  2535. of a normal file, all files in that directory that are matched by this
  2536. regular expression will be included."
  2537. :group 'org-agenda
  2538. :type 'regexp)
  2539. (defvaralias 'org-agenda-multi-occur-extra-files
  2540. 'org-agenda-text-search-extra-files)
  2541. (defcustom org-agenda-text-search-extra-files nil
  2542. "List of extra files to be searched by text search commands.
  2543. These files will be searched in addition to the agenda files by the
  2544. commands `org-search-view' (`\\[org-agenda] s') \
  2545. and `org-occur-in-agenda-files'.
  2546. Note that these files will only be searched for text search commands,
  2547. not for the other agenda views like todo lists, tag searches or the weekly
  2548. agenda. This variable is intended to list notes and possibly archive files
  2549. that should also be searched by these two commands.
  2550. In fact, if the first element in the list is the symbol `agenda-archives',
  2551. then all archive files of all agenda files will be added to the search
  2552. scope."
  2553. :group 'org-agenda
  2554. :type '(set :greedy t
  2555. (const :tag "Agenda Archives" agenda-archives)
  2556. (repeat :inline t (file))))
  2557. (defcustom org-agenda-skip-unavailable-files nil
  2558. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2559. A nil value means to remove them, after a query, from the list."
  2560. :group 'org-agenda
  2561. :type 'boolean)
  2562. (defgroup org-latex nil
  2563. "Options for embedding LaTeX code into Org mode."
  2564. :tag "Org LaTeX"
  2565. :group 'org)
  2566. (defcustom org-format-latex-options
  2567. '(:foreground default :background default :scale 1.0
  2568. :html-foreground "Black" :html-background "Transparent"
  2569. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2570. "Options for creating images from LaTeX fragments.
  2571. This is a property list with the following properties:
  2572. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2573. `default' means use the foreground of the default face.
  2574. `auto' means use the foreground from the text face.
  2575. :background the background color, or \"Transparent\".
  2576. `default' means use the background of the default face.
  2577. `auto' means use the background from the text face.
  2578. :scale a scaling factor for the size of the images, to get more pixels
  2579. :html-foreground, :html-background, :html-scale
  2580. the same numbers for HTML export.
  2581. :matchers a list indicating which matchers should be used to
  2582. find LaTeX fragments. Valid members of this list are:
  2583. \"begin\" find environments
  2584. \"$1\" find single characters surrounded by $.$
  2585. \"$\" find math expressions surrounded by $...$
  2586. \"$$\" find math expressions surrounded by $$....$$
  2587. \"\\(\" find math expressions surrounded by \\(...\\)
  2588. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2589. :group 'org-latex
  2590. :type 'plist)
  2591. (defcustom org-format-latex-signal-error t
  2592. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2593. When nil, just push out a message."
  2594. :group 'org-latex
  2595. :version "24.1"
  2596. :type 'boolean)
  2597. (defcustom org-latex-to-mathml-jar-file nil
  2598. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2599. Use this to specify additional executable file say a jar file.
  2600. When using MathToWeb as the converter, specify the full-path to
  2601. your mathtoweb.jar file."
  2602. :group 'org-latex
  2603. :version "24.1"
  2604. :type '(choice
  2605. (const :tag "None" nil)
  2606. (file :tag "JAR file" :must-match t)))
  2607. (defcustom org-latex-to-mathml-convert-command nil
  2608. "Command to convert LaTeX fragments to MathML.
  2609. Replace format-specifiers in the command as noted below and use
  2610. `shell-command' to convert LaTeX to MathML.
  2611. %j: Executable file in fully expanded form as specified by
  2612. `org-latex-to-mathml-jar-file'.
  2613. %I: Input LaTeX file in fully expanded form.
  2614. %i: The latex fragment to be converted.
  2615. %o: Output MathML file.
  2616. This command is used by `org-create-math-formula'.
  2617. When using MathToWeb as the converter, set this option to
  2618. \"java -jar %j -unicode -force -df %o %I\".
  2619. When using LaTeXML set this option to
  2620. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2621. :group 'org-latex
  2622. :version "24.1"
  2623. :type '(choice
  2624. (const :tag "None" nil)
  2625. (string :tag "\nShell command")))
  2626. (defcustom org-latex-to-html-convert-command nil
  2627. "Command to convert LaTeX fragments to HTML.
  2628. This command is very open-ended: the output of the command will
  2629. directly replace the LaTeX fragment in the resulting HTML.
  2630. Replace format-specifiers in the command as noted below and use
  2631. `shell-command' to convert LaTeX to HTML.
  2632. %i: The LaTeX fragment to be converted.
  2633. For example, this could be used with LaTeXML as
  2634. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2635. :group 'org-latex
  2636. :package-version '(Org . "9.4")
  2637. :type '(choice
  2638. (const :tag "None" nil)
  2639. (string :tag "Shell command")))
  2640. (defcustom org-preview-latex-default-process 'dvipng
  2641. "The default process to convert LaTeX fragments to image files.
  2642. All available processes and theirs documents can be found in
  2643. `org-preview-latex-process-alist', which see."
  2644. :group 'org-latex
  2645. :version "26.1"
  2646. :package-version '(Org . "9.0")
  2647. :type 'symbol)
  2648. (defcustom org-preview-latex-process-alist
  2649. '((dvipng
  2650. :programs ("latex" "dvipng")
  2651. :description "dvi > png"
  2652. :message "you need to install the programs: latex and dvipng."
  2653. :image-input-type "dvi"
  2654. :image-output-type "png"
  2655. :image-size-adjust (1.0 . 1.0)
  2656. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2657. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2658. :transparent-image-converter
  2659. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2660. (dvisvgm
  2661. :programs ("latex" "dvisvgm")
  2662. :description "dvi > svg"
  2663. :message "you need to install the programs: latex and dvisvgm."
  2664. :image-input-type "dvi"
  2665. :image-output-type "svg"
  2666. :image-size-adjust (1.7 . 1.5)
  2667. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2668. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2669. (imagemagick
  2670. :programs ("latex" "convert")
  2671. :description "pdf > png"
  2672. :message "you need to install the programs: latex and imagemagick."
  2673. :image-input-type "pdf"
  2674. :image-output-type "png"
  2675. :image-size-adjust (1.0 . 1.0)
  2676. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2677. :image-converter
  2678. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2679. "Definitions of external processes for LaTeX previewing.
  2680. Org mode can use some external commands to generate TeX snippet's images for
  2681. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2682. `org-create-formula-image' how to call them.
  2683. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2684. PROPERTIES accepts the following attributes:
  2685. :programs list of strings, required programs.
  2686. :description string, describe the process.
  2687. :message string, message it when required programs cannot be found.
  2688. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2689. :image-output-type string, output file type of image converter (e.g., \"png\").
  2690. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2691. image size showed in buffer and the cdr element is for
  2692. HTML file. This option is only useful for process
  2693. developers, users should use variable
  2694. `org-format-latex-options' instead.
  2695. :post-clean list of strings, files matched are to be cleaned up once
  2696. the image is generated. When nil, the files with \".dvi\",
  2697. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2698. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2699. be cleaned up.
  2700. :latex-header list of strings, the LaTeX header of the snippet file.
  2701. When nil, the fallback value is used instead, which is
  2702. controlled by `org-format-latex-header',
  2703. `org-latex-default-packages-alist' and
  2704. `org-latex-packages-alist', which see.
  2705. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2706. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2707. replaced with values defined below.
  2708. :image-converter list of image converter commands strings. Each of them is
  2709. given to the shell and supports any of the following
  2710. place-holders defined below.
  2711. If set, :transparent-image-converter is used instead of :image-converter to
  2712. convert an image when the background color is nil or \"Transparent\".
  2713. Place-holders used by `:image-converter' and `:latex-compiler':
  2714. %f input file name
  2715. %b base name of input file
  2716. %o base directory of input file
  2717. %O absolute output file name
  2718. Place-holders only used by `:image-converter':
  2719. %D dpi, which is used to adjust image size by some processing commands.
  2720. %S the image size scale ratio, which is used to adjust image size by some
  2721. processing commands."
  2722. :group 'org-latex
  2723. :version "26.1"
  2724. :package-version '(Org . "9.0")
  2725. :type '(alist :tag "LaTeX to image backends"
  2726. :value-type (plist)))
  2727. (defcustom org-preview-latex-image-directory "ltximg/"
  2728. "Path to store latex preview images.
  2729. A relative path here creates many directories relative to the
  2730. processed Org files paths. An absolute path puts all preview
  2731. images at the same place."
  2732. :group 'org-latex
  2733. :version "26.1"
  2734. :package-version '(Org . "9.0")
  2735. :type 'string)
  2736. (defun org-format-latex-mathml-available-p ()
  2737. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2738. (save-match-data
  2739. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2740. org-latex-to-mathml-convert-command)
  2741. (let ((executable (car (split-string
  2742. org-latex-to-mathml-convert-command))))
  2743. (when (executable-find executable)
  2744. (if (string-match
  2745. "%j" org-latex-to-mathml-convert-command)
  2746. (file-readable-p org-latex-to-mathml-jar-file)
  2747. t))))))
  2748. (defcustom org-format-latex-header "\\documentclass{article}
  2749. \\usepackage[usenames]{color}
  2750. \[PACKAGES]
  2751. \[DEFAULT-PACKAGES]
  2752. \\pagestyle{empty} % do not remove
  2753. % The settings below are copied from fullpage.sty
  2754. \\setlength{\\textwidth}{\\paperwidth}
  2755. \\addtolength{\\textwidth}{-3cm}
  2756. \\setlength{\\oddsidemargin}{1.5cm}
  2757. \\addtolength{\\oddsidemargin}{-2.54cm}
  2758. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2759. \\setlength{\\textheight}{\\paperheight}
  2760. \\addtolength{\\textheight}{-\\headheight}
  2761. \\addtolength{\\textheight}{-\\headsep}
  2762. \\addtolength{\\textheight}{-\\footskip}
  2763. \\addtolength{\\textheight}{-3cm}
  2764. \\setlength{\\topmargin}{1.5cm}
  2765. \\addtolength{\\topmargin}{-2.54cm}"
  2766. "The document header used for processing LaTeX fragments.
  2767. It is imperative that this header make sure that no page number
  2768. appears on the page. The package defined in the variables
  2769. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2770. will either replace the placeholder \"[PACKAGES]\" in this
  2771. header, or they will be appended."
  2772. :group 'org-latex
  2773. :type 'string)
  2774. (defun org-set-packages-alist (var val)
  2775. "Set the packages alist and make sure it has 3 elements per entry."
  2776. (set var (mapcar (lambda (x)
  2777. (if (and (consp x) (= (length x) 2))
  2778. (list (car x) (nth 1 x) t)
  2779. x))
  2780. val)))
  2781. (defun org-get-packages-alist (var)
  2782. "Get the packages alist and make sure it has 3 elements per entry."
  2783. (mapcar (lambda (x)
  2784. (if (and (consp x) (= (length x) 2))
  2785. (list (car x) (nth 1 x) t)
  2786. x))
  2787. (default-value var)))
  2788. (defcustom org-latex-default-packages-alist
  2789. '(("AUTO" "inputenc" t ("pdflatex"))
  2790. ("T1" "fontenc" t ("pdflatex"))
  2791. ("" "graphicx" t)
  2792. ("" "longtable" nil)
  2793. ("" "wrapfig" nil)
  2794. ("" "rotating" nil)
  2795. ("normalem" "ulem" t)
  2796. ("" "amsmath" t)
  2797. ("" "amssymb" t)
  2798. ("" "capt-of" nil)
  2799. ("" "hyperref" nil))
  2800. "Alist of default packages to be inserted in the header.
  2801. Change this only if one of the packages here causes an
  2802. incompatibility with another package you are using.
  2803. The packages in this list are needed by one part or another of
  2804. Org mode to function properly:
  2805. - inputenc, fontenc: for basic font and character selection
  2806. - graphicx: for including images
  2807. - longtable: For multipage tables
  2808. - wrapfig: for figure placement
  2809. - rotating: for sideways figures and tables
  2810. - ulem: for underline and strike-through
  2811. - amsmath: for subscript and superscript and math environments
  2812. - amssymb: for various symbols used for interpreting the entities
  2813. in `org-entities'. You can skip some of this package if you don't
  2814. use any of the symbols.
  2815. - capt-of: for captions outside of floats
  2816. - hyperref: for cross references
  2817. Therefore you should not modify this variable unless you know
  2818. what you are doing. The one reason to change it anyway is that
  2819. you might be loading some other package that conflicts with one
  2820. of the default packages. Each element is either a cell or
  2821. a string.
  2822. A cell is of the format
  2823. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2824. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2825. when compiling LaTeX snippets into images for inclusion into
  2826. non-LaTeX output.
  2827. COMPILERS is a list of compilers that should include the package,
  2828. see `org-latex-compiler'. If the document compiler is not in the
  2829. list, and the list is non-nil, the package will not be inserted
  2830. in the final document.
  2831. A string will be inserted as-is in the header of the document."
  2832. :group 'org-latex
  2833. :group 'org-export-latex
  2834. :set 'org-set-packages-alist
  2835. :get 'org-get-packages-alist
  2836. :version "26.1"
  2837. :package-version '(Org . "8.3")
  2838. :type '(repeat
  2839. (choice
  2840. (list :tag "options/package pair"
  2841. (string :tag "options")
  2842. (string :tag "package")
  2843. (boolean :tag "Snippet")
  2844. (choice
  2845. (const :tag "For all compilers" nil)
  2846. (repeat :tag "Allowed compiler" string)))
  2847. (string :tag "A line of LaTeX"))))
  2848. (defcustom org-latex-packages-alist nil
  2849. "Alist of packages to be inserted in every LaTeX header.
  2850. These will be inserted after `org-latex-default-packages-alist'.
  2851. Each element is either a cell or a string.
  2852. A cell is of the format:
  2853. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2854. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2855. needed when turning LaTeX snippets into images for inclusion into
  2856. non-LaTeX output.
  2857. COMPILERS is a list of compilers that should include the package,
  2858. see `org-latex-compiler'. If the document compiler is not in the
  2859. list, and the list is non-nil, the package will not be inserted
  2860. in the final document.
  2861. A string will be inserted as-is in the header of the document.
  2862. Make sure that you only list packages here which:
  2863. - you want in every file;
  2864. - do not conflict with the setup in `org-format-latex-header';
  2865. - do not conflict with the default packages in
  2866. `org-latex-default-packages-alist'."
  2867. :group 'org-latex
  2868. :group 'org-export-latex
  2869. :set 'org-set-packages-alist
  2870. :get 'org-get-packages-alist
  2871. :type '(repeat
  2872. (choice
  2873. (list :tag "options/package pair"
  2874. (string :tag "options")
  2875. (string :tag "package")
  2876. (boolean :tag "Snippet"))
  2877. (string :tag "A line of LaTeX"))))
  2878. (defgroup org-appearance nil
  2879. "Settings for Org mode appearance."
  2880. :tag "Org Appearance"
  2881. :group 'org)
  2882. (defcustom org-level-color-stars-only nil
  2883. "Non-nil means fontify only the stars in each headline.
  2884. When nil, the entire headline is fontified.
  2885. Changing it requires restart of `font-lock-mode' to become effective
  2886. also in regions already fontified."
  2887. :group 'org-appearance
  2888. :type 'boolean)
  2889. (defcustom org-hide-leading-stars nil
  2890. "Non-nil means hide the first N-1 stars in a headline.
  2891. This works by using the face `org-hide' for these stars. This
  2892. face is white for a light background, and black for a dark
  2893. background. You may have to customize the face `org-hide' to
  2894. make this work.
  2895. Changing it requires restart of `font-lock-mode' to become effective
  2896. also in regions already fontified.
  2897. You may also set this on a per-file basis by adding one of the following
  2898. lines to the buffer:
  2899. #+STARTUP: hidestars
  2900. #+STARTUP: showstars"
  2901. :group 'org-appearance
  2902. :type 'boolean)
  2903. (defcustom org-hidden-keywords nil
  2904. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2905. For example, a value \\='(title) for this list makes the document's title
  2906. appear in the buffer without the initial \"#+TITLE:\" part."
  2907. :group 'org-appearance
  2908. :package-version '(Org . "9.5")
  2909. :type '(set (const :tag "#+AUTHOR" author)
  2910. (const :tag "#+DATE" date)
  2911. (const :tag "#+EMAIL" email)
  2912. (const :tag "#+SUBTITLE" subtitle)
  2913. (const :tag "#+TITLE" title)))
  2914. (defcustom org-custom-properties nil
  2915. "List of properties (as strings) with a special meaning.
  2916. The default use of these custom properties is to let the user
  2917. hide them with `org-toggle-custom-properties-visibility'."
  2918. :group 'org-properties
  2919. :group 'org-appearance
  2920. :version "24.3"
  2921. :type '(repeat (string :tag "Property Name")))
  2922. (defcustom org-fontify-todo-headline nil
  2923. "Non-nil means change the face of a headline if it is marked as TODO.
  2924. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2925. When this is non-nil, the headline after the keyword is set to the
  2926. `org-headline-todo' as an additional indication."
  2927. :group 'org-appearance
  2928. :package-version '(Org . "9.4")
  2929. :type 'boolean
  2930. :safe #'booleanp)
  2931. (defcustom org-fontify-done-headline t
  2932. "Non-nil means change the face of a headline if it is marked DONE.
  2933. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2934. When this is non-nil, the headline after the keyword is set to the
  2935. `org-headline-done' as an additional indication."
  2936. :group 'org-appearance
  2937. :package-version '(Org . "9.4")
  2938. :type 'boolean)
  2939. (defcustom org-fontify-emphasized-text t
  2940. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  2941. Changing this variable requires a restart of Emacs to take effect."
  2942. :group 'org-appearance
  2943. :type 'boolean)
  2944. (defcustom org-fontify-whole-heading-line nil
  2945. "Non-nil means fontify the whole line for headings.
  2946. This is useful when setting a background color for the
  2947. org-level-* faces."
  2948. :group 'org-appearance
  2949. :type 'boolean)
  2950. (defcustom org-fontify-whole-block-delimiter-line t
  2951. "Non-nil means fontify the whole line for begin/end lines of blocks.
  2952. This is useful when setting a background color for the
  2953. org-block-begin-line and org-block-end-line faces."
  2954. :group 'org-appearance
  2955. :type 'boolean)
  2956. (defcustom org-highlight-latex-and-related nil
  2957. "Non-nil means highlight LaTeX related syntax in the buffer.
  2958. When non-nil, the value should be a list containing any of the
  2959. following symbols:
  2960. `native' Highlight LaTeX snippets and environments natively.
  2961. `latex' Highlight LaTeX snippets and environments.
  2962. `script' Highlight subscript and superscript.
  2963. `entities' Highlight entities."
  2964. :group 'org-appearance
  2965. :version "24.4"
  2966. :package-version '(Org . "8.0")
  2967. :type '(choice
  2968. (const :tag "No highlighting" nil)
  2969. (set :greedy t :tag "Highlight"
  2970. (const :tag "LaTeX snippets and environments (native)" native)
  2971. (const :tag "LaTeX snippets and environments" latex)
  2972. (const :tag "Subscript and superscript" script)
  2973. (const :tag "Entities" entities))))
  2974. (defcustom org-hide-emphasis-markers nil
  2975. "Non-nil mean font-lock should hide the emphasis marker characters."
  2976. :group 'org-appearance
  2977. :type 'boolean
  2978. :safe #'booleanp)
  2979. (defcustom org-hide-macro-markers nil
  2980. "Non-nil mean font-lock should hide the brackets marking macro calls."
  2981. :group 'org-appearance
  2982. :type 'boolean)
  2983. (defcustom org-pretty-entities nil
  2984. "Non-nil means show entities as UTF8 characters.
  2985. When nil, the \\name form remains in the buffer."
  2986. :group 'org-appearance
  2987. :version "24.1"
  2988. :type 'boolean)
  2989. (defcustom org-pretty-entities-include-sub-superscripts t
  2990. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  2991. :group 'org-appearance
  2992. :version "24.1"
  2993. :type 'boolean)
  2994. (defvar org-emph-re nil
  2995. "Regular expression for matching emphasis.
  2996. After a match, the match groups contain these elements:
  2997. 0 The match of the full regular expression, including the characters
  2998. before and after the proper match
  2999. 1 The character before the proper match, or empty at beginning of line
  3000. 2 The proper match, including the leading and trailing markers
  3001. 3 The leading marker like * or /, indicating the type of highlighting
  3002. 4 The text between the emphasis markers, not including the markers
  3003. 5 The character after the match, empty at the end of a line")
  3004. (defvar org-verbatim-re nil
  3005. "Regular expression for matching verbatim text.")
  3006. (defvar org-emphasis-regexp-components) ; defined just below
  3007. (defvar org-emphasis-alist) ; defined just below
  3008. (defun org-set-emph-re (var val)
  3009. "Set variable and compute the emphasis regular expression."
  3010. (set var val)
  3011. (when (and (boundp 'org-emphasis-alist)
  3012. (boundp 'org-emphasis-regexp-components)
  3013. org-emphasis-alist org-emphasis-regexp-components)
  3014. (pcase-let*
  3015. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3016. (body (if (<= nl 0) body
  3017. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3018. (template
  3019. (format (concat "\\([%s]\\|^\\)" ;before markers
  3020. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3021. "\\([%s]\\|$\\)") ;after markers
  3022. pre border border body border post)))
  3023. (setq org-emph-re (format template "*/_+"))
  3024. (setq org-verbatim-re (format template "=~")))))
  3025. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3026. ;; set this option proved cumbersome. See this message/thread:
  3027. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3028. (defvar org-emphasis-regexp-components
  3029. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3030. "Components used to build the regular expression for emphasis.
  3031. This is a list with five entries. Terminology: In an emphasis string
  3032. like \" *strong word* \", we call the initial space PREMATCH, the final
  3033. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3034. and \"trong wor\" is the body. The different components in this variable
  3035. specify what is allowed/forbidden in each part:
  3036. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3037. post Chars allowed as postmatch. End of line will be allowed too.
  3038. border The chars *forbidden* as border characters.
  3039. body-regexp A regexp like \".\" to match a body character. Don't use
  3040. non-shy groups here, and don't allow newline here.
  3041. newline The maximum number of newlines allowed in an emphasis exp.
  3042. You need to reload Org or to restart Emacs after setting this.")
  3043. (defcustom org-emphasis-alist
  3044. '(("*" bold)
  3045. ("/" italic)
  3046. ("_" underline)
  3047. ("=" org-verbatim verbatim)
  3048. ("~" org-code verbatim)
  3049. ("+" (:strike-through t)))
  3050. "Alist of characters and faces to emphasize text.
  3051. Text starting and ending with a special character will be emphasized,
  3052. for example *bold*, _underlined_ and /italic/. This variable sets the
  3053. marker characters and the face to be used by font-lock for highlighting
  3054. in Org buffers.
  3055. You need to reload Org or to restart Emacs after customizing this."
  3056. :group 'org-appearance
  3057. :set 'org-set-emph-re
  3058. :version "24.4"
  3059. :package-version '(Org . "8.0")
  3060. :type '(repeat
  3061. (list
  3062. (string :tag "Marker character")
  3063. (choice
  3064. (face :tag "Font-lock-face")
  3065. (plist :tag "Face property list"))
  3066. (option (const verbatim)))))
  3067. (defvar org-protecting-blocks '("src" "example" "export")
  3068. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3069. This is needed for font-lock setup.")
  3070. ;;; Functions and variables from their packages
  3071. ;; Declared here to avoid compiler warnings
  3072. (defvar mark-active)
  3073. ;; Various packages
  3074. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3075. (declare-function calendar-forward-day "cal-move" (arg))
  3076. (declare-function calendar-goto-date "cal-move" (date))
  3077. (declare-function calendar-goto-today "cal-move" ())
  3078. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3079. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3080. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3081. (declare-function cdlatex-tab "ext:cdlatex" ())
  3082. (declare-function dired-get-filename
  3083. "dired"
  3084. (&optional localp no-error-if-not-filep))
  3085. (declare-function iswitchb-read-buffer
  3086. "iswitchb"
  3087. (prompt &optional
  3088. default require-match _predicate start matches-set))
  3089. (declare-function org-agenda-change-all-lines
  3090. "org-agenda"
  3091. (newhead hdmarker &optional fixface just-this))
  3092. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3093. "org-agenda"
  3094. (&optional end))
  3095. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3096. (declare-function org-agenda-format-item
  3097. "org-agenda"
  3098. (extra txt &optional level category tags dotime
  3099. remove-re habitp))
  3100. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3101. (declare-function org-agenda-save-markers-for-cut-and-paste
  3102. "org-agenda"
  3103. (beg end))
  3104. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3105. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3106. (declare-function org-attach-expand "org-attach" (file))
  3107. (declare-function org-attach-reveal "org-attach" ())
  3108. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3109. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3110. (declare-function org-indent-mode "org-indent" (&optional arg))
  3111. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3112. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3113. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3114. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3115. (declare-function parse-time-string "parse-time" (string))
  3116. (defvar align-mode-rules-list)
  3117. (defvar calc-embedded-close-formula)
  3118. (defvar calc-embedded-open-formula)
  3119. (defvar calc-embedded-open-mode)
  3120. (defvar font-lock-unfontify-region-function)
  3121. (defvar iswitchb-temp-buflist)
  3122. (defvar org-agenda-tags-todo-honor-ignore-options)
  3123. (defvar remember-data-file)
  3124. (defvar texmathp-why)
  3125. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3126. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3127. (declare-function org-resolve-clocks "org-clock"
  3128. (&optional also-non-dangling-p prompt last-valid))
  3129. (defvar org-clock-start-time)
  3130. (defvar org-clock-marker (make-marker)
  3131. "Marker recording the last clock-in.")
  3132. (defvar org-clock-hd-marker (make-marker)
  3133. "Marker recording the last clock-in, but the headline position.")
  3134. (defvar org-clock-heading ""
  3135. "The heading of the current clock entry.")
  3136. (defun org-clocking-buffer ()
  3137. "Return the buffer where the clock is currently running.
  3138. Return nil if no clock is running."
  3139. (marker-buffer org-clock-marker))
  3140. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3141. (defun org-check-running-clock ()
  3142. "Check if the current buffer contains the running clock.
  3143. If yes, offer to stop it and to save the buffer with the changes."
  3144. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3145. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3146. (buffer-name))))
  3147. (org-clock-out)
  3148. (when (y-or-n-p "Save changed buffer?")
  3149. (save-buffer))))
  3150. (defun org-clocktable-try-shift (dir n)
  3151. "Check if this line starts a clock table, if yes, shift the time block."
  3152. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3153. (org-clocktable-shift dir n)))
  3154. ;;;###autoload
  3155. (defun org-clock-persistence-insinuate ()
  3156. "Set up hooks for clock persistence."
  3157. (require 'org-clock)
  3158. (add-hook 'org-mode-hook 'org-clock-load)
  3159. (add-hook 'kill-emacs-hook 'org-clock-save))
  3160. (defun org-clock-auto-clockout-insinuate ()
  3161. "Set up hook for auto clocking out when Emacs is idle.
  3162. See `org-clock-auto-clockout-timer'.
  3163. This function is meant to be added to the user configuration."
  3164. (require 'org-clock)
  3165. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3166. (defgroup org-archive nil
  3167. "Options concerning archiving in Org mode."
  3168. :tag "Org Archive"
  3169. :group 'org-structure)
  3170. (defcustom org-archive-location "%s_archive::"
  3171. "The location where subtrees should be archived.
  3172. The value of this variable is a string, consisting of two parts,
  3173. separated by a double-colon. The first part is a filename and
  3174. the second part is a headline.
  3175. When the filename is omitted, archiving happens in the same file.
  3176. %s in the filename will be replaced by the current file
  3177. name (without the directory part). Archiving to a different file
  3178. is useful to keep archived entries from contributing to the
  3179. Org Agenda.
  3180. The archived entries will be filed as subtrees of the specified
  3181. headline. When the headline is omitted, the subtrees are simply
  3182. filed away at the end of the file, as top-level entries. Also in
  3183. the heading you can use %s to represent the file name, this can be
  3184. useful when using the same archive for a number of different files.
  3185. Here are a few examples:
  3186. \"%s_archive::\"
  3187. If the current file is Projects.org, archive in file
  3188. Projects.org_archive, as top-level trees. This is the default.
  3189. \"::* Archived Tasks\"
  3190. Archive in the current file, under the top-level headline
  3191. \"* Archived Tasks\".
  3192. \"~/org/archive.org::\"
  3193. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3194. \"~/org/archive.org::* From %s\"
  3195. Archive in file ~/org/archive.org (absolute path), under headlines
  3196. \"From FILENAME\" where file name is the current file name.
  3197. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3198. The \"datetree/\" string is special, signifying to archive
  3199. items to the datetree. Items are placed in either the CLOSED
  3200. date of the item, or the current date if there is no CLOSED date.
  3201. The heading will be a subentry to the current date. There doesn't
  3202. need to be a heading, but there always needs to be a slash after
  3203. datetree. For example, to store archived items directly in the
  3204. datetree, use \"~/org/datetree.org::datetree/\".
  3205. \"basement::** Finished Tasks\"
  3206. Archive in file ./basement (relative path), as level 3 trees
  3207. below the level 2 heading \"** Finished Tasks\".
  3208. You may define it locally by setting an ARCHIVE property. If
  3209. such a property is found in the file or in an entry, and anywhere
  3210. up the hierarchy, it will be used.
  3211. You can also set it for the whole file using the keyword-syntax:
  3212. #+ARCHIVE: basement::** Finished Tasks"
  3213. :group 'org-archive
  3214. :type 'string)
  3215. (defcustom org-agenda-skip-archived-trees t
  3216. "Non-nil means the agenda will skip any items located in archived trees.
  3217. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3218. variable is no longer recommended, you should leave it at the value t.
  3219. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3220. :group 'org-archive
  3221. :group 'org-agenda-skip
  3222. :type 'boolean)
  3223. (defcustom org-columns-skip-archived-trees t
  3224. "Non-nil means ignore archived trees when creating column view."
  3225. :group 'org-archive
  3226. :group 'org-properties
  3227. :type 'boolean)
  3228. (defcustom org-sparse-tree-open-archived-trees nil
  3229. "Non-nil means sparse tree construction shows matches in archived trees.
  3230. When nil, matches in these trees are highlighted, but the trees are kept in
  3231. collapsed state."
  3232. :group 'org-archive
  3233. :group 'org-sparse-trees
  3234. :type 'boolean)
  3235. (defcustom org-sparse-tree-default-date-type nil
  3236. "The default date type when building a sparse tree.
  3237. When this is nil, a date is a scheduled or a deadline timestamp.
  3238. Otherwise, these types are allowed:
  3239. all: all timestamps
  3240. active: only active timestamps (<...>)
  3241. inactive: only inactive timestamps ([...])
  3242. scheduled: only scheduled timestamps
  3243. deadline: only deadline timestamps"
  3244. :type '(choice (const :tag "Scheduled or deadline" nil)
  3245. (const :tag "All timestamps" all)
  3246. (const :tag "Only active timestamps" active)
  3247. (const :tag "Only inactive timestamps" inactive)
  3248. (const :tag "Only scheduled timestamps" scheduled)
  3249. (const :tag "Only deadline timestamps" deadline)
  3250. (const :tag "Only closed timestamps" closed))
  3251. :version "26.1"
  3252. :package-version '(Org . "8.3")
  3253. :group 'org-sparse-trees)
  3254. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3255. ;; Declare Column View Code
  3256. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3257. (declare-function org-columns-compute "org-colview" (property))
  3258. ;; Declare ID code
  3259. (declare-function org-id-store-link "org-id")
  3260. (declare-function org-id-locations-load "org-id")
  3261. (declare-function org-id-locations-save "org-id")
  3262. (defvar org-id-track-globally)
  3263. ;;; Variables for pre-computed regular expressions, all buffer local
  3264. (defvar-local org-todo-regexp nil
  3265. "Matches any of the TODO state keywords.
  3266. Since TODO keywords are case-sensitive, `case-fold-search' is
  3267. expected to be bound to nil when matching against this regexp.")
  3268. (defvar-local org-not-done-regexp nil
  3269. "Matches any of the TODO state keywords except the last one.
  3270. Since TODO keywords are case-sensitive, `case-fold-search' is
  3271. expected to be bound to nil when matching against this regexp.")
  3272. (defvar-local org-not-done-heading-regexp nil
  3273. "Matches a TODO headline that is not done.
  3274. Since TODO keywords are case-sensitive, `case-fold-search' is
  3275. expected to be bound to nil when matching against this regexp.")
  3276. (defvar-local org-todo-line-regexp nil
  3277. "Matches a headline and puts TODO state into group 2 if present.
  3278. Since TODO keywords are case-sensitive, `case-fold-search' is
  3279. expected to be bound to nil when matching against this regexp.")
  3280. (defvar-local org-complex-heading-regexp nil
  3281. "Matches a headline and puts everything into groups:
  3282. group 1: Stars
  3283. group 2: The TODO keyword, maybe
  3284. group 3: Priority cookie
  3285. group 4: True headline
  3286. group 5: Tags
  3287. Since TODO keywords are case-sensitive, `case-fold-search' is
  3288. expected to be bound to nil when matching against this regexp.")
  3289. (defvar-local org-complex-heading-regexp-format nil
  3290. "Printf format to make regexp to match an exact headline.
  3291. This regexp will match the headline of any node which has the
  3292. exact headline text that is put into the format, but may have any
  3293. TODO state, priority, tags, statistics cookies (at the beginning
  3294. or end of the headline title), or COMMENT keyword.")
  3295. (defvar-local org-todo-line-tags-regexp nil
  3296. "Matches a headline and puts TODO state into group 2 if present.
  3297. Also put tags into group 4 if tags are present.")
  3298. (defconst org-plain-time-of-day-regexp
  3299. (concat
  3300. "\\(\\<[012]?[0-9]"
  3301. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3302. "\\(--?"
  3303. "\\(\\<[012]?[0-9]"
  3304. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3305. "\\)?")
  3306. "Regular expression to match a plain time or time range.
  3307. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3308. groups carry important information:
  3309. 0 the full match
  3310. 1 the first time, range or not
  3311. 8 the second time, if it is a range.")
  3312. (defconst org-plain-time-extension-regexp
  3313. (concat
  3314. "\\(\\<[012]?[0-9]"
  3315. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3316. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3317. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3318. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3319. groups carry important information:
  3320. 0 the full match
  3321. 7 hours of duration
  3322. 9 minutes of duration")
  3323. (defconst org-stamp-time-of-day-regexp
  3324. (concat
  3325. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3326. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3327. "\\(--?"
  3328. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3329. "Regular expression to match a timestamp time or time range.
  3330. After a match, the following groups carry important information:
  3331. 0 the full match
  3332. 1 date plus weekday, for back referencing to make sure
  3333. both times are on the same day
  3334. 2 the first time, range or not
  3335. 4 the second time, if it is a range.")
  3336. (defconst org-startup-options
  3337. '(("fold" org-startup-folded t)
  3338. ("overview" org-startup-folded t)
  3339. ("nofold" org-startup-folded nil)
  3340. ("showall" org-startup-folded nil)
  3341. ("show2levels" org-startup-folded show2levels)
  3342. ("show3levels" org-startup-folded show3levels)
  3343. ("show4levels" org-startup-folded show4levels)
  3344. ("show5levels" org-startup-folded show5levels)
  3345. ("showeverything" org-startup-folded showeverything)
  3346. ("content" org-startup-folded content)
  3347. ("indent" org-startup-indented t)
  3348. ("noindent" org-startup-indented nil)
  3349. ("num" org-startup-numerated t)
  3350. ("nonum" org-startup-numerated nil)
  3351. ("hidestars" org-hide-leading-stars t)
  3352. ("showstars" org-hide-leading-stars nil)
  3353. ("odd" org-odd-levels-only t)
  3354. ("oddeven" org-odd-levels-only nil)
  3355. ("align" org-startup-align-all-tables t)
  3356. ("noalign" org-startup-align-all-tables nil)
  3357. ("shrink" org-startup-shrink-all-tables t)
  3358. ("inlineimages" org-startup-with-inline-images t)
  3359. ("noinlineimages" org-startup-with-inline-images nil)
  3360. ("latexpreview" org-startup-with-latex-preview t)
  3361. ("nolatexpreview" org-startup-with-latex-preview nil)
  3362. ("customtime" org-display-custom-times t)
  3363. ("logdone" org-log-done time)
  3364. ("lognotedone" org-log-done note)
  3365. ("nologdone" org-log-done nil)
  3366. ("lognoteclock-out" org-log-note-clock-out t)
  3367. ("nolognoteclock-out" org-log-note-clock-out nil)
  3368. ("logrepeat" org-log-repeat state)
  3369. ("lognoterepeat" org-log-repeat note)
  3370. ("logdrawer" org-log-into-drawer t)
  3371. ("nologdrawer" org-log-into-drawer nil)
  3372. ("logstatesreversed" org-log-states-order-reversed t)
  3373. ("nologstatesreversed" org-log-states-order-reversed nil)
  3374. ("nologrepeat" org-log-repeat nil)
  3375. ("logreschedule" org-log-reschedule time)
  3376. ("lognotereschedule" org-log-reschedule note)
  3377. ("nologreschedule" org-log-reschedule nil)
  3378. ("logredeadline" org-log-redeadline time)
  3379. ("lognoteredeadline" org-log-redeadline note)
  3380. ("nologredeadline" org-log-redeadline nil)
  3381. ("logrefile" org-log-refile time)
  3382. ("lognoterefile" org-log-refile note)
  3383. ("nologrefile" org-log-refile nil)
  3384. ("fninline" org-footnote-define-inline t)
  3385. ("nofninline" org-footnote-define-inline nil)
  3386. ("fnlocal" org-footnote-section nil)
  3387. ("fnauto" org-footnote-auto-label t)
  3388. ("fnprompt" org-footnote-auto-label nil)
  3389. ("fnconfirm" org-footnote-auto-label confirm)
  3390. ("fnplain" org-footnote-auto-label plain)
  3391. ("fnadjust" org-footnote-auto-adjust t)
  3392. ("nofnadjust" org-footnote-auto-adjust nil)
  3393. ("constcgs" constants-unit-system cgs)
  3394. ("constSI" constants-unit-system SI)
  3395. ("noptag" org-tag-persistent-alist nil)
  3396. ("hideblocks" org-hide-block-startup t)
  3397. ("nohideblocks" org-hide-block-startup nil)
  3398. ("beamer" org-startup-with-beamer-mode t)
  3399. ("entitiespretty" org-pretty-entities t)
  3400. ("entitiesplain" org-pretty-entities nil))
  3401. "Variable associated with STARTUP options for Org.
  3402. Each element is a list of three items: the startup options (as written
  3403. in the #+STARTUP line), the corresponding variable, and the value to set
  3404. this variable to if the option is found. An optional fourth element PUSH
  3405. means to push this value onto the list in the variable.")
  3406. (defcustom org-group-tags t
  3407. "When non-nil (the default), use group tags.
  3408. This can be turned on/off through `org-toggle-tags-groups'."
  3409. :group 'org-tags
  3410. :group 'org-startup
  3411. :type 'boolean)
  3412. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3413. (defun org-toggle-tags-groups ()
  3414. "Toggle support for group tags.
  3415. Support for group tags is controlled by the option
  3416. `org-group-tags', which is non-nil by default."
  3417. (interactive)
  3418. (setq org-group-tags (not org-group-tags))
  3419. (cond ((and (derived-mode-p 'org-agenda-mode)
  3420. org-group-tags)
  3421. (org-agenda-redo))
  3422. ((derived-mode-p 'org-mode)
  3423. (let ((org-inhibit-startup t)) (org-mode))))
  3424. (message "Groups tags support has been turned %s"
  3425. (if org-group-tags "on" "off")))
  3426. (defun org--tag-add-to-alist (alist1 alist2)
  3427. "Merge tags from ALIST1 into ALIST2.
  3428. Duplicates tags outside a group are removed. Keywords and order
  3429. are preserved.
  3430. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3431. See `org-tag-alist' for their structure."
  3432. (cond
  3433. ((null alist2) alist1)
  3434. ((null alist1) alist2)
  3435. (t
  3436. (let ((to-add nil)
  3437. (group-flag nil))
  3438. (dolist (tag-pair alist1)
  3439. (pcase tag-pair
  3440. (`(,(or :startgrouptag :startgroup))
  3441. (setq group-flag t)
  3442. (push tag-pair to-add))
  3443. (`(,(or :endgrouptag :endgroup))
  3444. (setq group-flag nil)
  3445. (push tag-pair to-add))
  3446. (`(,(or :grouptags :newline))
  3447. (push tag-pair to-add))
  3448. (`(,tag . ,_)
  3449. ;; Remove duplicates from ALIST1, unless they are in
  3450. ;; a group. Indeed, it makes sense to have a tag appear in
  3451. ;; multiple groups.
  3452. (when (or group-flag (not (assoc tag alist2)))
  3453. (push tag-pair to-add)))
  3454. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3455. ;; Preserve order of ALIST1.
  3456. (append (nreverse to-add) alist2)))))
  3457. (defun org-priority-to-value (s)
  3458. "Convert priority string S to its numeric value."
  3459. (or (save-match-data
  3460. (and (string-match "\\([0-9]+\\)" s)
  3461. (string-to-number (match-string 1 s))))
  3462. (string-to-char s)))
  3463. (defun org-set-regexps-and-options (&optional tags-only)
  3464. "Precompute regular expressions used in the current buffer.
  3465. When optional argument TAGS-ONLY is non-nil, only compute tags
  3466. related expressions."
  3467. (when (derived-mode-p 'org-mode)
  3468. (let ((alist (org-collect-keywords
  3469. (append '("FILETAGS" "TAGS")
  3470. (and (not tags-only)
  3471. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3472. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3473. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3474. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3475. ;; Startup options. Get this early since it does change
  3476. ;; behavior for other options (e.g., tags).
  3477. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3478. (cdr (assoc "STARTUP" alist)))))
  3479. (dolist (option startup)
  3480. (pcase (assoc-string option org-startup-options t)
  3481. (`(,_ ,variable ,value t)
  3482. (unless (listp (symbol-value variable))
  3483. (set (make-local-variable variable) nil))
  3484. (add-to-list variable value))
  3485. (`(,_ ,variable ,value . ,_)
  3486. (set (make-local-variable variable) value))
  3487. (_ nil))))
  3488. (setq-local org-file-tags
  3489. (mapcar #'org-add-prop-inherited
  3490. (cl-mapcan (lambda (value)
  3491. (cl-mapcan
  3492. (lambda (k) (org-split-string k ":"))
  3493. (split-string value)))
  3494. (cdr (assoc "FILETAGS" alist)))))
  3495. (setq org-current-tag-alist
  3496. (org--tag-add-to-alist
  3497. org-tag-persistent-alist
  3498. (let ((tags (cdr (assoc "TAGS" alist))))
  3499. (if tags
  3500. (org-tag-string-to-alist
  3501. (mapconcat #'identity tags "\n"))
  3502. org-tag-alist))))
  3503. (setq org-tag-groups-alist
  3504. (org-tag-alist-to-groups org-current-tag-alist))
  3505. (unless tags-only
  3506. ;; Properties.
  3507. (let ((properties nil))
  3508. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3509. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3510. (setq properties (org--update-property-plist
  3511. (match-string-no-properties 1 value)
  3512. (match-string-no-properties 2 value)
  3513. properties))))
  3514. (setq-local org-keyword-properties properties))
  3515. ;; Archive location.
  3516. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3517. (when archive (setq-local org-archive-location archive)))
  3518. ;; Category.
  3519. (let ((category (cdr (assoc "CATEGORY" alist))))
  3520. (when category
  3521. (setq-local org-category (intern category))
  3522. (setq-local org-keyword-properties
  3523. (org--update-property-plist
  3524. "CATEGORY" category org-keyword-properties))))
  3525. ;; Columns.
  3526. (let ((column (cdr (assoc "COLUMNS" alist))))
  3527. (when column (setq-local org-columns-default-format column)))
  3528. ;; Constants.
  3529. (let ((store nil))
  3530. (dolist (pair (cl-mapcan #'split-string
  3531. (cdr (assoc "CONSTANTS" alist))))
  3532. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3533. (let* ((name (match-string 1 pair))
  3534. (value (match-string 2 pair))
  3535. (old (assoc name store)))
  3536. (if old (setcdr old value)
  3537. (push (cons name value) store)))))
  3538. (setq org-table-formula-constants-local store))
  3539. ;; Link abbreviations.
  3540. (let ((links
  3541. (delq nil
  3542. (mapcar
  3543. (lambda (value)
  3544. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3545. (cons (match-string-no-properties 1 value)
  3546. (match-string-no-properties 2 value))))
  3547. (cdr (assoc "LINK" alist))))))
  3548. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3549. ;; Priorities.
  3550. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3551. (pcase (and value (split-string value))
  3552. (`(,high ,low ,default . ,_)
  3553. (setq-local org-priority-highest (org-priority-to-value high))
  3554. (setq-local org-priority-lowest (org-priority-to-value low))
  3555. (setq-local org-priority-default (org-priority-to-value default)))))
  3556. ;; Scripts.
  3557. (let ((value (cdr (assoc "OPTIONS" alist))))
  3558. (dolist (option value)
  3559. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3560. (setq-local org-use-sub-superscripts
  3561. (read (match-string 1 option))))))
  3562. ;; TODO keywords.
  3563. (setq-local org-todo-kwd-alist nil)
  3564. (setq-local org-todo-key-alist nil)
  3565. (setq-local org-todo-key-trigger nil)
  3566. (setq-local org-todo-keywords-1 nil)
  3567. (setq-local org-done-keywords nil)
  3568. (setq-local org-todo-heads nil)
  3569. (setq-local org-todo-sets nil)
  3570. (setq-local org-todo-log-states nil)
  3571. (let ((todo-sequences
  3572. (or (append (mapcar (lambda (value)
  3573. (cons 'type (split-string value)))
  3574. (cdr (assoc "TYP_TODO" alist)))
  3575. (mapcar (lambda (value)
  3576. (cons 'sequence (split-string value)))
  3577. (append (cdr (assoc "TODO" alist))
  3578. (cdr (assoc "SEQ_TODO" alist)))))
  3579. (let ((d (default-value 'org-todo-keywords)))
  3580. (if (not (stringp (car d))) d
  3581. ;; XXX: Backward compatibility code.
  3582. (list (cons org-todo-interpretation d)))))))
  3583. (dolist (sequence todo-sequences)
  3584. (let* ((sequence (or (run-hook-with-args-until-success
  3585. 'org-todo-setup-filter-hook sequence)
  3586. sequence))
  3587. (sequence-type (car sequence))
  3588. (keywords (cdr sequence))
  3589. (sep (member "|" keywords))
  3590. names alist)
  3591. (dolist (k (remove "|" keywords))
  3592. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3593. k)
  3594. (error "Invalid TODO keyword %s" k))
  3595. (let ((name (match-string 1 k))
  3596. (key (match-string 2 k))
  3597. (log (org-extract-log-state-settings k)))
  3598. (push name names)
  3599. (push (cons name (and key (string-to-char key))) alist)
  3600. (when log (push log org-todo-log-states))))
  3601. (let* ((names (nreverse names))
  3602. (done (if sep (org-remove-keyword-keys (cdr sep))
  3603. (last names)))
  3604. (head (car names))
  3605. (tail (list sequence-type head (car done) (org-last done))))
  3606. (add-to-list 'org-todo-heads head 'append)
  3607. (push names org-todo-sets)
  3608. (setq org-done-keywords (append org-done-keywords done nil))
  3609. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3610. (setq org-todo-key-alist
  3611. (append org-todo-key-alist
  3612. (and alist
  3613. (append '((:startgroup))
  3614. (nreverse alist)
  3615. '((:endgroup))))))
  3616. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3617. (setq org-todo-sets (nreverse org-todo-sets)
  3618. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3619. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3620. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3621. ;; Compute the regular expressions and other local variables.
  3622. ;; Using `org-outline-regexp-bol' would complicate them much,
  3623. ;; because of the fixed white space at the end of that string.
  3624. (unless org-done-keywords
  3625. (setq org-done-keywords
  3626. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3627. (setq org-not-done-keywords
  3628. (org-delete-all org-done-keywords
  3629. (copy-sequence org-todo-keywords-1))
  3630. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3631. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3632. org-not-done-heading-regexp
  3633. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3634. org-todo-line-regexp
  3635. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3636. org-complex-heading-regexp
  3637. (concat "^\\(\\*+\\)"
  3638. "\\(?: +" org-todo-regexp "\\)?"
  3639. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3640. "\\(?: +\\(.*?\\)\\)??"
  3641. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3642. "[ \t]*$")
  3643. org-complex-heading-regexp-format
  3644. (concat "^\\(\\*+\\)"
  3645. "\\(?: +" org-todo-regexp "\\)?"
  3646. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3647. "\\(?: +"
  3648. ;; Headline might be commented
  3649. "\\(?:" org-comment-string " +\\)?"
  3650. ;; Stats cookies can be stuck to body.
  3651. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3652. "\\(%s\\)"
  3653. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3654. "\\)"
  3655. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3656. "[ \t]*$")
  3657. org-todo-line-tags-regexp
  3658. (concat "^\\(\\*+\\)"
  3659. "\\(?: +" org-todo-regexp "\\)?"
  3660. "\\(?: +\\(.*?\\)\\)??"
  3661. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3662. "[ \t]*$"))
  3663. (org-compute-latex-and-related-regexp)))))
  3664. (defun org-collect-keywords (keywords &optional unique directory)
  3665. "Return values for KEYWORDS in current buffer, as an alist.
  3666. KEYWORDS is a list of strings. Return value is a list of
  3667. elements with the pattern:
  3668. (NAME . LIST-OF-VALUES)
  3669. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3670. is a list of non-empty values, as strings, in order of appearance
  3671. in the buffer.
  3672. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3673. value, empty or not, appearing in the buffer, as a string.
  3674. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3675. (VALUE . DIRECTORY)
  3676. where VALUE is the regular value, and DIRECTORY is the variable
  3677. `default-directory' for the buffer containing the keyword. This
  3678. is important for values containing relative file names, since the
  3679. function follows SETUPFILE keywords, and may change its working
  3680. directory."
  3681. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3682. (unique (mapcar #'upcase unique))
  3683. (alist (org--collect-keywords-1
  3684. keywords unique directory
  3685. (and buffer-file-name (list buffer-file-name))
  3686. nil)))
  3687. ;; Re-order results.
  3688. (dolist (entry alist)
  3689. (pcase entry
  3690. (`(,_ . ,(and value (pred consp)))
  3691. (setcdr entry (nreverse value)))))
  3692. (nreverse alist)))
  3693. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3694. (org-with-point-at 1
  3695. (let ((case-fold-search t)
  3696. (regexp (org-make-options-regexp keywords)))
  3697. (while (and keywords (re-search-forward regexp nil t))
  3698. (let ((element (org-element-at-point)))
  3699. (when (eq 'keyword (org-element-type element))
  3700. (let ((value (org-element-property :value element)))
  3701. (pcase (org-element-property :key element)
  3702. ("SETUPFILE"
  3703. (when (and (org-string-nw-p value)
  3704. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3705. (let* ((uri (org-strip-quotes value))
  3706. (uri-is-url (org-url-p uri))
  3707. (uri (if uri-is-url
  3708. uri
  3709. (expand-file-name uri))))
  3710. (unless (member uri files)
  3711. (with-temp-buffer
  3712. (unless uri-is-url
  3713. (setq default-directory (file-name-directory uri)))
  3714. (let ((contents (org-file-contents uri :noerror)))
  3715. (when contents
  3716. (insert contents)
  3717. ;; Fake Org mode: `org-element-at-point'
  3718. ;; doesn't need full set-up.
  3719. (let ((major-mode 'org-mode))
  3720. (setq alist
  3721. (org--collect-keywords-1
  3722. keywords unique directory
  3723. (cons uri files)
  3724. alist))))))))))
  3725. (keyword
  3726. (let ((entry (assoc keyword alist))
  3727. (final
  3728. (cond ((not (member keyword directory)) value)
  3729. (buffer-file-name
  3730. (cons value
  3731. (file-name-directory buffer-file-name)))
  3732. (t (cons value default-directory)))))
  3733. (cond ((member keyword unique)
  3734. (push (cons keyword final) alist)
  3735. (setq keywords (remove keyword keywords))
  3736. (setq regexp (org-make-options-regexp keywords)))
  3737. ((null entry) (push (list keyword final) alist))
  3738. (t (push final (cdr entry)))))))))))
  3739. alist)))
  3740. (defun org-tag-string-to-alist (s)
  3741. "Return tag alist associated to string S.
  3742. S is a value for TAGS keyword or produced with
  3743. `org-tag-alist-to-string'. Return value is an alist suitable for
  3744. `org-tag-alist' or `org-tag-persistent-alist'."
  3745. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3746. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3747. "\\(?:(\\(.\\))\\)?\\'"))
  3748. alist group-flag)
  3749. (dolist (tokens lines (cdr (nreverse alist)))
  3750. (push '(:newline) alist)
  3751. (while tokens
  3752. (let ((token (pop tokens)))
  3753. (pcase token
  3754. ("{"
  3755. (push '(:startgroup) alist)
  3756. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3757. ("}"
  3758. (push '(:endgroup) alist)
  3759. (setq group-flag nil))
  3760. ("["
  3761. (push '(:startgrouptag) alist)
  3762. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3763. ("]"
  3764. (push '(:endgrouptag) alist)
  3765. (setq group-flag nil))
  3766. (":"
  3767. (push '(:grouptags) alist))
  3768. ((guard (string-match tag-re token))
  3769. (let ((tag (match-string 1 token))
  3770. (key (and (match-beginning 2)
  3771. (string-to-char (match-string 2 token)))))
  3772. ;; Push all tags in groups, no matter if they already
  3773. ;; appear somewhere else in the list.
  3774. (when (or group-flag (not (assoc tag alist)))
  3775. (push (cons tag key) alist))))))))))
  3776. (defun org-tag-alist-to-string (alist &optional skip-key)
  3777. "Return tag string associated to ALIST.
  3778. ALIST is an alist, as defined in `org-tag-alist' or
  3779. `org-tag-persistent-alist', or produced with
  3780. `org-tag-string-to-alist'.
  3781. Return value is a string suitable as a value for \"TAGS\"
  3782. keyword.
  3783. When optional argument SKIP-KEY is non-nil, skip selection keys
  3784. next to tags."
  3785. (mapconcat (lambda (token)
  3786. (pcase token
  3787. (`(:startgroup) "{")
  3788. (`(:endgroup) "}")
  3789. (`(:startgrouptag) "[")
  3790. (`(:endgrouptag) "]")
  3791. (`(:grouptags) ":")
  3792. (`(:newline) "\\n")
  3793. ((and
  3794. (guard (not skip-key))
  3795. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3796. (format "%s(%c)" tag key))
  3797. (`(,(and tag (pred stringp)) . ,_) tag)
  3798. (_ (user-error "Invalid tag token: %S" token))))
  3799. alist
  3800. " "))
  3801. (defun org-tag-alist-to-groups (alist)
  3802. "Return group alist from tag ALIST.
  3803. ALIST is an alist, as defined in `org-tag-alist' or
  3804. `org-tag-persistent-alist', or produced with
  3805. `org-tag-string-to-alist'. Return value is an alist following
  3806. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3807. a string, summarizing TAGS, as a list of strings."
  3808. (let (groups group-status current-group)
  3809. (dolist (token alist (nreverse groups))
  3810. (pcase token
  3811. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3812. (`(,(or :endgroup :endgrouptag))
  3813. (when (eq group-status 'append)
  3814. (push (nreverse current-group) groups))
  3815. (setq group-status nil current-group nil))
  3816. (`(:grouptags) (setq group-status 'append))
  3817. ((and `(,tag . ,_) (guard group-status))
  3818. (if (eq group-status 'append) (push tag current-group)
  3819. (setq current-group (list tag))))
  3820. (_ nil)))))
  3821. (defvar org--file-cache (make-hash-table :test #'equal)
  3822. "Hash table to store contents of files referenced via a URL.
  3823. This is the cache of file URLs read using `org-file-contents'.")
  3824. (defun org-reset-file-cache ()
  3825. "Reset the cache of files downloaded by `org-file-contents'."
  3826. (clrhash org--file-cache))
  3827. (defun org-file-contents (file &optional noerror nocache)
  3828. "Return the contents of FILE, as a string.
  3829. FILE can be a file name or URL.
  3830. If FILE is a URL, download the contents. If the URL contents are
  3831. already cached in the `org--file-cache' hash table, the download step
  3832. is skipped.
  3833. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3834. from file or URL, and return nil.
  3835. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3836. is available. This option applies only if FILE is a URL."
  3837. (let* ((is-url (org-url-p file))
  3838. (cache (and is-url
  3839. (not nocache)
  3840. (gethash file org--file-cache))))
  3841. (cond
  3842. (cache)
  3843. (is-url
  3844. (with-current-buffer (url-retrieve-synchronously file)
  3845. (goto-char (point-min))
  3846. ;; Move point to after the url-retrieve header.
  3847. (search-forward "\n\n" nil :move)
  3848. ;; Search for the success code only in the url-retrieve header.
  3849. (if (save-excursion
  3850. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3851. ;; Update the cache `org--file-cache' and return contents.
  3852. (puthash file
  3853. (buffer-substring-no-properties (point) (point-max))
  3854. org--file-cache)
  3855. (funcall (if noerror #'message #'user-error)
  3856. "Unable to fetch file from %S"
  3857. file)
  3858. nil)))
  3859. (t
  3860. (with-temp-buffer
  3861. (condition-case nil
  3862. (progn
  3863. (insert-file-contents file)
  3864. (buffer-string))
  3865. (file-error
  3866. (funcall (if noerror #'message #'user-error)
  3867. "Unable to read file %S"
  3868. file)
  3869. nil)))))))
  3870. (defun org-extract-log-state-settings (x)
  3871. "Extract the log state setting from a TODO keyword string.
  3872. This will extract info from a string like \"WAIT(w@/!)\"."
  3873. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  3874. (let ((kw (match-string 1 x))
  3875. (log1 (and (match-end 3) (match-string 3 x)))
  3876. (log2 (and (match-end 4) (match-string 4 x))))
  3877. (and (or log1 log2)
  3878. (list kw
  3879. (and log1 (if (equal log1 "!") 'time 'note))
  3880. (and log2 (if (equal log2 "!") 'time 'note)))))))
  3881. (defun org-remove-keyword-keys (list)
  3882. "Remove a pair of parenthesis at the end of each string in LIST."
  3883. (mapcar (lambda (x)
  3884. (if (string-match "(.*)$" x)
  3885. (substring x 0 (match-beginning 0))
  3886. x))
  3887. list))
  3888. (defun org-assign-fast-keys (alist)
  3889. "Assign fast keys to a keyword-key alist.
  3890. Respect keys that are already there."
  3891. (let (new e (alt ?0))
  3892. (while (setq e (pop alist))
  3893. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  3894. (cdr e)) ;; Key already assigned.
  3895. (push e new)
  3896. (let ((clist (string-to-list (downcase (car e))))
  3897. (used (append new alist)))
  3898. (when (= (car clist) ?@)
  3899. (pop clist))
  3900. (while (and clist (rassoc (car clist) used))
  3901. (pop clist))
  3902. (unless clist
  3903. (while (rassoc alt used)
  3904. (cl-incf alt)))
  3905. (push (cons (car e) (or (car clist) alt)) new))))
  3906. (nreverse new)))
  3907. ;;; Some variables used in various places
  3908. (defvar org-window-configuration nil
  3909. "Used in various places to store a window configuration.")
  3910. (defvar org-selected-window nil
  3911. "Used in various places to store a window configuration.")
  3912. (defvar org-finish-function nil
  3913. "Function to be called when `C-c C-c' is used.
  3914. This is for getting out of special buffers like capture.")
  3915. (defvar org-last-state)
  3916. ;; Defined somewhere in this file, but used before definition.
  3917. (defvar org-entities) ;; defined in org-entities.el
  3918. (defvar org-struct-menu)
  3919. (defvar org-org-menu)
  3920. (defvar org-tbl-menu)
  3921. ;;;; Define the Org mode
  3922. (defun org-before-change-function (_beg _end)
  3923. "Every change indicates that a table might need an update."
  3924. (setq org-table-may-need-update t))
  3925. (defvar org-mode-map)
  3926. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  3927. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  3928. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  3929. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  3930. (defvar bidi-paragraph-direction)
  3931. (defvar buffer-face-mode-face)
  3932. (require 'outline)
  3933. ;; Other stuff we need.
  3934. (require 'time-date)
  3935. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  3936. (require 'easymenu))
  3937. (require 'org-entities)
  3938. (require 'org-faces)
  3939. (require 'org-list)
  3940. (require 'org-pcomplete)
  3941. (require 'org-src)
  3942. (require 'org-footnote)
  3943. (require 'org-macro)
  3944. ;; babel
  3945. (require 'ob)
  3946. (defvar org-element-cache-persistent); Defined in org-element.el
  3947. (defvar org-element-use-cache); Defined in org-element.el
  3948. (defvar org-mode-loading nil
  3949. "Non-nil during Org mode initialisation.")
  3950. ;;;###autoload
  3951. (define-derived-mode org-mode outline-mode "Org"
  3952. "Outline-based notes management and organizer, alias
  3953. \"Carsten's outline-mode for keeping track of everything.\"
  3954. Org mode develops organizational tasks around a NOTES file which
  3955. contains information about projects as plain text. Org mode is
  3956. implemented on top of Outline mode, which is ideal to keep the content
  3957. of large files well structured. It supports ToDo items, deadlines and
  3958. time stamps, which magically appear in the diary listing of the Emacs
  3959. calendar. Tables are easily created with a built-in table editor.
  3960. Plain text URL-like links connect to websites, emails (VM), Usenet
  3961. messages (Gnus), BBDB entries, and any files related to the project.
  3962. For printing and sharing of notes, an Org file (or a part of it)
  3963. can be exported as a structured ASCII or HTML file.
  3964. The following commands are available:
  3965. \\{org-mode-map}"
  3966. (setq-local org-mode-loading t)
  3967. (org-load-modules-maybe)
  3968. (org-install-agenda-files-menu)
  3969. (when (and org-link-descriptive
  3970. (eq org-fold-core-style 'overlays))
  3971. (add-to-invisibility-spec '(org-link)))
  3972. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  3973. "..."))
  3974. (make-local-variable 'org-link-descriptive)
  3975. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  3976. (if org-link-descriptive
  3977. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  3978. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  3979. (setq-local outline-regexp org-outline-regexp)
  3980. (setq-local outline-level 'org-outline-level)
  3981. (setq bidi-paragraph-direction 'left-to-right)
  3982. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  3983. (unless org-display-table
  3984. (setq org-display-table (make-display-table)))
  3985. (set-display-table-slot
  3986. org-display-table 4
  3987. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  3988. org-ellipsis)))
  3989. (setq buffer-display-table org-display-table))
  3990. (org-set-regexps-and-options)
  3991. (org-set-font-lock-defaults)
  3992. (when (and org-tag-faces (not org-tags-special-faces-re))
  3993. ;; tag faces set outside customize.... force initialization.
  3994. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  3995. ;; Calc embedded
  3996. (setq-local calc-embedded-open-mode "# ")
  3997. ;; Modify a few syntax entries
  3998. (modify-syntax-entry ?\" "\"")
  3999. (modify-syntax-entry ?\\ "_")
  4000. (modify-syntax-entry ?~ "_")
  4001. (modify-syntax-entry ?< "(>")
  4002. (modify-syntax-entry ?> ")<")
  4003. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4004. ;; Activate before-change-function
  4005. (setq-local org-table-may-need-update t)
  4006. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4007. ;; Check for running clock before killing a buffer
  4008. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4009. ;; Initialize cache.
  4010. (org-element-cache-reset)
  4011. (when (and org-element-cache-persistent
  4012. org-element-use-cache)
  4013. (org-persist-load 'org-element--cache (current-buffer) t))
  4014. ;; Initialize macros templates.
  4015. (org-macro-initialize-templates)
  4016. ;; Initialize radio targets.
  4017. (org-update-radio-target-regexp)
  4018. ;; Indentation.
  4019. (setq-local indent-line-function 'org-indent-line)
  4020. (setq-local indent-region-function 'org-indent-region)
  4021. ;; Filling and auto-filling.
  4022. (org-setup-filling)
  4023. ;; Comments.
  4024. (org-setup-comments-handling)
  4025. ;; Beginning/end of defun
  4026. (setq-local beginning-of-defun-function 'org-backward-element)
  4027. (setq-local end-of-defun-function
  4028. (lambda ()
  4029. (if (not (org-at-heading-p))
  4030. (org-forward-element)
  4031. (org-forward-element)
  4032. (forward-char -1))))
  4033. ;; Next error for sparse trees
  4034. (setq-local next-error-function 'org-occur-next-match)
  4035. ;; Make commit log messages from Org documents easier.
  4036. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4037. ;; Make sure dependence stuff works reliably, even for users who set it
  4038. ;; too late :-(
  4039. (if org-enforce-todo-dependencies
  4040. (add-hook 'org-blocker-hook
  4041. 'org-block-todo-from-children-or-siblings-or-parent)
  4042. (remove-hook 'org-blocker-hook
  4043. 'org-block-todo-from-children-or-siblings-or-parent))
  4044. (if org-enforce-todo-checkbox-dependencies
  4045. (add-hook 'org-blocker-hook
  4046. 'org-block-todo-from-checkboxes)
  4047. (remove-hook 'org-blocker-hook
  4048. 'org-block-todo-from-checkboxes))
  4049. ;; Align options lines
  4050. (setq-local
  4051. align-mode-rules-list
  4052. '((org-in-buffer-settings
  4053. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4054. (modes . '(org-mode)))))
  4055. ;; Setup the pcomplete hooks
  4056. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4057. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4058. (setq-local pcomplete-default-completion-function #'ignore)
  4059. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4060. (setq-local pcomplete-termination-string "")
  4061. (add-hook 'completion-at-point-functions
  4062. #'pcomplete-completions-at-point nil t)
  4063. (setq-local buffer-face-mode-face 'org-default)
  4064. ;; If empty file that did not turn on Org mode automatically, make
  4065. ;; it to.
  4066. (when (and org-insert-mode-line-in-empty-file
  4067. (called-interactively-p 'any)
  4068. (= (point-min) (point-max)))
  4069. (insert "# -*- mode: org -*-\n\n"))
  4070. (unless org-inhibit-startup
  4071. (org-unmodified
  4072. (when org-startup-with-beamer-mode (org-beamer-mode))
  4073. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4074. (org-table-map-tables
  4075. (cond ((and org-startup-align-all-tables
  4076. org-startup-shrink-all-tables)
  4077. (lambda () (org-table-align) (org-table-shrink)))
  4078. (org-startup-align-all-tables #'org-table-align)
  4079. (t #'org-table-shrink))
  4080. t))
  4081. (when org-startup-with-inline-images (org-display-inline-images))
  4082. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4083. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4084. (when org-startup-truncated (setq truncate-lines t))
  4085. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4086. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4087. ;; Add a custom keymap for `visual-line-mode' so that activating
  4088. ;; this minor mode does not override Org's keybindings.
  4089. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4090. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4091. (newmap (make-sparse-keymap)))
  4092. (set-keymap-parent newmap oldmap)
  4093. (define-key newmap [remap move-beginning-of-line] nil)
  4094. (define-key newmap [remap move-end-of-line] nil)
  4095. (define-key newmap [remap kill-line] nil)
  4096. (make-local-variable 'minor-mode-overriding-map-alist)
  4097. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4098. ;; Activate `org-table-header-line-mode'
  4099. (when org-table-header-line-p
  4100. (org-table-header-line-mode 1))
  4101. ;; Try to set `org-hide' face correctly.
  4102. (let ((foreground (org-find-invisible-foreground)))
  4103. (when foreground
  4104. (set-face-foreground 'org-hide foreground)))
  4105. ;; Set face extension as requested.
  4106. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4107. org-fontify-whole-block-delimiter-line)
  4108. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4109. (setq-local org-mode-loading nil))
  4110. ;; Update `customize-package-emacs-version-alist'
  4111. (add-to-list 'customize-package-emacs-version-alist
  4112. '(Org ("8.0" . "24.4")
  4113. ("8.1" . "24.4")
  4114. ("8.2" . "24.4")
  4115. ("8.2.7" . "24.4")
  4116. ("8.3" . "26.1")
  4117. ("9.0" . "26.1")
  4118. ("9.1" . "26.1")
  4119. ("9.2" . "27.1")
  4120. ("9.3" . "27.1")
  4121. ("9.4" . "27.2")
  4122. ("9.5" . "28.1")
  4123. ("9.6" . "29.1")))
  4124. (defvar org-mode-transpose-word-syntax-table
  4125. (let ((st (make-syntax-table text-mode-syntax-table)))
  4126. (dolist (c org-emphasis-alist st)
  4127. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4128. (when (fboundp 'abbrev-table-put)
  4129. (abbrev-table-put org-mode-abbrev-table
  4130. :parents (list text-mode-abbrev-table)))
  4131. (defun org-find-invisible-foreground ()
  4132. (let ((candidates (remove
  4133. "unspecified-bg"
  4134. (nconc
  4135. (list (face-background 'default)
  4136. (face-background 'org-default))
  4137. (mapcar
  4138. (lambda (alist)
  4139. (when (boundp alist)
  4140. (cdr (assq 'background-color (symbol-value alist)))))
  4141. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4142. (list (face-foreground 'org-hide))))))
  4143. (car (remove nil candidates))))
  4144. (defun org-current-time (&optional rounding-minutes past)
  4145. "Current time, possibly rounded to ROUNDING-MINUTES.
  4146. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4147. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4148. the rounding returns a past time."
  4149. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4150. (car org-time-stamp-rounding-minutes)))
  4151. (now (current-time)))
  4152. (if (< r 1)
  4153. now
  4154. (let* ((time (decode-time now))
  4155. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4156. (nthcdr 2 time))))
  4157. (if (or (not past) (time-less-p res now))
  4158. res
  4159. (time-subtract res (* r 60)))))))
  4160. (defun org-today ()
  4161. "Return today date, considering `org-extend-today-until'."
  4162. (time-to-days
  4163. (time-since (* 3600 org-extend-today-until))))
  4164. ;;;; Font-Lock stuff, including the activators
  4165. (defconst org-match-sexp-depth 3
  4166. "Number of stacked braces for sub/superscript matching.")
  4167. (defun org-create-multibrace-regexp (left right n)
  4168. "Create a regular expression which will match a balanced sexp.
  4169. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4170. as single character strings.
  4171. The regexp returned will match the entire expression including the
  4172. delimiters. It will also define a single group which contains the
  4173. match except for the outermost delimiters. The maximum depth of
  4174. stacked delimiters is N. Escaping delimiters is not possible."
  4175. (let* ((nothing (concat "[^" left right "]*?"))
  4176. (or "\\|")
  4177. (re nothing)
  4178. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4179. (while (> n 1)
  4180. (setq n (1- n)
  4181. re (concat re or next)
  4182. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4183. (concat left "\\(" re "\\)" right)))
  4184. (defconst org-match-substring-regexp
  4185. (concat
  4186. "\\(\\S-\\)\\([_^]\\)\\("
  4187. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4188. "\\|"
  4189. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4190. "\\|"
  4191. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4192. "The regular expression matching a sub- or superscript.")
  4193. (defconst org-match-substring-with-braces-regexp
  4194. (concat
  4195. "\\(\\S-\\)\\([_^]\\)"
  4196. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4197. "The regular expression matching a sub- or superscript, forcing braces.")
  4198. (defvar org-emph-face nil)
  4199. (defun org-do-emphasis-faces (limit)
  4200. "Run through the buffer and emphasize strings."
  4201. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4202. (car org-emphasis-regexp-components))))
  4203. (catch :exit
  4204. (while (re-search-forward quick-re limit t)
  4205. (let* ((marker (match-string 2))
  4206. (verbatim? (member marker '("~" "="))))
  4207. (when (save-excursion
  4208. (goto-char (match-beginning 0))
  4209. (and
  4210. ;; Do not match table hlines.
  4211. (not (and (equal marker "+")
  4212. (org-match-line
  4213. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4214. ;; Do not match headline stars. Do not consider
  4215. ;; stars of a headline as closing marker for bold
  4216. ;; markup either.
  4217. (not (and (equal marker "*")
  4218. (save-excursion
  4219. (forward-char)
  4220. (skip-chars-backward "*")
  4221. (looking-at-p org-outline-regexp-bol))))
  4222. ;; Match full emphasis markup regexp.
  4223. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4224. ;; Do not span over paragraph boundaries.
  4225. (not (string-match-p org-element-paragraph-separate
  4226. (match-string 2)))
  4227. ;; Do not span over cells in table rows.
  4228. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4229. (string-match-p "|" (match-string 4))))))
  4230. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4231. (m (if org-hide-emphasis-markers 4 2)))
  4232. (font-lock-prepend-text-property
  4233. (match-beginning m) (match-end m) 'face face)
  4234. (when verbatim?
  4235. (org-remove-flyspell-overlays-in
  4236. (match-beginning 0) (match-end 0))
  4237. (remove-text-properties (match-beginning 2) (match-end 2)
  4238. '(display t invisible t intangible t)))
  4239. (add-text-properties (match-beginning 2) (match-end 2)
  4240. '(font-lock-multiline t org-emphasis t))
  4241. (when (and org-hide-emphasis-markers
  4242. (not (org-at-comment-p)))
  4243. (add-text-properties (match-end 4) (match-beginning 5)
  4244. '(invisible t))
  4245. (add-text-properties (match-beginning 3) (match-end 3)
  4246. '(invisible t)))
  4247. (throw :exit t))))))))
  4248. (defun org-emphasize (&optional char)
  4249. "Insert or change an emphasis, i.e. a font like bold or italic.
  4250. If there is an active region, change that region to a new emphasis.
  4251. If there is no region, just insert the marker characters and position
  4252. the cursor between them.
  4253. CHAR should be the marker character. If it is a space, it means to
  4254. remove the emphasis of the selected region.
  4255. If CHAR is not given (for example in an interactive call) it will be
  4256. prompted for."
  4257. (interactive)
  4258. (let ((erc org-emphasis-regexp-components)
  4259. (string "") beg end move s)
  4260. (if (org-region-active-p)
  4261. (setq beg (region-beginning)
  4262. end (region-end)
  4263. string (buffer-substring beg end))
  4264. (setq move t))
  4265. (unless char
  4266. (message "Emphasis marker or tag: [%s]"
  4267. (mapconcat #'car org-emphasis-alist ""))
  4268. (setq char (read-char-exclusive)))
  4269. (if (equal char ?\s)
  4270. (setq s ""
  4271. move nil)
  4272. (unless (assoc (char-to-string char) org-emphasis-alist)
  4273. (user-error "No such emphasis marker: \"%c\"" char))
  4274. (setq s (char-to-string char)))
  4275. (while (and (> (length string) 1)
  4276. (equal (substring string 0 1) (substring string -1))
  4277. (assoc (substring string 0 1) org-emphasis-alist))
  4278. (setq string (substring string 1 -1)))
  4279. (setq string (concat s string s))
  4280. (when beg (delete-region beg end))
  4281. (unless (or (bolp)
  4282. (string-match (concat "[" (nth 0 erc) "\n]")
  4283. (char-to-string (char-before (point)))))
  4284. (insert " "))
  4285. (unless (or (eobp)
  4286. (string-match (concat "[" (nth 1 erc) "\n]")
  4287. (char-to-string (char-after (point)))))
  4288. (insert " ") (backward-char 1))
  4289. (insert string)
  4290. (and move (backward-char 1))))
  4291. (defconst org-nonsticky-props
  4292. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4293. (defsubst org-rear-nonsticky-at (pos)
  4294. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4295. (defun org-activate-links--overlays (limit)
  4296. "Add link properties to links.
  4297. This includes angle, plain, and bracket links."
  4298. (catch :exit
  4299. (while (re-search-forward org-link-any-re limit t)
  4300. (let* ((start (match-beginning 0))
  4301. (end (match-end 0))
  4302. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4303. (visible-end (or (match-end 3) (match-end 2)))
  4304. (style (cond ((eq ?< (char-after start)) 'angle)
  4305. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4306. (t 'plain))))
  4307. (when (and (memq style org-highlight-links)
  4308. ;; Do not span over paragraph boundaries.
  4309. (not (string-match-p org-element-paragraph-separate
  4310. (match-string 0)))
  4311. ;; Do not confuse plain links with tags.
  4312. (not (and (eq style 'plain)
  4313. (let ((face (get-text-property
  4314. (max (1- start) (point-min)) 'face)))
  4315. (if (consp face) (memq 'org-tag face)
  4316. (eq 'org-tag face))))))
  4317. (let* ((link-object (save-excursion
  4318. (goto-char start)
  4319. (save-match-data (org-element-link-parser))))
  4320. (link (org-element-property :raw-link link-object))
  4321. (type (org-element-property :type link-object))
  4322. (path (org-element-property :path link-object))
  4323. (face-property (pcase (org-link-get-parameter type :face)
  4324. ((and (pred functionp) face) (funcall face path))
  4325. ((and (pred facep) face) face)
  4326. ((and (pred consp) face) face) ;anonymous
  4327. (_ 'org-link)))
  4328. (properties ;for link's visible part
  4329. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4330. 'highlight)
  4331. 'keymap (or (org-link-get-parameter type :keymap)
  4332. org-mouse-map)
  4333. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4334. ((and (pred stringp) echo) echo)
  4335. ((and (pred functionp) echo) echo)
  4336. (_ (concat "LINK: " link)))
  4337. 'htmlize-link (pcase (org-link-get-parameter type
  4338. :htmlize-link)
  4339. ((and (pred functionp) f) (funcall f))
  4340. (_ `(:uri ,link)))
  4341. 'font-lock-multiline t)))
  4342. (org-remove-flyspell-overlays-in start end)
  4343. (org-rear-nonsticky-at end)
  4344. (if (not (eq 'bracket style))
  4345. (progn
  4346. (add-face-text-property start end face-property)
  4347. (add-text-properties start end properties))
  4348. ;; Handle invisible parts in bracket links.
  4349. (remove-text-properties start end '(invisible nil))
  4350. (let ((hidden
  4351. (append `(invisible
  4352. ,(or (org-link-get-parameter type :display)
  4353. 'org-link))
  4354. properties)))
  4355. (add-text-properties start visible-start hidden)
  4356. (add-face-text-property start end face-property)
  4357. (add-text-properties visible-start visible-end properties)
  4358. (add-text-properties visible-end end hidden)
  4359. (org-rear-nonsticky-at visible-start)
  4360. (org-rear-nonsticky-at visible-end)))
  4361. (let ((f (org-link-get-parameter type :activate-func)))
  4362. (when (functionp f)
  4363. (funcall f start end path (eq style 'bracket))))
  4364. (throw :exit t))))) ;signal success
  4365. nil))
  4366. (defun org-activate-links--text-properties (limit)
  4367. "Add link properties to links.
  4368. This includes angle, plain, and bracket links."
  4369. (catch :exit
  4370. (while (re-search-forward org-link-any-re limit t)
  4371. (let* ((start (match-beginning 0))
  4372. (end (match-end 0))
  4373. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4374. (visible-end (or (match-end 3) (match-end 2)))
  4375. (style (cond ((eq ?< (char-after start)) 'angle)
  4376. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4377. (t 'plain))))
  4378. (when (and (memq style org-highlight-links)
  4379. ;; Do not span over paragraph boundaries.
  4380. (not (string-match-p org-element-paragraph-separate
  4381. (match-string 0)))
  4382. ;; Do not confuse plain links with tags.
  4383. (not (and (eq style 'plain)
  4384. (let ((face (get-text-property
  4385. (max (1- start) (point-min)) 'face)))
  4386. (if (consp face) (memq 'org-tag face)
  4387. (eq 'org-tag face))))))
  4388. (let* ((link-object (save-excursion
  4389. (goto-char start)
  4390. (save-match-data (org-element-link-parser))))
  4391. (link (org-element-property :raw-link link-object))
  4392. (type (org-element-property :type link-object))
  4393. (path (org-element-property :path link-object))
  4394. (face-property (pcase (org-link-get-parameter type :face)
  4395. ((and (pred functionp) face) (funcall face path))
  4396. ((and (pred facep) face) face)
  4397. ((and (pred consp) face) face) ;anonymous
  4398. (_ 'org-link)))
  4399. (properties ;for link's visible part
  4400. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4401. 'highlight)
  4402. 'keymap (or (org-link-get-parameter type :keymap)
  4403. org-mouse-map)
  4404. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4405. ((and (pred stringp) echo) echo)
  4406. ((and (pred functionp) echo) echo)
  4407. (_ (concat "LINK: " link)))
  4408. 'htmlize-link (pcase (org-link-get-parameter type
  4409. :htmlize-link)
  4410. ((and (pred functionp) f) (funcall f))
  4411. (_ `(:uri ,link)))
  4412. 'font-lock-multiline t)))
  4413. (org-remove-flyspell-overlays-in start end)
  4414. (org-rear-nonsticky-at end)
  4415. (if (not (eq 'bracket style))
  4416. (progn
  4417. (add-face-text-property start end face-property)
  4418. (add-text-properties start end properties))
  4419. ;; Initialise folding when used ouside org-mode.
  4420. (unless (or (derived-mode-p 'org-mode)
  4421. (and (org-fold-folding-spec-p 'org-link-description)
  4422. (org-fold-folding-spec-p 'org-link)))
  4423. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4424. "...")))
  4425. ;; Handle invisible parts in bracket links.
  4426. (let ((spec (or (org-link-get-parameter type :display)
  4427. 'org-link)))
  4428. (unless (org-fold-folding-spec-p spec)
  4429. (org-fold-add-folding-spec spec
  4430. (cdr org-link--link-folding-spec)
  4431. nil
  4432. 'append)
  4433. (org-fold-core-set-folding-spec-property spec :visible t))
  4434. (org-fold-region start end nil 'org-link)
  4435. (org-fold-region start end nil 'org-link-description)
  4436. ;; We are folding the whole emphasised text with SPEC
  4437. ;; first. It makes everything invisible (or whatever
  4438. ;; the user wants).
  4439. (org-fold-region start end t spec)
  4440. ;; The visible part of the text is folded using
  4441. ;; 'org-link-description, which is forcing this part of
  4442. ;; the text to be visible.
  4443. (org-fold-region visible-start visible-end t 'org-link-description)
  4444. (add-text-properties start end properties)
  4445. (add-face-text-property start end face-property)
  4446. (org-rear-nonsticky-at visible-start)
  4447. (org-rear-nonsticky-at visible-end)))
  4448. (let ((f (org-link-get-parameter type :activate-func)))
  4449. (when (functionp f)
  4450. (funcall f start end path (eq style 'bracket))))
  4451. (throw :exit t))))) ;signal success
  4452. nil))
  4453. (defsubst org-activate-links (limit)
  4454. "Add link properties to links.
  4455. This includes angle, plain, and bracket links."
  4456. (if (eq org-fold-core-style 'text-properties)
  4457. (org-activate-links--text-properties limit)
  4458. (org-activate-links--overlays limit)))
  4459. (defun org-activate-code (limit)
  4460. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4461. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4462. (remove-text-properties (match-beginning 0) (match-end 0)
  4463. '(display t invisible t intangible t))
  4464. t))
  4465. (defcustom org-src-fontify-natively t
  4466. "When non-nil, fontify code in code blocks.
  4467. See also the `org-block' face."
  4468. :type 'boolean
  4469. :version "26.1"
  4470. :package-version '(Org . "8.3")
  4471. :group 'org-appearance
  4472. :group 'org-babel)
  4473. (defcustom org-allow-promoting-top-level-subtree nil
  4474. "When non-nil, allow promoting a top level subtree.
  4475. The leading star of the top level headline will be replaced
  4476. by a #."
  4477. :type 'boolean
  4478. :version "24.1"
  4479. :group 'org-appearance)
  4480. (defun org-fontify-meta-lines-and-blocks (limit)
  4481. (condition-case nil
  4482. (org-fontify-meta-lines-and-blocks-1 limit)
  4483. (error (message "Org mode fontification error in %S at %d"
  4484. (current-buffer)
  4485. (line-number-at-pos)))))
  4486. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4487. "Fontify #+ lines and blocks."
  4488. (let ((case-fold-search t))
  4489. (when (re-search-forward
  4490. (rx bol (group (zero-or-more (any " \t")) "#"
  4491. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4492. (any " \t")
  4493. eol))
  4494. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4495. (zero-or-more (any " \t"))
  4496. (group (group (zero-or-more (not (any " \t\n"))))
  4497. (zero-or-more (any " \t"))
  4498. (group (zero-or-more any)))))
  4499. limit t)
  4500. (let ((beg (match-beginning 0))
  4501. (end-of-beginline (match-end 0))
  4502. ;; Including \n at end of #+begin line will include \n
  4503. ;; after the end of block content.
  4504. (block-start (match-end 0))
  4505. (block-end nil)
  4506. (lang (match-string 7)) ; The language, if it is a source block.
  4507. (bol-after-beginline (line-beginning-position 2))
  4508. (dc1 (downcase (match-string 2)))
  4509. (dc3 (downcase (match-string 3)))
  4510. (whole-blockline org-fontify-whole-block-delimiter-line)
  4511. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4512. (cond
  4513. ((and (match-end 4) (equal dc3 "+begin"))
  4514. ;; Truly a block
  4515. (setq block-type (downcase (match-string 5))
  4516. ;; Src, example, export, maybe more.
  4517. quoting (member block-type org-protecting-blocks))
  4518. (when (re-search-forward
  4519. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4520. (seq (zero-or-more (any " \t"))
  4521. "#+end"
  4522. ,(match-string 4)
  4523. word-end
  4524. (zero-or-more any)))))
  4525. ;; We look further than LIMIT on purpose.
  4526. nil t)
  4527. ;; We do have a matching #+end line.
  4528. (setq beg-of-endline (match-beginning 0)
  4529. end-of-endline (match-end 0)
  4530. nl-before-endline (1- (match-beginning 0)))
  4531. (setq block-end (match-beginning 0)) ; Include the final newline.
  4532. (when quoting
  4533. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4534. (remove-text-properties beg end-of-endline
  4535. '(display t invisible t intangible t)))
  4536. (add-text-properties
  4537. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4538. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4539. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4540. (cond
  4541. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4542. (save-match-data
  4543. (org-src-font-lock-fontify-block lang block-start block-end))
  4544. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4545. (quoting
  4546. (add-text-properties
  4547. bol-after-beginline beg-of-endline
  4548. (list 'face
  4549. (list :inherit
  4550. (let ((face-name
  4551. (intern (format "org-block-%s" lang))))
  4552. (append (and (facep face-name) (list face-name))
  4553. '(org-block)))))))
  4554. ((not org-fontify-quote-and-verse-blocks))
  4555. ((string= block-type "quote")
  4556. (add-face-text-property
  4557. bol-after-beginline beg-of-endline 'org-quote t))
  4558. ((string= block-type "verse")
  4559. (add-face-text-property
  4560. bol-after-beginline beg-of-endline 'org-verse t)))
  4561. ;; Fontify the #+begin and #+end lines of the blocks
  4562. (add-text-properties
  4563. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4564. '(face org-block-begin-line))
  4565. (unless (eq (char-after beg-of-endline) ?*)
  4566. (add-text-properties
  4567. beg-of-endline
  4568. (if whole-blockline
  4569. (let ((beg-of-next-line (1+ end-of-endline)))
  4570. (min (point-max) beg-of-next-line))
  4571. (min (point-max) end-of-endline))
  4572. '(face org-block-end-line)))
  4573. t))
  4574. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4575. (org-remove-flyspell-overlays-in
  4576. (match-beginning 0)
  4577. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4578. (add-text-properties
  4579. beg (match-end 3)
  4580. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4581. '(font-lock-fontified t invisible t)
  4582. '(font-lock-fontified t face org-document-info-keyword)))
  4583. (add-text-properties
  4584. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4585. (if (string-equal dc1 "+title:")
  4586. '(font-lock-fontified t face org-document-title)
  4587. '(font-lock-fontified t face org-document-info))))
  4588. ((string-prefix-p "+caption" dc1)
  4589. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4590. (remove-text-properties (match-beginning 0) (match-end 0)
  4591. '(display t invisible t intangible t))
  4592. ;; Handle short captions
  4593. (save-excursion
  4594. (beginning-of-line)
  4595. (looking-at (rx (group (zero-or-more (any " \t"))
  4596. "#+caption"
  4597. (optional "[" (zero-or-more any) "]")
  4598. ":")
  4599. (zero-or-more (any " \t")))))
  4600. (add-text-properties (line-beginning-position) (match-end 1)
  4601. '(font-lock-fontified t face org-meta-line))
  4602. (add-text-properties (match-end 0) (line-end-position)
  4603. '(font-lock-fontified t face org-block))
  4604. t)
  4605. ((member dc3 '(" " ""))
  4606. ;; Just a comment, the plus was not there
  4607. (org-remove-flyspell-overlays-in beg (match-end 0))
  4608. (add-text-properties
  4609. beg (match-end 0)
  4610. '(font-lock-fontified t face font-lock-comment-face)))
  4611. (t ;; Just any other in-buffer setting, but not indented
  4612. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4613. (remove-text-properties (match-beginning 0) (match-end 0)
  4614. '(display t invisible t intangible t))
  4615. (add-text-properties beg (match-end 0)
  4616. '(font-lock-fontified t face org-meta-line))
  4617. t))))))
  4618. (defun org-fontify-drawers (limit)
  4619. "Fontify drawers."
  4620. (when (re-search-forward org-drawer-regexp limit t)
  4621. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4622. '(font-lock-fontified t face org-drawer))
  4623. (org-remove-flyspell-overlays-in
  4624. (line-beginning-position) (line-beginning-position 2))
  4625. t))
  4626. (defun org-fontify-macros (limit)
  4627. "Fontify macros."
  4628. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4629. (let ((begin (match-beginning 0))
  4630. (opening-end (match-beginning 1)))
  4631. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4632. (match-string 1))
  4633. (let ((end (match-end 1))
  4634. (closing-start (match-beginning 1)))
  4635. (add-text-properties
  4636. begin end
  4637. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4638. (org-remove-flyspell-overlays-in begin end)
  4639. (when org-hide-macro-markers
  4640. (add-text-properties begin opening-end '(invisible t))
  4641. (add-text-properties closing-start end '(invisible t)))
  4642. t)))))
  4643. (defun org-fontify-extend-region (beg end _old-len)
  4644. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4645. (1+ end) end))
  4646. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4647. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4648. (extend
  4649. (lambda (r1 r2 dir)
  4650. (let ((re (replace-regexp-in-string
  4651. "\\(begin\\|end\\)" r1
  4652. (replace-regexp-in-string
  4653. "[][]" r2
  4654. (match-string-no-properties 0)))))
  4655. (re-search-forward (regexp-quote re) nil t dir)))))
  4656. (goto-char beg)
  4657. (back-to-indentation)
  4658. (save-match-data
  4659. (cond ((looking-at end-re)
  4660. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4661. ((looking-at begin-re)
  4662. (cons beg (or (funcall extend "end" "]" 1) end)))
  4663. (t (cons beg end))))))
  4664. (defun org-activate-footnote-links (limit)
  4665. "Add text properties for footnotes."
  4666. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4667. (when fn
  4668. (let* ((beg (nth 1 fn))
  4669. (end (nth 2 fn))
  4670. (label (car fn))
  4671. (referencep (/= (line-beginning-position) beg)))
  4672. (when (and referencep (nth 3 fn))
  4673. (save-excursion
  4674. (goto-char beg)
  4675. (search-forward (or label "fn:"))
  4676. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4677. (add-text-properties beg end
  4678. (list 'mouse-face 'highlight
  4679. 'keymap org-mouse-map
  4680. 'help-echo
  4681. (if referencep "Footnote reference"
  4682. "Footnote definition")
  4683. 'font-lock-fontified t
  4684. 'font-lock-multiline t
  4685. 'face 'org-footnote))))))
  4686. (defun org-activate-dates (limit)
  4687. "Add text properties for dates."
  4688. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4689. (not (equal (char-before (match-beginning 0)) 91)))
  4690. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4691. (add-text-properties (match-beginning 0) (match-end 0)
  4692. (list 'mouse-face 'highlight
  4693. 'keymap org-mouse-map))
  4694. (org-rear-nonsticky-at (match-end 0))
  4695. (when org-display-custom-times
  4696. ;; If it's a date range, activate custom time for second date.
  4697. (when (match-end 3)
  4698. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4699. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4700. t))
  4701. (defun org-activate-target-links (limit)
  4702. "Add text properties for target matches."
  4703. (when org-target-link-regexp
  4704. (let ((case-fold-search t))
  4705. ;; `org-target-link-regexp' matches one character before the
  4706. ;; actual target.
  4707. (unless (bolp) (forward-char -1))
  4708. (when (re-search-forward org-target-link-regexp limit t)
  4709. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4710. (add-text-properties (match-beginning 1) (match-end 1)
  4711. (list 'mouse-face 'highlight
  4712. 'keymap org-mouse-map
  4713. 'help-echo "Radio target link"
  4714. 'org-linked-text t))
  4715. (org-rear-nonsticky-at (match-end 1))
  4716. t))))
  4717. (defvar org-latex-and-related-regexp nil
  4718. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4719. (defun org-compute-latex-and-related-regexp ()
  4720. "Compute regular expression for LaTeX, entities and sub/superscript.
  4721. Result depends on variable `org-highlight-latex-and-related'."
  4722. (let ((re-sub
  4723. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4724. ((eq org-use-sub-superscripts '{})
  4725. (list org-match-substring-with-braces-regexp))
  4726. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4727. (re-latex
  4728. (when (or (memq 'latex org-highlight-latex-and-related)
  4729. (memq 'native org-highlight-latex-and-related))
  4730. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4731. (delq nil
  4732. (mapcar (lambda (x)
  4733. (and (member (car x) matchers) (nth 1 x)))
  4734. org-latex-regexps)))))
  4735. (re-entities
  4736. (when (memq 'entities org-highlight-latex-and-related)
  4737. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4738. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4739. (setq-local org-latex-and-related-regexp
  4740. (mapconcat #'identity
  4741. (append re-latex re-entities re-sub)
  4742. "\\|"))))
  4743. (defun org-do-latex-and-related (limit)
  4744. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4745. Stop at first highlighted object, if any. Return t if some
  4746. highlighting was done, nil otherwise."
  4747. (when (org-string-nw-p org-latex-and-related-regexp)
  4748. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4749. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4750. (catch 'found
  4751. (while (and (< (point) limit)
  4752. (re-search-forward org-latex-and-related-regexp nil t))
  4753. (cond
  4754. ((>= (match-beginning 0) limit)
  4755. (throw 'found nil))
  4756. ((cl-some (lambda (f)
  4757. (memq f '(org-code org-verbatim underline
  4758. org-special-keyword)))
  4759. (save-excursion
  4760. (goto-char (1+ (match-beginning 0)))
  4761. (face-at-point nil t))))
  4762. ;; Try to limit false positives. In this case, ignore
  4763. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4764. ;; contain an empty line.
  4765. ((save-excursion
  4766. (goto-char (match-beginning 0))
  4767. (and (looking-at-p latex-prefix-re)
  4768. (save-match-data
  4769. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4770. (t
  4771. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4772. '(?_ ?^))
  4773. 1
  4774. 0))
  4775. (start (+ offset (match-beginning 0)))
  4776. (end (match-end 0)))
  4777. (if (memq 'native org-highlight-latex-and-related)
  4778. (org-src-font-lock-fontify-block "latex" start end)
  4779. (font-lock-prepend-text-property start end
  4780. 'face 'org-latex-and-related))
  4781. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4782. '(font-lock-multiline t))
  4783. (throw 'found t)))))
  4784. nil))))
  4785. (defun org-restart-font-lock ()
  4786. "Restart `font-lock-mode', to force refontification."
  4787. (when font-lock-mode
  4788. (font-lock-mode -1)
  4789. (font-lock-mode 1)))
  4790. (defun org-activate-tags (limit)
  4791. (when (re-search-forward org-tag-line-re limit t)
  4792. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4793. (add-text-properties (match-beginning 1) (match-end 1)
  4794. (list 'mouse-face 'highlight
  4795. 'keymap org-mouse-map))
  4796. (org-rear-nonsticky-at (match-end 1))
  4797. t))
  4798. (defun org-outline-level ()
  4799. "Compute the outline level of the heading at point.
  4800. If this is called at a normal headline, the level is the number
  4801. of stars. Use `org-reduced-level' to remove the effect of
  4802. `org-odd-levels'. Unlike to `org-current-level', this function
  4803. takes into consideration inlinetasks."
  4804. (org-with-wide-buffer
  4805. (end-of-line)
  4806. (if (re-search-backward org-outline-regexp-bol nil t)
  4807. (1- (- (match-end 0) (match-beginning 0)))
  4808. 0)))
  4809. (defvar org-font-lock-keywords nil)
  4810. (defsubst org-re-property (property &optional literal allow-null value)
  4811. "Return a regexp matching a PROPERTY line.
  4812. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4813. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4814. non-nil, match properties even without a value.
  4815. Match group 3 is set to the value when it exists. If there is no
  4816. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4817. With optional argument VALUE, match only property lines with
  4818. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4819. unless LITERAL is non-nil."
  4820. (concat
  4821. "^\\(?4:[ \t]*\\)"
  4822. (format "\\(?1::\\(?2:%s\\):\\)"
  4823. (if literal property (regexp-quote property)))
  4824. (cond (value
  4825. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4826. (if literal value (regexp-quote value))))
  4827. (allow-null
  4828. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4829. (t
  4830. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4831. (defconst org-property-re
  4832. (org-re-property "\\S-+" 'literal t)
  4833. "Regular expression matching a property line.
  4834. There are four matching groups:
  4835. 1: :PROPKEY: including the leading and trailing colon,
  4836. 2: PROPKEY without the leading and trailing colon,
  4837. 3: PROPVAL without leading or trailing spaces,
  4838. 4: the indentation of the current line,
  4839. 5: trailing whitespace.")
  4840. (defvar org-font-lock-hook nil
  4841. "Functions to be called for special font lock stuff.")
  4842. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4843. (defvar org-font-lock-set-keywords-hook nil
  4844. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4845. This is called after `org-font-lock-extra-keywords' is defined, but before
  4846. it is installed to be used by font lock. This can be useful if something
  4847. needs to be inserted at a specific position in the font-lock sequence.")
  4848. (defun org-font-lock-hook (limit)
  4849. "Run `org-font-lock-hook' within LIMIT."
  4850. (run-hook-with-args 'org-font-lock-hook limit))
  4851. (defun org-set-font-lock-defaults ()
  4852. "Set font lock defaults for the current buffer."
  4853. (let ((org-font-lock-extra-keywords
  4854. (list
  4855. ;; Call the hook
  4856. '(org-font-lock-hook)
  4857. ;; Headlines
  4858. `(,(if org-fontify-whole-heading-line
  4859. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4860. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4861. (1 (org-get-level-face 1))
  4862. (2 (org-get-level-face 2))
  4863. (3 (org-get-level-face 3)))
  4864. ;; Table lines
  4865. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4866. (1 'org-table t))
  4867. ;; Table internals
  4868. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4869. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4870. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4871. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4872. ;; Properties
  4873. (list org-property-re
  4874. '(1 'org-special-keyword t)
  4875. '(3 'org-property-value t))
  4876. ;; Drawers
  4877. '(org-fontify-drawers)
  4878. ;; Link related fontification.
  4879. '(org-activate-links)
  4880. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  4881. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  4882. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  4883. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  4884. ;; Targets.
  4885. (list org-radio-target-regexp '(0 'org-target t))
  4886. (list org-target-regexp '(0 'org-target t))
  4887. ;; Diary sexps.
  4888. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4889. ;; Macro
  4890. '(org-fontify-macros)
  4891. ;; TODO keyword
  4892. (list (format org-heading-keyword-regexp-format
  4893. org-todo-regexp)
  4894. '(2 (org-get-todo-face 2) prepend))
  4895. ;; TODO
  4896. (when org-fontify-todo-headline
  4897. (list (format org-heading-keyword-regexp-format
  4898. (concat
  4899. "\\(?:"
  4900. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4901. "\\)"))
  4902. '(2 'org-headline-todo prepend)))
  4903. ;; DONE
  4904. (when org-fontify-done-headline
  4905. (list (format org-heading-keyword-regexp-format
  4906. (concat
  4907. "\\(?:"
  4908. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4909. "\\)"))
  4910. '(2 'org-headline-done prepend)))
  4911. ;; Priorities
  4912. '(org-font-lock-add-priority-faces)
  4913. ;; Tags
  4914. '(org-font-lock-add-tag-faces)
  4915. ;; Tags groups
  4916. (when (and org-group-tags org-tag-groups-alist)
  4917. (list (concat org-outline-regexp-bol ".+\\(:"
  4918. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4919. ":\\).*$")
  4920. '(1 'org-tag-group prepend)))
  4921. ;; Special keywords
  4922. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4923. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4924. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4925. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4926. ;; Emphasis
  4927. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  4928. ;; Checkboxes
  4929. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4930. 1 'org-checkbox prepend)
  4931. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4932. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4933. (0 (org-get-checkbox-statistics-face) prepend)))
  4934. ;; Description list items
  4935. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4936. 1 'org-list-dt prepend)
  4937. ;; Inline export snippets
  4938. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  4939. (1 'font-lock-comment-face t)
  4940. (2 'org-tag t)
  4941. (3 'font-lock-comment-face t))
  4942. ;; ARCHIVEd headings
  4943. (list (concat
  4944. org-outline-regexp-bol
  4945. "\\(.*:" org-archive-tag ":.*\\)")
  4946. '(1 'org-archived prepend))
  4947. ;; Specials
  4948. '(org-do-latex-and-related)
  4949. '(org-fontify-entities)
  4950. '(org-raise-scripts)
  4951. ;; Code
  4952. '(org-activate-code (1 'org-code t))
  4953. ;; COMMENT
  4954. (list (format
  4955. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  4956. org-todo-regexp
  4957. org-comment-string)
  4958. '(9 'org-special-keyword t))
  4959. ;; Blocks and meta lines
  4960. '(org-fontify-meta-lines-and-blocks)
  4961. '(org-fontify-inline-src-blocks)
  4962. ;; Citations. When an activate processor is specified, if
  4963. ;; specified, try loading it beforehand.
  4964. (progn
  4965. (unless (null org-cite-activate-processor)
  4966. (org-cite-try-load-processor org-cite-activate-processor))
  4967. '(org-cite-activate)))))
  4968. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  4969. (run-hooks 'org-font-lock-set-keywords-hook)
  4970. ;; Now set the full font-lock-keywords
  4971. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  4972. (setq-local font-lock-defaults
  4973. '(org-font-lock-keywords t nil nil backward-paragraph))
  4974. (setq-local font-lock-extend-after-change-region-function
  4975. #'org-fontify-extend-region)
  4976. (kill-local-variable 'font-lock-keywords)
  4977. nil))
  4978. (defun org-toggle-pretty-entities ()
  4979. "Toggle the composition display of entities as UTF8 characters."
  4980. (interactive)
  4981. (setq-local org-pretty-entities (not org-pretty-entities))
  4982. (org-restart-font-lock)
  4983. (if org-pretty-entities
  4984. (message "Entities are now displayed as UTF8 characters")
  4985. (save-restriction
  4986. (widen)
  4987. (decompose-region (point-min) (point-max))
  4988. (message "Entities are now displayed as plain text"))))
  4989. (defvar-local org-custom-properties-overlays nil
  4990. "List of overlays used for custom properties.")
  4991. (defun org-toggle-custom-properties-visibility ()
  4992. "Display or hide properties in `org-custom-properties'."
  4993. (interactive)
  4994. (if org-custom-properties-overlays
  4995. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  4996. (setq org-custom-properties-overlays nil))
  4997. (when org-custom-properties
  4998. (org-with-wide-buffer
  4999. (goto-char (point-min))
  5000. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5001. (while (re-search-forward regexp nil t)
  5002. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5003. (when (and end (< (point) end))
  5004. ;; Hide first custom property in current drawer.
  5005. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5006. (overlay-put o 'invisible t)
  5007. (overlay-put o 'org-custom-property t)
  5008. (push o org-custom-properties-overlays))
  5009. ;; Hide additional custom properties in the same drawer.
  5010. (while (re-search-forward regexp end t)
  5011. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5012. (overlay-put o 'invisible t)
  5013. (overlay-put o 'org-custom-property t)
  5014. (push o org-custom-properties-overlays)))))
  5015. ;; Each entry is limited to a single property drawer.
  5016. (outline-next-heading)))))))
  5017. (defun org-fontify-entities (limit)
  5018. "Find an entity to fontify."
  5019. (let (ee)
  5020. (when org-pretty-entities
  5021. (catch 'match
  5022. ;; "\_ "-family is left out on purpose. Only the first one,
  5023. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5024. ;; confusing when adding a second white space character.
  5025. (while (re-search-forward
  5026. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5027. limit t)
  5028. (when (and (not (org-at-comment-p))
  5029. (setq ee (org-entity-get (match-string 1)))
  5030. (= (length (nth 6 ee)) 1))
  5031. (let* ((end (if (equal (match-string 2) "{}")
  5032. (match-end 2)
  5033. (match-end 1))))
  5034. (add-text-properties
  5035. (match-beginning 0) end
  5036. (list 'font-lock-fontified t))
  5037. (compose-region (match-beginning 0) end
  5038. (nth 6 ee) nil)
  5039. (backward-char 1)
  5040. (throw 'match t))))
  5041. nil))))
  5042. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5043. "Fontify string S like in Org mode."
  5044. (with-temp-buffer
  5045. (insert s)
  5046. (let ((org-odd-levels-only odd-levels))
  5047. (org-mode)
  5048. (org-font-lock-ensure)
  5049. (if org-link-descriptive
  5050. (org-link-display-format
  5051. (buffer-string))
  5052. (buffer-string)))))
  5053. (defun org-get-level-face (n)
  5054. "Get the right face for match N in font-lock matching of headlines."
  5055. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5056. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5057. (org-f (if org-cycle-level-faces
  5058. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5059. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5060. (cond
  5061. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5062. ((eq n 2) org-f)
  5063. (t (unless org-level-color-stars-only org-f)))))
  5064. (defun org-face-from-face-or-color (context inherit face-or-color)
  5065. "Create a face list that inherits INHERIT, but sets the foreground color.
  5066. When FACE-OR-COLOR is not a string, just return it."
  5067. (if (stringp face-or-color)
  5068. (list :inherit inherit
  5069. (cdr (assoc context org-faces-easy-properties))
  5070. face-or-color)
  5071. face-or-color))
  5072. (defun org-get-todo-face (kwd)
  5073. "Get the right face for a TODO keyword KWD.
  5074. If KWD is a number, get the corresponding match group."
  5075. (when (numberp kwd) (setq kwd (match-string kwd)))
  5076. (or (org-face-from-face-or-color
  5077. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5078. (and (member kwd org-done-keywords) 'org-done)
  5079. 'org-todo))
  5080. (defun org-get-priority-face (priority)
  5081. "Get the right face for PRIORITY.
  5082. PRIORITY is a character."
  5083. (or (org-face-from-face-or-color
  5084. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5085. 'org-priority))
  5086. (defun org-get-tag-face (tag)
  5087. "Get the right face for TAG.
  5088. If TAG is a number, get the corresponding match group."
  5089. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5090. (or (org-face-from-face-or-color
  5091. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5092. 'org-tag)))
  5093. (defvar org-priority-regexp) ; defined later in the file
  5094. (defun org-font-lock-add-priority-faces (limit)
  5095. "Add the special priority faces."
  5096. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5097. (let ((beg (match-beginning 1))
  5098. (end (1+ (match-end 2))))
  5099. (add-face-text-property
  5100. beg end
  5101. (org-get-priority-face (string-to-char (match-string 2))))
  5102. (add-text-properties
  5103. beg end
  5104. (list 'font-lock-fontified t)))))
  5105. (defun org-font-lock-add-tag-faces (limit)
  5106. "Add the special tag faces."
  5107. (when (and org-tag-faces org-tags-special-faces-re)
  5108. (while (re-search-forward org-tags-special-faces-re limit t)
  5109. (add-face-text-property
  5110. (match-beginning 1)
  5111. (match-end 1)
  5112. (org-get-tag-face 1))
  5113. (add-text-properties (match-beginning 1) (match-end 1)
  5114. (list 'font-lock-fontified t))
  5115. (backward-char 1))))
  5116. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5117. "Remove fontification and activation overlays from links."
  5118. (font-lock-default-unfontify-region beg end)
  5119. (let* ((buffer-undo-list t)
  5120. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5121. (inhibit-modification-hooks t)
  5122. deactivate-mark buffer-file-name buffer-file-truename)
  5123. (decompose-region beg end)
  5124. (remove-text-properties beg end
  5125. '(mouse-face t keymap t org-linked-text t
  5126. invisible t intangible t
  5127. org-emphasis t))
  5128. (org-fold-core-update-optimisation beg end)
  5129. (org-remove-font-lock-display-properties beg end)))
  5130. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5131. ((raise 0.3) (height 0.7))
  5132. ((raise -0.5))
  5133. ((raise 0.5)))
  5134. "Display properties for showing superscripts and subscripts.")
  5135. (defun org-remove-font-lock-display-properties (beg end)
  5136. "Remove specific display properties that have been added by font lock.
  5137. The will remove the raise properties that are used to show superscripts
  5138. and subscripts."
  5139. (let (next prop)
  5140. (while (< beg end)
  5141. (setq next (next-single-property-change beg 'display nil end)
  5142. prop (get-text-property beg 'display))
  5143. (when (member prop org-script-display)
  5144. (put-text-property beg next 'display nil))
  5145. (setq beg next))))
  5146. (defun org-raise-scripts (limit)
  5147. "Add raise properties to sub/superscripts."
  5148. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5149. (re-search-forward
  5150. (if (eq org-use-sub-superscripts t)
  5151. org-match-substring-regexp
  5152. org-match-substring-with-braces-regexp)
  5153. limit t))
  5154. (let* ((pos (point)) table-p comment-p
  5155. (mpos (match-beginning 3))
  5156. (emph-p (get-text-property mpos 'org-emphasis))
  5157. (link-p (get-text-property mpos 'mouse-face))
  5158. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5159. (goto-char (point-at-bol))
  5160. (setq table-p (looking-at-p org-table-dataline-regexp)
  5161. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5162. (goto-char pos)
  5163. ;; Handle a_b^c
  5164. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5165. (unless (or comment-p emph-p link-p keyw-p)
  5166. (put-text-property (match-beginning 3) (match-end 0)
  5167. 'display
  5168. (if (equal (char-after (match-beginning 2)) ?^)
  5169. (nth (if table-p 3 1) org-script-display)
  5170. (nth (if table-p 2 0) org-script-display)))
  5171. (put-text-property (match-beginning 2) (match-end 3)
  5172. 'org-emphasis t)
  5173. (add-text-properties (match-beginning 2) (match-end 2)
  5174. (list 'invisible t))
  5175. (when (and (eq (char-after (match-beginning 3)) ?{)
  5176. (eq (char-before (match-end 3)) ?}))
  5177. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5178. (list 'invisible t))
  5179. (add-text-properties (1- (match-end 3)) (match-end 3)
  5180. (list 'invisible t))))
  5181. t)))
  5182. (defun org-remove-empty-overlays-at (pos)
  5183. "Remove outline overlays that do not contain non-white stuff."
  5184. (dolist (o (overlays-at pos))
  5185. (and (eq 'outline (overlay-get o 'invisible))
  5186. (not (string-match-p
  5187. "\\S-" (buffer-substring (overlay-start o)
  5188. (overlay-end o))))
  5189. (delete-overlay o))))
  5190. ;; FIXME: This function is unused.
  5191. (defun org-show-empty-lines-in-parent ()
  5192. "Move to the parent and re-show empty lines before visible headlines."
  5193. (save-excursion
  5194. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5195. (org-cycle-show-empty-lines context))))
  5196. (defun org-files-list ()
  5197. "Return `org-agenda-files' list, plus all open Org files.
  5198. This is useful for operations that need to scan all of a user's
  5199. open and agenda-wise Org files."
  5200. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5201. (dolist (buf (buffer-list))
  5202. (with-current-buffer buf
  5203. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5204. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5205. :test #'equal))))
  5206. files))
  5207. (defsubst org-entry-beginning-position ()
  5208. "Return the beginning position of the current entry."
  5209. (save-excursion (org-back-to-heading t) (point)))
  5210. (defsubst org-entry-end-position ()
  5211. "Return the end position of the current entry."
  5212. (save-excursion (outline-next-heading) (point)))
  5213. (defun org-subtree-end-visible-p ()
  5214. "Is the end of the current subtree visible?"
  5215. (pos-visible-in-window-p
  5216. (save-excursion (org-end-of-subtree t) (point))))
  5217. (defun org-first-headline-recenter ()
  5218. "Move cursor to the first headline and recenter the headline."
  5219. (let ((window (get-buffer-window)))
  5220. (when window
  5221. (goto-char (point-min))
  5222. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5223. (set-window-start window (line-beginning-position))))))
  5224. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5225. (defvar org-called-with-limited-levels nil
  5226. "Non-nil when `org-with-limited-levels' is currently active.")
  5227. ;;; Indirect buffer display of subtrees
  5228. (defvar org-indirect-dedicated-frame nil
  5229. "This is the frame being used for indirect tree display.")
  5230. (defvar org-last-indirect-buffer nil)
  5231. (defun org-tree-to-indirect-buffer (&optional arg)
  5232. "Create indirect buffer and narrow it to current subtree.
  5233. With a numerical prefix ARG, go up to this level and then take that tree.
  5234. If ARG is negative, go up that many levels.
  5235. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5236. indirect buffer previously made with this command, to avoid proliferation of
  5237. indirect buffers. However, when you call the command with a \
  5238. `\\[universal-argument]' prefix, or
  5239. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5240. so that you can work with several indirect buffers at the same time. If
  5241. `org-indirect-buffer-display' is `dedicated-frame', the \
  5242. `\\[universal-argument]' prefix also
  5243. requests that a new frame be made for the new buffer, so that the dedicated
  5244. frame is not changed."
  5245. (interactive "P")
  5246. (let ((cbuf (current-buffer))
  5247. (cwin (selected-window))
  5248. (pos (point))
  5249. beg end level heading ibuf)
  5250. (save-excursion
  5251. (org-back-to-heading t)
  5252. (when (numberp arg)
  5253. (setq level (org-outline-level))
  5254. (when (< arg 0) (setq arg (+ level arg)))
  5255. (while (> (setq level (org-outline-level)) arg)
  5256. (org-up-heading-safe)))
  5257. (setq beg (point)
  5258. heading (org-get-heading 'no-tags))
  5259. (org-end-of-subtree t t)
  5260. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5261. (setq end (point)))
  5262. (when (and (buffer-live-p org-last-indirect-buffer)
  5263. (not (eq org-indirect-buffer-display 'new-frame))
  5264. (not arg))
  5265. (kill-buffer org-last-indirect-buffer))
  5266. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5267. org-last-indirect-buffer ibuf)
  5268. (cond
  5269. ((or (eq org-indirect-buffer-display 'new-frame)
  5270. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5271. (select-frame (make-frame))
  5272. (delete-other-windows)
  5273. (pop-to-buffer-same-window ibuf)
  5274. (org-set-frame-title heading))
  5275. ((eq org-indirect-buffer-display 'dedicated-frame)
  5276. (raise-frame
  5277. (select-frame (or (and org-indirect-dedicated-frame
  5278. (frame-live-p org-indirect-dedicated-frame)
  5279. org-indirect-dedicated-frame)
  5280. (setq org-indirect-dedicated-frame (make-frame)))))
  5281. (delete-other-windows)
  5282. (pop-to-buffer-same-window ibuf)
  5283. (org-set-frame-title (concat "Indirect: " heading)))
  5284. ((eq org-indirect-buffer-display 'current-window)
  5285. (pop-to-buffer-same-window ibuf))
  5286. ((eq org-indirect-buffer-display 'other-window)
  5287. (pop-to-buffer ibuf))
  5288. (t (error "Invalid value")))
  5289. (narrow-to-region beg end)
  5290. (org-fold-show-all '(headings drawers blocks))
  5291. (goto-char pos)
  5292. (run-hook-with-args 'org-cycle-hook 'all)
  5293. (and (window-live-p cwin) (select-window cwin))))
  5294. (defun org-get-indirect-buffer (&optional buffer heading)
  5295. (setq buffer (or buffer (current-buffer)))
  5296. (let ((n 1) (base (buffer-name buffer)) bname)
  5297. (while (buffer-live-p
  5298. (get-buffer
  5299. (setq bname
  5300. (concat base "-"
  5301. (if heading (concat heading "-" (number-to-string n))
  5302. (number-to-string n))))))
  5303. (setq n (1+ n)))
  5304. (condition-case nil
  5305. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5306. ;; Decouple folding state. We need to do it manually since
  5307. ;; `make-indirect-buffer' does not run
  5308. ;; `clone-indirect-buffer-hook'.
  5309. (org-fold-core-decouple-indirect-buffer-folds)
  5310. ;; Return the buffer.
  5311. indirect-buffer)
  5312. (error (make-indirect-buffer buffer bname)))))
  5313. (defun org-set-frame-title (title)
  5314. "Set the title of the current frame to the string TITLE."
  5315. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5316. ;;;; Structure editing
  5317. ;;; Inserting headlines
  5318. (defun org--blank-before-heading-p (&optional parent)
  5319. "Non-nil when an empty line should precede a new heading here.
  5320. When optional argument PARENT is non-nil, consider parent
  5321. headline instead of current one."
  5322. (pcase (assq 'heading org-blank-before-new-entry)
  5323. (`(heading . auto)
  5324. (save-excursion
  5325. (org-with-limited-levels
  5326. (unless (and (org-before-first-heading-p)
  5327. (not (outline-next-heading)))
  5328. (org-back-to-heading t)
  5329. (when parent (org-up-heading-safe))
  5330. (cond ((not (bobp))
  5331. (org-previous-line-empty-p))
  5332. ((outline-next-heading)
  5333. (org-previous-line-empty-p))
  5334. ;; Ignore trailing spaces on last buffer line.
  5335. ((progn (skip-chars-backward " \t") (bolp))
  5336. (org-previous-line-empty-p))
  5337. (t nil))))))
  5338. (`(heading . ,value) value)
  5339. (_ nil)))
  5340. (defun org-insert-heading (&optional arg invisible-ok top)
  5341. "Insert a new heading or an item with the same depth at point.
  5342. If point is at the beginning of a heading, insert a new heading
  5343. or a new headline above the current one. When at the beginning
  5344. of a regular line of text, turn it into a heading.
  5345. If point is in the middle of a line, split it and create a new
  5346. headline with the text in the current line after point (see
  5347. `org-M-RET-may-split-line' on how to modify this behavior). As
  5348. a special case, on a headline, splitting can only happen on the
  5349. title itself. E.g., this excludes breaking stars or tags.
  5350. With a `\\[universal-argument]' prefix, set \
  5351. `org-insert-heading-respect-content' to
  5352. a non-nil value for the duration of the command. This forces the
  5353. insertion of a heading after the current subtree, independently
  5354. on the location of point.
  5355. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5356. insert the heading at the end of the tree
  5357. above the current heading. For example, if point is within a
  5358. 2nd-level heading, then it will insert a 2nd-level heading at
  5359. the end of the 1st-level parent subtree.
  5360. When INVISIBLE-OK is set, stop at invisible headlines when going
  5361. back. This is important for non-interactive uses of the
  5362. command.
  5363. When optional argument TOP is non-nil, insert a level 1 heading,
  5364. unconditionally."
  5365. (interactive "P")
  5366. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5367. (level (org-current-level))
  5368. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5369. (cond
  5370. ((or org-insert-heading-respect-content
  5371. (member arg '((4) (16)))
  5372. (and (not invisible-ok)
  5373. (invisible-p (max (1- (point)) (point-min)))))
  5374. ;; Position point at the location of insertion. Make sure we
  5375. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5376. (org-with-limited-levels
  5377. (if (not level) (outline-next-heading) ;before first headline
  5378. (org-back-to-heading invisible-ok)
  5379. (when (equal arg '(16)) (org-up-heading-safe))
  5380. (org-end-of-subtree)))
  5381. (unless (bolp) (insert "\n"))
  5382. (when (and blank? (save-excursion
  5383. (backward-char)
  5384. (org-before-first-heading-p)))
  5385. (insert "\n")
  5386. (backward-char))
  5387. (when (and (not level) (not (eobp)) (not (bobp)))
  5388. (when (org-at-heading-p) (insert "\n"))
  5389. (backward-char))
  5390. (unless (and blank? (org-previous-line-empty-p))
  5391. (org-N-empty-lines-before-current (if blank? 1 0)))
  5392. (insert stars " ")
  5393. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5394. ;; is visible.
  5395. (unless invisible-ok
  5396. (if (eq org-fold-core-style 'text-properties)
  5397. (cond
  5398. ((org-fold-folded-p (line-beginning-position) 'headline)
  5399. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5400. (t nil))
  5401. (pcase (get-char-property-and-overlay (point) 'invisible)
  5402. (`(outline . ,o)
  5403. (move-overlay o (overlay-start o) (line-end-position 0)))
  5404. (_ nil)))))
  5405. ;; At a headline...
  5406. ((org-at-heading-p)
  5407. (cond ((bolp)
  5408. (when blank? (save-excursion (insert "\n")))
  5409. (save-excursion (insert stars " \n"))
  5410. (unless (and blank? (org-previous-line-empty-p))
  5411. (org-N-empty-lines-before-current (if blank? 1 0)))
  5412. (end-of-line))
  5413. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5414. (org-match-line org-complex-heading-regexp)
  5415. (org-pos-in-match-range (point) 4))
  5416. ;; Grab the text that should moved to the new headline.
  5417. ;; Preserve tags.
  5418. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5419. (if (looking-at "[ \t]*$") (replace-match "")
  5420. (org-align-tags))
  5421. (end-of-line)
  5422. (when blank? (insert "\n"))
  5423. (insert "\n" stars " ")
  5424. (when (org-string-nw-p split) (insert split))))
  5425. (t
  5426. (end-of-line)
  5427. (when blank? (insert "\n"))
  5428. (insert "\n" stars " "))))
  5429. ;; On regular text, turn line into a headline or split, if
  5430. ;; appropriate.
  5431. ((bolp)
  5432. (insert stars " ")
  5433. (unless (and blank? (org-previous-line-empty-p))
  5434. (org-N-empty-lines-before-current (if blank? 1 0))))
  5435. (t
  5436. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5437. (end-of-line))
  5438. (insert "\n" stars " ")
  5439. (unless (and blank? (org-previous-line-empty-p))
  5440. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5441. (run-hooks 'org-insert-heading-hook))
  5442. (defun org-N-empty-lines-before-current (n)
  5443. "Make the number of empty lines before current exactly N.
  5444. So this will delete or add empty lines."
  5445. (let ((column (current-column)))
  5446. (beginning-of-line)
  5447. (unless (bobp)
  5448. (let ((start (save-excursion
  5449. (skip-chars-backward " \r\t\n")
  5450. (line-end-position))))
  5451. (delete-region start (line-end-position 0))))
  5452. (insert (make-string n ?\n))
  5453. (move-to-column column)))
  5454. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5455. "Return the heading of the current entry, without the stars.
  5456. When NO-TAGS is non-nil, don't include tags.
  5457. When NO-TODO is non-nil, don't include TODO keywords.
  5458. When NO-PRIORITY is non-nil, don't include priority cookie.
  5459. When NO-COMMENT is non-nil, don't include COMMENT string.
  5460. Return nil before first heading."
  5461. (unless (org-before-first-heading-p)
  5462. (save-excursion
  5463. (org-back-to-heading t)
  5464. (let ((case-fold-search nil))
  5465. (looking-at org-complex-heading-regexp)
  5466. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5467. ;; returned text will be invisible. Clear it up.
  5468. (save-match-data
  5469. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
  5470. (let ((todo (and (not no-todo) (match-string 2)))
  5471. (priority (and (not no-priority) (match-string 3)))
  5472. (headline (pcase (match-string 4)
  5473. (`nil "")
  5474. ((and (guard no-comment) h)
  5475. (replace-regexp-in-string
  5476. (eval-when-compile
  5477. (format "\\`%s[ \t]+" org-comment-string))
  5478. "" h))
  5479. (h h)))
  5480. (tags (and (not no-tags) (match-string 5))))
  5481. ;; Restore cleared optimisation.
  5482. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5483. (mapconcat #'identity
  5484. (delq nil (list todo priority headline tags))
  5485. " "))))))
  5486. (defun org-heading-components ()
  5487. "Return the components of the current heading.
  5488. This is a list with the following elements:
  5489. - the level as an integer
  5490. - the reduced level, different if `org-odd-levels-only' is set.
  5491. - the TODO keyword, or nil
  5492. - the priority character, like ?A, or nil if no priority is given
  5493. - the headline text itself, or the tags string if no headline text
  5494. - the tags string, or nil."
  5495. (save-excursion
  5496. (org-back-to-heading t)
  5497. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5498. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5499. (prog1
  5500. (list (length (match-string 1))
  5501. (org-reduced-level (length (match-string 1)))
  5502. (match-string-no-properties 2)
  5503. (and (match-end 3) (aref (match-string 3) 2))
  5504. (match-string-no-properties 4)
  5505. (match-string-no-properties 5))
  5506. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5507. (defun org-get-entry ()
  5508. "Get the entry text, after heading, entire subtree."
  5509. (save-excursion
  5510. (org-back-to-heading t)
  5511. (filter-buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  5512. (defun org-edit-headline (&optional heading)
  5513. "Edit the current headline.
  5514. Set it to HEADING when provided."
  5515. (interactive)
  5516. (org-with-wide-buffer
  5517. (org-back-to-heading t)
  5518. (let ((case-fold-search nil))
  5519. (when (looking-at org-complex-heading-regexp)
  5520. (let* ((old (match-string-no-properties 4))
  5521. (new (save-match-data
  5522. (org-trim (or heading (read-string "Edit: " old))))))
  5523. (unless (equal old new)
  5524. (if old (replace-match new t t nil 4)
  5525. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5526. (insert " " new))
  5527. (org-align-tags)
  5528. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5529. (defun org-insert-heading-after-current ()
  5530. "Insert a new heading with same level as current, after current subtree."
  5531. (interactive)
  5532. (org-back-to-heading)
  5533. (org-insert-heading)
  5534. (org-move-subtree-down)
  5535. (end-of-line 1))
  5536. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5537. "Insert heading with `org-insert-heading-respect-content' set to t."
  5538. (interactive)
  5539. (org-insert-heading '(4) invisible-ok))
  5540. (defun org-insert-todo-heading-respect-content (&optional force-state)
  5541. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5542. (interactive)
  5543. (org-insert-todo-heading force-state '(4)))
  5544. (defun org-insert-todo-heading (arg &optional force-heading)
  5545. "Insert a new heading with the same level and TODO state as current heading.
  5546. If the heading has no TODO state, or if the state is DONE, use
  5547. the first state (TODO by default). Also with one prefix arg,
  5548. force first state. With two prefix args, force inserting at the
  5549. end of the parent subtree.
  5550. When called at a plain list item, insert a new item with an
  5551. unchecked check box."
  5552. (interactive "P")
  5553. (when (or force-heading (not (org-insert-item 'checkbox)))
  5554. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5555. force-heading))
  5556. (save-excursion
  5557. (org-forward-heading-same-level -1)
  5558. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5559. (let* ((new-mark-x
  5560. (if (or (equal arg '(4))
  5561. (not (match-beginning 2))
  5562. (member (match-string 2) org-done-keywords))
  5563. (car org-todo-keywords-1)
  5564. (match-string 2)))
  5565. (new-mark
  5566. (or
  5567. (run-hook-with-args-until-success
  5568. 'org-todo-get-default-hook new-mark-x nil)
  5569. new-mark-x)))
  5570. (beginning-of-line 1)
  5571. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5572. (if org-treat-insert-todo-heading-as-state-change
  5573. (org-todo new-mark)
  5574. (insert new-mark " "))))
  5575. (when org-provide-todo-statistics
  5576. (org-update-parent-todo-statistics))))
  5577. (defun org-insert-subheading (arg)
  5578. "Insert a new subheading and demote it.
  5579. Works for outline headings and for plain lists alike."
  5580. (interactive "P")
  5581. (org-insert-heading arg)
  5582. (cond
  5583. ((org-at-heading-p) (org-do-demote))
  5584. ((org-at-item-p) (org-indent-item))))
  5585. (defun org-insert-todo-subheading (arg)
  5586. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5587. Works for outline headings and for plain lists alike."
  5588. (interactive "P")
  5589. (org-insert-todo-heading arg)
  5590. (cond
  5591. ((org-at-heading-p) (org-do-demote))
  5592. ((org-at-item-p) (org-indent-item))))
  5593. ;;; Promotion and Demotion
  5594. (defvar org-after-demote-entry-hook nil
  5595. "Hook run after an entry has been demoted.
  5596. The cursor will be at the beginning of the entry.
  5597. When a subtree is being demoted, the hook will be called for each node.")
  5598. (defvar org-after-promote-entry-hook nil
  5599. "Hook run after an entry has been promoted.
  5600. The cursor will be at the beginning of the entry.
  5601. When a subtree is being promoted, the hook will be called for each node.")
  5602. (defun org-promote-subtree ()
  5603. "Promote the entire subtree.
  5604. See also `org-promote'."
  5605. (interactive)
  5606. (save-excursion
  5607. (org-back-to-heading t)
  5608. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5609. (org-with-limited-levels (org-map-tree 'org-promote))))
  5610. (org-fix-position-after-promote))
  5611. (defun org-demote-subtree ()
  5612. "Demote the entire subtree.
  5613. See `org-demote' and `org-promote'."
  5614. (interactive)
  5615. (save-excursion
  5616. (org-back-to-heading t)
  5617. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5618. (org-with-limited-levels (org-map-tree 'org-demote))))
  5619. (org-fix-position-after-promote))
  5620. (defun org-do-promote ()
  5621. "Promote the current heading higher up the tree.
  5622. If the region is active in `transient-mark-mode', promote all
  5623. headings in the region."
  5624. (interactive)
  5625. (save-excursion
  5626. (if (org-region-active-p)
  5627. (org-map-region 'org-promote (region-beginning) (region-end))
  5628. (org-promote)))
  5629. (org-fix-position-after-promote))
  5630. (defun org-do-demote ()
  5631. "Demote the current heading lower down the tree.
  5632. If the region is active in `transient-mark-mode', demote all
  5633. headings in the region."
  5634. (interactive)
  5635. (save-excursion
  5636. (if (org-region-active-p)
  5637. (org-map-region 'org-demote (region-beginning) (region-end))
  5638. (org-demote)))
  5639. (org-fix-position-after-promote))
  5640. (defun org-fix-position-after-promote ()
  5641. "Fix cursor position and indentation after demoting/promoting."
  5642. (let ((pos (point)))
  5643. (when (save-excursion
  5644. (beginning-of-line)
  5645. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5646. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5647. (cond ((eobp) (insert " "))
  5648. ((eolp) (insert " "))
  5649. ((equal (char-after) ?\s) (forward-char 1))))))
  5650. (defun org-current-level ()
  5651. "Return the level of the current entry, or nil if before the first headline.
  5652. The level is the number of stars at the beginning of the
  5653. headline. Use `org-reduced-level' to remove the effect of
  5654. `org-odd-levels'. Unlike to `org-outline-level', this function
  5655. ignores inlinetasks."
  5656. (let ((level (org-with-limited-levels (org-outline-level))))
  5657. (and (> level 0) level)))
  5658. (defun org-get-previous-line-level ()
  5659. "Return the outline depth of the last headline before the current line.
  5660. Returns 0 for the first headline in the buffer, and nil if before the
  5661. first headline."
  5662. (and (org-current-level)
  5663. (or (and (/= (line-beginning-position) (point-min))
  5664. (save-excursion (beginning-of-line 0) (org-current-level)))
  5665. 0)))
  5666. (defun org-reduced-level (l)
  5667. "Compute the effective level of a heading.
  5668. This takes into account the setting of `org-odd-levels-only'."
  5669. (cond
  5670. ((zerop l) 0)
  5671. (org-odd-levels-only (1+ (floor (/ l 2))))
  5672. (t l)))
  5673. (defun org-level-increment ()
  5674. "Return the number of stars that will be added or removed at a
  5675. time to headlines when structure editing, based on the value of
  5676. `org-odd-levels-only'."
  5677. (if org-odd-levels-only 2 1))
  5678. (defun org-get-valid-level (level &optional change)
  5679. "Rectify a level change under the influence of `org-odd-levels-only'.
  5680. LEVEL is a current level, CHANGE is by how much the level should
  5681. be modified. Even if CHANGE is nil, LEVEL may be returned
  5682. modified because even level numbers will become the next higher
  5683. odd number. Returns values greater than 0."
  5684. (if org-odd-levels-only
  5685. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5686. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5687. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5688. (max 1 (+ level (or change 0)))))
  5689. (defun org-promote ()
  5690. "Promote the current heading higher up the tree."
  5691. (org-with-wide-buffer
  5692. (org-back-to-heading t)
  5693. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5694. after-change-functions))
  5695. (level (save-match-data (funcall outline-level)))
  5696. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5697. (diff (abs (- level (length up-head) -1))))
  5698. (cond
  5699. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5700. (replace-match "# " nil t))
  5701. ((= level 1)
  5702. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5703. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5704. (unless (= level 1)
  5705. (when org-auto-align-tags (org-align-tags))
  5706. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5707. (run-hooks 'org-after-promote-entry-hook))))
  5708. (defun org-demote ()
  5709. "Demote the current heading lower down the tree."
  5710. (org-with-wide-buffer
  5711. (org-back-to-heading t)
  5712. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5713. after-change-functions))
  5714. (level (save-match-data (funcall outline-level)))
  5715. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5716. (diff (abs (- level (length down-head) -1))))
  5717. (org-fold-core-ignore-fragility-checks
  5718. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5719. (when org-auto-align-tags (org-align-tags))
  5720. (when org-adapt-indentation (org-fixup-indentation diff)))
  5721. (run-hooks 'org-after-demote-entry-hook))))
  5722. (defun org-cycle-level ()
  5723. "Cycle the level of an empty headline through possible states.
  5724. This goes first to child, then to parent, level, then up the hierarchy.
  5725. After top level, it switches back to sibling level."
  5726. (interactive)
  5727. (let ((org-adapt-indentation nil))
  5728. (when (org-point-at-end-of-empty-headline)
  5729. (setq this-command 'org-cycle-level) ; Only needed for caching
  5730. (let ((cur-level (org-current-level))
  5731. (prev-level (org-get-previous-line-level)))
  5732. (cond
  5733. ;; If first headline in file, promote to top-level.
  5734. ((= prev-level 0)
  5735. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5736. do (org-do-promote)))
  5737. ;; If same level as prev, demote one.
  5738. ((= prev-level cur-level)
  5739. (org-do-demote))
  5740. ;; If parent is top-level, promote to top level if not already.
  5741. ((= prev-level 1)
  5742. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5743. do (org-do-promote)))
  5744. ;; If top-level, return to prev-level.
  5745. ((= cur-level 1)
  5746. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5747. do (org-do-demote)))
  5748. ;; If less than prev-level, promote one.
  5749. ((< cur-level prev-level)
  5750. (org-do-promote))
  5751. ;; If deeper than prev-level, promote until higher than
  5752. ;; prev-level.
  5753. ((> cur-level prev-level)
  5754. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5755. do (org-do-promote))))
  5756. t))))
  5757. (defun org-map-tree (fun)
  5758. "Call FUN for every heading underneath the current one."
  5759. (org-back-to-heading t)
  5760. (let ((level (funcall outline-level)))
  5761. (save-excursion
  5762. (funcall fun)
  5763. (while (and (progn
  5764. (outline-next-heading)
  5765. (> (funcall outline-level) level))
  5766. (not (eobp)))
  5767. (funcall fun)))))
  5768. (defun org-map-region (fun beg end)
  5769. "Call FUN for every heading between BEG and END."
  5770. (let ((org-ignore-region t))
  5771. (save-excursion
  5772. (setq end (copy-marker end))
  5773. (goto-char beg)
  5774. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5775. (< (point) end))
  5776. (funcall fun))
  5777. (while (and (progn
  5778. (outline-next-heading)
  5779. (< (point) end))
  5780. (not (eobp)))
  5781. (funcall fun)))))
  5782. (defun org-fixup-indentation (diff)
  5783. "Change the indentation in the current entry by DIFF.
  5784. DIFF is an integer. Indentation is done according to the
  5785. following rules:
  5786. - Planning information and property drawers are always indented
  5787. according to the new level of the headline;
  5788. - Footnote definitions and their contents are ignored;
  5789. - Inlinetasks' boundaries are not shifted;
  5790. - Empty lines are ignored;
  5791. - Other lines' indentation are shifted by DIFF columns, unless
  5792. it would introduce a structural change in the document, in
  5793. which case no shifting is done at all.
  5794. Assume point is at a heading or an inlinetask beginning."
  5795. (org-with-wide-buffer
  5796. (narrow-to-region (line-beginning-position)
  5797. (save-excursion
  5798. (if (org-with-limited-levels (org-at-heading-p))
  5799. (org-with-limited-levels (outline-next-heading))
  5800. (org-inlinetask-goto-end))
  5801. (point)))
  5802. (forward-line)
  5803. ;; Indent properly planning info and property drawer.
  5804. (when (looking-at-p org-planning-line-re)
  5805. (org-indent-line)
  5806. (forward-line))
  5807. (when (looking-at org-property-drawer-re)
  5808. (goto-char (match-end 0))
  5809. (forward-line)
  5810. (org-indent-region (match-beginning 0) (match-end 0)))
  5811. (when (looking-at org-logbook-drawer-re)
  5812. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5813. (col (+ (current-indentation) diff)))
  5814. (when (wholenump col)
  5815. (while (< (point) end-marker)
  5816. (if (natnump diff)
  5817. (insert (make-string diff 32))
  5818. (delete-char (abs diff)))
  5819. (forward-line)))))
  5820. (catch 'no-shift
  5821. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5822. (throw 'no-shift nil))
  5823. ;; If DIFF is negative, first check if a shift is possible at all
  5824. ;; (e.g., it doesn't break structure). This can only happen if
  5825. ;; some contents are not properly indented.
  5826. (let ((case-fold-search t))
  5827. (when (< diff 0)
  5828. (let ((diff (- diff))
  5829. (forbidden-re (concat org-outline-regexp
  5830. "\\|"
  5831. (substring org-footnote-definition-re 1))))
  5832. (save-excursion
  5833. (while (not (eobp))
  5834. (cond
  5835. ((looking-at-p "[ \t]*$") (forward-line))
  5836. ((and (looking-at-p org-footnote-definition-re)
  5837. (let ((e (org-element-at-point)))
  5838. (and (eq (org-element-type e) 'footnote-definition)
  5839. (goto-char (org-element-property :end e))))))
  5840. ((looking-at-p org-outline-regexp) (forward-line))
  5841. ;; Give up if shifting would move before column 0 or
  5842. ;; if it would introduce a headline or a footnote
  5843. ;; definition.
  5844. (t
  5845. (skip-chars-forward " \t")
  5846. (let ((ind (current-column)))
  5847. (when (or (< ind diff)
  5848. (and (= ind diff) (looking-at-p forbidden-re)))
  5849. (throw 'no-shift nil)))
  5850. ;; Ignore contents of example blocks and source
  5851. ;; blocks if their indentation is meant to be
  5852. ;; preserved. Jump to block's closing line.
  5853. (beginning-of-line)
  5854. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5855. (let ((e (org-element-at-point)))
  5856. (and (memq (org-element-type e)
  5857. '(example-block src-block))
  5858. (or org-src-preserve-indentation
  5859. (org-element-property :preserve-indent e))
  5860. (goto-char (org-element-property :end e))
  5861. (progn (skip-chars-backward " \r\t\n")
  5862. (beginning-of-line)
  5863. t))))
  5864. (forward-line))))))))
  5865. ;; Shift lines but footnote definitions, inlinetasks boundaries
  5866. ;; by DIFF. Also skip contents of source or example blocks
  5867. ;; when indentation is meant to be preserved.
  5868. (while (not (eobp))
  5869. (cond
  5870. ((and (looking-at-p org-footnote-definition-re)
  5871. (let ((e (org-element-at-point)))
  5872. (and (eq (org-element-type e) 'footnote-definition)
  5873. (goto-char (org-element-property :end e))))))
  5874. ((looking-at-p org-outline-regexp) (forward-line))
  5875. ((looking-at-p "[ \t]*$") (forward-line))
  5876. (t
  5877. (indent-line-to (+ (current-indentation) diff))
  5878. (beginning-of-line)
  5879. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5880. (let ((e (org-element-at-point)))
  5881. (and (memq (org-element-type e)
  5882. '(example-block src-block))
  5883. (or org-src-preserve-indentation
  5884. (org-element-property :preserve-indent e))
  5885. (goto-char (org-element-property :end e))
  5886. (progn (skip-chars-backward " \r\t\n")
  5887. (beginning-of-line)
  5888. t))))
  5889. (forward-line)))))))))
  5890. (defun org-convert-to-odd-levels ()
  5891. "Convert an Org file with all levels allowed to one with odd levels.
  5892. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  5893. level 5 etc."
  5894. (interactive)
  5895. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  5896. (let ((outline-level 'org-outline-level)
  5897. (org-odd-levels-only nil) n)
  5898. (save-excursion
  5899. (goto-char (point-min))
  5900. (while (re-search-forward "^\\*\\*+ " nil t)
  5901. (setq n (- (length (match-string 0)) 2))
  5902. (while (>= (setq n (1- n)) 0)
  5903. (org-demote))
  5904. (end-of-line 1))))))
  5905. (defun org-convert-to-oddeven-levels ()
  5906. "Convert an Org file with only odd levels to one with odd/even levels.
  5907. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  5908. file contains a section with an even level, conversion would
  5909. destroy the structure of the file. An error is signaled in this
  5910. case."
  5911. (interactive)
  5912. (goto-char (point-min))
  5913. ;; First check if there are no even levels
  5914. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  5915. (org-fold-show-set-visibility 'canonical)
  5916. (error "Not all levels are odd in this file. Conversion not possible"))
  5917. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  5918. (let ((outline-regexp org-outline-regexp)
  5919. (outline-level 'org-outline-level)
  5920. (org-odd-levels-only nil) n)
  5921. (save-excursion
  5922. (goto-char (point-min))
  5923. (while (re-search-forward "^\\*\\*+ " nil t)
  5924. (setq n (/ (1- (length (match-string 0))) 2))
  5925. (while (>= (setq n (1- n)) 0)
  5926. (org-promote))
  5927. (end-of-line 1))))))
  5928. (defun org-tr-level (n)
  5929. "Make N odd if required."
  5930. (if org-odd-levels-only (1+ (/ n 2)) n))
  5931. ;;; Vertical tree motion, cutting and pasting of subtrees
  5932. (defun org-move-subtree-up (&optional arg)
  5933. "Move the current subtree up past ARG headlines of the same level."
  5934. (interactive "p")
  5935. (org-move-subtree-down (- (prefix-numeric-value arg))))
  5936. (defun org-clean-visibility-after-subtree-move ()
  5937. "Fix visibility issues after moving a subtree."
  5938. ;; First, find a reasonable region to look at:
  5939. ;; Start two siblings above, end three below
  5940. (let* ((beg (save-excursion
  5941. (and (org-get-previous-sibling)
  5942. (org-get-previous-sibling))
  5943. (point)))
  5944. (end (save-excursion
  5945. (and (org-get-next-sibling)
  5946. (org-get-next-sibling)
  5947. (org-get-next-sibling))
  5948. (if (org-at-heading-p)
  5949. (point-at-eol)
  5950. (point))))
  5951. (level (looking-at "\\*+"))
  5952. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5953. (save-excursion
  5954. (save-restriction
  5955. (narrow-to-region beg end)
  5956. (when re
  5957. ;; Properly fold already folded siblings
  5958. (goto-char (point-min))
  5959. (while (re-search-forward re nil t)
  5960. (when (and (not (org-invisible-p))
  5961. (org-invisible-p (line-end-position)))
  5962. (org-fold-heading nil))))
  5963. (org-cycle-hide-drawers 'all)
  5964. (org-cycle-show-empty-lines 'overview)))))
  5965. (defun org-move-subtree-down (&optional arg)
  5966. "Move the current subtree down past ARG headlines of the same level."
  5967. (interactive "p")
  5968. (setq arg (prefix-numeric-value arg))
  5969. (org-preserve-local-variables
  5970. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  5971. 'org-get-previous-sibling))
  5972. (ins-point (make-marker))
  5973. (cnt (abs arg))
  5974. (col (current-column))
  5975. beg end txt folded)
  5976. ;; Select the tree
  5977. (org-back-to-heading)
  5978. (setq beg (point))
  5979. (save-match-data
  5980. (save-excursion (outline-end-of-heading)
  5981. (setq folded (org-invisible-p)))
  5982. (progn (org-end-of-subtree nil t)
  5983. (unless (eobp) (backward-char))))
  5984. (outline-next-heading)
  5985. (setq end (point))
  5986. (goto-char beg)
  5987. ;; Find insertion point, with error handling
  5988. (while (> cnt 0)
  5989. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  5990. (goto-char beg)
  5991. (user-error "Cannot move past superior level or buffer limit"))
  5992. (setq cnt (1- cnt)))
  5993. (when (> arg 0)
  5994. ;; Moving forward - still need to move over subtree
  5995. (org-end-of-subtree t t)
  5996. (save-excursion
  5997. (org-back-over-empty-lines)
  5998. (or (bolp) (newline))))
  5999. (move-marker ins-point (point))
  6000. (setq txt (buffer-substring beg end))
  6001. (org-save-markers-in-region beg end)
  6002. (delete-region beg end)
  6003. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  6004. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6005. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6006. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6007. (let ((bbb (point)))
  6008. (insert-before-markers txt)
  6009. (org-reinstall-markers-in-region bbb)
  6010. (move-marker ins-point bbb))
  6011. (or (bolp) (insert "\n"))
  6012. (goto-char ins-point)
  6013. (org-skip-whitespace)
  6014. (move-marker ins-point nil)
  6015. (if folded
  6016. (org-fold-subtree t)
  6017. (org-fold-show-entry)
  6018. (org-fold-show-children))
  6019. (org-clean-visibility-after-subtree-move)
  6020. ;; move back to the initial column we were at
  6021. (move-to-column col))))
  6022. (defvar org-subtree-clip ""
  6023. "Clipboard for cut and paste of subtrees.
  6024. This is actually only a copy of the kill, because we use the normal kill
  6025. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6026. (defvar org-subtree-clip-folded nil
  6027. "Was the last copied subtree folded?
  6028. This is used to fold the tree back after pasting.")
  6029. (defun org-cut-subtree (&optional n)
  6030. "Cut the current subtree into the clipboard.
  6031. With prefix arg N, cut this many sequential subtrees.
  6032. This is a short-hand for marking the subtree and then cutting it."
  6033. (interactive "p")
  6034. (org-copy-subtree n 'cut))
  6035. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6036. "Copy the current subtree into the clipboard.
  6037. With prefix arg N, copy this many sequential subtrees.
  6038. This is a short-hand for marking the subtree and then copying it.
  6039. If CUT is non-nil, actually cut the subtree.
  6040. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6041. of some markers in the region, even if CUT is non-nil. This is
  6042. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6043. (interactive "p")
  6044. (org-preserve-local-variables
  6045. (let (beg end folded (beg0 (point)))
  6046. (if (called-interactively-p 'any)
  6047. (org-back-to-heading nil) ; take what looks like a subtree
  6048. (org-back-to-heading t)) ; take what is really there
  6049. (setq beg (point))
  6050. (skip-chars-forward " \t\r\n")
  6051. (save-match-data
  6052. (if nosubtrees
  6053. (outline-next-heading)
  6054. (save-excursion (outline-end-of-heading)
  6055. (setq folded (org-invisible-p)))
  6056. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6057. (org-end-of-subtree t t)))
  6058. ;; Include the end of an inlinetask
  6059. (when (and (featurep 'org-inlinetask)
  6060. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6061. "END[ \t]*$")))
  6062. (end-of-line))
  6063. (setq end (point))
  6064. (goto-char beg0)
  6065. (when (> end beg)
  6066. (setq org-subtree-clip-folded folded)
  6067. (when (or cut force-store-markers)
  6068. (org-save-markers-in-region beg end))
  6069. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6070. (setq org-subtree-clip (current-kill 0))
  6071. (message "%s: Subtree(s) with %d characters"
  6072. (if cut "Cut" "Copied")
  6073. (length org-subtree-clip))))))
  6074. (defun org-paste-subtree (&optional level tree for-yank remove)
  6075. "Paste the clipboard as a subtree, with modification of headline level.
  6076. The entire subtree is promoted or demoted in order to match a new headline
  6077. level.
  6078. If the cursor is at the beginning of a headline, the same level as
  6079. that headline is used to paste the tree.
  6080. If not, the new level is derived from the *visible* headings
  6081. before and after the insertion point, and taken to be the inferior headline
  6082. level of the two. So if the previous visible heading is level 3 and the
  6083. next is level 4 (or vice versa), level 4 will be used for insertion.
  6084. This makes sure that the subtree remains an independent subtree and does
  6085. not swallow low level entries.
  6086. You can also force a different level, either by using a numeric prefix
  6087. argument, or by inserting the heading marker by hand. For example, if the
  6088. cursor is after \"*****\", then the tree will be shifted to level 5.
  6089. If optional TREE is given, use this text instead of the kill ring.
  6090. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6091. move back over whitespace before inserting, and move point to the end of
  6092. the inserted text when done.
  6093. When REMOVE is non-nil, remove the subtree from the clipboard."
  6094. (interactive "P")
  6095. (setq tree (or tree (and kill-ring (current-kill 0))))
  6096. (unless (org-kill-is-subtree-p tree)
  6097. (user-error
  6098. (substitute-command-keys
  6099. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6100. (org-with-limited-levels
  6101. (org-fold-core-ignore-fragility-checks
  6102. (let* ((visp (not (org-invisible-p)))
  6103. (txt tree)
  6104. (old-level (if (string-match org-outline-regexp-bol txt)
  6105. (- (match-end 0) (match-beginning 0) 1)
  6106. -1))
  6107. (force-level
  6108. (cond
  6109. (level (prefix-numeric-value level))
  6110. ;; When point is after the stars in an otherwise empty
  6111. ;; headline, use the number of stars as the forced level.
  6112. ((and (org-match-line "^\\*+[ \t]*$")
  6113. (not (eq ?* (char-after))))
  6114. (org-outline-level))
  6115. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6116. (previous-level
  6117. (save-excursion
  6118. (org-previous-visible-heading 1)
  6119. (if (org-at-heading-p) (org-outline-level) 1)))
  6120. (next-level
  6121. (save-excursion
  6122. (if (org-at-heading-p) (org-outline-level)
  6123. (org-next-visible-heading 1)
  6124. (if (org-at-heading-p) (org-outline-level) 1))))
  6125. (new-level (or force-level (max previous-level next-level)))
  6126. (shift (if (or (= old-level -1)
  6127. (= new-level -1)
  6128. (= old-level new-level))
  6129. 0
  6130. (- new-level old-level)))
  6131. (delta (if (> shift 0) -1 1))
  6132. (func (if (> shift 0) #'org-demote #'org-promote))
  6133. (org-odd-levels-only nil)
  6134. beg end newend)
  6135. ;; Remove the forced level indicator.
  6136. (when (and force-level (not level))
  6137. (delete-region (line-beginning-position) (point)))
  6138. ;; Paste before the next visible heading or at end of buffer,
  6139. ;; unless point is at the beginning of a headline.
  6140. (unless (and (bolp) (org-at-heading-p))
  6141. (org-next-visible-heading 1)
  6142. (unless (bolp) (insert "\n")))
  6143. (setq beg (point))
  6144. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6145. ;; is inserted and then promoted.
  6146. (combine-change-calls beg beg
  6147. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6148. (insert-before-markers txt)
  6149. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6150. (setq newend (point))
  6151. (org-reinstall-markers-in-region beg)
  6152. (setq end (point))
  6153. (goto-char beg)
  6154. (skip-chars-forward " \t\n\r")
  6155. (setq beg (point))
  6156. (when (and (org-invisible-p) visp)
  6157. (save-excursion (org-fold-heading nil)))
  6158. ;; Shift if necessary.
  6159. (unless (= shift 0)
  6160. (save-restriction
  6161. (narrow-to-region beg end)
  6162. (while (not (= shift 0))
  6163. (org-map-region func (point-min) (point-max))
  6164. (setq shift (+ delta shift)))
  6165. (goto-char (point-min))
  6166. (setq newend (point-max)))))
  6167. (when (or for-yank (called-interactively-p 'interactive))
  6168. (message "Clipboard pasted as level %d subtree" new-level))
  6169. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6170. kill-ring
  6171. (equal org-subtree-clip (current-kill 0))
  6172. org-subtree-clip-folded)
  6173. ;; The tree was folded before it was killed/copied
  6174. (org-fold-subtree t))
  6175. (when for-yank (goto-char newend))
  6176. (when remove (pop kill-ring))))))
  6177. (defun org-kill-is-subtree-p (&optional txt)
  6178. "Check if the current kill is an outline subtree, or a set of trees.
  6179. Returns nil if kill does not start with a headline, or if the first
  6180. headline level is not the largest headline level in the tree.
  6181. So this will actually accept several entries of equal levels as well,
  6182. which is OK for `org-paste-subtree'.
  6183. If optional TXT is given, check this string instead of the current kill."
  6184. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6185. (re (org-get-limited-outline-regexp))
  6186. (^re (concat "^" re))
  6187. (start-level (and kill
  6188. (string-match
  6189. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6190. kill)
  6191. (- (match-end 2) (match-beginning 2) 1)))
  6192. (start (1+ (or (match-beginning 2) -1))))
  6193. (if (not start-level)
  6194. (progn
  6195. nil) ;; does not even start with a heading
  6196. (catch 'exit
  6197. (while (setq start (string-match ^re kill (1+ start)))
  6198. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6199. (throw 'exit nil)))
  6200. t))))
  6201. (defvar org-markers-to-move nil
  6202. "Markers that should be moved with a cut-and-paste operation.
  6203. Those markers are stored together with their positions relative to
  6204. the start of the region.")
  6205. (defun org-save-markers-in-region (beg end)
  6206. "Check markers in region.
  6207. If these markers are between BEG and END, record their position relative
  6208. to BEG, so that after moving the block of text, we can put the markers back
  6209. into place.
  6210. This function gets called just before an entry or tree gets cut from the
  6211. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6212. called immediately, to move the markers with the entries."
  6213. (setq org-markers-to-move nil)
  6214. (when (featurep 'org-clock)
  6215. (org-clock-save-markers-for-cut-and-paste beg end))
  6216. (when (featurep 'org-agenda)
  6217. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6218. (defun org-check-and-save-marker (marker beg end)
  6219. "Check if MARKER is between BEG and END.
  6220. If yes, remember the marker and the distance to BEG."
  6221. (when (and (marker-buffer marker)
  6222. (or (equal (marker-buffer marker) (current-buffer))
  6223. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6224. (>= marker beg) (< marker end))
  6225. (push (cons marker (- marker beg)) org-markers-to-move)))
  6226. (defun org-reinstall-markers-in-region (beg)
  6227. "Move all remembered markers to their position relative to BEG."
  6228. (dolist (x org-markers-to-move)
  6229. (move-marker (car x) (+ beg (cdr x))))
  6230. (setq org-markers-to-move nil))
  6231. (defun org-narrow-to-subtree (&optional element)
  6232. "Narrow buffer to the current subtree."
  6233. (interactive)
  6234. (if (org-element--cache-active-p)
  6235. (let* ((heading (org-element-lineage
  6236. (or element (org-element-at-point))
  6237. '(headline) t))
  6238. (end (org-element-property :end heading)))
  6239. (if (and heading end)
  6240. (narrow-to-region (org-element-property :begin heading)
  6241. (if (= end (point-max))
  6242. end (1- end)))
  6243. (signal 'outline-before-first-heading nil)))
  6244. (save-excursion
  6245. (save-match-data
  6246. (org-with-limited-levels
  6247. (narrow-to-region
  6248. (progn (org-back-to-heading t) (point))
  6249. (progn (org-end-of-subtree t t)
  6250. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6251. (point))))))))
  6252. (defun org-toggle-narrow-to-subtree ()
  6253. "Narrow to the subtree at point or widen a narrowed buffer."
  6254. (interactive)
  6255. (if (buffer-narrowed-p)
  6256. (progn (widen) (message "Buffer widen"))
  6257. (org-narrow-to-subtree)
  6258. (message "Buffer narrowed to current subtree")))
  6259. (defun org-narrow-to-block ()
  6260. "Narrow buffer to the current block."
  6261. (interactive)
  6262. (let* ((case-fold-search t)
  6263. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6264. "^[ \t]*#\\+end_.*")))
  6265. (if blockp
  6266. (narrow-to-region (car blockp) (cdr blockp))
  6267. (user-error "Not in a block"))))
  6268. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6269. "Clone the task (subtree) at point N times.
  6270. The clones will be inserted as siblings.
  6271. In interactive use, the user will be prompted for the number of
  6272. clones to be produced. If the entry has a timestamp, the user
  6273. will also be prompted for a time shift, which may be a repeater
  6274. as used in time stamps, for example `+3d'. To disable this,
  6275. you can call the function with a universal prefix argument.
  6276. When a valid repeater is given and the entry contains any time
  6277. stamps, the clones will become a sequence in time, with time
  6278. stamps in the subtree shifted for each clone produced. If SHIFT
  6279. is nil or the empty string, time stamps will be left alone. The
  6280. ID property of the original subtree is removed.
  6281. In each clone, all the CLOCK entries will be removed. This
  6282. prevents Org from considering that the clocked times overlap.
  6283. If the original subtree did contain time stamps with a repeater,
  6284. the following will happen:
  6285. - the repeater will be removed in each clone
  6286. - an additional clone will be produced, with the current, unshifted
  6287. date(s) in the entry.
  6288. - the original entry will be placed *after* all the clones, with
  6289. repeater intact.
  6290. - the start days in the repeater in the original entry will be shifted
  6291. to past the last clone.
  6292. In this way you can spell out a number of instances of a repeating task,
  6293. and still retain the repeater to cover future instances of the task.
  6294. As described above, N+1 clones are produced when the original
  6295. subtree has a repeater. Setting N to 0, then, can be used to
  6296. remove the repeater from a subtree and create a shifted clone
  6297. with the original repeater."
  6298. (interactive "nNumber of clones to produce: ")
  6299. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6300. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6301. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6302. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6303. (shift
  6304. (or shift
  6305. (if (and (not (equal current-prefix-arg '(4)))
  6306. (save-excursion
  6307. (goto-char beg)
  6308. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6309. (read-from-minibuffer
  6310. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6311. ""))) ;No time shift
  6312. (doshift
  6313. (and (org-string-nw-p shift)
  6314. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6315. shift)
  6316. (user-error "Invalid shift specification %s" shift)))))
  6317. (goto-char end-of-tree)
  6318. (unless (bolp) (insert "\n"))
  6319. (let* ((end (point))
  6320. (template (buffer-substring beg end))
  6321. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6322. (shift-what (pcase (and doshift (match-string 2 shift))
  6323. (`nil nil)
  6324. ("h" 'hour)
  6325. ("d" 'day)
  6326. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6327. ("m" 'month)
  6328. ("y" 'year)
  6329. (_ (error "Unsupported time unit"))))
  6330. (nmin 1)
  6331. (nmax n)
  6332. (n-no-remove -1)
  6333. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6334. (idprop (org-entry-get beg "ID")))
  6335. (when (and doshift
  6336. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6337. template))
  6338. (delete-region beg end)
  6339. (setq end beg)
  6340. (setq nmin 0)
  6341. (setq nmax (1+ nmax))
  6342. (setq n-no-remove nmax))
  6343. (goto-char end)
  6344. (cl-loop for n from nmin to nmax do
  6345. (insert
  6346. ;; Prepare clone.
  6347. (with-temp-buffer
  6348. (insert template)
  6349. (org-mode)
  6350. (goto-char (point-min))
  6351. (org-fold-show-subtree)
  6352. (and idprop (if org-clone-delete-id
  6353. (org-entry-delete nil "ID")
  6354. (org-id-get-create t)))
  6355. (unless (= n 0)
  6356. (while (re-search-forward org-clock-line-re nil t)
  6357. (delete-region (line-beginning-position)
  6358. (line-beginning-position 2)))
  6359. (goto-char (point-min))
  6360. (while (re-search-forward org-drawer-regexp nil t)
  6361. (org-remove-empty-drawer-at (point))))
  6362. (goto-char (point-min))
  6363. (when doshift
  6364. (while (re-search-forward org-ts-regexp-both nil t)
  6365. (org-timestamp-change (* n shift-n) shift-what))
  6366. (unless (= n n-no-remove)
  6367. (goto-char (point-min))
  6368. (while (re-search-forward org-ts-regexp nil t)
  6369. (save-excursion
  6370. (goto-char (match-beginning 0))
  6371. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6372. (delete-region (match-beginning 1) (match-end 1)))))))
  6373. (buffer-string)))))
  6374. (goto-char beg)))
  6375. ;;; Outline path
  6376. (defvar org-outline-path-cache nil
  6377. "Alist between buffer positions and outline paths.
  6378. It value is an alist (POSITION . PATH) where POSITION is the
  6379. buffer position at the beginning of an entry and PATH is a list
  6380. of strings describing the outline path for that entry, in reverse
  6381. order.")
  6382. (defun org--get-outline-path-1 (&optional use-cache)
  6383. "Return outline path to current headline.
  6384. Outline path is a list of strings, in reverse order. When
  6385. optional argument USE-CACHE is non-nil, make use of a cache. See
  6386. `org-get-outline-path' for details.
  6387. Assume buffer is widened and point is on a headline."
  6388. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6389. (let ((p (point))
  6390. (heading (let ((case-fold-search nil))
  6391. (looking-at org-complex-heading-regexp)
  6392. (if (not (match-end 4)) ""
  6393. ;; Remove statistics cookies.
  6394. (org-trim
  6395. (org-link-display-format
  6396. (replace-regexp-in-string
  6397. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6398. (match-string-no-properties 4))))))))
  6399. (if (org-up-heading-safe)
  6400. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6401. (when use-cache
  6402. (push (cons p path) org-outline-path-cache))
  6403. path)
  6404. ;; This is a new root node. Since we assume we are moving
  6405. ;; forward, we can drop previous cache so as to limit number
  6406. ;; of associations there.
  6407. (let ((path (list heading)))
  6408. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6409. path)))))
  6410. (defun org-get-outline-path (&optional with-self use-cache)
  6411. "Return the outline path to the current entry.
  6412. An outline path is a list of ancestors for current headline, as
  6413. a list of strings. Statistics cookies are removed and links are
  6414. replaced with their description, if any, or their path otherwise.
  6415. When optional argument WITH-SELF is non-nil, the path also
  6416. includes the current headline.
  6417. When optional argument USE-CACHE is non-nil, cache outline paths
  6418. between calls to this function so as to avoid backtracking. This
  6419. argument is useful when planning to find more than one outline
  6420. path in the same document. In that case, there are two
  6421. conditions to satisfy:
  6422. - `org-outline-path-cache' is set to nil before starting the
  6423. process;
  6424. - outline paths are computed by increasing buffer positions."
  6425. (org-with-wide-buffer
  6426. (and (or (and with-self (org-back-to-heading t))
  6427. (org-up-heading-safe))
  6428. (reverse (org--get-outline-path-1 use-cache)))))
  6429. (defun org-format-outline-path (path &optional width prefix separator)
  6430. "Format the outline path PATH for display.
  6431. WIDTH is the maximum number of characters that is available.
  6432. PREFIX is a prefix to be included in the returned string,
  6433. such as the file name.
  6434. SEPARATOR is inserted between the different parts of the path,
  6435. the default is \"/\"."
  6436. (setq width (or width 79))
  6437. (setq path (delq nil path))
  6438. (unless (> width 0)
  6439. (user-error "Argument `width' must be positive"))
  6440. (setq separator (or separator "/"))
  6441. (let* ((org-odd-levels-only nil)
  6442. (fpath (concat
  6443. prefix (and prefix path separator)
  6444. (mapconcat
  6445. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6446. (cl-loop for head in path
  6447. for n from 0
  6448. collect (org-add-props
  6449. head nil 'face
  6450. (nth (% n org-n-level-faces) org-level-faces)))
  6451. separator))))
  6452. (when (> (length fpath) width)
  6453. (if (< width 7)
  6454. ;; It's unlikely that `width' will be this small, but don't
  6455. ;; waste characters by adding ".." if it is.
  6456. (setq fpath (substring fpath 0 width))
  6457. (setf (substring fpath (- width 2)) "..")))
  6458. fpath))
  6459. (defun org-display-outline-path (&optional file current separator just-return-string)
  6460. "Display the current outline path in the echo area.
  6461. If FILE is non-nil, prepend the output with the file name.
  6462. If CURRENT is non-nil, append the current heading to the output.
  6463. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6464. the different parts of the path and defaults to \"/\".
  6465. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6466. (interactive "P")
  6467. (let* (case-fold-search
  6468. (bfn (buffer-file-name (buffer-base-buffer)))
  6469. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6470. res)
  6471. (when current (setq path (append path
  6472. (save-excursion
  6473. (org-back-to-heading t)
  6474. (when (looking-at org-complex-heading-regexp)
  6475. (list (match-string 4)))))))
  6476. (setq res
  6477. (org-format-outline-path
  6478. path
  6479. (1- (frame-width))
  6480. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6481. separator))
  6482. (add-face-text-property 0 (length res)
  6483. `(:height ,(face-attribute 'default :height))
  6484. nil res)
  6485. (if just-return-string
  6486. res
  6487. (org-unlogged-message "%s" res))))
  6488. ;;; Outline Sorting
  6489. (defun org-sort (&optional with-case)
  6490. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6491. Optional argument WITH-CASE means sort case-sensitively."
  6492. (interactive "P")
  6493. (org-call-with-arg
  6494. (cond ((org-at-table-p) #'org-table-sort-lines)
  6495. ((org-at-item-p) #'org-sort-list)
  6496. (t #'org-sort-entries))
  6497. with-case))
  6498. (defun org-sort-remove-invisible (s)
  6499. "Remove emphasis markers and any invisible property from string S.
  6500. Assume S may contain only objects."
  6501. ;; org-element-interpret-data clears any text property, including
  6502. ;; invisible part.
  6503. (org-element-interpret-data
  6504. (let ((tree (org-element-parse-secondary-string
  6505. s (org-element-restriction 'paragraph))))
  6506. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6507. (lambda (o)
  6508. (pcase (org-element-type o)
  6509. ;; Terminal object. Replace it with its value.
  6510. ((or `code `verbatim)
  6511. (let ((new (org-element-property :value o)))
  6512. (org-element-insert-before new o)
  6513. (org-element-put-property
  6514. new :post-blank (org-element-property :post-blank o))))
  6515. ;; Non-terminal objects. Splice contents.
  6516. (type
  6517. (let ((contents
  6518. (or (org-element-contents o)
  6519. (and (eq type 'link)
  6520. (list (org-element-property :raw-link o)))))
  6521. (c nil))
  6522. (while contents
  6523. (setq c (pop contents))
  6524. (org-element-insert-before c o))
  6525. (org-element-put-property
  6526. c :post-blank (org-element-property :post-blank o)))))
  6527. (org-element-extract-element o)))
  6528. ;; Return modified tree.
  6529. tree)))
  6530. (defvar org-after-sorting-entries-or-items-hook nil
  6531. "Hook that is run after a bunch of entries or items have been sorted.
  6532. When children are sorted, the cursor is in the parent line when this
  6533. hook gets called. When a region or a plain list is sorted, the cursor
  6534. will be in the first entry of the sorted region/list.")
  6535. (defun org-sort-entries
  6536. (&optional with-case sorting-type getkey-func compare-func property
  6537. interactive?)
  6538. "Sort entries on a certain level of an outline tree.
  6539. If there is an active region, the entries in the region are sorted.
  6540. Else, if the cursor is before the first entry, sort the top-level items.
  6541. Else, the children of the entry at point are sorted.
  6542. Sorting can be alphabetically, numerically, by date/time as given by
  6543. a time stamp, by a property, by priority order, or by a custom function.
  6544. The command prompts for the sorting type unless it has been given to the
  6545. function through the SORTING-TYPE argument, which needs to be a character,
  6546. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6547. the precise meaning of each character:
  6548. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6549. c By creation time, which is assumed to be the first inactive time stamp
  6550. at the beginning of a line.
  6551. d By deadline date/time.
  6552. k By clocking time.
  6553. n Numerically, by converting the beginning of the entry/item to a number.
  6554. o By order of TODO keywords.
  6555. p By priority according to the cookie.
  6556. r By the value of a property.
  6557. s By scheduled date/time.
  6558. t By date/time, either the first active time stamp in the entry, or, if
  6559. none exist, by the first inactive one.
  6560. Capital letters will reverse the sort order.
  6561. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6562. called with point at the beginning of the record. It must return a
  6563. value that is compatible with COMPARE-FUNC, the function used to
  6564. compare entries.
  6565. Comparing entries ignores case by default. However, with an optional argument
  6566. WITH-CASE, the sorting considers case as well.
  6567. Sorting is done against the visible part of the headlines, it ignores hidden
  6568. links.
  6569. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6570. A non-nil value for INTERACTIVE? is used to signal that this
  6571. function is being called interactively."
  6572. (interactive (list current-prefix-arg nil nil nil nil t))
  6573. (let ((case-func (if with-case 'identity 'downcase))
  6574. start beg end stars re re2
  6575. txt what tmp)
  6576. ;; Find beginning and end of region to sort
  6577. (cond
  6578. ((org-region-active-p)
  6579. ;; we will sort the region
  6580. (setq end (region-end)
  6581. what "region")
  6582. (goto-char (region-beginning))
  6583. (unless (org-at-heading-p) (outline-next-heading))
  6584. (setq start (point)))
  6585. ((or (org-at-heading-p)
  6586. (ignore-errors (progn (org-back-to-heading) t)))
  6587. ;; we will sort the children of the current headline
  6588. (org-back-to-heading)
  6589. (setq start (point)
  6590. end (progn (org-end-of-subtree t t)
  6591. (or (bolp) (insert "\n"))
  6592. (when (>= (org-back-over-empty-lines) 1)
  6593. (forward-line 1))
  6594. (point))
  6595. what "children")
  6596. (goto-char start)
  6597. (org-fold-show-subtree)
  6598. (outline-next-heading))
  6599. (t
  6600. ;; we will sort the top-level entries in this file
  6601. (goto-char (point-min))
  6602. (or (org-at-heading-p) (outline-next-heading))
  6603. (setq start (point))
  6604. (goto-char (point-max))
  6605. (beginning-of-line 1)
  6606. (when (looking-at ".*?\\S-")
  6607. ;; File ends in a non-white line
  6608. (end-of-line 1)
  6609. (insert "\n"))
  6610. (setq end (point-max))
  6611. (setq what "top-level")
  6612. (goto-char start)
  6613. (org-fold-show-all '(headings drawers blocks))))
  6614. (setq beg (point))
  6615. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6616. (looking-at "\\(\\*+\\)")
  6617. (setq stars (match-string 1)
  6618. re (concat "^" (regexp-quote stars) " +")
  6619. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6620. txt (buffer-substring beg end))
  6621. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6622. (when (and (not (equal stars "*")) (string-match re2 txt))
  6623. (user-error "Region to sort contains a level above the first entry"))
  6624. (unless sorting-type
  6625. (message
  6626. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6627. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6628. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6629. what)
  6630. (setq sorting-type (read-char-exclusive)))
  6631. (unless getkey-func
  6632. (and (= (downcase sorting-type) ?f)
  6633. (setq getkey-func
  6634. (or (and interactive?
  6635. (org-read-function
  6636. "Function for extracting keys: "))
  6637. (error "Missing key extractor")))))
  6638. (and (= (downcase sorting-type) ?r)
  6639. (not property)
  6640. (setq property
  6641. (completing-read "Property: "
  6642. (mapcar #'list (org-buffer-property-keys t))
  6643. nil t)))
  6644. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6645. (message "Sorting entries...")
  6646. (save-restriction
  6647. (narrow-to-region start end)
  6648. (let ((restore-clock?
  6649. ;; The clock marker is lost when using `sort-subr'; mark
  6650. ;; the clock with temporary `:org-clock-marker-backup'
  6651. ;; text property.
  6652. (when (and (eq (org-clocking-buffer) (current-buffer))
  6653. (<= start (marker-position org-clock-marker))
  6654. (>= end (marker-position org-clock-marker)))
  6655. (with-silent-modifications
  6656. (put-text-property (1- org-clock-marker) org-clock-marker
  6657. :org-clock-marker-backup t))
  6658. t))
  6659. (dcst (downcase sorting-type))
  6660. (case-fold-search nil)
  6661. (now (current-time)))
  6662. (org-preserve-local-variables
  6663. (sort-subr
  6664. (/= dcst sorting-type)
  6665. ;; This function moves to the beginning character of the
  6666. ;; "record" to be sorted.
  6667. (lambda nil
  6668. (if (re-search-forward re nil t)
  6669. (goto-char (match-beginning 0))
  6670. (goto-char (point-max))))
  6671. ;; This function moves to the last character of the "record" being
  6672. ;; sorted.
  6673. (lambda nil
  6674. (save-match-data
  6675. (condition-case nil
  6676. (outline-forward-same-level 1)
  6677. (error
  6678. (goto-char (point-max))))))
  6679. ;; This function returns the value that gets sorted against.
  6680. (lambda ()
  6681. (cond
  6682. ((= dcst ?n)
  6683. (string-to-number
  6684. (org-sort-remove-invisible (org-get-heading t t t t))))
  6685. ((= dcst ?a)
  6686. (funcall case-func
  6687. (org-sort-remove-invisible (org-get-heading t t t t))))
  6688. ((= dcst ?k)
  6689. (or (get-text-property (point) :org-clock-minutes) 0))
  6690. ((= dcst ?t)
  6691. (let ((end (save-excursion (outline-next-heading) (point))))
  6692. (if (or (re-search-forward org-ts-regexp end t)
  6693. (re-search-forward org-ts-regexp-both end t))
  6694. (org-time-string-to-seconds (match-string 0))
  6695. (float-time now))))
  6696. ((= dcst ?c)
  6697. (let ((end (save-excursion (outline-next-heading) (point))))
  6698. (if (re-search-forward
  6699. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6700. end t)
  6701. (org-time-string-to-seconds (match-string 0))
  6702. (float-time now))))
  6703. ((= dcst ?s)
  6704. (let ((end (save-excursion (outline-next-heading) (point))))
  6705. (if (re-search-forward org-scheduled-time-regexp end t)
  6706. (org-time-string-to-seconds (match-string 1))
  6707. (float-time now))))
  6708. ((= dcst ?d)
  6709. (let ((end (save-excursion (outline-next-heading) (point))))
  6710. (if (re-search-forward org-deadline-time-regexp end t)
  6711. (org-time-string-to-seconds (match-string 1))
  6712. (float-time now))))
  6713. ((= dcst ?p)
  6714. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  6715. (string-to-char (match-string 2))
  6716. org-priority-default))
  6717. ((= dcst ?r)
  6718. (or (org-entry-get nil property) ""))
  6719. ((= dcst ?o)
  6720. (when (looking-at org-complex-heading-regexp)
  6721. (let* ((m (match-string 2))
  6722. (s (if (member m org-done-keywords) '- '+)))
  6723. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6724. ((= dcst ?f)
  6725. (if getkey-func
  6726. (progn
  6727. (setq tmp (funcall getkey-func))
  6728. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6729. tmp)
  6730. (error "Invalid key function `%s'" getkey-func)))
  6731. (t (error "Invalid sorting type `%c'" sorting-type))))
  6732. nil
  6733. (cond
  6734. ((= dcst ?a) 'string-collate-lessp)
  6735. ((= dcst ?f)
  6736. (or compare-func
  6737. (and interactive?
  6738. (org-read-function
  6739. (concat "Function for comparing keys "
  6740. "(empty for default `sort-subr' predicate): ")
  6741. 'allow-empty))))
  6742. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6743. (org-cycle-hide-drawers 'all)
  6744. (when restore-clock?
  6745. (move-marker org-clock-marker
  6746. (1+ (next-single-property-change
  6747. start :org-clock-marker-backup)))
  6748. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6749. '(:org-clock-marker-backup t)))))
  6750. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6751. (message "Sorting entries...done")))
  6752. (defun org-contextualize-keys (alist contexts)
  6753. "Return valid elements in ALIST depending on CONTEXTS.
  6754. `org-agenda-custom-commands' or `org-capture-templates' are the
  6755. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6756. or `org-capture-templates-contexts' are the associated contexts
  6757. definitions."
  6758. (let ((contexts
  6759. ;; normalize contexts
  6760. (mapcar
  6761. (lambda(c) (cond ((listp (cadr c))
  6762. (list (car c) (car c) (nth 1 c)))
  6763. ((string= "" (cadr c))
  6764. (list (car c) (car c) (nth 2 c)))
  6765. (t c)))
  6766. contexts))
  6767. (a alist) r s)
  6768. ;; loop over all commands or templates
  6769. (dolist (c a)
  6770. (let (vrules repl)
  6771. (cond
  6772. ((not (assoc (car c) contexts))
  6773. (push c r))
  6774. ((and (assoc (car c) contexts)
  6775. (setq vrules (org-contextualize-validate-key
  6776. (car c) contexts)))
  6777. (mapc (lambda (vr)
  6778. (unless (equal (car vr) (cadr vr))
  6779. (setq repl vr)))
  6780. vrules)
  6781. (if (not repl) (push c r)
  6782. (push (cadr repl) s)
  6783. (push
  6784. (cons (car c)
  6785. (cdr (or (assoc (cadr repl) alist)
  6786. (error "Undefined key `%s' as contextual replacement for `%s'"
  6787. (cadr repl) (car c)))))
  6788. r))))))
  6789. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6790. (delq
  6791. nil
  6792. (delete-dups
  6793. (mapcar (lambda (x)
  6794. (let ((tpl (car x)))
  6795. (unless (delq
  6796. nil
  6797. (mapcar (lambda (y)
  6798. (equal y tpl))
  6799. s))
  6800. x)))
  6801. (reverse r))))))
  6802. (defun org-contextualize-validate-key (key contexts)
  6803. "Check CONTEXTS for agenda or capture KEY."
  6804. (let (res)
  6805. (dolist (r contexts)
  6806. (dolist (rr (car (last r)))
  6807. (when
  6808. (and (equal key (car r))
  6809. (if (functionp rr) (funcall rr)
  6810. (or (and (eq (car rr) 'in-file)
  6811. (buffer-file-name)
  6812. (string-match (cdr rr) (buffer-file-name)))
  6813. (and (eq (car rr) 'in-mode)
  6814. (string-match (cdr rr) (symbol-name major-mode)))
  6815. (and (eq (car rr) 'in-buffer)
  6816. (string-match (cdr rr) (buffer-name)))
  6817. (when (and (eq (car rr) 'not-in-file)
  6818. (buffer-file-name))
  6819. (not (string-match (cdr rr) (buffer-file-name))))
  6820. (when (eq (car rr) 'not-in-mode)
  6821. (not (string-match (cdr rr) (symbol-name major-mode))))
  6822. (when (eq (car rr) 'not-in-buffer)
  6823. (not (string-match (cdr rr) (buffer-name)))))))
  6824. (push r res))))
  6825. (delete-dups (delq nil res))))
  6826. ;; Defined to provide a value for defcustom, since there is no
  6827. ;; string-collate-greaterp in Emacs.
  6828. (defun org-string-collate-greaterp (s1 s2)
  6829. "Return non-nil if S1 is greater than S2 in collation order."
  6830. (not (string-collate-lessp s1 s2)))
  6831. ;;;###autoload
  6832. (defun org-run-like-in-org-mode (cmd)
  6833. "Run a command, pretending that the current buffer is in Org mode.
  6834. This will temporarily bind local variables that are typically bound in
  6835. Org mode to the values they have in Org mode, and then interactively
  6836. call CMD."
  6837. (org-load-modules-maybe)
  6838. (let (vars vals)
  6839. (dolist (var (org-get-local-variables))
  6840. (when (or (not (boundp (car var)))
  6841. (eq (symbol-value (car var))
  6842. (default-value (car var))))
  6843. (push (car var) vars)
  6844. (push (cadr var) vals)))
  6845. (cl-progv vars vals
  6846. (call-interactively cmd))))
  6847. (defun org-get-category (&optional pos force-refresh)
  6848. "Get the category applying to position POS."
  6849. (save-match-data
  6850. (when force-refresh (org-refresh-category-properties))
  6851. (let ((pos (or pos (point))))
  6852. (if (org-element--cache-active-p)
  6853. ;; Sync cache.
  6854. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  6855. (or (org-entry-get-with-inheritance "CATEGORY")
  6856. "???"))
  6857. (or (get-text-property pos 'org-category)
  6858. (progn
  6859. (org-refresh-category-properties)
  6860. (get-text-property pos 'org-category)))))))
  6861. ;;; Refresh properties
  6862. (defun org-refresh-properties (dprop tprop)
  6863. "Refresh buffer text properties.
  6864. DPROP is the drawer property and TPROP is either the
  6865. corresponding text property to set, or an alist with each element
  6866. being a text property (as a symbol) and a function to apply to
  6867. the value of the drawer property."
  6868. (let* ((case-fold-search t)
  6869. (inhibit-read-only t)
  6870. (inherit? (org-property-inherit-p dprop))
  6871. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  6872. (global-or-keyword (and inherit?
  6873. (org--property-global-or-keyword-value dprop nil))))
  6874. (with-silent-modifications
  6875. (org-with-point-at 1
  6876. ;; Set global and keyword based values to the whole buffer.
  6877. (when global-or-keyword
  6878. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  6879. ;; Set values based on property-drawers throughout the document.
  6880. (while (re-search-forward property-re nil t)
  6881. (when (org-at-property-p)
  6882. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  6883. (outline-next-heading))))))
  6884. (defun org-refresh-property (tprop p &optional inherit)
  6885. "Refresh the buffer text property TPROP from the drawer property P.
  6886. The refresh happens only for the current entry, or the whole
  6887. sub-tree if optional argument INHERIT is non-nil.
  6888. If point is before first headline, the function applies to the
  6889. part before the first headline. In that particular case, when
  6890. optional argument INHERIT is non-nil, it refreshes properties for
  6891. the whole buffer."
  6892. (save-excursion
  6893. (org-back-to-heading-or-point-min t)
  6894. (let ((start (point))
  6895. (end (save-excursion
  6896. (cond ((and inherit (org-before-first-heading-p))
  6897. (point-max))
  6898. (inherit
  6899. (org-end-of-subtree t t))
  6900. ((outline-next-heading))
  6901. ((point-max))))))
  6902. (with-silent-modifications
  6903. (if (symbolp tprop)
  6904. ;; TPROP is a text property symbol.
  6905. (put-text-property start end tprop p)
  6906. ;; TPROP is an alist with (property . function) elements.
  6907. (pcase-dolist (`(,prop . ,f) tprop)
  6908. (put-text-property start end prop (funcall f p))))))))
  6909. (defun org-refresh-category-properties ()
  6910. "Refresh category text properties in the buffer."
  6911. (unless (org-element--cache-active-p)
  6912. (let ((case-fold-search t)
  6913. (inhibit-read-only t)
  6914. (default-category
  6915. (cond ((null org-category)
  6916. (if buffer-file-name
  6917. (file-name-sans-extension
  6918. (file-name-nondirectory buffer-file-name))
  6919. "???"))
  6920. ((symbolp org-category) (symbol-name org-category))
  6921. (t org-category))))
  6922. (let ((category (catch 'buffer-category
  6923. (org-with-wide-buffer
  6924. (goto-char (point-max))
  6925. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  6926. (let ((element (org-element-at-point-no-context)))
  6927. (when (eq (org-element-type element) 'keyword)
  6928. (throw 'buffer-category
  6929. (org-element-property :value element))))))
  6930. default-category)))
  6931. (with-silent-modifications
  6932. (org-with-wide-buffer
  6933. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  6934. ;; keyword. If none is found, fall-back to `org-category' or
  6935. ;; buffer file name, or set it by the document property drawer.
  6936. (put-text-property (point-min) (point-max)
  6937. 'org-category category)
  6938. ;; Set categories from the document property drawer or
  6939. ;; property drawers in the outline. If category is found in
  6940. ;; the property drawer for the whole buffer that value
  6941. ;; overrides the keyword-based value set above.
  6942. (goto-char (point-min))
  6943. (let ((regexp (org-re-property "CATEGORY")))
  6944. (while (re-search-forward regexp nil t)
  6945. (let ((value (match-string-no-properties 3)))
  6946. (when (org-at-property-p)
  6947. (put-text-property
  6948. (save-excursion (org-back-to-heading-or-point-min t))
  6949. (save-excursion (if (org-before-first-heading-p)
  6950. (point-max)
  6951. (org-end-of-subtree t t)))
  6952. 'org-category
  6953. value)))))))))))
  6954. (defun org-refresh-stats-properties ()
  6955. "Refresh stats text properties in the buffer."
  6956. (with-silent-modifications
  6957. (org-with-point-at 1
  6958. (let ((regexp (concat org-outline-regexp-bol
  6959. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  6960. (while (re-search-forward regexp nil t)
  6961. (let* ((numerator (string-to-number (match-string 1)))
  6962. (denominator (and (match-end 2)
  6963. (string-to-number (match-string 2))))
  6964. (stats (cond ((not denominator) numerator) ;percent
  6965. ((= denominator 0) 0)
  6966. (t (/ (* numerator 100) denominator)))))
  6967. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  6968. 'org-stats stats)))))))
  6969. (defun org-refresh-effort-properties ()
  6970. "Refresh effort properties."
  6971. (org-refresh-properties
  6972. org-effort-property
  6973. '((effort . identity)
  6974. (effort-minutes . org-duration-to-minutes))))
  6975. (defun org-find-file-at-mouse (ev)
  6976. "Open file link or URL at mouse."
  6977. (interactive "e")
  6978. (mouse-set-point ev)
  6979. (org-open-at-point 'in-emacs))
  6980. (defun org-open-at-mouse (ev)
  6981. "Open file link or URL at mouse.
  6982. See the docstring of `org-open-file' for details."
  6983. (interactive "e")
  6984. (mouse-set-point ev)
  6985. (when (eq major-mode 'org-agenda-mode)
  6986. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  6987. (org-open-at-point))
  6988. (defvar org-window-config-before-follow-link nil
  6989. "The window configuration before following a link.
  6990. This is saved in case the need arises to restore it.")
  6991. (defun org--file-default-apps ()
  6992. "Return the default applications for this operating system."
  6993. (pcase system-type
  6994. (`darwin org-file-apps-macos)
  6995. (`windows-nt org-file-apps-windowsnt)
  6996. (_ org-file-apps-gnu)))
  6997. (defun org--file-apps-entry-dlink-p (entry)
  6998. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  6999. It assumes that is the case when the entry uses a regular
  7000. expression which has at least one grouping construct and the
  7001. action is either a Lisp form or a command string containing
  7002. \"%1\", i.e., using at least one subexpression match as
  7003. a parameter."
  7004. (pcase entry
  7005. (`(,selector . ,action)
  7006. (and (stringp selector)
  7007. (> (regexp-opt-depth selector) 0)
  7008. (or (and (stringp action)
  7009. (string-match "%[0-9]" action))
  7010. (consp action))))
  7011. (_ nil)))
  7012. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7013. "Convert extensions to regular expressions in the cars of LIST.
  7014. Also, weed out any non-string entries, because the return value
  7015. is used only for regexp matching.
  7016. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7017. point to the symbol `emacs', indicating that the file should be
  7018. opened in Emacs."
  7019. (append
  7020. (delq nil
  7021. (mapcar (lambda (x)
  7022. (unless (not (stringp (car x)))
  7023. (if (string-match "\\W" (car x))
  7024. x
  7025. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7026. list))
  7027. (when add-auto-mode
  7028. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7029. ;;;###autoload
  7030. (defun org-open-file (path &optional in-emacs line search)
  7031. "Open the file at PATH.
  7032. First, this expands any special file name abbreviations. Then the
  7033. configuration variable `org-file-apps' is checked if it contains an
  7034. entry for this file type, and if yes, the corresponding command is launched.
  7035. If no application is found, Emacs simply visits the file.
  7036. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7037. With a double \\[universal-argument] \\[universal-argument] \
  7038. prefix arg, Org tries to avoid opening in Emacs
  7039. and to use an external application to visit the file.
  7040. Optional LINE specifies a line to go to, optional SEARCH a string
  7041. to search for. If LINE or SEARCH is given, the file will be
  7042. opened in Emacs, unless an entry from `org-file-apps' that makes
  7043. use of groups in a regexp matches.
  7044. If you want to change the way frames are used when following a
  7045. link, please customize `org-link-frame-setup'.
  7046. If the file does not exist, throw an error."
  7047. (let* ((file (if (equal path "") buffer-file-name
  7048. (substitute-in-file-name (expand-file-name path))))
  7049. (file-apps (append org-file-apps (org--file-default-apps)))
  7050. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7051. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7052. file-apps))
  7053. (remp (and (assq 'remote apps) (file-remote-p file)))
  7054. (dirp (unless remp (file-directory-p file)))
  7055. (file (if (and dirp org-open-directory-means-index-dot-org)
  7056. (concat (file-name-as-directory file) "index.org")
  7057. file))
  7058. (a-m-a-p (assq 'auto-mode apps))
  7059. (dfile (downcase file))
  7060. ;; Reconstruct the original link from the PATH, LINE and
  7061. ;; SEARCH args.
  7062. (link (cond (line (concat file "::" (number-to-string line)))
  7063. (search (concat file "::" search))
  7064. (t file)))
  7065. (dlink (downcase link))
  7066. (ext
  7067. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7068. (match-string 1 dfile)))
  7069. (save-position-maybe
  7070. (let ((old-buffer (current-buffer))
  7071. (old-pos (point))
  7072. (old-mode major-mode))
  7073. (lambda ()
  7074. (and (derived-mode-p 'org-mode)
  7075. (eq old-mode 'org-mode)
  7076. (or (not (eq old-buffer (current-buffer)))
  7077. (not (eq old-pos (point))))
  7078. (org-mark-ring-push old-pos old-buffer)))))
  7079. cmd link-match-data)
  7080. (cond
  7081. ((member in-emacs '((16) system))
  7082. (setq cmd (cdr (assq 'system apps))))
  7083. (in-emacs (setq cmd 'emacs))
  7084. (t
  7085. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7086. (and dirp (cdr (assq 'directory apps)))
  7087. ;; First, try matching against apps-dlink if we
  7088. ;; get a match here, store the match data for
  7089. ;; later.
  7090. (let ((match (assoc-default dlink apps-dlink
  7091. 'string-match)))
  7092. (if match
  7093. (progn (setq link-match-data (match-data))
  7094. match)
  7095. (progn (setq in-emacs (or in-emacs line search))
  7096. nil))) ; if we have no match in apps-dlink,
  7097. ; always open the file in emacs if line or search
  7098. ; is given (for backwards compatibility)
  7099. (assoc-default dfile
  7100. (org--file-apps-regexp-alist apps a-m-a-p)
  7101. 'string-match)
  7102. (cdr (assoc ext apps))
  7103. (cdr (assq t apps))))))
  7104. (when (eq cmd 'system)
  7105. (setq cmd (cdr (assq 'system apps))))
  7106. (when (eq cmd 'default)
  7107. (setq cmd (cdr (assoc t apps))))
  7108. (when (eq cmd 'mailcap)
  7109. (require 'mailcap)
  7110. (mailcap-parse-mailcaps)
  7111. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7112. (command (mailcap-mime-info mime-type)))
  7113. (if (stringp command)
  7114. (setq cmd command)
  7115. (setq cmd 'emacs))))
  7116. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7117. (not (file-exists-p file))
  7118. (not org-open-non-existing-files))
  7119. (user-error "No such file: %s" file))
  7120. (cond
  7121. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7122. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7123. (while (string-match "['\"]%s['\"]" cmd)
  7124. (setq cmd (replace-match "%s" t t cmd)))
  7125. (setq cmd (replace-regexp-in-string
  7126. "%s"
  7127. (shell-quote-argument (convert-standard-filename file))
  7128. cmd
  7129. nil t))
  7130. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7131. (save-match-data
  7132. (let ((match-index 1)
  7133. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7134. (set-match-data link-match-data)
  7135. (while (<= match-index number-of-groups)
  7136. (let ((regex (concat "%" (number-to-string match-index)))
  7137. (replace-with (match-string match-index dlink)))
  7138. (while (string-match regex cmd)
  7139. (setq cmd (replace-match replace-with t t cmd))))
  7140. (setq match-index (+ match-index 1)))))
  7141. (save-window-excursion
  7142. (message "Running %s...done" cmd)
  7143. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7144. ;; and exit immediately. Use pipe connection type instead of pty to
  7145. ;; avoid killing children processes with SIGHUP when temporary terminal
  7146. ;; session is finished.
  7147. ;;
  7148. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7149. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7150. ;; error messages.
  7151. (let ((process-connection-type nil))
  7152. (start-process-shell-command cmd nil cmd))
  7153. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7154. ((or (stringp cmd)
  7155. (eq cmd 'emacs))
  7156. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7157. (widen)
  7158. (cond (line (org-goto-line line)
  7159. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7160. (search (condition-case err
  7161. (org-link-search search)
  7162. ;; Save position before error-ing out so user
  7163. ;; can easily move back to the original buffer.
  7164. (error (funcall save-position-maybe)
  7165. (error (nth 1 err)))))))
  7166. ((functionp cmd)
  7167. (save-match-data
  7168. (set-match-data link-match-data)
  7169. (condition-case nil
  7170. (funcall cmd file link)
  7171. ;; FIXME: Remove this check when most default installations
  7172. ;; of Emacs have at least Org 9.0.
  7173. ((debug wrong-number-of-arguments wrong-type-argument
  7174. invalid-function)
  7175. (user-error "Please see Org News for version 9.0 about \
  7176. `org-file-apps'--Lisp error: %S" cmd)))))
  7177. ((consp cmd)
  7178. ;; FIXME: Remove this check when most default installations of
  7179. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7180. ;; fall back to `org-link-frame-setup' for an old usage of
  7181. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7182. (user-error "Please see Org News for version 9.0 about \
  7183. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7184. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7185. (funcall save-position-maybe)))
  7186. ;;;###autoload
  7187. (defun org-open-at-point-global ()
  7188. "Follow a link or a time-stamp like Org mode does.
  7189. Also follow links and emails as seen by `thing-at-point'.
  7190. This command can be called in any mode to follow an external
  7191. link or a time-stamp that has Org mode syntax. Its behavior
  7192. is undefined when called on internal links like fuzzy links.
  7193. Raise a user error when there is nothing to follow."
  7194. (interactive)
  7195. (let ((tap-url (thing-at-point 'url))
  7196. (tap-email (thing-at-point 'email)))
  7197. (cond ((org-in-regexp org-link-any-re)
  7198. (org-link-open-from-string (match-string-no-properties 0)))
  7199. ((or (org-in-regexp org-ts-regexp-both nil t)
  7200. (org-in-regexp org-tsr-regexp-both nil t))
  7201. (org-follow-timestamp-link))
  7202. (tap-url (org-link-open-from-string tap-url))
  7203. (tap-email (org-link-open-from-string
  7204. (concat "mailto:" tap-email)))
  7205. (t (user-error "No link found")))))
  7206. (defvar org-open-at-point-functions nil
  7207. "Hook that is run when following a link at point.
  7208. Functions in this hook must return t if they identify and follow
  7209. a link at point. If they don't find anything interesting at point,
  7210. they must return nil.")
  7211. (defun org-open-at-point (&optional arg)
  7212. "Open link, timestamp, footnote or tags at point.
  7213. When point is on a link, follow it. Normally, files will be
  7214. opened by an appropriate application. If the optional prefix
  7215. argument ARG is non-nil, Emacs will visit the file. With
  7216. a double prefix argument, try to open outside of Emacs, in the
  7217. application the system uses for this file type.
  7218. When point is on a timestamp, open the agenda at the day
  7219. specified.
  7220. When point is a footnote definition, move to the first reference
  7221. found. If it is on a reference, move to the associated
  7222. definition.
  7223. When point is on a headline, display a list of every link in the
  7224. entry, so it is possible to pick one, or all, of them. If point
  7225. is on a tag, call `org-tags-view' instead.
  7226. On top of syntactically correct links, this function also tries
  7227. to open links and time-stamps in comments, node properties, and
  7228. keywords if point is on something looking like a timestamp or
  7229. a link."
  7230. (interactive "P")
  7231. (org-load-modules-maybe)
  7232. (setq org-window-config-before-follow-link (current-window-configuration))
  7233. (org-remove-occur-highlights nil nil t)
  7234. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7235. (let* ((context
  7236. ;; Only consider supported types, even if they are not the
  7237. ;; closest one.
  7238. (org-element-lineage
  7239. (org-element-context)
  7240. '(citation citation-reference clock comment comment-block
  7241. footnote-definition footnote-reference headline
  7242. inline-src-block inlinetask keyword link node-property
  7243. planning src-block timestamp)
  7244. t))
  7245. (type (org-element-type context))
  7246. (value (org-element-property :value context)))
  7247. (cond
  7248. ((not type) (user-error "No link found"))
  7249. ;; No valid link at point. For convenience, look if something
  7250. ;; looks like a link under point in some specific places.
  7251. ((memq type '(comment comment-block node-property keyword))
  7252. (call-interactively #'org-open-at-point-global))
  7253. ;; On a headline or an inlinetask, but not on a timestamp,
  7254. ;; a link, a footnote reference or a citation.
  7255. ((memq type '(headline inlinetask))
  7256. (org-match-line org-complex-heading-regexp)
  7257. (let ((tags-beg (match-beginning 5))
  7258. (tags-end (match-end 5)))
  7259. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7260. ;; On tags.
  7261. (org-tags-view
  7262. arg
  7263. (save-excursion
  7264. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7265. (end-tag (search-forward ":" tags-end nil 2)))
  7266. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7267. ;; Not on tags.
  7268. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7269. (`(nil . ,_)
  7270. (require 'org-attach)
  7271. (when (org-attach-dir)
  7272. (message "Opening attachment")
  7273. (if (equal arg '(4))
  7274. (org-attach-reveal-in-emacs)
  7275. (org-attach-reveal))))
  7276. (`(,links . ,links-end)
  7277. (dolist (link (if (stringp links) (list links) links))
  7278. (search-forward link nil links-end)
  7279. (goto-char (match-beginning 0))
  7280. (org-open-at-point arg)))))))
  7281. ;; On a footnote reference or at definition's label.
  7282. ((or (eq type 'footnote-reference)
  7283. (and (eq type 'footnote-definition)
  7284. (save-excursion
  7285. ;; Do not validate action when point is on the
  7286. ;; spaces right after the footnote label, in order
  7287. ;; to be on par with behavior on links.
  7288. (skip-chars-forward " \t")
  7289. (let ((begin
  7290. (org-element-property :contents-begin context)))
  7291. (if begin (< (point) begin)
  7292. (= (org-element-property :post-affiliated context)
  7293. (line-beginning-position)))))))
  7294. (org-footnote-action))
  7295. ;; On a planning line. Check if we are really on a timestamp.
  7296. ((and (eq type 'planning)
  7297. (org-in-regexp org-ts-regexp-both nil t))
  7298. (org-follow-timestamp-link))
  7299. ;; On a clock line, make sure point is on the timestamp
  7300. ;; before opening it.
  7301. ((and (eq type 'clock)
  7302. value
  7303. (>= (point) (org-element-property :begin value))
  7304. (<= (point) (org-element-property :end value)))
  7305. (org-follow-timestamp-link))
  7306. ((eq type 'src-block) (org-babel-open-src-block-result))
  7307. ;; Do nothing on white spaces after an object.
  7308. ((>= (point)
  7309. (save-excursion
  7310. (goto-char (org-element-property :end context))
  7311. (skip-chars-backward " \t")
  7312. (point)))
  7313. (user-error "No link found"))
  7314. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7315. ((eq type 'timestamp) (org-follow-timestamp-link))
  7316. ((eq type 'link) (org-link-open context arg))
  7317. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7318. (t (user-error "No link found")))))
  7319. (run-hook-with-args 'org-follow-link-hook))
  7320. ;;;###autoload
  7321. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7322. "Offer links in the current entry and return the selected link.
  7323. If there is only one link, return it.
  7324. If NTH is an integer, return the NTH link found.
  7325. If ZERO is a string, check also this string for a link, and if
  7326. there is one, return it."
  7327. (with-current-buffer buffer
  7328. (org-with-wide-buffer
  7329. (goto-char marker)
  7330. (let ((cnt ?0)
  7331. have-zero end links link c)
  7332. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7333. (push (match-string 0 zero) links)
  7334. (setq cnt (1- cnt) have-zero t))
  7335. (save-excursion
  7336. (org-back-to-heading t)
  7337. (setq end (save-excursion (outline-next-heading) (point)))
  7338. (while (re-search-forward org-link-any-re end t)
  7339. (push (match-string 0) links))
  7340. (setq links (org-uniquify (reverse links))))
  7341. (cond
  7342. ((null links)
  7343. (message "No links"))
  7344. ((equal (length links) 1)
  7345. (setq link (car links)))
  7346. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7347. (setq link (nth (if have-zero nth (1- nth)) links)))
  7348. (t ; we have to select a link
  7349. (save-excursion
  7350. (save-window-excursion
  7351. (delete-other-windows)
  7352. (with-output-to-temp-buffer "*Select Link*"
  7353. (dolist (l links)
  7354. (cond
  7355. ((not (string-match org-link-bracket-re l))
  7356. (princ (format "[%c] %s\n" (cl-incf cnt)
  7357. (org-unbracket-string "<" ">" l))))
  7358. ((match-end 2)
  7359. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7360. (match-string 2 l) (match-string 1 l))))
  7361. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7362. (match-string 1 l)))))))
  7363. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7364. (message "Select link to open, RET to open all:")
  7365. (setq c (read-char-exclusive))
  7366. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7367. (when (equal c ?q) (user-error "Abort"))
  7368. (if (equal c ?\C-m)
  7369. (setq link links)
  7370. (setq nth (- c ?0))
  7371. (when have-zero (setq nth (1+ nth)))
  7372. (unless (and (integerp nth) (>= (length links) nth))
  7373. (user-error "Invalid link selection"))
  7374. (setq link (nth (1- nth) links)))))
  7375. (cons link end)))))
  7376. ;;; File search
  7377. (defun org-do-occur (regexp &optional cleanup)
  7378. "Call the Emacs command `occur'.
  7379. If CLEANUP is non-nil, remove the printout of the regular expression
  7380. in the *Occur* buffer. This is useful if the regex is long and not useful
  7381. to read."
  7382. (occur regexp)
  7383. (when cleanup
  7384. (let ((cwin (selected-window)) win beg end)
  7385. (when (setq win (get-buffer-window "*Occur*"))
  7386. (select-window win))
  7387. (goto-char (point-min))
  7388. (when (re-search-forward "match[a-z]+" nil t)
  7389. (setq beg (match-end 0))
  7390. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7391. (setq end (1- (match-beginning 0)))))
  7392. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7393. (goto-char (point-min))
  7394. (select-window cwin))))
  7395. ;;; The Mark Ring
  7396. (defvar org-mark-ring nil
  7397. "Mark ring for positions before jumps in Org mode.")
  7398. (defvar org-mark-ring-last-goto nil
  7399. "Last position in the mark ring used to go back.")
  7400. ;; Fill and close the ring
  7401. (setq org-mark-ring nil)
  7402. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7403. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7404. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7405. org-mark-ring)
  7406. (defun org-mark-ring-push (&optional pos buffer)
  7407. "Put the current position into the mark ring and rotate it.
  7408. Also push position into the Emacs mark ring. If optional
  7409. argument POS and BUFFER are not nil, mark this location instead."
  7410. (interactive)
  7411. (let ((pos (or pos (point)))
  7412. (buffer (or buffer (current-buffer))))
  7413. (with-current-buffer buffer
  7414. (org-with-point-at pos (push-mark nil t)))
  7415. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7416. (move-marker (car org-mark-ring) pos buffer))
  7417. (message
  7418. (substitute-command-keys
  7419. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7420. (defun org-mark-ring-goto (&optional n)
  7421. "Jump to the previous position in the mark ring.
  7422. With prefix arg N, jump back that many stored positions. When
  7423. called several times in succession, walk through the entire ring.
  7424. Org mode commands jumping to a different position in the current file,
  7425. or to another Org file, automatically push the old position onto the ring."
  7426. (interactive "p")
  7427. (let (p m)
  7428. (if (eq last-command this-command)
  7429. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7430. (setq p org-mark-ring))
  7431. (setq org-mark-ring-last-goto p)
  7432. (setq m (car p))
  7433. (pop-to-buffer-same-window (marker-buffer m))
  7434. (goto-char m)
  7435. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7436. ;;; Following specific links
  7437. (defvar org-agenda-buffer-tmp-name)
  7438. (defvar org-agenda-start-on-weekday)
  7439. (defvar org-agenda-buffer-name)
  7440. (defun org-follow-timestamp-link ()
  7441. "Open an agenda view for the time-stamp date/range at point."
  7442. ;; Avoid changing the global value.
  7443. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7444. (cond
  7445. ((org-at-date-range-p t)
  7446. (let ((org-agenda-start-on-weekday)
  7447. (t1 (match-string 1))
  7448. (t2 (match-string 2)) tt1 tt2)
  7449. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7450. tt2 (time-to-days (org-time-string-to-time t2)))
  7451. (let ((org-agenda-buffer-tmp-name
  7452. (format "*Org Agenda(a:%s)"
  7453. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7454. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7455. ((org-at-timestamp-p 'lax)
  7456. (let ((org-agenda-buffer-tmp-name
  7457. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7458. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7459. (substring (match-string 1) 0 10)))
  7460. 1)))
  7461. (t (error "This should not happen")))))
  7462. ;;; Following file links
  7463. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7464. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7465. (declare-function mailcap-mime-info
  7466. "mailcap" (string &optional request no-decode))
  7467. (defvar org-wait nil)
  7468. ;;;; Refiling
  7469. (defun org-get-org-file ()
  7470. "Read a filename, with default directory `org-directory'."
  7471. (let ((default (or org-default-notes-file remember-data-file)))
  7472. (read-file-name (format "File name [%s]: " default)
  7473. (file-name-as-directory org-directory)
  7474. default)))
  7475. (defun org-notes-order-reversed-p ()
  7476. "Check if the current file should receive notes in reversed order."
  7477. (cond
  7478. ((not org-reverse-note-order) nil)
  7479. ((eq t org-reverse-note-order) t)
  7480. ((not (listp org-reverse-note-order)) nil)
  7481. (t (catch 'exit
  7482. (dolist (entry org-reverse-note-order)
  7483. (when (string-match (car entry) buffer-file-name)
  7484. (throw 'exit (cdr entry))))))))
  7485. (defvar org-agenda-new-buffers nil
  7486. "Buffers created to visit agenda files.")
  7487. (declare-function org-string-nw-p "org-macs" (s))
  7488. ;;;; Dynamic blocks
  7489. (defun org-find-dblock (name)
  7490. "Find the first dynamic block with name NAME in the buffer.
  7491. If not found, stay at current position and return nil."
  7492. (let ((case-fold-search t) pos)
  7493. (save-excursion
  7494. (goto-char (point-min))
  7495. (setq pos (and (re-search-forward
  7496. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7497. (match-beginning 0))))
  7498. (when pos (goto-char pos))
  7499. pos))
  7500. (defun org-create-dblock (plist)
  7501. "Create a dynamic block section, with parameters taken from PLIST.
  7502. PLIST must contain a :name entry which is used as the name of the block."
  7503. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  7504. (end-of-line 1)
  7505. (newline))
  7506. (let ((col (current-column))
  7507. (name (plist-get plist :name)))
  7508. (insert "#+BEGIN: " name)
  7509. (while plist
  7510. (if (eq (car plist) :name)
  7511. (setq plist (cddr plist))
  7512. (insert " " (prin1-to-string (pop plist)))))
  7513. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7514. (beginning-of-line -2)))
  7515. (defun org-prepare-dblock ()
  7516. "Prepare dynamic block for refresh.
  7517. This empties the block, puts the cursor at the insert position and returns
  7518. the property list including an extra property :name with the block name."
  7519. (unless (looking-at org-dblock-start-re)
  7520. (user-error "Not at a dynamic block"))
  7521. (let* ((begdel (1+ (match-end 0)))
  7522. (name (org-no-properties (match-string 1)))
  7523. (params (append (list :name name)
  7524. (read (concat "(" (match-string 3) ")")))))
  7525. (save-excursion
  7526. (beginning-of-line 1)
  7527. (skip-chars-forward " \t")
  7528. (setq params (plist-put params :indentation-column (current-column))))
  7529. (unless (re-search-forward org-dblock-end-re nil t)
  7530. (error "Dynamic block not terminated"))
  7531. (setq params
  7532. (append params
  7533. (list :content (buffer-substring
  7534. begdel (match-beginning 0)))))
  7535. (delete-region begdel (match-beginning 0))
  7536. (goto-char begdel)
  7537. (open-line 1)
  7538. params))
  7539. (defun org-map-dblocks (&optional command)
  7540. "Apply COMMAND to all dynamic blocks in the current buffer.
  7541. If COMMAND is not given, use `org-update-dblock'."
  7542. (let ((cmd (or command 'org-update-dblock)))
  7543. (save-excursion
  7544. (goto-char (point-min))
  7545. (while (re-search-forward org-dblock-start-re nil t)
  7546. (goto-char (match-beginning 0))
  7547. (save-excursion
  7548. (condition-case nil
  7549. (funcall cmd)
  7550. (error (message "Error during update of dynamic block"))))
  7551. (unless (re-search-forward org-dblock-end-re nil t)
  7552. (error "Dynamic block not terminated"))))))
  7553. (defvar org-dynamic-block-alist nil
  7554. "Alist defining all the Org dynamic blocks.
  7555. The key is the dynamic block type name, as a string. The value
  7556. is the function used to insert the dynamic block.
  7557. Use `org-dynamic-block-define' to populate it.")
  7558. (defun org-dynamic-block-function (type)
  7559. "Return function associated to a given dynamic block type.
  7560. TYPE is the dynamic block type, as a string."
  7561. (cdr (assoc type org-dynamic-block-alist)))
  7562. (defun org-dynamic-block-types ()
  7563. "List all defined dynamic block types."
  7564. (mapcar #'car org-dynamic-block-alist))
  7565. (defun org-dynamic-block-define (type func)
  7566. "Define dynamic block TYPE with FUNC.
  7567. TYPE is a string. FUNC is the function creating the dynamic
  7568. block of such type."
  7569. (pcase (assoc type org-dynamic-block-alist)
  7570. (`nil (push (cons type func) org-dynamic-block-alist))
  7571. (def (setcdr def func))))
  7572. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7573. "Insert a dynamic block of type TYPE.
  7574. When used interactively, select the dynamic block types among
  7575. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7576. is non-nil, call the dynamic block function interactively."
  7577. (interactive (list (completing-read "Dynamic block: "
  7578. (org-dynamic-block-types))
  7579. t))
  7580. (pcase (org-dynamic-block-function type)
  7581. (`nil (error "No such dynamic block: %S" type))
  7582. ((and f (pred functionp))
  7583. (if interactive-p (call-interactively f) (funcall f)))
  7584. (_ (error "Invalid function for dynamic block %S" type))))
  7585. (defun org-dblock-update (&optional arg)
  7586. "User command for updating dynamic blocks.
  7587. Update the dynamic block at point. With prefix ARG, update all dynamic
  7588. blocks in the buffer."
  7589. (interactive "P")
  7590. (if arg
  7591. (org-update-all-dblocks)
  7592. (or (looking-at org-dblock-start-re)
  7593. (org-beginning-of-dblock))
  7594. (org-update-dblock)))
  7595. (defun org-update-dblock ()
  7596. "Update the dynamic block at point.
  7597. This means to empty the block, parse for parameters and then call
  7598. the correct writing function."
  7599. (interactive)
  7600. (save-excursion
  7601. (let* ((win (selected-window))
  7602. (pos (point))
  7603. (line (org-current-line))
  7604. (params (org-prepare-dblock))
  7605. (name (plist-get params :name))
  7606. (indent (plist-get params :indentation-column))
  7607. (cmd (intern (concat "org-dblock-write:" name))))
  7608. (message "Updating dynamic block `%s' at line %d..." name line)
  7609. (funcall cmd params)
  7610. (message "Updating dynamic block `%s' at line %d...done" name line)
  7611. (goto-char pos)
  7612. (when (and indent (> indent 0))
  7613. (setq indent (make-string indent ?\ ))
  7614. (save-excursion
  7615. (select-window win)
  7616. (org-beginning-of-dblock)
  7617. (forward-line 1)
  7618. (while (not (looking-at org-dblock-end-re))
  7619. (insert indent)
  7620. (beginning-of-line 2))
  7621. (when (looking-at org-dblock-end-re)
  7622. (and (looking-at "[ \t]+")
  7623. (replace-match ""))
  7624. (insert indent)))))))
  7625. (defun org-beginning-of-dblock ()
  7626. "Find the beginning of the dynamic block at point.
  7627. Error if there is no such block at point."
  7628. (let ((pos (point))
  7629. beg)
  7630. (end-of-line 1)
  7631. (if (and (re-search-backward org-dblock-start-re nil t)
  7632. (setq beg (match-beginning 0))
  7633. (re-search-forward org-dblock-end-re nil t)
  7634. (> (match-end 0) pos))
  7635. (goto-char beg)
  7636. (goto-char pos)
  7637. (error "Not in a dynamic block"))))
  7638. (defun org-update-all-dblocks ()
  7639. "Update all dynamic blocks in the buffer.
  7640. This function can be used in a hook."
  7641. (interactive)
  7642. (when (derived-mode-p 'org-mode)
  7643. (org-map-dblocks 'org-update-dblock)))
  7644. ;;;; Completion
  7645. (declare-function org-export-backend-options "ox" (cl-x) t)
  7646. (defun org-get-export-keywords ()
  7647. "Return a list of all currently understood export keywords.
  7648. Export keywords include options, block names, attributes and
  7649. keywords relative to each registered export back-end."
  7650. (let (keywords)
  7651. (dolist (backend
  7652. (bound-and-true-p org-export-registered-backends)
  7653. (delq nil keywords))
  7654. ;; Back-end name (for keywords, like #+LATEX:)
  7655. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7656. (dolist (option-entry (org-export-backend-options backend))
  7657. ;; Back-end options.
  7658. (push (nth 1 option-entry) keywords)))))
  7659. (defconst org-options-keywords
  7660. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  7661. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  7662. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  7663. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  7664. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7665. (defcustom org-structure-template-alist
  7666. '(("a" . "export ascii")
  7667. ("c" . "center")
  7668. ("C" . "comment")
  7669. ("e" . "example")
  7670. ("E" . "export")
  7671. ("h" . "export html")
  7672. ("l" . "export latex")
  7673. ("q" . "quote")
  7674. ("s" . "src")
  7675. ("v" . "verse"))
  7676. "An alist of keys and block types.
  7677. `org-insert-structure-template' will display a menu with this
  7678. list of templates to choose from. The block type is inserted,
  7679. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  7680. The menu keys are defined by the car of each entry in this alist.
  7681. If two entries have the keys \"a\" and \"aa\" respectively, the
  7682. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7683. latter will be inserted by typing \"aa\". If an entry with the
  7684. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7685. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7686. block can be inserted by pressing TAB after the string \"<KEY\"."
  7687. :group 'org-edit-structure
  7688. :type '(repeat
  7689. (cons (string :tag "Key")
  7690. (string :tag "Template")))
  7691. :package-version '(Org . "9.2"))
  7692. (defun org--check-org-structure-template-alist (&optional checklist)
  7693. "Check whether `org-structure-template-alist' is set up correctly.
  7694. In particular, check if the Org 9.2 format is used as opposed to
  7695. previous format."
  7696. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7697. (or (symbol-value checklist)
  7698. org-structure-template-alist))))
  7699. (when elm
  7700. (org-display-warning
  7701. (format "
  7702. Please update the entries of `%s'.
  7703. In Org 9.2 the format was changed from something like
  7704. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7705. to something like
  7706. (\"s\" . \"src\")
  7707. Please refer to the documentation of `org-structure-template-alist'.
  7708. The following entries must be updated:
  7709. %s"
  7710. (or checklist 'org-structure-template-alist)
  7711. (pp-to-string elm))))))
  7712. (defun org--insert-structure-template-mks ()
  7713. "Present `org-structure-template-alist' with `org-mks'.
  7714. Menus are added if keys require more than one keystroke. Tabs
  7715. are added to single key entries when more than one stroke is
  7716. needed. Keys longer than two characters are reduced to two
  7717. characters."
  7718. (org--check-org-structure-template-alist)
  7719. (let* (case-fold-search
  7720. (templates (append org-structure-template-alist
  7721. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7722. (keys (mapcar #'car templates))
  7723. (start-letters
  7724. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7725. ;; Sort each element of `org-structure-template-alist' into
  7726. ;; sublists according to the first letter.
  7727. (superlist
  7728. (mapcar (lambda (letter)
  7729. (list letter
  7730. (cl-remove-if-not
  7731. (apply-partially #'string-match-p (concat "^" letter))
  7732. templates :key #'car)))
  7733. start-letters)))
  7734. (org-mks
  7735. (apply #'append
  7736. ;; Make an `org-mks' table. If only one element is
  7737. ;; present in a sublist, make it part of the top-menu,
  7738. ;; otherwise make a submenu according to the starting
  7739. ;; letter and populate it.
  7740. (mapcar (lambda (sublist)
  7741. (if (eq 1 (length (cadr sublist)))
  7742. (mapcar (lambda (elm)
  7743. (list (substring (car elm) 0 1)
  7744. (cdr elm) ""))
  7745. (cadr sublist))
  7746. ;; Create submenu.
  7747. (let* ((topkey (car sublist))
  7748. (elms (cadr sublist))
  7749. (keys (mapcar #'car elms))
  7750. (long (> (length elms) 3)))
  7751. (append
  7752. (list
  7753. ;; Make a description of the submenu.
  7754. (list topkey
  7755. (concat
  7756. (mapconcat #'cdr
  7757. (cl-subseq elms 0 (if long 3 (length elms)))
  7758. ", ")
  7759. (when long ", ..."))))
  7760. ;; List of entries in submenu.
  7761. (cl-mapcar #'list
  7762. (org--insert-structure-template-unique-keys keys)
  7763. (mapcar #'cdr elms)
  7764. (make-list (length elms) ""))))))
  7765. superlist))
  7766. "Select a key\n============"
  7767. "Key: ")))
  7768. (defun org--insert-structure-template-unique-keys (keys)
  7769. "Make a list of unique, two characters long elements from KEYS.
  7770. Elements of length one have a tab appended. Elements of length
  7771. two are kept as is. Longer elements are truncated to length two.
  7772. If an element cannot be made unique, an error is raised."
  7773. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7774. menu-keys)
  7775. (dolist (key ordered-keys)
  7776. (let ((potential-key
  7777. (cl-case (length key)
  7778. (1 (concat key "\t"))
  7779. (2 key)
  7780. (otherwise
  7781. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  7782. (mapcar (apply-partially #'concat (substring key 0 1))
  7783. (split-string (substring key 1) "" t)))))))
  7784. (if (or (not potential-key) (assoc potential-key menu-keys))
  7785. (user-error "Could not make unique key for `%s'" key)
  7786. (push (cons potential-key key) menu-keys))))
  7787. (mapcar #'car
  7788. (cl-sort menu-keys #'<
  7789. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  7790. (defun org-insert-structure-template (type)
  7791. "Insert a block structure of the type #+begin_foo/#+end_foo.
  7792. Select a block from `org-structure-template-alist' then type
  7793. either RET, TAB or SPC to write the block type. With an active
  7794. region, wrap the region in the block. Otherwise, insert an empty
  7795. block."
  7796. (interactive
  7797. (list (pcase (org--insert-structure-template-mks)
  7798. (`("\t" . ,_) (read-string "Structure type: "))
  7799. (`(,_ ,choice . ,_) choice))))
  7800. (let* ((region? (use-region-p))
  7801. (region-start (and region? (region-beginning)))
  7802. (region-end (and region? (copy-marker (region-end))))
  7803. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  7804. (verbatim? (string-match-p
  7805. (concat "\\`" (regexp-opt '("example" "export" "src")))
  7806. type)))
  7807. (when region? (goto-char region-start))
  7808. (let ((column (current-indentation)))
  7809. (if (save-excursion (skip-chars-backward " \t") (bolp))
  7810. (beginning-of-line)
  7811. (insert "\n"))
  7812. (save-excursion
  7813. (indent-to column)
  7814. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  7815. (when region?
  7816. (when verbatim? (org-escape-code-in-region (point) region-end))
  7817. (goto-char region-end)
  7818. ;; Ignore empty lines at the end of the region.
  7819. (skip-chars-backward " \r\t\n")
  7820. (end-of-line))
  7821. (unless (bolp) (insert "\n"))
  7822. (indent-to column)
  7823. (insert (format "#+end_%s" (car (split-string type))))
  7824. (if (looking-at "[ \t]*$") (replace-match "")
  7825. (insert "\n"))
  7826. (when (and (eobp) (not (bolp))) (insert "\n")))
  7827. (if extended? (end-of-line)
  7828. (forward-line)
  7829. (skip-chars-forward " \t")))))
  7830. ;;;; TODO, DEADLINE, Comments
  7831. (defun org-toggle-comment ()
  7832. "Change the COMMENT state of an entry."
  7833. (interactive)
  7834. (save-excursion
  7835. (org-back-to-heading)
  7836. (let ((case-fold-search nil))
  7837. (looking-at org-complex-heading-regexp))
  7838. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7839. (skip-chars-forward " \t")
  7840. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  7841. (if (org-in-commented-heading-p t)
  7842. (delete-region (point)
  7843. (progn (search-forward " " (line-end-position) 'move)
  7844. (skip-chars-forward " \t")
  7845. (point)))
  7846. (insert org-comment-string)
  7847. (unless (eolp) (insert " ")))))
  7848. (defvar org-last-todo-state-is-todo nil
  7849. "This is non-nil when the last TODO state change led to a TODO state.
  7850. If the last change removed the TODO tag or switched to DONE, then
  7851. this is nil.")
  7852. (defvar org-todo-setup-filter-hook nil
  7853. "Hook for functions that pre-filter todo specs.
  7854. Each function takes a todo spec and returns either nil or the spec
  7855. transformed into canonical form." )
  7856. (defvar org-todo-get-default-hook nil
  7857. "Hook for functions that get a default item for todo.
  7858. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  7859. nil or a string to be used for the todo mark." )
  7860. (defvar org-agenda-headline-snapshot-before-repeat)
  7861. (defun org-current-effective-time ()
  7862. "Return current time adjusted for `org-extend-today-until' variable."
  7863. (let* ((ct (org-current-time))
  7864. (dct (decode-time ct))
  7865. (ct1
  7866. (cond
  7867. (org-use-last-clock-out-time-as-effective-time
  7868. (or (org-clock-get-last-clock-out-time) ct))
  7869. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  7870. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  7871. (t ct))))
  7872. ct1))
  7873. (defun org-todo-yesterday (&optional arg)
  7874. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  7875. (interactive "P")
  7876. (if (eq major-mode 'org-agenda-mode)
  7877. (apply 'org-agenda-todo-yesterday arg)
  7878. (let* ((org-use-effective-time t)
  7879. (hour (nth 2 (decode-time (org-current-time))))
  7880. (org-extend-today-until (1+ hour)))
  7881. (org-todo arg))))
  7882. (defvar org-block-entry-blocking ""
  7883. "First entry preventing the TODO state change.")
  7884. (defun org-cancel-repeater ()
  7885. "Cancel a repeater by setting its numeric value to zero."
  7886. (interactive)
  7887. (save-excursion
  7888. (org-back-to-heading t)
  7889. (let ((bound1 (point))
  7890. (bound0 (save-excursion (outline-next-heading) (point))))
  7891. (when (and (re-search-forward
  7892. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  7893. org-deadline-time-regexp "\\)\\|\\("
  7894. org-ts-regexp "\\)")
  7895. bound0 t)
  7896. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  7897. bound1 t))
  7898. (replace-match "0" t nil nil 1)))))
  7899. (defvar org-state)
  7900. (defvar org-blocked-by-checkboxes)
  7901. (defun org-todo (&optional arg)
  7902. "Change the TODO state of an item.
  7903. The state of an item is given by a keyword at the start of the heading,
  7904. like
  7905. *** TODO Write paper
  7906. *** DONE Call mom
  7907. The different keywords are specified in the variable `org-todo-keywords'.
  7908. By default the available states are \"TODO\" and \"DONE\". So, for this
  7909. example: when the item starts with TODO, it is changed to DONE.
  7910. When it starts with DONE, the DONE is removed. And when neither TODO nor
  7911. DONE are present, add TODO at the beginning of the heading.
  7912. You can set up single-character keys to fast-select the new state. See the
  7913. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  7914. With `\\[universal-argument]' prefix ARG, force logging the state change \
  7915. and take a
  7916. logging note.
  7917. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  7918. next set of TODO \
  7919. keywords (nextset).
  7920. Another way to achieve this is `S-C-<right>'.
  7921. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  7922. prefix, circumvent any state blocking.
  7923. With numeric prefix arg, switch to the Nth state.
  7924. With a numeric prefix arg of 0, inhibit note taking for the change.
  7925. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  7926. When called through ELisp, arg is also interpreted in the following way:
  7927. `none' -> empty state
  7928. \"\" -> switch to empty state
  7929. `done' -> switch to DONE
  7930. `nextset' -> switch to the next set of keywords
  7931. `previousset' -> switch to the previous set of keywords
  7932. \"WAITING\" -> switch to the specified keyword, but only if it
  7933. really is a member of `org-todo-keywords'."
  7934. (interactive "P")
  7935. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  7936. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  7937. 'region-start-level 'region))
  7938. org-loop-over-headlines-in-active-region)
  7939. (org-map-entries
  7940. (lambda () (org-todo arg))
  7941. nil cl
  7942. (when (org-invisible-p) (org-end-of-subtree nil t))))
  7943. (when (equal arg '(16)) (setq arg 'nextset))
  7944. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  7945. (let ((org-blocker-hook org-blocker-hook)
  7946. commentp
  7947. case-fold-search)
  7948. (when (equal arg '(64))
  7949. (setq arg nil org-blocker-hook nil))
  7950. (when (and org-blocker-hook
  7951. (or org-inhibit-blocking
  7952. (org-entry-get nil "NOBLOCKING")))
  7953. (setq org-blocker-hook nil))
  7954. (save-excursion
  7955. (catch 'exit
  7956. (org-back-to-heading t)
  7957. (when (org-in-commented-heading-p t)
  7958. (org-toggle-comment)
  7959. (setq commentp t))
  7960. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  7961. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  7962. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  7963. (let* ((match-data (match-data))
  7964. (startpos (copy-marker (line-beginning-position)))
  7965. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  7966. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  7967. (org-log-done org-log-done)
  7968. (org-log-repeat org-log-repeat)
  7969. (org-todo-log-states org-todo-log-states)
  7970. (org-inhibit-logging
  7971. (if (equal arg 0)
  7972. (progn (setq arg nil) 'note) org-inhibit-logging))
  7973. (this (match-string 1))
  7974. (hl-pos (match-beginning 0))
  7975. (head (org-get-todo-sequence-head this))
  7976. (ass (assoc head org-todo-kwd-alist))
  7977. (interpret (nth 1 ass))
  7978. (done-word (nth 3 ass))
  7979. (final-done-word (nth 4 ass))
  7980. (org-last-state (or this ""))
  7981. (completion-ignore-case t)
  7982. (member (member this org-todo-keywords-1))
  7983. (tail (cdr member))
  7984. (org-state (cond
  7985. ((eq arg 'right)
  7986. ;; Next state
  7987. (if this
  7988. (if tail (car tail) nil)
  7989. (car org-todo-keywords-1)))
  7990. ((eq arg 'left)
  7991. ;; Previous state
  7992. (unless (equal member org-todo-keywords-1)
  7993. (if this
  7994. (nth (- (length org-todo-keywords-1)
  7995. (length tail) 2)
  7996. org-todo-keywords-1)
  7997. (org-last org-todo-keywords-1))))
  7998. (arg
  7999. ;; User or caller requests a specific state.
  8000. (cond
  8001. ((equal arg "") nil)
  8002. ((eq arg 'none) nil)
  8003. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8004. ((eq arg 'nextset)
  8005. (or (car (cdr (member head org-todo-heads)))
  8006. (car org-todo-heads)))
  8007. ((eq arg 'previousset)
  8008. (let ((org-todo-heads (reverse org-todo-heads)))
  8009. (or (car (cdr (member head org-todo-heads)))
  8010. (car org-todo-heads))))
  8011. ((car (member arg org-todo-keywords-1)))
  8012. ((stringp arg)
  8013. (user-error "State `%s' not valid in this file" arg))
  8014. ((nth (1- (prefix-numeric-value arg))
  8015. org-todo-keywords-1))))
  8016. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8017. ;; Use fast selection.
  8018. (org-fast-todo-selection this))
  8019. ((null member) (or head (car org-todo-keywords-1)))
  8020. ((equal this final-done-word) nil) ;-> make empty
  8021. ((null tail) nil) ;-> first entry
  8022. ((memq interpret '(type priority))
  8023. (if (eq this-command last-command)
  8024. (car tail)
  8025. (if (> (length tail) 0)
  8026. (or done-word (car org-done-keywords))
  8027. nil)))
  8028. (t
  8029. (car tail))))
  8030. (org-state (or
  8031. (run-hook-with-args-until-success
  8032. 'org-todo-get-default-hook org-state org-last-state)
  8033. org-state))
  8034. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8035. (change-plist (list :type 'todo-state-change :from this :to org-state
  8036. :position startpos))
  8037. dolog now-done-p)
  8038. (when org-blocker-hook
  8039. (let (org-blocked-by-checkboxes block-reason)
  8040. (setq org-last-todo-state-is-todo
  8041. (not (member this org-done-keywords)))
  8042. (unless (save-excursion
  8043. (save-match-data
  8044. (org-with-wide-buffer
  8045. (run-hook-with-args-until-failure
  8046. 'org-blocker-hook change-plist))))
  8047. (setq block-reason (if org-blocked-by-checkboxes
  8048. "contained checkboxes"
  8049. (format "\"%s\"" org-block-entry-blocking)))
  8050. (if (called-interactively-p 'interactive)
  8051. (user-error "TODO state change from %s to %s blocked (by %s)"
  8052. this org-state block-reason)
  8053. ;; Fail silently.
  8054. (message "TODO state change from %s to %s blocked (by %s)"
  8055. this org-state block-reason)
  8056. (throw 'exit nil)))))
  8057. (store-match-data match-data)
  8058. (org-fold-core-ignore-modifications
  8059. (goto-char (match-beginning 0))
  8060. (replace-match "")
  8061. ;; We need to use `insert-before-markers-and-inherit'
  8062. ;; because: (1) We want to preserve the folding state
  8063. ;; text properties; (2) We do not want to make point
  8064. ;; move before new todo state when inserting a new todo
  8065. ;; into an empty heading. In (2), the above
  8066. ;; `save-excursion' is relying on markers saved before.
  8067. (insert-before-markers-and-inherit next)
  8068. (unless (org-invisible-p (line-beginning-position))
  8069. (org-fold-region (line-beginning-position)
  8070. (line-end-position)
  8071. nil)))
  8072. (cond ((and org-state (equal this org-state))
  8073. (message "TODO state was already %s" (org-trim next)))
  8074. ((not (pos-visible-in-window-p hl-pos))
  8075. (message "TODO state changed to %s" (org-trim next))))
  8076. (unless head
  8077. (setq head (org-get-todo-sequence-head org-state)
  8078. ass (assoc head org-todo-kwd-alist)
  8079. interpret (nth 1 ass)
  8080. done-word (nth 3 ass)
  8081. final-done-word (nth 4 ass)))
  8082. (when (memq arg '(nextset previousset))
  8083. (message "Keyword-Set %d/%d: %s"
  8084. (- (length org-todo-sets) -1
  8085. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8086. (length org-todo-sets)
  8087. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8088. (setq org-last-todo-state-is-todo
  8089. (not (member org-state org-done-keywords)))
  8090. (setq now-done-p (and (member org-state org-done-keywords)
  8091. (not (member this org-done-keywords))))
  8092. (and logging (org-local-logging logging))
  8093. (when (or (and (or org-todo-log-states org-log-done)
  8094. (not (eq org-inhibit-logging t))
  8095. (not (memq arg '(nextset previousset))))
  8096. force-log)
  8097. ;; We need to look at recording a time and note.
  8098. (setq dolog (or (if force-log 'note)
  8099. (nth 1 (assoc org-state org-todo-log-states))
  8100. (nth 2 (assoc this org-todo-log-states))))
  8101. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8102. (setq dolog 'time))
  8103. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8104. (and org-state
  8105. (member org-state org-not-done-keywords)
  8106. (not (member this org-not-done-keywords))))
  8107. ;; This is now a todo state and was not one before
  8108. ;; If there was a CLOSED time stamp, get rid of it.
  8109. (org-add-planning-info nil nil 'closed))
  8110. (when (and now-done-p org-log-done)
  8111. ;; It is now done, and it was not done before.
  8112. (org-add-planning-info 'closed (org-current-effective-time))
  8113. (when (and (not dolog) (eq 'note org-log-done))
  8114. (org-add-log-setup 'done org-state this 'note)))
  8115. (when (and org-state dolog)
  8116. ;; This is a non-nil state, and we need to log it.
  8117. (org-add-log-setup 'state org-state this dolog)))
  8118. ;; Fixup tag positioning.
  8119. (org-todo-trigger-tag-changes org-state)
  8120. (when org-auto-align-tags (org-align-tags))
  8121. (when org-provide-todo-statistics
  8122. (org-update-parent-todo-statistics))
  8123. (when (bound-and-true-p org-clock-out-when-done)
  8124. (org-clock-out-if-current))
  8125. (run-hooks 'org-after-todo-state-change-hook)
  8126. (when (and arg (not (member org-state org-done-keywords)))
  8127. (setq head (org-get-todo-sequence-head org-state)))
  8128. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8129. ;; Do we need to trigger a repeat?
  8130. (when now-done-p
  8131. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8132. ;; This is for the agenda, take a snapshot of the headline.
  8133. (save-match-data
  8134. (setq org-agenda-headline-snapshot-before-repeat
  8135. (org-get-heading))))
  8136. (org-auto-repeat-maybe org-state))
  8137. ;; Fixup cursor location if close to the keyword.
  8138. (when (and (outline-on-heading-p)
  8139. (not (bolp))
  8140. (save-excursion (beginning-of-line 1)
  8141. (looking-at org-todo-line-regexp))
  8142. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8143. (goto-char (or (match-end 2) (match-end 1)))
  8144. (and (looking-at " ")
  8145. (not (looking-at " *:"))
  8146. (just-one-space)))
  8147. (when org-trigger-hook
  8148. (save-excursion
  8149. (run-hook-with-args 'org-trigger-hook change-plist)))
  8150. (when commentp (org-toggle-comment))))))))
  8151. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8152. "Block turning an entry into a TODO, using the hierarchy.
  8153. This checks whether the current task should be blocked from state
  8154. changes. Such blocking occurs when:
  8155. 1. The task has children which are not all in a completed state.
  8156. 2. A task has a parent with the property :ORDERED:, and there
  8157. are siblings prior to the current task with incomplete
  8158. status.
  8159. 3. The parent of the task is blocked because it has siblings that should
  8160. be done first, or is child of a block grandparent TODO entry."
  8161. (if (not org-enforce-todo-dependencies)
  8162. t ; if locally turned off don't block
  8163. (catch 'dont-block
  8164. ;; If this is not a todo state change, or if this entry is already DONE,
  8165. ;; do not block
  8166. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8167. (member (plist-get change-plist :from)
  8168. (cons 'done org-done-keywords))
  8169. (member (plist-get change-plist :to)
  8170. (cons 'todo org-not-done-keywords))
  8171. (not (plist-get change-plist :to)))
  8172. (throw 'dont-block t))
  8173. ;; If this task has children, and any are undone, it's blocked
  8174. (save-excursion
  8175. (org-back-to-heading t)
  8176. (let ((this-level (funcall outline-level)))
  8177. (outline-next-heading)
  8178. (let ((child-level (funcall outline-level)))
  8179. (while (and (not (eobp))
  8180. (> child-level this-level))
  8181. ;; this todo has children, check whether they are all
  8182. ;; completed
  8183. (when (and (not (org-entry-is-done-p))
  8184. (org-entry-is-todo-p))
  8185. (setq org-block-entry-blocking (org-get-heading))
  8186. (throw 'dont-block nil))
  8187. (outline-next-heading)
  8188. (setq child-level (funcall outline-level))))))
  8189. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8190. ;; any previous siblings are undone, it's blocked
  8191. (save-excursion
  8192. (org-back-to-heading t)
  8193. (let* ((pos (point))
  8194. (parent-pos (and (org-up-heading-safe) (point)))
  8195. (case-fold-search nil))
  8196. (unless parent-pos (throw 'dont-block t)) ; no parent
  8197. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8198. (forward-line 1)
  8199. (re-search-forward org-not-done-heading-regexp pos t))
  8200. (setq org-block-entry-blocking (match-string 0))
  8201. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8202. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8203. (while t
  8204. (goto-char parent-pos)
  8205. (unless (looking-at org-not-done-heading-regexp)
  8206. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8207. (setq pos (point))
  8208. (setq parent-pos (and (org-up-heading-safe) (point)))
  8209. (unless parent-pos (throw 'dont-block t)) ; no parent
  8210. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8211. (forward-line 1)
  8212. (re-search-forward org-not-done-heading-regexp pos t)
  8213. (setq org-block-entry-blocking (org-get-heading)))
  8214. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8215. (defcustom org-track-ordered-property-with-tag nil
  8216. "Should the ORDERED property also be shown as a tag?
  8217. The ORDERED property decides if an entry should require subtasks to be
  8218. completed in sequence. Since a property is not very visible, setting
  8219. this option means that toggling the ORDERED property with the command
  8220. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8221. not relevant for the behavior, but it makes things more visible.
  8222. Note that toggling the tag with tags commands will not change the property
  8223. and therefore not influence behavior!
  8224. This can be t, meaning the tag ORDERED should be used. It can also be a
  8225. string to select a different tag for this task."
  8226. :group 'org-todo
  8227. :type '(choice
  8228. (const :tag "No tracking" nil)
  8229. (const :tag "Track with ORDERED tag" t)
  8230. (string :tag "Use other tag")))
  8231. (defun org-toggle-ordered-property ()
  8232. "Toggle the ORDERED property of the current entry.
  8233. For better visibility, you can track the value of this property with a tag.
  8234. See variable `org-track-ordered-property-with-tag'."
  8235. (interactive)
  8236. (let* ((t1 org-track-ordered-property-with-tag)
  8237. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8238. (save-excursion
  8239. (org-back-to-heading)
  8240. (if (org-entry-get nil "ORDERED")
  8241. (progn
  8242. (org-delete-property "ORDERED")
  8243. (and tag (org-toggle-tag tag 'off))
  8244. (message "Subtasks can be completed in arbitrary order"))
  8245. (org-entry-put nil "ORDERED" "t")
  8246. (and tag (org-toggle-tag tag 'on))
  8247. (message "Subtasks must be completed in sequence")))))
  8248. (defun org-block-todo-from-checkboxes (change-plist)
  8249. "Block turning an entry into a TODO, using checkboxes.
  8250. This checks whether the current task should be blocked from state
  8251. changes because there are unchecked boxes in this entry."
  8252. (if (not org-enforce-todo-checkbox-dependencies)
  8253. t ; if locally turned off don't block
  8254. (catch 'dont-block
  8255. ;; If this is not a todo state change, or if this entry is already DONE,
  8256. ;; do not block
  8257. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8258. (member (plist-get change-plist :from)
  8259. (cons 'done org-done-keywords))
  8260. (member (plist-get change-plist :to)
  8261. (cons 'todo org-not-done-keywords))
  8262. (not (plist-get change-plist :to)))
  8263. (throw 'dont-block t))
  8264. ;; If this task has checkboxes that are not checked, it's blocked
  8265. (save-excursion
  8266. (org-back-to-heading t)
  8267. (let ((beg (point)) end)
  8268. (outline-next-heading)
  8269. (setq end (point))
  8270. (goto-char beg)
  8271. (when (org-list-search-forward
  8272. (concat (org-item-beginning-re)
  8273. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8274. "\\[[- ]\\]")
  8275. end t)
  8276. (when (boundp 'org-blocked-by-checkboxes)
  8277. (setq org-blocked-by-checkboxes t))
  8278. (throw 'dont-block nil))))
  8279. t))) ; do not block
  8280. (defun org-entry-blocked-p ()
  8281. "Non-nil if entry at point is blocked."
  8282. (and (not (org-entry-get nil "NOBLOCKING"))
  8283. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8284. (not (run-hook-with-args-until-failure
  8285. 'org-blocker-hook
  8286. (list :type 'todo-state-change
  8287. :position (point)
  8288. :from 'todo
  8289. :to 'done)))))
  8290. (defun org-update-statistics-cookies (all)
  8291. "Update the statistics cookie, either from TODO or from checkboxes.
  8292. This should be called with the cursor in a line with a statistics
  8293. cookie. When called with a \\[universal-argument] prefix, update
  8294. all statistics cookies in the buffer."
  8295. (interactive "P")
  8296. (if all
  8297. (progn
  8298. (org-update-checkbox-count 'all)
  8299. (org-map-region 'org-update-parent-todo-statistics
  8300. (point-min) (point-max)))
  8301. (if (not (org-at-heading-p))
  8302. (org-update-checkbox-count)
  8303. (let ((pos (point-marker))
  8304. end l1 l2)
  8305. (ignore-errors (org-back-to-heading t))
  8306. (if (not (org-at-heading-p))
  8307. (org-update-checkbox-count)
  8308. (setq l1 (org-outline-level))
  8309. (setq end
  8310. (save-excursion
  8311. (outline-next-heading)
  8312. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8313. (point)))
  8314. (if (and (save-excursion
  8315. (re-search-forward
  8316. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8317. (not (save-excursion
  8318. (re-search-forward
  8319. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8320. (org-update-checkbox-count)
  8321. (if (and l2 (> l2 l1))
  8322. (progn
  8323. (goto-char end)
  8324. (org-update-parent-todo-statistics))
  8325. (goto-char pos)
  8326. (beginning-of-line 1)
  8327. (while (re-search-forward
  8328. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8329. (point-at-eol) t)
  8330. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8331. (goto-char pos)
  8332. (move-marker pos nil)))))
  8333. (defvar org-entry-property-inherited-from) ;; defined below
  8334. (defun org-update-parent-todo-statistics ()
  8335. "Update any statistics cookie in the parent of the current headline.
  8336. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8337. the entire subtree and this will travel up the hierarchy and update
  8338. statistics everywhere."
  8339. (let* ((prop (save-excursion
  8340. (org-up-heading-safe)
  8341. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8342. (recursive (or (not org-hierarchical-todo-statistics)
  8343. (and prop (string-match "\\<recursive\\>" prop))))
  8344. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8345. 0))
  8346. (first t)
  8347. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8348. level ltoggle l1 new ndel
  8349. (cnt-all 0) (cnt-done 0) is-percent kwd
  8350. checkbox-beg cookie-present)
  8351. (catch 'exit
  8352. (save-excursion
  8353. (beginning-of-line 1)
  8354. (setq ltoggle (funcall outline-level))
  8355. ;; Three situations are to consider:
  8356. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8357. ;; to the top-level ancestor on the headline;
  8358. ;; 2. If parent has "recursive" property, repeat up to the
  8359. ;; headline setting that property, taking inheritance into
  8360. ;; account;
  8361. ;; 3. Else, move up to direct parent and proceed only once.
  8362. (while (and (setq level (org-up-heading-safe))
  8363. (or recursive first)
  8364. (>= (point) lim))
  8365. (setq first nil cookie-present nil)
  8366. (unless (and level
  8367. (not (string-match
  8368. "\\<checkbox\\>"
  8369. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8370. "")))))
  8371. (throw 'exit nil))
  8372. (while (re-search-forward box-re (point-at-eol) t)
  8373. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8374. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8375. (save-match-data
  8376. (unless (outline-next-heading) (throw 'exit nil))
  8377. (while (and (looking-at org-complex-heading-regexp)
  8378. (> (setq l1 (length (match-string 1))) level))
  8379. (setq kwd (and (or recursive (= l1 ltoggle))
  8380. (match-string 2)))
  8381. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8382. (and (eq org-provide-todo-statistics t)
  8383. (or (member kwd org-done-keywords)))
  8384. (and (listp org-provide-todo-statistics)
  8385. (stringp (car org-provide-todo-statistics))
  8386. (or (member kwd org-provide-todo-statistics)
  8387. (member kwd org-done-keywords)))
  8388. (and (listp org-provide-todo-statistics)
  8389. (listp (car org-provide-todo-statistics))
  8390. (or (member kwd (car org-provide-todo-statistics))
  8391. (and (member kwd org-done-keywords)
  8392. (member kwd (cadr org-provide-todo-statistics))))))
  8393. (setq cnt-all (1+ cnt-all))
  8394. (and (eq org-provide-todo-statistics t)
  8395. kwd
  8396. (setq cnt-all (1+ cnt-all))))
  8397. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8398. (member kwd org-done-keywords))
  8399. (and (listp org-provide-todo-statistics)
  8400. (listp (car org-provide-todo-statistics))
  8401. (member kwd org-done-keywords)
  8402. (member kwd (cadr org-provide-todo-statistics)))
  8403. (and (listp org-provide-todo-statistics)
  8404. (stringp (car org-provide-todo-statistics))
  8405. (member kwd org-done-keywords)))
  8406. (setq cnt-done (1+ cnt-done)))
  8407. (outline-next-heading)))
  8408. (setq new
  8409. (if is-percent
  8410. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8411. (max 1 cnt-all)))
  8412. (format "[%d/%d]" cnt-done cnt-all))
  8413. ndel (- (match-end 0) checkbox-beg))
  8414. (goto-char checkbox-beg)
  8415. (insert new)
  8416. (delete-region (point) (+ (point) ndel))
  8417. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8418. (when cookie-present
  8419. (run-hook-with-args 'org-after-todo-statistics-hook
  8420. cnt-done (- cnt-all cnt-done))))))
  8421. (run-hooks 'org-todo-statistics-hook)))
  8422. (defvar org-after-todo-statistics-hook nil
  8423. "Hook that is called after a TODO statistics cookie has been updated.
  8424. Each function is called with two arguments: the number of not-done entries
  8425. and the number of done entries.
  8426. For example, the following function, when added to this hook, will switch
  8427. an entry to DONE when all children are done, and back to TODO when new
  8428. entries are set to a TODO status. Note that this hook is only called
  8429. when there is a statistics cookie in the headline!
  8430. (defun org-summary-todo (n-done n-not-done)
  8431. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8432. (let (org-log-done org-log-states) ; turn off logging
  8433. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8434. (defvar org-todo-statistics-hook nil
  8435. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8436. This hook runs even if there is no statistics cookie present, in which case
  8437. `org-after-todo-statistics-hook' would not run.")
  8438. (defun org-todo-trigger-tag-changes (state)
  8439. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8440. (let ((l org-todo-state-tags-triggers)
  8441. changes)
  8442. (when (or (not state) (equal state ""))
  8443. (setq changes (append changes (cdr (assoc "" l)))))
  8444. (when (and (stringp state) (> (length state) 0))
  8445. (setq changes (append changes (cdr (assoc state l)))))
  8446. (when (member state org-not-done-keywords)
  8447. (setq changes (append changes (cdr (assq 'todo l)))))
  8448. (when (member state org-done-keywords)
  8449. (setq changes (append changes (cdr (assq 'done l)))))
  8450. (dolist (c changes)
  8451. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8452. (defun org-local-logging (value)
  8453. "Get logging settings from a property VALUE."
  8454. ;; Directly set the variables, they are already local.
  8455. (setq org-log-done nil
  8456. org-log-repeat nil
  8457. org-todo-log-states nil)
  8458. (dolist (w (split-string value))
  8459. (let (a)
  8460. (cond
  8461. ((setq a (assoc w org-startup-options))
  8462. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8463. (set (nth 1 a) (nth 2 a))))
  8464. ((setq a (org-extract-log-state-settings w))
  8465. (and (member (car a) org-todo-keywords-1)
  8466. (push a org-todo-log-states)))))))
  8467. (defun org-get-todo-sequence-head (kwd)
  8468. "Return the head of the TODO sequence to which KWD belongs.
  8469. If KWD is not set, check if there is a text property remembering the
  8470. right sequence."
  8471. (let (p)
  8472. (cond
  8473. ((not kwd)
  8474. (or (get-text-property (point-at-bol) 'org-todo-head)
  8475. (progn
  8476. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  8477. nil (point-at-eol)))
  8478. (get-text-property p 'org-todo-head))))
  8479. ((not (member kwd org-todo-keywords-1))
  8480. (car org-todo-keywords-1))
  8481. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8482. (defun org-fast-todo-selection (&optional current-state)
  8483. "Fast TODO keyword selection with single keys.
  8484. Returns the new TODO keyword, or nil if no state change should occur.
  8485. When CURRENT-STATE is given and selection letters are not unique globally,
  8486. prefer a state in the current sequence over on in another sequence."
  8487. (let* ((fulltable org-todo-key-alist)
  8488. (head (org-get-todo-sequence-head current-state))
  8489. (done-keywords org-done-keywords) ;; needed for the faces.
  8490. (maxlen (apply 'max (mapcar
  8491. (lambda (x)
  8492. (if (stringp (car x)) (string-width (car x)) 0))
  8493. fulltable)))
  8494. (expert (equal org-use-fast-todo-selection 'expert))
  8495. (prompt "")
  8496. (fwidth (+ maxlen 3 1 3))
  8497. (ncol (/ (- (window-width) 4) fwidth))
  8498. tg cnt e c tbl subtable
  8499. groups ingroup in-current-sequence)
  8500. (save-excursion
  8501. (save-window-excursion
  8502. (if expert
  8503. (set-buffer (get-buffer-create " *Org todo*"))
  8504. (delete-other-windows)
  8505. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8506. (org-switch-to-buffer-other-window " *Org todo*"))
  8507. (erase-buffer)
  8508. (setq-local org-done-keywords done-keywords)
  8509. (setq tbl fulltable cnt 0)
  8510. (while (setq e (pop tbl))
  8511. (cond
  8512. ((equal e '(:startgroup))
  8513. (push '() groups) (setq ingroup t)
  8514. (unless (= cnt 0)
  8515. (setq cnt 0)
  8516. (insert "\n"))
  8517. (setq prompt (concat prompt "{"))
  8518. (insert "{ "))
  8519. ((equal e '(:endgroup))
  8520. (setq ingroup nil cnt 0 in-current-sequence nil)
  8521. (setq prompt (concat prompt "}"))
  8522. (insert "}\n"))
  8523. ((equal e '(:newline))
  8524. (unless (= cnt 0)
  8525. (setq cnt 0)
  8526. (insert "\n")
  8527. (setq e (car tbl))
  8528. (while (equal (car tbl) '(:newline))
  8529. (insert "\n")
  8530. (setq tbl (cdr tbl)))))
  8531. (t
  8532. (setq tg (car e) c (cdr e))
  8533. (if (equal tg head) (setq in-current-sequence t))
  8534. (when ingroup (push tg (car groups)))
  8535. (when in-current-sequence (push e subtable))
  8536. (setq tg (org-add-props tg nil 'face
  8537. (org-get-todo-face tg)))
  8538. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8539. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8540. (insert "[" c "] " tg (make-string
  8541. (- fwidth 4 (length tg)) ?\ ))
  8542. (when (and (= (setq cnt (1+ cnt)) ncol)
  8543. ;; Avoid lines with just a closing delimiter.
  8544. (not (equal (car tbl) '(:endgroup))))
  8545. (insert "\n")
  8546. (when ingroup (insert " "))
  8547. (setq cnt 0)))))
  8548. (insert "\n")
  8549. (goto-char (point-min))
  8550. (unless expert (org-fit-window-to-buffer))
  8551. (message (concat "[a-z..]:Set [SPC]:clear"
  8552. (if expert (concat "\n" prompt) "")))
  8553. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8554. (setq subtable (nreverse subtable))
  8555. (cond
  8556. ((or (= c ?\C-g)
  8557. (and (= c ?q) (not (rassoc c fulltable))))
  8558. (setq quit-flag t))
  8559. ((= c ?\ ) nil)
  8560. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8561. tg (car e))
  8562. tg)
  8563. (t (setq quit-flag t)))))))
  8564. (defun org-entry-is-todo-p ()
  8565. (member (org-get-todo-state) org-not-done-keywords))
  8566. (defun org-entry-is-done-p ()
  8567. (member (org-get-todo-state) org-done-keywords))
  8568. (defun org-get-todo-state ()
  8569. "Return the TODO keyword of the current subtree."
  8570. (save-excursion
  8571. (org-back-to-heading t)
  8572. (and (let ((case-fold-search nil))
  8573. (looking-at org-todo-line-regexp))
  8574. (match-end 2)
  8575. (match-string 2))))
  8576. (defun org-at-date-range-p (&optional inactive-ok)
  8577. "Non-nil if point is inside a date range.
  8578. When optional argument INACTIVE-OK is non-nil, also consider
  8579. inactive time ranges.
  8580. When this function returns a non-nil value, match data is set
  8581. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8582. on INACTIVE-OK."
  8583. (interactive)
  8584. (save-excursion
  8585. (catch 'exit
  8586. (let ((pos (point)))
  8587. (skip-chars-backward "^[<\r\n")
  8588. (skip-chars-backward "<[")
  8589. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8590. (>= (match-end 0) pos)
  8591. (throw 'exit t))
  8592. (skip-chars-backward "^<[\r\n")
  8593. (skip-chars-backward "<[")
  8594. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8595. (>= (match-end 0) pos)
  8596. (throw 'exit t)))
  8597. nil)))
  8598. (defun org-get-repeat (&optional timestamp)
  8599. "Check if there is a time-stamp with repeater in this entry.
  8600. Return the repeater, as a string, or nil. Also return nil when
  8601. this function is called before first heading.
  8602. When optional argument TIMESTAMP is a string, extract the
  8603. repeater from there instead."
  8604. (save-match-data
  8605. (cond
  8606. (timestamp
  8607. (and (string-match org-repeat-re timestamp)
  8608. (match-string-no-properties 1 timestamp)))
  8609. ((org-before-first-heading-p) nil)
  8610. (t
  8611. (save-excursion
  8612. (org-back-to-heading t)
  8613. (let ((end (org-entry-end-position)))
  8614. (catch :repeat
  8615. (while (re-search-forward org-repeat-re end t)
  8616. (when (save-match-data (org-at-timestamp-p 'agenda))
  8617. (throw :repeat (match-string-no-properties 1)))))))))))
  8618. (defvar org-last-changed-timestamp)
  8619. (defvar org-last-inserted-timestamp)
  8620. (defvar org-log-post-message)
  8621. (defvar org-log-note-purpose)
  8622. (defvar org-log-note-how nil)
  8623. (defvar org-log-note-extra)
  8624. (defvar org-log-setup nil)
  8625. (defun org-auto-repeat-maybe (done-word)
  8626. "Check if the current headline contains a repeated time-stamp.
  8627. If yes, set TODO state back to what it was and change the base date
  8628. of repeating deadline/scheduled time stamps to new date.
  8629. This function is run automatically after each state change to a DONE state."
  8630. (let* ((repeat (org-get-repeat))
  8631. (aa (assoc org-last-state org-todo-kwd-alist))
  8632. (interpret (nth 1 aa))
  8633. (head (nth 2 aa))
  8634. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8635. (msg "Entry repeats: ")
  8636. (org-log-done nil)
  8637. (org-todo-log-states nil)
  8638. (end (copy-marker (org-entry-end-position))))
  8639. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8640. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8641. (let ((to-state
  8642. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8643. (and (stringp org-todo-repeat-to-state)
  8644. org-todo-repeat-to-state)
  8645. (and org-todo-repeat-to-state org-last-state))))
  8646. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8647. to-state)
  8648. ((eq interpret 'type) org-last-state)
  8649. (head)
  8650. (t 'none))))
  8651. (org-back-to-heading t)
  8652. (org-add-planning-info nil nil 'closed)
  8653. ;; When `org-log-repeat' is non-nil or entry contains
  8654. ;; a clock, set LAST_REPEAT property.
  8655. (when (or org-log-repeat
  8656. (catch :clock
  8657. (save-excursion
  8658. (while (re-search-forward org-clock-line-re end t)
  8659. (when (org-at-clock-log-p) (throw :clock t))))))
  8660. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8661. (org-time-stamp-format t t))))
  8662. (when org-log-repeat
  8663. (if org-log-setup
  8664. ;; We are already setup for some record.
  8665. (when (eq org-log-repeat 'note)
  8666. ;; Make sure we take a note, not only a time stamp.
  8667. (setq org-log-note-how 'note))
  8668. ;; Set up for taking a record.
  8669. (org-add-log-setup 'state
  8670. (or done-word (car org-done-keywords))
  8671. org-last-state
  8672. org-log-repeat)))
  8673. ;; Time-stamps without a repeater are usually skipped. However,
  8674. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8675. ;; longer relevant.
  8676. (save-excursion
  8677. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8678. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8679. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8680. ;; Update every time-stamp with a repeater in the entry.
  8681. (let ((planning-re (regexp-opt
  8682. (list org-scheduled-string org-deadline-string))))
  8683. (while (re-search-forward org-repeat-re end t)
  8684. (let* ((ts (match-string 0))
  8685. (type (if (not (org-at-planning-p)) "Plain:"
  8686. (save-excursion
  8687. (re-search-backward
  8688. planning-re (line-beginning-position) t)
  8689. (match-string 0)))))
  8690. (when (and (org-at-timestamp-p 'agenda)
  8691. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8692. (let ((n (string-to-number (match-string 2 ts)))
  8693. (what (match-string 3 ts)))
  8694. (when (equal what "w") (setq n (* n 7) what "d"))
  8695. (when (and (equal what "h")
  8696. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8697. ts)))
  8698. (user-error
  8699. "Cannot repeat in %d hour(s) because no hour has been set"
  8700. n))
  8701. ;; Preparation, see if we need to modify the start
  8702. ;; date for the change.
  8703. (when (match-end 1)
  8704. (let ((time (save-match-data (org-time-string-to-time ts)))
  8705. (repeater-type (match-string 1 ts)))
  8706. (cond
  8707. ((equal "." repeater-type)
  8708. ;; Shift starting date to today, or now if
  8709. ;; repeater is by hours.
  8710. (if (equal what "h")
  8711. (org-timestamp-change
  8712. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8713. (org-timestamp-change
  8714. (- (org-today) (time-to-days time)) 'day)))
  8715. ((equal "+" repeater-type)
  8716. (let ((nshiftmax 10)
  8717. (nshift 0))
  8718. (while (or (= nshift 0)
  8719. (not (time-less-p nil time)))
  8720. (when (= nshiftmax (cl-incf nshift))
  8721. (or (y-or-n-p
  8722. (format "%d repeater intervals were not \
  8723. enough to shift date past today. Continue? "
  8724. nshift))
  8725. (user-error "Abort")))
  8726. (org-timestamp-change n (cdr (assoc what whata)))
  8727. (org-in-regexp org-ts-regexp3)
  8728. (setq ts (match-string 1))
  8729. (setq time
  8730. (save-match-data
  8731. (org-time-string-to-time ts)))))
  8732. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8733. ;; Rematch, so that we have everything in place
  8734. ;; for the real shift.
  8735. (org-in-regexp org-ts-regexp3)
  8736. (setq ts (match-string 1))
  8737. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8738. ts)))))
  8739. (save-excursion
  8740. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8741. (setq msg
  8742. (concat msg type " " org-last-changed-timestamp " ")))))))
  8743. (run-hooks 'org-todo-repeat-hook)
  8744. (setq org-log-post-message msg)
  8745. (message msg))))
  8746. (defun org-show-todo-tree (arg)
  8747. "Make a compact tree which shows all headlines marked with TODO.
  8748. The tree will show the lines where the regexp matches, and all higher
  8749. headlines above the match.
  8750. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8751. With a numeric prefix N, construct a sparse tree for the Nth element
  8752. of `org-todo-keywords-1'."
  8753. (interactive "P")
  8754. (let ((case-fold-search nil)
  8755. (kwd-re
  8756. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8757. ((equal arg '(4))
  8758. (let ((kwd
  8759. (completing-read "Keyword (or KWD1|KWD2|...): "
  8760. (mapcar #'list org-todo-keywords-1))))
  8761. (concat "\\("
  8762. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8763. "\\)\\>")))
  8764. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8765. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8766. org-todo-keywords-1)))
  8767. (t (user-error "Invalid prefix argument: %s" arg)))))
  8768. (message "%d TODO entries found"
  8769. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8770. (defun org--deadline-or-schedule (arg type time)
  8771. "Insert DEADLINE or SCHEDULE information in current entry.
  8772. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8773. `org-schedule' for information about ARG and TIME arguments."
  8774. (org-fold-core-ignore-modifications
  8775. (let* ((deadline? (eq type 'deadline))
  8776. (keyword (if deadline? org-deadline-string org-scheduled-string))
  8777. (log (if deadline? org-log-redeadline org-log-reschedule))
  8778. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  8779. (old-date-time (and old-date (org-time-string-to-time old-date)))
  8780. ;; Save repeater cookie from either TIME or current scheduled
  8781. ;; time stamp. We are going to insert it back at the end of
  8782. ;; the process.
  8783. (repeater (or (and (org-string-nw-p time)
  8784. ;; We use `org-ts-regexp-both' because we
  8785. ;; need to tell the difference between a
  8786. ;; real repeater and a time delta, e.g.
  8787. ;; "+2d".
  8788. (string-match-p org-ts-regexp-both time)
  8789. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8790. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8791. time)
  8792. (match-string 1 time))
  8793. (and (org-string-nw-p old-date)
  8794. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8795. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8796. old-date)
  8797. (match-string 1 old-date)))))
  8798. (pcase arg
  8799. (`(4)
  8800. (if (not old-date)
  8801. (message (if deadline? "Entry had no deadline to remove"
  8802. "Entry was not scheduled"))
  8803. (when (and old-date log)
  8804. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  8805. nil old-date log))
  8806. (org-remove-timestamp-with-keyword keyword)
  8807. (message (if deadline? "Entry no longer has a deadline."
  8808. "Entry is no longer scheduled."))))
  8809. (`(16)
  8810. (save-excursion
  8811. (org-back-to-heading t)
  8812. (let ((regexp (if deadline? org-deadline-time-regexp
  8813. org-scheduled-time-regexp)))
  8814. (if (not (re-search-forward regexp (line-end-position 2) t))
  8815. (user-error (if deadline? "No deadline information to update"
  8816. "No scheduled information to update"))
  8817. (let* ((rpl0 (match-string 1))
  8818. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  8819. (msg (if deadline? "Warn starting from" "Delay until")))
  8820. (replace-match
  8821. (concat keyword
  8822. " <" rpl
  8823. (format " -%dd"
  8824. (abs (- (time-to-days
  8825. (save-match-data
  8826. (org-read-date
  8827. nil t nil msg old-date-time)))
  8828. (time-to-days old-date-time))))
  8829. ">") t t))))))
  8830. (_
  8831. (org-add-planning-info type time 'closed)
  8832. (when (and old-date
  8833. log
  8834. (not (equal old-date org-last-inserted-timestamp)))
  8835. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  8836. org-last-inserted-timestamp
  8837. old-date
  8838. log))
  8839. (when repeater
  8840. (save-excursion
  8841. (org-back-to-heading t)
  8842. (when (re-search-forward
  8843. (concat keyword " " org-last-inserted-timestamp)
  8844. (line-end-position 2)
  8845. t)
  8846. (goto-char (1- (match-end 0)))
  8847. (insert-and-inherit " " repeater)
  8848. (setq org-last-inserted-timestamp
  8849. (concat (substring org-last-inserted-timestamp 0 -1)
  8850. " " repeater
  8851. (substring org-last-inserted-timestamp -1))))))
  8852. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  8853. org-last-inserted-timestamp))))))
  8854. (defun org-deadline (arg &optional time)
  8855. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  8856. When called interactively, this command pops up the Emacs calendar to let
  8857. the user select a date.
  8858. With one universal prefix argument, remove any deadline from the item.
  8859. With two universal prefix arguments, prompt for a warning delay.
  8860. With argument TIME, set the deadline at the corresponding date. TIME
  8861. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  8862. (interactive "P")
  8863. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8864. (org-map-entries
  8865. (lambda () (org--deadline-or-schedule arg 'deadline time))
  8866. nil
  8867. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8868. 'region-start-level
  8869. 'region)
  8870. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  8871. (org--deadline-or-schedule arg 'deadline time)))
  8872. (defun org-schedule (arg &optional time)
  8873. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  8874. When called interactively, this command pops up the Emacs calendar to let
  8875. the user select a date.
  8876. With one universal prefix argument, remove any scheduling date from the item.
  8877. With two universal prefix arguments, prompt for a delay cookie.
  8878. With argument TIME, scheduled at the corresponding date. TIME can
  8879. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  8880. (interactive "P")
  8881. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8882. (org-map-entries
  8883. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  8884. nil
  8885. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8886. 'region-start-level
  8887. 'region)
  8888. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  8889. (org--deadline-or-schedule arg 'scheduled time)))
  8890. (defun org-get-scheduled-time (pom &optional inherit)
  8891. "Get the scheduled time as a time tuple, of a format suitable
  8892. for calling org-schedule with, or if there is no scheduling,
  8893. returns nil."
  8894. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  8895. (when time
  8896. (org-time-string-to-time time))))
  8897. (defun org-get-deadline-time (pom &optional inherit)
  8898. "Get the deadline as a time tuple, of a format suitable for
  8899. calling org-deadline with, or if there is no scheduling, returns
  8900. nil."
  8901. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  8902. (when time
  8903. (org-time-string-to-time time))))
  8904. (defun org-remove-timestamp-with-keyword (keyword)
  8905. "Remove all time stamps with KEYWORD in the current entry."
  8906. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  8907. beg)
  8908. (save-excursion
  8909. (org-back-to-heading t)
  8910. (setq beg (point))
  8911. (outline-next-heading)
  8912. (while (re-search-backward re beg t)
  8913. (replace-match "")
  8914. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  8915. (equal (char-before) ?\ ))
  8916. (backward-delete-char 1)
  8917. (when (string-match "^[ \t]*$" (buffer-substring
  8918. (point-at-bol) (point-at-eol)))
  8919. (delete-region (point-at-bol)
  8920. (min (point-max) (1+ (point-at-eol))))))))))
  8921. (defvar org-time-was-given) ; dynamically scoped parameter
  8922. (defvar org-end-time-was-given) ; dynamically scoped parameter
  8923. (defun org-at-planning-p ()
  8924. "Non-nil when point is on a planning info line."
  8925. ;; This is as accurate and faster than `org-element-at-point' since
  8926. ;; planning info location is fixed in the section.
  8927. (or (let ((cached (org-element-at-point nil 'cached)))
  8928. (and cached
  8929. (eq 'planning (org-element-type cached))))
  8930. (org-with-wide-buffer
  8931. (beginning-of-line)
  8932. (and (looking-at-p org-planning-line-re)
  8933. (eq (point)
  8934. (ignore-errors
  8935. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  8936. (org-back-to-heading t)
  8937. (org-with-limited-levels (org-back-to-heading t)))
  8938. (line-beginning-position 2)))))))
  8939. (defun org-add-planning-info (what &optional time &rest remove)
  8940. "Insert new timestamp with keyword in the planning line.
  8941. WHAT indicates what kind of time stamp to add. It is a symbol
  8942. among `closed', `deadline', `scheduled' and nil. TIME indicates
  8943. the time to use. If none is given, the user is prompted for
  8944. a date. REMOVE indicates what kind of entries to remove. An old
  8945. WHAT entry will also be removed."
  8946. (org-fold-core-ignore-modifications
  8947. (let (org-time-was-given org-end-time-was-given default-time default-input)
  8948. (when (and (memq what '(scheduled deadline))
  8949. (or (not time)
  8950. (and (stringp time)
  8951. (string-match "^[-+]+[0-9]" time))))
  8952. ;; Try to get a default date/time from existing timestamp
  8953. (save-excursion
  8954. (org-back-to-heading t)
  8955. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  8956. (when (re-search-forward (if (eq what 'scheduled)
  8957. org-scheduled-time-regexp
  8958. org-deadline-time-regexp)
  8959. end t)
  8960. (setq ts (match-string 1)
  8961. default-time (org-time-string-to-time ts)
  8962. default-input (and ts (org-get-compact-tod ts)))))))
  8963. (when what
  8964. (setq time
  8965. (if (stringp time)
  8966. ;; This is a string (relative or absolute), set
  8967. ;; proper date.
  8968. (apply #'encode-time
  8969. (org-read-date-analyze
  8970. time default-time (decode-time default-time)))
  8971. ;; If necessary, get the time from the user
  8972. (or time (org-read-date nil 'to-time nil
  8973. (cl-case what
  8974. (deadline "DEADLINE")
  8975. (scheduled "SCHEDULED")
  8976. (otherwise nil))
  8977. default-time default-input)))))
  8978. (org-with-wide-buffer
  8979. (org-back-to-heading t)
  8980. (let ((planning? (save-excursion
  8981. (forward-line)
  8982. (looking-at-p org-planning-line-re))))
  8983. (cond
  8984. (planning?
  8985. (forward-line)
  8986. ;; Move to current indentation.
  8987. (skip-chars-forward " \t")
  8988. ;; Check if we have to remove something.
  8989. (dolist (type (if what (cons what remove) remove))
  8990. (save-excursion
  8991. (when (re-search-forward
  8992. (cl-case type
  8993. (closed org-closed-time-regexp)
  8994. (deadline org-deadline-time-regexp)
  8995. (scheduled org-scheduled-time-regexp)
  8996. (otherwise (error "Invalid planning type: %s" type)))
  8997. (line-end-position)
  8998. t)
  8999. ;; Delete until next keyword or end of line.
  9000. (delete-region
  9001. (match-beginning 0)
  9002. (if (re-search-forward org-keyword-time-not-clock-regexp
  9003. (line-end-position)
  9004. t)
  9005. (match-beginning 0)
  9006. (line-end-position))))))
  9007. ;; If there is nothing more to add and no more keyword is
  9008. ;; left, remove the line completely.
  9009. (if (and (looking-at-p "[ \t]*$") (not what))
  9010. (delete-region (line-end-position 0)
  9011. (line-end-position))
  9012. ;; If we removed last keyword, do not leave trailing white
  9013. ;; space at the end of line.
  9014. (let ((p (point)))
  9015. (save-excursion
  9016. (end-of-line)
  9017. (unless (= (skip-chars-backward " \t" p) 0)
  9018. (delete-region (point) (line-end-position)))))))
  9019. (what
  9020. (end-of-line)
  9021. (insert-and-inherit "\n")
  9022. (when org-adapt-indentation
  9023. (indent-to-column (1+ (org-outline-level)))))
  9024. (t nil)))
  9025. (when what
  9026. ;; Insert planning keyword.
  9027. (insert-and-inherit (cl-case what
  9028. (closed org-closed-string)
  9029. (deadline org-deadline-string)
  9030. (scheduled org-scheduled-string)
  9031. (otherwise (error "Invalid planning type: %s" what)))
  9032. " ")
  9033. ;; Insert associated timestamp.
  9034. (let ((ts (org-insert-time-stamp
  9035. time
  9036. (or org-time-was-given
  9037. (and (eq what 'closed) org-log-done-with-time))
  9038. (eq what 'closed)
  9039. nil nil (list org-end-time-was-given))))
  9040. (unless (eolp) (insert " "))
  9041. ts))))))
  9042. (defvar org-log-note-marker (make-marker)
  9043. "Marker pointing at the entry where the note is to be inserted.")
  9044. (defvar org-log-note-purpose nil)
  9045. (defvar org-log-note-state nil)
  9046. (defvar org-log-note-previous-state nil)
  9047. (defvar org-log-note-extra nil)
  9048. (defvar org-log-note-window-configuration nil)
  9049. (defvar org-log-note-return-to (make-marker))
  9050. (defvar org-log-note-effective-time nil
  9051. "Remembered current time.
  9052. So that dynamically scoped `org-extend-today-until' affects
  9053. timestamps in state change log.")
  9054. (defvar org-log-post-message nil
  9055. "Message to be displayed after a log note has been stored.
  9056. The auto-repeater uses this.")
  9057. (defun org-add-note ()
  9058. "Add a note to the current entry.
  9059. This is done in the same way as adding a state change note."
  9060. (interactive)
  9061. (org-add-log-setup 'note))
  9062. (defun org-log-beginning (&optional create)
  9063. "Return expected start of log notes in current entry.
  9064. When optional argument CREATE is non-nil, the function creates
  9065. a drawer to store notes, if necessary. Returned position ignores
  9066. narrowing."
  9067. (org-with-wide-buffer
  9068. (let ((drawer (org-log-into-drawer)))
  9069. (cond
  9070. (drawer
  9071. (org-end-of-meta-data)
  9072. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9073. (end (if (org-at-heading-p) (point)
  9074. (save-excursion (outline-next-heading) (point))))
  9075. (case-fold-search t))
  9076. (catch 'exit
  9077. ;; Try to find existing drawer.
  9078. (while (re-search-forward regexp end t)
  9079. (let ((element (org-element-at-point)))
  9080. (when (eq (org-element-type element) 'drawer)
  9081. (let ((cend (org-element-property :contents-end element)))
  9082. (when (and (not org-log-states-order-reversed) cend)
  9083. (goto-char cend)))
  9084. (throw 'exit nil))))
  9085. ;; No drawer found. Create one, if permitted.
  9086. (when create
  9087. ;; Avoid situation when we insert drawer right before
  9088. ;; first "*". Otherwise, if the previous heading is
  9089. ;; folded, we are inserting after visible newline at
  9090. ;; the end of the fold, thus breaking the fold
  9091. ;; continuity.
  9092. (when (org-at-heading-p) (backward-char))
  9093. (org-fold-core-ignore-modifications
  9094. (unless (bolp) (insert-and-inherit "\n"))
  9095. (let ((beg (point)))
  9096. (insert-and-inherit ":" drawer ":\n:END:\n")
  9097. (org-indent-region beg (point))
  9098. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9099. (end-of-line -1))))
  9100. (t
  9101. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9102. (skip-chars-forward " \t\n")
  9103. (beginning-of-line)
  9104. (unless org-log-states-order-reversed
  9105. (org-skip-over-state-notes)
  9106. (skip-chars-backward " \t\n")
  9107. (beginning-of-line 2)))))
  9108. (if (bolp) (point) (line-beginning-position 2))))
  9109. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9110. "Set up the post command hook to take a note.
  9111. If this is about to TODO state change, the new state is expected in STATE.
  9112. HOW is an indicator what kind of note should be created.
  9113. EXTRA is additional text that will be inserted into the notes buffer."
  9114. (move-marker org-log-note-marker (point))
  9115. (setq org-log-note-purpose purpose
  9116. org-log-note-state state
  9117. org-log-note-previous-state prev-state
  9118. org-log-note-how how
  9119. org-log-note-extra extra
  9120. org-log-note-effective-time (org-current-effective-time)
  9121. org-log-setup t)
  9122. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9123. (defun org-skip-over-state-notes ()
  9124. "Skip past the list of State notes in an entry."
  9125. (when (ignore-errors (goto-char (org-in-item-p)))
  9126. (let* ((struct (org-list-struct))
  9127. (prevs (org-list-prevs-alist struct))
  9128. (regexp
  9129. (concat "[ \t]*- +"
  9130. (replace-regexp-in-string
  9131. " +" " +"
  9132. (org-replace-escapes
  9133. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9134. `(("%d" . ,org-ts-regexp-inactive)
  9135. ("%D" . ,org-ts-regexp)
  9136. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9137. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9138. ("%t" . ,org-ts-regexp-inactive)
  9139. ("%T" . ,org-ts-regexp)
  9140. ("%u" . ".*?")
  9141. ("%U" . ".*?")))))))
  9142. (while (looking-at-p regexp)
  9143. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9144. (org-list-get-item-end (point) struct)))))))
  9145. (defun org-add-log-note (&optional _purpose)
  9146. "Pop up a window for taking a note, and add this note later."
  9147. (remove-hook 'post-command-hook 'org-add-log-note)
  9148. (setq org-log-setup nil)
  9149. (setq org-log-note-window-configuration (current-window-configuration))
  9150. (delete-other-windows)
  9151. (move-marker org-log-note-return-to (point))
  9152. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9153. (goto-char org-log-note-marker)
  9154. (org-switch-to-buffer-other-window "*Org Note*")
  9155. (erase-buffer)
  9156. (if (memq org-log-note-how '(time state))
  9157. (org-store-log-note)
  9158. (let ((org-inhibit-startup t)) (org-mode))
  9159. (insert (format "# Insert note for %s.
  9160. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9161. (cl-case org-log-note-purpose
  9162. (clock-out "stopped clock")
  9163. (done "closed todo item")
  9164. (reschedule "rescheduling")
  9165. (delschedule "no longer scheduled")
  9166. (redeadline "changing deadline")
  9167. (deldeadline "removing deadline")
  9168. (refile "refiling")
  9169. (note "this entry")
  9170. (state
  9171. (format "state change from \"%s\" to \"%s\""
  9172. (or org-log-note-previous-state "")
  9173. (or org-log-note-state "")))
  9174. (t (error "This should not happen")))))
  9175. (when org-log-note-extra (insert org-log-note-extra))
  9176. (setq-local org-finish-function 'org-store-log-note)
  9177. (run-hooks 'org-log-buffer-setup-hook)))
  9178. (defvar org-note-abort nil) ; dynamically scoped
  9179. (defun org-store-log-note ()
  9180. "Finish taking a log note, and insert it to where it belongs."
  9181. (let ((txt (prog1 (buffer-string)
  9182. (kill-buffer)))
  9183. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9184. lines)
  9185. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9186. (setq txt (replace-match "" t t txt)))
  9187. (when (string-match "\\s-+\\'" txt)
  9188. (setq txt (replace-match "" t t txt)))
  9189. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9190. (when (org-string-nw-p note)
  9191. (setq note
  9192. (org-replace-escapes
  9193. note
  9194. (list (cons "%u" (user-login-name))
  9195. (cons "%U" user-full-name)
  9196. (cons "%t" (format-time-string
  9197. (org-time-stamp-format 'long 'inactive)
  9198. org-log-note-effective-time))
  9199. (cons "%T" (format-time-string
  9200. (org-time-stamp-format 'long nil)
  9201. org-log-note-effective-time))
  9202. (cons "%d" (format-time-string
  9203. (org-time-stamp-format nil 'inactive)
  9204. org-log-note-effective-time))
  9205. (cons "%D" (format-time-string
  9206. (org-time-stamp-format nil nil)
  9207. org-log-note-effective-time))
  9208. (cons "%s" (cond
  9209. ((not org-log-note-state) "")
  9210. ((string-match-p org-ts-regexp
  9211. org-log-note-state)
  9212. (format "\"[%s]\""
  9213. (substring org-log-note-state 1 -1)))
  9214. (t (format "\"%s\"" org-log-note-state))))
  9215. (cons "%S"
  9216. (cond
  9217. ((not org-log-note-previous-state) "")
  9218. ((string-match-p org-ts-regexp
  9219. org-log-note-previous-state)
  9220. (format "\"[%s]\""
  9221. (substring
  9222. org-log-note-previous-state 1 -1)))
  9223. (t (format "\"%s\""
  9224. org-log-note-previous-state)))))))
  9225. (when lines (setq note (concat note " \\\\")))
  9226. (push note lines))
  9227. (when (and lines (not org-note-abort))
  9228. (with-current-buffer (marker-buffer org-log-note-marker)
  9229. (org-fold-core-ignore-modifications
  9230. (org-with-wide-buffer
  9231. ;; Find location for the new note.
  9232. (goto-char org-log-note-marker)
  9233. (set-marker org-log-note-marker nil)
  9234. ;; Note associated to a clock is to be located right after
  9235. ;; the clock. Do not move point.
  9236. (unless (eq org-log-note-purpose 'clock-out)
  9237. (goto-char (org-log-beginning t)))
  9238. ;; Make sure point is at the beginning of an empty line.
  9239. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9240. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9241. ;; In an existing list, add a new item at the top level.
  9242. ;; Otherwise, indent line like a regular one.
  9243. (let ((itemp (org-in-item-p)))
  9244. (if itemp
  9245. (indent-line-to
  9246. (let ((struct (save-excursion
  9247. (goto-char itemp) (org-list-struct))))
  9248. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9249. (org-indent-line)))
  9250. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9251. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9252. (dolist (line lines)
  9253. (insert-and-inherit "\n")
  9254. (indent-line-to ind)
  9255. (insert-and-inherit line)))
  9256. (message "Note stored")
  9257. (org-back-to-heading t))))))
  9258. ;; Don't add undo information when called from `org-agenda-todo'.
  9259. (set-window-configuration org-log-note-window-configuration)
  9260. (with-current-buffer (marker-buffer org-log-note-return-to)
  9261. (goto-char org-log-note-return-to))
  9262. (move-marker org-log-note-return-to nil)
  9263. (when org-log-post-message (message "%s" org-log-post-message)))
  9264. (defun org-remove-empty-drawer-at (pos)
  9265. "Remove an empty drawer at position POS.
  9266. POS may also be a marker."
  9267. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9268. (org-with-wide-buffer
  9269. (goto-char pos)
  9270. (let ((drawer (org-element-at-point)))
  9271. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9272. (not (org-element-property :contents-begin drawer)))
  9273. (delete-region (org-element-property :begin drawer)
  9274. (progn (goto-char (org-element-property :end drawer))
  9275. (skip-chars-backward " \r\t\n")
  9276. (forward-line)
  9277. (point))))))))
  9278. (defvar org-ts-type nil)
  9279. (defun org-sparse-tree (&optional arg type)
  9280. "Create a sparse tree, prompt for the details.
  9281. This command can create sparse trees. You first need to select the type
  9282. of match used to create the tree:
  9283. t Show all TODO entries.
  9284. T Show entries with a specific TODO keyword.
  9285. m Show entries selected by a tags/property match.
  9286. p Enter a property name and its value (both with completion on existing
  9287. names/values) and show entries with that property.
  9288. r Show entries matching a regular expression (`/' can be used as well).
  9289. b Show deadlines and scheduled items before a date.
  9290. a Show deadlines and scheduled items after a date.
  9291. d Show deadlines due within `org-deadline-warning-days'.
  9292. D Show deadlines and scheduled items between a date range."
  9293. (interactive "P")
  9294. (setq type (or type org-sparse-tree-default-date-type))
  9295. (setq org-ts-type type)
  9296. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9297. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9298. [c]ycle through date types: %s"
  9299. (cl-case type
  9300. (all "all timestamps")
  9301. (scheduled "only scheduled")
  9302. (deadline "only deadline")
  9303. (active "only active timestamps")
  9304. (inactive "only inactive timestamps")
  9305. (closed "with a closed time-stamp")
  9306. (otherwise "scheduled/deadline")))
  9307. (let ((answer (read-char-exclusive)))
  9308. (cl-case answer
  9309. (?c
  9310. (org-sparse-tree
  9311. arg
  9312. (cadr
  9313. (memq type '(nil all scheduled deadline active inactive closed)))))
  9314. (?d (call-interactively 'org-check-deadlines))
  9315. (?b (call-interactively 'org-check-before-date))
  9316. (?a (call-interactively 'org-check-after-date))
  9317. (?D (call-interactively 'org-check-dates-range))
  9318. (?t (call-interactively 'org-show-todo-tree))
  9319. (?T (org-show-todo-tree '(4)))
  9320. (?m (call-interactively 'org-match-sparse-tree))
  9321. ((?p ?P)
  9322. (let* ((kwd (completing-read
  9323. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9324. (value (completing-read
  9325. "Value: " (mapcar #'list (org-property-values kwd)))))
  9326. (unless (string-match "\\`{.*}\\'" value)
  9327. (setq value (concat "\"" value "\"")))
  9328. (org-match-sparse-tree arg (concat kwd "=" value))))
  9329. ((?r ?R ?/) (call-interactively 'org-occur))
  9330. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9331. (defvar-local org-occur-highlights nil
  9332. "List of overlays used for occur matches.")
  9333. (defvar-local org-occur-parameters nil
  9334. "Parameters of the active org-occur calls.
  9335. This is a list, each call to org-occur pushes as cons cell,
  9336. containing the regular expression and the callback, onto the list.
  9337. The list can contain several entries if `org-occur' has been called
  9338. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9339. will only contain one set of parameters. When the highlights are
  9340. removed (for example with `C-c C-c', or with the next edit (depending
  9341. on `org-remove-highlights-with-change'), this variable is emptied
  9342. as well.")
  9343. (defun org-occur (regexp &optional keep-previous callback)
  9344. "Make a compact tree showing all matches of REGEXP.
  9345. The tree will show the lines where the regexp matches, and any other context
  9346. defined in `org-fold-show-context-detail', which see.
  9347. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9348. done by a previous call to `org-occur' will be kept, to allow stacking of
  9349. calls to this command.
  9350. Optional argument CALLBACK can be a function of no argument. In this case,
  9351. it is called with point at the end of the match, match data being set
  9352. accordingly. Current match is shown only if the return value is non-nil.
  9353. The function must neither move point nor alter narrowing."
  9354. (interactive "sRegexp: \nP")
  9355. (when (equal regexp "")
  9356. (user-error "Regexp cannot be empty"))
  9357. (unless keep-previous
  9358. (org-remove-occur-highlights nil nil t))
  9359. (push (cons regexp callback) org-occur-parameters)
  9360. (let ((cnt 0))
  9361. (save-excursion
  9362. (goto-char (point-min))
  9363. (when (or (not keep-previous) ; do not want to keep
  9364. (not org-occur-highlights)) ; no previous matches
  9365. ;; hide everything
  9366. (org-cycle-overview))
  9367. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9368. (isearch-no-upper-case-p regexp t)
  9369. org-occur-case-fold-search)))
  9370. (while (re-search-forward regexp nil t)
  9371. (when (or (not callback)
  9372. (save-match-data (funcall callback)))
  9373. (setq cnt (1+ cnt))
  9374. (when org-highlight-sparse-tree-matches
  9375. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9376. (org-fold-show-context 'occur-tree)))))
  9377. (when org-remove-highlights-with-change
  9378. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9379. nil 'local))
  9380. (unless org-sparse-tree-open-archived-trees
  9381. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9382. (run-hooks 'org-occur-hook)
  9383. (when (called-interactively-p 'interactive)
  9384. (message "%d match(es) for regexp %s" cnt regexp))
  9385. cnt))
  9386. (defun org-occur-next-match (&optional n _reset)
  9387. "Function for `next-error-function' to find sparse tree matches.
  9388. N is the number of matches to move, when negative move backwards.
  9389. This function always goes back to the starting point when no
  9390. match is found."
  9391. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9392. (search-func (if (< n 0)
  9393. 'previous-single-char-property-change
  9394. 'next-single-char-property-change))
  9395. (n (abs n))
  9396. (pos (point))
  9397. p1)
  9398. (catch 'exit
  9399. (while (setq p1 (funcall search-func (point) 'org-type))
  9400. (when (equal p1 limit)
  9401. (goto-char pos)
  9402. (user-error "No more matches"))
  9403. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9404. (setq n (1- n))
  9405. (when (= n 0)
  9406. (goto-char p1)
  9407. (throw 'exit (point))))
  9408. (goto-char p1))
  9409. (goto-char p1)
  9410. (user-error "No more matches"))))
  9411. (defun org-highlight-new-match (beg end)
  9412. "Highlight from BEG to END and mark the highlight is an occur headline."
  9413. (let ((ov (make-overlay beg end)))
  9414. (overlay-put ov 'face 'secondary-selection)
  9415. (overlay-put ov 'org-type 'org-occur)
  9416. (push ov org-occur-highlights)))
  9417. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9418. "Remove the occur highlights from the buffer.
  9419. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9420. from the `before-change-functions' in the current buffer."
  9421. (interactive)
  9422. (unless org-inhibit-highlight-removal
  9423. (mapc #'delete-overlay org-occur-highlights)
  9424. (setq org-occur-highlights nil)
  9425. (setq org-occur-parameters nil)
  9426. (unless noremove
  9427. (remove-hook 'before-change-functions
  9428. 'org-remove-occur-highlights 'local))))
  9429. ;;;; Priorities
  9430. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9431. "Regular expression matching the priority indicator.
  9432. A priority indicator can be e.g. [#A] or [#1].
  9433. This regular expression matches these groups:
  9434. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9435. 1 : the priority cookie, e.g. \"[#A]\"
  9436. 2 : the value of the priority cookie, e.g. \"A\".")
  9437. (defun org-priority-up ()
  9438. "Increase the priority of the current item."
  9439. (interactive)
  9440. (org-priority 'up))
  9441. (defun org-priority-down ()
  9442. "Decrease the priority of the current item."
  9443. (interactive)
  9444. (org-priority 'down))
  9445. (defun org-priority (&optional action show)
  9446. "Change the priority of an item.
  9447. When called interactively with a `\\[universal-argument]' prefix,
  9448. show the priority in the minibuffer instead of changing it.
  9449. When called programmatically, ACTION can be `set', `up', `down',
  9450. or a character."
  9451. (interactive "P")
  9452. (when show
  9453. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9454. ;; passed the SHOW argument should be removed.
  9455. (warn "`org-priority' called with deprecated SHOW argument"))
  9456. (if (equal action '(4))
  9457. (org-priority-show)
  9458. (unless org-priority-enable-commands
  9459. (user-error "Priority commands are disabled"))
  9460. (setq action (or action 'set))
  9461. (let ((nump (< org-priority-lowest 65))
  9462. current new news have remove)
  9463. (save-excursion
  9464. (org-back-to-heading t)
  9465. (when (looking-at org-priority-regexp)
  9466. (let ((ms (match-string 2)))
  9467. (setq current (org-priority-to-value ms)
  9468. have t)))
  9469. (cond
  9470. ((eq action 'remove)
  9471. (setq remove t new ?\ ))
  9472. ((or (eq action 'set)
  9473. (integerp action))
  9474. (if (not (eq action 'set))
  9475. (setq new action)
  9476. (setq
  9477. new
  9478. (if nump
  9479. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9480. (number-to-string org-priority-highest)
  9481. (number-to-string org-priority-lowest)))
  9482. (s (if (< 9 org-priority-lowest)
  9483. (read-string msg)
  9484. (message msg)
  9485. (char-to-string (read-char-exclusive)))))
  9486. (if (equal s " ") ?\s (string-to-number s)))
  9487. (progn (message "Priority %c-%c, SPC to remove: "
  9488. org-priority-highest org-priority-lowest)
  9489. (save-match-data
  9490. (setq new (read-char-exclusive)))))))
  9491. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9492. (= (upcase org-priority-lowest) org-priority-lowest))
  9493. (setq new (upcase new)))
  9494. (cond ((equal new ?\s) (setq remove t))
  9495. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9496. (user-error
  9497. (if nump
  9498. "Priority must be between `%s' and `%s'"
  9499. "Priority must be between `%c' and `%c'")
  9500. org-priority-highest org-priority-lowest))))
  9501. ((eq action 'up)
  9502. (setq new (if have
  9503. (1- current) ; normal cycling
  9504. ;; last priority was empty
  9505. (if (eq last-command this-command)
  9506. org-priority-lowest ; wrap around empty to lowest
  9507. ;; default
  9508. (if org-priority-start-cycle-with-default
  9509. org-priority-default
  9510. (1- org-priority-default))))))
  9511. ((eq action 'down)
  9512. (setq new (if have
  9513. (1+ current) ; normal cycling
  9514. ;; last priority was empty
  9515. (if (eq last-command this-command)
  9516. org-priority-highest ; wrap around empty to highest
  9517. ;; default
  9518. (if org-priority-start-cycle-with-default
  9519. org-priority-default
  9520. (1+ org-priority-default))))))
  9521. (t (user-error "Invalid action")))
  9522. (when (or (< (upcase new) org-priority-highest)
  9523. (> (upcase new) org-priority-lowest))
  9524. (if (and (memq action '(up down))
  9525. (not have) (not (eq last-command this-command)))
  9526. ;; `new' is from default priority
  9527. (error
  9528. "The default can not be set, see `org-priority-default' why")
  9529. ;; normal cycling: `new' is beyond highest/lowest priority
  9530. ;; and is wrapped around to the empty priority
  9531. (setq remove t)))
  9532. ;; Numerical priorities are limited to 64, beyond that number,
  9533. ;; assume the priority cookie is a character.
  9534. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9535. (if have
  9536. (if remove
  9537. (replace-match "" t t nil 1)
  9538. (replace-match news t t nil 2))
  9539. (if remove
  9540. (user-error "No priority cookie found in line")
  9541. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9542. (if (match-end 2)
  9543. (progn
  9544. (goto-char (match-end 2))
  9545. (insert " [#" news "]"))
  9546. (goto-char (match-beginning 3))
  9547. (insert "[#" news "] "))))
  9548. (org-align-tags))
  9549. (if remove
  9550. (message "Priority removed")
  9551. (message "Priority of current item set to %s" news)))))
  9552. (defalias 'org-show-priority 'org-priority-show)
  9553. (defun org-priority-show ()
  9554. "Show the priority of the current item.
  9555. This priority is composed of the main priority given with the [#A] cookies,
  9556. and by additional input from the age of a schedules or deadline entry."
  9557. (interactive)
  9558. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9559. (org-get-at-bol 'priority)
  9560. (save-excursion
  9561. (save-match-data
  9562. (beginning-of-line)
  9563. (and (looking-at org-heading-regexp)
  9564. (org-get-priority (match-string 0))))))))
  9565. (message "Priority is %d" (if pri pri -1000))))
  9566. (defun org-get-priority (s)
  9567. "Find priority cookie and return priority.
  9568. S is a string against which you can match `org-priority-regexp'.
  9569. If `org-priority-get-priority-function' is set to a custom
  9570. function, use it. Otherwise process S and output the priority
  9571. value, an integer."
  9572. (save-match-data
  9573. (if (functionp org-priority-get-priority-function)
  9574. (funcall org-priority-get-priority-function s)
  9575. (if (not (string-match org-priority-regexp s))
  9576. (* 1000 (- org-priority-lowest org-priority-default))
  9577. (* 1000 (- org-priority-lowest
  9578. (org-priority-to-value (match-string 2 s))))))))
  9579. ;;;; Tags
  9580. (defvar org-agenda-archives-mode)
  9581. (defvar org-map-continue-from nil
  9582. "Position from where mapping should continue.
  9583. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9584. (defvar org-scanner-tags nil
  9585. "The current tag list while the tags scanner is running.")
  9586. (defvar org-trust-scanner-tags nil
  9587. "Should `org-get-tags' use the tags for the scanner.
  9588. This is for internal dynamical scoping only.
  9589. When this is non-nil, the function `org-get-tags' will return the value
  9590. of `org-scanner-tags' instead of building the list by itself. This
  9591. can lead to large speed-ups when the tags scanner is used in a file with
  9592. many entries, and when the list of tags is retrieved, for example to
  9593. obtain a list of properties. Building the tags list for each entry in such
  9594. a file becomes an N^2 operation - but with this variable set, it scales
  9595. as N.")
  9596. (defvar org--matcher-tags-todo-only nil)
  9597. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9598. "Scan headline tags with inheritance and produce output ACTION.
  9599. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9600. or `agenda' to produce an entry list for an agenda view. It can also be
  9601. a Lisp form or a function that should be called at each matched headline, in
  9602. this case the return value is a list of all return values from these calls.
  9603. MATCHER is a function accepting three arguments, returning
  9604. a non-nil value whenever a given set of tags qualifies a headline
  9605. for inclusion. See `org-make-tags-matcher' for more information.
  9606. As a special case, it can also be set to t (respectively nil) in
  9607. order to match all (respectively none) headline.
  9608. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9609. included in the output.
  9610. START-LEVEL can be a string with asterisks, reducing the scope to
  9611. headlines matching this string."
  9612. (require 'org-agenda)
  9613. (let* ((re (concat "^"
  9614. (if start-level
  9615. ;; Get the correct level to match
  9616. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9617. org-outline-regexp)
  9618. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  9619. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9620. (props (list 'face 'default
  9621. 'done-face 'org-agenda-done
  9622. 'undone-face 'default
  9623. 'mouse-face 'highlight
  9624. 'org-not-done-regexp org-not-done-regexp
  9625. 'org-todo-regexp org-todo-regexp
  9626. 'org-complex-heading-regexp org-complex-heading-regexp
  9627. 'help-echo
  9628. (format "mouse-2 or RET jump to Org file %S"
  9629. (abbreviate-file-name
  9630. (or (buffer-file-name (buffer-base-buffer))
  9631. (buffer-name (buffer-base-buffer)))))))
  9632. (org-map-continue-from nil)
  9633. lspos tags tags-list
  9634. (tags-alist (list (cons 0 org-file-tags)))
  9635. (llast 0) rtn rtn1 level category i txt
  9636. todo marker entry priority
  9637. ts-date ts-date-type ts-date-pair)
  9638. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9639. (setq action (list 'lambda nil action)))
  9640. (save-excursion
  9641. (goto-char (point-min))
  9642. (when (eq action 'sparse-tree)
  9643. (org-cycle-overview)
  9644. (org-remove-occur-highlights))
  9645. (if (org-element--cache-active-p)
  9646. (let ((fast-re (concat "^"
  9647. (if start-level
  9648. ;; Get the correct level to match
  9649. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9650. org-outline-regexp))))
  9651. (org-element-cache-map
  9652. (lambda (el)
  9653. (goto-char (org-element-property :begin el))
  9654. (setq todo (org-element-property :todo-keyword el)
  9655. level (org-element-property :level el)
  9656. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9657. tags-list (org-get-tags el)
  9658. org-scanner-tags tags-list)
  9659. (when (eq action 'agenda)
  9660. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9661. ts-date (car ts-date-pair)
  9662. ts-date-type (cdr ts-date-pair)))
  9663. (catch :skip
  9664. (when (and
  9665. ;; eval matcher only when the todo condition is OK
  9666. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9667. (if (functionp matcher)
  9668. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9669. (funcall matcher todo tags-list level))
  9670. matcher))
  9671. ;; Call the skipper, but return t if it does not
  9672. ;; skip, so that the `and' form continues evaluating.
  9673. (progn
  9674. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9675. t)
  9676. ;; Check if timestamps are deselecting this entry
  9677. (or (not todo-only)
  9678. (and (member todo org-todo-keywords-1)
  9679. (or (not org-agenda-tags-todo-honor-ignore-options)
  9680. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9681. ;; select this headline
  9682. (cond
  9683. ((eq action 'sparse-tree)
  9684. (and org-highlight-sparse-tree-matches
  9685. (org-get-heading) (match-end 0)
  9686. (org-highlight-new-match
  9687. (match-beginning 1) (match-end 1)))
  9688. (org-fold-show-context 'tags-tree))
  9689. ((eq action 'agenda)
  9690. (let* ((effort (org-entry-get (point) org-effort-property))
  9691. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9692. (setq txt (org-agenda-format-item
  9693. ""
  9694. ;; Add `effort' and `effort-minutes'
  9695. ;; properties for prefix format.
  9696. (org-add-props
  9697. (concat
  9698. (if (eq org-tags-match-list-sublevels 'indented)
  9699. (make-string (1- level) ?.) "")
  9700. (org-get-heading))
  9701. nil
  9702. 'effort effort
  9703. 'effort-minutes effort-minutes)
  9704. (make-string level ?\s)
  9705. category
  9706. tags-list)
  9707. priority (org-get-priority txt))
  9708. ;; Now add `effort' and `effort-minutes' to
  9709. ;; full agenda line.
  9710. (setq txt (org-add-props txt nil
  9711. 'effort effort
  9712. 'effort-minutes effort-minutes)))
  9713. (goto-char (org-element-property :begin el))
  9714. (setq marker (org-agenda-new-marker))
  9715. (org-add-props txt props
  9716. 'org-marker marker 'org-hd-marker marker 'org-category category
  9717. 'todo-state todo
  9718. 'ts-date ts-date
  9719. 'priority priority
  9720. 'type (concat "tagsmatch" ts-date-type))
  9721. (push txt rtn))
  9722. ((functionp action)
  9723. (setq org-map-continue-from nil)
  9724. (save-excursion
  9725. (setq rtn1 (funcall action))
  9726. (push rtn1 rtn)))
  9727. (t (user-error "Invalid action")))
  9728. ;; if we are to skip sublevels, jump to end of subtree
  9729. (unless org-tags-match-list-sublevels
  9730. (goto-char (1- (org-element-property :end el))))))
  9731. ;; Get the correct position from where to continue
  9732. (when org-map-continue-from
  9733. (setq org-element-cache-map-continue-from org-map-continue-from)
  9734. (goto-char org-map-continue-from))
  9735. ;; Return nil.
  9736. nil)
  9737. :next-re fast-re
  9738. :fail-re fast-re
  9739. :narrow t))
  9740. (while (let (case-fold-search)
  9741. (re-search-forward re nil t))
  9742. (setq org-map-continue-from nil)
  9743. (catch :skip
  9744. ;; Ignore closing parts of inline tasks.
  9745. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9746. (throw :skip t))
  9747. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9748. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9749. (goto-char (setq lspos (match-beginning 0)))
  9750. (setq level (org-reduced-level (org-outline-level))
  9751. category (org-get-category))
  9752. (when (eq action 'agenda)
  9753. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9754. ts-date (car ts-date-pair)
  9755. ts-date-type (cdr ts-date-pair)))
  9756. (setq i llast llast level)
  9757. ;; remove tag lists from same and sublevels
  9758. (while (>= i level)
  9759. (when (setq entry (assoc i tags-alist))
  9760. (setq tags-alist (delete entry tags-alist)))
  9761. (setq i (1- i)))
  9762. ;; add the next tags
  9763. (when tags
  9764. (setq tags (org-split-string tags ":")
  9765. tags-alist
  9766. (cons (cons level tags) tags-alist)))
  9767. ;; compile tags for current headline
  9768. (setq tags-list
  9769. (if org-use-tag-inheritance
  9770. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  9771. tags)
  9772. org-scanner-tags tags-list)
  9773. (when org-use-tag-inheritance
  9774. (setcdr (car tags-alist)
  9775. (mapcar (lambda (x)
  9776. (setq x (copy-sequence x))
  9777. (org-add-prop-inherited x))
  9778. (cdar tags-alist))))
  9779. (when (and tags org-use-tag-inheritance
  9780. (or (not (eq t org-use-tag-inheritance))
  9781. org-tags-exclude-from-inheritance))
  9782. ;; Selective inheritance, remove uninherited ones.
  9783. (setcdr (car tags-alist)
  9784. (org-remove-uninherited-tags (cdar tags-alist))))
  9785. (when (and
  9786. ;; eval matcher only when the todo condition is OK
  9787. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9788. (if (functionp matcher)
  9789. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9790. (funcall matcher todo tags-list level))
  9791. matcher))
  9792. ;; Call the skipper, but return t if it does not
  9793. ;; skip, so that the `and' form continues evaluating.
  9794. (progn
  9795. (unless (eq action 'sparse-tree) (org-agenda-skip))
  9796. t)
  9797. ;; Check if timestamps are deselecting this entry
  9798. (or (not todo-only)
  9799. (and (member todo org-todo-keywords-1)
  9800. (or (not org-agenda-tags-todo-honor-ignore-options)
  9801. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9802. ;; select this headline
  9803. (cond
  9804. ((eq action 'sparse-tree)
  9805. (and org-highlight-sparse-tree-matches
  9806. (org-get-heading) (match-end 0)
  9807. (org-highlight-new-match
  9808. (match-beginning 1) (match-end 1)))
  9809. (org-fold-show-context 'tags-tree))
  9810. ((eq action 'agenda)
  9811. (setq txt (org-agenda-format-item
  9812. ""
  9813. (concat
  9814. (if (eq org-tags-match-list-sublevels 'indented)
  9815. (make-string (1- level) ?.) "")
  9816. (org-get-heading))
  9817. (make-string level ?\s)
  9818. category
  9819. tags-list)
  9820. priority (org-get-priority txt))
  9821. (goto-char lspos)
  9822. (setq marker (org-agenda-new-marker))
  9823. (org-add-props txt props
  9824. 'org-marker marker 'org-hd-marker marker 'org-category category
  9825. 'todo-state todo
  9826. 'ts-date ts-date
  9827. 'priority priority
  9828. 'type (concat "tagsmatch" ts-date-type))
  9829. (push txt rtn))
  9830. ((functionp action)
  9831. (setq org-map-continue-from nil)
  9832. (save-excursion
  9833. (setq rtn1 (funcall action))
  9834. (push rtn1 rtn)))
  9835. (t (user-error "Invalid action")))
  9836. ;; if we are to skip sublevels, jump to end of subtree
  9837. (unless org-tags-match-list-sublevels
  9838. (org-end-of-subtree t)
  9839. (backward-char 1))))
  9840. ;; Get the correct position from where to continue
  9841. (if org-map-continue-from
  9842. (goto-char org-map-continue-from)
  9843. (and (= (point) lspos) (end-of-line 1))))))
  9844. (when (and (eq action 'sparse-tree)
  9845. (not org-sparse-tree-open-archived-trees))
  9846. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9847. (nreverse rtn)))
  9848. (defun org-remove-uninherited-tags (tags)
  9849. "Remove all tags that are not inherited from the list TAGS."
  9850. (cond
  9851. ((eq org-use-tag-inheritance t)
  9852. (if org-tags-exclude-from-inheritance
  9853. (org-delete-all org-tags-exclude-from-inheritance tags)
  9854. tags))
  9855. ((not org-use-tag-inheritance) nil)
  9856. ((stringp org-use-tag-inheritance)
  9857. (delq nil (mapcar
  9858. (lambda (x)
  9859. (if (and (string-match org-use-tag-inheritance x)
  9860. (not (member x org-tags-exclude-from-inheritance)))
  9861. x nil))
  9862. tags)))
  9863. ((listp org-use-tag-inheritance)
  9864. (delq nil (mapcar
  9865. (lambda (x)
  9866. (if (member x org-use-tag-inheritance) x nil))
  9867. tags)))))
  9868. (defun org-match-sparse-tree (&optional todo-only match)
  9869. "Create a sparse tree according to tags string MATCH.
  9870. MATCH is a string with match syntax. It can contain a selection
  9871. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  9872. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  9873. those. See the manual for details.
  9874. If optional argument TODO-ONLY is non-nil, only select lines that
  9875. are also TODO tasks."
  9876. (interactive "P")
  9877. (org-agenda-prepare-buffers (list (current-buffer)))
  9878. (let ((org--matcher-tags-todo-only todo-only))
  9879. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  9880. org--matcher-tags-todo-only)))
  9881. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  9882. (defvar org-cached-props nil)
  9883. (defun org-cached-entry-get (pom property)
  9884. (if (or (eq t org-use-property-inheritance)
  9885. (and (stringp org-use-property-inheritance)
  9886. (let ((case-fold-search t))
  9887. (string-match-p org-use-property-inheritance property)))
  9888. (and (listp org-use-property-inheritance)
  9889. (member-ignore-case property org-use-property-inheritance)))
  9890. ;; Caching is not possible, check it directly.
  9891. (org-entry-get pom property 'inherit)
  9892. ;; Get all properties, so we can do complicated checks easily.
  9893. (cdr (assoc-string property
  9894. (or org-cached-props
  9895. (setq org-cached-props (org-entry-properties pom)))
  9896. t))))
  9897. (defun org-global-tags-completion-table (&optional files)
  9898. "Return the list of all tags in all agenda buffer/files.
  9899. Optional FILES argument is a list of files which can be used
  9900. instead of the agenda files."
  9901. (save-excursion
  9902. (org-uniquify
  9903. (delq nil
  9904. (apply #'append
  9905. (mapcar
  9906. (lambda (file)
  9907. (set-buffer (find-file-noselect file))
  9908. (org--tag-add-to-alist
  9909. (org-get-buffer-tags)
  9910. (mapcar (lambda (x)
  9911. (and (stringp (car-safe x))
  9912. (list (car-safe x))))
  9913. org-current-tag-alist)))
  9914. (if (car-safe files) files
  9915. (org-agenda-files))))))))
  9916. (defun org-make-tags-matcher (match &optional only-local-tags)
  9917. "Create the TAGS/TODO matcher form for the selection string MATCH.
  9918. Returns a cons of the selection string MATCH and a function
  9919. implementing the matcher.
  9920. The matcher is to be called at an Org entry, with point on the
  9921. headline, and returns non-nil if the entry matches the selection
  9922. string MATCH. It must be called with three arguments: the TODO
  9923. keyword at the entry (or nil if none), the list of all tags at
  9924. the entry including inherited ones and the reduced level of the
  9925. headline. Additionally, the category of the entry, if any, must
  9926. be specified as the text property `org-category' on the headline.
  9927. This function sets the variable `org--matcher-tags-todo-only' to
  9928. a non-nil value if the matcher restricts matching to TODO
  9929. entries, otherwise it is not touched.
  9930. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  9931. table, only get buffer tags.
  9932. See also `org-scan-tags'."
  9933. (unless match
  9934. ;; Get a new match request, with completion against the global
  9935. ;; tags table and the local tags in current buffer.
  9936. (let ((org-last-tags-completion-table
  9937. (org--tag-add-to-alist
  9938. (org-get-buffer-tags)
  9939. (unless only-local-tags
  9940. (org-global-tags-completion-table)))))
  9941. (setq match
  9942. (completing-read
  9943. "Match: "
  9944. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  9945. (let ((match0 match)
  9946. (re (concat
  9947. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  9948. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  9949. "\\([<>=]\\{1,2\\}\\)"
  9950. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  9951. "\\|" org-tag-re "\\)"))
  9952. (start 0)
  9953. tagsmatch todomatch tagsmatcher todomatcher)
  9954. ;; Expand group tags.
  9955. (setq match (org-tags-expand match))
  9956. ;; Check if there is a TODO part of this match, which would be the
  9957. ;; part after a "/". To make sure that this slash is not part of
  9958. ;; a property value to be matched against, we also check that
  9959. ;; there is no / after that slash. First, find the last slash.
  9960. (let ((s 0))
  9961. (while (string-match "/+" match s)
  9962. (setq start (match-beginning 0))
  9963. (setq s (match-end 0))))
  9964. (if (and (string-match "/+" match start)
  9965. (not (string-match-p "\"" match start)))
  9966. ;; Match contains also a TODO-matching request.
  9967. (progn
  9968. (setq tagsmatch (substring match 0 (match-beginning 0)))
  9969. (setq todomatch (substring match (match-end 0)))
  9970. (when (string-prefix-p "!" todomatch)
  9971. (setq org--matcher-tags-todo-only t)
  9972. (setq todomatch (substring todomatch 1)))
  9973. (when (string-match "\\`\\s-*\\'" todomatch)
  9974. (setq todomatch nil)))
  9975. ;; Only matching tags.
  9976. (setq tagsmatch match)
  9977. (setq todomatch nil))
  9978. ;; Make the tags matcher.
  9979. (when (org-string-nw-p tagsmatch)
  9980. (let ((orlist nil)
  9981. (orterms (org-split-string tagsmatch "|"))
  9982. term)
  9983. (while (setq term (pop orterms))
  9984. (while (and (equal (substring term -1) "\\") orterms)
  9985. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  9986. (while (string-match re term)
  9987. (let* ((rest (substring term (match-end 0)))
  9988. (minus (and (match-end 1)
  9989. (equal (match-string 1 term) "-")))
  9990. (tag (save-match-data
  9991. (replace-regexp-in-string
  9992. "\\\\-" "-" (match-string 2 term))))
  9993. (regexp (eq (string-to-char tag) ?{))
  9994. (levelp (match-end 4))
  9995. (propp (match-end 5))
  9996. (mm
  9997. (cond
  9998. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  9999. (levelp
  10000. `(,(org-op-to-function (match-string 3 term))
  10001. level
  10002. ,(string-to-number (match-string 4 term))))
  10003. (propp
  10004. (let* ((gv (pcase (upcase (match-string 5 term))
  10005. ("CATEGORY"
  10006. '(org-get-category (point)))
  10007. ("TODO" 'todo)
  10008. (p `(org-cached-entry-get nil ,p))))
  10009. (pv (match-string 7 term))
  10010. (regexp (eq (string-to-char pv) ?{))
  10011. (strp (eq (string-to-char pv) ?\"))
  10012. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10013. (po (org-op-to-function (match-string 6 term)
  10014. (if timep 'time strp))))
  10015. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10016. (when timep (setq pv (org-matcher-time pv)))
  10017. (cond ((and regexp (eq po '/=))
  10018. `(not (string-match ,pv (or ,gv ""))))
  10019. (regexp `(string-match ,pv (or ,gv "")))
  10020. (strp `(,po (or ,gv "") ,pv))
  10021. (t
  10022. `(,po
  10023. (string-to-number (or ,gv ""))
  10024. ,(string-to-number pv))))))
  10025. (t `(member ,tag tags-list)))))
  10026. (push (if minus `(not ,mm) mm) tagsmatcher)
  10027. (setq term rest)))
  10028. (push `(and ,@tagsmatcher) orlist)
  10029. (setq tagsmatcher nil))
  10030. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10031. ;; Make the TODO matcher.
  10032. (when (org-string-nw-p todomatch)
  10033. (let ((orlist nil))
  10034. (dolist (term (org-split-string todomatch "|"))
  10035. (while (string-match re term)
  10036. (let* ((minus (and (match-end 1)
  10037. (equal (match-string 1 term) "-")))
  10038. (kwd (match-string 2 term))
  10039. (regexp (eq (string-to-char kwd) ?{))
  10040. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10041. `(equal todo ,kwd))))
  10042. (push (if minus `(not ,mm) mm) todomatcher))
  10043. (setq term (substring term (match-end 0))))
  10044. (push (if (> (length todomatcher) 1)
  10045. (cons 'and todomatcher)
  10046. (car todomatcher))
  10047. orlist)
  10048. (setq todomatcher nil))
  10049. (setq todomatcher (cons 'or orlist))))
  10050. ;; Return the string and function of the matcher. If no
  10051. ;; tags-specific or todo-specific matcher exists, match
  10052. ;; everything.
  10053. (let ((matcher (if (and tagsmatcher todomatcher)
  10054. `(and ,tagsmatcher ,todomatcher)
  10055. (or tagsmatcher todomatcher t))))
  10056. (when org--matcher-tags-todo-only
  10057. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10058. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10059. (defun org--tags-expand-group (group tag-groups expanded)
  10060. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10061. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10062. an accumulator used in recursive calls."
  10063. (dolist (tag group)
  10064. (unless (member tag expanded)
  10065. (let ((group (assoc tag tag-groups)))
  10066. (push tag expanded)
  10067. (when group
  10068. (setq expanded
  10069. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10070. expanded)
  10071. (defun org-tags-expand (match &optional single-as-list)
  10072. "Expand group tags in MATCH.
  10073. This replaces every group tag in MATCH with a regexp tag search.
  10074. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10075. will be replaced like this:
  10076. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10077. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10078. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10079. Replacing by a regexp preserves the structure of the match.
  10080. E.g., this expansion
  10081. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10082. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10083. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10084. A group tag in MATCH can contain regular expressions of its own.
  10085. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10086. will be replaced like this:
  10087. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10088. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10089. assumed to be a single group tag, and the function will return
  10090. the list of tags in this group."
  10091. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10092. (let ((tag-groups
  10093. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10094. (cond
  10095. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10096. (org-group-tags
  10097. (let* ((case-fold-search t)
  10098. (tag-syntax org-mode-syntax-table)
  10099. (group-keys (mapcar #'car tag-groups))
  10100. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10101. (return-match match))
  10102. ;; Mark regexp-expressions in the match-expression so that we
  10103. ;; do not replace them later on.
  10104. (let ((s 0))
  10105. (while (string-match "{.+?}" return-match s)
  10106. (setq s (match-end 0))
  10107. (add-text-properties
  10108. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10109. ;; @ and _ are allowed as word-components in tags.
  10110. (modify-syntax-entry ?@ "w" tag-syntax)
  10111. (modify-syntax-entry ?_ "w" tag-syntax)
  10112. ;; For each tag token found in MATCH, compute a regexp and it
  10113. (with-syntax-table tag-syntax
  10114. (replace-regexp-in-string
  10115. key-regexp
  10116. (lambda (m)
  10117. (if (get-text-property (match-beginning 2) 'regexp m)
  10118. m ;regexp tag: ignore
  10119. (let* ((operator (match-string 1 m))
  10120. (tag-token (let ((tag (match-string 2 m)))
  10121. (list tag)))
  10122. regexp-tags regular-tags)
  10123. ;; Partition tags between regexp and regular tags.
  10124. ;; Remove curly bracket syntax from regexp tags.
  10125. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10126. (save-match-data
  10127. (if (string-match "{\\(.+?\\)}" tag)
  10128. (push (match-string 1 tag) regexp-tags)
  10129. (push tag regular-tags))))
  10130. ;; Replace tag token by the appropriate regexp.
  10131. ;; Regular tags need to be regexp-quoted, whereas
  10132. ;; regexp-tags are inserted as-is.
  10133. (let ((regular (regexp-opt regular-tags))
  10134. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10135. (concat operator
  10136. (cond
  10137. ((null regular-tags) (format "{%s}" regexp))
  10138. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10139. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10140. return-match
  10141. t t))))
  10142. (t match))))
  10143. (defun org-op-to-function (op &optional stringp)
  10144. "Turn an operator into the appropriate function."
  10145. (setq op
  10146. (cond
  10147. ((equal op "<" ) '(< org-string< org-time<))
  10148. ((equal op ">" ) '(> org-string> org-time>))
  10149. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10150. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10151. ((member op '("=" "==")) '(= string= org-time=))
  10152. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10153. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10154. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10155. (defvar org-tags-overlay (make-overlay 1 1))
  10156. (delete-overlay org-tags-overlay)
  10157. (defun org-add-prop-inherited (s)
  10158. (add-text-properties 0 (length s) '(inherited t) s)
  10159. s)
  10160. (defun org-toggle-tag (tag &optional onoff)
  10161. "Toggle the tag TAG for the current line.
  10162. If ONOFF is `on' or `off', don't toggle but set to this state."
  10163. (save-excursion
  10164. (org-back-to-heading t)
  10165. (let ((current
  10166. ;; Reverse the tags list so any new tag is appended to the
  10167. ;; current list of tags.
  10168. (nreverse (org-get-tags nil t)))
  10169. res)
  10170. (pcase onoff
  10171. (`off (setq current (delete tag current)))
  10172. ((or `on (guard (not (member tag current))))
  10173. (setq res t)
  10174. (cl-pushnew tag current :test #'equal))
  10175. (_ (setq current (delete tag current))))
  10176. (org-set-tags (nreverse current))
  10177. res)))
  10178. (defun org--align-tags-here (to-col)
  10179. "Align tags on the current headline to TO-COL.
  10180. Assume point is on a headline. Preserve point when aligning
  10181. tags."
  10182. (when (org-match-line org-tag-line-re)
  10183. (let* ((tags-start (match-beginning 1))
  10184. (blank-start (save-excursion
  10185. (goto-char tags-start)
  10186. (skip-chars-backward " \t")
  10187. (point)))
  10188. (new (max (if (>= to-col 0) to-col
  10189. (- (abs to-col) (string-width (match-string 1))))
  10190. ;; Introduce at least one space after the heading
  10191. ;; or the stars.
  10192. (save-excursion
  10193. (goto-char blank-start)
  10194. (1+ (current-column)))))
  10195. (current
  10196. (save-excursion (goto-char tags-start) (current-column)))
  10197. (origin (point-marker))
  10198. (column (current-column))
  10199. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10200. (when (/= new current)
  10201. (delete-region blank-start tags-start)
  10202. (goto-char blank-start)
  10203. (let ((indent-tabs-mode nil)) (indent-to new))
  10204. ;; Try to move back to original position. If point was in the
  10205. ;; blanks before the tags, ORIGIN marker is of no use because
  10206. ;; it now points to BLANK-START. Use COLUMN instead.
  10207. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10208. (defun org-set-tags-command (&optional arg)
  10209. "Set the tags for the current visible entry.
  10210. When called with `\\[universal-argument]' prefix argument ARG, \
  10211. realign all tags
  10212. in the current buffer.
  10213. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10214. unconditionally do not
  10215. offer the fast tag selection interface.
  10216. If a region is active, set tags in the region according to the
  10217. setting of `org-loop-over-headlines-in-active-region'.
  10218. This function is for interactive use only;
  10219. in Lisp code use `org-set-tags' instead."
  10220. (interactive "P")
  10221. (let ((org-use-fast-tag-selection
  10222. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10223. (cond
  10224. ((equal '(4) arg) (org-align-tags t))
  10225. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10226. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10227. (org-map-entries
  10228. #'org-set-tags-command
  10229. nil
  10230. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10231. 'region-start-level
  10232. 'region)
  10233. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10234. (t
  10235. (save-excursion
  10236. (org-back-to-heading)
  10237. (let* ((all-tags (org-get-tags))
  10238. (table (setq org-last-tags-completion-table
  10239. (org--tag-add-to-alist
  10240. (and org-complete-tags-always-offer-all-agenda-tags
  10241. (org-global-tags-completion-table
  10242. (org-agenda-files)))
  10243. (or org-current-tag-alist (org-get-buffer-tags)))))
  10244. (current-tags
  10245. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10246. all-tags))
  10247. (inherited-tags
  10248. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10249. all-tags))
  10250. (tags
  10251. (replace-regexp-in-string
  10252. ;; Ignore all forbidden characters in tags.
  10253. "[^[:alnum:]_@#%]+" ":"
  10254. (if (or (eq t org-use-fast-tag-selection)
  10255. (and org-use-fast-tag-selection
  10256. (delq nil (mapcar #'cdr table))))
  10257. (org-fast-tag-selection
  10258. current-tags
  10259. inherited-tags
  10260. table
  10261. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10262. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10263. (crm-separator "[ \t]*:[ \t]*"))
  10264. (mapconcat #'identity
  10265. (completing-read-multiple
  10266. "Tags: "
  10267. org-last-tags-completion-table
  10268. nil nil (org-make-tag-string current-tags)
  10269. 'org-tags-history)
  10270. ":"))))))
  10271. (org-set-tags tags)))))
  10272. ;; `save-excursion' may not replace the point at the right
  10273. ;; position.
  10274. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10275. (looking-at-p " "))
  10276. (forward-char))))
  10277. (defun org-align-tags (&optional all)
  10278. "Align tags in current entry.
  10279. When optional argument ALL is non-nil, align all tags in the
  10280. visible part of the buffer."
  10281. (let ((get-indent-column
  10282. (lambda ()
  10283. (let ((offset (if (bound-and-true-p org-indent-mode)
  10284. (* (1- org-indent-indentation-per-level)
  10285. (1- (org-current-level)))
  10286. 0)))
  10287. (+ org-tags-column
  10288. (if (> org-tags-column 0) (- offset) offset))))))
  10289. (if (and (not all) (org-at-heading-p))
  10290. (org--align-tags-here (funcall get-indent-column))
  10291. (save-excursion
  10292. (if all
  10293. (progn
  10294. (goto-char (point-min))
  10295. (while (re-search-forward org-tag-line-re nil t)
  10296. (org--align-tags-here (funcall get-indent-column))))
  10297. (org-back-to-heading t)
  10298. (org--align-tags-here (funcall get-indent-column)))))))
  10299. (defun org-set-tags (tags)
  10300. "Set the tags of the current entry to TAGS, replacing current tags.
  10301. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10302. If TAGS is nil or the empty string, all tags are removed.
  10303. This function assumes point is on a headline."
  10304. (org-with-wide-buffer
  10305. (org-fold-core-ignore-modifications
  10306. (let ((tags (pcase tags
  10307. ((pred listp) tags)
  10308. ((pred stringp) (split-string (org-trim tags) ":" t))
  10309. (_ (error "Invalid tag specification: %S" tags))))
  10310. (old-tags (org-get-tags nil t))
  10311. (tags-change? nil))
  10312. (when (functionp org-tags-sort-function)
  10313. (setq tags (sort tags org-tags-sort-function)))
  10314. (setq tags-change? (not (equal tags old-tags)))
  10315. (when tags-change?
  10316. ;; Delete previous tags and any trailing white space.
  10317. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10318. (line-end-position)))
  10319. (skip-chars-backward " \t")
  10320. (delete-region (point) (line-end-position))
  10321. ;; Deleting white spaces may break an otherwise empty headline.
  10322. ;; Re-introduce one space in this case.
  10323. (unless (org-at-heading-p) (insert " "))
  10324. (when tags
  10325. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10326. ;; When text is being inserted on an invisible region
  10327. ;; boundary, it can be inadvertently sucked into
  10328. ;; invisibility.
  10329. (unless (org-invisible-p (line-beginning-position))
  10330. (org-fold-region (point) (line-end-position) nil 'outline))))
  10331. ;; Align tags, if any.
  10332. (when tags (org-align-tags))
  10333. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10334. (defun org-change-tag-in-region (beg end tag off)
  10335. "Add or remove TAG for each entry in the region.
  10336. This works in the agenda, and also in an Org buffer."
  10337. (interactive
  10338. (list (region-beginning) (region-end)
  10339. (let ((org-last-tags-completion-table
  10340. (if (derived-mode-p 'org-mode)
  10341. (org--tag-add-to-alist
  10342. (org-get-buffer-tags)
  10343. (org-global-tags-completion-table))
  10344. (org-global-tags-completion-table))))
  10345. (completing-read
  10346. "Tag: " org-last-tags-completion-table nil nil nil
  10347. 'org-tags-history))
  10348. (progn
  10349. (message "[s]et or [r]emove? ")
  10350. (equal (read-char-exclusive) ?r))))
  10351. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10352. (let ((agendap (equal major-mode 'org-agenda-mode))
  10353. l1 l2 m buf pos newhead (cnt 0))
  10354. (goto-char end)
  10355. (setq l2 (1- (org-current-line)))
  10356. (goto-char beg)
  10357. (setq l1 (org-current-line))
  10358. (cl-loop for l from l1 to l2 do
  10359. (org-goto-line l)
  10360. (setq m (get-text-property (point) 'org-hd-marker))
  10361. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10362. (and agendap m))
  10363. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10364. pos (if agendap m (point)))
  10365. (with-current-buffer buf
  10366. (save-excursion
  10367. (save-restriction
  10368. (goto-char pos)
  10369. (setq cnt (1+ cnt))
  10370. (org-toggle-tag tag (if off 'off 'on))
  10371. (setq newhead (org-get-heading)))))
  10372. (and agendap (org-agenda-change-all-lines newhead m))))
  10373. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10374. (defun org-tags-completion-function (string _predicate &optional flag)
  10375. "Complete tag STRING.
  10376. FLAG specifies the type of completion operation to perform. This
  10377. function is passed as a collection function to `completing-read',
  10378. which see."
  10379. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10380. (confirm (lambda (x) (stringp (car x))))
  10381. (prefix ""))
  10382. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10383. (setq prefix (match-string 1 string))
  10384. (setq string (match-string 2 string)))
  10385. (pcase flag
  10386. (`t (all-completions string org-last-tags-completion-table confirm))
  10387. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10388. (`nil
  10389. (pcase (try-completion string org-last-tags-completion-table confirm)
  10390. ((and completion (pred stringp))
  10391. (concat prefix
  10392. completion
  10393. (if (and org-add-colon-after-tag-completion
  10394. (assoc completion org-last-tags-completion-table))
  10395. ":"
  10396. "")))
  10397. (completion completion)))
  10398. (_ nil))))
  10399. (defun org-fast-tag-insert (kwd tags face &optional end)
  10400. "Insert KWD, and the TAGS, the latter with face FACE.
  10401. Also insert END."
  10402. (insert (format "%-12s" (concat kwd ":"))
  10403. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10404. (or end "")))
  10405. (defun org-fast-tag-show-exit (flag)
  10406. (save-excursion
  10407. (org-goto-line 3)
  10408. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10409. (replace-match ""))
  10410. (when flag
  10411. (end-of-line 1)
  10412. (org-move-to-column (- (window-width) 19) t)
  10413. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10414. (defun org-set-current-tags-overlay (current prefix)
  10415. "Add an overlay to CURRENT tag with PREFIX."
  10416. (let ((s (org-make-tag-string current)))
  10417. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10418. (org-overlay-display org-tags-overlay (concat prefix s))))
  10419. (defvar org-last-tag-selection-key nil)
  10420. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10421. "Fast tag selection with single keys.
  10422. CURRENT is the current list of tags in the headline, INHERITED is the
  10423. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10424. possibly with grouping information. TODO-TABLE is a similar table with
  10425. TODO keywords, should these have keys assigned to them.
  10426. If the keys are nil, a-z are automatically assigned.
  10427. Returns the new tags string, or nil to not change the current settings."
  10428. (let* ((fulltable (append table todo-table))
  10429. (maxlen (if (null fulltable) 0
  10430. (apply #'max
  10431. (mapcar (lambda (x)
  10432. (if (stringp (car x)) (string-width (car x))
  10433. 0))
  10434. fulltable))))
  10435. (buf (current-buffer))
  10436. (expert (eq org-fast-tag-selection-single-key 'expert))
  10437. (tab-tags nil)
  10438. (fwidth (+ maxlen 3 1 3))
  10439. (ncol (/ (- (window-width) 4) fwidth))
  10440. (i-face 'org-done)
  10441. (c-face 'org-todo)
  10442. tg cnt e c char c1 c2 ntable tbl rtn
  10443. ov-start ov-end ov-prefix
  10444. (exit-after-next org-fast-tag-selection-single-key)
  10445. (done-keywords org-done-keywords)
  10446. groups ingroup intaggroup)
  10447. (save-excursion
  10448. (beginning-of-line)
  10449. (if (looking-at org-tag-line-re)
  10450. (setq ov-start (match-beginning 1)
  10451. ov-end (match-end 1)
  10452. ov-prefix "")
  10453. (setq ov-start (1- (point-at-eol))
  10454. ov-end (1+ ov-start))
  10455. (skip-chars-forward "^\n\r")
  10456. (setq ov-prefix
  10457. (concat
  10458. (buffer-substring (1- (point)) (point))
  10459. (if (> (current-column) org-tags-column)
  10460. " "
  10461. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10462. (move-overlay org-tags-overlay ov-start ov-end)
  10463. (save-excursion
  10464. (save-window-excursion
  10465. (if expert
  10466. (set-buffer (get-buffer-create " *Org tags*"))
  10467. (delete-other-windows)
  10468. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10469. (org-switch-to-buffer-other-window " *Org tags*"))
  10470. (erase-buffer)
  10471. (setq-local org-done-keywords done-keywords)
  10472. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10473. (org-fast-tag-insert "Current" current c-face "\n\n")
  10474. (org-fast-tag-show-exit exit-after-next)
  10475. (org-set-current-tags-overlay current ov-prefix)
  10476. (setq tbl fulltable char ?a cnt 0)
  10477. (while (setq e (pop tbl))
  10478. (cond
  10479. ((eq (car e) :startgroup)
  10480. (push '() groups) (setq ingroup t)
  10481. (unless (zerop cnt)
  10482. (setq cnt 0)
  10483. (insert "\n"))
  10484. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10485. ((eq (car e) :endgroup)
  10486. (setq ingroup nil cnt 0)
  10487. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10488. ((eq (car e) :startgrouptag)
  10489. (setq intaggroup t)
  10490. (unless (zerop cnt)
  10491. (setq cnt 0)
  10492. (insert "\n"))
  10493. (insert "[ "))
  10494. ((eq (car e) :endgrouptag)
  10495. (setq intaggroup nil cnt 0)
  10496. (insert "]\n"))
  10497. ((equal e '(:newline))
  10498. (unless (zerop cnt)
  10499. (setq cnt 0)
  10500. (insert "\n")
  10501. (setq e (car tbl))
  10502. (while (equal (car tbl) '(:newline))
  10503. (insert "\n")
  10504. (setq tbl (cdr tbl)))))
  10505. ((equal e '(:grouptags)) (insert " : "))
  10506. (t
  10507. (setq tg (copy-sequence (car e)) c2 nil)
  10508. (if (cdr e)
  10509. (setq c (cdr e))
  10510. ;; automatically assign a character.
  10511. (setq c1 (string-to-char
  10512. (downcase (substring
  10513. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10514. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10515. (while (or (rassoc char ntable) (rassoc char table))
  10516. (setq char (1+ char)))
  10517. (setq c2 c1))
  10518. (setq c (or c2 char)))
  10519. (when ingroup (push tg (car groups)))
  10520. (setq tg (org-add-props tg nil 'face
  10521. (cond
  10522. ((not (assoc tg table))
  10523. (org-get-todo-face tg))
  10524. ((member tg current) c-face)
  10525. ((member tg inherited) i-face))))
  10526. (when (equal (caar tbl) :grouptags)
  10527. (org-add-props tg nil 'face 'org-tag-group))
  10528. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10529. (insert "[" c "] " tg (make-string
  10530. (- fwidth 4 (length tg)) ?\ ))
  10531. (push (cons tg c) ntable)
  10532. (when (= (cl-incf cnt) ncol)
  10533. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10534. (insert "\n")
  10535. (when (or ingroup intaggroup) (insert " ")))
  10536. (setq cnt 0)))))
  10537. (setq ntable (nreverse ntable))
  10538. (insert "\n")
  10539. (goto-char (point-min))
  10540. (unless expert (org-fit-window-to-buffer))
  10541. (setq rtn
  10542. (catch 'exit
  10543. (while t
  10544. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10545. (if (not groups) "no " "")
  10546. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10547. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10548. (setq org-last-tag-selection-key c)
  10549. (cond
  10550. ((= c ?\r) (throw 'exit t))
  10551. ((= c ?!)
  10552. (setq groups (not groups))
  10553. (goto-char (point-min))
  10554. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10555. ((= c ?\C-c)
  10556. (if (not expert)
  10557. (org-fast-tag-show-exit
  10558. (setq exit-after-next (not exit-after-next)))
  10559. (setq expert nil)
  10560. (delete-other-windows)
  10561. (set-window-buffer (split-window-vertically) " *Org tags*")
  10562. (org-switch-to-buffer-other-window " *Org tags*")
  10563. (org-fit-window-to-buffer)))
  10564. ((or (= c ?\C-g)
  10565. (and (= c ?q) (not (rassoc c ntable))))
  10566. (delete-overlay org-tags-overlay)
  10567. (setq quit-flag t))
  10568. ((= c ?\ )
  10569. (setq current nil)
  10570. (when exit-after-next (setq exit-after-next 'now)))
  10571. ((= c ?\t)
  10572. (condition-case nil
  10573. (unless tab-tags
  10574. (setq tab-tags
  10575. (delq nil
  10576. (mapcar (lambda (x)
  10577. (let ((item (car-safe x)))
  10578. (and (stringp item)
  10579. (list item))))
  10580. (org--tag-add-to-alist
  10581. (with-current-buffer buf
  10582. (org-get-buffer-tags))
  10583. table))))))
  10584. (setq tg (completing-read "Tag: " tab-tags))
  10585. (when (string-match "\\S-" tg)
  10586. (cl-pushnew (list tg) tab-tags :test #'equal)
  10587. (if (member tg current)
  10588. (setq current (delete tg current))
  10589. (push tg current)))
  10590. (when exit-after-next (setq exit-after-next 'now)))
  10591. ((setq e (rassoc c todo-table) tg (car e))
  10592. (with-current-buffer buf
  10593. (save-excursion (org-todo tg)))
  10594. (when exit-after-next (setq exit-after-next 'now)))
  10595. ((setq e (rassoc c ntable) tg (car e))
  10596. (if (member tg current)
  10597. (setq current (delete tg current))
  10598. (cl-loop for g in groups do
  10599. (when (member tg g)
  10600. (dolist (x g) (setq current (delete x current)))))
  10601. (push tg current))
  10602. (when exit-after-next (setq exit-after-next 'now))))
  10603. ;; Create a sorted list
  10604. (setq current
  10605. (sort current
  10606. (lambda (a b)
  10607. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10608. (when (eq exit-after-next 'now) (throw 'exit t))
  10609. (goto-char (point-min))
  10610. (beginning-of-line 2)
  10611. (delete-region (point) (point-at-eol))
  10612. (org-fast-tag-insert "Current" current c-face)
  10613. (org-set-current-tags-overlay current ov-prefix)
  10614. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10615. (while (re-search-forward tag-re nil t)
  10616. (let ((tag (match-string 1)))
  10617. (add-text-properties
  10618. (match-beginning 1) (match-end 1)
  10619. (list 'face
  10620. (cond
  10621. ((member tag current) c-face)
  10622. ((member tag inherited) i-face)
  10623. (t 'default)))))))
  10624. (goto-char (point-min)))))
  10625. (delete-overlay org-tags-overlay)
  10626. (if rtn
  10627. (mapconcat 'identity current ":")
  10628. nil)))))
  10629. (defun org-make-tag-string (tags)
  10630. "Return string associated to TAGS.
  10631. TAGS is a list of strings."
  10632. (if (null tags) ""
  10633. (format ":%s:" (mapconcat #'identity tags ":"))))
  10634. (defun org--get-local-tags ()
  10635. "Return list of tags for the current headline.
  10636. Assume point is at the beginning of the headline."
  10637. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10638. (cached-tags (org-element-property :tags cached)))
  10639. (if cached
  10640. ;; If we do not explicitly copy the result, reference would
  10641. ;; be returned and cache element might be modified directly.
  10642. (mapcar #'copy-sequence cached-tags)
  10643. ;; Parse tags manually.
  10644. (and (looking-at org-tag-line-re)
  10645. (split-string (match-string-no-properties 2) ":" t)))))
  10646. (defun org-get-tags (&optional pos-or-element local)
  10647. "Get the list of tags specified in the current headline.
  10648. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10649. POS.
  10650. According to `org-use-tag-inheritance', tags may be inherited
  10651. from parent headlines, and from the whole document, through
  10652. `org-file-tags'. In this case, the returned list of tags
  10653. contains tags in this order: file tags, tags inherited from
  10654. parent headlines, local tags. If a tag appears multiple times,
  10655. only the most local tag is returned.
  10656. However, when optional argument LOCAL is non-nil, only return
  10657. tags specified at the headline.
  10658. Inherited tags have the `inherited' text property."
  10659. (save-match-data
  10660. (if (and org-trust-scanner-tags
  10661. (or (not pos-or-element) (eq pos-or-element (point)))
  10662. (not local))
  10663. org-scanner-tags
  10664. (org-with-point-at (unless (org-element-type pos-or-element)
  10665. (or pos-or-element (point)))
  10666. (unless (or (org-element-type pos-or-element)
  10667. (org-before-first-heading-p))
  10668. (org-back-to-heading t))
  10669. (let ((ltags (if (org-element-type pos-or-element)
  10670. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10671. (org--get-local-tags)))
  10672. itags)
  10673. (if (or local (not org-use-tag-inheritance)) ltags
  10674. (let ((cached (and (org-element--cache-active-p)
  10675. (if (org-element-type pos-or-element)
  10676. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10677. (org-element-at-point nil 'cached)))))
  10678. (if cached
  10679. (while (setq cached (org-element-property :parent cached))
  10680. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10681. ;; If we do explicitly copy the result, reference would
  10682. ;; be returned and cache element might be modified directly.
  10683. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10684. itags)))
  10685. (while (org-up-heading-safe)
  10686. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10687. (org--get-local-tags))
  10688. itags)))))
  10689. (setq itags (append org-file-tags itags))
  10690. (nreverse
  10691. (delete-dups
  10692. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10693. (defun org-get-buffer-tags ()
  10694. "Get a table of all tags used in the buffer, for completion."
  10695. (if (org-element--cache-active-p)
  10696. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10697. ;; search.
  10698. (let ((tags (org-element-cache-map
  10699. (lambda (el) (org-element-property :tags el)))))
  10700. (mapcar #'list (mapcar #'substring-no-properties
  10701. (delete-dups
  10702. (append org-file-tags
  10703. (apply #'append tags))))))
  10704. (org-with-point-at 1
  10705. (let (tags)
  10706. (while (re-search-forward org-tag-line-re nil t)
  10707. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10708. tags)))
  10709. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10710. ;;;; The mapping API
  10711. (defvar org-agenda-skip-comment-trees)
  10712. (defvar org-agenda-skip-function)
  10713. (defun org-map-entries (func &optional match scope &rest skip)
  10714. "Call FUNC at each headline selected by MATCH in SCOPE.
  10715. FUNC is a function or a Lisp form. The function will be called without
  10716. arguments, with the cursor positioned at the beginning of the headline.
  10717. The return values of all calls to the function will be collected and
  10718. returned as a list.
  10719. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10720. does not need to preserve point. After evaluation, the cursor will be
  10721. moved to the end of the line (presumably of the headline of the
  10722. processed entry) and search continues from there. Under some
  10723. circumstances, this may not produce the wanted results. For example,
  10724. if you have removed (e.g. archived) the current (sub)tree it could
  10725. mean that the next entry will be skipped entirely. In such cases, you
  10726. can specify the position from where search should continue by making
  10727. FUNC set the variable `org-map-continue-from' to the desired buffer
  10728. position.
  10729. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10730. Only headlines that are matched by this query will be considered during
  10731. the iteration. When MATCH is nil or t, all headlines will be
  10732. visited by the iteration.
  10733. SCOPE determines the scope of this command. It can be any of:
  10734. nil The current buffer, respecting the restriction if any
  10735. tree The subtree started with the entry at point
  10736. region The entries within the active region, if any
  10737. region-start-level
  10738. The entries within the active region, but only those at
  10739. the same level than the first one.
  10740. file The current buffer, without restriction
  10741. file-with-archives
  10742. The current buffer, and any archives associated with it
  10743. agenda All agenda files
  10744. agenda-with-archives
  10745. All agenda files with any archive files associated with them
  10746. \(file1 file2 ...)
  10747. If this is a list, all files in the list will be scanned
  10748. The remaining args are treated as settings for the skipping facilities of
  10749. the scanner. The following items can be given here:
  10750. archive skip trees with the archive tag
  10751. comment skip trees with the COMMENT keyword
  10752. function or Emacs Lisp form:
  10753. will be used as value for `org-agenda-skip-function', so
  10754. whenever the function returns a position, FUNC will not be
  10755. called for that entry and search will continue from the
  10756. position returned
  10757. If your function needs to retrieve the tags including inherited tags
  10758. at the *current* entry, you can use the value of the variable
  10759. `org-scanner-tags' which will be much faster than getting the value
  10760. with `org-get-tags'. If your function gets properties with
  10761. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  10762. to t around the call to `org-entry-properties' to get the same speedup.
  10763. Note that if your function moves around to retrieve tags and properties at
  10764. a *different* entry, you cannot use these techniques."
  10765. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  10766. (not (org-region-active-p)))
  10767. (let* ((org-agenda-archives-mode nil) ; just to make sure
  10768. (org-agenda-skip-archived-trees (memq 'archive skip))
  10769. (org-agenda-skip-comment-trees (memq 'comment skip))
  10770. (org-agenda-skip-function
  10771. (car (org-delete-all '(comment archive) skip)))
  10772. (org-tags-match-list-sublevels t)
  10773. (start-level (eq scope 'region-start-level))
  10774. matcher res
  10775. org-todo-keywords-for-agenda
  10776. org-done-keywords-for-agenda
  10777. org-todo-keyword-alist-for-agenda
  10778. org-tag-alist-for-agenda
  10779. org--matcher-tags-todo-only)
  10780. (cond
  10781. ((eq match t) (setq matcher t))
  10782. ((eq match nil) (setq matcher t))
  10783. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  10784. (save-excursion
  10785. (save-restriction
  10786. (cond ((eq scope 'tree)
  10787. (org-back-to-heading t)
  10788. (org-narrow-to-subtree)
  10789. (setq scope nil))
  10790. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  10791. (org-region-active-p))
  10792. ;; If needed, set start-level to a string like "2"
  10793. (when start-level
  10794. (save-excursion
  10795. (goto-char (region-beginning))
  10796. (unless (org-at-heading-p) (outline-next-heading))
  10797. (setq start-level (org-current-level))))
  10798. (narrow-to-region (region-beginning)
  10799. (save-excursion
  10800. (goto-char (region-end))
  10801. (unless (and (bolp) (org-at-heading-p))
  10802. (outline-next-heading))
  10803. (point)))
  10804. (setq scope nil)))
  10805. (if (not scope)
  10806. (progn
  10807. (org-agenda-prepare-buffers
  10808. (and buffer-file-name (list buffer-file-name)))
  10809. (setq res
  10810. (org-scan-tags
  10811. func matcher org--matcher-tags-todo-only start-level)))
  10812. ;; Get the right scope
  10813. (cond
  10814. ((and scope (listp scope) (symbolp (car scope)))
  10815. (setq scope (eval scope t)))
  10816. ((eq scope 'agenda)
  10817. (setq scope (org-agenda-files t)))
  10818. ((eq scope 'agenda-with-archives)
  10819. (setq scope (org-agenda-files t))
  10820. (setq scope (org-add-archive-files scope)))
  10821. ((eq scope 'file)
  10822. (setq scope (and buffer-file-name (list buffer-file-name))))
  10823. ((eq scope 'file-with-archives)
  10824. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  10825. (org-agenda-prepare-buffers scope)
  10826. (dolist (file scope)
  10827. (with-current-buffer (org-find-base-buffer-visiting file)
  10828. (org-with-wide-buffer
  10829. (goto-char (point-min))
  10830. (setq res
  10831. (append
  10832. res
  10833. (org-scan-tags
  10834. func matcher org--matcher-tags-todo-only)))))))))
  10835. res)))
  10836. ;;; Properties API
  10837. (defconst org-special-properties
  10838. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  10839. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  10840. "The special properties valid in Org mode.
  10841. These are properties that are not defined in the property drawer,
  10842. but in some other way.")
  10843. (defconst org-default-properties
  10844. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  10845. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  10846. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  10847. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  10848. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  10849. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  10850. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  10851. "Some properties that are used by Org mode for various purposes.
  10852. Being in this list makes sure that they are offered for completion.")
  10853. (defun org--valid-property-p (property)
  10854. "Non-nil when string PROPERTY is a valid property name."
  10855. (not
  10856. (or (equal property "")
  10857. (string-match-p "\\s-" property))))
  10858. (defun org--update-property-plist (key val props)
  10859. "Associate KEY to VAL in alist PROPS.
  10860. Modifications are made by side-effect. Return new alist."
  10861. (let* ((appending (string= (substring key -1) "+"))
  10862. (key (if appending (substring key 0 -1) key))
  10863. (old (assoc-string key props t)))
  10864. (if (not old) (cons (cons key val) props)
  10865. (setcdr old (if appending (concat (cdr old) " " val) val))
  10866. props)))
  10867. (defun org-get-property-block (&optional beg force)
  10868. "Return the (beg . end) range of the body of the property drawer.
  10869. BEG is the beginning of the current subtree or the beginning of
  10870. the document if before the first headline. If it is not given,
  10871. it will be found. If the drawer does not exist, create it if
  10872. FORCE is non-nil, or return nil."
  10873. (org-with-wide-buffer
  10874. (let ((beg (cond (beg (goto-char beg))
  10875. ((or (not (featurep 'org-inlinetask))
  10876. (org-inlinetask-in-task-p))
  10877. (org-back-to-heading-or-point-min t) (point))
  10878. (t (org-with-limited-levels
  10879. (org-back-to-heading-or-point-min t))
  10880. (point)))))
  10881. ;; Move point to its position according to its positional rules.
  10882. (cond ((org-before-first-heading-p)
  10883. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  10884. (t (forward-line)
  10885. (when (looking-at-p org-planning-line-re) (forward-line))))
  10886. (cond ((looking-at org-property-drawer-re)
  10887. (forward-line)
  10888. (cons (point) (progn (goto-char (match-end 0))
  10889. (line-beginning-position))))
  10890. (force
  10891. (goto-char beg)
  10892. (org-insert-property-drawer)
  10893. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  10894. (line-beginning-position))))
  10895. (cons pos pos)))))))
  10896. (defun org-at-property-drawer-p ()
  10897. "Non-nil when point is at the first line of a property drawer."
  10898. (org-with-wide-buffer
  10899. (beginning-of-line)
  10900. (and (looking-at org-property-drawer-re)
  10901. (or (bobp)
  10902. (progn
  10903. (forward-line -1)
  10904. (cond ((org-at-heading-p))
  10905. ((looking-at org-planning-line-re)
  10906. (forward-line -1)
  10907. (org-at-heading-p))
  10908. ((looking-at org-comment-regexp)
  10909. (forward-line -1)
  10910. (while (and (not (bobp)) (looking-at org-comment-regexp))
  10911. (forward-line -1))
  10912. (looking-at org-comment-regexp))
  10913. (t nil)))))))
  10914. (defun org-at-property-p ()
  10915. "Non-nil when point is inside a property drawer.
  10916. See `org-property-re' for match data, if applicable."
  10917. (save-excursion
  10918. (beginning-of-line)
  10919. (and (looking-at org-property-re)
  10920. (let ((property-drawer (save-match-data (org-get-property-block))))
  10921. (and property-drawer
  10922. (>= (point) (car property-drawer))
  10923. (< (point) (cdr property-drawer)))))))
  10924. (defun org-property-action ()
  10925. "Do an action on properties."
  10926. (interactive)
  10927. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  10928. (let ((c (read-char-exclusive)))
  10929. (cl-case c
  10930. (?s (call-interactively #'org-set-property))
  10931. (?d (call-interactively #'org-delete-property))
  10932. (?D (call-interactively #'org-delete-property-globally))
  10933. (?c (call-interactively #'org-compute-property-at-point))
  10934. (otherwise (user-error "No such property action %c" c)))))
  10935. (defun org-inc-effort ()
  10936. "Increment the value of the effort property in the current entry."
  10937. (interactive)
  10938. (org-set-effort t))
  10939. (defvar org-clock-effort) ; Defined in org-clock.el.
  10940. (defvar org-clock-current-task) ; Defined in org-clock.el.
  10941. (defun org-set-effort (&optional increment value)
  10942. "Set the effort property of the current entry.
  10943. If INCREMENT is non-nil, set the property to the next allowed
  10944. value. Otherwise, if optional argument VALUE is provided, use
  10945. it. Eventually, prompt for the new value if none of the previous
  10946. variables is set."
  10947. (interactive "P")
  10948. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  10949. (current (org-entry-get nil org-effort-property))
  10950. (value
  10951. (cond
  10952. (increment
  10953. (unless allowed (user-error "Allowed effort values are not set"))
  10954. (or (cl-caadr (member (list current) allowed))
  10955. (user-error "Unknown value %S among allowed values" current)))
  10956. (value
  10957. (if (stringp value) value
  10958. (error "Invalid effort value: %S" value)))
  10959. (t
  10960. (let ((must-match
  10961. (and allowed
  10962. (not (get-text-property 0 'org-unrestricted
  10963. (caar allowed))))))
  10964. (completing-read "Effort: " allowed nil must-match))))))
  10965. ;; Test whether the value can be interpreted as a duration before
  10966. ;; inserting it in the buffer:
  10967. (org-duration-to-minutes value)
  10968. ;; Maybe update the effort value:
  10969. (unless (equal current value)
  10970. (org-entry-put nil org-effort-property value))
  10971. (unless (org-element--cache-active-p)
  10972. (org-refresh-property '((effort . identity)
  10973. (effort-minutes . org-duration-to-minutes))
  10974. value))
  10975. (when (equal (org-get-heading t t t t)
  10976. (bound-and-true-p org-clock-current-task))
  10977. (setq org-clock-effort value)
  10978. (org-clock-update-mode-line))
  10979. (message "%s is now %s" org-effort-property value)))
  10980. (defun org-entry-properties (&optional pom which)
  10981. "Get all properties of the current entry.
  10982. When POM is a buffer position, get all properties from the entry
  10983. there instead.
  10984. This includes the TODO keyword, the tags, time strings for
  10985. deadline, scheduled, and clocking, and any additional properties
  10986. defined in the entry.
  10987. If WHICH is nil or `all', get all properties. If WHICH is
  10988. `special' or `standard', only get that subclass. If WHICH is
  10989. a string, only get that property.
  10990. Return value is an alist. Keys are properties, as upcased
  10991. strings."
  10992. (org-with-point-at pom
  10993. (when (and (derived-mode-p 'org-mode)
  10994. (org-back-to-heading-or-point-min t))
  10995. (catch 'exit
  10996. (let* ((beg (point))
  10997. (specific (and (stringp which) (upcase which)))
  10998. (which (cond ((not specific) which)
  10999. ((member specific org-special-properties) 'special)
  11000. (t 'standard)))
  11001. props)
  11002. ;; Get the special properties, like TODO and TAGS.
  11003. (when (memq which '(nil all special))
  11004. (when (or (not specific) (string= specific "CLOCKSUM"))
  11005. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11006. (when clocksum
  11007. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11008. props)))
  11009. (when specific (throw 'exit props)))
  11010. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11011. (let ((clocksumt (get-text-property (point)
  11012. :org-clock-minutes-today)))
  11013. (when clocksumt
  11014. (push (cons "CLOCKSUM_T"
  11015. (org-duration-from-minutes clocksumt))
  11016. props)))
  11017. (when specific (throw 'exit props)))
  11018. (when (or (not specific) (string= specific "ITEM"))
  11019. (let ((case-fold-search nil))
  11020. (when (looking-at org-complex-heading-regexp)
  11021. (push (cons "ITEM"
  11022. (let ((title (match-string-no-properties 4)))
  11023. (if (org-string-nw-p title)
  11024. (org-remove-tabs title)
  11025. "")))
  11026. props)))
  11027. (when specific (throw 'exit props)))
  11028. (when (or (not specific) (string= specific "TODO"))
  11029. (let ((case-fold-search nil))
  11030. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11031. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11032. (when specific (throw 'exit props)))
  11033. (when (or (not specific) (string= specific "PRIORITY"))
  11034. (push (cons "PRIORITY"
  11035. (if (looking-at org-priority-regexp)
  11036. (match-string-no-properties 2)
  11037. (char-to-string org-priority-default)))
  11038. props)
  11039. (when specific (throw 'exit props)))
  11040. (when (or (not specific) (string= specific "FILE"))
  11041. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11042. props)
  11043. (when specific (throw 'exit props)))
  11044. (when (or (not specific) (string= specific "TAGS"))
  11045. (let ((tags (org-get-tags nil t)))
  11046. (when tags
  11047. (push (cons "TAGS" (org-make-tag-string tags))
  11048. props)))
  11049. (when specific (throw 'exit props)))
  11050. (when (or (not specific) (string= specific "ALLTAGS"))
  11051. (let ((tags (org-get-tags)))
  11052. (when tags
  11053. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11054. props)))
  11055. (when specific (throw 'exit props)))
  11056. (when (or (not specific) (string= specific "BLOCKED"))
  11057. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11058. (when specific (throw 'exit props)))
  11059. (when (or (not specific)
  11060. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11061. (forward-line)
  11062. (when (looking-at-p org-planning-line-re)
  11063. (end-of-line)
  11064. (let ((bol (line-beginning-position))
  11065. ;; Backward compatibility: time keywords used to
  11066. ;; be configurable (before 8.3). Make sure we
  11067. ;; get the correct keyword.
  11068. (key-assoc `(("CLOSED" . ,org-closed-string)
  11069. ("DEADLINE" . ,org-deadline-string)
  11070. ("SCHEDULED" . ,org-scheduled-string))))
  11071. (dolist (pair (if specific (list (assoc specific key-assoc))
  11072. key-assoc))
  11073. (save-excursion
  11074. (when (search-backward (cdr pair) bol t)
  11075. (goto-char (match-end 0))
  11076. (skip-chars-forward " \t")
  11077. (and (looking-at org-ts-regexp-both)
  11078. (push (cons (car pair)
  11079. (match-string-no-properties 0))
  11080. props)))))))
  11081. (when specific (throw 'exit props)))
  11082. (when (or (not specific)
  11083. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11084. (let ((find-ts
  11085. (lambda (end ts)
  11086. ;; Fix next time-stamp before END. TS is the
  11087. ;; list of time-stamps found so far.
  11088. (let ((ts ts)
  11089. (regexp (cond
  11090. ((string= specific "TIMESTAMP")
  11091. org-ts-regexp)
  11092. ((string= specific "TIMESTAMP_IA")
  11093. org-ts-regexp-inactive)
  11094. ((assoc "TIMESTAMP_IA" ts)
  11095. org-ts-regexp)
  11096. ((assoc "TIMESTAMP" ts)
  11097. org-ts-regexp-inactive)
  11098. (t org-ts-regexp-both))))
  11099. (catch 'next
  11100. (while (re-search-forward regexp end t)
  11101. (backward-char)
  11102. (let ((object (org-element-context)))
  11103. ;; Accept to match timestamps in node
  11104. ;; properties, too.
  11105. (when (memq (org-element-type object)
  11106. '(node-property timestamp))
  11107. (let ((type
  11108. (org-element-property :type object)))
  11109. (cond
  11110. ((and (memq type '(active active-range))
  11111. (not (equal specific "TIMESTAMP_IA")))
  11112. (unless (assoc "TIMESTAMP" ts)
  11113. (push (cons "TIMESTAMP"
  11114. (org-element-property
  11115. :raw-value object))
  11116. ts)
  11117. (when specific (throw 'exit ts))))
  11118. ((and (memq type '(inactive inactive-range))
  11119. (not (string= specific "TIMESTAMP")))
  11120. (unless (assoc "TIMESTAMP_IA" ts)
  11121. (push (cons "TIMESTAMP_IA"
  11122. (org-element-property
  11123. :raw-value object))
  11124. ts)
  11125. (when specific (throw 'exit ts))))))
  11126. ;; Both timestamp types are found,
  11127. ;; move to next part.
  11128. (when (= (length ts) 2) (throw 'next ts)))))
  11129. ts)))))
  11130. (goto-char beg)
  11131. ;; First look for timestamps within headline.
  11132. (let ((ts (funcall find-ts (line-end-position) nil)))
  11133. (if (= (length ts) 2) (setq props (nconc ts props))
  11134. ;; Then find timestamps in the section, skipping
  11135. ;; planning line.
  11136. (let ((end (save-excursion (outline-next-heading))))
  11137. (forward-line)
  11138. (when (looking-at-p org-planning-line-re) (forward-line))
  11139. (setq props (nconc (funcall find-ts end ts) props))))))))
  11140. ;; Get the standard properties, like :PROP:.
  11141. (when (memq which '(nil all standard))
  11142. ;; If we are looking after a specific property, delegate
  11143. ;; to `org-entry-get', which is faster. However, make an
  11144. ;; exception for "CATEGORY", since it can be also set
  11145. ;; through keywords (i.e. #+CATEGORY).
  11146. (if (and specific (not (equal specific "CATEGORY")))
  11147. (let ((value (org-entry-get beg specific nil t)))
  11148. (throw 'exit (and value (list (cons specific value)))))
  11149. (let ((range (org-get-property-block beg)))
  11150. (when range
  11151. (let ((end (cdr range)) seen-base)
  11152. (goto-char (car range))
  11153. ;; Unlike to `org--update-property-plist', we
  11154. ;; handle the case where base values is found
  11155. ;; after its extension. We also forbid standard
  11156. ;; properties to be named as special properties.
  11157. (while (re-search-forward org-property-re end t)
  11158. (let* ((key (upcase (match-string-no-properties 2)))
  11159. (extendp (string-match-p "\\+\\'" key))
  11160. (key-base (if extendp (substring key 0 -1) key))
  11161. (value (match-string-no-properties 3)))
  11162. (cond
  11163. ((member-ignore-case key-base org-special-properties))
  11164. (extendp
  11165. (setq props
  11166. (org--update-property-plist key value props)))
  11167. ((member key seen-base))
  11168. (t (push key seen-base)
  11169. (let ((p (assoc-string key props t)))
  11170. (if p (setcdr p (concat value " " (cdr p)))
  11171. (push (cons key value) props))))))))))))
  11172. (unless (assoc "CATEGORY" props)
  11173. (push (cons "CATEGORY" (org-get-category beg)) props)
  11174. (when (string= specific "CATEGORY") (throw 'exit props)))
  11175. ;; Return value.
  11176. props)))))
  11177. (defun org--property-local-values (property literal-nil &optional element)
  11178. "Return value for PROPERTY in current entry or ELEMENT.
  11179. Value is a list whose car is the base value for PROPERTY and cdr
  11180. a list of accumulated values. Return nil if neither is found in
  11181. the entry. Also return nil when PROPERTY is set to \"nil\",
  11182. unless LITERAL-NIL is non-nil."
  11183. (let ((element (or element
  11184. (and (org-element--cache-active-p)
  11185. (org-element-at-point nil 'cached)))))
  11186. (if element
  11187. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11188. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11189. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11190. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11191. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11192. (value (cons base-value extra-value)))
  11193. (and (not (equal value '(nil))) value))
  11194. (let ((range (org-get-property-block)))
  11195. (when range
  11196. (goto-char (car range))
  11197. (let* ((case-fold-search t)
  11198. (end (cdr range))
  11199. (value
  11200. ;; Base value.
  11201. (save-excursion
  11202. (let ((v (and (re-search-forward
  11203. (org-re-property property nil t) end t)
  11204. (match-string-no-properties 3))))
  11205. (list (if literal-nil v (org-not-nil v)))))))
  11206. ;; Find additional values.
  11207. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11208. (while (re-search-forward property+ end t)
  11209. (push (match-string-no-properties 3) value)))
  11210. ;; Return final values.
  11211. (and (not (equal value '(nil))) (nreverse value))))))))
  11212. (defun org--property-global-or-keyword-value (property literal-nil)
  11213. "Return value for PROPERTY as defined by global properties or by keyword.
  11214. Return value is a string. Return nil if property is not set
  11215. globally or by keyword. Also return nil when PROPERTY is set to
  11216. \"nil\", unless LITERAL-NIL is non-nil."
  11217. (let ((global
  11218. (cdr (or (assoc-string property org-keyword-properties t)
  11219. (assoc-string property org-global-properties t)
  11220. (assoc-string property org-global-properties-fixed t)))))
  11221. (if literal-nil global (org-not-nil global))))
  11222. (defun org-entry-get (pom property &optional inherit literal-nil)
  11223. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11224. If INHERIT is non-nil and the entry does not have the property,
  11225. then also check higher levels of the hierarchy. If INHERIT is
  11226. the symbol `selective', use inheritance only if the setting in
  11227. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11228. If the property is present but empty, the return value is the
  11229. empty string. If the property is not present at all, nil is
  11230. returned. In any other case, return the value as a string.
  11231. Search is case-insensitive.
  11232. If LITERAL-NIL is set, return the string value \"nil\" as
  11233. a string, do not interpret it as the list atom nil. This is used
  11234. for inheritance when a \"nil\" value can supersede a non-nil
  11235. value higher up the hierarchy."
  11236. (org-with-point-at pom
  11237. (cond
  11238. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11239. ;; We need a special property. Use `org-entry-properties' to
  11240. ;; retrieve it, but specify the wanted property.
  11241. (cdr (assoc-string property (org-entry-properties nil property))))
  11242. ((and inherit
  11243. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11244. (org-entry-get-with-inheritance property literal-nil))
  11245. (t
  11246. (let* ((local (org--property-local-values property literal-nil))
  11247. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11248. (if literal-nil value (org-not-nil value)))))))
  11249. (defun org-property-or-variable-value (var &optional inherit)
  11250. "Check if there is a property fixing the value of VAR.
  11251. If yes, return this value. If not, return the current value of the variable."
  11252. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11253. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11254. (read prop)
  11255. (symbol-value var))))
  11256. (defun org-entry-delete (pom property)
  11257. "Delete PROPERTY from entry at point-or-marker POM.
  11258. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11259. non-nil when a property was removed."
  11260. (org-with-point-at pom
  11261. (pcase (org-get-property-block)
  11262. (`(,begin . ,origin)
  11263. (let* ((end (copy-marker origin))
  11264. (re (org-re-property
  11265. (concat (regexp-quote property) "\\+?") t t)))
  11266. (goto-char begin)
  11267. (while (re-search-forward re end t)
  11268. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11269. ;; If drawer is empty, remove it altogether.
  11270. (when (= begin end)
  11271. (delete-region (line-beginning-position 0)
  11272. (line-beginning-position 2)))
  11273. ;; Return non-nil if some property was removed.
  11274. (prog1 (/= end origin) (set-marker end nil))))
  11275. (_ nil))))
  11276. ;; Multi-values properties are properties that contain multiple values
  11277. ;; These values are assumed to be single words, separated by whitespace.
  11278. (defun org-entry-add-to-multivalued-property (pom property value)
  11279. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11280. (let* ((old (org-entry-get pom property))
  11281. (values (and old (split-string old))))
  11282. (setq value (org-entry-protect-space value))
  11283. (unless (member value values)
  11284. (setq values (append values (list value)))
  11285. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11286. (defun org-entry-remove-from-multivalued-property (pom property value)
  11287. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11288. (let* ((old (org-entry-get pom property))
  11289. (values (and old (split-string old))))
  11290. (setq value (org-entry-protect-space value))
  11291. (when (member value values)
  11292. (setq values (delete value values))
  11293. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11294. (defun org-entry-member-in-multivalued-property (pom property value)
  11295. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11296. (let* ((old (org-entry-get pom property))
  11297. (values (and old (split-string old))))
  11298. (setq value (org-entry-protect-space value))
  11299. (member value values)))
  11300. (defun org-entry-get-multivalued-property (pom property)
  11301. "Return a list of values in a multivalued property."
  11302. (let* ((value (org-entry-get pom property))
  11303. (values (and value (split-string value))))
  11304. (mapcar #'org-entry-restore-space values)))
  11305. (defun org-entry-put-multivalued-property (pom property &rest values)
  11306. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11307. VALUES should be a list of strings. Spaces will be protected."
  11308. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11309. (let* ((value (org-entry-get pom property))
  11310. (values (and value (split-string value))))
  11311. (mapcar #'org-entry-restore-space values)))
  11312. (defun org-entry-protect-space (s)
  11313. "Protect spaces and newline in string S."
  11314. (while (string-match " " s)
  11315. (setq s (replace-match "%20" t t s)))
  11316. (while (string-match "\n" s)
  11317. (setq s (replace-match "%0A" t t s)))
  11318. s)
  11319. (defun org-entry-restore-space (s)
  11320. "Restore spaces and newline in string S."
  11321. (while (string-match "%20" s)
  11322. (setq s (replace-match " " t t s)))
  11323. (while (string-match "%0A" s)
  11324. (setq s (replace-match "\n" t t s)))
  11325. s)
  11326. (defvar org-entry-property-inherited-from (make-marker)
  11327. "Marker pointing to the entry from where a property was inherited.
  11328. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11329. location of the entry where the inheritance search matched. If there was
  11330. no match, the marker will point nowhere.
  11331. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11332. is set.")
  11333. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11334. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11335. The search will stop at the first ancestor which has the property defined.
  11336. If the value found is \"nil\", return nil to show that the property
  11337. should be considered as undefined (this is the meaning of nil here).
  11338. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11339. (move-marker org-entry-property-inherited-from nil)
  11340. (org-with-wide-buffer
  11341. (let (value at-bob-no-heading)
  11342. (catch 'exit
  11343. (let ((element (or element
  11344. (and (org-element--cache-active-p)
  11345. (org-element-at-point nil 'cached)))))
  11346. (if element
  11347. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11348. (while t
  11349. (let* ((v (org--property-local-values property literal-nil element))
  11350. (v (if (listp v) v (list v))))
  11351. (when v
  11352. (setq value
  11353. (concat (mapconcat #'identity (delq nil v) " ")
  11354. (and value " ")
  11355. value)))
  11356. (cond
  11357. ((car v)
  11358. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11359. (throw 'exit nil))
  11360. ((org-element-property :parent element)
  11361. (setq element (org-element-property :parent element)))
  11362. (t
  11363. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11364. (cond ((not global))
  11365. (value (setq value (concat global " " value)))
  11366. (t (setq value global))))
  11367. (throw 'exit nil))))))
  11368. (while t
  11369. (let ((v (org--property-local-values property literal-nil)))
  11370. (when v
  11371. (setq value
  11372. (concat (mapconcat #'identity (delq nil v) " ")
  11373. (and value " ")
  11374. value)))
  11375. (cond
  11376. ((car v)
  11377. (org-back-to-heading-or-point-min t)
  11378. (move-marker org-entry-property-inherited-from (point))
  11379. (throw 'exit nil))
  11380. ((or (org-up-heading-safe)
  11381. (and (not (bobp))
  11382. (goto-char (point-min))
  11383. nil)
  11384. ;; `org-up-heading-safe' returned nil. We are at low
  11385. ;; level heading or bob. If there is headline
  11386. ;; there, do not try to fetch its properties.
  11387. (and (bobp)
  11388. (not at-bob-no-heading)
  11389. (not (org-at-heading-p))
  11390. (setq at-bob-no-heading t))))
  11391. (t
  11392. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11393. (cond ((not global))
  11394. (value (setq value (concat global " " value)))
  11395. (t (setq value global))))
  11396. (throw 'exit nil))))))))
  11397. (if literal-nil value (org-not-nil value)))))
  11398. (defvar org-property-changed-functions nil
  11399. "Hook called when the value of a property has changed.
  11400. Each hook function should accept two arguments, the name of the property
  11401. and the new value.")
  11402. (defun org-entry-put (pom property value)
  11403. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11404. If the value is nil, it is converted to the empty string. If it
  11405. is not a string, an error is raised. Also raise an error on
  11406. invalid property names.
  11407. PROPERTY can be any regular property (see
  11408. `org-special-properties'). It can also be \"TODO\",
  11409. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11410. For the last two properties, VALUE may have any of the special
  11411. values \"earlier\" and \"later\". The function then increases or
  11412. decreases scheduled or deadline date by one day."
  11413. (cond ((null value) (setq value ""))
  11414. ((not (stringp value)) (error "Properties values should be strings"))
  11415. ((not (org--valid-property-p property))
  11416. (user-error "Invalid property name: \"%s\"" property)))
  11417. (org-no-read-only
  11418. (org-with-point-at pom
  11419. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11420. (org-back-to-heading-or-point-min t)
  11421. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11422. (let ((beg (point)))
  11423. (cond
  11424. ((equal property "TODO")
  11425. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11426. ((not (member value org-todo-keywords-1))
  11427. (user-error "\"%s\" is not a valid TODO state" value)))
  11428. (org-todo value)
  11429. (org-align-tags))
  11430. ((equal property "PRIORITY")
  11431. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11432. (org-align-tags))
  11433. ((equal property "SCHEDULED")
  11434. (forward-line)
  11435. (if (and (looking-at-p org-planning-line-re)
  11436. (re-search-forward
  11437. org-scheduled-time-regexp (line-end-position) t))
  11438. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11439. ((string= value "later") (org-timestamp-change 1 'day))
  11440. ((string= value "") (org-schedule '(4)))
  11441. (t (org-schedule nil value)))
  11442. (if (member value '("earlier" "later" ""))
  11443. (call-interactively #'org-schedule)
  11444. (org-schedule nil value))))
  11445. ((equal property "DEADLINE")
  11446. (forward-line)
  11447. (if (and (looking-at-p org-planning-line-re)
  11448. (re-search-forward
  11449. org-deadline-time-regexp (line-end-position) t))
  11450. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11451. ((string= value "later") (org-timestamp-change 1 'day))
  11452. ((string= value "") (org-deadline '(4)))
  11453. (t (org-deadline nil value)))
  11454. (if (member value '("earlier" "later" ""))
  11455. (call-interactively #'org-deadline)
  11456. (org-deadline nil value))))
  11457. ((member property org-special-properties)
  11458. (error "The %s property cannot be set with `org-entry-put'" property))
  11459. (t
  11460. (org-fold-core-ignore-modifications
  11461. (let* ((range (org-get-property-block beg 'force))
  11462. (end (cdr range))
  11463. (case-fold-search t))
  11464. (goto-char (car range))
  11465. (if (re-search-forward (org-re-property property nil t) end t)
  11466. (progn (delete-region (match-beginning 0) (match-end 0))
  11467. (goto-char (match-beginning 0)))
  11468. (goto-char end)
  11469. (insert-and-inherit "\n")
  11470. (backward-char))
  11471. (insert-and-inherit ":" property ":")
  11472. (when value (insert-and-inherit " " value))
  11473. (org-indent-line))))))
  11474. (run-hook-with-args 'org-property-changed-functions property value))))
  11475. (defun org-buffer-property-keys (&optional specials defaults columns)
  11476. "Get all property keys in the current buffer.
  11477. When SPECIALS is non-nil, also list the special properties that
  11478. reflect things like tags and TODO state.
  11479. When DEFAULTS is non-nil, also include properties that has
  11480. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11481. DESCRIPTION, LOCATION, and LOGGING and others.
  11482. When COLUMNS in non-nil, also include property names given in
  11483. COLUMN formats in the current buffer."
  11484. (let ((case-fold-search t)
  11485. (props (append
  11486. (and specials org-special-properties)
  11487. (and defaults (cons org-effort-property org-default-properties))
  11488. ;; Get property names from #+PROPERTY keywords as well
  11489. (mapcar (lambda (s)
  11490. (nth 0 (split-string s)))
  11491. (cdar (org-collect-keywords '("PROPERTY")))))))
  11492. (org-with-wide-buffer
  11493. (goto-char (point-min))
  11494. (while (re-search-forward org-property-start-re nil t)
  11495. (catch :skip
  11496. (let ((range (org-get-property-block)))
  11497. (unless range (throw :skip nil))
  11498. (goto-char (car range))
  11499. (let ((begin (car range))
  11500. (end (cdr range)))
  11501. ;; Make sure that found property block is not located
  11502. ;; before current point, as it would generate an infloop.
  11503. ;; It can happen, for example, in the following
  11504. ;; situation:
  11505. ;;
  11506. ;; * Headline
  11507. ;; :PROPERTIES:
  11508. ;; ...
  11509. ;; :END:
  11510. ;; *************** Inlinetask
  11511. ;; #+BEGIN_EXAMPLE
  11512. ;; :PROPERTIES:
  11513. ;; #+END_EXAMPLE
  11514. ;;
  11515. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11516. (while (< (point) end)
  11517. (let ((p (progn (looking-at org-property-re)
  11518. (match-string-no-properties 2))))
  11519. ;; Only add true property name, not extension symbol.
  11520. (push (if (not (string-match-p "\\+\\'" p)) p
  11521. (substring p 0 -1))
  11522. props))
  11523. (forward-line))))
  11524. (outline-next-heading)))
  11525. (when columns
  11526. (goto-char (point-min))
  11527. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11528. (let ((element (org-element-at-point)))
  11529. (when (memq (org-element-type element) '(keyword node-property))
  11530. (let ((value (org-element-property :value element))
  11531. (start 0))
  11532. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11533. \\(?:{[^}]+}\\)?"
  11534. value start)
  11535. (setq start (match-end 0))
  11536. (let ((p (match-string-no-properties 1 value)))
  11537. (unless (member-ignore-case p org-special-properties)
  11538. (push p props))))))))))
  11539. (sort (delete-dups
  11540. (append props
  11541. ;; for each xxx_ALL property, make sure the bare
  11542. ;; xxx property is also included
  11543. (delq nil (mapcar (lambda (p)
  11544. (and (string-match-p "._ALL\\'" p)
  11545. (substring p 0 -4)))
  11546. props))))
  11547. (lambda (a b) (string< (upcase a) (upcase b))))))
  11548. (defun org-property-values (key)
  11549. "List all non-nil values of property KEY in current buffer."
  11550. (org-with-wide-buffer
  11551. (goto-char (point-min))
  11552. (let ((case-fold-search t)
  11553. (re (org-re-property key))
  11554. values)
  11555. (while (re-search-forward re nil t)
  11556. (push (org-entry-get (point) key) values))
  11557. (delete-dups values))))
  11558. (defun org-insert-property-drawer ()
  11559. "Insert a property drawer into the current entry.
  11560. Do nothing if the drawer already exists. The newly created
  11561. drawer is immediately hidden."
  11562. (org-with-wide-buffer
  11563. ;; Set point to the position where the drawer should be inserted.
  11564. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11565. (org-back-to-heading-or-point-min t)
  11566. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11567. (if (org-before-first-heading-p)
  11568. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11569. (forward-line)
  11570. (when (looking-at-p org-planning-line-re) (forward-line)))
  11571. (unless (looking-at-p org-property-drawer-re)
  11572. ;; Make sure we start editing a line from current entry, not from
  11573. ;; next one. It prevents extending text properties or overlays
  11574. ;; belonging to the latter.
  11575. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11576. (let ((begin (if (bobp) (point) (1+ (point))))
  11577. (inhibit-read-only t))
  11578. (unless (bobp) (insert "\n"))
  11579. (insert ":PROPERTIES:\n:END:")
  11580. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11581. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11582. (org-indent-region begin (point))))))
  11583. (defun org-insert-drawer (&optional arg drawer)
  11584. "Insert a drawer at point.
  11585. When optional argument ARG is non-nil, insert a property drawer.
  11586. Optional argument DRAWER, when non-nil, is a string representing
  11587. drawer's name. Otherwise, the user is prompted for a name.
  11588. If a region is active, insert the drawer around that region
  11589. instead.
  11590. Point is left between drawer's boundaries."
  11591. (interactive "P")
  11592. (let* ((drawer (if arg "PROPERTIES"
  11593. (or drawer (read-from-minibuffer "Drawer: ")))))
  11594. (cond
  11595. ;; With C-u, fall back on `org-insert-property-drawer'
  11596. (arg (org-insert-property-drawer))
  11597. ;; Check validity of suggested drawer's name.
  11598. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11599. (user-error "Invalid drawer name"))
  11600. ;; With an active region, insert a drawer at point.
  11601. ((not (org-region-active-p))
  11602. (progn
  11603. (unless (bolp) (insert "\n"))
  11604. (insert (format ":%s:\n\n:END:\n" drawer))
  11605. (forward-line -2)))
  11606. ;; Otherwise, insert the drawer at point
  11607. (t
  11608. (let ((rbeg (region-beginning))
  11609. (rend (copy-marker (region-end))))
  11610. (unwind-protect
  11611. (progn
  11612. (goto-char rbeg)
  11613. (beginning-of-line)
  11614. (when (save-excursion
  11615. (re-search-forward org-outline-regexp-bol rend t))
  11616. (user-error "Drawers cannot contain headlines"))
  11617. ;; Position point at the beginning of the first
  11618. ;; non-blank line in region. Insert drawer's opening
  11619. ;; there, then indent it.
  11620. (org-skip-whitespace)
  11621. (beginning-of-line)
  11622. (insert ":" drawer ":\n")
  11623. (forward-line -1)
  11624. (indent-for-tab-command)
  11625. ;; Move point to the beginning of the first blank line
  11626. ;; after the last non-blank line in region. Insert
  11627. ;; drawer's closing, then indent it.
  11628. (goto-char rend)
  11629. (skip-chars-backward " \r\t\n")
  11630. (insert "\n:END:")
  11631. (deactivate-mark t)
  11632. (indent-for-tab-command)
  11633. (unless (eolp) (insert "\n")))
  11634. ;; Clear marker, whatever the outcome of insertion is.
  11635. (set-marker rend nil)))))))
  11636. (defvar org-property-set-functions-alist nil
  11637. "Property set function alist.
  11638. Each entry should have the following format:
  11639. (PROPERTY . READ-FUNCTION)
  11640. The read function will be called with the same argument as
  11641. `org-completing-read'.")
  11642. (defun org-set-property-function (property)
  11643. "Get the function that should be used to set PROPERTY.
  11644. This is computed according to `org-property-set-functions-alist'."
  11645. (or (cdr (assoc property org-property-set-functions-alist))
  11646. 'org-completing-read))
  11647. (defun org-read-property-value (property &optional pom default)
  11648. "Read value for PROPERTY, as a string.
  11649. When optional argument POM is non-nil, completion uses additional
  11650. information, i.e., allowed or existing values at point or marker
  11651. POM.
  11652. Optional argument DEFAULT provides a default value for PROPERTY."
  11653. (let* ((completion-ignore-case t)
  11654. (allowed
  11655. (or (org-property-get-allowed-values nil property 'table)
  11656. (and pom (org-property-get-allowed-values pom property 'table))))
  11657. (current (org-entry-get nil property))
  11658. (prompt (format "%s value%s: "
  11659. property
  11660. (if (org-string-nw-p current)
  11661. (format " [%s]" current)
  11662. "")))
  11663. (set-function (org-set-property-function property)))
  11664. (org-trim
  11665. (if allowed
  11666. (funcall set-function
  11667. prompt allowed nil
  11668. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11669. default nil default)
  11670. (let ((all (mapcar #'list
  11671. (append (org-property-values property)
  11672. (and pom
  11673. (org-with-point-at pom
  11674. (org-property-values property)))))))
  11675. (funcall set-function prompt all nil nil "" nil current))))))
  11676. (defvar org-last-set-property nil)
  11677. (defvar org-last-set-property-value nil)
  11678. (defun org-read-property-name ()
  11679. "Read a property name."
  11680. (let ((completion-ignore-case t)
  11681. (default-prop (or (and (org-at-property-p)
  11682. (match-string-no-properties 2))
  11683. org-last-set-property)))
  11684. (org-completing-read
  11685. (concat "Property"
  11686. (if default-prop (concat " [" default-prop "]") "")
  11687. ": ")
  11688. (mapcar #'list (org-buffer-property-keys nil t t))
  11689. nil nil nil nil default-prop)))
  11690. (defun org-set-property-and-value (use-last)
  11691. "Allow to set [PROPERTY]: [value] direction from prompt.
  11692. When use-default, don't even ask, just use the last
  11693. \"[PROPERTY]: [value]\" string from the history."
  11694. (interactive "P")
  11695. (let* ((completion-ignore-case t)
  11696. (pv (or (and use-last org-last-set-property-value)
  11697. (org-completing-read
  11698. "Enter a \"[Property]: [value]\" pair: "
  11699. nil nil nil nil nil
  11700. org-last-set-property-value)))
  11701. prop val)
  11702. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11703. (setq prop (match-string 1 pv)
  11704. val (match-string 2 pv))
  11705. (org-set-property prop val))))
  11706. (defun org-set-property (property value)
  11707. "In the current entry, set PROPERTY to VALUE.
  11708. When called interactively, this will prompt for a property name, offering
  11709. completion on existing and default properties. And then it will prompt
  11710. for a value, offering completion either on allowed values (via an inherited
  11711. xxx_ALL property) or on existing values in other instances of this property
  11712. in the current file.
  11713. Throw an error when trying to set a property with an invalid name."
  11714. (interactive (list nil nil))
  11715. (let ((property (or property (org-read-property-name))))
  11716. ;; `org-entry-put' also makes the following check, but this one
  11717. ;; avoids polluting `org-last-set-property' and
  11718. ;; `org-last-set-property-value' needlessly.
  11719. (unless (org--valid-property-p property)
  11720. (user-error "Invalid property name: \"%s\"" property))
  11721. (let ((value (or value (org-read-property-value property)))
  11722. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11723. (setq org-last-set-property property)
  11724. (setq org-last-set-property-value (concat property ": " value))
  11725. ;; Possibly postprocess the inserted value:
  11726. (when fn (setq value (funcall fn value)))
  11727. (unless (equal (org-entry-get nil property) value)
  11728. (org-entry-put nil property value)))))
  11729. (defun org-find-property (property &optional value)
  11730. "Find first entry in buffer that sets PROPERTY.
  11731. When optional argument VALUE is non-nil, only consider an entry
  11732. if it contains PROPERTY set to this value. If PROPERTY should be
  11733. explicitly set to nil, use string \"nil\" for VALUE.
  11734. Return position where the entry begins, or nil if there is no
  11735. such entry. If narrowing is in effect, only search the visible
  11736. part of the buffer."
  11737. (save-excursion
  11738. (goto-char (point-min))
  11739. (let ((case-fold-search t)
  11740. (re (org-re-property property nil (not value) value)))
  11741. (catch 'exit
  11742. (while (re-search-forward re nil t)
  11743. (when (if value (org-at-property-p)
  11744. (org-entry-get (point) property nil t))
  11745. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  11746. (point)))))))))
  11747. (defun org-delete-property (property)
  11748. "In the current entry, delete PROPERTY."
  11749. (interactive
  11750. (let* ((completion-ignore-case t)
  11751. (cat (org-entry-get (point) "CATEGORY"))
  11752. (props0 (org-entry-properties nil 'standard))
  11753. (props (if cat props0
  11754. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  11755. (prop (if (< 1 (length props))
  11756. (completing-read "Property: " props nil t)
  11757. (caar props))))
  11758. (list prop)))
  11759. (if (not property)
  11760. (message "No property to delete in this entry")
  11761. (org-entry-delete nil property)
  11762. (message "Property \"%s\" deleted" property)))
  11763. (defun org-delete-property-globally (property)
  11764. "Remove PROPERTY globally, from all entries.
  11765. This function ignores narrowing, if any."
  11766. (interactive
  11767. (let* ((completion-ignore-case t)
  11768. (prop (completing-read
  11769. "Globally remove property: "
  11770. (mapcar #'list (org-buffer-property-keys)))))
  11771. (list prop)))
  11772. (org-with-wide-buffer
  11773. (goto-char (point-min))
  11774. (let ((count 0)
  11775. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  11776. (while (re-search-forward re nil t)
  11777. (when (org-entry-delete (point) property) (cl-incf count)))
  11778. (message "Property \"%s\" removed from %d entries" property count))))
  11779. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  11780. (defun org-compute-property-at-point ()
  11781. "Compute the property at point.
  11782. This looks for an enclosing column format, extracts the operator and
  11783. then applies it to the property in the column format's scope."
  11784. (interactive)
  11785. (unless (org-at-property-p)
  11786. (user-error "Not at a property"))
  11787. (let ((prop (match-string-no-properties 2)))
  11788. (org-columns-get-format-and-top-level)
  11789. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  11790. (user-error "No operator defined for property %s" prop))
  11791. (org-columns-compute prop)))
  11792. (defvar org-property-allowed-value-functions nil
  11793. "Hook for functions supplying allowed values for a specific property.
  11794. The functions must take a single argument, the name of the property, and
  11795. return a flat list of allowed values. If \":ETC\" is one of
  11796. the values, this means that these values are intended as defaults for
  11797. completion, but that other values should be allowed too.
  11798. The functions must return nil if they are not responsible for this
  11799. property.")
  11800. (defun org-property-get-allowed-values (pom property &optional table)
  11801. "Get allowed values for the property PROPERTY.
  11802. When TABLE is non-nil, return an alist that can directly be used for
  11803. completion."
  11804. (let (vals)
  11805. (cond
  11806. ((equal property "TODO")
  11807. (setq vals (org-with-point-at pom
  11808. (append org-todo-keywords-1 '("")))))
  11809. ((equal property "PRIORITY")
  11810. (let ((n org-priority-lowest))
  11811. (while (>= n org-priority-highest)
  11812. (push (char-to-string n) vals)
  11813. (setq n (1- n)))))
  11814. ((equal property "CATEGORY"))
  11815. ((member property org-special-properties))
  11816. ((setq vals (run-hook-with-args-until-success
  11817. 'org-property-allowed-value-functions property)))
  11818. (t
  11819. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  11820. (when (and vals (string-match "\\S-" vals))
  11821. (setq vals (car (read-from-string (concat "(" vals ")"))))
  11822. (setq vals (mapcar (lambda (x)
  11823. (cond ((stringp x) x)
  11824. ((numberp x) (number-to-string x))
  11825. ((symbolp x) (symbol-name x))
  11826. (t "???")))
  11827. vals)))))
  11828. (when (member ":ETC" vals)
  11829. (setq vals (remove ":ETC" vals))
  11830. (org-add-props (car vals) '(org-unrestricted t)))
  11831. (if table (mapcar 'list vals) vals)))
  11832. (defun org-property-previous-allowed-value (&optional _previous)
  11833. "Switch to the next allowed value for this property."
  11834. (interactive)
  11835. (org-property-next-allowed-value t))
  11836. (defun org-property-next-allowed-value (&optional previous)
  11837. "Switch to the next allowed value for this property."
  11838. (interactive)
  11839. (unless (org-at-property-p)
  11840. (user-error "Not at a property"))
  11841. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  11842. (key (match-string 2))
  11843. (value (match-string 3))
  11844. (allowed (or (org-property-get-allowed-values (point) key)
  11845. (and (member value '("[ ]" "[-]" "[X]"))
  11846. '("[ ]" "[X]"))))
  11847. (heading (save-match-data (nth 4 (org-heading-components))))
  11848. nval)
  11849. (unless allowed
  11850. (user-error "Allowed values for this property have not been defined"))
  11851. (when previous (setq allowed (reverse allowed)))
  11852. (when (member value allowed)
  11853. (setq nval (car (cdr (member value allowed)))))
  11854. (setq nval (or nval (car allowed)))
  11855. (when (equal nval value)
  11856. (user-error "Only one allowed value for this property"))
  11857. (org-at-property-p)
  11858. (replace-match (concat " :" key ": " nval) t t)
  11859. (org-indent-line)
  11860. (beginning-of-line 1)
  11861. (skip-chars-forward " \t")
  11862. (when (equal prop org-effort-property)
  11863. (unless (org-element--cache-active-p)
  11864. (org-refresh-property
  11865. '((effort . identity)
  11866. (effort-minutes . org-duration-to-minutes))
  11867. nval))
  11868. (when (string= org-clock-current-task heading)
  11869. (setq org-clock-effort nval)
  11870. (org-clock-update-mode-line)))
  11871. (run-hook-with-args 'org-property-changed-functions key nval)))
  11872. (defun org-find-olp (path &optional this-buffer)
  11873. "Return a marker pointing to the entry at outline path OLP.
  11874. If anything goes wrong, throw an error, and if you need to do
  11875. something based on this error, you can catch it with
  11876. `condition-case'.
  11877. If THIS-BUFFER is set, the outline path does not contain a file,
  11878. only headings."
  11879. (let* ((file (if this-buffer buffer-file-name (pop path)))
  11880. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  11881. (level 1)
  11882. (lmin 1)
  11883. (lmax 1)
  11884. end found flevel)
  11885. (unless buffer (error "File not found :%s" file))
  11886. (with-current-buffer buffer
  11887. (unless (derived-mode-p 'org-mode)
  11888. (error "Buffer %s needs to be in Org mode" buffer))
  11889. (org-with-wide-buffer
  11890. (goto-char (point-min))
  11891. (dolist (heading path)
  11892. (let ((re (format org-complex-heading-regexp-format
  11893. (regexp-quote heading)))
  11894. (cnt 0))
  11895. (while (re-search-forward re end t)
  11896. (setq level (- (match-end 1) (match-beginning 1)))
  11897. (when (and (>= level lmin) (<= level lmax))
  11898. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  11899. (when (= cnt 0)
  11900. (error "Heading not found on level %d: %s" lmax heading))
  11901. (when (> cnt 1)
  11902. (error "Heading not unique on level %d: %s" lmax heading))
  11903. (goto-char found)
  11904. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  11905. (setq end (save-excursion (org-end-of-subtree t t)))))
  11906. (when (org-at-heading-p)
  11907. (point-marker))))))
  11908. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  11909. "Find node HEADING in BUFFER.
  11910. Return a marker to the heading if it was found, or nil if not.
  11911. If POS-ONLY is set, return just the position instead of a marker.
  11912. The heading text must match exact, but it may have a TODO keyword,
  11913. a priority cookie and tags in the standard locations."
  11914. (with-current-buffer (or buffer (current-buffer))
  11915. (org-with-wide-buffer
  11916. (goto-char (point-min))
  11917. (let (case-fold-search)
  11918. (when (re-search-forward
  11919. (format org-complex-heading-regexp-format
  11920. (regexp-quote heading)) nil t)
  11921. (if pos-only
  11922. (match-beginning 0)
  11923. (move-marker (make-marker) (match-beginning 0))))))))
  11924. (defun org-find-exact-heading-in-directory (heading &optional dir)
  11925. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  11926. When the target headline is found, return a marker to this location."
  11927. (let ((files (directory-files (or dir default-directory)
  11928. t "\\`[^.#].*\\.org\\'"))
  11929. visiting m buffer)
  11930. (catch 'found
  11931. (dolist (file files)
  11932. (message "trying %s" file)
  11933. (setq visiting (org-find-base-buffer-visiting file))
  11934. (setq buffer (or visiting (find-file-noselect file)))
  11935. (setq m (org-find-exact-headline-in-buffer
  11936. heading buffer))
  11937. (when (and (not m) (not visiting)) (kill-buffer buffer))
  11938. (and m (throw 'found m))))))
  11939. (defun org-find-entry-with-id (ident)
  11940. "Locate the entry that contains the ID property with exact value IDENT.
  11941. IDENT can be a string, a symbol or a number, this function will search for
  11942. the string representation of it.
  11943. Return the position where this entry starts, or nil if there is no such entry."
  11944. (interactive "sID: ")
  11945. (let ((id (cond
  11946. ((stringp ident) ident)
  11947. ((symbolp ident) (symbol-name ident))
  11948. ((numberp ident) (number-to-string ident))
  11949. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  11950. (org-with-wide-buffer (org-find-property "ID" id))))
  11951. ;;;; Timestamps
  11952. (defvar org-last-changed-timestamp nil)
  11953. (defvar org-last-inserted-timestamp nil
  11954. "The last time stamp inserted with `org-insert-time-stamp'.")
  11955. (defun org-time-stamp (arg &optional inactive)
  11956. "Prompt for a date/time and insert a time stamp.
  11957. If the user specifies a time like HH:MM or if this command is
  11958. called with at least one prefix argument, the time stamp contains
  11959. the date and the time. Otherwise, only the date is included.
  11960. All parts of a date not specified by the user are filled in from
  11961. the timestamp at point, if any, or the current date/time
  11962. otherwise.
  11963. If there is already a timestamp at the cursor, it is replaced.
  11964. With two universal prefix arguments, insert an active timestamp
  11965. with the current time without prompting the user.
  11966. When called from Lisp, the timestamp is inactive if INACTIVE is
  11967. non-nil."
  11968. (interactive "P")
  11969. (let* ((ts (cond
  11970. ((org-at-date-range-p t)
  11971. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  11972. ((org-at-timestamp-p 'lax) (match-string 0))))
  11973. ;; Default time is either the timestamp at point or today.
  11974. ;; When entering a range, only the range start is considered.
  11975. (default-time (and ts (org-time-string-to-time ts)))
  11976. (default-input (and ts (org-get-compact-tod ts)))
  11977. (repeater (and ts
  11978. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  11979. (match-string 0 ts)))
  11980. org-time-was-given
  11981. org-end-time-was-given
  11982. (time
  11983. (if (equal arg '(16)) (current-time)
  11984. ;; Preserve `this-command' and `last-command'.
  11985. (let ((this-command this-command)
  11986. (last-command last-command))
  11987. (org-read-date
  11988. arg 'totime nil nil default-time default-input
  11989. inactive)))))
  11990. (cond
  11991. ((and ts
  11992. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  11993. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  11994. (insert "--")
  11995. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  11996. (ts
  11997. ;; Make sure we're on a timestamp. When in the middle of a date
  11998. ;; range, move arbitrarily to range end.
  11999. (unless (org-at-timestamp-p 'lax)
  12000. (skip-chars-forward "-")
  12001. (org-at-timestamp-p 'lax))
  12002. (replace-match "")
  12003. (setq org-last-changed-timestamp
  12004. (org-insert-time-stamp
  12005. time (or org-time-was-given arg)
  12006. inactive nil nil (list org-end-time-was-given)))
  12007. (when repeater
  12008. (backward-char)
  12009. (insert " " repeater)
  12010. (setq org-last-changed-timestamp
  12011. (concat (substring org-last-inserted-timestamp 0 -1)
  12012. " " repeater ">")))
  12013. (message "Timestamp updated"))
  12014. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12015. (t (org-insert-time-stamp
  12016. time (or org-time-was-given arg) inactive nil nil
  12017. (list org-end-time-was-given))))))
  12018. ;; FIXME: can we use this for something else, like computing time differences?
  12019. (defun org-get-compact-tod (s)
  12020. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12021. (let* ((t1 (match-string 1 s))
  12022. (h1 (string-to-number (match-string 2 s)))
  12023. (m1 (string-to-number (match-string 3 s)))
  12024. (t2 (and (match-end 4) (match-string 5 s)))
  12025. (h2 (and t2 (string-to-number (match-string 6 s))))
  12026. (m2 (and t2 (string-to-number (match-string 7 s))))
  12027. dh dm)
  12028. (if (not t2)
  12029. t1
  12030. (setq dh (- h2 h1) dm (- m2 m1))
  12031. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12032. (concat t1 "+" (number-to-string dh)
  12033. (and (/= 0 dm) (format ":%02d" dm)))))))
  12034. (defun org-time-stamp-inactive (&optional arg)
  12035. "Insert an inactive time stamp.
  12036. An inactive time stamp is enclosed in square brackets instead of
  12037. angle brackets. It is inactive in the sense that it does not
  12038. trigger agenda entries. So these are more for recording a
  12039. certain time/date.
  12040. If the user specifies a time like HH:MM or if this command is called with
  12041. at least one prefix argument, the time stamp contains the date and the time.
  12042. Otherwise, only the date is included.
  12043. When called with two universal prefix arguments, insert an inactive time stamp
  12044. with the current time without prompting the user."
  12045. (interactive "P")
  12046. (org-time-stamp arg 'inactive))
  12047. (defvar org-date-ovl (make-overlay 1 1))
  12048. (overlay-put org-date-ovl 'face 'org-date-selected)
  12049. (delete-overlay org-date-ovl)
  12050. (defvar org-ans1) ; dynamically scoped parameter
  12051. (defvar org-ans2) ; dynamically scoped parameter
  12052. (defvar org-plain-time-of-day-regexp) ; defined below
  12053. (defvar org-overriding-default-time nil) ; dynamically scoped
  12054. (defvar org-read-date-overlay nil)
  12055. (defvar org-read-date-history nil)
  12056. (defvar org-read-date-final-answer nil)
  12057. (defvar org-read-date-analyze-futurep nil)
  12058. (defvar org-read-date-analyze-forced-year nil)
  12059. (defvar org-read-date-inactive)
  12060. (defvar org-def)
  12061. (defvar org-defdecode)
  12062. (defvar org-with-time)
  12063. (defvar calendar-setup) ; Dynamically scoped.
  12064. (defun org-read-date (&optional with-time to-time from-string prompt
  12065. default-time default-input inactive)
  12066. "Read a date, possibly a time, and make things smooth for the user.
  12067. The prompt will suggest to enter an ISO date, but you can also enter anything
  12068. which will at least partially be understood by `parse-time-string'.
  12069. Unrecognized parts of the date will default to the current day, month, year,
  12070. hour and minute. If this command is called to replace a timestamp at point,
  12071. or to enter the second timestamp of a range, the default time is taken
  12072. from the existing stamp. Furthermore, the command prefers the future,
  12073. so if you are giving a date where the year is not given, and the day-month
  12074. combination is already past in the current year, it will assume you
  12075. mean next year. For details, see the manual. A few examples:
  12076. 3-2-5 --> 2003-02-05
  12077. feb 15 --> currentyear-02-15
  12078. 2/15 --> currentyear-02-15
  12079. sep 12 9 --> 2009-09-12
  12080. 12:45 --> today 12:45
  12081. 22 sept 0:34 --> currentyear-09-22 0:34
  12082. 12 --> currentyear-currentmonth-12
  12083. Fri --> nearest Friday after today
  12084. -Tue --> last Tuesday
  12085. etc.
  12086. Furthermore you can specify a relative date by giving, as the *first* thing
  12087. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12088. change in days weeks, months, years.
  12089. With a single plus or minus, the date is relative to today. With a double
  12090. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12091. +4d --> four days from today
  12092. +4 --> same as above
  12093. +2w --> two weeks from today
  12094. ++5 --> five days from default date
  12095. The function understands only English month and weekday abbreviations.
  12096. While prompting, a calendar is popped up - you can also select the
  12097. date with the mouse (button 1). The calendar shows a period of three
  12098. months. To scroll it to other months, use the keys `>' and `<'.
  12099. If you don't like the calendar, turn it off with
  12100. (setq org-read-date-popup-calendar nil)
  12101. With optional argument TO-TIME, the date will immediately be converted
  12102. to an internal time.
  12103. With an optional argument WITH-TIME, the prompt will suggest to
  12104. also insert a time. Note that when WITH-TIME is not set, you can
  12105. still enter a time, and this function will inform the calling routine
  12106. about this change. The calling routine may then choose to change the
  12107. format used to insert the time stamp into the buffer to include the time.
  12108. With optional argument FROM-STRING, read from this string instead from
  12109. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12110. the time/date that is used for everything that is not specified by the
  12111. user."
  12112. (require 'parse-time)
  12113. (let* ((org-with-time with-time)
  12114. (org-time-stamp-rounding-minutes
  12115. (if (equal org-with-time '(16))
  12116. '(0 0)
  12117. org-time-stamp-rounding-minutes))
  12118. (ct (org-current-time))
  12119. (org-def (or org-overriding-default-time default-time ct))
  12120. (org-defdecode (decode-time org-def))
  12121. (cur-frame (selected-frame))
  12122. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12123. (calendar-setup
  12124. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12125. (calendar-move-hook nil)
  12126. (calendar-view-diary-initially-flag nil)
  12127. (calendar-view-holidays-initially-flag nil)
  12128. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12129. ;; Rationalize `org-def' and `org-defdecode', if required.
  12130. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12131. (setf (nth 2 org-defdecode) -1)
  12132. (setf (nth 1 org-defdecode) 59)
  12133. (setq org-def (apply #'encode-time org-defdecode))
  12134. (setq org-defdecode (decode-time org-def)))
  12135. (let* ((timestr (format-time-string
  12136. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12137. org-def))
  12138. (prompt (concat (if prompt (concat prompt " ") "")
  12139. (format "Date+time [%s]: " timestr))))
  12140. (cond
  12141. (from-string (setq ans from-string))
  12142. (org-read-date-popup-calendar
  12143. (save-excursion
  12144. (save-window-excursion
  12145. (calendar)
  12146. (when (eq calendar-setup 'calendar-only)
  12147. (setq cal-frame
  12148. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12149. (select-frame cal-frame))
  12150. (org-eval-in-calendar '(setq cursor-type nil) t)
  12151. (unwind-protect
  12152. (progn
  12153. (calendar-forward-day (- (time-to-days org-def)
  12154. (calendar-absolute-from-gregorian
  12155. (calendar-current-date))))
  12156. (org-eval-in-calendar nil t)
  12157. (let* ((old-map (current-local-map))
  12158. (map (copy-keymap calendar-mode-map))
  12159. (minibuffer-local-map
  12160. (copy-keymap org-read-date-minibuffer-local-map)))
  12161. (org-defkey map (kbd "RET") 'org-calendar-select)
  12162. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12163. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12164. (unwind-protect
  12165. (progn
  12166. (use-local-map map)
  12167. (setq org-read-date-inactive inactive)
  12168. (add-hook 'post-command-hook 'org-read-date-display)
  12169. (setq org-ans0
  12170. (read-string prompt
  12171. default-input
  12172. 'org-read-date-history
  12173. nil))
  12174. ;; org-ans0: from prompt
  12175. ;; org-ans1: from mouse click
  12176. ;; org-ans2: from calendar motion
  12177. (setq ans
  12178. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12179. (remove-hook 'post-command-hook 'org-read-date-display)
  12180. (use-local-map old-map)
  12181. (when org-read-date-overlay
  12182. (delete-overlay org-read-date-overlay)
  12183. (setq org-read-date-overlay nil)))))
  12184. (bury-buffer "*Calendar*")
  12185. (when cal-frame
  12186. (delete-frame cal-frame)
  12187. (select-frame-set-input-focus cur-frame))))))
  12188. (t ; Naked prompt only
  12189. (unwind-protect
  12190. (setq ans (read-string prompt default-input
  12191. 'org-read-date-history timestr))
  12192. (when org-read-date-overlay
  12193. (delete-overlay org-read-date-overlay)
  12194. (setq org-read-date-overlay nil))))))
  12195. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12196. (when org-read-date-analyze-forced-year
  12197. (message "Year was forced into %s"
  12198. (if org-read-date-force-compatible-dates
  12199. "compatible range (1970-2037)"
  12200. "range representable on this machine"))
  12201. (ding))
  12202. (setq final (apply #'encode-time final))
  12203. (setq org-read-date-final-answer ans)
  12204. (if to-time
  12205. final
  12206. ;; This round-trip gets rid of 34th of August and stuff like that....
  12207. (setq final (decode-time final))
  12208. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12209. (format "%04d-%02d-%02d %02d:%02d"
  12210. (nth 5 final) (nth 4 final) (nth 3 final)
  12211. (nth 2 final) (nth 1 final))
  12212. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12213. (defun org-read-date-display ()
  12214. "Display the current date prompt interpretation in the minibuffer."
  12215. (when org-read-date-display-live
  12216. (when org-read-date-overlay
  12217. (delete-overlay org-read-date-overlay))
  12218. (when (minibufferp (current-buffer))
  12219. (save-excursion
  12220. (end-of-line 1)
  12221. (while (not (equal (buffer-substring
  12222. (max (point-min) (- (point) 4)) (point))
  12223. " "))
  12224. (insert " ")))
  12225. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12226. " " (or org-ans1 org-ans2)))
  12227. (org-end-time-was-given nil)
  12228. (f (org-read-date-analyze ans org-def org-defdecode))
  12229. (fmts (if org-display-custom-times
  12230. org-time-stamp-custom-formats
  12231. org-time-stamp-formats))
  12232. (fmt (if (or org-with-time
  12233. (and (boundp 'org-time-was-given) org-time-was-given))
  12234. (cdr fmts)
  12235. (car fmts)))
  12236. (txt (format-time-string fmt (apply #'encode-time f)))
  12237. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12238. (txt (concat "=> " txt)))
  12239. (when (and org-end-time-was-given
  12240. (string-match org-plain-time-of-day-regexp txt))
  12241. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12242. org-end-time-was-given
  12243. (substring txt (match-end 0)))))
  12244. (when org-read-date-analyze-futurep
  12245. (setq txt (concat txt " (=>F)")))
  12246. (setq org-read-date-overlay
  12247. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12248. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12249. (defun org-read-date-analyze (ans def defdecode)
  12250. "Analyze the combined answer of the date prompt."
  12251. ;; FIXME: cleanup and comment
  12252. (let ((org-def def)
  12253. (org-defdecode defdecode)
  12254. (nowdecode (decode-time))
  12255. delta deltan deltaw deltadef year month day
  12256. hour minute second wday pm h2 m2 tl wday1
  12257. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12258. (setq org-read-date-analyze-futurep nil
  12259. org-read-date-analyze-forced-year nil)
  12260. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12261. (setq ans "+0"))
  12262. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12263. (setq ans (replace-match "" t t ans)
  12264. deltan (car delta)
  12265. deltaw (nth 1 delta)
  12266. deltadef (nth 2 delta)))
  12267. ;; Check if there is an iso week date in there. If yes, store the
  12268. ;; info and postpone interpreting it until the rest of the parsing
  12269. ;; is done.
  12270. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12271. (setq iso-year (when (match-end 1)
  12272. (org-small-year-to-year
  12273. (string-to-number (match-string 1 ans))))
  12274. iso-weekday (when (match-end 3)
  12275. (string-to-number (match-string 3 ans)))
  12276. iso-week (string-to-number (match-string 2 ans)))
  12277. (setq ans (replace-match "" t t ans)))
  12278. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12279. (when (string-match
  12280. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12281. (setq year (if (match-end 2)
  12282. (string-to-number (match-string 2 ans))
  12283. (progn (setq kill-year t)
  12284. (string-to-number (format-time-string "%Y"))))
  12285. month (string-to-number (match-string 3 ans))
  12286. day (string-to-number (match-string 4 ans)))
  12287. (setq year (org-small-year-to-year year))
  12288. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12289. t nil ans)))
  12290. ;; Help matching dotted european dates
  12291. (when (string-match
  12292. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12293. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12294. (setq kill-year t)
  12295. (string-to-number (format-time-string "%Y")))
  12296. day (string-to-number (match-string 1 ans))
  12297. month (string-to-number (match-string 2 ans))
  12298. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12299. t nil ans)))
  12300. ;; Help matching american dates, like 5/30 or 5/30/7
  12301. (when (string-match
  12302. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12303. (setq year (if (match-end 4)
  12304. (string-to-number (match-string 4 ans))
  12305. (progn (setq kill-year t)
  12306. (string-to-number (format-time-string "%Y"))))
  12307. month (string-to-number (match-string 1 ans))
  12308. day (string-to-number (match-string 2 ans)))
  12309. (setq year (org-small-year-to-year year))
  12310. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12311. t nil ans)))
  12312. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12313. ;; If there is a time with am/pm, and *no* time without it, we convert
  12314. ;; so that matching will be successful.
  12315. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12316. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12317. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12318. (setq hour (string-to-number (match-string 1 ans))
  12319. minute (if (match-end 3)
  12320. (string-to-number (match-string 3 ans))
  12321. 0)
  12322. pm (equal ?p
  12323. (string-to-char (downcase (match-string 4 ans)))))
  12324. (if (and (= hour 12) (not pm))
  12325. (setq hour 0)
  12326. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12327. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12328. t t ans))))
  12329. ;; Help matching HHhMM times, similarly as for am/pm times.
  12330. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12331. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12332. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12333. (setq hour (if (match-end 1)
  12334. (string-to-number (match-string 1 ans))
  12335. 0)
  12336. minute (if (match-end 2)
  12337. (string-to-number (match-string 2 ans))
  12338. 0))
  12339. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12340. t t ans))))
  12341. ;; Check if a time range is given as a duration
  12342. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12343. (setq hour (string-to-number (match-string 1 ans))
  12344. h2 (+ hour (string-to-number (match-string 3 ans)))
  12345. minute (string-to-number (match-string 2 ans))
  12346. m2 (+ minute (if (match-end 5) (string-to-number
  12347. (match-string 5 ans))0)))
  12348. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12349. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12350. t t ans)))
  12351. ;; Check if there is a time range
  12352. (when (boundp 'org-end-time-was-given)
  12353. (setq org-time-was-given nil)
  12354. (when (and (string-match org-plain-time-of-day-regexp ans)
  12355. (match-end 8))
  12356. (setq org-end-time-was-given (match-string 8 ans))
  12357. (setq ans (concat (substring ans 0 (match-beginning 7))
  12358. (substring ans (match-end 7))))))
  12359. (setq tl (parse-time-string ans)
  12360. day (or (nth 3 tl) (nth 3 org-defdecode))
  12361. month
  12362. (cond ((nth 4 tl))
  12363. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12364. ;; Day was specified. Make sure DAY+MONTH
  12365. ;; combination happens in the future.
  12366. ((nth 3 tl)
  12367. (setq futurep t)
  12368. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12369. (nth 4 nowdecode)))
  12370. (t (nth 4 org-defdecode)))
  12371. year
  12372. (cond ((and (not kill-year) (nth 5 tl)))
  12373. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12374. ;; Month was guessed in the future and is at least
  12375. ;; equal to NOWDECODE's. Fix year accordingly.
  12376. (futurep
  12377. (if (or (> month (nth 4 nowdecode))
  12378. (>= day (nth 3 nowdecode)))
  12379. (nth 5 nowdecode)
  12380. (1+ (nth 5 nowdecode))))
  12381. ;; Month was specified. Make sure MONTH+YEAR
  12382. ;; combination happens in the future.
  12383. ((nth 4 tl)
  12384. (setq futurep t)
  12385. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12386. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12387. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12388. (t (nth 5 nowdecode))))
  12389. (t (nth 5 org-defdecode)))
  12390. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12391. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12392. second (or (nth 0 tl) 0)
  12393. wday (nth 6 tl))
  12394. (when (and (eq org-read-date-prefer-future 'time)
  12395. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12396. (equal day (nth 3 nowdecode))
  12397. (equal month (nth 4 nowdecode))
  12398. (equal year (nth 5 nowdecode))
  12399. (nth 2 tl)
  12400. (or (< (nth 2 tl) (nth 2 nowdecode))
  12401. (and (= (nth 2 tl) (nth 2 nowdecode))
  12402. (nth 1 tl)
  12403. (< (nth 1 tl) (nth 1 nowdecode)))))
  12404. (setq day (1+ day)
  12405. futurep t))
  12406. ;; Special date definitions below
  12407. (cond
  12408. (iso-week
  12409. ;; There was an iso week
  12410. (require 'cal-iso)
  12411. (setq futurep nil)
  12412. (setq year (or iso-year year)
  12413. day (or iso-weekday wday 1)
  12414. wday nil ; to make sure that the trigger below does not match
  12415. iso-date (calendar-gregorian-from-absolute
  12416. (calendar-iso-to-absolute
  12417. (list iso-week day year))))
  12418. ; FIXME: Should we also push ISO weeks into the future?
  12419. ; (when (and org-read-date-prefer-future
  12420. ; (not iso-year)
  12421. ; (< (calendar-absolute-from-gregorian iso-date)
  12422. ; (time-to-days nil)))
  12423. ; (setq year (1+ year)
  12424. ; iso-date (calendar-gregorian-from-absolute
  12425. ; (calendar-iso-to-absolute
  12426. ; (list iso-week day year)))))
  12427. (setq month (car iso-date)
  12428. year (nth 2 iso-date)
  12429. day (nth 1 iso-date)))
  12430. (deltan
  12431. (setq futurep nil)
  12432. (unless deltadef
  12433. (let ((now (decode-time)))
  12434. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12435. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12436. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12437. ((equal deltaw "m") (setq month (+ month deltan)))
  12438. ((equal deltaw "y") (setq year (+ year deltan)))))
  12439. ((and wday (not (nth 3 tl)))
  12440. ;; Weekday was given, but no day, so pick that day in the week
  12441. ;; on or after the derived date.
  12442. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12443. (unless (equal wday wday1)
  12444. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12445. (when (and (boundp 'org-time-was-given)
  12446. (nth 2 tl))
  12447. (setq org-time-was-given t))
  12448. (when (< year 100) (setq year (+ 2000 year)))
  12449. ;; Check of the date is representable
  12450. (if org-read-date-force-compatible-dates
  12451. (progn
  12452. (when (< year 1970)
  12453. (setq year 1970 org-read-date-analyze-forced-year t))
  12454. (when (> year 2037)
  12455. (setq year 2037 org-read-date-analyze-forced-year t)))
  12456. (condition-case nil
  12457. (ignore (encode-time second minute hour day month year))
  12458. (error
  12459. (setq year (nth 5 org-defdecode))
  12460. (setq org-read-date-analyze-forced-year t))))
  12461. (setq org-read-date-analyze-futurep futurep)
  12462. (list second minute hour day month year)))
  12463. (defvar parse-time-weekdays)
  12464. (defun org-read-date-get-relative (s today default)
  12465. "Check string S for special relative date string.
  12466. TODAY and DEFAULT are internal times, for today and for a default.
  12467. Return shift list (N what def-flag)
  12468. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12469. N is the number of WHATs to shift.
  12470. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12471. the DEFAULT date rather than TODAY."
  12472. (require 'parse-time)
  12473. (when (and
  12474. (string-match
  12475. (concat
  12476. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12477. "\\([0-9]+\\)?"
  12478. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12479. "\\([ \t]\\|$\\)") s)
  12480. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12481. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12482. (string-to-char (substring (match-string 1 s) -1))
  12483. ?+))
  12484. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12485. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12486. (what (if (match-end 3) (match-string 3 s) "d"))
  12487. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12488. (date (if rel default today))
  12489. (wday (nth 6 (decode-time date)))
  12490. delta)
  12491. (if wday1
  12492. (progn
  12493. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12494. (when (= delta 0) (setq delta 7))
  12495. (when (= dir ?-)
  12496. (setq delta (- delta 7))
  12497. (when (= delta 0) (setq delta -7)))
  12498. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12499. (list delta "d" rel))
  12500. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12501. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12502. "Turn a user-specified date into the internal representation.
  12503. The internal representation needed by the calendar is (month day year).
  12504. This is a wrapper to handle the brain-dead convention in calendar that
  12505. user function argument order change dependent on argument order."
  12506. (pcase calendar-date-style
  12507. (`american (list arg1 arg2 arg3))
  12508. (`european (list arg2 arg1 arg3))
  12509. (`iso (list arg2 arg3 arg1))))
  12510. (defun org-eval-in-calendar (form &optional keepdate)
  12511. "Eval FORM in the calendar window and return to current window.
  12512. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12513. (let ((sf (selected-frame))
  12514. (sw (selected-window)))
  12515. (select-window (get-buffer-window "*Calendar*" t))
  12516. (eval form t)
  12517. (when (and (not keepdate) (calendar-cursor-to-date))
  12518. (let* ((date (calendar-cursor-to-date))
  12519. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12520. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12521. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12522. (select-window sw)
  12523. (select-frame-set-input-focus sf)))
  12524. (defun org-calendar-select ()
  12525. "Return to `org-read-date' with the date currently selected.
  12526. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12527. (interactive)
  12528. (when (calendar-cursor-to-date)
  12529. (let* ((date (calendar-cursor-to-date))
  12530. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12531. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12532. (when (active-minibuffer-window) (exit-minibuffer))))
  12533. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12534. "Insert a date stamp for the date given by the internal TIME.
  12535. See `format-time-string' for the format of TIME.
  12536. WITH-HM means use the stamp format that includes the time of the day.
  12537. INACTIVE means use square brackets instead of angular ones, so that the
  12538. stamp will not contribute to the agenda.
  12539. PRE and POST are optional strings to be inserted before and after the
  12540. stamp.
  12541. The command returns the inserted time stamp."
  12542. (org-fold-core-ignore-modifications
  12543. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12544. stamp)
  12545. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12546. (insert-before-markers-and-inherit (or pre ""))
  12547. (when (listp extra)
  12548. (setq extra (car extra))
  12549. (if (and (stringp extra)
  12550. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12551. (setq extra (format "-%02d:%02d"
  12552. (string-to-number (match-string 1 extra))
  12553. (string-to-number (match-string 2 extra))))
  12554. (setq extra nil)))
  12555. (when extra
  12556. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12557. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12558. (insert-before-markers-and-inherit (or post ""))
  12559. (setq org-last-inserted-timestamp stamp))))
  12560. (defun org-toggle-time-stamp-overlays ()
  12561. "Toggle the use of custom time stamp formats."
  12562. (interactive)
  12563. (setq org-display-custom-times (not org-display-custom-times))
  12564. (unless org-display-custom-times
  12565. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12566. (while (setq p (next-single-property-change p 'display))
  12567. (when (and (get-text-property p 'display)
  12568. (eq (get-text-property p 'face) 'org-date))
  12569. (remove-text-properties
  12570. p (setq p (next-single-property-change p 'display))
  12571. '(display t))))
  12572. (set-buffer-modified-p bmp)))
  12573. (org-restart-font-lock)
  12574. (setq org-table-may-need-update t)
  12575. (if org-display-custom-times
  12576. (message "Time stamps are overlaid with custom format")
  12577. (message "Time stamp overlays removed")))
  12578. (defun org-display-custom-time (beg end)
  12579. "Overlay modified time stamp format over timestamp between BEG and END."
  12580. (let* ((ts (buffer-substring beg end))
  12581. t1 with-hm tf time str (off 0))
  12582. (save-match-data
  12583. (setq t1 (org-parse-time-string ts t))
  12584. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12585. (setq off (- (match-end 0) (match-beginning 0)))))
  12586. (setq end (- end off))
  12587. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12588. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12589. time (org-fix-decoded-time t1)
  12590. str (org-add-props
  12591. (format-time-string
  12592. (substring tf 1 -1) (apply 'encode-time time))
  12593. nil 'mouse-face 'highlight))
  12594. (put-text-property beg end 'display str)))
  12595. (defun org-fix-decoded-time (time)
  12596. "Set 0 instead of nil for the first 6 elements of time.
  12597. Don't touch the rest."
  12598. (let ((n 0))
  12599. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12600. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12601. "Difference between TIMESTAMP-STRING and now in days.
  12602. If SECONDS is non-nil, return the difference in seconds."
  12603. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12604. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12605. (funcall fdiff nil))))
  12606. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12607. "Is the time in TIMESTAMP-STRING close to the current date?"
  12608. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12609. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12610. (not (org-entry-is-done-p))))
  12611. (defun org-get-wdays (ts &optional delay zero-delay)
  12612. "Get the deadline lead time appropriate for timestring TS.
  12613. When DELAY is non-nil, get the delay time for scheduled items
  12614. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12615. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12616. don't try to find the delay cookie in the scheduled timestamp."
  12617. (let ((tv (if delay org-scheduled-delay-days
  12618. org-deadline-warning-days)))
  12619. (cond
  12620. ((or (and delay (< tv 0))
  12621. (and delay zero-delay (<= tv 0))
  12622. (and (not delay) (<= tv 0)))
  12623. ;; Enforce this value no matter what
  12624. (- tv))
  12625. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12626. ;; lead time is specified.
  12627. (floor (* (string-to-number (match-string 1 ts))
  12628. (cdr (assoc (match-string 2 ts)
  12629. '(("d" . 1) ("w" . 7)
  12630. ("m" . 30.4) ("y" . 365.25)
  12631. ("h" . 0.041667)))))))
  12632. ;; go for the default.
  12633. (t tv))))
  12634. (defun org-calendar-select-mouse (ev)
  12635. "Return to `org-read-date' with the date currently selected.
  12636. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12637. (interactive "e")
  12638. (mouse-set-point ev)
  12639. (when (calendar-cursor-to-date)
  12640. (let* ((date (calendar-cursor-to-date))
  12641. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12642. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12643. (when (active-minibuffer-window) (exit-minibuffer))))
  12644. (defun org-check-deadlines (ndays)
  12645. "Check if there are any deadlines due or past due.
  12646. A deadline is considered due if it happens within `org-deadline-warning-days'
  12647. days from today's date. If the deadline appears in an entry marked DONE,
  12648. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12649. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12650. are shown."
  12651. (interactive "P")
  12652. (let* ((org-warn-days
  12653. (cond
  12654. ((equal ndays '(4)) 100000)
  12655. (ndays (prefix-numeric-value ndays))
  12656. (t (abs org-deadline-warning-days))))
  12657. (case-fold-search nil)
  12658. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12659. (callback
  12660. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12661. (message "%d deadlines past-due or due within %d days"
  12662. (org-occur regexp nil callback)
  12663. org-warn-days)))
  12664. (defsubst org-re-timestamp (type)
  12665. "Return a regexp for timestamp TYPE.
  12666. Allowed values for TYPE are:
  12667. all: all timestamps
  12668. active: only active timestamps (<...>)
  12669. inactive: only inactive timestamps ([...])
  12670. scheduled: only scheduled timestamps
  12671. deadline: only deadline timestamps
  12672. closed: only closed time-stamps
  12673. When TYPE is nil, fall back on returning a regexp that matches
  12674. both scheduled and deadline timestamps."
  12675. (cl-case type
  12676. (all org-ts-regexp-both)
  12677. (active org-ts-regexp)
  12678. (inactive org-ts-regexp-inactive)
  12679. (scheduled org-scheduled-time-regexp)
  12680. (deadline org-deadline-time-regexp)
  12681. (closed org-closed-time-regexp)
  12682. (otherwise
  12683. (concat "\\<"
  12684. (regexp-opt (list org-deadline-string org-scheduled-string))
  12685. " *<\\([^>]+\\)>"))))
  12686. (defun org-check-before-date (d)
  12687. "Check if there are deadlines or scheduled entries before date D."
  12688. (interactive (list (org-read-date)))
  12689. (let* ((case-fold-search nil)
  12690. (regexp (org-re-timestamp org-ts-type))
  12691. (ts-type org-ts-type)
  12692. (callback
  12693. (lambda ()
  12694. (let ((match (match-string 1)))
  12695. (and (if (memq ts-type '(active inactive all))
  12696. (eq (org-element-type (save-excursion
  12697. (backward-char)
  12698. (org-element-context)))
  12699. 'timestamp)
  12700. (org-at-planning-p))
  12701. (time-less-p
  12702. (org-time-string-to-time match)
  12703. (org-time-string-to-time d)))))))
  12704. (message "%d entries before %s"
  12705. (org-occur regexp nil callback)
  12706. d)))
  12707. (defun org-check-after-date (d)
  12708. "Check if there are deadlines or scheduled entries after date D."
  12709. (interactive (list (org-read-date)))
  12710. (let* ((case-fold-search nil)
  12711. (regexp (org-re-timestamp org-ts-type))
  12712. (ts-type org-ts-type)
  12713. (callback
  12714. (lambda ()
  12715. (let ((match (match-string 1)))
  12716. (and (if (memq ts-type '(active inactive all))
  12717. (eq (org-element-type (save-excursion
  12718. (backward-char)
  12719. (org-element-context)))
  12720. 'timestamp)
  12721. (org-at-planning-p))
  12722. (not (time-less-p
  12723. (org-time-string-to-time match)
  12724. (org-time-string-to-time d))))))))
  12725. (message "%d entries after %s"
  12726. (org-occur regexp nil callback)
  12727. d)))
  12728. (defun org-check-dates-range (start-date end-date)
  12729. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12730. (interactive (list (org-read-date nil nil nil "Range starts")
  12731. (org-read-date nil nil nil "Range end")))
  12732. (let ((case-fold-search nil)
  12733. (regexp (org-re-timestamp org-ts-type))
  12734. (callback
  12735. (let ((type org-ts-type))
  12736. (lambda ()
  12737. (let ((match (match-string 1)))
  12738. (and
  12739. (if (memq type '(active inactive all))
  12740. (eq (org-element-type (save-excursion
  12741. (backward-char)
  12742. (org-element-context)))
  12743. 'timestamp)
  12744. (org-at-planning-p))
  12745. (not (time-less-p
  12746. (org-time-string-to-time match)
  12747. (org-time-string-to-time start-date)))
  12748. (time-less-p
  12749. (org-time-string-to-time match)
  12750. (org-time-string-to-time end-date))))))))
  12751. (message "%d entries between %s and %s"
  12752. (org-occur regexp nil callback) start-date end-date)))
  12753. (defun org-evaluate-time-range (&optional to-buffer)
  12754. "Evaluate a time range by computing the difference between start and end.
  12755. Normally the result is just printed in the echo area, but with prefix arg
  12756. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  12757. If the time range is actually in a table, the result is inserted into the
  12758. next column.
  12759. For time difference computation, a year is assumed to be exactly 365
  12760. days in order to avoid rounding problems."
  12761. (interactive "P")
  12762. (or
  12763. (org-clock-update-time-maybe)
  12764. (save-excursion
  12765. (unless (org-at-date-range-p t)
  12766. (goto-char (point-at-bol))
  12767. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  12768. (unless (org-at-date-range-p t)
  12769. (user-error "Not at a time-stamp range, and none found in current line")))
  12770. (let* ((ts1 (match-string 1))
  12771. (ts2 (match-string 2))
  12772. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  12773. (match-end (match-end 0))
  12774. (time1 (org-time-string-to-time ts1))
  12775. (time2 (org-time-string-to-time ts2))
  12776. (diff (abs (float-time (time-subtract time2 time1))))
  12777. (negative (time-less-p time2 time1))
  12778. ;; (ys (floor (* 365 24 60 60)))
  12779. (ds (* 24 60 60))
  12780. (hs (* 60 60))
  12781. (fy "%dy %dd %02d:%02d")
  12782. (fy1 "%dy %dd")
  12783. (fd "%dd %02d:%02d")
  12784. (fd1 "%dd")
  12785. (fh "%02d:%02d")
  12786. y d h m align)
  12787. (if havetime
  12788. (setq ; y (floor diff ys) diff (mod diff ys)
  12789. y 0
  12790. d (floor diff ds) diff (mod diff ds)
  12791. h (floor diff hs) diff (mod diff hs)
  12792. m (floor diff 60))
  12793. (setq ; y (floor diff ys) diff (mod diff ys)
  12794. y 0
  12795. d (round diff ds)
  12796. h 0 m 0))
  12797. (if (not to-buffer)
  12798. (message "%s" (org-make-tdiff-string y d h m))
  12799. (if (org-at-table-p)
  12800. (progn
  12801. (goto-char match-end)
  12802. (setq align t)
  12803. (and (looking-at " *|") (goto-char (match-end 0))))
  12804. (goto-char match-end))
  12805. (when (looking-at
  12806. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  12807. (replace-match ""))
  12808. (when negative (insert " -"))
  12809. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  12810. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  12811. (insert " " (format fh h m))))
  12812. (when align (org-table-align))
  12813. (message "Time difference inserted")))))
  12814. (defun org-make-tdiff-string (y d h m)
  12815. (let ((fmt "")
  12816. (l nil))
  12817. (when (> y 0)
  12818. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  12819. (push y l))
  12820. (when (> d 0)
  12821. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  12822. (push d l))
  12823. (when (> h 0)
  12824. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  12825. (push h l))
  12826. (when (> m 0)
  12827. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  12828. (push m l))
  12829. (apply 'format fmt (nreverse l))))
  12830. (defun org-time-string-to-time (s)
  12831. "Convert timestamp string S into internal time."
  12832. (apply #'encode-time (org-parse-time-string s)))
  12833. (defun org-time-string-to-seconds (s)
  12834. "Convert a timestamp string S into a number of seconds."
  12835. (float-time (org-time-string-to-time s)))
  12836. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  12837. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  12838. "Convert time stamp S to an absolute day number.
  12839. If DAYNR in non-nil, and there is a specifier for a cyclic time
  12840. stamp, get the closest date to DAYNR. If PREFER is
  12841. `past' (respectively `future') return a date past (respectively
  12842. after) or equal to DAYNR.
  12843. POS is the location of time stamp S, as a buffer position in
  12844. BUFFER.
  12845. Diary sexp timestamps are matched against DAYNR, when non-nil.
  12846. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  12847. signaled."
  12848. (cond
  12849. ((string-match "\\`%%\\((.*)\\)" s)
  12850. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  12851. ;; only able to match individual dates. If it fails, raise an
  12852. ;; error.
  12853. (if (and daynr
  12854. (org-diary-sexp-entry
  12855. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  12856. daynr
  12857. (signal 'org-diary-sexp-no-match (list s))))
  12858. (daynr (org-closest-date s daynr prefer))
  12859. (t (time-to-days
  12860. (condition-case errdata
  12861. (org-time-string-to-time s)
  12862. (error (error "Bad timestamp `%s'%s\nError was: %s"
  12863. s
  12864. (if (not (and buffer pos)) ""
  12865. (format-message " at %d in buffer `%s'" pos buffer))
  12866. (cdr errdata))))))))
  12867. (defun org-days-to-iso-week (days)
  12868. "Return the ISO week number."
  12869. (require 'cal-iso)
  12870. (car (calendar-iso-from-absolute days)))
  12871. (defun org-small-year-to-year (year)
  12872. "Convert 2-digit years into 4-digit years.
  12873. YEAR is expanded into one of the 30 next years, if possible, or
  12874. into a past one. Any year larger than 99 is returned unchanged."
  12875. (if (>= year 100) year
  12876. (let* ((current (string-to-number (format-time-string "%Y")))
  12877. (century (/ current 100))
  12878. (offset (- year (% current 100))))
  12879. (cond ((> offset 30) (+ (* (1- century) 100) year))
  12880. ((> offset -70) (+ (* century 100) year))
  12881. (t (+ (* (1+ century) 100) year))))))
  12882. (defun org-time-from-absolute (d)
  12883. "Return the time corresponding to date D.
  12884. D may be an absolute day number, or a calendar-type list (month day year)."
  12885. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  12886. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  12887. (defvar org-agenda-current-date)
  12888. (defun org-calendar-holiday ()
  12889. "List of holidays, for Diary display in Org mode."
  12890. (require 'holidays)
  12891. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  12892. (and hl (mapconcat #'identity hl "; "))))
  12893. (defun org-diary-sexp-entry (sexp entry d)
  12894. "Process a SEXP diary ENTRY for date D."
  12895. (require 'diary-lib)
  12896. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  12897. ;; dynamically.
  12898. (let* ((sexp `(let ((entry ,entry)
  12899. (date ',d))
  12900. ,(car (read-from-string sexp))))
  12901. ;; FIXME: Do not use (eval ... t) in the following sexp as
  12902. ;; diary vars are still using dynamic scope.
  12903. (result (if calendar-debug-sexp (eval sexp)
  12904. (condition-case nil
  12905. (eval sexp)
  12906. (error
  12907. (beep)
  12908. (message "Bad sexp at line %d in %s: %s"
  12909. (org-current-line)
  12910. (buffer-file-name) sexp)
  12911. (sleep-for 2))))))
  12912. (cond ((stringp result) (split-string result "; "))
  12913. ((and (consp result)
  12914. (not (consp (cdr result)))
  12915. (stringp (cdr result))) (cdr result))
  12916. ((and (consp result)
  12917. (stringp (car result))) result)
  12918. (result entry))))
  12919. (defun org-diary-to-ical-string (frombuf)
  12920. "Get iCalendar entries from diary entries in buffer FROMBUF.
  12921. This uses the icalendar.el library."
  12922. (let* ((tmpdir temporary-file-directory)
  12923. (tmpfile (make-temp-name
  12924. (expand-file-name "orgics" tmpdir)))
  12925. buf rtn b e)
  12926. (with-current-buffer frombuf
  12927. (icalendar-export-region (point-min) (point-max) tmpfile)
  12928. (setq buf (find-buffer-visiting tmpfile))
  12929. (set-buffer buf)
  12930. (goto-char (point-min))
  12931. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  12932. (setq b (match-beginning 0)))
  12933. (goto-char (point-max))
  12934. (when (re-search-backward "^END:VEVENT" nil t)
  12935. (setq e (match-end 0)))
  12936. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  12937. (kill-buffer buf)
  12938. (delete-file tmpfile)
  12939. rtn))
  12940. (defun org-closest-date (start current prefer)
  12941. "Return closest date to CURRENT starting from START.
  12942. CURRENT and START are both time stamps.
  12943. When PREFER is `past', return a date that is either CURRENT or
  12944. past. When PREFER is `future', return a date that is either
  12945. CURRENT or future.
  12946. Only time stamps with a repeater are modified. Any other time
  12947. stamp stay unchanged. In any case, return value is an absolute
  12948. day number."
  12949. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  12950. ;; No repeater. Do not shift time stamp.
  12951. (time-to-days (org-time-string-to-time start))
  12952. (let ((value (string-to-number (match-string 1 start)))
  12953. (type (match-string 2 start)))
  12954. (if (= 0 value)
  12955. ;; Repeater with a 0-value is considered as void.
  12956. (time-to-days (org-time-string-to-time start))
  12957. (let* ((base (org-date-to-gregorian start))
  12958. (target (org-date-to-gregorian current))
  12959. (sday (calendar-absolute-from-gregorian base))
  12960. (cday (calendar-absolute-from-gregorian target))
  12961. n1 n2)
  12962. ;; If START is already past CURRENT, just return START.
  12963. (if (<= cday sday) sday
  12964. ;; Compute closest date before (N1) and closest date past
  12965. ;; (N2) CURRENT.
  12966. (pcase type
  12967. ("h"
  12968. (let ((missing-hours
  12969. (mod (+ (- (* 24 (- cday sday))
  12970. (nth 2 (org-parse-time-string start)))
  12971. org-extend-today-until)
  12972. value)))
  12973. (setf n1 (if (= missing-hours 0) cday
  12974. (- cday (1+ (/ missing-hours 24)))))
  12975. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  12976. ((or "d" "w")
  12977. (let ((value (if (equal type "w") (* 7 value) value)))
  12978. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  12979. (setf n2 (+ n1 value))))
  12980. ("m"
  12981. (let* ((add-months
  12982. (lambda (d n)
  12983. ;; Add N months to gregorian date D, i.e.,
  12984. ;; a list (MONTH DAY YEAR). Return a valid
  12985. ;; gregorian date.
  12986. (let ((m (+ (nth 0 d) n)))
  12987. (list (mod m 12)
  12988. (nth 1 d)
  12989. (+ (/ m 12) (nth 2 d))))))
  12990. (months ; Complete months to TARGET.
  12991. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  12992. (- (nth 0 target) (nth 0 base))
  12993. ;; If START's day is greater than
  12994. ;; TARGET's, remove incomplete month.
  12995. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  12996. value)
  12997. value))
  12998. (before (funcall add-months base months)))
  12999. (setf n1 (calendar-absolute-from-gregorian before))
  13000. (setf n2
  13001. (calendar-absolute-from-gregorian
  13002. (funcall add-months before value)))))
  13003. (_
  13004. (let* ((d (nth 1 base))
  13005. (m (nth 0 base))
  13006. (y (nth 2 base))
  13007. (years ; Complete years to TARGET.
  13008. (* (/ (- (nth 2 target)
  13009. y
  13010. ;; If START's month and day are
  13011. ;; greater than TARGET's, remove
  13012. ;; incomplete year.
  13013. (if (or (> (nth 0 target) m)
  13014. (and (= (nth 0 target) m)
  13015. (> (nth 1 target) d)))
  13016. 0
  13017. 1))
  13018. value)
  13019. value))
  13020. (before (list m d (+ y years))))
  13021. (setf n1 (calendar-absolute-from-gregorian before))
  13022. (setf n2 (calendar-absolute-from-gregorian
  13023. (list m d (+ (nth 2 before) value)))))))
  13024. ;; Handle PREFER parameter, if any.
  13025. (cond
  13026. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13027. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13028. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13029. (defun org-date-to-gregorian (d)
  13030. "Turn any specification of date D into a Gregorian date for the calendar."
  13031. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13032. ((and (listp d) (= (length d) 3)) d)
  13033. ((stringp d)
  13034. (let ((d (org-parse-time-string d)))
  13035. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13036. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13037. (defun org-timestamp-up (&optional arg)
  13038. "Increase the date item at the cursor by one.
  13039. If the cursor is on the year, change the year. If it is on the month,
  13040. the day or the time, change that. If the cursor is on the enclosing
  13041. bracket, change the timestamp type.
  13042. With prefix ARG, change by that many units."
  13043. (interactive "p")
  13044. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13045. (defun org-timestamp-down (&optional arg)
  13046. "Decrease the date item at the cursor by one.
  13047. If the cursor is on the year, change the year. If it is on the month,
  13048. the day or the time, change that. If the cursor is on the enclosing
  13049. bracket, change the timestamp type.
  13050. With prefix ARG, change by that many units."
  13051. (interactive "p")
  13052. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13053. (defun org-timestamp-up-day (&optional arg)
  13054. "Increase the date in the time stamp by one day.
  13055. With prefix ARG, change that many days."
  13056. (interactive "p")
  13057. (if (and (not (org-at-timestamp-p 'lax))
  13058. (org-at-heading-p))
  13059. (org-todo 'up)
  13060. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13061. (defun org-timestamp-down-day (&optional arg)
  13062. "Decrease the date in the time stamp by one day.
  13063. With prefix ARG, change that many days."
  13064. (interactive "p")
  13065. (if (and (not (org-at-timestamp-p 'lax))
  13066. (org-at-heading-p))
  13067. (org-todo 'down)
  13068. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13069. (defun org-at-timestamp-p (&optional extended)
  13070. "Non-nil if point is inside a timestamp.
  13071. By default, the function only consider syntactically valid active
  13072. timestamps. However, the caller may have a broader definition
  13073. for timestamps. As a consequence, optional argument EXTENDED can
  13074. be set to the following values
  13075. `inactive'
  13076. Include also syntactically valid inactive timestamps.
  13077. `agenda'
  13078. Include timestamps allowed in Agenda, i.e., those in
  13079. properties drawers, planning lines and clock lines.
  13080. `lax'
  13081. Ignore context. The function matches any part of the
  13082. document looking like a timestamp. This includes comments,
  13083. example blocks...
  13084. For backward-compatibility with Org 9.0, every other non-nil
  13085. value is equivalent to `inactive'.
  13086. When at a timestamp, return the position of the point as a symbol
  13087. among `bracket', `after', `year', `month', `hour', `minute',
  13088. `day' or a number of character from the last know part of the
  13089. time stamp. If diary sexp timestamps, any point inside the timestamp
  13090. is considered `day' (i.e. only `bracket', `day', and `after' return
  13091. values are possible).
  13092. When matching, the match groups are the following:
  13093. group 1: year, if any
  13094. group 2: month, if any
  13095. group 3: day number, if any
  13096. group 4: day name, if any
  13097. group 5: hours, if any
  13098. group 6: minutes, if any"
  13099. (let* ((regexp
  13100. (if extended
  13101. (if (eq extended 'agenda)
  13102. (rx-to-string
  13103. `(or (regexp ,org-ts-regexp3)
  13104. (regexp ,org-element--timestamp-regexp)))
  13105. org-ts-regexp3)
  13106. org-ts-regexp2))
  13107. (pos (point))
  13108. (match?
  13109. (let ((boundaries (org-in-regexp regexp)))
  13110. (save-match-data
  13111. (cond ((null boundaries) nil)
  13112. ((eq extended 'lax) t)
  13113. (t
  13114. (or (and (eq extended 'agenda)
  13115. (or (org-at-planning-p)
  13116. (org-at-property-p)
  13117. (and (bound-and-true-p
  13118. org-agenda-include-inactive-timestamps)
  13119. (org-at-clock-log-p))))
  13120. (eq 'timestamp
  13121. (save-excursion
  13122. (when (= pos (cdr boundaries)) (forward-char -1))
  13123. (org-element-type (org-element-context)))))))))))
  13124. (cond
  13125. ((not match?) nil)
  13126. ((= pos (match-beginning 0)) 'bracket)
  13127. ;; Distinguish location right before the closing bracket from
  13128. ;; right after it.
  13129. ((= pos (1- (match-end 0))) 'bracket)
  13130. ((= pos (match-end 0)) 'after)
  13131. ((org-pos-in-match-range pos 2) 'year)
  13132. ((org-pos-in-match-range pos 3) 'month)
  13133. ((org-pos-in-match-range pos 7) 'hour)
  13134. ((org-pos-in-match-range pos 8) 'minute)
  13135. ((or (org-pos-in-match-range pos 4)
  13136. (org-pos-in-match-range pos 5)) 'day)
  13137. ((and (or (match-end 8) (match-end 5))
  13138. (> pos (or (match-end 8) (match-end 5)))
  13139. (< pos (match-end 0)))
  13140. (- pos (or (match-end 8) (match-end 5))))
  13141. (t 'day))))
  13142. (defun org-toggle-timestamp-type ()
  13143. "Toggle the type (<active> or [inactive]) of a time stamp."
  13144. (interactive)
  13145. (when (org-at-timestamp-p 'lax)
  13146. (let ((beg (match-beginning 0)) (end (match-end 0))
  13147. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13148. (save-excursion
  13149. (goto-char beg)
  13150. (while (re-search-forward "[][<>]" end t)
  13151. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13152. t t)))
  13153. (message "Timestamp is now %sactive"
  13154. (if (equal (char-after beg) ?<) "" "in")))))
  13155. (defun org-at-clock-log-p ()
  13156. "Non-nil if point is on a clock log line."
  13157. (and (org-match-line org-clock-line-re)
  13158. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13159. (defvar org-clock-history) ; defined in org-clock.el
  13160. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13161. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13162. "Change the date in the time stamp at point.
  13163. The date is changed by N times WHAT. WHAT can be `day', `month',
  13164. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13165. position in the timestamp determines what is changed.
  13166. When optional argument UPDOWN is non-nil, minutes are rounded
  13167. according to `org-time-stamp-rounding-minutes'.
  13168. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13169. \"--2d\"."
  13170. (let ((origin (point))
  13171. (timestamp? (org-at-timestamp-p 'lax))
  13172. origin-cat
  13173. with-hm inactive
  13174. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13175. extra rem
  13176. ts time time0 fixnext clrgx)
  13177. (unless timestamp? (user-error "Not at a timestamp"))
  13178. (if (and (not what) (eq timestamp? 'bracket))
  13179. (org-toggle-timestamp-type)
  13180. ;; Point isn't on brackets. Remember the part of the time-stamp
  13181. ;; the point was in. Indeed, size of time-stamps may change,
  13182. ;; but point must be kept in the same category nonetheless.
  13183. (setq origin-cat timestamp?)
  13184. (when (and (not what) (not (eq timestamp? 'day))
  13185. org-display-custom-times
  13186. (get-text-property (point) 'display)
  13187. (not (get-text-property (1- (point)) 'display)))
  13188. (setq timestamp? 'day))
  13189. (setq timestamp? (or what timestamp?)
  13190. inactive (= (char-after (match-beginning 0)) ?\[)
  13191. ts (match-string 0))
  13192. (replace-match "")
  13193. (when (string-match
  13194. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13195. ts)
  13196. (setq extra (match-string 1 ts))
  13197. (when suppress-tmp-delay
  13198. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13199. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13200. (setq with-hm t))
  13201. (setq time0 (org-parse-time-string ts))
  13202. (when (and updown
  13203. (eq timestamp? 'minute)
  13204. (not current-prefix-arg))
  13205. ;; This looks like s-up and s-down. Change by one rounding step.
  13206. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13207. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13208. (setcar (cdr time0) (+ (nth 1 time0)
  13209. (if (> n 0) (- rem) (- dm rem))))))
  13210. (setq time
  13211. (apply #'encode-time
  13212. (or (car time0) 0)
  13213. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13214. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13215. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13216. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13217. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13218. (nthcdr 6 time0)))
  13219. (when (and (memq timestamp? '(hour minute))
  13220. extra
  13221. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13222. (setq extra (org-modify-ts-extra
  13223. extra
  13224. (if (eq timestamp? 'hour) 2 5)
  13225. n dm)))
  13226. (when (integerp timestamp?)
  13227. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13228. (when (eq what 'calendar)
  13229. (let ((cal-date (org-get-date-from-calendar)))
  13230. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13231. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13232. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13233. (setcar time0 (or (car time0) 0))
  13234. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13235. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13236. (setq time (apply 'encode-time time0))))
  13237. ;; Insert the new time-stamp, and ensure point stays in the same
  13238. ;; category as before (i.e. not after the last position in that
  13239. ;; category).
  13240. (let ((pos (point)))
  13241. ;; Stay before inserted string. `save-excursion' is of no use.
  13242. (setq org-last-changed-timestamp
  13243. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13244. (goto-char pos))
  13245. (save-match-data
  13246. (looking-at org-ts-regexp3)
  13247. (goto-char
  13248. (pcase origin-cat
  13249. ;; `day' category ends before `hour' if any, or at the end
  13250. ;; of the day name.
  13251. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13252. (`hour (min (match-end 7) origin))
  13253. (`minute (min (1- (match-end 8)) origin))
  13254. ((pred integerp) (min (1- (match-end 0)) origin))
  13255. ;; Point was right after the time-stamp. However, the
  13256. ;; time-stamp length might have changed, so refer to
  13257. ;; (match-end 0) instead.
  13258. (`after (match-end 0))
  13259. ;; `year' and `month' have both fixed size: point couldn't
  13260. ;; have moved into another part.
  13261. (_ origin))))
  13262. ;; Update clock if on a CLOCK line.
  13263. (org-clock-update-time-maybe)
  13264. ;; Maybe adjust the closest clock in `org-clock-history'
  13265. (when org-clock-adjust-closest
  13266. (if (not (and (org-at-clock-log-p)
  13267. (< 1 (length (delq nil (mapcar 'marker-position
  13268. org-clock-history))))))
  13269. (message "No clock to adjust")
  13270. (cond ((save-excursion ; fix previous clock?
  13271. (re-search-backward org-ts-regexp0 nil t)
  13272. (looking-back (concat org-clock-string " \\[")
  13273. (line-beginning-position)))
  13274. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13275. ((save-excursion ; fix next clock?
  13276. (re-search-backward org-ts-regexp0 nil t)
  13277. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13278. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13279. (save-window-excursion
  13280. ;; Find closest clock to point, adjust the previous/next one in history
  13281. (let* ((p (save-excursion (org-back-to-heading t)))
  13282. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13283. (clfixnth
  13284. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13285. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13286. (if (not clfixpos)
  13287. (message "No clock to adjust")
  13288. (save-excursion
  13289. (org-goto-marker-or-bmk clfixpos)
  13290. (org-fold-show-subtree)
  13291. (when (re-search-forward clrgx nil t)
  13292. (goto-char (match-beginning 1))
  13293. (let (org-clock-adjust-closest)
  13294. (org-timestamp-change n timestamp? updown))
  13295. (message "Clock adjusted in %s for heading: %s"
  13296. (file-name-nondirectory (buffer-file-name))
  13297. (org-get-heading t t)))))))))
  13298. ;; Try to recenter the calendar window, if any.
  13299. (when (and org-calendar-follow-timestamp-change
  13300. (get-buffer-window "*Calendar*" t)
  13301. (memq timestamp? '(day month year)))
  13302. (org-recenter-calendar (time-to-days time))))))
  13303. (defun org-modify-ts-extra (s pos n dm)
  13304. "Change the different parts of the lead-time and repeat fields in timestamp."
  13305. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13306. ng h m new rem)
  13307. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13308. (cond
  13309. ((or (org-pos-in-match-range pos 2)
  13310. (org-pos-in-match-range pos 3))
  13311. (setq m (string-to-number (match-string 3 s))
  13312. h (string-to-number (match-string 2 s)))
  13313. (if (org-pos-in-match-range pos 2)
  13314. (setq h (+ h n))
  13315. (setq n (* dm (with-no-warnings (cl-signum n))))
  13316. (unless (= 0 (setq rem (% m dm)))
  13317. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13318. (setq m (+ m n)))
  13319. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13320. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13321. (setq h (mod h 24))
  13322. (setq ng 1 new (format "-%02d:%02d" h m)))
  13323. ((org-pos-in-match-range pos 6)
  13324. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13325. ((org-pos-in-match-range pos 5)
  13326. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13327. ((org-pos-in-match-range pos 9)
  13328. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13329. ((org-pos-in-match-range pos 8)
  13330. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13331. (when ng
  13332. (setq s (concat
  13333. (substring s 0 (match-beginning ng))
  13334. new
  13335. (substring s (match-end ng))))))
  13336. s))
  13337. (defun org-recenter-calendar (d)
  13338. "If the calendar is visible, recenter it to date D."
  13339. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13340. (when cwin
  13341. (let ((calendar-move-hook nil))
  13342. (with-selected-window cwin
  13343. (calendar-goto-date
  13344. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13345. (defun org-goto-calendar (&optional arg)
  13346. "Go to the Emacs calendar at the current date.
  13347. If there is a time stamp in the current line, go to that date.
  13348. A prefix ARG can be used to force the current date."
  13349. (interactive "P")
  13350. (let ((calendar-move-hook nil)
  13351. (calendar-view-holidays-initially-flag nil)
  13352. (calendar-view-diary-initially-flag nil)
  13353. diff)
  13354. (when (or (org-at-timestamp-p 'lax)
  13355. (org-match-line (concat ".*" org-ts-regexp)))
  13356. (let ((d1 (time-to-days nil))
  13357. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13358. (setq diff (- d2 d1))))
  13359. (calendar)
  13360. (calendar-goto-today)
  13361. (when (and diff (not arg)) (calendar-forward-day diff))))
  13362. (defun org-get-date-from-calendar ()
  13363. "Return a list (month day year) of date at point in calendar."
  13364. (with-current-buffer "*Calendar*"
  13365. (save-match-data
  13366. (calendar-cursor-to-date))))
  13367. (defun org-date-from-calendar ()
  13368. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13369. If there is already a time stamp at the cursor position, update it."
  13370. (interactive)
  13371. (if (org-at-timestamp-p 'lax)
  13372. (org-timestamp-change 0 'calendar)
  13373. (let ((cal-date (org-get-date-from-calendar)))
  13374. (org-insert-time-stamp
  13375. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13376. (defcustom org-image-actual-width t
  13377. "When non-nil, use the actual width of images when inlining them.
  13378. When set to a number, use imagemagick (when available) to set the
  13379. image's width to this value.
  13380. When set to a number in a list, try to get the width from any
  13381. #+ATTR.* keyword if it matches a width specification like
  13382. #+ATTR_HTML: :width 300px
  13383. and fall back on that number if none is found.
  13384. When set to nil, try to get the width from an #+ATTR.* keyword
  13385. and fall back on the original width if none is found.
  13386. When set to any other non-nil value, always use the image width.
  13387. This requires Emacs >= 24.1, built with imagemagick support."
  13388. :group 'org-appearance
  13389. :version "24.4"
  13390. :package-version '(Org . "8.0")
  13391. :type '(choice
  13392. (const :tag "Use the image width" t)
  13393. (integer :tag "Use a number of pixels")
  13394. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13395. (const :tag "Use #+ATTR* or don't resize" nil)))
  13396. (defcustom org-agenda-inhibit-startup nil
  13397. "Inhibit startup when preparing agenda buffers.
  13398. When this variable is t, the initialization of the Org agenda
  13399. buffers is inhibited: e.g. the visibility state is not set, the
  13400. tables are not re-aligned, etc."
  13401. :type 'boolean
  13402. :version "24.3"
  13403. :group 'org-agenda)
  13404. (defcustom org-agenda-ignore-properties nil
  13405. "Avoid updating text properties when building the agenda.
  13406. Properties are used to prepare buffers for effort estimates,
  13407. appointments, statistics and subtree-local categories.
  13408. If you don't use these in the agenda, you can add them to this
  13409. list and agenda building will be a bit faster.
  13410. The value is a list, with zero or more of the symbols `effort', `appt',
  13411. `stats' or `category'."
  13412. :type '(set :greedy t
  13413. (const effort)
  13414. (const appt)
  13415. (const stats)
  13416. (const category))
  13417. :version "26.1"
  13418. :package-version '(Org . "8.3")
  13419. :group 'org-agenda)
  13420. ;;;; Files
  13421. (defun org-save-all-org-buffers ()
  13422. "Save all Org buffers without user confirmation."
  13423. (interactive)
  13424. (message "Saving all Org buffers...")
  13425. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13426. (when (featurep 'org-id) (org-id-locations-save))
  13427. (message "Saving all Org buffers... done"))
  13428. (defun org-revert-all-org-buffers ()
  13429. "Revert all Org buffers.
  13430. Prompt for confirmation when there are unsaved changes.
  13431. Be sure you know what you are doing before letting this function
  13432. overwrite your changes.
  13433. This function is useful in a setup where one tracks Org files
  13434. with a version control system, to revert on one machine after pulling
  13435. changes from another. I believe the procedure must be like this:
  13436. 1. \\[org-save-all-org-buffers]
  13437. 2. Pull changes from the other machine, resolve conflicts
  13438. 3. \\[org-revert-all-org-buffers]"
  13439. (interactive)
  13440. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13441. (user-error "Abort"))
  13442. (save-excursion
  13443. (save-window-excursion
  13444. (dolist (b (buffer-list))
  13445. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13446. (with-current-buffer b buffer-file-name))
  13447. (pop-to-buffer-same-window b)
  13448. (revert-buffer t 'no-confirm)))
  13449. (when (and (featurep 'org-id) org-id-track-globally)
  13450. (org-id-locations-load)))))
  13451. ;;;; Agenda files
  13452. ;;;###autoload
  13453. (defun org-switchb (&optional arg)
  13454. "Switch between Org buffers.
  13455. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13456. With `\\[universal-argument] \\[universal-argument]' \
  13457. prefix, restrict available buffers to agenda files."
  13458. (interactive "P")
  13459. (let ((blist (org-buffer-list
  13460. (cond ((equal arg '(4)) 'files)
  13461. ((equal arg '(16)) 'agenda)))))
  13462. (pop-to-buffer-same-window
  13463. (completing-read "Org buffer: "
  13464. (mapcar #'list (mapcar #'buffer-name blist))
  13465. nil t))))
  13466. (defun org-agenda-files (&optional unrestricted archives)
  13467. "Get the list of agenda files.
  13468. Optional UNRESTRICTED means return the full list even if a restriction
  13469. is currently in place.
  13470. When ARCHIVES is t, include all archive files that are really being
  13471. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13472. `org-agenda-archives-mode' is t."
  13473. (let ((files
  13474. (cond
  13475. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13476. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13477. ((listp org-agenda-files) org-agenda-files)
  13478. (t (error "Invalid value of `org-agenda-files'")))))
  13479. (setq files (apply 'append
  13480. (mapcar (lambda (f)
  13481. (if (file-directory-p f)
  13482. (directory-files
  13483. f t org-agenda-file-regexp)
  13484. (list (expand-file-name f org-directory))))
  13485. files)))
  13486. (when org-agenda-skip-unavailable-files
  13487. (setq files (delq nil
  13488. (mapcar (lambda (file)
  13489. (and (file-readable-p file) file))
  13490. files))))
  13491. (when (or (eq archives t)
  13492. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13493. (setq files (org-add-archive-files files)))
  13494. files))
  13495. (defun org-agenda-file-p (&optional file)
  13496. "Return non-nil, if FILE is an agenda file.
  13497. If FILE is omitted, use the file associated with the current
  13498. buffer."
  13499. (let ((fname (or file (buffer-file-name))))
  13500. (and fname
  13501. (member (file-truename fname)
  13502. (mapcar #'file-truename (org-agenda-files t))))))
  13503. (defun org-edit-agenda-file-list ()
  13504. "Edit the list of agenda files.
  13505. Depending on setup, this either uses customize to edit the variable
  13506. `org-agenda-files', or it visits the file that is holding the list. In the
  13507. latter case, the buffer is set up in a way that saving it automatically kills
  13508. the buffer and restores the previous window configuration."
  13509. (interactive)
  13510. (if (stringp org-agenda-files)
  13511. (let ((cw (current-window-configuration)))
  13512. (find-file org-agenda-files)
  13513. (setq-local org-window-configuration cw)
  13514. (add-hook 'after-save-hook
  13515. (lambda ()
  13516. (set-window-configuration
  13517. (prog1 org-window-configuration
  13518. (kill-buffer (current-buffer))))
  13519. (org-install-agenda-files-menu)
  13520. (message "New agenda file list installed"))
  13521. nil 'local)
  13522. (message "%s" (substitute-command-keys
  13523. "Edit list and finish with \\[save-buffer]")))
  13524. (customize-variable 'org-agenda-files)))
  13525. (defun org-store-new-agenda-file-list (list)
  13526. "Set new value for the agenda file list and save it correctly."
  13527. (if (stringp org-agenda-files)
  13528. (let ((fe (org-read-agenda-file-list t)) b u)
  13529. (while (setq b (find-buffer-visiting org-agenda-files))
  13530. (kill-buffer b))
  13531. (with-temp-file org-agenda-files
  13532. (insert
  13533. (mapconcat
  13534. (lambda (f) ;; Keep un-expanded entries.
  13535. (if (setq u (assoc f fe))
  13536. (cdr u)
  13537. f))
  13538. list "\n")
  13539. "\n")))
  13540. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13541. (org-insert-mode-line-in-empty-file nil))
  13542. (setq org-agenda-files list)
  13543. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13544. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13545. "Read the list of agenda files from a file.
  13546. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13547. filenames, used by `org-store-new-agenda-file-list' to write back
  13548. un-expanded file names."
  13549. (when (file-directory-p org-agenda-files)
  13550. (error "`org-agenda-files' cannot be a single directory"))
  13551. (when (stringp org-agenda-files)
  13552. (with-temp-buffer
  13553. (insert-file-contents org-agenda-files)
  13554. (mapcar
  13555. (lambda (f)
  13556. (let ((e (expand-file-name (substitute-in-file-name f)
  13557. org-directory)))
  13558. (if pair-with-expansion
  13559. (cons e f)
  13560. e)))
  13561. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13562. ;;;###autoload
  13563. (defun org-cycle-agenda-files ()
  13564. "Cycle through the files in `org-agenda-files'.
  13565. If the current buffer visits an agenda file, find the next one in the list.
  13566. If the current buffer does not, find the first agenda file."
  13567. (interactive)
  13568. (let* ((fs (or (org-agenda-files t)
  13569. (user-error "No agenda files")))
  13570. (files (copy-sequence fs))
  13571. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13572. file)
  13573. (when tcf
  13574. (while (and (setq file (pop files))
  13575. (not (equal (file-truename file) tcf)))))
  13576. (find-file (car (or files fs)))
  13577. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13578. (defun org-agenda-file-to-front (&optional to-end)
  13579. "Move/add the current file to the top of the agenda file list.
  13580. If the file is not present in the list, it is added to the front. If it is
  13581. present, it is moved there. With optional argument TO-END, add/move to the
  13582. end of the list."
  13583. (interactive "P")
  13584. (let ((org-agenda-skip-unavailable-files nil)
  13585. (file-alist (mapcar (lambda (x)
  13586. (cons (file-truename x) x))
  13587. (org-agenda-files t)))
  13588. (ctf (file-truename
  13589. (or buffer-file-name
  13590. (user-error "Please save the current buffer to a file"))))
  13591. x had)
  13592. (setq x (assoc ctf file-alist) had x)
  13593. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13594. (if to-end
  13595. (setq file-alist (append (delq x file-alist) (list x)))
  13596. (setq file-alist (cons x (delq x file-alist))))
  13597. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13598. (org-install-agenda-files-menu)
  13599. (message "File %s to %s of agenda file list"
  13600. (if had "moved" "added") (if to-end "end" "front"))))
  13601. (defun org-remove-file (&optional file)
  13602. "Remove current file from the list of files in variable `org-agenda-files'.
  13603. These are the files which are being checked for agenda entries.
  13604. Optional argument FILE means use this file instead of the current."
  13605. (interactive)
  13606. (let* ((org-agenda-skip-unavailable-files nil)
  13607. (file (or file buffer-file-name
  13608. (user-error "Current buffer does not visit a file")))
  13609. (true-file (file-truename file))
  13610. (afile (abbreviate-file-name file))
  13611. (files (delq nil (mapcar
  13612. (lambda (x)
  13613. (unless (equal true-file
  13614. (file-truename x))
  13615. x))
  13616. (org-agenda-files t)))))
  13617. (if (not (= (length files) (length (org-agenda-files t))))
  13618. (progn
  13619. (org-store-new-agenda-file-list files)
  13620. (org-install-agenda-files-menu)
  13621. (message "Removed from Org Agenda list: %s" afile))
  13622. (message "File was not in list: %s (not removed)" afile))))
  13623. (defun org-file-menu-entry (file)
  13624. (vector file (list 'find-file file) t))
  13625. (defun org-check-agenda-file (file)
  13626. "Make sure FILE exists. If not, ask user what to do."
  13627. (unless (file-exists-p file)
  13628. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13629. (abbreviate-file-name file))
  13630. (let ((r (downcase (read-char-exclusive))))
  13631. (cond
  13632. ((equal r ?r)
  13633. (org-remove-file file)
  13634. (throw 'nextfile t))
  13635. (t (user-error "Abort"))))))
  13636. (defun org-get-agenda-file-buffer (file)
  13637. "Get an agenda buffer visiting FILE.
  13638. If the buffer needs to be created, add it to the list of buffers
  13639. which might be released later."
  13640. (let ((buf (org-find-base-buffer-visiting file)))
  13641. (if buf
  13642. buf ; just return it
  13643. ;; Make a new buffer and remember it
  13644. (setq buf (find-file-noselect file))
  13645. (when buf (push buf org-agenda-new-buffers))
  13646. buf)))
  13647. (defun org-release-buffers (blist)
  13648. "Release all buffers in list, asking the user for confirmation when needed.
  13649. When a buffer is unmodified, it is just killed. When modified, it is saved
  13650. \(if the user agrees) and then killed."
  13651. (let (file)
  13652. (dolist (buf blist)
  13653. (setq file (buffer-file-name buf))
  13654. (when (and (buffer-modified-p buf)
  13655. file
  13656. (y-or-n-p (format "Save file %s? " file)))
  13657. (with-current-buffer buf (save-buffer)))
  13658. (kill-buffer buf))))
  13659. (defun org-agenda-prepare-buffers (files)
  13660. "Create buffers for all agenda files, protect archived trees and comments."
  13661. (interactive)
  13662. (let ((inhibit-read-only t)
  13663. (org-inhibit-startup org-agenda-inhibit-startup)
  13664. pos)
  13665. (setq org-tag-alist-for-agenda nil
  13666. org-tag-groups-alist-for-agenda nil)
  13667. (save-excursion
  13668. (save-restriction
  13669. (dolist (file files)
  13670. (catch 'nextfile
  13671. (if (bufferp file)
  13672. (set-buffer file)
  13673. (org-check-agenda-file file)
  13674. (set-buffer (org-get-agenda-file-buffer file)))
  13675. (widen)
  13676. (org-set-regexps-and-options 'tags-only)
  13677. (setq pos (point))
  13678. (or (memq 'category org-agenda-ignore-properties)
  13679. (org-refresh-category-properties))
  13680. (or (memq 'stats org-agenda-ignore-properties)
  13681. (org-refresh-stats-properties))
  13682. (or (memq 'effort org-agenda-ignore-properties)
  13683. (unless org-element-use-cache
  13684. (org-refresh-effort-properties)))
  13685. (or (memq 'appt org-agenda-ignore-properties)
  13686. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13687. (setq org-todo-keywords-for-agenda
  13688. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  13689. (setq org-done-keywords-for-agenda
  13690. (append org-done-keywords-for-agenda org-done-keywords))
  13691. (setq org-todo-keyword-alist-for-agenda
  13692. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  13693. (setq org-tag-alist-for-agenda
  13694. (org--tag-add-to-alist
  13695. org-tag-alist-for-agenda
  13696. org-current-tag-alist))
  13697. ;; Merge current file's tag groups into global
  13698. ;; `org-tag-groups-alist-for-agenda'.
  13699. (when org-group-tags
  13700. (dolist (alist org-tag-groups-alist)
  13701. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13702. (if old
  13703. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13704. (push alist org-tag-groups-alist-for-agenda)))))
  13705. (goto-char pos)))))
  13706. (setq org-todo-keywords-for-agenda
  13707. (org-uniquify org-todo-keywords-for-agenda))
  13708. (setq org-todo-keyword-alist-for-agenda
  13709. (org-uniquify org-todo-keyword-alist-for-agenda))))
  13710. ;;;; CDLaTeX minor mode
  13711. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13712. "Keymap for the minor `org-cdlatex-mode'.")
  13713. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13714. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13715. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13716. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13717. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13718. (defvar org-cdlatex-texmathp-advice-is-done nil
  13719. "Flag remembering if we have applied the advice to texmathp already.")
  13720. (define-minor-mode org-cdlatex-mode
  13721. "Toggle the minor `org-cdlatex-mode'.
  13722. This mode supports entering LaTeX environment and math in LaTeX fragments
  13723. in Org mode.
  13724. \\{org-cdlatex-mode-map}"
  13725. :lighter " OCDL"
  13726. (when org-cdlatex-mode
  13727. (require 'cdlatex)
  13728. (run-hooks 'cdlatex-mode-hook)
  13729. (cdlatex-compute-tables))
  13730. (unless org-cdlatex-texmathp-advice-is-done
  13731. (setq org-cdlatex-texmathp-advice-is-done t)
  13732. (advice-add 'texmathp :around #'org--math-always-on)))
  13733. (defun org--math-always-on (orig-fun &rest args)
  13734. "Always return t in Org buffers.
  13735. This is because we want to insert math symbols without dollars even outside
  13736. the LaTeX math segments. If Org mode thinks that point is actually inside
  13737. an embedded LaTeX fragment, let `texmathp' do its job.
  13738. `\\[org-cdlatex-mode-map]'"
  13739. (interactive)
  13740. (cond
  13741. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  13742. ((eq this-command 'cdlatex-math-symbol)
  13743. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  13744. t)
  13745. (t
  13746. (let ((p (org-inside-LaTeX-fragment-p)))
  13747. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  13748. (if (member (car p)
  13749. (plist-get org-format-latex-options :matchers))
  13750. (progn
  13751. (setq texmathp-why '("Org mode embedded math" . 0))
  13752. t)
  13753. (apply orig-fun args)))))))
  13754. (defun turn-on-org-cdlatex ()
  13755. "Unconditionally turn on `org-cdlatex-mode'."
  13756. (org-cdlatex-mode 1))
  13757. (defun org-try-cdlatex-tab ()
  13758. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  13759. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  13760. - inside a LaTeX fragment, or
  13761. - after the first word in a line, where an abbreviation expansion could
  13762. insert a LaTeX environment."
  13763. (when org-cdlatex-mode
  13764. (cond
  13765. ;; Before any word on the line: No expansion possible.
  13766. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  13767. ;; Just after first word on the line: Expand it. Make sure it
  13768. ;; cannot happen on headlines, though.
  13769. ((save-excursion
  13770. (skip-chars-backward "a-zA-Z0-9*")
  13771. (skip-chars-backward " \t")
  13772. (and (bolp) (not (org-at-heading-p))))
  13773. (cdlatex-tab) t)
  13774. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  13775. (defun org-cdlatex-underscore-caret (&optional _arg)
  13776. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  13777. Revert to the normal definition outside of these fragments."
  13778. (interactive "P")
  13779. (if (org-inside-LaTeX-fragment-p)
  13780. (call-interactively 'cdlatex-sub-superscript)
  13781. (let (org-cdlatex-mode)
  13782. (call-interactively (key-binding (vector last-input-event))))))
  13783. (defun org-cdlatex-math-modify (&optional _arg)
  13784. "Execute `cdlatex-math-modify' in LaTeX fragments.
  13785. Revert to the normal definition outside of these fragments."
  13786. (interactive "P")
  13787. (if (org-inside-LaTeX-fragment-p)
  13788. (call-interactively 'cdlatex-math-modify)
  13789. (let (org-cdlatex-mode)
  13790. (call-interactively (key-binding (vector last-input-event))))))
  13791. (defun org-cdlatex-environment-indent (&optional environment item)
  13792. "Execute `cdlatex-environment' and indent the inserted environment.
  13793. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  13794. The inserted environment is indented to current indentation
  13795. unless point is at the beginning of the line, in which the
  13796. environment remains unintended."
  13797. (interactive)
  13798. ;; cdlatex-environment always return nil. Therefore, capture output
  13799. ;; first and determine if an environment was selected.
  13800. (let* ((beg (point-marker))
  13801. (end (copy-marker (point) t))
  13802. (inserted (progn
  13803. (ignore-errors (cdlatex-environment environment item))
  13804. (< beg end)))
  13805. ;; Figure out how many lines to move forward after the
  13806. ;; environment has been inserted.
  13807. (lines (when inserted
  13808. (save-excursion
  13809. (- (cl-loop while (< beg (point))
  13810. with x = 0
  13811. do (forward-line -1)
  13812. (cl-incf x)
  13813. finally return x)
  13814. (if (progn (goto-char beg)
  13815. (and (progn (skip-chars-forward " \t") (eolp))
  13816. (progn (skip-chars-backward " \t") (bolp))))
  13817. 1 0)))))
  13818. (env (org-trim (delete-and-extract-region beg end))))
  13819. (when inserted
  13820. ;; Get indentation of next line unless at column 0.
  13821. (let ((ind (if (bolp) 0
  13822. (save-excursion
  13823. (org-return t)
  13824. (prog1 (current-indentation)
  13825. (when (progn (skip-chars-forward " \t") (eolp))
  13826. (delete-region beg (point)))))))
  13827. (bol (progn (skip-chars-backward " \t") (bolp))))
  13828. ;; Insert a newline before environment unless at column zero
  13829. ;; to "escape" the current line. Insert a newline if
  13830. ;; something is one the same line as \end{ENVIRONMENT}.
  13831. (insert
  13832. (concat (unless bol "\n") env
  13833. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  13834. (unless (zerop ind)
  13835. (save-excursion
  13836. (goto-char beg)
  13837. (while (< (point) end)
  13838. (unless (eolp) (indent-line-to ind))
  13839. (forward-line))))
  13840. (goto-char beg)
  13841. (forward-line lines)
  13842. (indent-line-to ind)))
  13843. (set-marker beg nil)
  13844. (set-marker end nil)))
  13845. ;;;; LaTeX fragments
  13846. (defun org-inside-LaTeX-fragment-p ()
  13847. "Test if point is inside a LaTeX fragment.
  13848. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  13849. sequence appearing also before point.
  13850. Even though the matchers for math are configurable, this function assumes
  13851. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  13852. delimiters are skipped when they have been removed by customization.
  13853. The return value is nil, or a cons cell with the delimiter and the
  13854. position of this delimiter.
  13855. This function does a reasonably good job, but can locally be fooled by
  13856. for example currency specifications. For example it will assume being in
  13857. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  13858. fragments that are properly closed, but during editing, we have to live
  13859. with the uncertainty caused by missing closing delimiters. This function
  13860. looks only before point, not after."
  13861. (catch 'exit
  13862. (let ((pos (point))
  13863. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  13864. (lim (progn
  13865. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  13866. 'move)
  13867. (point)))
  13868. dd-on str (start 0) m re)
  13869. (goto-char pos)
  13870. (when dodollar
  13871. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  13872. re (nth 1 (assoc "$" org-latex-regexps)))
  13873. (while (string-match re str start)
  13874. (cond
  13875. ((= (match-end 0) (length str))
  13876. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  13877. ((= (match-end 0) (- (length str) 5))
  13878. (throw 'exit nil))
  13879. (t (setq start (match-end 0))))))
  13880. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  13881. (goto-char pos)
  13882. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  13883. (and (match-beginning 2) (throw 'exit nil))
  13884. ;; count $$
  13885. (while (re-search-backward "\\$\\$" lim t)
  13886. (setq dd-on (not dd-on)))
  13887. (goto-char pos)
  13888. (when dd-on (cons "$$" m))))))
  13889. (defun org-inside-latex-macro-p ()
  13890. "Is point inside a LaTeX macro or its arguments?"
  13891. (save-match-data
  13892. (org-in-regexp
  13893. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  13894. (defun org--make-preview-overlay (beg end image &optional imagetype)
  13895. "Build an overlay between BEG and END using IMAGE file.
  13896. Argument IMAGETYPE is the extension of the displayed image,
  13897. as a string. It defaults to \"png\"."
  13898. (let ((ov (make-overlay beg end))
  13899. (imagetype (or (intern imagetype) 'png)))
  13900. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  13901. (overlay-put ov 'evaporate t)
  13902. (overlay-put ov
  13903. 'modification-hooks
  13904. (list (lambda (o _flag _beg _end &optional _l)
  13905. (delete-overlay o))))
  13906. (overlay-put ov
  13907. 'display
  13908. (list 'image :type imagetype :file image :ascent 'center))))
  13909. (defun org-clear-latex-preview (&optional beg end)
  13910. "Remove all overlays with LaTeX fragment images in current buffer.
  13911. When optional arguments BEG and END are non-nil, remove all
  13912. overlays between them instead. Return a non-nil value when some
  13913. overlays were removed, nil otherwise."
  13914. (let ((overlays
  13915. (cl-remove-if-not
  13916. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  13917. (overlays-in (or beg (point-min)) (or end (point-max))))))
  13918. (mapc #'delete-overlay overlays)
  13919. overlays))
  13920. (defun org--latex-preview-region (beg end)
  13921. "Preview LaTeX fragments between BEG and END.
  13922. BEG and END are buffer positions."
  13923. (let ((file (buffer-file-name (buffer-base-buffer))))
  13924. (save-excursion
  13925. (org-format-latex
  13926. (concat org-preview-latex-image-directory "org-ltximg")
  13927. beg end
  13928. ;; Emacs cannot overlay images from remote hosts. Create it in
  13929. ;; `temporary-file-directory' instead.
  13930. (if (or (not file) (file-remote-p file))
  13931. temporary-file-directory
  13932. default-directory)
  13933. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  13934. (defun org-latex-preview (&optional arg)
  13935. "Toggle preview of the LaTeX fragment at point.
  13936. If the cursor is on a LaTeX fragment, create the image and
  13937. overlay it over the source code, if there is none. Remove it
  13938. otherwise. If there is no fragment at point, display images for
  13939. all fragments in the current section.
  13940. With a `\\[universal-argument]' prefix argument ARG, clear images \
  13941. for all fragments
  13942. in the current section.
  13943. With a `\\[universal-argument] \\[universal-argument]' prefix \
  13944. argument ARG, display image for all
  13945. fragments in the buffer.
  13946. With a `\\[universal-argument] \\[universal-argument] \
  13947. \\[universal-argument]' prefix argument ARG, clear image for all
  13948. fragments in the buffer."
  13949. (interactive "P")
  13950. (cond
  13951. ((not (display-graphic-p)) nil)
  13952. ;; Clear whole buffer.
  13953. ((equal arg '(64))
  13954. (org-clear-latex-preview (point-min) (point-max))
  13955. (message "LaTeX previews removed from buffer"))
  13956. ;; Preview whole buffer.
  13957. ((equal arg '(16))
  13958. (message "Creating LaTeX previews in buffer...")
  13959. (org--latex-preview-region (point-min) (point-max))
  13960. (message "Creating LaTeX previews in buffer... done."))
  13961. ;; Clear current section.
  13962. ((equal arg '(4))
  13963. (org-clear-latex-preview
  13964. (if (org-before-first-heading-p) (point-min)
  13965. (save-excursion
  13966. (org-with-limited-levels (org-back-to-heading t) (point))))
  13967. (org-with-limited-levels (org-entry-end-position))))
  13968. ;; Toggle preview on LaTeX code at point.
  13969. ((let ((datum (org-element-context)))
  13970. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  13971. (let ((beg (org-element-property :begin datum))
  13972. (end (org-element-property :end datum)))
  13973. (if (org-clear-latex-preview beg end)
  13974. (message "LaTeX preview removed")
  13975. (message "Creating LaTeX preview...")
  13976. (org--latex-preview-region beg end)
  13977. (message "Creating LaTeX preview... done."))
  13978. t))))
  13979. ;; Preview current section.
  13980. (t
  13981. (let ((beg (if (org-before-first-heading-p) (point-min)
  13982. (save-excursion
  13983. (org-with-limited-levels (org-back-to-heading t) (point)))))
  13984. (end (org-with-limited-levels (org-entry-end-position))))
  13985. (message "Creating LaTeX previews in section...")
  13986. (org--latex-preview-region beg end)
  13987. (message "Creating LaTeX previews in section... done.")))))
  13988. (defun org-format-latex
  13989. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  13990. "Replace LaTeX fragments with links to an image.
  13991. The function takes care of creating the replacement image.
  13992. Only consider fragments between BEG and END when those are
  13993. provided.
  13994. When optional argument OVERLAYS is non-nil, display the image on
  13995. top of the fragment instead of replacing it.
  13996. PROCESSING-TYPE is the conversion method to use, as a symbol.
  13997. Some of the options can be changed using the variable
  13998. `org-format-latex-options', which see."
  13999. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14000. (unless (eq processing-type 'verbatim)
  14001. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14002. (cnt 0)
  14003. checkdir-flag)
  14004. (goto-char (or beg (point-min)))
  14005. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14006. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14007. (overlay-recenter (or end (point-max))))
  14008. (while (re-search-forward math-regexp end t)
  14009. (unless (and overlays
  14010. (eq (get-char-property (point) 'org-overlay-type)
  14011. 'org-latex-overlay))
  14012. (let* ((context (org-element-context))
  14013. (type (org-element-type context)))
  14014. (when (memq type '(latex-environment latex-fragment))
  14015. (let ((block-type (eq type 'latex-environment))
  14016. (value (org-element-property :value context))
  14017. (beg (org-element-property :begin context))
  14018. (end (save-excursion
  14019. (goto-char (org-element-property :end context))
  14020. (skip-chars-backward " \r\t\n")
  14021. (point))))
  14022. (cond
  14023. ((eq processing-type 'mathjax)
  14024. ;; Prepare for MathJax processing.
  14025. (if (not (string-match "\\`\\$\\$?" value))
  14026. (goto-char end)
  14027. (delete-region beg end)
  14028. (if (string= (match-string 0 value) "$$")
  14029. (insert "\\[" (substring value 2 -2) "\\]")
  14030. (insert "\\(" (substring value 1 -1) "\\)"))))
  14031. ((eq processing-type 'html)
  14032. (goto-char beg)
  14033. (delete-region beg end)
  14034. (insert (org-format-latex-as-html value)))
  14035. ((assq processing-type org-preview-latex-process-alist)
  14036. ;; Process to an image.
  14037. (cl-incf cnt)
  14038. (goto-char beg)
  14039. (let* ((processing-info
  14040. (cdr (assq processing-type org-preview-latex-process-alist)))
  14041. (face (face-at-point))
  14042. ;; Get the colors from the face at point.
  14043. (fg
  14044. (let ((color (plist-get org-format-latex-options
  14045. :foreground)))
  14046. (if forbuffer
  14047. (cond
  14048. ((eq color 'auto)
  14049. (face-attribute face :foreground nil 'default))
  14050. ((eq color 'default)
  14051. (face-attribute 'default :foreground nil))
  14052. (t color))
  14053. color)))
  14054. (bg
  14055. (let ((color (plist-get org-format-latex-options
  14056. :background)))
  14057. (if forbuffer
  14058. (cond
  14059. ((eq color 'auto)
  14060. (face-attribute face :background nil 'default))
  14061. ((eq color 'default)
  14062. (face-attribute 'default :background nil))
  14063. (t color))
  14064. color)))
  14065. (hash (sha1 (prin1-to-string
  14066. (list org-format-latex-header
  14067. org-latex-default-packages-alist
  14068. org-latex-packages-alist
  14069. org-format-latex-options
  14070. forbuffer value fg bg))))
  14071. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14072. (absprefix (expand-file-name prefix dir))
  14073. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14074. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14075. (sep (and block-type "\n\n"))
  14076. (link (concat sep "[[file:" linkfile "]]" sep))
  14077. (options
  14078. (org-combine-plists
  14079. org-format-latex-options
  14080. `(:foreground ,fg :background ,bg))))
  14081. (when msg (message msg cnt))
  14082. (unless checkdir-flag ; Ensure the directory exists.
  14083. (setq checkdir-flag t)
  14084. (let ((todir (file-name-directory absprefix)))
  14085. (unless (file-directory-p todir)
  14086. (make-directory todir t))))
  14087. (unless (file-exists-p movefile)
  14088. (org-create-formula-image
  14089. value movefile options forbuffer processing-type))
  14090. (if overlays
  14091. (progn
  14092. (dolist (o (overlays-in beg end))
  14093. (when (eq (overlay-get o 'org-overlay-type)
  14094. 'org-latex-overlay)
  14095. (delete-overlay o)))
  14096. (org--make-preview-overlay beg end movefile imagetype)
  14097. (goto-char end))
  14098. (delete-region beg end)
  14099. (insert
  14100. (org-add-props link
  14101. (list 'org-latex-src
  14102. (replace-regexp-in-string "\"" "" value)
  14103. 'org-latex-src-embed-type
  14104. (if block-type 'paragraph 'character)))))))
  14105. ((eq processing-type 'mathml)
  14106. ;; Process to MathML.
  14107. (unless (org-format-latex-mathml-available-p)
  14108. (user-error "LaTeX to MathML converter not configured"))
  14109. (cl-incf cnt)
  14110. (when msg (message msg cnt))
  14111. (goto-char beg)
  14112. (delete-region beg end)
  14113. (insert (org-format-latex-as-mathml
  14114. value block-type prefix dir)))
  14115. (t
  14116. (error "Unknown conversion process %s for LaTeX fragments"
  14117. processing-type)))))))))))
  14118. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14119. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14120. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14121. successful, return the portion between \"<math...> </math>\"
  14122. elements otherwise return nil. When MATHML-FILE is specified,
  14123. write the results in to that file. When invoked as an
  14124. interactive command, prompt for LATEX-FRAG, with initial value
  14125. set to the current active region and echo the results for user
  14126. inspection."
  14127. (interactive (list (let ((frag (when (org-region-active-p)
  14128. (buffer-substring-no-properties
  14129. (region-beginning) (region-end)))))
  14130. (read-string "LaTeX Fragment: " frag nil frag))))
  14131. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14132. (let* ((tmp-in-file
  14133. (let ((file (file-relative-name
  14134. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14135. (write-region latex-frag nil file)
  14136. file))
  14137. (tmp-out-file (file-relative-name
  14138. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14139. (cmd (format-spec
  14140. org-latex-to-mathml-convert-command
  14141. `((?j . ,(and org-latex-to-mathml-jar-file
  14142. (shell-quote-argument
  14143. (expand-file-name
  14144. org-latex-to-mathml-jar-file))))
  14145. (?I . ,(shell-quote-argument tmp-in-file))
  14146. (?i . ,latex-frag)
  14147. (?o . ,(shell-quote-argument tmp-out-file)))))
  14148. mathml shell-command-output)
  14149. (when (called-interactively-p 'any)
  14150. (unless (org-format-latex-mathml-available-p)
  14151. (user-error "LaTeX to MathML converter not configured")))
  14152. (message "Running %s" cmd)
  14153. (setq shell-command-output (shell-command-to-string cmd))
  14154. (setq mathml
  14155. (when (file-readable-p tmp-out-file)
  14156. (with-current-buffer (find-file-noselect tmp-out-file t)
  14157. (goto-char (point-min))
  14158. (when (re-search-forward
  14159. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14160. (regexp-quote
  14161. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14162. nil t)
  14163. (prog1 (match-string 0) (kill-buffer))))))
  14164. (cond
  14165. (mathml
  14166. (setq mathml
  14167. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14168. (when mathml-file
  14169. (write-region mathml nil mathml-file))
  14170. (when (called-interactively-p 'any)
  14171. (message mathml)))
  14172. ((warn "LaTeX to MathML conversion failed")
  14173. (message shell-command-output)))
  14174. (delete-file tmp-in-file)
  14175. (when (file-exists-p tmp-out-file)
  14176. (delete-file tmp-out-file))
  14177. mathml))
  14178. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14179. prefix &optional dir)
  14180. "Use `org-create-math-formula' but check local cache first."
  14181. (let* ((absprefix (expand-file-name prefix dir))
  14182. (print-length nil) (print-level nil)
  14183. (formula-id (concat
  14184. "formula-"
  14185. (sha1
  14186. (prin1-to-string
  14187. (list latex-frag
  14188. org-latex-to-mathml-convert-command)))))
  14189. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14190. (formula-cache-dir (file-name-directory formula-cache)))
  14191. (unless (file-directory-p formula-cache-dir)
  14192. (make-directory formula-cache-dir t))
  14193. (unless (file-exists-p formula-cache)
  14194. (org-create-math-formula latex-frag formula-cache))
  14195. (if (file-exists-p formula-cache)
  14196. ;; Successful conversion. Return the link to MathML file.
  14197. (org-add-props
  14198. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14199. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14200. 'org-latex-src-embed-type (if latex-frag-type
  14201. 'paragraph 'character)))
  14202. ;; Failed conversion. Return the LaTeX fragment verbatim
  14203. latex-frag)))
  14204. (defun org-format-latex-as-html (latex-fragment)
  14205. "Convert LATEX-FRAGMENT to HTML.
  14206. This uses `org-latex-to-html-convert-command', which see."
  14207. (let ((cmd (format-spec org-latex-to-html-convert-command
  14208. `((?i . ,latex-fragment)))))
  14209. (message "Running %s" cmd)
  14210. (shell-command-to-string cmd)))
  14211. (defun org--get-display-dpi ()
  14212. "Get the DPI of the display.
  14213. The function assumes that the display has the same pixel width in
  14214. the horizontal and vertical directions."
  14215. (if (display-graphic-p)
  14216. (round (/ (display-pixel-height)
  14217. (/ (display-mm-height) 25.4)))
  14218. (error "Attempt to calculate the dpi of a non-graphic display")))
  14219. (defun org-create-formula-image
  14220. (string tofile options buffer &optional processing-type)
  14221. "Create an image from LaTeX source using external processes.
  14222. The LaTeX STRING is saved to a temporary LaTeX file, then
  14223. converted to an image file by process PROCESSING-TYPE defined in
  14224. `org-preview-latex-process-alist'. A nil value defaults to
  14225. `org-preview-latex-default-process'.
  14226. The generated image file is eventually moved to TOFILE.
  14227. The OPTIONS argument controls the size, foreground color and
  14228. background color of the generated image.
  14229. When BUFFER non-nil, this function is used for LaTeX previewing.
  14230. Otherwise, it is used to deal with LaTeX snippets showed in
  14231. a HTML file."
  14232. (let* ((processing-type (or processing-type
  14233. org-preview-latex-default-process))
  14234. (processing-info
  14235. (cdr (assq processing-type org-preview-latex-process-alist)))
  14236. (programs (plist-get processing-info :programs))
  14237. (error-message (or (plist-get processing-info :message) ""))
  14238. (image-input-type (plist-get processing-info :image-input-type))
  14239. (image-output-type (plist-get processing-info :image-output-type))
  14240. (post-clean (or (plist-get processing-info :post-clean)
  14241. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14242. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14243. (latex-header
  14244. (or (plist-get processing-info :latex-header)
  14245. (org-latex-make-preamble
  14246. (org-export-get-environment (org-export-get-backend 'latex))
  14247. org-format-latex-header
  14248. 'snippet)))
  14249. (latex-compiler (plist-get processing-info :latex-compiler))
  14250. (tmpdir temporary-file-directory)
  14251. (texfilebase (make-temp-name
  14252. (expand-file-name "orgtex" tmpdir)))
  14253. (texfile (concat texfilebase ".tex"))
  14254. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14255. '(1.0 . 1.0)))
  14256. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14257. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14258. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14259. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14260. "Black"))
  14261. (bg (or (plist-get options (if buffer :background :html-background))
  14262. "Transparent"))
  14263. (image-converter
  14264. (or (and (string= bg "Transparent")
  14265. (plist-get processing-info :transparent-image-converter))
  14266. (plist-get processing-info :image-converter)))
  14267. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14268. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14269. (dolist (program programs)
  14270. (org-check-external-command program error-message))
  14271. (if (eq fg 'default)
  14272. (setq fg (org-latex-color :foreground))
  14273. (setq fg (org-latex-color-format fg)))
  14274. (setq bg (cond
  14275. ((eq bg 'default) (org-latex-color :background))
  14276. ((string= bg "Transparent") nil)
  14277. (t (org-latex-color-format bg))))
  14278. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14279. (if (string-suffix-p string "\n")
  14280. (aset string (1- (length string)) ?%)
  14281. (setq string (concat string "%")))
  14282. (with-temp-file texfile
  14283. (insert latex-header)
  14284. (insert "\n\\begin{document}\n"
  14285. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14286. (if bg
  14287. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14288. "\n\\pagecolor{bg}%\n")
  14289. "")
  14290. "\n{\\color{fg}\n"
  14291. string
  14292. "\n}\n"
  14293. "\n\\end{document}\n"))
  14294. (let* ((err-msg (format "Please adjust `%s' part of \
  14295. `org-preview-latex-process-alist'."
  14296. processing-type))
  14297. (image-input-file
  14298. (org-compile-file
  14299. texfile latex-compiler image-input-type err-msg log-buf))
  14300. (image-output-file
  14301. (org-compile-file
  14302. image-input-file image-converter image-output-type err-msg log-buf
  14303. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14304. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14305. (copy-file image-output-file tofile 'replace)
  14306. (dolist (e post-clean)
  14307. (when (file-exists-p (concat texfilebase e))
  14308. (delete-file (concat texfilebase e))))
  14309. image-output-file)))
  14310. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14311. "Fill a LaTeX header template TPL.
  14312. In the template, the following place holders will be recognized:
  14313. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14314. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14315. [PACKAGES] \\usepackage statements for PKG
  14316. [NO-PACKAGES] do not include PKG
  14317. [EXTRA] the string EXTRA
  14318. [NO-EXTRA] do not include EXTRA
  14319. For backward compatibility, if both the positive and the negative place
  14320. holder is missing, the positive one (without the \"NO-\") will be
  14321. assumed to be present at the end of the template.
  14322. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14323. EXTRA is a string.
  14324. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14325. (let (rpl (end ""))
  14326. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14327. (setq rpl (if (or (match-end 1) (not def-pkg))
  14328. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14329. tpl (replace-match rpl t t tpl))
  14330. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14331. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14332. (setq rpl (if (or (match-end 1) (not pkg))
  14333. "" (org-latex-packages-to-string pkg snippets-p t))
  14334. tpl (replace-match rpl t t tpl))
  14335. (when pkg (setq end
  14336. (concat end "\n"
  14337. (org-latex-packages-to-string pkg snippets-p)))))
  14338. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14339. (setq rpl (if (or (match-end 1) (not extra))
  14340. "" (concat extra "\n"))
  14341. tpl (replace-match rpl t t tpl))
  14342. (when (and extra (string-match "\\S-" extra))
  14343. (setq end (concat end "\n" extra))))
  14344. (if (string-match "\\S-" end)
  14345. (concat tpl "\n" end)
  14346. tpl)))
  14347. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14348. "Turn an alist of packages into a string with the \\usepackage macros."
  14349. (setq pkg (mapconcat (lambda(p)
  14350. (cond
  14351. ((stringp p) p)
  14352. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14353. (format "%% Package %s omitted" (cadr p)))
  14354. ((equal "" (car p))
  14355. (format "\\usepackage{%s}" (cadr p)))
  14356. (t
  14357. (format "\\usepackage[%s]{%s}"
  14358. (car p) (cadr p)))))
  14359. pkg
  14360. "\n"))
  14361. (if newline (concat pkg "\n") pkg))
  14362. (defun org-dvipng-color (attr)
  14363. "Return a RGB color specification for dvipng."
  14364. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14365. (defun org-dvipng-color-format (color-name)
  14366. "Convert COLOR-NAME to a RGB color value for dvipng."
  14367. (apply #'format "rgb %s %s %s"
  14368. (mapcar 'org-normalize-color
  14369. (color-values color-name))))
  14370. (defun org-latex-color (attr)
  14371. "Return a RGB color for the LaTeX color package."
  14372. (org-latex-color-format (face-attribute 'default attr nil)))
  14373. (defun org-latex-color-format (color-name)
  14374. "Convert COLOR-NAME to a RGB color value."
  14375. (apply #'format "%s,%s,%s"
  14376. (mapcar 'org-normalize-color
  14377. (color-values color-name))))
  14378. (defun org-normalize-color (value)
  14379. "Return string to be used as color value for an RGB component."
  14380. (format "%g" (/ value 65535.0)))
  14381. ;; Image display
  14382. (defvar-local org-inline-image-overlays nil)
  14383. (defun org-toggle-inline-images (&optional include-linked)
  14384. "Toggle the display of inline images.
  14385. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14386. (interactive "P")
  14387. (if org-inline-image-overlays
  14388. (progn
  14389. (org-remove-inline-images)
  14390. (when (called-interactively-p 'interactive)
  14391. (message "Inline image display turned off")))
  14392. (org-display-inline-images include-linked)
  14393. (when (called-interactively-p 'interactive)
  14394. (message (if org-inline-image-overlays
  14395. (format "%d images displayed inline"
  14396. (length org-inline-image-overlays))
  14397. "No images to display inline")))))
  14398. (defun org-redisplay-inline-images ()
  14399. "Assure display of inline images and refresh them."
  14400. (interactive)
  14401. (org-toggle-inline-images)
  14402. (unless org-inline-image-overlays
  14403. (org-toggle-inline-images)))
  14404. ;; For without-x builds.
  14405. (declare-function image-refresh "image" (spec &optional frame))
  14406. (defcustom org-display-remote-inline-images 'skip
  14407. "How to display remote inline images.
  14408. Possible values of this option are:
  14409. skip Don't display remote images.
  14410. download Always download and display remote images.
  14411. cache Display remote images, and open them in separate buffers
  14412. for caching. Silently update the image buffer when a file
  14413. change is detected."
  14414. :group 'org-appearance
  14415. :package-version '(Org . "9.4")
  14416. :type '(choice
  14417. (const :tag "Ignore remote images" skip)
  14418. (const :tag "Always display remote images" download)
  14419. (const :tag "Display and silently update remote images" cache))
  14420. :safe #'symbolp)
  14421. (defun org--create-inline-image (file width)
  14422. "Create image located at FILE, or return nil.
  14423. WIDTH is the width of the image. The image may not be created
  14424. according to the value of `org-display-remote-inline-images'."
  14425. (let* ((remote? (file-remote-p file))
  14426. (file-or-data
  14427. (pcase org-display-remote-inline-images
  14428. ((guard (not remote?)) file)
  14429. (`download (with-temp-buffer
  14430. (set-buffer-multibyte nil)
  14431. (insert-file-contents-literally file)
  14432. (buffer-string)))
  14433. (`cache (let ((revert-without-query '(".")))
  14434. (with-current-buffer (find-file-noselect file)
  14435. (buffer-string))))
  14436. (`skip nil)
  14437. (other
  14438. (message "Invalid value of `org-display-remote-inline-images': %S"
  14439. other)
  14440. nil))))
  14441. (when file-or-data
  14442. (create-image file-or-data
  14443. (and (image-type-available-p 'imagemagick)
  14444. width
  14445. 'imagemagick)
  14446. remote?
  14447. :width width :scale 1))))
  14448. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14449. "Display inline images.
  14450. An inline image is a link which follows either of these
  14451. conventions:
  14452. 1. Its path is a file with an extension matching return value
  14453. from `image-file-name-regexp' and it has no contents.
  14454. 2. Its description consists in a single link of the previous
  14455. type. In this case, that link must be a well-formed plain
  14456. or angle link, i.e., it must have an explicit \"file\" type.
  14457. Equip each image with the key-map `image-map'.
  14458. When optional argument INCLUDE-LINKED is non-nil, also links with
  14459. a text description part will be inlined. This can be nice for
  14460. a quick look at those images, but it does not reflect what
  14461. exported files will look like.
  14462. When optional argument REFRESH is non-nil, refresh existing
  14463. images between BEG and END. This will create new image displays
  14464. only if necessary.
  14465. BEG and END define the considered part. They default to the
  14466. buffer boundaries with possible narrowing."
  14467. (interactive "P")
  14468. (when (display-graphic-p)
  14469. (unless refresh
  14470. (org-remove-inline-images)
  14471. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14472. (let ((end (or end (point-max))))
  14473. (org-with-point-at (or beg (point-min))
  14474. (let* ((case-fold-search t)
  14475. (file-extension-re (image-file-name-regexp))
  14476. (link-abbrevs (mapcar #'car
  14477. (append org-link-abbrev-alist-local
  14478. org-link-abbrev-alist)))
  14479. ;; Check absolute, relative file names and explicit
  14480. ;; "file:" links. Also check link abbreviations since
  14481. ;; some might expand to "file" links.
  14482. (file-types-re
  14483. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14484. (if (not link-abbrevs) ""
  14485. (concat "\\|" (regexp-opt link-abbrevs))))))
  14486. (while (re-search-forward file-types-re end t)
  14487. (let* ((link (org-element-lineage
  14488. (save-match-data (org-element-context))
  14489. '(link) t))
  14490. (linktype (org-element-property :type link))
  14491. (inner-start (match-beginning 1))
  14492. (path
  14493. (cond
  14494. ;; No link at point; no inline image.
  14495. ((not link) nil)
  14496. ;; File link without a description. Also handle
  14497. ;; INCLUDE-LINKED here since it should have
  14498. ;; precedence over the next case. I.e., if link
  14499. ;; contains filenames in both the path and the
  14500. ;; description, prioritize the path only when
  14501. ;; INCLUDE-LINKED is non-nil.
  14502. ((or (not (org-element-property :contents-begin link))
  14503. include-linked)
  14504. (and (or (equal "file" linktype)
  14505. (equal "attachment" linktype))
  14506. (org-element-property :path link)))
  14507. ;; Link with a description. Check if description
  14508. ;; is a filename. Even if Org doesn't have syntax
  14509. ;; for those -- clickable image -- constructs, fake
  14510. ;; them, as in `org-export-insert-image-links'.
  14511. ((not inner-start) nil)
  14512. (t
  14513. (org-with-point-at inner-start
  14514. (and (looking-at
  14515. (if (char-equal ?< (char-after inner-start))
  14516. org-link-angle-re
  14517. org-link-plain-re))
  14518. ;; File name must fill the whole
  14519. ;; description.
  14520. (= (org-element-property :contents-end link)
  14521. (match-end 0))
  14522. (match-string 2)))))))
  14523. (when (and path (string-match-p file-extension-re path))
  14524. (let ((file (if (equal "attachment" linktype)
  14525. (progn
  14526. (require 'org-attach)
  14527. (ignore-errors (org-attach-expand path)))
  14528. (expand-file-name path))))
  14529. (when (and file (file-exists-p file))
  14530. (let ((width (org-display-inline-image--width link))
  14531. (old (get-char-property-and-overlay
  14532. (org-element-property :begin link)
  14533. 'org-image-overlay)))
  14534. (if (and (car-safe old) refresh)
  14535. (image-refresh (overlay-get (cdr old) 'display))
  14536. (let ((image (org--create-inline-image file width)))
  14537. (when image
  14538. (let ((ov (make-overlay
  14539. (org-element-property :begin link)
  14540. (progn
  14541. (goto-char
  14542. (org-element-property :end link))
  14543. (skip-chars-backward " \t")
  14544. (point)))))
  14545. (overlay-put ov 'display image)
  14546. (overlay-put ov 'face 'default)
  14547. (overlay-put ov 'org-image-overlay t)
  14548. (overlay-put
  14549. ov 'modification-hooks
  14550. (list 'org-display-inline-remove-overlay))
  14551. (when (boundp 'image-map)
  14552. (overlay-put ov 'keymap image-map))
  14553. (push ov org-inline-image-overlays))))))))))))))))
  14554. (defvar visual-fill-column-width) ; Silence compiler warning
  14555. (defun org-display-inline-image--width (link)
  14556. "Determine the display width of the image LINK, in pixels.
  14557. - When `org-image-actual-width' is t, the image's pixel width is used.
  14558. - When `org-image-actual-width' is a number, that value will is used.
  14559. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14560. set (if it exists) is used to set the image width. A width of X% is
  14561. divided by 100.
  14562. If no :width attribute is given and `org-image-actual-width' is a list with
  14563. a number as the car, then that number is used as the default value.
  14564. If the value is a float between 0 and 2, it interpreted as that proportion
  14565. of the text width in the buffer."
  14566. ;; Apply `org-image-actual-width' specifications.
  14567. (cond
  14568. ((eq org-image-actual-width t) nil)
  14569. ((listp org-image-actual-width)
  14570. (let* ((case-fold-search t)
  14571. (par (org-element-lineage link '(paragraph)))
  14572. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14573. (par-end (org-element-property :post-affiliated par))
  14574. ;; Try to find an attribute providing a :width.
  14575. (attr-width
  14576. (when (and par (org-with-point-at
  14577. (org-element-property :begin par)
  14578. (re-search-forward attr-re par-end t)))
  14579. (match-string 1)))
  14580. (width
  14581. (cond
  14582. ;; Treat :width t as if `org-image-actual-width' were t.
  14583. ((string= attr-width "t") nil)
  14584. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14585. ((or (null attr-width)
  14586. (string-match-p "\\`[^0-9]" attr-width))
  14587. (car org-image-actual-width))
  14588. ;; Convert numeric widths to numbers, converting percentages.
  14589. ((string-match-p "\\`[0-9.]+%" attr-width)
  14590. (/ (string-to-number attr-width) 100.0))
  14591. (t (string-to-number attr-width)))))
  14592. (if (and (floatp width) (<= 0.0 width 2.0))
  14593. ;; A float in [0,2] should be interpereted as this portion of
  14594. ;; the text width in the window. This works well with cases like
  14595. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14596. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14597. ;; bound as cases such as 1.2\linewidth are feasible.
  14598. (round (* width
  14599. (window-pixel-width)
  14600. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14601. (or visual-fill-column-width auto-fill-function))
  14602. (when auto-fill-function fill-column)
  14603. (- (window-text-width) (line-number-display-width)))
  14604. (float (window-total-width)))))
  14605. width)))
  14606. ((numberp org-image-actual-width)
  14607. org-image-actual-width)
  14608. (t nil)))
  14609. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14610. "Remove inline-display overlay if a corresponding region is modified."
  14611. (let ((inhibit-modification-hooks t))
  14612. (when (and ov after)
  14613. (delete ov org-inline-image-overlays)
  14614. (delete-overlay ov))))
  14615. (defun org-remove-inline-images ()
  14616. "Remove inline display of images."
  14617. (interactive)
  14618. (mapc #'delete-overlay org-inline-image-overlays)
  14619. (setq org-inline-image-overlays nil))
  14620. (defvar org-self-insert-command-undo-counter 0)
  14621. (defvar org-speed-command nil)
  14622. (defun org-fix-tags-on-the-fly ()
  14623. "Align tags in headline at point.
  14624. Unlike `org-align-tags', this function does nothing if point is
  14625. either not currently on a tagged headline or on a tag."
  14626. (when (and (org-match-line org-tag-line-re)
  14627. (< (point) (match-beginning 1)))
  14628. (org-align-tags)))
  14629. (defun org-self-insert-command (N)
  14630. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14631. If the cursor is in a table looking at whitespace, the whitespace is
  14632. overwritten, and the table is not marked as requiring realignment."
  14633. (interactive "p")
  14634. (org-fold-check-before-invisible-edit 'insert)
  14635. (cond
  14636. ((and org-use-speed-commands
  14637. (let ((kv (this-command-keys-vector)))
  14638. (setq org-speed-command
  14639. (run-hook-with-args-until-success
  14640. 'org-speed-command-hook
  14641. (make-string 1 (aref kv (1- (length kv))))))))
  14642. (cond
  14643. ((commandp org-speed-command)
  14644. (setq this-command org-speed-command)
  14645. (call-interactively org-speed-command))
  14646. ((functionp org-speed-command)
  14647. (funcall org-speed-command))
  14648. ((consp org-speed-command)
  14649. (eval org-speed-command t))
  14650. (t (let (org-use-speed-commands)
  14651. (call-interactively 'org-self-insert-command)))))
  14652. ((and
  14653. (= N 1)
  14654. (not (org-region-active-p))
  14655. (org-at-table-p)
  14656. (progn
  14657. ;; Check if we blank the field, and if that triggers align.
  14658. (and (featurep 'org-table)
  14659. org-table-auto-blank-field
  14660. (memq last-command
  14661. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14662. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14663. ;; Got extra space, this field does not determine
  14664. ;; column width.
  14665. (let (org-table-may-need-update) (org-table-blank-field))
  14666. ;; No extra space, this field may determine column
  14667. ;; width.
  14668. (org-table-blank-field)))
  14669. t)
  14670. (looking-at "[^|\n]* |"))
  14671. ;; There is room for insertion without re-aligning the table.
  14672. (self-insert-command N)
  14673. (org-table-with-shrunk-field
  14674. (save-excursion
  14675. (skip-chars-forward "^|")
  14676. ;; Do not delete last space, which is
  14677. ;; `org-table-separator-space', but the regular space before
  14678. ;; it.
  14679. (delete-region (- (point) 2) (1- (point))))))
  14680. (t
  14681. (setq org-table-may-need-update t)
  14682. (self-insert-command N)
  14683. (org-fix-tags-on-the-fly)
  14684. (when org-self-insert-cluster-for-undo
  14685. (if (not (eq last-command 'org-self-insert-command))
  14686. (setq org-self-insert-command-undo-counter 1)
  14687. (if (>= org-self-insert-command-undo-counter 20)
  14688. (setq org-self-insert-command-undo-counter 1)
  14689. (and (> org-self-insert-command-undo-counter 0)
  14690. buffer-undo-list (listp buffer-undo-list)
  14691. (not (cadr buffer-undo-list)) ; remove nil entry
  14692. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14693. (setq org-self-insert-command-undo-counter
  14694. (1+ org-self-insert-command-undo-counter))))))))
  14695. (defun org-delete-backward-char (N)
  14696. "Like `delete-backward-char', insert whitespace at field end in tables.
  14697. When deleting backwards, in tables this function will insert whitespace in
  14698. front of the next \"|\" separator, to keep the table aligned. The table will
  14699. still be marked for re-alignment if the field did fill the entire column,
  14700. because, in this case the deletion might narrow the column."
  14701. (interactive "p")
  14702. (save-match-data
  14703. (org-fold-check-before-invisible-edit 'delete-backward)
  14704. (if (and (= N 1)
  14705. (not overwrite-mode)
  14706. (not (org-region-active-p))
  14707. (not (eq (char-before) ?|))
  14708. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14709. (looking-at-p ".*?|")
  14710. (org-at-table-p))
  14711. (progn (forward-char -1) (org-delete-char 1))
  14712. (backward-delete-char N)
  14713. (org-fix-tags-on-the-fly))))
  14714. (defun org-delete-char (N)
  14715. "Like `delete-char', but insert whitespace at field end in tables.
  14716. When deleting characters, in tables this function will insert whitespace in
  14717. front of the next \"|\" separator, to keep the table aligned. The table will
  14718. still be marked for re-alignment if the field did fill the entire column,
  14719. because, in this case the deletion might narrow the column."
  14720. (interactive "p")
  14721. (save-match-data
  14722. (org-fold-check-before-invisible-edit 'delete)
  14723. (cond
  14724. ((or (/= N 1)
  14725. (eq (char-after) ?|)
  14726. (save-excursion (skip-chars-backward " \t") (bolp))
  14727. (not (org-at-table-p)))
  14728. (delete-char N)
  14729. (org-fix-tags-on-the-fly))
  14730. ((looking-at ".\\(.*?\\)|")
  14731. (let* ((update? org-table-may-need-update)
  14732. (noalign (looking-at-p ".*? |")))
  14733. (delete-char 1)
  14734. (org-table-with-shrunk-field
  14735. (save-excursion
  14736. ;; Last space is `org-table-separator-space', so insert
  14737. ;; a regular one before it instead.
  14738. (goto-char (- (match-end 0) 2))
  14739. (insert " ")))
  14740. ;; If there were two spaces at the end, this field does not
  14741. ;; determine the width of the column.
  14742. (when noalign (setq org-table-may-need-update update?))))
  14743. (t
  14744. (delete-char N)))))
  14745. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  14746. (put 'org-self-insert-command 'delete-selection
  14747. (lambda ()
  14748. (not (run-hook-with-args-until-success
  14749. 'self-insert-uses-region-functions))))
  14750. (put 'orgtbl-self-insert-command 'delete-selection
  14751. (lambda ()
  14752. (not (run-hook-with-args-until-success
  14753. 'self-insert-uses-region-functions))))
  14754. (put 'org-delete-char 'delete-selection 'supersede)
  14755. (put 'org-delete-backward-char 'delete-selection 'supersede)
  14756. (put 'org-yank 'delete-selection 'yank)
  14757. (put 'org-return 'delete-selection t)
  14758. ;; Make `flyspell-mode' delay after some commands
  14759. (put 'org-self-insert-command 'flyspell-delayed t)
  14760. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  14761. (put 'org-delete-char 'flyspell-delayed t)
  14762. (put 'org-delete-backward-char 'flyspell-delayed t)
  14763. ;; Make pabbrev-mode expand after Org mode commands
  14764. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  14765. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  14766. (defun org-transpose-words ()
  14767. "Transpose words for Org.
  14768. This uses the `org-mode-transpose-word-syntax-table' syntax
  14769. table, which interprets characters in `org-emphasis-alist' as
  14770. word constituents."
  14771. (interactive)
  14772. (with-syntax-table org-mode-transpose-word-syntax-table
  14773. (call-interactively 'transpose-words)))
  14774. (defvar org-ctrl-c-ctrl-c-hook nil
  14775. "Hook for functions attaching themselves to `C-c C-c'.
  14776. This can be used to add additional functionality to the `C-c C-c'
  14777. key which executes context-dependent commands. This hook is run
  14778. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  14779. run after the last test.
  14780. Each function will be called with no arguments. The function
  14781. must check if the context is appropriate for it to act. If yes,
  14782. it should do its thing and then return a non-nil value. If the
  14783. context is wrong, just do nothing and return nil.")
  14784. (defvar org-ctrl-c-ctrl-c-final-hook nil
  14785. "Hook for functions attaching themselves to `C-c C-c'.
  14786. This can be used to add additional functionality to the `C-c C-c'
  14787. key which executes context-dependent commands. This hook is run
  14788. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  14789. before the first test.
  14790. Each function will be called with no arguments. The function
  14791. must check if the context is appropriate for it to act. If yes,
  14792. it should do its thing and then return a non-nil value. If the
  14793. context is wrong, just do nothing and return nil.")
  14794. (defvar org-tab-after-check-for-table-hook nil
  14795. "Hook for functions to attach themselves to TAB.
  14796. See `org-ctrl-c-ctrl-c-hook' for more information.
  14797. This hook runs after it has been established that the cursor is not in a
  14798. table, but before checking if the cursor is in a headline or if global cycling
  14799. should be done.
  14800. If any function in this hook returns t, not other actions like visibility
  14801. cycling will be done.")
  14802. (defvar org-tab-after-check-for-cycling-hook nil
  14803. "Hook for functions to attach themselves to TAB.
  14804. See `org-ctrl-c-ctrl-c-hook' for more information.
  14805. This hook runs after it has been established that not table field motion and
  14806. not visibility should be done because of current context. This is probably
  14807. the place where a package like yasnippets can hook in.")
  14808. (defvar org-tab-before-tab-emulation-hook nil
  14809. "Hook for functions to attach themselves to TAB.
  14810. See `org-ctrl-c-ctrl-c-hook' for more information.
  14811. This hook runs after every other options for TAB have been exhausted, but
  14812. before indentation and \t insertion takes place.")
  14813. (defvar org-metaleft-hook nil
  14814. "Hook for functions attaching themselves to `M-left'.
  14815. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14816. (defvar org-metaright-hook nil
  14817. "Hook for functions attaching themselves to `M-right'.
  14818. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14819. (defvar org-metaup-hook nil
  14820. "Hook for functions attaching themselves to `M-up'.
  14821. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14822. (defvar org-metadown-hook nil
  14823. "Hook for functions attaching themselves to `M-down'.
  14824. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14825. (defvar org-shiftmetaleft-hook nil
  14826. "Hook for functions attaching themselves to `M-S-left'.
  14827. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14828. (defvar org-shiftmetaright-hook nil
  14829. "Hook for functions attaching themselves to `M-S-right'.
  14830. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14831. (defvar org-shiftmetaup-hook nil
  14832. "Hook for functions attaching themselves to `M-S-up'.
  14833. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14834. (defvar org-shiftmetadown-hook nil
  14835. "Hook for functions attaching themselves to `M-S-down'.
  14836. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14837. (defvar org-metareturn-hook nil
  14838. "Hook for functions attaching themselves to `M-RET'.
  14839. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14840. (defvar org-shiftup-hook nil
  14841. "Hook for functions attaching themselves to `S-up'.
  14842. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14843. (defvar org-shiftup-final-hook nil
  14844. "Hook for functions attaching themselves to `S-up'.
  14845. This one runs after all other options except shift-select have been excluded.
  14846. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14847. (defvar org-shiftdown-hook nil
  14848. "Hook for functions attaching themselves to `S-down'.
  14849. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14850. (defvar org-shiftdown-final-hook nil
  14851. "Hook for functions attaching themselves to `S-down'.
  14852. This one runs after all other options except shift-select have been excluded.
  14853. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14854. (defvar org-shiftleft-hook nil
  14855. "Hook for functions attaching themselves to `S-left'.
  14856. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14857. (defvar org-shiftleft-final-hook nil
  14858. "Hook for functions attaching themselves to `S-left'.
  14859. This one runs after all other options except shift-select have been excluded.
  14860. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14861. (defvar org-shiftright-hook nil
  14862. "Hook for functions attaching themselves to `S-right'.
  14863. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14864. (defvar org-shiftright-final-hook nil
  14865. "Hook for functions attaching themselves to `S-right'.
  14866. This one runs after all other options except shift-select have been excluded.
  14867. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14868. (defun org-modifier-cursor-error ()
  14869. "Throw an error, a modified cursor command was applied in wrong context."
  14870. (user-error "This command is active in special context like tables, headlines or items"))
  14871. (defun org-shiftselect-error ()
  14872. "Throw an error because Shift-Cursor command was applied in wrong context."
  14873. (if (and (boundp 'shift-select-mode) shift-select-mode)
  14874. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  14875. (user-error "This command works only in special context like headlines or timestamps")))
  14876. (defun org-call-for-shift-select (cmd)
  14877. (let ((this-command-keys-shift-translated t))
  14878. (call-interactively cmd)))
  14879. (defun org-shifttab (&optional arg)
  14880. "Global visibility cycling or move to previous table field.
  14881. Call `org-table-previous-field' within a table.
  14882. When ARG is nil, cycle globally through visibility states.
  14883. When ARG is a numeric prefix, show contents of this level."
  14884. (interactive "P")
  14885. (cond
  14886. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  14887. ((integerp arg)
  14888. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  14889. (message "Content view to level: %d" arg)
  14890. (org-cycle-content (prefix-numeric-value arg2))
  14891. (org-cycle-show-empty-lines t)
  14892. (setq org-cycle-global-status 'overview)
  14893. (run-hook-with-args 'org-cycle-hook 'overview)))
  14894. (t (call-interactively 'org-cycle-global))))
  14895. (defun org-shiftmetaleft ()
  14896. "Promote subtree or delete table column.
  14897. Calls `org-promote-subtree', `org-outdent-item-tree', or
  14898. `org-table-delete-column', depending on context. See the
  14899. individual commands for more information."
  14900. (interactive)
  14901. (cond
  14902. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  14903. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  14904. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  14905. ((if (not (org-region-active-p)) (org-at-item-p)
  14906. (save-excursion (goto-char (region-beginning))
  14907. (org-at-item-p)))
  14908. (call-interactively 'org-outdent-item-tree))
  14909. (t (org-modifier-cursor-error))))
  14910. (defun org-shiftmetaright ()
  14911. "Demote subtree or insert table column.
  14912. Calls `org-demote-subtree', `org-indent-item-tree', or
  14913. `org-table-insert-column', depending on context. See the
  14914. individual commands for more information."
  14915. (interactive)
  14916. (cond
  14917. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  14918. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  14919. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  14920. ((if (not (org-region-active-p)) (org-at-item-p)
  14921. (save-excursion (goto-char (region-beginning))
  14922. (org-at-item-p)))
  14923. (call-interactively 'org-indent-item-tree))
  14924. (t (org-modifier-cursor-error))))
  14925. (defun org-shiftmetaup (&optional _arg)
  14926. "Drag the line at point up.
  14927. In a table, kill the current row.
  14928. On a clock timestamp, update the value of the timestamp like `S-<up>'
  14929. but also adjust the previous clocked item in the clock history.
  14930. Everywhere else, drag the line at point up."
  14931. (interactive "P")
  14932. (cond
  14933. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  14934. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  14935. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  14936. (call-interactively 'org-timestamp-up)))
  14937. (t (call-interactively 'org-drag-line-backward))))
  14938. (defun org-shiftmetadown (&optional _arg)
  14939. "Drag the line at point down.
  14940. In a table, insert an empty row at the current line.
  14941. On a clock timestamp, update the value of the timestamp like `S-<down>'
  14942. but also adjust the previous clocked item in the clock history.
  14943. Everywhere else, drag the line at point down."
  14944. (interactive "P")
  14945. (cond
  14946. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  14947. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  14948. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  14949. (call-interactively 'org-timestamp-down)))
  14950. (t (call-interactively 'org-drag-line-forward))))
  14951. (defsubst org-hidden-tree-error ()
  14952. (user-error
  14953. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  14954. (defun org-metaleft (&optional _arg)
  14955. "Promote heading, list item at point or move table column left.
  14956. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  14957. depending on context. With no specific context, calls the Emacs
  14958. default `backward-word'. See the individual commands for more
  14959. information.
  14960. This function runs the hook `org-metaleft-hook' as a first step,
  14961. and returns at first non-nil value."
  14962. (interactive "P")
  14963. (cond
  14964. ((run-hook-with-args-until-success 'org-metaleft-hook))
  14965. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  14966. ((org-with-limited-levels
  14967. (or (org-at-heading-p)
  14968. (and (org-region-active-p)
  14969. (save-excursion
  14970. (goto-char (region-beginning))
  14971. (org-at-heading-p)))))
  14972. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  14973. (call-interactively 'org-do-promote))
  14974. ;; At an inline task.
  14975. ((org-at-heading-p)
  14976. (call-interactively 'org-inlinetask-promote))
  14977. ((or (org-at-item-p)
  14978. (and (org-region-active-p)
  14979. (save-excursion
  14980. (goto-char (region-beginning))
  14981. (org-at-item-p))))
  14982. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  14983. (call-interactively 'org-outdent-item))
  14984. (t (call-interactively 'backward-word))))
  14985. (defun org-metaright (&optional _arg)
  14986. "Demote heading, list item at point or move table column right.
  14987. In front of a drawer or a block keyword, indent it correctly.
  14988. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  14989. `org-indent-drawer' or `org-indent-block' depending on context.
  14990. With no specific context, calls the Emacs default `forward-word'.
  14991. See the individual commands for more information.
  14992. This function runs the hook `org-metaright-hook' as a first step,
  14993. and returns at first non-nil value."
  14994. (interactive "P")
  14995. (cond
  14996. ((run-hook-with-args-until-success 'org-metaright-hook))
  14997. ((org-at-table-p) (call-interactively 'org-table-move-column))
  14998. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  14999. ((org-at-block-p) (call-interactively 'org-indent-block))
  15000. ((org-with-limited-levels
  15001. (or (org-at-heading-p)
  15002. (and (org-region-active-p)
  15003. (save-excursion
  15004. (goto-char (region-beginning))
  15005. (org-at-heading-p)))))
  15006. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15007. (call-interactively 'org-do-demote))
  15008. ;; At an inline task.
  15009. ((org-at-heading-p)
  15010. (call-interactively 'org-inlinetask-demote))
  15011. ((or (org-at-item-p)
  15012. (and (org-region-active-p)
  15013. (save-excursion
  15014. (goto-char (region-beginning))
  15015. (org-at-item-p))))
  15016. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15017. (call-interactively 'org-indent-item))
  15018. (t (call-interactively 'forward-word))))
  15019. (defun org-check-for-hidden (what)
  15020. "Check if there are hidden headlines/items in the current visual line.
  15021. WHAT can be either `headlines' or `items'. If the current line is
  15022. an outline or item heading and it has a folded subtree below it,
  15023. this function returns t, nil otherwise."
  15024. (let ((re (cond
  15025. ((eq what 'headlines) org-outline-regexp-bol)
  15026. ((eq what 'items) (org-item-beginning-re))
  15027. (t (error "This should not happen"))))
  15028. beg end)
  15029. (save-excursion
  15030. (catch 'exit
  15031. (unless (org-region-active-p)
  15032. (setq beg (point-at-bol))
  15033. (beginning-of-line 2)
  15034. (while (and (not (eobp)) ;; this is like `next-line'
  15035. (org-invisible-p (1- (point))))
  15036. (beginning-of-line 2))
  15037. (setq end (point))
  15038. (goto-char beg)
  15039. (goto-char (point-at-eol))
  15040. (setq end (max end (point)))
  15041. (while (re-search-forward re end t)
  15042. (when (org-invisible-p (match-beginning 0))
  15043. (throw 'exit t))))
  15044. nil))))
  15045. (defun org-metaup (&optional _arg)
  15046. "Move subtree up or move table row up.
  15047. Calls `org-move-subtree-up' or `org-table-move-row' or
  15048. `org-move-item-up', depending on context. See the individual commands
  15049. for more information."
  15050. (interactive "P")
  15051. (cond
  15052. ((run-hook-with-args-until-success 'org-metaup-hook))
  15053. ((org-region-active-p)
  15054. (let* ((a (save-excursion
  15055. (goto-char (region-beginning))
  15056. (line-beginning-position)))
  15057. (b (save-excursion
  15058. (goto-char (region-end))
  15059. (if (bolp) (1- (point)) (line-end-position))))
  15060. (c (save-excursion
  15061. (goto-char a)
  15062. (move-beginning-of-line 0)
  15063. (point)))
  15064. (d (save-excursion
  15065. (goto-char a)
  15066. (move-end-of-line 0)
  15067. (point))))
  15068. (transpose-regions a b c d)
  15069. (goto-char c)))
  15070. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15071. ((and (featurep 'org-inlinetask)
  15072. (org-inlinetask-in-task-p))
  15073. (org-drag-element-backward))
  15074. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15075. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15076. (t (org-drag-element-backward))))
  15077. (defun org-metadown (&optional _arg)
  15078. "Move subtree down or move table row down.
  15079. Calls `org-move-subtree-down' or `org-table-move-row' or
  15080. `org-move-item-down', depending on context. See the individual
  15081. commands for more information."
  15082. (interactive "P")
  15083. (cond
  15084. ((run-hook-with-args-until-success 'org-metadown-hook))
  15085. ((org-region-active-p)
  15086. (let* ((a (save-excursion
  15087. (goto-char (region-beginning))
  15088. (line-beginning-position)))
  15089. (b (save-excursion
  15090. (goto-char (region-end))
  15091. (if (bolp) (1- (point)) (line-end-position))))
  15092. (c (save-excursion
  15093. (goto-char b)
  15094. (move-beginning-of-line (if (bolp) 1 2))
  15095. (point)))
  15096. (d (save-excursion
  15097. (goto-char b)
  15098. (move-end-of-line (if (bolp) 1 2))
  15099. (point))))
  15100. (transpose-regions a b c d)
  15101. (goto-char d)))
  15102. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15103. ((and (featurep 'org-inlinetask)
  15104. (org-inlinetask-in-task-p))
  15105. (org-drag-element-forward))
  15106. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15107. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15108. (t (org-drag-element-forward))))
  15109. (defun org-shiftup (&optional arg)
  15110. "Act on current element according to context.
  15111. Call `org-timestamp-up' or `org-priority-up', or
  15112. `org-previous-item', or `org-table-move-cell-up'. See the
  15113. individual commands for more information."
  15114. (interactive "P")
  15115. (cond
  15116. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15117. ((and org-support-shift-select (org-region-active-p))
  15118. (org-call-for-shift-select 'previous-line))
  15119. ((org-at-timestamp-p 'lax)
  15120. (call-interactively (if org-edit-timestamp-down-means-later
  15121. 'org-timestamp-down 'org-timestamp-up)))
  15122. ((and (not (eq org-support-shift-select 'always))
  15123. org-priority-enable-commands
  15124. (org-at-heading-p))
  15125. (call-interactively 'org-priority-up))
  15126. ((and (not org-support-shift-select) (org-at-item-p))
  15127. (call-interactively 'org-previous-item))
  15128. ((org-clocktable-try-shift 'up arg))
  15129. ((and (not (eq org-support-shift-select 'always))
  15130. (org-at-table-p))
  15131. (org-table-move-cell-up))
  15132. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15133. (org-support-shift-select
  15134. (org-call-for-shift-select 'previous-line))
  15135. (t (org-shiftselect-error))))
  15136. (defun org-shiftdown (&optional arg)
  15137. "Act on current element according to context.
  15138. Call `org-timestamp-down' or `org-priority-down', or
  15139. `org-next-item', or `org-table-move-cell-down'. See the
  15140. individual commands for more information."
  15141. (interactive "P")
  15142. (cond
  15143. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15144. ((and org-support-shift-select (org-region-active-p))
  15145. (org-call-for-shift-select 'next-line))
  15146. ((org-at-timestamp-p 'lax)
  15147. (call-interactively (if org-edit-timestamp-down-means-later
  15148. 'org-timestamp-up 'org-timestamp-down)))
  15149. ((and (not (eq org-support-shift-select 'always))
  15150. org-priority-enable-commands
  15151. (org-at-heading-p))
  15152. (call-interactively 'org-priority-down))
  15153. ((and (not org-support-shift-select) (org-at-item-p))
  15154. (call-interactively 'org-next-item))
  15155. ((org-clocktable-try-shift 'down arg))
  15156. ((and (not (eq org-support-shift-select 'always))
  15157. (org-at-table-p))
  15158. (org-table-move-cell-down))
  15159. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15160. (org-support-shift-select
  15161. (org-call-for-shift-select 'next-line))
  15162. (t (org-shiftselect-error))))
  15163. (defun org-shiftright (&optional arg)
  15164. "Act on the current element according to context.
  15165. This does one of the following:
  15166. - switch a timestamp at point one day into the future
  15167. - on a headline, switch to the next TODO keyword
  15168. - on an item, switch entire list to the next bullet type
  15169. - on a property line, switch to the next allowed value
  15170. - on a clocktable definition line, move time block into the future
  15171. - in a table, move a single cell right"
  15172. (interactive "P")
  15173. (cond
  15174. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15175. ((and org-support-shift-select (org-region-active-p))
  15176. (org-call-for-shift-select 'forward-char))
  15177. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15178. ((and (not (eq org-support-shift-select 'always))
  15179. (org-at-heading-p))
  15180. (let ((org-inhibit-logging
  15181. (not org-treat-S-cursor-todo-selection-as-state-change))
  15182. (org-inhibit-blocking
  15183. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15184. (org-call-with-arg 'org-todo 'right)))
  15185. ((or (and org-support-shift-select
  15186. (not (eq org-support-shift-select 'always))
  15187. (org-at-item-bullet-p))
  15188. (and (not org-support-shift-select) (org-at-item-p)))
  15189. (org-call-with-arg 'org-cycle-list-bullet nil))
  15190. ((and (not (eq org-support-shift-select 'always))
  15191. (org-at-property-p))
  15192. (call-interactively 'org-property-next-allowed-value))
  15193. ((org-clocktable-try-shift 'right arg))
  15194. ((and (not (eq org-support-shift-select 'always))
  15195. (org-at-table-p))
  15196. (org-table-move-cell-right))
  15197. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15198. (org-support-shift-select
  15199. (org-call-for-shift-select 'forward-char))
  15200. (t (org-shiftselect-error))))
  15201. (defun org-shiftleft (&optional arg)
  15202. "Act on current element according to context.
  15203. This does one of the following:
  15204. - switch a timestamp at point one day into the past
  15205. - on a headline, switch to the previous TODO keyword.
  15206. - on an item, switch entire list to the previous bullet type
  15207. - on a property line, switch to the previous allowed value
  15208. - on a clocktable definition line, move time block into the past
  15209. - in a table, move a single cell left"
  15210. (interactive "P")
  15211. (cond
  15212. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15213. ((and org-support-shift-select (org-region-active-p))
  15214. (org-call-for-shift-select 'backward-char))
  15215. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15216. ((and (not (eq org-support-shift-select 'always))
  15217. (org-at-heading-p))
  15218. (let ((org-inhibit-logging
  15219. (not org-treat-S-cursor-todo-selection-as-state-change))
  15220. (org-inhibit-blocking
  15221. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15222. (org-call-with-arg 'org-todo 'left)))
  15223. ((or (and org-support-shift-select
  15224. (not (eq org-support-shift-select 'always))
  15225. (org-at-item-bullet-p))
  15226. (and (not org-support-shift-select) (org-at-item-p)))
  15227. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15228. ((and (not (eq org-support-shift-select 'always))
  15229. (org-at-property-p))
  15230. (call-interactively 'org-property-previous-allowed-value))
  15231. ((org-clocktable-try-shift 'left arg))
  15232. ((and (not (eq org-support-shift-select 'always))
  15233. (org-at-table-p))
  15234. (org-table-move-cell-left))
  15235. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15236. (org-support-shift-select
  15237. (org-call-for-shift-select 'backward-char))
  15238. (t (org-shiftselect-error))))
  15239. (defun org-shiftcontrolright ()
  15240. "Switch to next TODO set."
  15241. (interactive)
  15242. (cond
  15243. ((and org-support-shift-select (org-region-active-p))
  15244. (org-call-for-shift-select 'forward-word))
  15245. ((and (not (eq org-support-shift-select 'always))
  15246. (org-at-heading-p))
  15247. (org-call-with-arg 'org-todo 'nextset))
  15248. (org-support-shift-select
  15249. (org-call-for-shift-select 'forward-word))
  15250. (t (org-shiftselect-error))))
  15251. (defun org-shiftcontrolleft ()
  15252. "Switch to previous TODO set."
  15253. (interactive)
  15254. (cond
  15255. ((and org-support-shift-select (org-region-active-p))
  15256. (org-call-for-shift-select 'backward-word))
  15257. ((and (not (eq org-support-shift-select 'always))
  15258. (org-at-heading-p))
  15259. (org-call-with-arg 'org-todo 'previousset))
  15260. (org-support-shift-select
  15261. (org-call-for-shift-select 'backward-word))
  15262. (t (org-shiftselect-error))))
  15263. (defun org-shiftcontrolup (&optional n)
  15264. "Change timestamps synchronously up in CLOCK log lines.
  15265. Optional argument N tells to change by that many units."
  15266. (interactive "P")
  15267. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15268. (let (org-support-shift-select)
  15269. (org-clock-timestamps-up n))
  15270. (user-error "Not at a clock log")))
  15271. (defun org-shiftcontroldown (&optional n)
  15272. "Change timestamps synchronously down in CLOCK log lines.
  15273. Optional argument N tells to change by that many units."
  15274. (interactive "P")
  15275. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15276. (let (org-support-shift-select)
  15277. (org-clock-timestamps-down n))
  15278. (user-error "Not at a clock log")))
  15279. (defun org-increase-number-at-point (&optional inc)
  15280. "Increment the number at point.
  15281. With an optional prefix numeric argument INC, increment using
  15282. this numeric value."
  15283. (interactive "p")
  15284. (if (not (number-at-point))
  15285. (user-error "Not on a number")
  15286. (unless inc (setq inc 1))
  15287. (let ((pos (point))
  15288. (beg (skip-chars-backward "-+^/*0-9eE."))
  15289. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15290. (setq nap (buffer-substring-no-properties
  15291. (+ pos beg) (+ pos beg end)))
  15292. (delete-region (+ pos beg) (+ pos beg end))
  15293. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15294. (when (org-at-table-p)
  15295. (org-table-align)
  15296. (org-table-end-of-field 1))))
  15297. (defun org-decrease-number-at-point (&optional inc)
  15298. "Decrement the number at point.
  15299. With an optional prefix numeric argument INC, decrement using
  15300. this numeric value."
  15301. (interactive "p")
  15302. (org-increase-number-at-point (- (or inc 1))))
  15303. (defun org-ctrl-c-ret ()
  15304. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15305. (interactive)
  15306. (cond
  15307. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15308. (t (call-interactively 'org-insert-heading))))
  15309. (defun org-copy-visible (beg end)
  15310. "Copy the visible parts of the region."
  15311. (interactive "r")
  15312. (let ((result ""))
  15313. (while (/= beg end)
  15314. (if (eq org-fold-core-style 'text-properties)
  15315. (progn
  15316. (while (org-invisible-p beg)
  15317. (setq beg (org-fold-next-visibility-change beg end)))
  15318. (let ((next (org-fold-next-visibility-change beg end)))
  15319. (setq result (concat result (buffer-substring beg next)))
  15320. (setq beg next)))
  15321. (when (invisible-p beg)
  15322. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15323. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15324. (setq result (concat result (buffer-substring beg next)))
  15325. (setq beg next))))
  15326. (setq deactivate-mark t)
  15327. (kill-new result)
  15328. (message "Visible strings have been copied to the kill ring.")))
  15329. (defun org-copy-special ()
  15330. "Copy region in table or copy current subtree.
  15331. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15332. context. See the individual commands for more information."
  15333. (interactive)
  15334. (call-interactively
  15335. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15336. (defun org-cut-special ()
  15337. "Cut region in table or cut current subtree.
  15338. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15339. context. See the individual commands for more information."
  15340. (interactive)
  15341. (call-interactively
  15342. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15343. (defun org-paste-special (arg)
  15344. "Paste rectangular region into table, or past subtree relative to level.
  15345. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15346. See the individual commands for more information."
  15347. (interactive "P")
  15348. (if (org-at-table-p)
  15349. (org-table-paste-rectangle)
  15350. (org-paste-subtree arg)))
  15351. (defun org-edit-special (&optional arg)
  15352. "Call a special editor for the element at point.
  15353. When at a table, call the formula editor with `org-table-edit-formulas'.
  15354. When in a source code block, call `org-edit-src-code'.
  15355. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15356. When in an export block, call `org-edit-export-block'.
  15357. When in a LaTeX environment, call `org-edit-latex-environment'.
  15358. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15359. When at a footnote reference, call `org-edit-footnote-reference'.
  15360. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15361. When at an active timestamp, call `org-time-stamp'.
  15362. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15363. On a link, call `ffap' to visit the link at point.
  15364. Otherwise, return a user error."
  15365. (interactive "P")
  15366. (let ((element (org-element-at-point)))
  15367. (barf-if-buffer-read-only)
  15368. (pcase (org-element-type element)
  15369. (`src-block
  15370. (if (not arg) (org-edit-src-code)
  15371. (let* ((info (org-babel-get-src-block-info))
  15372. (lang (nth 0 info))
  15373. (params (nth 2 info))
  15374. (session (cdr (assq :session params))))
  15375. (if (not session) (org-edit-src-code)
  15376. ;; At a source block with a session and function called
  15377. ;; with an ARG: switch to the buffer related to the
  15378. ;; inferior process.
  15379. (switch-to-buffer
  15380. (funcall (intern (concat "org-babel-prep-session:" lang))
  15381. session params))))))
  15382. (`keyword
  15383. (unless (member (org-element-property :key element)
  15384. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15385. (user-error "No special environment to edit here"))
  15386. (let ((value (org-element-property :value element)))
  15387. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15388. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15389. (or (match-string 1 value)
  15390. (match-string 0 value)))))
  15391. (when (org-url-p file)
  15392. (user-error "Files located with a URL cannot be edited"))
  15393. (org-link-open-from-string
  15394. (format "[[%s]]" (expand-file-name file))))))
  15395. (`table
  15396. (if (eq (org-element-property :type element) 'table.el)
  15397. (org-edit-table.el)
  15398. (call-interactively 'org-table-edit-formulas)))
  15399. ;; Only Org tables contain `table-row' type elements.
  15400. (`table-row (call-interactively 'org-table-edit-formulas))
  15401. (`example-block (org-edit-src-code))
  15402. (`export-block (org-edit-export-block))
  15403. (`fixed-width (org-edit-fixed-width-region))
  15404. (`latex-environment (org-edit-latex-environment))
  15405. (`planning
  15406. (let ((proplist (cadr element)))
  15407. (mapc #'call-interactively
  15408. (remq nil
  15409. (list
  15410. (when (plist-get proplist :deadline) #'org-deadline)
  15411. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15412. (_
  15413. ;; No notable element at point. Though, we may be at a link or
  15414. ;; a footnote reference, which are objects. Thus, scan deeper.
  15415. (let ((context (org-element-context element)))
  15416. (pcase (org-element-type context)
  15417. (`footnote-reference (org-edit-footnote-reference))
  15418. (`inline-src-block (org-edit-inline-src-code))
  15419. (`latex-fragment (org-edit-latex-fragment))
  15420. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15421. (call-interactively #'org-time-stamp-inactive)
  15422. (call-interactively #'org-time-stamp)))
  15423. (`link (call-interactively #'ffap))
  15424. (_ (user-error "No special environment to edit here"))))))))
  15425. (defun org-ctrl-c-ctrl-c (&optional arg)
  15426. "Set tags in headline, or update according to changed information at point.
  15427. This command does many different things, depending on context:
  15428. - If column view is active, in agenda or org buffers, quit it.
  15429. - If there are highlights, remove them.
  15430. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15431. this is what we do.
  15432. - If the cursor is on a statistics cookie, update it.
  15433. - If the cursor is in a headline, in an agenda or an org buffer,
  15434. prompt for tags and insert them into the current line, aligned
  15435. to `org-tags-column'. When called with prefix arg, realign all
  15436. tags in the current buffer.
  15437. - If the cursor is in one of the special #+KEYWORD lines, this
  15438. triggers scanning the buffer for these lines and updating the
  15439. information.
  15440. - If the cursor is inside a table, realign the table. This command
  15441. works even if the automatic table editor has been turned off.
  15442. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15443. the entire table.
  15444. - If the cursor is at a footnote reference or definition, jump to
  15445. the corresponding definition or references, respectively.
  15446. - If the cursor is a the beginning of a dynamic block, update it.
  15447. - If the current buffer is a capture buffer, close note and file it.
  15448. - If the cursor is on a <<<target>>>, update radio targets and
  15449. corresponding links in this buffer.
  15450. - If the cursor is on a numbered item in a plain list, renumber the
  15451. ordered list.
  15452. - If the cursor is on a checkbox, toggle it.
  15453. - If the cursor is on a code block, evaluate it. The variable
  15454. `org-confirm-babel-evaluate' can be used to control prompting
  15455. before code block evaluation, by default every code block
  15456. evaluation requires confirmation. Code block evaluation can be
  15457. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15458. (interactive "P")
  15459. (cond
  15460. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15461. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15462. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15463. (org-remove-occur-highlights)
  15464. (message "Temporary highlights/overlays removed from current buffer"))
  15465. ((and (local-variable-p 'org-finish-function)
  15466. (fboundp org-finish-function))
  15467. (funcall org-finish-function))
  15468. ((org-babel-hash-at-point))
  15469. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15470. (t
  15471. (let* ((context
  15472. (org-element-lineage
  15473. (org-element-context)
  15474. ;; Limit to supported contexts.
  15475. '(babel-call clock dynamic-block footnote-definition
  15476. footnote-reference inline-babel-call inline-src-block
  15477. inlinetask item keyword node-property paragraph
  15478. plain-list planning property-drawer radio-target
  15479. src-block statistics-cookie table table-cell table-row
  15480. timestamp)
  15481. t))
  15482. (radio-list-p (org-at-radio-list-p))
  15483. (type (org-element-type context)))
  15484. ;; For convenience: at the first line of a paragraph on the same
  15485. ;; line as an item, apply function on that item instead.
  15486. (when (eq type 'paragraph)
  15487. (let ((parent (org-element-property :parent context)))
  15488. (when (and (eq (org-element-type parent) 'item)
  15489. (= (line-beginning-position)
  15490. (org-element-property :begin parent)))
  15491. (setq context parent)
  15492. (setq type 'item))))
  15493. ;; Act according to type of element or object at point.
  15494. ;;
  15495. ;; Do nothing on a blank line, except if it is contained in
  15496. ;; a source block. Hence, we first check if point is in such
  15497. ;; a block and then if it is at a blank line.
  15498. (pcase type
  15499. ((or `inline-src-block `src-block)
  15500. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15501. (org-babel-eval-wipe-error-buffer)
  15502. (org-babel-execute-src-block
  15503. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15504. ((guard (org-match-line "[ \t]*$"))
  15505. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15506. (user-error
  15507. (substitute-command-keys
  15508. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15509. ((or `babel-call `inline-babel-call)
  15510. (let ((info (org-babel-lob-get-info context)))
  15511. (when info (org-babel-execute-src-block nil info))))
  15512. (`clock (org-clock-update-time-maybe))
  15513. (`dynamic-block
  15514. (save-excursion
  15515. (goto-char (org-element-property :post-affiliated context))
  15516. (org-update-dblock)))
  15517. (`footnote-definition
  15518. (goto-char (org-element-property :post-affiliated context))
  15519. (call-interactively 'org-footnote-action))
  15520. (`footnote-reference (call-interactively #'org-footnote-action))
  15521. ((or `headline `inlinetask)
  15522. (save-excursion (goto-char (org-element-property :begin context))
  15523. (call-interactively #'org-set-tags-command)))
  15524. (`item
  15525. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15526. ;; unconditionally, whereas `C-u' will toggle its presence.
  15527. ;; Without a universal argument, if the item has a checkbox,
  15528. ;; toggle it. Otherwise repair the list.
  15529. (if (or radio-list-p
  15530. (and (boundp org-list-checkbox-radio-mode)
  15531. org-list-checkbox-radio-mode))
  15532. (org-toggle-radio-button arg)
  15533. (let* ((box (org-element-property :checkbox context))
  15534. (struct (org-element-property :structure context))
  15535. (old-struct (copy-tree struct))
  15536. (parents (org-list-parents-alist struct))
  15537. (prevs (org-list-prevs-alist struct))
  15538. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15539. (org-list-set-checkbox
  15540. (org-element-property :begin context) struct
  15541. (cond ((equal arg '(16)) "[-]")
  15542. ((and (not box) (equal arg '(4))) "[ ]")
  15543. ((or (not box) (equal arg '(4))) nil)
  15544. ((eq box 'on) "[ ]")
  15545. (t "[X]")))
  15546. ;; Mimic `org-list-write-struct' but with grabbing a return
  15547. ;; value from `org-list-struct-fix-box'.
  15548. (org-list-struct-fix-ind struct parents 2)
  15549. (org-list-struct-fix-item-end struct)
  15550. (org-list-struct-fix-bul struct prevs)
  15551. (org-list-struct-fix-ind struct parents)
  15552. (let ((block-item
  15553. (org-list-struct-fix-box struct parents prevs orderedp)))
  15554. (if (and box (equal struct old-struct))
  15555. (if (equal arg '(16))
  15556. (message "Checkboxes already reset")
  15557. (user-error "Cannot toggle this checkbox: %s"
  15558. (if (eq box 'on)
  15559. "all subitems checked"
  15560. "unchecked subitems")))
  15561. (org-list-struct-apply-struct struct old-struct)
  15562. (org-update-checkbox-count-maybe))
  15563. (when block-item
  15564. (message "Checkboxes were removed due to empty box at line %d"
  15565. (org-current-line block-item)))))))
  15566. (`plain-list
  15567. ;; At a plain list, with a double C-u argument, set
  15568. ;; checkboxes of each item to "[-]", whereas a single one
  15569. ;; will toggle their presence according to the state of the
  15570. ;; first item in the list. Without an argument, repair the
  15571. ;; list.
  15572. (if (or radio-list-p
  15573. (and (boundp org-list-checkbox-radio-mode)
  15574. org-list-checkbox-radio-mode))
  15575. (org-toggle-radio-button arg)
  15576. (let* ((begin (org-element-property :contents-begin context))
  15577. (struct (org-element-property :structure context))
  15578. (old-struct (copy-tree struct))
  15579. (first-box (save-excursion
  15580. (goto-char begin)
  15581. (looking-at org-list-full-item-re)
  15582. (match-string-no-properties 3)))
  15583. (new-box (cond ((equal arg '(16)) "[-]")
  15584. ((equal arg '(4)) (unless first-box "[ ]"))
  15585. ((equal first-box "[X]") "[ ]")
  15586. (t "[X]"))))
  15587. (cond
  15588. (arg
  15589. (dolist (pos
  15590. (org-list-get-all-items
  15591. begin struct (org-list-prevs-alist struct)))
  15592. (org-list-set-checkbox pos struct new-box)))
  15593. ((and first-box (eq (point) begin))
  15594. ;; For convenience, when point is at bol on the first
  15595. ;; item of the list and no argument is provided, simply
  15596. ;; toggle checkbox of that item, if any.
  15597. (org-list-set-checkbox begin struct new-box)))
  15598. (when (equal
  15599. (org-list-write-struct
  15600. struct (org-list-parents-alist struct) old-struct)
  15601. old-struct)
  15602. (message "Cannot update this checkbox"))
  15603. (org-update-checkbox-count-maybe))))
  15604. (`keyword
  15605. (let ((org-inhibit-startup-visibility-stuff t)
  15606. (org-startup-align-all-tables nil))
  15607. (when (boundp 'org-table-coordinate-overlays)
  15608. (mapc #'delete-overlay org-table-coordinate-overlays)
  15609. (setq org-table-coordinate-overlays nil))
  15610. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15611. (message "Local setup has been refreshed"))
  15612. ((or `property-drawer `node-property)
  15613. (call-interactively #'org-property-action))
  15614. (`radio-target
  15615. (call-interactively #'org-update-radio-target-regexp))
  15616. (`statistics-cookie
  15617. (call-interactively #'org-update-statistics-cookies))
  15618. ((or `table `table-cell `table-row)
  15619. ;; At a table, generate a plot if on the #+plot line,
  15620. ;; recalculate every field and align it otherwise. Also
  15621. ;; send the table if necessary.
  15622. (cond
  15623. ((and (org-match-line "[ \t]*#\\+plot:")
  15624. (< (point) (org-element-property :post-affiliated context)))
  15625. (org-plot/gnuplot))
  15626. ;; If the table has a `table.el' type, just give up.
  15627. ((eq (org-element-property :type context) 'table.el)
  15628. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15629. Use `\\[org-edit-special]' to edit table.el tables")))
  15630. ;; At a table row or cell, maybe recalculate line but always
  15631. ;; align table.
  15632. ((or (eq type 'table)
  15633. ;; Check if point is at a TBLFM line.
  15634. (and (eq type 'table-row)
  15635. (= (point) (org-element-property :end context))))
  15636. (save-excursion
  15637. (if (org-at-TBLFM-p)
  15638. (progn (require 'org-table)
  15639. (org-table-calc-current-TBLFM))
  15640. (goto-char (org-element-property :contents-begin context))
  15641. (org-call-with-arg 'org-table-recalculate (or arg t))
  15642. (orgtbl-send-table 'maybe))))
  15643. (t
  15644. (org-table-maybe-eval-formula)
  15645. (cond (arg (call-interactively #'org-table-recalculate))
  15646. ((org-table-maybe-recalculate-line))
  15647. (t (org-table-align))))))
  15648. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15649. (org-timestamp-change 0 'day))
  15650. ((and `nil (guard (org-at-heading-p)))
  15651. ;; When point is on an unsupported object type, we can miss
  15652. ;; the fact that it also is at a heading. Handle it here.
  15653. (call-interactively #'org-set-tags-command))
  15654. ((guard
  15655. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15656. (_
  15657. (user-error
  15658. (substitute-command-keys
  15659. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15660. (defun org-mode-restart ()
  15661. "Restart `org-mode'."
  15662. (interactive)
  15663. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15664. (funcall major-mode)
  15665. (hack-local-variables)
  15666. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15667. (org-indent-mode -1))
  15668. (org-reset-file-cache))
  15669. (message "%s restarted" major-mode))
  15670. (defun org-kill-note-or-show-branches ()
  15671. "Abort storing current note, or show just branches."
  15672. (interactive)
  15673. (cond (org-finish-function
  15674. (let ((org-note-abort t)) (funcall org-finish-function)))
  15675. ((org-before-first-heading-p)
  15676. (org-fold-show-branches-buffer)
  15677. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15678. (t
  15679. (let ((beg (progn (org-back-to-heading) (point)))
  15680. (end (save-excursion (org-end-of-subtree t t) (point))))
  15681. (org-fold-hide-subtree)
  15682. (org-fold-show-branches)
  15683. (org-fold-hide-archived-subtrees beg end)))))
  15684. (defun org-delete-indentation (&optional arg)
  15685. "Join current line to previous and fix whitespace at join.
  15686. If previous line is a headline add to headline title. Otherwise
  15687. the function calls `delete-indentation'.
  15688. I.e. with a non-nil optional argument, join the line with the
  15689. following one. If there is a region then join the lines in that
  15690. region."
  15691. (interactive "*P")
  15692. (if (save-excursion
  15693. (beginning-of-line (if arg 1 0))
  15694. (let ((case-fold-search nil))
  15695. (looking-at org-complex-heading-regexp)))
  15696. ;; At headline.
  15697. (let ((tags-column (when (match-beginning 5)
  15698. (save-excursion (goto-char (match-beginning 5))
  15699. (current-column))))
  15700. (string (concat " " (progn (when arg (forward-line 1))
  15701. (org-trim (delete-and-extract-region
  15702. (line-beginning-position)
  15703. (line-end-position)))))))
  15704. (unless (bobp) (delete-region (point) (1- (point))))
  15705. (goto-char (or (match-end 4)
  15706. (match-beginning 5)
  15707. (match-end 0)))
  15708. (skip-chars-backward " \t")
  15709. (save-excursion (insert string))
  15710. ;; Adjust alignment of tags.
  15711. (cond
  15712. ((not tags-column)) ;no tags
  15713. (org-auto-align-tags (org-align-tags))
  15714. (t (org--align-tags-here tags-column)))) ;preserve tags column
  15715. (let ((current-prefix-arg arg))
  15716. (call-interactively #'delete-indentation))))
  15717. (defun org-open-line (n)
  15718. "Insert a new row in tables, call `open-line' elsewhere.
  15719. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  15720. As a special case, when a document starts with a table, allow to
  15721. call `open-line' on the very first character."
  15722. (interactive "*p")
  15723. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  15724. (org-table-insert-row)
  15725. (open-line n)))
  15726. (defun org--newline (indent arg interactive)
  15727. "Call `newline-and-indent' or just `newline'.
  15728. If INDENT is non-nil, call `newline-and-indent' with ARG to
  15729. indent unconditionally; otherwise, call `newline' with ARG and
  15730. INTERACTIVE, which can trigger indentation if
  15731. `electric-indent-mode' is enabled."
  15732. (if indent
  15733. (org-newline-and-indent arg)
  15734. (newline arg interactive)))
  15735. (defun org-return (&optional indent arg interactive)
  15736. "Goto next table row or insert a newline.
  15737. Calls `org-table-next-row' or `newline', depending on context.
  15738. When optional INDENT argument is non-nil, call
  15739. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  15740. and INTERACTIVE.
  15741. When `org-return-follows-link' is non-nil and point is on
  15742. a timestamp or a link, call `org-open-at-point'. However, it
  15743. will not happen if point is in a table or on a \"dead\"
  15744. object (e.g., within a comment). In these case, you need to use
  15745. `org-open-at-point' directly."
  15746. (interactive "i\nP\np")
  15747. (let* ((context (if org-return-follows-link (org-element-context)
  15748. (org-element-at-point)))
  15749. (element-type (org-element-type context)))
  15750. (cond
  15751. ;; In a table, call `org-table-next-row'. However, before first
  15752. ;; column or after last one, split the table.
  15753. ((or (and (eq 'table element-type)
  15754. (not (eq 'table.el (org-element-property :type context)))
  15755. (>= (point) (org-element-property :contents-begin context))
  15756. (< (point) (org-element-property :contents-end context)))
  15757. (org-element-lineage context '(table-row table-cell) t))
  15758. (if (or (looking-at-p "[ \t]*$")
  15759. (save-excursion (skip-chars-backward " \t") (bolp)))
  15760. (insert "\n")
  15761. (org-table-justify-field-maybe)
  15762. (call-interactively #'org-table-next-row)))
  15763. ;; On a link or a timestamp, call `org-open-at-point' if
  15764. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  15765. ;; locations, e.g., in a comment, as `org-open-at-point'.
  15766. ((and org-return-follows-link
  15767. (or (and (eq 'link element-type)
  15768. ;; Ensure point is not on the white spaces after
  15769. ;; the link.
  15770. (let ((origin (point)))
  15771. (org-with-point-at (org-element-property :end context)
  15772. (skip-chars-backward " \t")
  15773. (> (point) origin))))
  15774. (org-in-regexp org-ts-regexp-both nil t)
  15775. (org-in-regexp org-tsr-regexp-both nil t)
  15776. (org-in-regexp org-link-any-re nil t)))
  15777. (call-interactively #'org-open-at-point))
  15778. ;; Insert newline in heading, but preserve tags.
  15779. ((and (not (bolp))
  15780. (let ((case-fold-search nil))
  15781. (org-match-line org-complex-heading-regexp)))
  15782. ;; At headline. Split line. However, if point is on keyword,
  15783. ;; priority cookie or tags, do not break any of them: add
  15784. ;; a newline after the headline instead.
  15785. (let ((tags-column (and (match-beginning 5)
  15786. (save-excursion (goto-char (match-beginning 5))
  15787. (current-column))))
  15788. (string
  15789. (when (and (match-end 4) (org-point-in-group (point) 4))
  15790. (delete-and-extract-region (point) (match-end 4)))))
  15791. ;; Adjust tag alignment.
  15792. (cond
  15793. ((not (and tags-column string)))
  15794. (org-auto-align-tags (org-align-tags))
  15795. (t (org--align-tags-here tags-column))) ;preserve tags column
  15796. (end-of-line)
  15797. (org-fold-show-entry)
  15798. (org--newline indent arg interactive)
  15799. (when string (save-excursion (insert (org-trim string))))))
  15800. ;; In a list, make sure indenting keeps trailing text within.
  15801. ((and (not (eolp))
  15802. (org-element-lineage context '(item)))
  15803. (let ((trailing-data
  15804. (delete-and-extract-region (point) (line-end-position))))
  15805. (org--newline indent arg interactive)
  15806. (save-excursion (insert trailing-data))))
  15807. (t
  15808. ;; Do not auto-fill when point is in an Org property drawer.
  15809. (let ((auto-fill-function (and (not (org-at-property-p))
  15810. auto-fill-function)))
  15811. (org--newline indent arg interactive))))))
  15812. (defun org-return-and-maybe-indent ()
  15813. "Goto next table row, or insert a newline, maybe indented.
  15814. Call `org-table-next-row' or `org-return', depending on context.
  15815. See the individual commands for more information.
  15816. When inserting a newline, if `org-adapt-indentation' is t:
  15817. indent the line if `electric-indent-mode' is disabled, don't
  15818. indent it if it is enabled."
  15819. (interactive)
  15820. (org-return (not electric-indent-mode)))
  15821. (defun org-ctrl-c-tab (&optional arg)
  15822. "Toggle columns width in a table, or show children.
  15823. Call `org-table-toggle-column-width' if point is in a table.
  15824. Otherwise provide a compact view of the children. ARG is the
  15825. level to hide."
  15826. (interactive "p")
  15827. (cond
  15828. ((org-at-table-p)
  15829. (call-interactively #'org-table-toggle-column-width))
  15830. ((org-before-first-heading-p)
  15831. (save-excursion
  15832. (org-fold-flag-above-first-heading)
  15833. (org-fold-hide-sublevels (or arg 1))))
  15834. (t
  15835. (org-fold-hide-subtree)
  15836. (org-fold-show-children arg))))
  15837. (defun org-ctrl-c-star ()
  15838. "Compute table, or change heading status of lines.
  15839. Calls `org-table-recalculate' or `org-toggle-heading',
  15840. depending on context."
  15841. (interactive)
  15842. (cond
  15843. ((org-at-table-p)
  15844. (call-interactively 'org-table-recalculate))
  15845. (t
  15846. ;; Convert all lines in region to list items
  15847. (call-interactively 'org-toggle-heading))))
  15848. (defun org-ctrl-c-minus ()
  15849. "Insert separator line in table or modify bullet status of line.
  15850. Also turns a plain line or a region of lines into list items.
  15851. Calls `org-table-insert-hline', `org-toggle-item', or
  15852. `org-cycle-list-bullet', depending on context."
  15853. (interactive)
  15854. (cond
  15855. ((org-at-table-p)
  15856. (call-interactively 'org-table-insert-hline))
  15857. ((org-region-active-p)
  15858. (call-interactively 'org-toggle-item))
  15859. ((org-in-item-p)
  15860. (call-interactively 'org-cycle-list-bullet))
  15861. (t
  15862. (call-interactively 'org-toggle-item))))
  15863. (defun org-toggle-heading (&optional nstars)
  15864. "Convert headings to normal text, or items or text to headings.
  15865. If there is no active region, only convert the current line.
  15866. With a `\\[universal-argument]' prefix, convert the whole list at
  15867. point into heading.
  15868. In a region:
  15869. - If the first non blank line is a headline, remove the stars
  15870. from all headlines in the region.
  15871. - If it is a normal line, turn each and every normal line (i.e.,
  15872. not an heading or an item) in the region into headings. If you
  15873. want to convert only the first line of this region, use one
  15874. universal prefix argument.
  15875. - If it is a plain list item, turn all plain list items into headings.
  15876. When converting a line into a heading, the number of stars is chosen
  15877. such that the lines become children of the current entry. However,
  15878. when a numeric prefix argument is given, its value determines the
  15879. number of stars to add."
  15880. (interactive "P")
  15881. (let ((skip-blanks
  15882. ;; Return beginning of first non-blank line, starting from
  15883. ;; line at POS.
  15884. (lambda (pos)
  15885. (save-excursion
  15886. (goto-char pos)
  15887. (while (org-at-comment-p) (forward-line))
  15888. (skip-chars-forward " \r\t\n")
  15889. (point-at-bol))))
  15890. beg end toggled)
  15891. ;; Determine boundaries of changes. If a universal prefix has
  15892. ;; been given, put the list in a region. If region ends at a bol,
  15893. ;; do not consider the last line to be in the region.
  15894. (when (and current-prefix-arg (org-at-item-p))
  15895. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  15896. (org-mark-element))
  15897. (if (org-region-active-p)
  15898. (setq beg (funcall skip-blanks (region-beginning))
  15899. end (copy-marker (save-excursion
  15900. (goto-char (region-end))
  15901. (if (bolp) (point) (point-at-eol)))))
  15902. (setq beg (funcall skip-blanks (point-at-bol))
  15903. end (copy-marker (point-at-eol))))
  15904. ;; Ensure inline tasks don't count as headings.
  15905. (org-with-limited-levels
  15906. (save-excursion
  15907. (goto-char beg)
  15908. (cond
  15909. ;; Case 1. Started at an heading: de-star headings.
  15910. ((org-at-heading-p)
  15911. (while (< (point) end)
  15912. (when (org-at-heading-p)
  15913. (looking-at org-outline-regexp) (replace-match "")
  15914. (setq toggled t))
  15915. (forward-line)))
  15916. ;; Case 2. Started at an item: change items into headlines.
  15917. ;; One star will be added by `org-list-to-subtree'.
  15918. ((org-at-item-p)
  15919. (while (< (point) end)
  15920. (when (org-at-item-p)
  15921. ;; Pay attention to cases when region ends before list.
  15922. (let* ((struct (org-list-struct))
  15923. (list-end
  15924. (min (org-list-get-bottom-point struct) (1+ end))))
  15925. (save-restriction
  15926. (narrow-to-region (point) list-end)
  15927. (insert (org-list-to-subtree
  15928. (org-list-to-lisp t)
  15929. (pcase (org-current-level)
  15930. (`nil 1)
  15931. (l (1+ (org-reduced-level l)))))
  15932. "\n")))
  15933. (setq toggled t))
  15934. (forward-line)))
  15935. ;; Case 3. Started at normal text: make every line an heading,
  15936. ;; skipping headlines and items.
  15937. (t (let* ((stars
  15938. (make-string
  15939. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  15940. (add-stars
  15941. (cond (nstars "") ; stars from prefix only
  15942. ((equal stars "") "*") ; before first heading
  15943. (org-odd-levels-only "**") ; inside heading, odd
  15944. (t "*"))) ; inside heading, oddeven
  15945. (rpl (concat stars add-stars " "))
  15946. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  15947. (while (< (point) (if (equal nstars '(4)) lend end))
  15948. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  15949. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  15950. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  15951. (forward-line)))))))
  15952. (unless toggled (message "Cannot toggle heading from here"))))
  15953. (defun org-meta-return (&optional arg)
  15954. "Insert a new heading or wrap a region in a table.
  15955. Calls `org-insert-heading', `org-insert-item' or
  15956. `org-table-wrap-region', depending on context. When called with
  15957. an argument, unconditionally call `org-insert-heading'."
  15958. (interactive "P")
  15959. (org-fold-check-before-invisible-edit 'insert)
  15960. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  15961. (call-interactively (cond (arg #'org-insert-heading)
  15962. ((org-at-table-p) #'org-table-wrap-region)
  15963. ((org-in-item-p) #'org-insert-item)
  15964. (t #'org-insert-heading)))))
  15965. ;;; Menu entries
  15966. (defsubst org-in-subtree-not-table-p ()
  15967. "Are we in a subtree and not in a table?"
  15968. (and (not (org-before-first-heading-p))
  15969. (not (org-at-table-p))))
  15970. ;; Define the Org mode menus
  15971. (easy-menu-define org-org-menu org-mode-map "Org menu."
  15972. `("Org"
  15973. ("Show/Hide"
  15974. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  15975. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  15976. ["Sparse Tree..." org-sparse-tree t]
  15977. ["Reveal Context" org-fold-reveal t]
  15978. ["Show All" org-fold-show-all t]
  15979. "--"
  15980. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  15981. "--"
  15982. ["New Heading" org-insert-heading t]
  15983. ("Navigate Headings"
  15984. ["Up" outline-up-heading t]
  15985. ["Next" outline-next-visible-heading t]
  15986. ["Previous" outline-previous-visible-heading t]
  15987. ["Next Same Level" outline-forward-same-level t]
  15988. ["Previous Same Level" outline-backward-same-level t]
  15989. "--"
  15990. ["Jump" org-goto t])
  15991. ("Edit Structure"
  15992. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  15993. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  15994. "--"
  15995. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  15996. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  15997. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  15998. "--"
  15999. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16000. "--"
  16001. ["Copy visible text" org-copy-visible t]
  16002. "--"
  16003. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16004. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16005. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16006. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16007. "--"
  16008. ["Sort Region/Children" org-sort t]
  16009. "--"
  16010. ["Convert to odd levels" org-convert-to-odd-levels t]
  16011. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16012. ("Editing"
  16013. ["Emphasis..." org-emphasize t]
  16014. ["Add block structure" org-insert-structure-template t]
  16015. ["Edit Source Example" org-edit-special t]
  16016. "--"
  16017. ["Footnote new/jump" org-footnote-action t]
  16018. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16019. ("Archive"
  16020. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16021. "--"
  16022. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16023. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16024. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16025. "--"
  16026. ("Hyperlinks"
  16027. ["Store Link (Global)" org-store-link t]
  16028. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16029. ["Insert Link" org-insert-link t]
  16030. ["Follow Link" org-open-at-point t]
  16031. "--"
  16032. ["Next link" org-next-link t]
  16033. ["Previous link" org-previous-link t]
  16034. "--"
  16035. ["Descriptive Links"
  16036. org-toggle-link-display
  16037. :style radio
  16038. :selected org-descriptive-links
  16039. ]
  16040. ["Literal Links"
  16041. org-toggle-link-display
  16042. :style radio
  16043. :selected (not org-descriptive-links)])
  16044. "--"
  16045. ("TODO Lists"
  16046. ["TODO/DONE/-" org-todo t]
  16047. ("Select keyword"
  16048. ["Next keyword" org-shiftright (org-at-heading-p)]
  16049. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16050. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16051. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16052. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16053. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16054. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16055. "--"
  16056. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16057. :selected org-enforce-todo-dependencies :style toggle :active t]
  16058. "Settings for tree at point"
  16059. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16060. :selected (org-entry-get nil "ORDERED")
  16061. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16062. ["Do Children parallel" org-toggle-ordered-property :style radio
  16063. :selected (not (org-entry-get nil "ORDERED"))
  16064. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16065. "--"
  16066. ["Set Priority" org-priority t]
  16067. ["Priority Up" org-shiftup t]
  16068. ["Priority Down" org-shiftdown t]
  16069. "--"
  16070. ["Get news from all feeds" org-feed-update-all t]
  16071. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16072. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16073. ("TAGS and Properties"
  16074. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16075. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16076. "--"
  16077. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16078. ["Column view of properties" org-columns t]
  16079. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16080. ("Dates and Scheduling"
  16081. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16082. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16083. ("Change Date"
  16084. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16085. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16086. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16087. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16088. ["Compute Time Range" org-evaluate-time-range t]
  16089. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16090. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16091. "--"
  16092. ["Custom time format" org-toggle-time-stamp-overlays
  16093. :style radio :selected org-display-custom-times]
  16094. "--"
  16095. ["Goto Calendar" org-goto-calendar t]
  16096. ["Date from Calendar" org-date-from-calendar t]
  16097. "--"
  16098. ["Start/Restart Timer" org-timer-start t]
  16099. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16100. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16101. ["Insert Timer String" org-timer t]
  16102. ["Insert Timer Item" org-timer-item t])
  16103. ("Logging work"
  16104. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16105. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16106. ["Clock out" org-clock-out t]
  16107. ["Clock cancel" org-clock-cancel t]
  16108. "--"
  16109. ["Mark as default task" org-clock-mark-default-task t]
  16110. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16111. ["Goto running clock" org-clock-goto t]
  16112. "--"
  16113. ["Display times" org-clock-display t]
  16114. ["Create clock table" org-clock-report t]
  16115. "--"
  16116. ["Record DONE time"
  16117. (progn (setq org-log-done (not org-log-done))
  16118. (message "Switching to %s will %s record a timestamp"
  16119. (car org-done-keywords)
  16120. (if org-log-done "automatically" "not")))
  16121. :style toggle :selected org-log-done])
  16122. "--"
  16123. ["Agenda Command..." org-agenda t]
  16124. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16125. ("File List for Agenda")
  16126. ("Special views current file"
  16127. ["TODO Tree" org-show-todo-tree t]
  16128. ["Check Deadlines" org-check-deadlines t]
  16129. ["Tags/Property tree" org-match-sparse-tree t])
  16130. "--"
  16131. ["Export/Publish..." org-export-dispatch t]
  16132. ("LaTeX"
  16133. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16134. :style toggle :selected org-cdlatex-mode]
  16135. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16136. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16137. ["Modify math symbol" org-cdlatex-math-modify
  16138. (org-inside-LaTeX-fragment-p)]
  16139. ["Insert citation" org-reftex-citation t])
  16140. "--"
  16141. ("Documentation"
  16142. ["Show Version" org-version t]
  16143. ["Info Documentation" org-info t]
  16144. ["Browse Org News" org-browse-news t])
  16145. ("Customize"
  16146. ["Browse Org Group" org-customize t]
  16147. "--"
  16148. ["Expand This Menu" org-create-customize-menu t])
  16149. ["Send bug report" org-submit-bug-report t]
  16150. "--"
  16151. ("Refresh/Reload"
  16152. ["Refresh setup current buffer" org-mode-restart t]
  16153. ["Reload Org (after update)" org-reload t]
  16154. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16155. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16156. '("Table"
  16157. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16158. ["Next Field" org-cycle (org-at-table-p)]
  16159. ["Previous Field" org-shifttab (org-at-table-p)]
  16160. ["Next Row" org-return (org-at-table-p)]
  16161. "--"
  16162. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16163. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16164. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16165. "--"
  16166. ("Column"
  16167. ["Move Column Left" org-metaleft (org-at-table-p)]
  16168. ["Move Column Right" org-metaright (org-at-table-p)]
  16169. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16170. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16171. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16172. ("Row"
  16173. ["Move Row Up" org-metaup (org-at-table-p)]
  16174. ["Move Row Down" org-metadown (org-at-table-p)]
  16175. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16176. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16177. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16178. "--"
  16179. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16180. ("Rectangle"
  16181. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16182. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16183. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16184. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16185. "--"
  16186. ("Calculate"
  16187. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16188. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16189. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16190. "--"
  16191. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16192. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16193. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16194. "--"
  16195. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16196. "--"
  16197. ["Sum Column/Rectangle" org-table-sum
  16198. (or (org-at-table-p) (org-region-active-p))]
  16199. ["Which Column?" org-table-current-column (org-at-table-p)])
  16200. ["Debug Formulas"
  16201. org-table-toggle-formula-debugger
  16202. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16203. ["Show Col/Row Numbers"
  16204. org-table-toggle-coordinate-overlays
  16205. :style toggle
  16206. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16207. "--"
  16208. ["Create" org-table-create (not (org-at-table-p))]
  16209. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16210. ["Import from File" org-table-import (not (org-at-table-p))]
  16211. ["Export to File" org-table-export (org-at-table-p)]
  16212. "--"
  16213. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16214. "--"
  16215. ("Plot"
  16216. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16217. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16218. (defun org-info (&optional node)
  16219. "Read documentation for Org in the info system.
  16220. With optional NODE, go directly to that node."
  16221. (interactive)
  16222. (info (format "(org)%s" (or node ""))))
  16223. (defun org-browse-news ()
  16224. "Browse the news for the latest major release."
  16225. (interactive)
  16226. (browse-url "https://orgmode.org/Changes.html"))
  16227. ;;;###autoload
  16228. (defun org-submit-bug-report ()
  16229. "Submit a bug report on Org via mail.
  16230. Don't hesitate to report any problems or inaccurate documentation.
  16231. If you don't have setup sending mail from (X)Emacs, please copy the
  16232. output buffer into your mail program, as it gives us important
  16233. information about your Org version and configuration."
  16234. (interactive)
  16235. (require 'reporter)
  16236. (defvar reporter-prompt-for-summary-p)
  16237. (org-load-modules-maybe)
  16238. (org-require-autoloaded-modules)
  16239. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16240. (reporter-submit-bug-report
  16241. "emacs-orgmode@gnu.org"
  16242. (org-version nil 'full)
  16243. (let (list)
  16244. (save-window-excursion
  16245. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16246. (delete-other-windows)
  16247. (erase-buffer)
  16248. (insert "You are about to submit a bug report to the Org mailing list.
  16249. If your report is about Org installation, please read this section:
  16250. https://orgmode.org/org.html#Installation
  16251. Please read https://orgmode.org/org.html#Feedback on how to make
  16252. a good report, it will help Org contributors fixing your problem.
  16253. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16254. if the issue you are about to raise has already been dealt with.
  16255. We also would like to add your full Org and Outline configuration
  16256. to the bug report. It will help us debugging the issue.
  16257. *HOWEVER*, some variables you have customized may contain private
  16258. information. The names of customers, colleagues, or friends, might
  16259. appear in the form of file names, tags, todo states or search strings.
  16260. If you answer \"yes\" to the prompt, you might want to check and remove
  16261. such private information before sending the email.")
  16262. (add-text-properties (point-min) (point-max) '(face org-warning))
  16263. (when (yes-or-no-p "Include your Org configuration ")
  16264. (mapatoms
  16265. (lambda (v)
  16266. (and (boundp v)
  16267. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16268. (or (and (symbol-value v)
  16269. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16270. (and
  16271. (get v 'custom-type) (get v 'standard-value)
  16272. (not (equal (symbol-value v)
  16273. (eval (car (get v 'standard-value)) t)))))
  16274. (push v list)))))
  16275. (kill-buffer (get-buffer "*Warn about privacy*"))
  16276. list))
  16277. nil nil
  16278. "Remember to cover the basics, that is, what you expected to happen and
  16279. what in fact did happen. You don't know how to make a good report? See
  16280. https://orgmode.org/manual/Feedback.html#Feedback
  16281. Your bug report will be posted to the Org mailing list.
  16282. ------------------------------------------------------------------------")
  16283. (save-excursion
  16284. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16285. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16286. (defun org-install-agenda-files-menu ()
  16287. "Install agenda file menu."
  16288. (let ((bl (buffer-list)))
  16289. (save-excursion
  16290. (while bl
  16291. (set-buffer (pop bl))
  16292. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16293. (when (derived-mode-p 'org-mode)
  16294. (easy-menu-change
  16295. '("Org") "File List for Agenda"
  16296. (append
  16297. (list
  16298. ["Edit File List" (org-edit-agenda-file-list) t]
  16299. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16300. ["Remove Current File from List" org-remove-file t]
  16301. ["Cycle through agenda files" org-cycle-agenda-files t]
  16302. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16303. "--")
  16304. (mapcar 'org-file-menu-entry
  16305. ;; Prevent initialization from failing.
  16306. (ignore-errors (org-agenda-files t)))))))))
  16307. ;;;; Documentation
  16308. (defun org-require-autoloaded-modules ()
  16309. (interactive)
  16310. (mapc #'require
  16311. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16312. org-table org-timer)))
  16313. ;;;###autoload
  16314. (defun org-reload (&optional uncompiled)
  16315. "Reload all Org Lisp files.
  16316. With prefix arg UNCOMPILED, load the uncompiled versions."
  16317. (interactive "P")
  16318. (require 'loadhist)
  16319. (let* ((org-dir (org-find-library-dir "org"))
  16320. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16321. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16322. (remove-re (format "\\`%s\\'"
  16323. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16324. (feats (delete-dups
  16325. (mapcar 'file-name-sans-extension
  16326. (mapcar 'file-name-nondirectory
  16327. (delq nil
  16328. (mapcar 'feature-file
  16329. features))))))
  16330. (lfeat (append
  16331. (sort
  16332. (setq feats
  16333. (delq nil (mapcar
  16334. (lambda (f)
  16335. (if (and (string-match feature-re f)
  16336. (not (string-match remove-re f)))
  16337. f nil))
  16338. feats)))
  16339. 'string-lessp)
  16340. (list "org-version" "org")))
  16341. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16342. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16343. load-uncore load-misses)
  16344. (setq load-misses
  16345. (delq 't
  16346. (mapcar (lambda (f)
  16347. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16348. (and (string= org-dir contrib-dir)
  16349. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16350. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16351. (push f load-uncore)
  16352. 't)
  16353. f))
  16354. lfeat)))
  16355. (when load-uncore
  16356. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16357. (if (> (length load-uncore) 1) "s were" " was")
  16358. (reverse load-uncore)))
  16359. (if load-misses
  16360. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16361. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16362. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16363. ;;;###autoload
  16364. (defun org-customize ()
  16365. "Call the customize function with org as argument."
  16366. (interactive)
  16367. (org-load-modules-maybe)
  16368. (org-require-autoloaded-modules)
  16369. (customize-browse 'org))
  16370. (defun org-create-customize-menu ()
  16371. "Create a full customization menu for Org mode, insert it into the menu."
  16372. (interactive)
  16373. (org-load-modules-maybe)
  16374. (org-require-autoloaded-modules)
  16375. (easy-menu-change
  16376. '("Org") "Customize"
  16377. `(["Browse Org group" org-customize t]
  16378. "--"
  16379. ,(customize-menu-create 'org)
  16380. ["Set" Custom-set t]
  16381. ["Save" Custom-save t]
  16382. ["Reset to Current" Custom-reset-current t]
  16383. ["Reset to Saved" Custom-reset-saved t]
  16384. ["Reset to Standard Settings" Custom-reset-standard t]))
  16385. (message "\"Org\"-menu now contains full customization menu"))
  16386. ;;;; Miscellaneous stuff
  16387. ;;; Generally useful functions
  16388. (defun org-in-clocktable-p ()
  16389. "Check if the cursor is in a clocktable."
  16390. (let ((pos (point)) start)
  16391. (save-excursion
  16392. (end-of-line 1)
  16393. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16394. (setq start (match-beginning 0))
  16395. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16396. (>= (match-end 0) pos)
  16397. start))))
  16398. (defun org-in-verbatim-emphasis ()
  16399. (save-match-data
  16400. (and (org-in-regexp org-verbatim-re 2)
  16401. (>= (point) (match-beginning 3))
  16402. (<= (point) (match-end 4)))))
  16403. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16404. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16405. (if (and marker (marker-buffer marker)
  16406. (buffer-live-p (marker-buffer marker)))
  16407. (progn
  16408. (pop-to-buffer-same-window (marker-buffer marker))
  16409. (when (or (> marker (point-max)) (< marker (point-min)))
  16410. (widen))
  16411. (goto-char marker)
  16412. (org-fold-show-context 'org-goto))
  16413. (if bookmark
  16414. (bookmark-jump bookmark)
  16415. (error "Cannot find location"))))
  16416. (defun org-quote-csv-field (s)
  16417. "Quote field for inclusion in CSV material."
  16418. (if (string-match "[\",]" s)
  16419. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16420. s))
  16421. (defun org-force-self-insert (N)
  16422. "Needed to enforce self-insert under remapping."
  16423. (interactive "p")
  16424. (self-insert-command N))
  16425. (defun org-quote-vert (s)
  16426. "Replace \"|\" with \"\\vert\"."
  16427. (while (string-match "|" s)
  16428. (setq s (replace-match "\\vert" t t s)))
  16429. s)
  16430. (defun org-uuidgen-p (s)
  16431. "Is S an ID created by UUIDGEN?"
  16432. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16433. (defun org-in-src-block-p (&optional inside element)
  16434. "Whether point is in a code source block.
  16435. When INSIDE is non-nil, don't consider we are within a source
  16436. block when point is at #+BEGIN_SRC or #+END_SRC.
  16437. When ELEMENT is provided, it is considered to be element at point."
  16438. (save-match-data (setq element (or element (org-element-at-point))))
  16439. (when (eq 'src-block (org-element-type element))
  16440. (or (not inside)
  16441. (not (or (= (line-beginning-position)
  16442. (org-element-property :post-affiliated element))
  16443. (= (1+ (line-end-position))
  16444. (- (org-element-property :end element)
  16445. (org-element-property :post-blank element))))))))
  16446. (defun org-context ()
  16447. "Return a list of contexts of the current cursor position.
  16448. If several contexts apply, all are returned.
  16449. Each context entry is a list with a symbol naming the context, and
  16450. two positions indicating start and end of the context. Possible
  16451. contexts are:
  16452. :headline anywhere in a headline
  16453. :headline-stars on the leading stars in a headline
  16454. :todo-keyword on a TODO keyword (including DONE) in a headline
  16455. :tags on the TAGS in a headline
  16456. :priority on the priority cookie in a headline
  16457. :item on the first line of a plain list item
  16458. :item-bullet on the bullet/number of a plain list item
  16459. :checkbox on the checkbox in a plain list item
  16460. :table in an Org table
  16461. :table-special on a special filed in a table
  16462. :table-table in a table.el table
  16463. :clocktable in a clocktable
  16464. :src-block in a source block
  16465. :link on a hyperlink
  16466. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16467. :latex-fragment on a LaTeX fragment
  16468. :latex-preview on a LaTeX fragment with overlaid preview image
  16469. This function expects the position to be visible because it uses font-lock
  16470. faces as a help to recognize the following contexts: :table-special, :link,
  16471. and :keyword."
  16472. (let* ((f (get-text-property (point) 'face))
  16473. (faces (if (listp f) f (list f)))
  16474. (case-fold-search t)
  16475. (p (point)) clist o)
  16476. ;; First the large context
  16477. (cond
  16478. ((org-at-heading-p)
  16479. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16480. (when (progn
  16481. (beginning-of-line 1)
  16482. (looking-at org-todo-line-tags-regexp))
  16483. (push (org-point-in-group p 1 :headline-stars) clist)
  16484. (push (org-point-in-group p 2 :todo-keyword) clist)
  16485. (push (org-point-in-group p 4 :tags) clist))
  16486. (goto-char p)
  16487. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16488. (when (looking-at "\\[#[A-Z0-9]\\]")
  16489. (push (org-point-in-group p 0 :priority) clist)))
  16490. ((org-at-item-p)
  16491. (push (org-point-in-group p 2 :item-bullet) clist)
  16492. (push (list :item (point-at-bol)
  16493. (save-excursion (org-end-of-item) (point)))
  16494. clist)
  16495. (and (org-at-item-checkbox-p)
  16496. (push (org-point-in-group p 0 :checkbox) clist)))
  16497. ((org-at-table-p)
  16498. (push (list :table (org-table-begin) (org-table-end)) clist)
  16499. (when (memq 'org-formula faces)
  16500. (push (list :table-special
  16501. (previous-single-property-change p 'face)
  16502. (next-single-property-change p 'face))
  16503. clist)))
  16504. ((org-at-table-p 'any)
  16505. (push (list :table-table) clist)))
  16506. (goto-char p)
  16507. (let ((case-fold-search t))
  16508. ;; New the "medium" contexts: clocktables, source blocks
  16509. (cond ((org-in-clocktable-p)
  16510. (push (list :clocktable
  16511. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16512. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16513. (match-beginning 1))
  16514. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16515. (match-end 0)))
  16516. clist))
  16517. ((org-in-src-block-p)
  16518. (push (list :src-block
  16519. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16520. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16521. (match-beginning 1))
  16522. (and (search-forward "#+END_SRC" nil t)
  16523. (match-beginning 0)))
  16524. clist))))
  16525. (goto-char p)
  16526. ;; Now the small context
  16527. (cond
  16528. ((org-at-timestamp-p)
  16529. (push (org-point-in-group p 0 :timestamp) clist))
  16530. ((memq 'org-link faces)
  16531. (push (list :link
  16532. (previous-single-property-change p 'face)
  16533. (next-single-property-change p 'face))
  16534. clist))
  16535. ((memq 'org-special-keyword faces)
  16536. (push (list :keyword
  16537. (previous-single-property-change p 'face)
  16538. (next-single-property-change p 'face))
  16539. clist))
  16540. ((setq o (cl-some
  16541. (lambda (o)
  16542. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16543. o))
  16544. (overlays-at (point))))
  16545. (push (list :latex-fragment
  16546. (overlay-start o) (overlay-end o))
  16547. clist)
  16548. (push (list :latex-preview
  16549. (overlay-start o) (overlay-end o))
  16550. clist))
  16551. ((org-inside-LaTeX-fragment-p)
  16552. ;; FIXME: positions wrong.
  16553. (push (list :latex-fragment (point) (point)) clist)))
  16554. (setq clist (nreverse (delq nil clist)))
  16555. clist))
  16556. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16557. "Non-nil when point is between matches of START-RE and END-RE.
  16558. Also return a non-nil value when point is on one of the matches.
  16559. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16560. buffer positions. Default values are the positions of headlines
  16561. surrounding the point.
  16562. The functions returns a cons cell whose car (resp. cdr) is the
  16563. position before START-RE (resp. after END-RE)."
  16564. (save-match-data
  16565. (let ((pos (point))
  16566. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16567. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16568. beg end)
  16569. (save-excursion
  16570. ;; Point is on a block when on START-RE or if START-RE can be
  16571. ;; found before it...
  16572. (and (or (org-in-regexp start-re)
  16573. (re-search-backward start-re limit-up t))
  16574. (setq beg (match-beginning 0))
  16575. ;; ... and END-RE after it...
  16576. (goto-char (match-end 0))
  16577. (re-search-forward end-re limit-down t)
  16578. (> (setq end (match-end 0)) pos)
  16579. ;; ... without another START-RE in-between.
  16580. (goto-char (match-beginning 0))
  16581. (not (re-search-backward start-re (1+ beg) t))
  16582. ;; Return value.
  16583. (cons beg end))))))
  16584. (defun org-in-block-p (names)
  16585. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16586. NAMES is a list of strings containing names of blocks.
  16587. Return first block name matched, or nil. Beware that in case of
  16588. nested blocks, the returned name may not belong to the closest
  16589. block from point."
  16590. (save-match-data
  16591. (catch 'exit
  16592. (let ((case-fold-search t)
  16593. (lim-up (save-excursion (outline-previous-heading)))
  16594. (lim-down (save-excursion (outline-next-heading))))
  16595. (dolist (name names)
  16596. (let ((n (regexp-quote name)))
  16597. (when (org-between-regexps-p
  16598. (concat "^[ \t]*#\\+begin_" n)
  16599. (concat "^[ \t]*#\\+end_" n)
  16600. lim-up lim-down)
  16601. (throw 'exit n)))))
  16602. nil)))
  16603. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16604. "Call `multi-occur' with buffers for all agenda files."
  16605. (interactive "sOrg-files matching: ")
  16606. (let* ((files (org-agenda-files))
  16607. (tnames (mapcar #'file-truename files))
  16608. (extra org-agenda-text-search-extra-files))
  16609. (when (eq (car extra) 'agenda-archives)
  16610. (setq extra (cdr extra))
  16611. (setq files (org-add-archive-files files)))
  16612. (dolist (f extra)
  16613. (unless (member (file-truename f) tnames)
  16614. (unless (member f files) (setq files (append files (list f))))
  16615. (setq tnames (append tnames (list (file-truename f))))))
  16616. (multi-occur
  16617. (mapcar (lambda (x)
  16618. (with-current-buffer
  16619. ;; FIXME: Why not just (find-file-noselect x)?
  16620. ;; Is it to avoid the "revert buffer" prompt?
  16621. (or (get-file-buffer x) (find-file-noselect x))
  16622. (widen)
  16623. (current-buffer)))
  16624. files)
  16625. regexp)))
  16626. (add-hook 'occur-mode-find-occurrence-hook
  16627. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16628. (defun org-occur-link-in-agenda-files ()
  16629. "Create a link and search for it in the agendas.
  16630. The link is not stored in `org-stored-links', it is just created
  16631. for the search purpose."
  16632. (interactive)
  16633. (let ((link (condition-case nil
  16634. (org-store-link nil)
  16635. (error "Unable to create a link to here"))))
  16636. (org-occur-in-agenda-files (regexp-quote link))))
  16637. (defun org-back-over-empty-lines ()
  16638. "Move backwards over whitespace, to the beginning of the first empty line.
  16639. Returns the number of empty lines passed."
  16640. (let ((pos (point)))
  16641. (if (cdr (assq 'heading org-blank-before-new-entry))
  16642. (skip-chars-backward " \t\n\r")
  16643. (unless (eobp)
  16644. (forward-line -1)))
  16645. (beginning-of-line 2)
  16646. (goto-char (min (point) pos))
  16647. (count-lines (point) pos)))
  16648. ;;; TODO: Only called once, from ox-odt which should probably use
  16649. ;;; org-export-inline-image-p or something.
  16650. (defun org-file-image-p (file)
  16651. "Return non-nil if FILE is an image."
  16652. (save-match-data
  16653. (string-match (image-file-name-regexp) file)))
  16654. (defun org-get-cursor-date (&optional with-time)
  16655. "Return the date at cursor in as a time.
  16656. This works in the calendar and in the agenda, anywhere else it just
  16657. returns the current time.
  16658. If WITH-TIME is non-nil, returns the time of the event at point (in
  16659. the agenda) or the current time of the day; otherwise returns the
  16660. earliest time on the cursor date that Org treats as that date
  16661. (bearing in mind `org-extend-today-until')."
  16662. (let (date day defd tp hod mod)
  16663. (when with-time
  16664. (setq tp (get-text-property (point) 'time))
  16665. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16666. (setq hod (string-to-number (match-string 1 tp))
  16667. mod (string-to-number (match-string 2 tp))))
  16668. (or tp (let ((now (decode-time)))
  16669. (setq hod (nth 2 now)
  16670. mod (nth 1 now)))))
  16671. (cond
  16672. ((eq major-mode 'calendar-mode)
  16673. (setq date (calendar-cursor-to-date)
  16674. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16675. (nth 1 date) (nth 0 date) (nth 2 date))))
  16676. ((eq major-mode 'org-agenda-mode)
  16677. (setq day (get-text-property (point) 'day))
  16678. (when day
  16679. (setq date (calendar-gregorian-from-absolute day)
  16680. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16681. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16682. (or defd (current-time))))
  16683. (defun org-mark-subtree (&optional up)
  16684. "Mark the current subtree.
  16685. This puts point at the start of the current subtree, and mark at
  16686. the end. If a numeric prefix UP is given, move up into the
  16687. hierarchy of headlines by UP levels before marking the subtree."
  16688. (interactive "P")
  16689. (org-with-limited-levels
  16690. (cond ((org-at-heading-p) (beginning-of-line))
  16691. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16692. (t (outline-previous-visible-heading 1))))
  16693. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16694. (if (called-interactively-p 'any)
  16695. (call-interactively 'org-mark-element)
  16696. (org-mark-element)))
  16697. ;;; Indentation
  16698. (defvar org-element-greater-elements)
  16699. (defun org--get-expected-indentation (element contentsp)
  16700. "Expected indentation column for current line, according to ELEMENT.
  16701. ELEMENT is an element containing point. CONTENTSP is non-nil
  16702. when indentation is to be computed according to contents of
  16703. ELEMENT."
  16704. (let ((type (org-element-type element))
  16705. (start (org-element-property :begin element))
  16706. (post-affiliated (org-element-property :post-affiliated element)))
  16707. (org-with-wide-buffer
  16708. (cond
  16709. (contentsp
  16710. (cl-case type
  16711. ((diary-sexp footnote-definition) 0)
  16712. (section
  16713. (org--get-expected-indentation
  16714. (org-element-property :parent element)
  16715. t))
  16716. ((headline inlinetask nil)
  16717. (if (not org-adapt-indentation) 0
  16718. (let ((level (org-current-level)))
  16719. (if level (1+ level) 0))))
  16720. ((item plain-list) (org-list-item-body-column post-affiliated))
  16721. (t
  16722. (goto-char start)
  16723. (current-indentation))))
  16724. ((memq type '(headline inlinetask nil))
  16725. (if (org-match-line "[ \t]*$")
  16726. (org--get-expected-indentation element t)
  16727. 0))
  16728. ((memq type '(diary-sexp footnote-definition)) 0)
  16729. ;; First paragraph of a footnote definition or an item.
  16730. ;; Indent like parent.
  16731. ((< (line-beginning-position) start)
  16732. (org--get-expected-indentation
  16733. (org-element-property :parent element) t))
  16734. ;; At first line: indent according to previous sibling, if any,
  16735. ;; ignoring footnote definitions and inline tasks, or parent's
  16736. ;; contents.
  16737. ((and ( = (line-beginning-position) start)
  16738. (eq org-adapt-indentation t))
  16739. (catch 'exit
  16740. (while t
  16741. (if (= (point-min) start) (throw 'exit 0)
  16742. (goto-char (1- start))
  16743. (let* ((previous (org-element-at-point))
  16744. (parent previous))
  16745. (while (and parent (<= (org-element-property :end parent) start))
  16746. (setq previous parent
  16747. parent (org-element-property :parent parent)))
  16748. (cond
  16749. ((not previous) (throw 'exit 0))
  16750. ((> (org-element-property :end previous) start)
  16751. (throw 'exit (org--get-expected-indentation previous t)))
  16752. ((memq (org-element-type previous)
  16753. '(footnote-definition inlinetask))
  16754. (setq start (org-element-property :begin previous)))
  16755. (t (goto-char (org-element-property :begin previous))
  16756. (throw 'exit
  16757. (if (bolp) (current-indentation)
  16758. ;; At first paragraph in an item or
  16759. ;; a footnote definition.
  16760. (org--get-expected-indentation
  16761. (org-element-property :parent previous) t))))))))))
  16762. ;; Otherwise, move to the first non-blank line above.
  16763. (t
  16764. (beginning-of-line)
  16765. (let ((pos (point)))
  16766. (skip-chars-backward " \r\t\n")
  16767. (cond
  16768. ;; Two blank lines end a footnote definition or a plain
  16769. ;; list. When we indent an empty line after them, the
  16770. ;; containing list or footnote definition is over, so it
  16771. ;; qualifies as a previous sibling. Therefore, we indent
  16772. ;; like its first line.
  16773. ((and (memq type '(footnote-definition plain-list))
  16774. (> (count-lines (point) pos) 2))
  16775. (goto-char start)
  16776. (current-indentation))
  16777. ;; Line above is the first one of a paragraph at the
  16778. ;; beginning of an item or a footnote definition. Indent
  16779. ;; like parent.
  16780. ((< (line-beginning-position) start)
  16781. (org--get-expected-indentation
  16782. (org-element-property :parent element) t))
  16783. ;; Line above is the beginning of an element, i.e., point
  16784. ;; was originally on the blank lines between element's start
  16785. ;; and contents.
  16786. ((= (line-beginning-position) post-affiliated)
  16787. (org--get-expected-indentation element t))
  16788. ;; POS is after contents in a greater element. Indent like
  16789. ;; the beginning of the element.
  16790. ((and (memq type org-element-greater-elements)
  16791. (let ((cend (org-element-property :contents-end element)))
  16792. (and cend (<= cend pos))))
  16793. ;; As a special case, if point is at the end of a footnote
  16794. ;; definition or an item, indent like the very last element
  16795. ;; within. If that last element is an item, indent like
  16796. ;; its contents.
  16797. (if (memq type '(footnote-definition item plain-list))
  16798. (let ((last (org-element-at-point)))
  16799. (goto-char pos)
  16800. (org--get-expected-indentation
  16801. last (eq (org-element-type last) 'item)))
  16802. (goto-char start)
  16803. (current-indentation)))
  16804. ;; In any other case, indent like the current line.
  16805. (t (current-indentation)))))
  16806. ;; Finally, no indentation is needed, fall back to 0.
  16807. (t (current-indentation))))))
  16808. (defun org--align-node-property ()
  16809. "Align node property at point.
  16810. Alignment is done according to `org-property-format', which see."
  16811. (when (save-excursion
  16812. (beginning-of-line)
  16813. (looking-at org-property-re))
  16814. (combine-change-calls (match-beginning 0) (match-end 0)
  16815. (let ((newtext (concat (match-string 4)
  16816. (org-trim
  16817. (format org-property-format (match-string 1) (match-string 3))))))
  16818. ;; Do not use `replace-match' here as we want to inherit folding
  16819. ;; properties if inside fold.
  16820. (setf (buffer-substring (match-beginning 0) (match-end 0)) "")
  16821. (insert-and-inherit newtext)))))
  16822. (defun org-indent-line ()
  16823. "Indent line depending on context.
  16824. Indentation is done according to the following rules:
  16825. - Footnote definitions, diary sexps, headlines and inline tasks
  16826. have to start at column 0.
  16827. - On the very first line of an element, consider, in order, the
  16828. next rules until one matches:
  16829. 1. If there's a sibling element before, ignoring footnote
  16830. definitions and inline tasks, indent like its first line.
  16831. 2. If element has a parent, indent like its contents. More
  16832. precisely, if parent is an item, indent after the bullet.
  16833. Else, indent like parent's first line.
  16834. 3. Otherwise, indent relatively to current level, if
  16835. `org-adapt-indentation' is t, or to left margin.
  16836. - On a blank line at the end of an element, indent according to
  16837. the type of the element. More precisely
  16838. 1. If element is a plain list, an item, or a footnote
  16839. definition, indent like the very last element within.
  16840. 2. If element is a paragraph, indent like its last non blank
  16841. line.
  16842. 3. Otherwise, indent like its very first line.
  16843. - In the code part of a source block, use language major mode
  16844. to indent current line if `org-src-tab-acts-natively' is
  16845. non-nil. If it is nil, do nothing.
  16846. - Otherwise, indent like the first non-blank line above.
  16847. The function doesn't indent an item as it could break the whole
  16848. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  16849. `\\[org-shiftmetaright]'.
  16850. Also align node properties according to `org-property-format'."
  16851. (interactive)
  16852. (unless (or (org-at-heading-p)
  16853. (and (eq org-adapt-indentation 'headline-data)
  16854. (not (or (org-at-clock-log-p)
  16855. (org-at-planning-p)))
  16856. (save-excursion
  16857. (beginning-of-line 1)
  16858. (skip-chars-backward "\n")
  16859. (or (org-at-heading-p)
  16860. (looking-back ":END:.*" (point-at-bol))))))
  16861. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  16862. (type (org-element-type element)))
  16863. (cond ((and (memq type '(plain-list item))
  16864. (= (line-beginning-position)
  16865. (org-element-property :post-affiliated element)))
  16866. nil)
  16867. ((and (eq type 'latex-environment)
  16868. (>= (point) (org-element-property :post-affiliated element))
  16869. (< (point)
  16870. (org-with-point-at (org-element-property :end element)
  16871. (skip-chars-backward " \t\n")
  16872. (line-beginning-position 2))))
  16873. nil)
  16874. ((and (eq type 'src-block)
  16875. org-src-tab-acts-natively
  16876. (> (line-beginning-position)
  16877. (org-element-property :post-affiliated element))
  16878. (< (line-beginning-position)
  16879. (org-with-point-at (org-element-property :end element)
  16880. (skip-chars-backward " \t\n")
  16881. (line-beginning-position))))
  16882. ;; At the beginning of a blank line, do some preindentation. This
  16883. ;; signals org-src--edit-element to preserve the indentation on exit
  16884. (when (and (looking-at-p "^[[:space:]]*$")
  16885. (not org-src-preserve-indentation))
  16886. (let ((element (org-element-at-point))
  16887. block-content-ind some-ind)
  16888. (org-with-point-at (org-element-property :begin element)
  16889. (setq block-content-ind (+ (current-indentation)
  16890. org-edit-src-content-indentation))
  16891. (forward-line)
  16892. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  16893. (backward-char)
  16894. (setq some-ind (if (looking-at-p "#\\+end_src")
  16895. block-content-ind (current-indentation))))
  16896. (indent-line-to (min block-content-ind some-ind))))
  16897. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  16898. (t
  16899. (let ((column (org--get-expected-indentation element nil)))
  16900. ;; Preserve current column.
  16901. (if (<= (current-column) (current-indentation))
  16902. (indent-line-to column)
  16903. (save-excursion (indent-line-to column))))
  16904. ;; Align node property. Also preserve current column.
  16905. (when (eq type 'node-property)
  16906. (let ((column (current-column)))
  16907. (org--align-node-property)
  16908. (org-move-to-column column))))))))
  16909. (defun org-indent-region (start end)
  16910. "Indent each non-blank line in the region.
  16911. Called from a program, START and END specify the region to
  16912. indent. The function will not indent contents of example blocks,
  16913. verse blocks and export blocks as leading white spaces are
  16914. assumed to be significant there."
  16915. (interactive "r")
  16916. (save-excursion
  16917. (goto-char start)
  16918. (skip-chars-forward " \r\t\n")
  16919. (unless (eobp) (beginning-of-line))
  16920. (let ((indent-to
  16921. (lambda (ind pos)
  16922. ;; Set IND as indentation for all lines between point and
  16923. ;; POS. Blank lines are ignored. Leave point after POS
  16924. ;; once done.
  16925. (let ((limit (copy-marker pos)))
  16926. (while (< (point) limit)
  16927. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  16928. (forward-line))
  16929. (set-marker limit nil))))
  16930. (end (copy-marker end)))
  16931. (while (< (point) end)
  16932. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  16933. (let* ((element (org-element-at-point-no-context))
  16934. (type (org-element-type element))
  16935. (element-end (copy-marker (org-element-property :end element)))
  16936. (ind (org--get-expected-indentation element nil)))
  16937. (cond
  16938. ;; Element indented as a single block. Example blocks
  16939. ;; preserving indentation are a special case since the
  16940. ;; "contents" must not be indented whereas the block
  16941. ;; boundaries can.
  16942. ((or (memq type '(export-block latex-environment))
  16943. (and (eq type 'example-block)
  16944. (not
  16945. (or org-src-preserve-indentation
  16946. (org-element-property :preserve-indent element)))))
  16947. (let ((offset (- ind (current-indentation))))
  16948. (unless (zerop offset)
  16949. (indent-rigidly (org-element-property :begin element)
  16950. (org-element-property :end element)
  16951. offset)))
  16952. (goto-char element-end))
  16953. ;; Elements indented line wise. Be sure to exclude
  16954. ;; example blocks (preserving indentation) and source
  16955. ;; blocks from this category as they are treated
  16956. ;; specially later.
  16957. ((or (memq type '(paragraph table table-row))
  16958. (not (or (org-element-property :contents-begin element)
  16959. (memq type '(example-block src-block)))))
  16960. (when (eq type 'node-property)
  16961. (org--align-node-property)
  16962. (beginning-of-line))
  16963. (funcall indent-to ind (min element-end end)))
  16964. ;; Elements consisting of three parts: before the
  16965. ;; contents, the contents, and after the contents. The
  16966. ;; contents are treated specially, according to the
  16967. ;; element type, or not indented at all. Other parts are
  16968. ;; indented as a single block.
  16969. (t
  16970. (let* ((post (copy-marker
  16971. (org-element-property :post-affiliated element)))
  16972. (cbeg
  16973. (copy-marker
  16974. (cond
  16975. ((not (org-element-property :contents-begin element))
  16976. ;; Fake contents for source blocks.
  16977. (org-with-wide-buffer
  16978. (goto-char post)
  16979. (line-beginning-position 2)))
  16980. ((memq type '(footnote-definition item plain-list))
  16981. ;; Contents in these elements could start on
  16982. ;; the same line as the beginning of the
  16983. ;; element. Make sure we start indenting
  16984. ;; from the second line.
  16985. (org-with-wide-buffer
  16986. (goto-char post)
  16987. (end-of-line)
  16988. (skip-chars-forward " \r\t\n")
  16989. (if (eobp) (point) (line-beginning-position))))
  16990. (t (org-element-property :contents-begin element)))))
  16991. (cend (copy-marker
  16992. (or (org-element-property :contents-end element)
  16993. ;; Fake contents for source blocks.
  16994. (org-with-wide-buffer
  16995. (goto-char element-end)
  16996. (skip-chars-backward " \r\t\n")
  16997. (line-beginning-position)))
  16998. t)))
  16999. ;; Do not change items indentation individually as it
  17000. ;; might break the list as a whole. On the other
  17001. ;; hand, when at a plain list, indent it as a whole.
  17002. (cond ((eq type 'plain-list)
  17003. (let ((offset (- ind (current-indentation))))
  17004. (unless (zerop offset)
  17005. (indent-rigidly (org-element-property :begin element)
  17006. (org-element-property :end element)
  17007. offset))
  17008. (goto-char cbeg)))
  17009. ((eq type 'item) (goto-char cbeg))
  17010. (t (funcall indent-to ind (min cbeg end))))
  17011. (when (< (point) end)
  17012. (cl-case type
  17013. ((example-block verse-block))
  17014. (src-block
  17015. ;; In a source block, indent source code
  17016. ;; according to language major mode, but only if
  17017. ;; `org-src-tab-acts-natively' is non-nil.
  17018. (when (and (< (point) end) org-src-tab-acts-natively)
  17019. (ignore-errors
  17020. (org-babel-do-in-edit-buffer
  17021. (indent-region (point-min) (point-max))))))
  17022. (t (org-indent-region (point) (min cend end))))
  17023. (goto-char (min cend end))
  17024. (when (< (point) end)
  17025. (funcall indent-to ind (min element-end end))))
  17026. (set-marker post nil)
  17027. (set-marker cbeg nil)
  17028. (set-marker cend nil))))
  17029. (set-marker element-end nil))))
  17030. (set-marker end nil))))
  17031. (defun org-indent-drawer ()
  17032. "Indent the drawer at point."
  17033. (interactive)
  17034. (unless (save-excursion
  17035. (beginning-of-line)
  17036. (looking-at-p org-drawer-regexp))
  17037. (user-error "Not at a drawer"))
  17038. (let ((element (org-element-at-point-no-context)))
  17039. (unless (memq (org-element-type element) '(drawer property-drawer))
  17040. (user-error "Not at a drawer"))
  17041. (org-with-wide-buffer
  17042. (org-indent-region (org-element-property :begin element)
  17043. (org-element-property :end element))))
  17044. (message "Drawer at point indented"))
  17045. (defun org-indent-block ()
  17046. "Indent the block at point."
  17047. (interactive)
  17048. (unless (save-excursion
  17049. (beginning-of-line)
  17050. (let ((case-fold-search t))
  17051. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17052. (user-error "Not at a block"))
  17053. (let ((element (org-element-at-point-no-context)))
  17054. (unless (memq (org-element-type element)
  17055. '(comment-block center-block dynamic-block example-block
  17056. export-block quote-block special-block
  17057. src-block verse-block))
  17058. (user-error "Not at a block"))
  17059. (org-with-wide-buffer
  17060. (org-indent-region (org-element-property :begin element)
  17061. (org-element-property :end element))))
  17062. (message "Block at point indented"))
  17063. ;;; Filling
  17064. ;; We use our own fill-paragraph and auto-fill functions.
  17065. ;; `org-fill-paragraph' relies on adaptive filling and context
  17066. ;; checking. Appropriate `fill-prefix' is computed with
  17067. ;; `org-adaptive-fill-function'.
  17068. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17069. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17070. ;; `org-adaptive-fill-function' value. Internally,
  17071. ;; `org-comment-line-break-function' breaks the line.
  17072. ;; `org-setup-filling' installs filling and auto-filling related
  17073. ;; variables during `org-mode' initialization.
  17074. (defun org-setup-filling ()
  17075. (require 'org-element)
  17076. ;; Prevent auto-fill from inserting unwanted new items.
  17077. (when (boundp 'fill-nobreak-predicate)
  17078. (setq-local
  17079. fill-nobreak-predicate
  17080. (org-uniquify
  17081. (append fill-nobreak-predicate
  17082. '(org-fill-line-break-nobreak-p
  17083. org-fill-n-macro-as-item-nobreak-p
  17084. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17085. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17086. (setq-local paragraph-start paragraph-ending)
  17087. (setq-local paragraph-separate paragraph-ending))
  17088. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17089. (setq-local auto-fill-inhibit-regexp nil)
  17090. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17091. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17092. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17093. (defun org-fill-line-break-nobreak-p ()
  17094. "Non-nil when a new line at point would create an Org line break."
  17095. (save-excursion
  17096. (skip-chars-backward " \t")
  17097. (skip-chars-backward "\\\\")
  17098. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17099. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17100. "Non-nil when a new line at point would split a timestamp."
  17101. (and (org-at-timestamp-p 'lax)
  17102. (not (looking-at org-ts-regexp-both))))
  17103. (defun org-fill-n-macro-as-item-nobreak-p ()
  17104. "Non-nil when a new line at point would create a new list."
  17105. ;; During export, a "n" macro followed by a dot or a closing
  17106. ;; parenthesis can end up being parsed as a new list item.
  17107. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17108. (defun org-adaptive-fill-function ()
  17109. "Compute a fill prefix for the current line.
  17110. Return fill prefix, as a string, or nil if current line isn't
  17111. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17112. matches in paragraphs or comments, use it."
  17113. (org-with-wide-buffer
  17114. (unless (org-at-heading-p)
  17115. (let* ((p (line-beginning-position))
  17116. (element (save-excursion
  17117. (beginning-of-line)
  17118. (org-element-at-point)))
  17119. (type (org-element-type element))
  17120. (post-affiliated (org-element-property :post-affiliated element)))
  17121. (unless (< p post-affiliated)
  17122. (cl-case type
  17123. (comment
  17124. (save-excursion
  17125. (beginning-of-line)
  17126. (looking-at "[ \t]*")
  17127. (concat (match-string 0) "# ")))
  17128. (footnote-definition "")
  17129. ((item plain-list)
  17130. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17131. (paragraph
  17132. ;; Fill prefix is usually the same as the current line,
  17133. ;; unless the paragraph is at the beginning of an item.
  17134. (let ((parent (org-element-property :parent element)))
  17135. (save-excursion
  17136. (beginning-of-line)
  17137. (cond ((eq (org-element-type parent) 'item)
  17138. (make-string (org-list-item-body-column
  17139. (org-element-property :begin parent))
  17140. ?\s))
  17141. ((and adaptive-fill-regexp
  17142. ;; Locally disable
  17143. ;; `adaptive-fill-function' to let
  17144. ;; `fill-context-prefix' handle
  17145. ;; `adaptive-fill-regexp' variable.
  17146. (let (adaptive-fill-function)
  17147. (fill-context-prefix
  17148. post-affiliated
  17149. (org-element-property :end element)))))
  17150. ((looking-at "[ \t]+") (match-string 0))
  17151. (t "")))))
  17152. (comment-block
  17153. ;; Only fill contents if P is within block boundaries.
  17154. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17155. (forward-line)
  17156. (point)))
  17157. (cend (save-excursion
  17158. (goto-char (org-element-property :end element))
  17159. (skip-chars-backward " \r\t\n")
  17160. (line-beginning-position))))
  17161. (when (and (>= p cbeg) (< p cend))
  17162. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17163. (match-string 0)
  17164. ""))))))))))
  17165. (defun org-fill-element (&optional justify)
  17166. "Fill element at point, when applicable.
  17167. This function only applies to comment blocks, comments, example
  17168. blocks and paragraphs. Also, as a special case, re-align table
  17169. when point is at one.
  17170. If JUSTIFY is non-nil (interactively, with prefix argument),
  17171. justify as well. If `sentence-end-double-space' is non-nil, then
  17172. period followed by one space does not end a sentence, so don't
  17173. break a line there. The variable `fill-column' controls the
  17174. width for filling.
  17175. For convenience, when point is at a plain list, an item or
  17176. a footnote definition, try to fill the first paragraph within."
  17177. (with-syntax-table org-mode-transpose-word-syntax-table
  17178. ;; Move to end of line in order to get the first paragraph within
  17179. ;; a plain list or a footnote definition.
  17180. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17181. ;; First check if point is in a blank line at the beginning of
  17182. ;; the buffer. In that case, ignore filling.
  17183. (cl-case (org-element-type element)
  17184. ;; Use major mode filling function is source blocks.
  17185. (src-block (org-babel-do-in-edit-buffer
  17186. (push-mark (point-min))
  17187. (goto-char (point-max))
  17188. (setq mark-active t)
  17189. (funcall-interactively #'fill-paragraph justify 'region)))
  17190. ;; Align Org tables, leave table.el tables as-is.
  17191. (table-row (org-table-align) t)
  17192. (table
  17193. (when (eq (org-element-property :type element) 'org)
  17194. (save-excursion
  17195. (goto-char (org-element-property :post-affiliated element))
  17196. (org-table-align)))
  17197. t)
  17198. (paragraph
  17199. ;; Paragraphs may contain `line-break' type objects.
  17200. (let ((beg (max (point-min)
  17201. (org-element-property :contents-begin element)))
  17202. (end (min (point-max)
  17203. (org-element-property :contents-end element))))
  17204. ;; Do nothing if point is at an affiliated keyword.
  17205. (if (< (line-end-position) beg) t
  17206. ;; Fill paragraph, taking line breaks into account.
  17207. (save-excursion
  17208. (goto-char beg)
  17209. (let ((cuts (list beg)))
  17210. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17211. (when (eq 'line-break
  17212. (org-element-type
  17213. (save-excursion (backward-char)
  17214. (org-element-context))))
  17215. (push (point) cuts)))
  17216. (dolist (c (delq end cuts))
  17217. (fill-region-as-paragraph c end justify)
  17218. (setq end c))))
  17219. t)))
  17220. ;; Contents of `comment-block' type elements should be
  17221. ;; filled as plain text, but only if point is within block
  17222. ;; markers.
  17223. (comment-block
  17224. (let* ((case-fold-search t)
  17225. (beg (save-excursion
  17226. (goto-char (org-element-property :begin element))
  17227. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17228. (forward-line)
  17229. (point)))
  17230. (end (save-excursion
  17231. (goto-char (org-element-property :end element))
  17232. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17233. (line-beginning-position))))
  17234. (if (or (< (point) beg) (> (point) end)) t
  17235. (fill-region-as-paragraph
  17236. (save-excursion (end-of-line)
  17237. (re-search-backward "^[ \t]*$" beg 'move)
  17238. (line-beginning-position))
  17239. (save-excursion (beginning-of-line)
  17240. (re-search-forward "^[ \t]*$" end 'move)
  17241. (line-beginning-position))
  17242. justify))))
  17243. ;; Fill comments.
  17244. (comment
  17245. (let ((begin (org-element-property :post-affiliated element))
  17246. (end (org-element-property :end element)))
  17247. (when (and (>= (point) begin) (<= (point) end))
  17248. (let ((begin (save-excursion
  17249. (end-of-line)
  17250. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17251. (progn (forward-line) (point))
  17252. begin)))
  17253. (end (save-excursion
  17254. (end-of-line)
  17255. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17256. (1- (line-beginning-position))
  17257. (skip-chars-backward " \r\t\n")
  17258. (line-end-position)))))
  17259. ;; Do not fill comments when at a blank line.
  17260. (when (> end begin)
  17261. (let ((fill-prefix
  17262. (save-excursion
  17263. (beginning-of-line)
  17264. (looking-at "[ \t]*#")
  17265. (let ((comment-prefix (match-string 0)))
  17266. (goto-char (match-end 0))
  17267. (if (looking-at adaptive-fill-regexp)
  17268. (concat comment-prefix (match-string 0))
  17269. (concat comment-prefix " "))))))
  17270. (save-excursion
  17271. (fill-region-as-paragraph begin end justify))))))
  17272. t))
  17273. ;; Ignore every other element.
  17274. (otherwise t)))))
  17275. (defun org-fill-paragraph (&optional justify region)
  17276. "Fill element at point, when applicable.
  17277. This function only applies to comment blocks, comments, example
  17278. blocks and paragraphs. Also, as a special case, re-align table
  17279. when point is at one.
  17280. For convenience, when point is at a plain list, an item or
  17281. a footnote definition, try to fill the first paragraph within.
  17282. If JUSTIFY is non-nil (interactively, with prefix argument),
  17283. justify as well. If `sentence-end-double-space' is non-nil, then
  17284. period followed by one space does not end a sentence, so don't
  17285. break a line there. The variable `fill-column' controls the
  17286. width for filling.
  17287. The REGION argument is non-nil if called interactively; in that
  17288. case, if Transient Mark mode is enabled and the mark is active,
  17289. fill each of the elements in the active region, instead of just
  17290. filling the current element."
  17291. (interactive (progn
  17292. (barf-if-buffer-read-only)
  17293. (list (when current-prefix-arg 'full) t)))
  17294. (let ((hash (and (not (buffer-modified-p))
  17295. (org-buffer-hash))))
  17296. (cond
  17297. ((and region transient-mark-mode mark-active
  17298. (not (eq (region-beginning) (region-end))))
  17299. (let ((origin (point-marker))
  17300. (start (region-beginning)))
  17301. (unwind-protect
  17302. (progn
  17303. (goto-char (region-end))
  17304. (skip-chars-backward " \t\n")
  17305. (while (> (point) start)
  17306. (org-fill-element justify)
  17307. (org-backward-paragraph)))
  17308. (goto-char origin)
  17309. (set-marker origin nil))))
  17310. (t
  17311. (save-excursion
  17312. (when (org-match-line "[ \t]*$")
  17313. (skip-chars-forward " \t\n"))
  17314. (org-fill-element justify))))
  17315. ;; If we didn't change anything in the buffer (and the buffer was
  17316. ;; previously unmodified), then flip the modification status back
  17317. ;; to "unchanged".
  17318. (when (and hash (equal hash (org-buffer-hash)))
  17319. (set-buffer-modified-p nil))
  17320. ;; Return non-nil.
  17321. t))
  17322. (defun org-auto-fill-function ()
  17323. "Auto-fill function."
  17324. ;; Check if auto-filling is meaningful.
  17325. (let ((fc (current-fill-column)))
  17326. (when (and fc (> (current-column) fc))
  17327. (let* ((fill-prefix (org-adaptive-fill-function))
  17328. ;; Enforce empty fill prefix, if required. Otherwise, it
  17329. ;; will be computed again.
  17330. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17331. (when fill-prefix (do-auto-fill))))))
  17332. (defun org-comment-line-break-function (&optional soft)
  17333. "Break line at point and indent, continuing comment if within one.
  17334. The inserted newline is marked hard if variable
  17335. `use-hard-newlines' is true, unless optional argument SOFT is
  17336. non-nil."
  17337. (if soft (insert-and-inherit ?\n) (newline 1))
  17338. (save-excursion (forward-char -1) (delete-horizontal-space))
  17339. (delete-horizontal-space)
  17340. (indent-to-left-margin)
  17341. (insert-before-markers-and-inherit fill-prefix))
  17342. ;;; Fixed Width Areas
  17343. (defun org-toggle-fixed-width ()
  17344. "Toggle fixed-width markup.
  17345. Add or remove fixed-width markup on current line, whenever it
  17346. makes sense. Return an error otherwise.
  17347. If a region is active and if it contains only fixed-width areas
  17348. or blank lines, remove all fixed-width markup in it. If the
  17349. region contains anything else, convert all non-fixed-width lines
  17350. to fixed-width ones.
  17351. Blank lines at the end of the region are ignored unless the
  17352. region only contains such lines."
  17353. (interactive)
  17354. (if (not (org-region-active-p))
  17355. ;; No region:
  17356. ;;
  17357. ;; Remove fixed width marker only in a fixed-with element.
  17358. ;;
  17359. ;; Add fixed width maker in paragraphs, in blank lines after
  17360. ;; elements or at the beginning of a headline or an inlinetask,
  17361. ;; and before any one-line elements (e.g., a clock).
  17362. (progn
  17363. (beginning-of-line)
  17364. (let* ((element (org-element-at-point))
  17365. (type (org-element-type element)))
  17366. (cond
  17367. ((and (eq type 'fixed-width)
  17368. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17369. (replace-match
  17370. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17371. ((and (memq type '(babel-call clock comment diary-sexp headline
  17372. horizontal-rule keyword paragraph
  17373. planning))
  17374. (<= (org-element-property :post-affiliated element) (point)))
  17375. (skip-chars-forward " \t")
  17376. (insert ": "))
  17377. ((and (looking-at-p "[ \t]*$")
  17378. (or (eq type 'inlinetask)
  17379. (save-excursion
  17380. (skip-chars-forward " \r\t\n")
  17381. (<= (org-element-property :end element) (point)))))
  17382. (delete-region (point) (line-end-position))
  17383. (org-indent-line)
  17384. (insert ": "))
  17385. (t (user-error "Cannot insert a fixed-width line here")))))
  17386. ;; Region active.
  17387. (let* ((begin (save-excursion
  17388. (goto-char (region-beginning))
  17389. (line-beginning-position)))
  17390. (end (copy-marker
  17391. (save-excursion
  17392. (goto-char (region-end))
  17393. (unless (eolp) (beginning-of-line))
  17394. (if (save-excursion (re-search-backward "\\S-" begin t))
  17395. (progn (skip-chars-backward " \r\t\n") (point))
  17396. (point)))))
  17397. (all-fixed-width-p
  17398. (catch 'not-all-p
  17399. (save-excursion
  17400. (goto-char begin)
  17401. (skip-chars-forward " \r\t\n")
  17402. (when (eobp) (throw 'not-all-p nil))
  17403. (while (< (point) end)
  17404. (let ((element (org-element-at-point)))
  17405. (if (eq (org-element-type element) 'fixed-width)
  17406. (goto-char (org-element-property :end element))
  17407. (throw 'not-all-p nil))))
  17408. t))))
  17409. (if all-fixed-width-p
  17410. (save-excursion
  17411. (goto-char begin)
  17412. (while (< (point) end)
  17413. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17414. (replace-match
  17415. "" nil nil nil
  17416. (if (= (line-end-position) (match-end 0)) 0 1)))
  17417. (forward-line)))
  17418. (let ((min-ind (point-max)))
  17419. ;; Find minimum indentation across all lines.
  17420. (save-excursion
  17421. (goto-char begin)
  17422. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17423. (setq min-ind 0)
  17424. (catch 'zerop
  17425. (while (< (point) end)
  17426. (unless (looking-at-p "[ \t]*$")
  17427. (let ((ind (current-indentation)))
  17428. (setq min-ind (min min-ind ind))
  17429. (when (zerop ind) (throw 'zerop t))))
  17430. (forward-line)))))
  17431. ;; Loop over all lines and add fixed-width markup everywhere
  17432. ;; but in fixed-width lines.
  17433. (save-excursion
  17434. (goto-char begin)
  17435. (while (< (point) end)
  17436. (cond
  17437. ((org-at-heading-p)
  17438. (insert ": ")
  17439. (forward-line)
  17440. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17441. (insert ":")
  17442. (forward-line)))
  17443. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17444. (let* ((element (org-element-at-point))
  17445. (element-end (org-element-property :end element)))
  17446. (if (eq (org-element-type element) 'fixed-width)
  17447. (progn (goto-char element-end)
  17448. (skip-chars-backward " \r\t\n")
  17449. (forward-line))
  17450. (let ((limit (min end element-end)))
  17451. (while (< (point) limit)
  17452. (org-move-to-column min-ind t)
  17453. (insert ": ")
  17454. (forward-line))))))
  17455. (t
  17456. (org-move-to-column min-ind t)
  17457. (insert ": ")
  17458. (forward-line)))))))
  17459. (set-marker end nil))))
  17460. ;;; Blocks
  17461. (defun org-block-map (function &optional start end)
  17462. "Call FUNCTION at the head of all source blocks in the current buffer.
  17463. Optional arguments START and END can be used to limit the range."
  17464. (let ((start (or start (point-min)))
  17465. (end (or end (point-max))))
  17466. (save-excursion
  17467. (goto-char start)
  17468. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17469. (save-excursion
  17470. (save-match-data
  17471. (goto-char (match-beginning 0))
  17472. (funcall function)))))))
  17473. (defun org-next-block (arg &optional backward block-regexp)
  17474. "Jump to the next block.
  17475. With a prefix argument ARG, jump forward ARG many blocks.
  17476. When BACKWARD is non-nil, jump to the previous block.
  17477. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17478. Match data is set according to this regexp when the function
  17479. returns.
  17480. Return point at beginning of the opening line of found block.
  17481. Throw an error if no block is found."
  17482. (interactive "p")
  17483. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17484. (case-fold-search t)
  17485. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17486. (count (or arg 1))
  17487. (origin (point))
  17488. last-element)
  17489. (if backward (beginning-of-line) (end-of-line))
  17490. (while (and (> count 0) (funcall search-fn re nil t))
  17491. (let ((element (save-excursion
  17492. (goto-char (match-beginning 0))
  17493. (save-match-data (org-element-at-point)))))
  17494. (when (and (memq (org-element-type element)
  17495. '(center-block comment-block dynamic-block
  17496. example-block export-block quote-block
  17497. special-block src-block verse-block))
  17498. (<= (match-beginning 0)
  17499. (org-element-property :post-affiliated element)))
  17500. (setq last-element element)
  17501. (cl-decf count))))
  17502. (if (= count 0)
  17503. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17504. (save-match-data (org-fold-show-context)))
  17505. (goto-char origin)
  17506. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17507. (defun org-previous-block (arg &optional block-regexp)
  17508. "Jump to the previous block.
  17509. With a prefix argument ARG, jump backward ARG many source blocks.
  17510. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17511. (interactive "p")
  17512. (org-next-block arg t block-regexp))
  17513. ;;; Comments
  17514. ;; Org comments syntax is quite complex. It requires the entire line
  17515. ;; to be just a comment. Also, even with the right syntax at the
  17516. ;; beginning of line, some elements (e.g., verse-block or
  17517. ;; example-block) don't accept comments. Usual Emacs comment commands
  17518. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17519. ;; Org still relies on 'comment-dwim', but cannot trust
  17520. ;; 'comment-only-p'. So, 'comment-region-function' and
  17521. ;; 'uncomment-region-function' both point
  17522. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17523. ;; 'org-insert-comment' takes care of insertion of comments at the
  17524. ;; beginning of line.
  17525. ;; 'org-setup-comments-handling' install comments related variables
  17526. ;; during 'org-mode' initialization.
  17527. (defun org-setup-comments-handling ()
  17528. (interactive)
  17529. (setq-local comment-use-syntax nil)
  17530. (setq-local comment-start "# ")
  17531. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17532. (setq-local comment-insert-comment-function 'org-insert-comment)
  17533. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17534. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17535. (defun org-insert-comment ()
  17536. "Insert an empty comment above current line.
  17537. If the line is empty, insert comment at its beginning. When
  17538. point is within a source block, comment according to the related
  17539. major mode."
  17540. (if (let ((element (org-element-at-point)))
  17541. (and (eq (org-element-type element) 'src-block)
  17542. (< (save-excursion
  17543. (goto-char (org-element-property :post-affiliated element))
  17544. (line-end-position))
  17545. (point))
  17546. (> (save-excursion
  17547. (goto-char (org-element-property :end element))
  17548. (skip-chars-backward " \r\t\n")
  17549. (line-beginning-position))
  17550. (point))))
  17551. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17552. (beginning-of-line)
  17553. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17554. (open-line 1))
  17555. (org-indent-line)
  17556. (insert "# ")))
  17557. (defvar comment-empty-lines) ; From newcomment.el.
  17558. (defun org-comment-or-uncomment-region (beg end &rest _)
  17559. "Comment or uncomment each non-blank line in the region.
  17560. Uncomment each non-blank line between BEG and END if it only
  17561. contains commented lines. Otherwise, comment them. If region is
  17562. strictly within a source block, use appropriate comment syntax."
  17563. (if (let ((element (org-element-at-point)))
  17564. (and (eq (org-element-type element) 'src-block)
  17565. (< (save-excursion
  17566. (goto-char (org-element-property :post-affiliated element))
  17567. (line-end-position))
  17568. beg)
  17569. (>= (save-excursion
  17570. (goto-char (org-element-property :end element))
  17571. (skip-chars-backward " \r\t\n")
  17572. (line-beginning-position))
  17573. end)))
  17574. ;; Translate region boundaries for the Org buffer to the source
  17575. ;; buffer.
  17576. (let ((offset (- end beg)))
  17577. (save-excursion
  17578. (goto-char beg)
  17579. (org-babel-do-in-edit-buffer
  17580. (comment-or-uncomment-region (point) (+ offset (point))))))
  17581. (save-restriction
  17582. ;; Restrict region
  17583. (narrow-to-region (save-excursion (goto-char beg)
  17584. (skip-chars-forward " \r\t\n" end)
  17585. (line-beginning-position))
  17586. (save-excursion (goto-char end)
  17587. (skip-chars-backward " \r\t\n" beg)
  17588. (line-end-position)))
  17589. (let ((uncommentp
  17590. ;; UNCOMMENTP is non-nil when every non blank line between
  17591. ;; BEG and END is a comment.
  17592. (save-excursion
  17593. (goto-char (point-min))
  17594. (while (and (not (eobp))
  17595. (let ((element (org-element-at-point)))
  17596. (and (eq (org-element-type element) 'comment)
  17597. (goto-char (min (point-max)
  17598. (org-element-property
  17599. :end element)))))))
  17600. (eobp))))
  17601. (if uncommentp
  17602. ;; Only blank lines and comments in region: uncomment it.
  17603. (save-excursion
  17604. (goto-char (point-min))
  17605. (while (not (eobp))
  17606. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17607. (replace-match "" nil nil nil 1))
  17608. (forward-line)))
  17609. ;; Comment each line in region.
  17610. (let ((min-indent (point-max)))
  17611. ;; First find the minimum indentation across all lines.
  17612. (save-excursion
  17613. (goto-char (point-min))
  17614. (while (and (not (eobp)) (not (zerop min-indent)))
  17615. (unless (looking-at "[ \t]*$")
  17616. (setq min-indent (min min-indent (current-indentation))))
  17617. (forward-line)))
  17618. ;; Then loop over all lines.
  17619. (save-excursion
  17620. (goto-char (point-min))
  17621. (while (not (eobp))
  17622. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17623. ;; Don't get fooled by invisible text (e.g. link path)
  17624. ;; when moving to column MIN-INDENT.
  17625. (let ((buffer-invisibility-spec nil))
  17626. (org-move-to-column min-indent t))
  17627. (insert comment-start))
  17628. (forward-line)))))))))
  17629. (defun org-comment-dwim (_arg)
  17630. "Call the comment command you mean.
  17631. Call `org-toggle-comment' if on a heading, otherwise call
  17632. `comment-dwim', within a source edit buffer if needed."
  17633. (interactive "*P")
  17634. (cond ((org-at-heading-p)
  17635. (call-interactively #'org-toggle-comment))
  17636. ((org-in-src-block-p)
  17637. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17638. (t (call-interactively #'comment-dwim))))
  17639. ;;; Timestamps API
  17640. ;; This section contains tools to operate on, or create, timestamp
  17641. ;; objects, as returned by, e.g. `org-element-context'.
  17642. (defun org-timestamp-from-string (s)
  17643. "Convert Org timestamp S, as a string, into a timestamp object.
  17644. Return nil if S is not a valid timestamp string."
  17645. (when (org-string-nw-p s)
  17646. (with-temp-buffer
  17647. (save-excursion (insert s))
  17648. (org-element-timestamp-parser))))
  17649. (defun org-timestamp-from-time (time &optional with-time inactive)
  17650. "Convert a time value into a timestamp object.
  17651. TIME is an Emacs internal time representation, as returned, e.g.,
  17652. by `current-time'.
  17653. When optional argument WITH-TIME is non-nil, return a timestamp
  17654. object with a time part, i.e., with hours and minutes.
  17655. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17656. return an active timestamp."
  17657. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17658. (org-element-create 'timestamp
  17659. (list :type (if inactive 'inactive 'active)
  17660. :year-start year
  17661. :month-start month
  17662. :day-start day
  17663. :hour-start (and with-time hour)
  17664. :minute-start (and with-time minute)))))
  17665. (defun org-timestamp-to-time (timestamp &optional end)
  17666. "Convert TIMESTAMP object into an Emacs internal time value.
  17667. Use end of date range or time range when END is non-nil.
  17668. Otherwise, use its start."
  17669. (apply #'encode-time 0
  17670. (mapcar
  17671. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17672. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17673. '(:minute-start :hour-start :day-start :month-start
  17674. :year-start)))))
  17675. (defun org-timestamp-has-time-p (timestamp)
  17676. "Non-nil when TIMESTAMP has a time specified."
  17677. (org-element-property :hour-start timestamp))
  17678. (defun org-timestamp-format (timestamp format &optional end utc)
  17679. "Format a TIMESTAMP object into a string.
  17680. FORMAT is a format specifier to be passed to
  17681. `format-time-string'.
  17682. When optional argument END is non-nil, use end of date-range or
  17683. time-range, if possible.
  17684. When optional argument UTC is non-nil, time is be expressed as
  17685. Universal Time."
  17686. (format-time-string format (org-timestamp-to-time timestamp end)
  17687. (and utc t)))
  17688. (defun org-timestamp-split-range (timestamp &optional end)
  17689. "Extract a TIMESTAMP object from a date or time range.
  17690. END, when non-nil, means extract the end of the range.
  17691. Otherwise, extract its start.
  17692. Return a new timestamp object."
  17693. (let ((type (org-element-property :type timestamp)))
  17694. (if (memq type '(active inactive diary)) timestamp
  17695. (let ((split-ts (org-element-copy timestamp)))
  17696. ;; Set new type.
  17697. (org-element-put-property
  17698. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  17699. ;; Copy start properties over end properties if END is
  17700. ;; non-nil. Otherwise, copy end properties over `start' ones.
  17701. (let ((p-alist '((:minute-start . :minute-end)
  17702. (:hour-start . :hour-end)
  17703. (:day-start . :day-end)
  17704. (:month-start . :month-end)
  17705. (:year-start . :year-end))))
  17706. (dolist (p-cell p-alist)
  17707. (org-element-put-property
  17708. split-ts
  17709. (funcall (if end #'car #'cdr) p-cell)
  17710. (org-element-property
  17711. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  17712. ;; Eventually refresh `:raw-value'.
  17713. (org-element-put-property split-ts :raw-value nil)
  17714. (org-element-put-property
  17715. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  17716. (defun org-timestamp-translate (timestamp &optional boundary)
  17717. "Translate TIMESTAMP object to custom format.
  17718. Format string is defined in `org-time-stamp-custom-formats',
  17719. which see.
  17720. When optional argument BOUNDARY is non-nil, it is either the
  17721. symbol `start' or `end'. In this case, only translate the
  17722. starting or ending part of TIMESTAMP if it is a date or time
  17723. range. Otherwise, translate both parts.
  17724. Return timestamp as-is if `org-display-custom-times' is nil or if
  17725. it has a `diary' type."
  17726. (let ((type (org-element-property :type timestamp)))
  17727. (if (or (not org-display-custom-times) (eq type 'diary))
  17728. (org-element-interpret-data timestamp)
  17729. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  17730. org-time-stamp-custom-formats)))
  17731. (if (and (not boundary) (memq type '(active-range inactive-range)))
  17732. (concat (org-timestamp-format timestamp fmt)
  17733. "--"
  17734. (org-timestamp-format timestamp fmt t))
  17735. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  17736. ;;; Other stuff
  17737. (defvar reftex-docstruct-symbol)
  17738. (defvar org--rds)
  17739. (defun org-reftex-citation ()
  17740. "Use `reftex-citation' to insert a citation into the buffer.
  17741. This looks for a line like
  17742. #+BIBLIOGRAPHY: foo plain option:-d
  17743. and derives from it that foo.bib is the bibliography file relevant
  17744. for this document. It then installs the necessary environment for RefTeX
  17745. to work in this buffer and calls `reftex-citation' to insert a citation
  17746. into the buffer.
  17747. Export of such citations to both LaTeX and HTML is handled by the contributed
  17748. package ox-bibtex by Taru Karttunen."
  17749. (interactive)
  17750. (let ((reftex-docstruct-symbol 'org--rds)
  17751. org--rds bib)
  17752. (org-with-wide-buffer
  17753. (let ((case-fold-search t)
  17754. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  17755. (if (not (save-excursion
  17756. (or (re-search-forward re nil t)
  17757. (re-search-backward re nil t))))
  17758. (user-error "No bibliography defined in file")
  17759. (setq bib (concat (match-string 1) ".bib")
  17760. org--rds (list (list 'bib bib))))))
  17761. (call-interactively 'reftex-citation)))
  17762. ;;;; Functions extending outline functionality
  17763. (defun org-beginning-of-line (&optional n)
  17764. "Go to the beginning of the current visible line.
  17765. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17766. symbol `reversed', on the first attempt move to where the
  17767. headline text starts, and only move to beginning of line when the
  17768. cursor is already before the start of the text of the headline.
  17769. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  17770. start of the text on the second attempt.
  17771. With argument N not nil or 1, move forward N - 1 lines first."
  17772. (interactive "^p")
  17773. (let ((origin (point))
  17774. (special (pcase org-special-ctrl-a/e
  17775. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  17776. deactivate-mark)
  17777. ;; First move to a visible line.
  17778. (if (bound-and-true-p visual-line-mode)
  17779. (beginning-of-visual-line n)
  17780. (move-beginning-of-line n)
  17781. ;; `move-beginning-of-line' may leave point after invisible
  17782. ;; characters if line starts with such of these (e.g., with
  17783. ;; a link at column 0). Really move to the beginning of the
  17784. ;; current visible line.
  17785. (beginning-of-line))
  17786. (cond
  17787. ;; No special behavior. Point is already at the beginning of
  17788. ;; a line, logical or visual.
  17789. ((not special))
  17790. ;; `beginning-of-visual-line' left point before logical beginning
  17791. ;; of line: point is at the beginning of a visual line. Bail
  17792. ;; out.
  17793. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  17794. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  17795. ;; At a headline, special position is before the title, but
  17796. ;; after any TODO keyword or priority cookie.
  17797. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  17798. (line-end-position)))
  17799. (bol (point)))
  17800. (if (eq special 'reversed)
  17801. (when (and (= origin bol) (eq last-command this-command))
  17802. (goto-char refpos))
  17803. (when (or (> origin refpos) (= origin bol))
  17804. (goto-char refpos)))))
  17805. ((and (looking-at org-list-full-item-re)
  17806. (memq (org-element-type (save-match-data (org-element-at-point)))
  17807. '(item plain-list)))
  17808. ;; Set special position at first white space character after
  17809. ;; bullet, and check-box, if any.
  17810. (let ((after-bullet
  17811. (let ((box (match-end 3)))
  17812. (cond ((not box) (match-end 1))
  17813. ((eq (char-after box) ?\s) (1+ box))
  17814. (t box)))))
  17815. (if (eq special 'reversed)
  17816. (when (and (= (point) origin) (eq last-command this-command))
  17817. (goto-char after-bullet))
  17818. (when (or (> origin after-bullet) (= (point) origin))
  17819. (goto-char after-bullet)))))
  17820. ;; No special context. Point is already at beginning of line.
  17821. (t nil))))
  17822. (defun org-end-of-line (&optional n)
  17823. "Go to the end of the line, but before ellipsis, if any.
  17824. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17825. symbol `reversed', ignore tags on the first attempt, and only
  17826. move to after the tags when the cursor is already beyond the end
  17827. of the headline.
  17828. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  17829. on the second attempt.
  17830. With argument N not nil or 1, move forward N - 1 lines first."
  17831. (interactive "^p")
  17832. (let ((origin (point))
  17833. (special (pcase org-special-ctrl-a/e
  17834. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  17835. deactivate-mark)
  17836. ;; First move to a visible line.
  17837. (if (bound-and-true-p visual-line-mode)
  17838. (beginning-of-visual-line n)
  17839. (move-beginning-of-line n))
  17840. (cond
  17841. ;; At a headline, with tags.
  17842. ((and special
  17843. (save-excursion
  17844. (beginning-of-line)
  17845. (let ((case-fold-search nil))
  17846. (looking-at org-complex-heading-regexp)))
  17847. (match-end 5))
  17848. (let ((tags (save-excursion
  17849. (goto-char (match-beginning 5))
  17850. (skip-chars-backward " \t")
  17851. (point)))
  17852. (visual-end (and (bound-and-true-p visual-line-mode)
  17853. (save-excursion
  17854. (end-of-visual-line)
  17855. (point)))))
  17856. ;; If `end-of-visual-line' brings us before end of line or
  17857. ;; even tags, i.e., the headline spans over multiple visual
  17858. ;; lines, move there.
  17859. (cond ((and visual-end
  17860. (< visual-end tags)
  17861. (<= origin visual-end))
  17862. (goto-char visual-end))
  17863. ((eq special 'reversed)
  17864. (if (and (= origin (line-end-position))
  17865. (eq this-command last-command))
  17866. (goto-char tags)
  17867. (end-of-line)))
  17868. (t
  17869. (if (or (< origin tags) (= origin (line-end-position)))
  17870. (goto-char tags)
  17871. (end-of-line))))))
  17872. ((bound-and-true-p visual-line-mode)
  17873. (let ((bol (line-beginning-position)))
  17874. (end-of-visual-line)
  17875. ;; If `end-of-visual-line' gets us past the ellipsis at the
  17876. ;; end of a line, backtrack and use `end-of-line' instead.
  17877. (when (/= bol (line-beginning-position))
  17878. (goto-char bol)
  17879. (end-of-line))))
  17880. (t (end-of-line)))))
  17881. (defun org-backward-sentence (&optional _arg)
  17882. "Go to beginning of sentence, or beginning of table field.
  17883. This will call `backward-sentence' or `org-table-beginning-of-field',
  17884. depending on context."
  17885. (interactive)
  17886. (let* ((element (org-element-at-point))
  17887. (contents-begin (org-element-property :contents-begin element))
  17888. (table (org-element-lineage element '(table) t)))
  17889. (if (and table
  17890. (> (point) contents-begin)
  17891. (<= (point) (org-element-property :contents-end table)))
  17892. (call-interactively #'org-table-beginning-of-field)
  17893. (save-restriction
  17894. (when (and contents-begin
  17895. (< (point-min) contents-begin)
  17896. (> (point) contents-begin))
  17897. (narrow-to-region contents-begin
  17898. (org-element-property :contents-end element)))
  17899. (call-interactively #'backward-sentence)))))
  17900. (defun org-forward-sentence (&optional _arg)
  17901. "Go to end of sentence, or end of table field.
  17902. This will call `forward-sentence' or `org-table-end-of-field',
  17903. depending on context."
  17904. (interactive)
  17905. (if (and (org-at-heading-p)
  17906. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  17907. (save-restriction
  17908. (narrow-to-region (line-beginning-position) (line-end-position))
  17909. (call-interactively #'forward-sentence))
  17910. (let* ((element (org-element-at-point))
  17911. (contents-end (org-element-property :contents-end element))
  17912. (table (org-element-lineage element '(table) t)))
  17913. (if (and table
  17914. (>= (point) (org-element-property :contents-begin table))
  17915. (< (point) contents-end))
  17916. (call-interactively #'org-table-end-of-field)
  17917. (save-restriction
  17918. (when (and contents-end
  17919. (> (point-max) contents-end)
  17920. ;; Skip blank lines between elements.
  17921. (< (org-element-property :end element)
  17922. (save-excursion (goto-char contents-end)
  17923. (skip-chars-forward " \r\t\n"))))
  17924. (narrow-to-region (org-element-property :contents-begin element)
  17925. contents-end))
  17926. ;; End of heading is considered as the end of a sentence.
  17927. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  17928. (call-interactively #'forward-sentence)))))))
  17929. (defun org-kill-line (&optional _arg)
  17930. "Kill line, to tags or end of line."
  17931. (interactive)
  17932. (cond
  17933. ((or (not org-special-ctrl-k)
  17934. (bolp)
  17935. (not (org-at-heading-p)))
  17936. (when (and (org-invisible-p (line-end-position))
  17937. org-ctrl-k-protect-subtree
  17938. (or (eq org-ctrl-k-protect-subtree 'error)
  17939. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  17940. (user-error
  17941. (substitute-command-keys
  17942. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  17943. (call-interactively
  17944. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  17945. ((org-match-line org-tag-line-re)
  17946. (let ((end (save-excursion
  17947. (goto-char (match-beginning 1))
  17948. (skip-chars-backward " \t")
  17949. (point))))
  17950. (if (<= end (point)) ;on tags part
  17951. (kill-region (point) (line-end-position))
  17952. (kill-region (point) end)))
  17953. ;; Only align tags when we are still on a heading:
  17954. (if (org-at-heading-p) (org-align-tags)))
  17955. (t (kill-region (point) (line-end-position)))))
  17956. (defun org-yank (&optional arg)
  17957. "Yank. If the kill is a subtree, treat it specially.
  17958. This command will look at the current kill and check if is a single
  17959. subtree, or a series of subtrees[1]. If it passes the test, and if the
  17960. cursor is at the beginning of a line or after the stars of a currently
  17961. empty headline, then the yank is handled specially. How exactly depends
  17962. on the value of the following variables.
  17963. `org-yank-folded-subtrees'
  17964. By default, this variable is non-nil, which results in
  17965. subtree(s) being folded after insertion, except if doing so
  17966. would swallow text after the yanked text.
  17967. `org-yank-adjusted-subtrees'
  17968. When non-nil (the default value is nil), the subtree will be
  17969. promoted or demoted in order to fit into the local outline tree
  17970. structure, which means that the level will be adjusted so that it
  17971. becomes the smaller one of the two *visible* surrounding headings.
  17972. Any prefix to this command will cause `yank' to be called directly with
  17973. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  17974. will just
  17975. plainly yank the text as it is.
  17976. \[1] The test checks if the first non-white line is a heading
  17977. and if there are no other headings with fewer stars."
  17978. (interactive "P")
  17979. (org-yank-generic 'yank arg))
  17980. (defun org-yank-generic (command arg)
  17981. "Perform some yank-like command.
  17982. This function implements the behavior described in the `org-yank'
  17983. documentation. However, it has been generalized to work for any
  17984. interactive command with similar behavior."
  17985. ;; pretend to be command COMMAND
  17986. (setq this-command command)
  17987. (if arg
  17988. (call-interactively command)
  17989. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  17990. (and (org-kill-is-subtree-p)
  17991. (or (bolp)
  17992. (and (looking-at "[ \t]*$")
  17993. (string-match
  17994. "\\`\\*+\\'"
  17995. (buffer-substring (point-at-bol) (point)))))))
  17996. swallowp)
  17997. (cond
  17998. ((and subtreep org-yank-folded-subtrees)
  17999. (let ((beg (point))
  18000. end)
  18001. (if (and subtreep org-yank-adjusted-subtrees)
  18002. (org-paste-subtree nil nil 'for-yank)
  18003. (call-interactively command))
  18004. (setq end (point))
  18005. (goto-char beg)
  18006. (when (and (bolp) subtreep
  18007. (not (setq swallowp
  18008. (org-yank-folding-would-swallow-text beg end))))
  18009. (org-with-limited-levels
  18010. (or (looking-at org-outline-regexp)
  18011. (re-search-forward org-outline-regexp-bol end t))
  18012. (while (and (< (point) end) (looking-at org-outline-regexp))
  18013. (org-fold-subtree t)
  18014. (org-cycle-show-empty-lines 'folded)
  18015. (condition-case nil
  18016. (outline-forward-same-level 1)
  18017. (error (goto-char end))))))
  18018. (when swallowp
  18019. (message
  18020. "Inserted text not folded because that would swallow text"))
  18021. (goto-char end)
  18022. (skip-chars-forward " \t\n\r")
  18023. (beginning-of-line 1)
  18024. (push-mark beg 'nomsg)))
  18025. ((and subtreep org-yank-adjusted-subtrees)
  18026. (let ((beg (point-at-bol)))
  18027. (org-paste-subtree nil nil 'for-yank)
  18028. (push-mark beg 'nomsg)))
  18029. (t
  18030. (call-interactively command))))))
  18031. (defun org-yank-folding-would-swallow-text (beg end)
  18032. "Would `hide-subtree' at BEG swallow any text after END?"
  18033. (let (level)
  18034. (org-with-limited-levels
  18035. (save-excursion
  18036. (goto-char beg)
  18037. (when (or (looking-at org-outline-regexp)
  18038. (re-search-forward org-outline-regexp-bol end t))
  18039. (setq level (org-outline-level)))
  18040. (goto-char end)
  18041. (skip-chars-forward " \t\r\n\v\f")
  18042. (not (or (eobp)
  18043. (and (bolp) (looking-at-p org-outline-regexp)
  18044. (<= (org-outline-level) level))))))))
  18045. (defun org-back-to-heading (&optional invisible-ok)
  18046. "Go back to beginning of heading."
  18047. (beginning-of-line)
  18048. (or (org-at-heading-p (not invisible-ok))
  18049. (let (found)
  18050. (save-excursion
  18051. ;; At inlinetask end. Move to bol, so that the following
  18052. ;; search goes to the beginning of the inlinetask.
  18053. (when (and (featurep 'org-inlinetask)
  18054. (fboundp 'org-inlinetask-end-p)
  18055. (org-inlinetask-end-p))
  18056. (goto-char (line-beginning-position)))
  18057. (while (not found)
  18058. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18059. nil t)
  18060. (user-error "Before first headline at position %d in buffer %s"
  18061. (point) (current-buffer)))
  18062. ;; Skip inlinetask end.
  18063. (if (and (featurep 'org-inlinetask)
  18064. (fboundp 'org-inlinetask-end-p)
  18065. (org-inlinetask-end-p))
  18066. (org-inlinetask-goto-beginning)
  18067. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18068. (point))))))
  18069. (goto-char found)
  18070. found)))
  18071. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18072. "Go back to heading or first point in buffer.
  18073. If point is before first heading go to first point in buffer
  18074. instead of back to heading."
  18075. (if (org-before-first-heading-p)
  18076. (goto-char (point-min))
  18077. (org-back-to-heading invisible-ok)))
  18078. (defun org-before-first-heading-p ()
  18079. "Before first heading?
  18080. Respect narrowing."
  18081. (if (org-element--cache-active-p)
  18082. (let ((cached-headline (org-element-lineage (org-element-at-point) '(headline) t)))
  18083. (or (not cached-headline)
  18084. (< (org-element-property :begin cached-headline) (point-min))))
  18085. (org-with-limited-levels
  18086. (save-excursion
  18087. (end-of-line)
  18088. (null (re-search-backward org-outline-regexp-bol nil t))))))
  18089. (defun org-at-heading-p (&optional invisible-not-ok)
  18090. "Return t if point is on a (possibly invisible) heading line.
  18091. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18092. (save-excursion
  18093. (beginning-of-line)
  18094. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18095. (looking-at outline-regexp))))
  18096. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18097. "Non-nil if point is under a commented heading.
  18098. This function also checks ancestors of the current headline,
  18099. unless optional argument NO-INHERITANCE is non-nil.
  18100. Optional argument ELEMENT contains element at point."
  18101. (save-match-data
  18102. (let ((el (or element (org-element-at-point nil 'cached))))
  18103. (if el
  18104. (catch :found
  18105. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18106. (if no-inheritance
  18107. (org-element-property :commentedp el)
  18108. (while el
  18109. (when (org-element-property :commentedp el)
  18110. (throw :found t))
  18111. (setq el (org-element-property :parent el)))))
  18112. (cond
  18113. ((org-before-first-heading-p) nil)
  18114. ((let ((headline (nth 4 (org-heading-components))))
  18115. (and headline
  18116. (let ((case-fold-search nil))
  18117. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18118. headline)))))
  18119. (no-inheritance nil)
  18120. (t
  18121. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p)))))))))
  18122. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18123. "Non-nil if point is under an archived heading.
  18124. This function also checks ancestors of the current headline,
  18125. unless optional argument NO-INHERITANCE is non-nil.
  18126. Optional argument ELEMENT contains element at point."
  18127. (cond
  18128. ((and (not element) (org-before-first-heading-p)) nil)
  18129. ((if element
  18130. (org-element-property :archivedp element)
  18131. (let ((tags (org-get-tags element 'local)))
  18132. (and tags
  18133. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18134. (no-inheritance nil)
  18135. (t
  18136. (if (org-element--cache-active-p)
  18137. (cl-some (lambda (el) (org-element-property :archivedp el))
  18138. (org-element-lineage (or element (org-element-at-point)) nil t))
  18139. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18140. (defun org-at-comment-p nil
  18141. "Return t if cursor is in a commented line."
  18142. (save-excursion
  18143. (save-match-data
  18144. (beginning-of-line)
  18145. (looking-at org-comment-regexp))))
  18146. (defun org-at-keyword-p nil
  18147. "Return t if cursor is at a keyword-line."
  18148. (save-excursion
  18149. (move-beginning-of-line 1)
  18150. (looking-at org-keyword-regexp)))
  18151. (defun org-at-drawer-p nil
  18152. "Return t if cursor is at a drawer keyword."
  18153. (save-excursion
  18154. (move-beginning-of-line 1)
  18155. (looking-at org-drawer-regexp)))
  18156. (defun org-at-block-p nil
  18157. "Return t if cursor is at a block keyword."
  18158. (save-excursion
  18159. (move-beginning-of-line 1)
  18160. (looking-at org-block-regexp)))
  18161. (defun org-point-at-end-of-empty-headline ()
  18162. "If point is at the end of an empty headline, return t, else nil.
  18163. If the heading only contains a TODO keyword, it is still considered
  18164. empty."
  18165. (let ((case-fold-search nil))
  18166. (and (looking-at "[ \t]*$")
  18167. org-todo-line-regexp
  18168. (save-excursion
  18169. (beginning-of-line)
  18170. (looking-at org-todo-line-regexp)
  18171. (string= (match-string 3) "")))))
  18172. (defun org-at-heading-or-item-p ()
  18173. (or (org-at-heading-p) (org-at-item-p)))
  18174. (defun org-up-heading-all (arg)
  18175. "Move to the heading line of which the present line is a subheading.
  18176. This function considers both visible and invisible heading lines.
  18177. With argument, move up ARG levels."
  18178. (outline-up-heading arg t))
  18179. (defvar-local org--up-heading-cache nil
  18180. "Buffer-local `org-up-heading-safe' cache.")
  18181. (defvar-local org--up-heading-cache-tick nil
  18182. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18183. (defun org-up-heading-safe ()
  18184. "Move to the heading line of which the present line is a subheading.
  18185. This version will not throw an error. It will return the level of the
  18186. headline found, or nil if no higher level is found.
  18187. Also, this function will be a lot faster than `outline-up-heading',
  18188. because it relies on stars being the outline starters. This can really
  18189. make a significant difference in outlines with very many siblings."
  18190. (let ((element (and (org-element--cache-active-p)
  18191. (org-element-at-point nil t))))
  18192. (if element
  18193. (let* ((current-heading (org-element-lineage element '(headline) 'with-self))
  18194. (parent (org-element-lineage current-heading '(headline))))
  18195. (if (and parent
  18196. (<= (point-min) (org-element-property :begin parent)))
  18197. (progn
  18198. (goto-char (org-element-property :begin parent))
  18199. (org-element-property :level parent))
  18200. (when (and current-heading
  18201. (<= (point-min) (org-element-property :begin current-heading)))
  18202. (goto-char (org-element-property :begin current-heading))
  18203. nil)))
  18204. (when (ignore-errors (org-back-to-heading t))
  18205. (let (level-cache)
  18206. (unless org--up-heading-cache
  18207. (setq org--up-heading-cache (make-hash-table)))
  18208. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18209. (setq level-cache (gethash (point) org--up-heading-cache)))
  18210. (when (<= (point-min) (car level-cache) (point-max))
  18211. ;; Parent is inside accessible part of the buffer.
  18212. (progn (goto-char (car level-cache))
  18213. (cdr level-cache)))
  18214. ;; Buffer modified. Invalidate cache.
  18215. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18216. (setq-local org--up-heading-cache-tick
  18217. (buffer-chars-modified-tick))
  18218. (clrhash org--up-heading-cache))
  18219. (let* ((level-up (1- (funcall outline-level)))
  18220. (pos (point))
  18221. (result (and (> level-up 0)
  18222. (re-search-backward
  18223. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18224. (funcall outline-level))))
  18225. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18226. result)))))))
  18227. (defun org-up-heading-or-point-min ()
  18228. "Move to the heading line of which the present is a subheading, or point-min.
  18229. This version is needed to make point-min behave like a virtual
  18230. heading of level 0 for property-inheritance. It will return the
  18231. level of the headline found (down to 0) or nil if already at a
  18232. point before the first headline or at point-min."
  18233. (when (ignore-errors (org-back-to-heading t))
  18234. (if (< 1 (funcall outline-level))
  18235. (or (org-up-heading-safe)
  18236. ;; The first heading may not be level 1 heading.
  18237. (goto-char (point-min)))
  18238. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18239. (defun org-first-sibling-p ()
  18240. "Is this heading the first child of its parents?"
  18241. (interactive)
  18242. (let ((re org-outline-regexp-bol)
  18243. level l)
  18244. (unless (org-at-heading-p t)
  18245. (user-error "Not at a heading"))
  18246. (setq level (funcall outline-level))
  18247. (save-excursion
  18248. (if (not (re-search-backward re nil t))
  18249. t
  18250. (setq l (funcall outline-level))
  18251. (< l level)))))
  18252. (defun org-goto-sibling (&optional previous)
  18253. "Goto the next sibling, even if it is invisible.
  18254. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18255. when a sibling was found. When none is found, return nil and don't
  18256. move point."
  18257. (let ((fun (if previous 're-search-backward 're-search-forward))
  18258. (pos (point))
  18259. (re org-outline-regexp-bol)
  18260. level l)
  18261. (when (ignore-errors (org-back-to-heading t))
  18262. (setq level (funcall outline-level))
  18263. (catch 'exit
  18264. (or previous (forward-char 1))
  18265. (while (funcall fun re nil t)
  18266. (setq l (funcall outline-level))
  18267. (when (< l level) (goto-char pos) (throw 'exit nil))
  18268. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18269. (goto-char pos)
  18270. nil))))
  18271. (defun org-goto-first-child (&optional element)
  18272. "Goto the first child, even if it is invisible.
  18273. Return t when a child was found. Otherwise don't move point and
  18274. return nil."
  18275. (if (org-element--cache-active-p)
  18276. (let ((heading (org-element-lineage
  18277. (or element (org-element-at-point))
  18278. '(headline inlinetask org-data)
  18279. t)))
  18280. (when heading
  18281. (unless (or (eq 'inlinetask (org-element-type heading))
  18282. (not (org-element-property :contents-begin heading)))
  18283. (let ((pos (point)))
  18284. (goto-char (org-element-property :contents-begin heading))
  18285. (if (re-search-forward
  18286. org-outline-regexp-bol
  18287. (org-element-property :end heading)
  18288. t)
  18289. (progn (goto-char (match-beginning 0)) t)
  18290. (goto-char pos) nil)))))
  18291. (let (level (pos (point)) (re org-outline-regexp-bol))
  18292. (when (org-back-to-heading-or-point-min t)
  18293. (setq level (org-outline-level))
  18294. (forward-char 1)
  18295. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18296. (progn (goto-char (match-beginning 0)) t)
  18297. (goto-char pos) nil)))))
  18298. (defun org-get-next-sibling ()
  18299. "Move to next heading of the same level, and return point.
  18300. If there is no such heading, return nil.
  18301. This is like outline-next-sibling, but invisible headings are ok."
  18302. (let ((level (funcall outline-level)))
  18303. (outline-next-heading)
  18304. (while (and (not (eobp)) (> (funcall outline-level) level))
  18305. (outline-next-heading))
  18306. (unless (or (eobp) (< (funcall outline-level) level))
  18307. (point))))
  18308. (defun org-get-previous-sibling ()
  18309. "Move to previous heading of the same level, and return point.
  18310. If there is no such heading, return nil."
  18311. (let ((opoint (point))
  18312. (level (funcall outline-level)))
  18313. (outline-previous-heading)
  18314. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18315. (while (and (> (funcall outline-level) level)
  18316. (not (bobp)))
  18317. (outline-previous-heading))
  18318. (unless (< (funcall outline-level) level)
  18319. (point)))))
  18320. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18321. "Goto to the end of a subtree at point or for ELEMENT heading."
  18322. ;; This contains an exact copy of the original function, but it uses
  18323. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18324. ;; trees and before first headline. And is uses an invisible-ok argument.
  18325. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18326. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18327. ;; with many children and grandchildren etc, this can be much faster
  18328. ;; than the outline version.
  18329. (org-back-to-heading-or-point-min invisible-ok)
  18330. (unless (and (org-element--cache-active-p)
  18331. (let ((cached (or element (org-element-at-point nil t))))
  18332. (and cached
  18333. (eq 'headline (org-element-type cached))
  18334. (goto-char (org-element-property
  18335. :end cached)))))
  18336. (let ((first t)
  18337. (level (funcall outline-level)))
  18338. (cond ((= level 0)
  18339. (goto-char (point-max)))
  18340. ((and (derived-mode-p 'org-mode) (< level 1000))
  18341. ;; A true heading (not a plain list item), in Org
  18342. ;; This means we can easily find the end by looking
  18343. ;; only for the right number of stars. Using a regexp to do
  18344. ;; this is so much faster than using a Lisp loop.
  18345. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18346. (forward-char 1)
  18347. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18348. (t
  18349. ;; something else, do it the slow way
  18350. (while (and (not (eobp))
  18351. (or first (> (funcall outline-level) level)))
  18352. (setq first nil)
  18353. (outline-next-heading))))))
  18354. (unless to-heading
  18355. (when (memq (preceding-char) '(?\n ?\^M))
  18356. ;; Go to end of line before heading
  18357. (forward-char -1)
  18358. (when (memq (preceding-char) '(?\n ?\^M))
  18359. ;; leave blank line before heading
  18360. (forward-char -1))))
  18361. (point))
  18362. (defun org-end-of-meta-data (&optional full)
  18363. "Skip planning line and properties drawer in current entry.
  18364. When optional argument FULL is t, also skip planning information,
  18365. clocking lines and any kind of drawer.
  18366. When FULL is non-nil but not t, skip planning information,
  18367. properties, clocking lines and logbook drawers."
  18368. (org-back-to-heading t)
  18369. (forward-line)
  18370. ;; Skip planning information.
  18371. (when (looking-at-p org-planning-line-re) (forward-line))
  18372. ;; Skip property drawer.
  18373. (when (looking-at org-property-drawer-re)
  18374. (goto-char (match-end 0))
  18375. (forward-line))
  18376. ;; When FULL is not nil, skip more.
  18377. (when (and full (not (org-at-heading-p)))
  18378. (catch 'exit
  18379. (let ((end (save-excursion (outline-next-heading) (point)))
  18380. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18381. (while (not (eobp))
  18382. (cond ;; Skip clock lines.
  18383. ((looking-at-p re) (forward-line))
  18384. ;; Skip logbook drawer.
  18385. ((looking-at-p org-logbook-drawer-re)
  18386. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18387. (forward-line)
  18388. (throw 'exit t)))
  18389. ;; When FULL is t, skip regular drawer too.
  18390. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18391. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18392. (forward-line)
  18393. (throw 'exit t)))
  18394. (t (throw 'exit t))))))))
  18395. (defun org--line-fully-invisible-p ()
  18396. "Return non-nil if the current line is fully invisible."
  18397. (let ((line-beg (line-beginning-position))
  18398. (line-pos (1- (line-end-position)))
  18399. (is-invisible t))
  18400. (while (and (< line-beg line-pos) is-invisible)
  18401. (setq is-invisible (org-invisible-p line-pos))
  18402. (setq line-pos (1- line-pos)))
  18403. is-invisible))
  18404. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18405. "Move forward to the ARG'th subheading at same level as this one.
  18406. Stop at the first and last subheadings of a superior heading.
  18407. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18408. non-nil it will also look at invisible ones."
  18409. (interactive "p")
  18410. (let ((backward? (and arg (< arg 0))))
  18411. (if (org-before-first-heading-p)
  18412. (if backward? (goto-char (point-min)) (outline-next-heading))
  18413. (org-back-to-heading invisible-ok)
  18414. (unless backward? (end-of-line)) ;do not match current headline
  18415. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18416. (f (if backward? #'re-search-backward #'re-search-forward))
  18417. (count (if arg (abs arg) 1))
  18418. (result (point)))
  18419. (while (and (> count 0)
  18420. (funcall f org-outline-regexp-bol nil 'move))
  18421. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18422. (cond ((< l level) (setq count 0))
  18423. ((and (= l level)
  18424. (or invisible-ok
  18425. ;; FIXME: See commit a700fadd72 and the
  18426. ;; related discussion on why using
  18427. ;; `org--line-fully-invisible-p' is needed
  18428. ;; here, which is to serve the needs of an
  18429. ;; external package. If the change is
  18430. ;; wrong regarding Org itself, it should
  18431. ;; be removed.
  18432. (not (org--line-fully-invisible-p))))
  18433. (cl-decf count)
  18434. (when (= l level) (setq result (point)))))))
  18435. (goto-char result))
  18436. (beginning-of-line))))
  18437. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18438. "Move backward to the ARG'th subheading at same level as this one.
  18439. Stop at the first and last subheadings of a superior heading."
  18440. (interactive "p")
  18441. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18442. (defun org-next-visible-heading--overlays (arg)
  18443. "Move to the next visible heading line.
  18444. With ARG, repeats or can move backward if negative."
  18445. (interactive "p")
  18446. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18447. (if (< arg 0)
  18448. (beginning-of-line)
  18449. (end-of-line))
  18450. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18451. (unless (bobp)
  18452. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18453. (`(outline . ,o)
  18454. (goto-char (overlay-start o))
  18455. (re-search-backward regexp nil :move))
  18456. (_ nil))))
  18457. (cl-incf arg))
  18458. (while (and (> arg 0) (re-search-forward regexp nil t))
  18459. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18460. (`(outline . ,o)
  18461. (goto-char (overlay-end o))
  18462. (re-search-forward regexp nil :move))
  18463. (_
  18464. (end-of-line)
  18465. nil))) ;leave the loop
  18466. (cl-decf arg))
  18467. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18468. (defun org-next-visible-heading--text-properties (arg)
  18469. "Move to the next visible heading line.
  18470. With ARG, repeats or can move backward if negative."
  18471. (interactive "p")
  18472. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18473. (if (< arg 0)
  18474. (beginning-of-line)
  18475. (end-of-line))
  18476. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18477. (unless (bobp)
  18478. (when (org-fold-folded-p)
  18479. (goto-char (org-fold-previous-visibility-change))
  18480. (unless (looking-at-p regexp)
  18481. (re-search-backward regexp nil :mode))))
  18482. (cl-incf arg))
  18483. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18484. (when (org-fold-folded-p)
  18485. (goto-char (org-fold-next-visibility-change))
  18486. (skip-chars-forward " \t\n")
  18487. (end-of-line))
  18488. (cl-decf arg))
  18489. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18490. (defun org-next-visible-heading (arg)
  18491. "Move to the next visible heading line.
  18492. With ARG, repeats or can move backward if negative."
  18493. (interactive "p")
  18494. (if (eq org-fold-core-style 'text-properties)
  18495. (org-next-visible-heading--text-properties arg)
  18496. (org-next-visible-heading--overlays arg)))
  18497. (defun org-previous-visible-heading (arg)
  18498. "Move to the previous visible heading.
  18499. With ARG, repeats or can move forward if negative."
  18500. (interactive "p")
  18501. (org-next-visible-heading (- arg)))
  18502. (defun org-forward-paragraph (&optional arg)
  18503. "Move forward by a paragraph, or equivalent, unit.
  18504. With argument ARG, do it ARG times;
  18505. a negative argument ARG = -N means move backward N paragraphs.
  18506. The function moves point between two structural
  18507. elements (paragraphs, tables, lists, etc.).
  18508. It also provides the following special moves for convenience:
  18509. - on a table or a property drawer, move to its beginning;
  18510. - on comment, example, export, source and verse blocks, stop
  18511. at blank lines;
  18512. - skip consecutive clocks, diary S-exps, and keywords."
  18513. (interactive "^p")
  18514. (unless arg (setq arg 1))
  18515. (if (< arg 0) (org-backward-paragraph (- arg))
  18516. (while (and (> arg 0) (not (eobp)))
  18517. (org--forward-paragraph-once)
  18518. (cl-decf arg))
  18519. ;; Return moves left.
  18520. arg))
  18521. (defun org-backward-paragraph (&optional arg)
  18522. "Move backward by a paragraph, or equivalent, unit.
  18523. With argument ARG, do it ARG times;
  18524. a negative argument ARG = -N means move forward N paragraphs.
  18525. The function moves point between two structural
  18526. elements (paragraphs, tables, lists, etc.).
  18527. It also provides the following special moves for convenience:
  18528. - on a table or a property drawer, move to its beginning;
  18529. - on comment, example, export, source and verse blocks, stop
  18530. at blank lines;
  18531. - skip consecutive clocks, diary S-exps, and keywords."
  18532. (interactive "^p")
  18533. (unless arg (setq arg 1))
  18534. (if (< arg 0) (org-forward-paragraph (- arg))
  18535. (while (and (> arg 0) (not (bobp)))
  18536. (org--backward-paragraph-once)
  18537. (cl-decf arg))
  18538. ;; Return moves left.
  18539. arg))
  18540. (defun org--paragraph-at-point ()
  18541. "Return paragraph, or equivalent, element at point.
  18542. Paragraph element at point is the element at point, with the
  18543. following special cases:
  18544. - treat table rows (resp. node properties) as the table
  18545. \(resp. property drawer) containing them.
  18546. - treat plain lists with an item every line as a whole.
  18547. - treat consecutive keywords, clocks, and diary-sexps as a single
  18548. block.
  18549. Function may return a real element, or a pseudo-element with type
  18550. `pseudo-paragraph'."
  18551. (let* ((e (org-element-at-point))
  18552. (type (org-element-type e))
  18553. ;; If we need to fake a new pseudo-element, triplet is
  18554. ;;
  18555. ;; (BEG END PARENT)
  18556. ;;
  18557. ;; where BEG and END are element boundaries, and PARENT the
  18558. ;; element containing it, or nil.
  18559. (triplet
  18560. (cond
  18561. ((memq type '(table property-drawer))
  18562. (list (org-element-property :begin e)
  18563. (org-element-property :end e)
  18564. (org-element-property :parent e)))
  18565. ((memq type '(node-property table-row))
  18566. (let ((e (org-element-property :parent e)))
  18567. (list (org-element-property :begin e)
  18568. (org-element-property :end e)
  18569. (org-element-property :parent e))))
  18570. ((memq type '(clock diary-sexp keyword))
  18571. (let* ((regexp (pcase type
  18572. (`clock org-clock-line-re)
  18573. (`diary-sexp "%%(")
  18574. (_ org-keyword-regexp)))
  18575. (end (if (< 0 (org-element-property :post-blank e))
  18576. (org-element-property :end e)
  18577. (org-with-wide-buffer
  18578. (forward-line)
  18579. (while (looking-at regexp) (forward-line))
  18580. (skip-chars-forward " \t\n")
  18581. (line-beginning-position))))
  18582. (begin (org-with-point-at (org-element-property :begin e)
  18583. (while (and (not (bobp)) (looking-at regexp))
  18584. (forward-line -1))
  18585. ;; We may have gotten one line too far.
  18586. (if (looking-at regexp)
  18587. (point)
  18588. (line-beginning-position 2)))))
  18589. (list begin end (org-element-property :parent e))))
  18590. ;; Find the full plain list containing point, the check it
  18591. ;; contains exactly one line per item.
  18592. ((let ((l (org-element-lineage e '(plain-list) t)))
  18593. (while (memq (org-element-type (org-element-property :parent l))
  18594. '(item plain-list))
  18595. (setq l (org-element-property :parent l)))
  18596. (and l
  18597. (org-with-point-at (org-element-property :post-affiliated l)
  18598. (forward-line (length (org-element-property :structure l)))
  18599. (= (point) (org-element-property :contents-end l)))
  18600. ;; Return value.
  18601. (list (org-element-property :begin l)
  18602. (org-element-property :end l)
  18603. (org-element-property :parent l)))))
  18604. (t nil)))) ;no triplet: return element
  18605. (pcase triplet
  18606. (`(,b ,e ,p)
  18607. (org-element-create
  18608. 'pseudo-paragraph
  18609. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18610. (_ e))))
  18611. (defun org--forward-paragraph-once--overlays ()
  18612. "Move forward to end of paragraph or equivalent, once.
  18613. See `org-forward-paragraph'."
  18614. (interactive)
  18615. (save-restriction
  18616. (widen)
  18617. (skip-chars-forward " \t\n")
  18618. (cond
  18619. ((eobp) nil)
  18620. ;; When inside a folded part, move out of it.
  18621. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18622. (`(,(or `outline `org-hide-block) . ,o)
  18623. (goto-char (overlay-end o))
  18624. (forward-line)
  18625. t)
  18626. (_ nil)))
  18627. (t
  18628. (let* ((element (org--paragraph-at-point))
  18629. (type (org-element-type element))
  18630. (contents-begin (org-element-property :contents-begin element))
  18631. (end (org-element-property :end element))
  18632. (post-affiliated (org-element-property :post-affiliated element)))
  18633. (cond
  18634. ((eq type 'plain-list)
  18635. (forward-char)
  18636. (org--forward-paragraph-once))
  18637. ;; If the element is folded, skip it altogether.
  18638. ((pcase (org-with-point-at post-affiliated
  18639. (get-char-property-and-overlay (line-end-position)
  18640. 'invisible))
  18641. (`(,(or `outline `org-hide-block) . ,o)
  18642. (goto-char (overlay-end o))
  18643. (forward-line)
  18644. t)
  18645. (_ nil)))
  18646. ;; At a greater element, move inside.
  18647. ((and contents-begin
  18648. (> contents-begin (point))
  18649. (not (eq type 'paragraph)))
  18650. (goto-char contents-begin)
  18651. ;; Items and footnote definitions contents may not start at
  18652. ;; the beginning of the line. In this case, skip until the
  18653. ;; next paragraph.
  18654. (cond
  18655. ((not (bolp)) (org--forward-paragraph-once))
  18656. ((org-previous-line-empty-p) (forward-line -1))
  18657. (t nil)))
  18658. ;; Move between empty lines in some blocks.
  18659. ((memq type '(comment-block example-block export-block src-block
  18660. verse-block))
  18661. (let ((contents-start
  18662. (org-with-point-at post-affiliated
  18663. (line-beginning-position 2))))
  18664. (if (< (point) contents-start)
  18665. (goto-char contents-start)
  18666. (let ((contents-end
  18667. (org-with-point-at end
  18668. (skip-chars-backward " \t\n")
  18669. (line-beginning-position))))
  18670. (cond
  18671. ((>= (point) contents-end)
  18672. (goto-char end)
  18673. (skip-chars-backward " \t\n")
  18674. (forward-line))
  18675. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18676. (forward-line -1))
  18677. (t nil))))))
  18678. (t
  18679. ;; Move to element's end.
  18680. (goto-char end)
  18681. (skip-chars-backward " \t\n")
  18682. (forward-line))))))))
  18683. (defun org--forward-paragraph-once--text-properties ()
  18684. "Move forward to end of paragraph or equivalent, once.
  18685. See `org-forward-paragraph'."
  18686. (interactive)
  18687. (save-restriction
  18688. (widen)
  18689. (skip-chars-forward " \t\n")
  18690. (cond
  18691. ((eobp) nil)
  18692. ;; When inside a folded part, move out of it.
  18693. ((when (org-invisible-p nil t)
  18694. (goto-char (cdr (org-fold-get-region-at-point)))
  18695. (forward-line)
  18696. t))
  18697. (t
  18698. (let* ((element (org--paragraph-at-point))
  18699. (type (org-element-type element))
  18700. (contents-begin (org-element-property :contents-begin element))
  18701. (end (org-element-property :end element))
  18702. (post-affiliated (org-element-property :post-affiliated element)))
  18703. (cond
  18704. ((eq type 'plain-list)
  18705. (forward-char)
  18706. (org--forward-paragraph-once))
  18707. ;; If the element is folded, skip it altogether.
  18708. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18709. (goto-char (cdr (org-fold-get-region-at-point
  18710. nil
  18711. (org-with-point-at post-affiliated
  18712. (line-end-position)))))
  18713. (forward-line)
  18714. t))
  18715. ;; At a greater element, move inside.
  18716. ((and contents-begin
  18717. (> contents-begin (point))
  18718. (not (eq type 'paragraph)))
  18719. (goto-char contents-begin)
  18720. ;; Items and footnote definitions contents may not start at
  18721. ;; the beginning of the line. In this case, skip until the
  18722. ;; next paragraph.
  18723. (cond
  18724. ((not (bolp)) (org--forward-paragraph-once))
  18725. ((org-previous-line-empty-p) (forward-line -1))
  18726. (t nil)))
  18727. ;; Move between empty lines in some blocks.
  18728. ((memq type '(comment-block example-block export-block src-block
  18729. verse-block))
  18730. (let ((contents-start
  18731. (org-with-point-at post-affiliated
  18732. (line-beginning-position 2))))
  18733. (if (< (point) contents-start)
  18734. (goto-char contents-start)
  18735. (let ((contents-end
  18736. (org-with-point-at end
  18737. (skip-chars-backward " \t\n")
  18738. (line-beginning-position))))
  18739. (cond
  18740. ((>= (point) contents-end)
  18741. (goto-char end)
  18742. (skip-chars-backward " \t\n")
  18743. (forward-line))
  18744. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18745. (forward-line -1))
  18746. (t nil))))))
  18747. (t
  18748. ;; Move to element's end.
  18749. (goto-char end)
  18750. (skip-chars-backward " \t\n")
  18751. (forward-line))))))))
  18752. (defun org--forward-paragraph-once ()
  18753. "Move forward to end of paragraph or equivalent, once.
  18754. See `org-forward-paragraph'."
  18755. (interactive)
  18756. (if (eq org-fold-core-style 'text-properties)
  18757. (org--forward-paragraph-once--text-properties)
  18758. (org--forward-paragraph-once--overlays)))
  18759. (defun org--backward-paragraph-once--overlays ()
  18760. "Move backward to start of paragraph or equivalent, once.
  18761. See `org-backward-paragraph'."
  18762. (interactive)
  18763. (save-restriction
  18764. (widen)
  18765. (cond
  18766. ((bobp) nil)
  18767. ;; Blank lines at the beginning of the buffer.
  18768. ((and (org-match-line "^[ \t]*$")
  18769. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18770. (goto-char (point-min)))
  18771. ;; When inside a folded part, move out of it.
  18772. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18773. (`(,(or `outline `org-hide-block) . ,o)
  18774. (goto-char (1- (overlay-start o)))
  18775. (org--backward-paragraph-once)
  18776. t)
  18777. (_ nil)))
  18778. (t
  18779. (let* ((element (org--paragraph-at-point))
  18780. (type (org-element-type element))
  18781. (begin (org-element-property :begin element))
  18782. (post-affiliated (org-element-property :post-affiliated element))
  18783. (contents-end (org-element-property :contents-end element))
  18784. (end (org-element-property :end element))
  18785. (parent (org-element-property :parent element))
  18786. (reach
  18787. ;; Move to the visible empty line above position P, or
  18788. ;; to position P. Return t.
  18789. (lambda (p)
  18790. (goto-char p)
  18791. (when (and (org-previous-line-empty-p)
  18792. (let ((end (line-end-position 0)))
  18793. (or (= end (point-min))
  18794. (not (org-invisible-p (1- end))))))
  18795. (forward-line -1))
  18796. t)))
  18797. (cond
  18798. ;; Already at the beginning of an element.
  18799. ((= begin (point))
  18800. (cond
  18801. ;; There is a blank line above. Move there.
  18802. ((and (org-previous-line-empty-p)
  18803. (let ((lep (line-end-position 0)))
  18804. ;; When the first headline start at point 2, don't choke while
  18805. ;; checking with `org-invisible-p'.
  18806. (or (= lep 1)
  18807. (not (org-invisible-p (1- (line-end-position 0)))))))
  18808. (forward-line -1))
  18809. ;; At the beginning of the first element within a greater
  18810. ;; element. Move to the beginning of the greater element.
  18811. ((and parent
  18812. (not (eq 'section (org-element-type parent)))
  18813. (= begin (org-element-property :contents-begin parent)))
  18814. (funcall reach (org-element-property :begin parent)))
  18815. ;; Since we have to move anyway, find the beginning
  18816. ;; position of the element above.
  18817. (t
  18818. (forward-char -1)
  18819. (org--backward-paragraph-once))))
  18820. ;; Skip paragraphs at the very beginning of footnote
  18821. ;; definitions or items.
  18822. ((and (eq type 'paragraph)
  18823. (org-with-point-at begin (not (bolp))))
  18824. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  18825. ;; If the element is folded, skip it altogether.
  18826. ((org-with-point-at post-affiliated
  18827. (org-invisible-p (line-end-position) t))
  18828. (funcall reach begin))
  18829. ;; At the end of a greater element, move inside.
  18830. ((and contents-end
  18831. (<= contents-end (point))
  18832. (not (eq type 'paragraph)))
  18833. (cond
  18834. ((memq type '(footnote-definition plain-list))
  18835. (skip-chars-backward " \t\n")
  18836. (org--backward-paragraph-once))
  18837. ((= contents-end (point))
  18838. (forward-char -1)
  18839. (org--backward-paragraph-once))
  18840. (t
  18841. (goto-char contents-end))))
  18842. ;; Move between empty lines in some blocks.
  18843. ((and (memq type '(comment-block example-block export-block src-block
  18844. verse-block))
  18845. (let ((contents-start
  18846. (org-with-point-at post-affiliated
  18847. (line-beginning-position 2))))
  18848. (when (> (point) contents-start)
  18849. (let ((contents-end
  18850. (org-with-point-at end
  18851. (skip-chars-backward " \t\n")
  18852. (line-beginning-position))))
  18853. (if (> (point) contents-end)
  18854. (progn (goto-char contents-end) t)
  18855. (skip-chars-backward " \t\n" begin)
  18856. (re-search-backward "^[ \t]*\n" contents-start :move)
  18857. t))))))
  18858. ;; Move to element's start.
  18859. (t
  18860. (funcall reach begin))))))))
  18861. (defun org--backward-paragraph-once--text-properties ()
  18862. "Move backward to start of paragraph or equivalent, once.
  18863. See `org-backward-paragraph'."
  18864. (interactive)
  18865. (save-restriction
  18866. (widen)
  18867. (cond
  18868. ((bobp) nil)
  18869. ;; Blank lines at the beginning of the buffer.
  18870. ((and (org-match-line "^[ \t]*$")
  18871. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18872. (goto-char (point-min)))
  18873. ;; When inside a folded part, move out of it.
  18874. ((when (org-invisible-p (1- (point)) t)
  18875. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  18876. (org--backward-paragraph-once)
  18877. t))
  18878. (t
  18879. (let* ((element (org--paragraph-at-point))
  18880. (type (org-element-type element))
  18881. (begin (org-element-property :begin element))
  18882. (post-affiliated (org-element-property :post-affiliated element))
  18883. (contents-end (org-element-property :contents-end element))
  18884. (end (org-element-property :end element))
  18885. (parent (org-element-property :parent element))
  18886. (reach
  18887. ;; Move to the visible empty line above position P, or
  18888. ;; to position P. Return t.
  18889. (lambda (p)
  18890. (goto-char p)
  18891. (when (and (org-previous-line-empty-p)
  18892. (let ((end (line-end-position 0)))
  18893. (or (= end (point-min))
  18894. (not (org-invisible-p (1- end))))))
  18895. (forward-line -1))
  18896. t)))
  18897. (cond
  18898. ;; Already at the beginning of an element.
  18899. ((= begin (point))
  18900. (cond
  18901. ;; There is a blank line above. Move there.
  18902. ((and (org-previous-line-empty-p)
  18903. (not (org-invisible-p (1- (line-end-position 0)))))
  18904. (forward-line -1))
  18905. ;; At the beginning of the first element within a greater
  18906. ;; element. Move to the beginning of the greater element.
  18907. ((and parent
  18908. (not (eq 'section (org-element-type parent)))
  18909. (= begin (org-element-property :contents-begin parent)))
  18910. (funcall reach (org-element-property :begin parent)))
  18911. ;; Since we have to move anyway, find the beginning
  18912. ;; position of the element above.
  18913. (t
  18914. (forward-char -1)
  18915. (org--backward-paragraph-once))))
  18916. ;; Skip paragraphs at the very beginning of footnote
  18917. ;; definitions or items.
  18918. ((and (eq type 'paragraph)
  18919. (org-with-point-at begin (not (bolp))))
  18920. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  18921. ;; If the element is folded, skip it altogether.
  18922. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18923. (funcall reach begin))
  18924. ;; At the end of a greater element, move inside.
  18925. ((and contents-end
  18926. (<= contents-end (point))
  18927. (not (eq type 'paragraph)))
  18928. (cond
  18929. ((memq type '(footnote-definition plain-list))
  18930. (skip-chars-backward " \t\n")
  18931. (org--backward-paragraph-once))
  18932. ((= contents-end (point))
  18933. (forward-char -1)
  18934. (org--backward-paragraph-once))
  18935. (t
  18936. (goto-char contents-end))))
  18937. ;; Move between empty lines in some blocks.
  18938. ((and (memq type '(comment-block example-block export-block src-block
  18939. verse-block))
  18940. (let ((contents-start
  18941. (org-with-point-at post-affiliated
  18942. (line-beginning-position 2))))
  18943. (when (> (point) contents-start)
  18944. (let ((contents-end
  18945. (org-with-point-at end
  18946. (skip-chars-backward " \t\n")
  18947. (line-beginning-position))))
  18948. (if (> (point) contents-end)
  18949. (progn (goto-char contents-end) t)
  18950. (skip-chars-backward " \t\n" begin)
  18951. (re-search-backward "^[ \t]*\n" contents-start :move)
  18952. t))))))
  18953. ;; Move to element's start.
  18954. (t
  18955. (funcall reach begin))))))))
  18956. (defun org--backward-paragraph-once ()
  18957. "Move backward to start of paragraph or equivalent, once.
  18958. See `org-backward-paragraph'."
  18959. (interactive)
  18960. (if (eq org-fold-core-style 'text-properties)
  18961. (org--backward-paragraph-once--text-properties)
  18962. (org--backward-paragraph-once--overlays)))
  18963. (defun org-forward-element ()
  18964. "Move forward by one element.
  18965. Move to the next element at the same level, when possible."
  18966. (interactive)
  18967. (cond ((eobp) (user-error "Cannot move further down"))
  18968. ((org-with-limited-levels (org-at-heading-p))
  18969. (let ((origin (point)))
  18970. (goto-char (org-end-of-subtree nil t))
  18971. (unless (org-with-limited-levels (org-at-heading-p))
  18972. (goto-char origin)
  18973. (user-error "Cannot move further down"))))
  18974. (t
  18975. (let* ((elem (org-element-at-point))
  18976. (end (org-element-property :end elem))
  18977. (parent (org-element-property :parent elem)))
  18978. (cond ((and parent (= (org-element-property :contents-end parent) end))
  18979. (goto-char (org-element-property :end parent)))
  18980. ((integer-or-marker-p end) (goto-char end))
  18981. (t (message "No element at point")))))))
  18982. (defun org-backward-element ()
  18983. "Move backward by one element.
  18984. Move to the previous element at the same level, when possible."
  18985. (interactive)
  18986. (cond ((bobp) (user-error "Cannot move further up"))
  18987. ((org-with-limited-levels (org-at-heading-p))
  18988. ;; At a headline, move to the previous one, if any, or stay
  18989. ;; here.
  18990. (let ((origin (point)))
  18991. (org-with-limited-levels (org-backward-heading-same-level 1))
  18992. ;; When current headline has no sibling above, move to its
  18993. ;; parent.
  18994. (when (= (point) origin)
  18995. (or (org-with-limited-levels (org-up-heading-safe))
  18996. (progn (goto-char origin)
  18997. (user-error "Cannot move further up"))))))
  18998. (t
  18999. (let* ((elem (org-element-at-point))
  19000. (beg (org-element-property :begin elem)))
  19001. (cond
  19002. ;; Move to beginning of current element if point isn't
  19003. ;; there already.
  19004. ((null beg) (message "No element at point"))
  19005. ((/= (point) beg) (goto-char beg))
  19006. (t (goto-char beg)
  19007. (skip-chars-backward " \r\t\n")
  19008. (unless (bobp)
  19009. (let ((prev (org-element-at-point)))
  19010. (goto-char (org-element-property :begin prev))
  19011. (while (and (setq prev (org-element-property :parent prev))
  19012. (<= (org-element-property :end prev) beg))
  19013. (goto-char (org-element-property :begin prev)))))))))))
  19014. (defun org-up-element ()
  19015. "Move to upper element."
  19016. (interactive)
  19017. (if (org-with-limited-levels (org-at-heading-p))
  19018. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19019. (let* ((elem (org-element-at-point))
  19020. (parent (org-element-property :parent elem)))
  19021. (if (and parent
  19022. (not (memq (org-element-type parent) '(section org-data))))
  19023. (goto-char (org-element-property :begin parent))
  19024. (if (org-with-limited-levels (org-before-first-heading-p))
  19025. (user-error "No surrounding element")
  19026. (org-with-limited-levels (org-back-to-heading)))))))
  19027. (defun org-down-element ()
  19028. "Move to inner element."
  19029. (interactive)
  19030. (let ((element (org-element-at-point)))
  19031. (cond
  19032. ((memq (org-element-type element) '(plain-list table))
  19033. (goto-char (org-element-property :contents-begin element))
  19034. (forward-char))
  19035. ((memq (org-element-type element) org-element-greater-elements)
  19036. ;; If contents are hidden, first disclose them.
  19037. (when (org-invisible-p (line-end-position)) (org-cycle))
  19038. (goto-char (or (org-element-property :contents-begin element)
  19039. (user-error "No content for this element"))))
  19040. (t (user-error "No inner element")))))
  19041. (defun org-drag-element-backward ()
  19042. "Move backward element at point."
  19043. (interactive)
  19044. (let ((elem (or (org-element-at-point)
  19045. (user-error "No element at point"))))
  19046. (if (eq (org-element-type elem) 'headline)
  19047. ;; Preserve point when moving a whole tree, even if point was
  19048. ;; on blank lines below the headline.
  19049. (let ((offset (skip-chars-backward " \t\n")))
  19050. (unwind-protect (org-move-subtree-up)
  19051. (forward-char (- offset))))
  19052. (let ((prev-elem
  19053. (save-excursion
  19054. (goto-char (org-element-property :begin elem))
  19055. (skip-chars-backward " \r\t\n")
  19056. (unless (bobp)
  19057. (let* ((beg (org-element-property :begin elem))
  19058. (prev (org-element-at-point))
  19059. (up prev))
  19060. (while (and (setq up (org-element-property :parent up))
  19061. (<= (org-element-property :end up) beg))
  19062. (setq prev up))
  19063. prev)))))
  19064. ;; Error out if no previous element or previous element is
  19065. ;; a parent of the current one.
  19066. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19067. (user-error "Cannot drag element backward")
  19068. (let ((pos (point)))
  19069. (org-element-swap-A-B prev-elem elem)
  19070. (goto-char (+ (org-element-property :begin prev-elem)
  19071. (- pos (org-element-property :begin elem))))))))))
  19072. (defun org-drag-element-forward ()
  19073. "Move forward element at point."
  19074. (interactive)
  19075. (let* ((pos (point))
  19076. (elem (or (org-element-at-point)
  19077. (user-error "No element at point"))))
  19078. (when (= (point-max) (org-element-property :end elem))
  19079. (user-error "Cannot drag element forward"))
  19080. (goto-char (org-element-property :end elem))
  19081. (let ((next-elem (org-element-at-point)))
  19082. (when (or (org-element-nested-p elem next-elem)
  19083. (and (eq (org-element-type next-elem) 'headline)
  19084. (not (eq (org-element-type elem) 'headline))))
  19085. (goto-char pos)
  19086. (user-error "Cannot drag element forward"))
  19087. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19088. ;; body's length (without final blanks) and by the length of
  19089. ;; blanks between ELEM and NEXT-ELEM.
  19090. (let ((size-next (- (save-excursion
  19091. (goto-char (org-element-property :end next-elem))
  19092. (skip-chars-backward " \r\t\n")
  19093. (forward-line)
  19094. ;; Small correction if buffer doesn't end
  19095. ;; with a newline character.
  19096. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19097. (org-element-property :begin next-elem)))
  19098. (size-blank (- (org-element-property :end elem)
  19099. (save-excursion
  19100. (goto-char (org-element-property :end elem))
  19101. (skip-chars-backward " \r\t\n")
  19102. (forward-line)
  19103. (point)))))
  19104. (org-element-swap-A-B elem next-elem)
  19105. (goto-char (+ pos size-next size-blank))))))
  19106. (defun org-drag-line-forward (arg)
  19107. "Drag the line at point ARG lines forward."
  19108. (interactive "p")
  19109. (dotimes (_ (abs arg))
  19110. (let ((c (current-column)))
  19111. (if (< 0 arg)
  19112. (progn
  19113. (beginning-of-line 2)
  19114. (transpose-lines 1)
  19115. (beginning-of-line 0))
  19116. (transpose-lines 1)
  19117. (beginning-of-line -1))
  19118. (org-move-to-column c))))
  19119. (defun org-drag-line-backward (arg)
  19120. "Drag the line at point ARG lines backward."
  19121. (interactive "p")
  19122. (org-drag-line-forward (- arg)))
  19123. (defun org-mark-element ()
  19124. "Put point at beginning of this element, mark at end.
  19125. Interactively, if this command is repeated or (in Transient Mark
  19126. mode) if the mark is active, it marks the next element after the
  19127. ones already marked."
  19128. (interactive)
  19129. (let (deactivate-mark)
  19130. (if (and (called-interactively-p 'any)
  19131. (or (and (eq last-command this-command) (mark t))
  19132. (and transient-mark-mode mark-active)))
  19133. (set-mark
  19134. (save-excursion
  19135. (goto-char (mark))
  19136. (goto-char (org-element-property :end (org-element-at-point)))
  19137. (point)))
  19138. (let ((element (org-element-at-point)))
  19139. (end-of-line)
  19140. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19141. (goto-char (org-element-property :begin element))))))
  19142. (defun org-narrow-to-element ()
  19143. "Narrow buffer to current element."
  19144. (interactive)
  19145. (let ((elem (org-element-at-point)))
  19146. (cond
  19147. ((eq (car elem) 'headline)
  19148. (narrow-to-region
  19149. (org-element-property :begin elem)
  19150. (org-element-property :end elem)))
  19151. ((memq (car elem) org-element-greater-elements)
  19152. (narrow-to-region
  19153. (org-element-property :contents-begin elem)
  19154. (org-element-property :contents-end elem)))
  19155. (t
  19156. (narrow-to-region
  19157. (org-element-property :begin elem)
  19158. (org-element-property :end elem))))))
  19159. (defun org-transpose-element ()
  19160. "Transpose current and previous elements, keeping blank lines between.
  19161. Point is moved after both elements."
  19162. (interactive)
  19163. (org-skip-whitespace)
  19164. (let ((end (org-element-property :end (org-element-at-point))))
  19165. (org-drag-element-backward)
  19166. (goto-char end)))
  19167. (defun org-unindent-buffer ()
  19168. "Un-indent the visible part of the buffer.
  19169. Relative indentation (between items, inside blocks, etc.) isn't
  19170. modified."
  19171. (interactive)
  19172. (unless (eq major-mode 'org-mode)
  19173. (user-error "Cannot un-indent a buffer not in Org mode"))
  19174. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19175. (unindent-tree
  19176. (lambda (contents)
  19177. (dolist (element (reverse contents))
  19178. (if (memq (org-element-type element) '(headline section))
  19179. (funcall unindent-tree (org-element-contents element))
  19180. (save-excursion
  19181. (save-restriction
  19182. (narrow-to-region
  19183. (org-element-property :begin element)
  19184. (org-element-property :end element))
  19185. (org-do-remove-indentation))))))))
  19186. (funcall unindent-tree (org-element-contents parse-tree))))
  19187. (defun org-make-options-regexp (kwds &optional extra)
  19188. "Make a regular expression for keyword lines.
  19189. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19190. when non-nil, is a regexp matching keywords names."
  19191. (concat "^[ \t]*#\\+\\("
  19192. (regexp-opt kwds)
  19193. (and extra (concat (and kwds "\\|") extra))
  19194. "\\):[ \t]*\\(.*\\)"))
  19195. ;;; Conveniently switch to Info nodes
  19196. (defun org-info-find-node (&optional nodename)
  19197. "Find Info documentation NODENAME or Org documentation according context.
  19198. Started from `gnus-info-find-node'."
  19199. (interactive)
  19200. (Info-goto-node
  19201. (or nodename
  19202. (let ((default-org-info-node "(org) Top"))
  19203. (cond
  19204. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19205. ((eq 'org-mode major-mode)
  19206. (let* ((context (org-element-at-point))
  19207. (element-info-nodes ; compare to `org-element-all-elements'.
  19208. `((babel-call . "(org) Evaluating Code Blocks")
  19209. (center-block . "(org) Paragraphs")
  19210. (clock . ,default-org-info-node)
  19211. (comment . "(org) Comment Lines")
  19212. (comment-block . "(org) Comment Lines")
  19213. (diary-sexp . ,default-org-info-node)
  19214. (drawer . "(org) Drawers")
  19215. (dynamic-block . "(org) Dynamic Blocks")
  19216. (example-block . "(org) Literal Examples")
  19217. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19218. (fixed-width . ,default-org-info-node)
  19219. (footnote-definition . "(org) Creating Footnotes")
  19220. (headline . "(org) Document Structure")
  19221. (horizontal-rule . "(org) Built-in Table Editor")
  19222. (inlinetask . ,default-org-info-node)
  19223. (item . "(org) Plain Lists")
  19224. (keyword . "(org) Per-file keywords")
  19225. (latex-environment . "(org) LaTeX Export")
  19226. (node-property . "(org) Properties and Columns")
  19227. (paragraph . "(org) Paragraphs")
  19228. (plain-list . "(org) Plain Lists")
  19229. (planning . "(org) Deadlines and Scheduling")
  19230. (property-drawer . "(org) Properties and Columns")
  19231. (quote-block . "(org) Paragraphs")
  19232. (section . ,default-org-info-node)
  19233. (special-block . ,default-org-info-node)
  19234. (src-block . "(org) Working with Source Code")
  19235. (table . "(org) Tables")
  19236. (table-row . "(org) Tables")
  19237. (verse-block . "(org) Paragraphs"))))
  19238. (or (cdr (assoc (car context) element-info-nodes))
  19239. default-org-info-node)))
  19240. (t default-org-info-node))))))
  19241. ;;; Finish up
  19242. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19243. (lambda () (add-hook 'change-major-mode-hook
  19244. 'org-fold-show-all 'append 'local)))
  19245. (provide 'org)
  19246. (run-hooks 'org-load-hook)
  19247. ;;; org.el ends here