org.el 811 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417
  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-2021 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 "24.3"))
  10. ;; Version: 9.5-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 'org-table)
  86. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  87. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  88. (defvar org-outline-regexp "\\*+ "
  89. "Regexp to match Org headlines.")
  90. (defvar org-outline-regexp-bol "^\\*+ "
  91. "Regexp to match Org headlines.
  92. This is similar to `org-outline-regexp' but additionally makes
  93. sure that we are at the beginning of the line.")
  94. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  95. "Matches a headline, putting stars and text into groups.
  96. Stars are put in group 1 and the trimmed body in group 2.")
  97. (declare-function calendar-check-holidays "holidays" (date))
  98. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  99. (declare-function cdlatex-math-symbol "ext:cdlatex")
  100. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  101. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  102. (declare-function org-add-archive-files "org-archive" (files))
  103. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  104. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  105. (declare-function org-agenda-redo "org-agenda" (&optional all))
  106. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  107. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  108. (declare-function org-archive-subtree-default "org-archive" ())
  109. (declare-function org-archive-to-archive-sibling "org-archive" ())
  110. (declare-function org-attach "org-attach" ())
  111. (declare-function org-attach-dir "org-attach"
  112. (&optional create-if-not-exists-p no-fs-check))
  113. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  114. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  115. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  116. (declare-function org-clock-auto-clockout "org-clock" ())
  117. (declare-function org-clock-cancel "org-clock" ())
  118. (declare-function org-clock-display "org-clock" (&optional arg))
  119. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  120. (declare-function org-clock-goto "org-clock" (&optional select))
  121. (declare-function org-clock-in "org-clock" (&optional select start-time))
  122. (declare-function org-clock-in-last "org-clock" (&optional arg))
  123. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  124. (declare-function org-clock-out-if-current "org-clock" ())
  125. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  126. (declare-function org-clock-report "org-clock" (&optional arg))
  127. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  128. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  129. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  130. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  131. (declare-function org-clock-update-time-maybe "org-clock" ())
  132. (declare-function org-clocktable-shift "org-clock" (dir n))
  133. (declare-function org-columns-quit "org-colview" ())
  134. (declare-function org-columns-insert-dblock "org-colview" ())
  135. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  136. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  137. (declare-function org-element-at-point "org-element" ())
  138. (declare-function org-element-cache-refresh "org-element" (pos))
  139. (declare-function org-element-cache-reset "org-element" (&optional all))
  140. (declare-function org-element-contents "org-element" (element))
  141. (declare-function org-element-context "org-element" (&optional element))
  142. (declare-function org-element-copy "org-element" (datum))
  143. (declare-function org-element-create "org-element" (type &optional props &rest children))
  144. (declare-function org-element-interpret-data "org-element" (data))
  145. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  146. (declare-function org-element-link-parser "org-element" ())
  147. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  148. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  149. (declare-function org-element-property "org-element" (property element))
  150. (declare-function org-element-put-property "org-element" (element property value))
  151. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  152. (declare-function org-element-timestamp-parser "org-element" ())
  153. (declare-function org-element-type "org-element" (element))
  154. (declare-function org-export-dispatch "ox" (&optional arg))
  155. (declare-function org-export-get-backend "ox" (name))
  156. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  157. (declare-function org-feed-goto-inbox "org-feed" (feed))
  158. (declare-function org-feed-update-all "org-feed" ())
  159. (declare-function org-goto "org-goto" (&optional alternative-interface))
  160. (declare-function org-id-find-id-file "org-id" (id))
  161. (declare-function org-id-get-create "org-id" (&optional force))
  162. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  163. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  164. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  165. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  166. (declare-function org-num-mode "org-num" (&optional arg))
  167. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  168. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  169. (declare-function org-timer "org-timer" (&optional restart no-insert))
  170. (declare-function org-timer-item "org-timer" (&optional arg))
  171. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  172. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  173. (declare-function org-timer-start "org-timer" (&optional offset))
  174. (declare-function org-timer-stop "org-timer" ())
  175. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  176. (declare-function org-update-radio-target-regexp "ol" ())
  177. (defvar ffap-url-regexp)
  178. (defvar org-element-paragraph-separate)
  179. (defvar org-indent-indentation-per-level)
  180. (defvar org-radio-target-regexp)
  181. (defvar org-target-link-regexp)
  182. (defvar org-target-regexp)
  183. (defvar org-id-overriding-file-name)
  184. ;; load languages based on value of `org-babel-load-languages'
  185. (defvar org-babel-load-languages)
  186. ;;;###autoload
  187. (defun org-babel-do-load-languages (sym value)
  188. "Load the languages defined in `org-babel-load-languages'."
  189. (set-default sym value)
  190. (dolist (pair org-babel-load-languages)
  191. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  192. (if active
  193. (require (intern (concat "ob-" lang)))
  194. (fmakunbound
  195. (intern (concat "org-babel-execute:" lang)))
  196. (fmakunbound
  197. (intern (concat "org-babel-expand-body:" lang)))))))
  198. ;;;###autoload
  199. (defun org-babel-load-file (file &optional compile)
  200. "Load Emacs Lisp source code blocks in the Org FILE.
  201. This function exports the source code using `org-babel-tangle'
  202. and then loads the resulting file using `load-file'. With
  203. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  204. byte-compiled before it is loaded."
  205. (interactive "fFile to load: \nP")
  206. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  207. ;; Tangle only if the Org file is newer than the Elisp file.
  208. (unless (org-file-newer-than-p
  209. tangled-file
  210. (file-attribute-modification-time
  211. (file-attributes (file-truename file))))
  212. (org-babel-tangle-file file tangled-file "emacs-lisp\\|elisp"))
  213. (if compile
  214. (progn
  215. (byte-compile-file tangled-file)
  216. (load tangled-file)
  217. (message "Compiled and loaded %s" tangled-file))
  218. (load-file tangled-file)
  219. (message "Loaded %s" tangled-file))))
  220. (defcustom org-babel-load-languages '((emacs-lisp . t))
  221. "Languages which can be evaluated in Org buffers.
  222. \\<org-mode-map>
  223. This list can be used to load support for any of the languages
  224. below. Each language will depend on a different set of system
  225. executables and/or Emacs modes.
  226. When a language is \"loaded\", code blocks in that language can
  227. be evaluated with `org-babel-execute-src-block', which is bound
  228. by default to \\[org-ctrl-c-ctrl-c].
  229. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  230. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  231. default, only Emacs Lisp is loaded, since it has no specific
  232. requirement."
  233. :group 'org-babel
  234. :set 'org-babel-do-load-languages
  235. :version "24.1"
  236. :type '(alist :tag "Babel Languages"
  237. :key-type
  238. (choice
  239. (const :tag "Awk" awk)
  240. (const :tag "C" C)
  241. (const :tag "R" R)
  242. (const :tag "Asymptote" asymptote)
  243. (const :tag "Calc" calc)
  244. (const :tag "Clojure" clojure)
  245. (const :tag "CSS" css)
  246. (const :tag "Ditaa" ditaa)
  247. (const :tag "Dot" dot)
  248. (const :tag "Ebnf2ps" ebnf2ps)
  249. (const :tag "Emacs Lisp" emacs-lisp)
  250. (const :tag "Forth" forth)
  251. (const :tag "Fortran" fortran)
  252. (const :tag "Gnuplot" gnuplot)
  253. (const :tag "Haskell" haskell)
  254. (const :tag "hledger" hledger)
  255. (const :tag "IO" io)
  256. (const :tag "J" J)
  257. (const :tag "Java" java)
  258. (const :tag "Javascript" js)
  259. (const :tag "LaTeX" latex)
  260. (const :tag "Ledger" ledger)
  261. (const :tag "Lilypond" lilypond)
  262. (const :tag "Lisp" lisp)
  263. (const :tag "Makefile" makefile)
  264. (const :tag "Maxima" maxima)
  265. (const :tag "Matlab" matlab)
  266. (const :tag "Mscgen" mscgen)
  267. (const :tag "Ocaml" ocaml)
  268. (const :tag "Octave" octave)
  269. (const :tag "Org" org)
  270. (const :tag "Perl" perl)
  271. (const :tag "Pico Lisp" picolisp)
  272. (const :tag "PlantUML" plantuml)
  273. (const :tag "Python" python)
  274. (const :tag "Ruby" ruby)
  275. (const :tag "Sass" sass)
  276. (const :tag "Scala" scala)
  277. (const :tag "Scheme" scheme)
  278. (const :tag "Screen" screen)
  279. (const :tag "Shell Script" shell)
  280. (const :tag "Shen" shen)
  281. (const :tag "Sql" sql)
  282. (const :tag "Sqlite" sqlite)
  283. (const :tag "Stan" stan)
  284. (const :tag "Vala" vala))
  285. :value-type (boolean :tag "Activate" :value t)))
  286. ;;;; Customization variables
  287. (defcustom org-clone-delete-id nil
  288. "Remove ID property of clones of a subtree.
  289. When non-nil, clones of a subtree don't inherit the ID property.
  290. Otherwise they inherit the ID property with a new unique
  291. identifier."
  292. :type 'boolean
  293. :version "24.1"
  294. :group 'org-id)
  295. ;;; Version
  296. (org-check-version)
  297. ;;;###autoload
  298. (defun org-version (&optional here full message)
  299. "Show the Org version.
  300. Interactively, or when MESSAGE is non-nil, show it in echo area.
  301. With prefix argument, or when HERE is non-nil, insert it at point.
  302. In non-interactive uses, a reduced version string is output unless
  303. FULL is given."
  304. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  305. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  306. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  307. (load-suffixes (list ".el"))
  308. (org-install-dir
  309. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  310. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  311. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  312. (let* ((load-suffixes save-load-suffixes)
  313. (release (org-release))
  314. (git-version (org-git-version))
  315. (version (format "Org mode version %s (%s @ %s)"
  316. release
  317. git-version
  318. (if org-install-dir
  319. (if (string= org-dir org-install-dir)
  320. org-install-dir
  321. (concat "mixed installation! "
  322. org-install-dir
  323. " and "
  324. org-dir))
  325. "org-loaddefs.el can not be found!")))
  326. (version1 (if full version release)))
  327. (when here (insert version1))
  328. (when message (message "%s" version1))
  329. version1)))
  330. (defconst org-version (org-version))
  331. ;;; Syntax Constants
  332. ;;;; Comments
  333. (defconst org-comment-regexp
  334. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  335. "Regular expression for comment lines.")
  336. ;;;; Keyword
  337. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  338. "Regular expression for keyword-lines.")
  339. ;;;; Block
  340. (defconst org-block-regexp
  341. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  342. "Regular expression for hiding blocks.")
  343. (defconst org-dblock-start-re
  344. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  345. "Matches the start line of a dynamic block, with parameters.")
  346. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  347. "Matches the end of a dynamic block.")
  348. ;;;; Timestamp
  349. (defconst org-ts--internal-regexp
  350. (rx (seq
  351. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  352. (optional " " (*? nonl))))
  353. "Regular expression matching the innards of a time stamp.")
  354. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  355. "Regular expression for fast time stamp matching.")
  356. (defconst org-ts-regexp-inactive
  357. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  358. "Regular expression for fast inactive time stamp matching.")
  359. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  360. "Regular expression for fast time stamp matching.")
  361. (defconst org-ts-regexp0
  362. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  363. "Regular expression matching time strings for analysis.
  364. This one does not require the space after the date, so it can be used
  365. on a string that terminates immediately after the date.")
  366. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  367. "Regular expression matching time strings for analysis.")
  368. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  369. "Regular expression matching time stamps, with groups.")
  370. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  371. "Regular expression matching time stamps (also [..]), with groups.")
  372. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  373. "Regular expression matching a time stamp range.")
  374. (defconst org-tr-regexp-both
  375. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  376. "Regular expression matching a time stamp range.")
  377. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  378. org-ts-regexp "\\)?")
  379. "Regular expression matching a time stamp or time stamp range.")
  380. (defconst org-tsr-regexp-both
  381. (concat org-ts-regexp-both "\\(--?-?"
  382. org-ts-regexp-both "\\)?")
  383. "Regular expression matching a time stamp or time stamp range.
  384. The time stamps may be either active or inactive.")
  385. (defconst org-repeat-re
  386. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  387. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  388. "Regular expression for specifying repeated events.
  389. After a match, group 1 contains the repeat expression.")
  390. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  391. "Formats for `format-time-string' which are used for time stamps.")
  392. ;;;; Clock and Planning
  393. (defconst org-clock-string "CLOCK:"
  394. "String used as prefix for timestamps clocking work hours on an item.")
  395. (defvar org-closed-string "CLOSED:"
  396. "String used as the prefix for timestamps logging closing a TODO entry.")
  397. (defvar org-deadline-string "DEADLINE:"
  398. "String to mark deadline entries.
  399. \\<org-mode-map>
  400. A deadline is this string, followed by a time stamp. It must be
  401. a word, terminated by a colon. You can insert a schedule keyword
  402. and a timestamp with `\\[org-deadline]'.")
  403. (defvar org-scheduled-string "SCHEDULED:"
  404. "String to mark scheduled TODO entries.
  405. \\<org-mode-map>
  406. A schedule is this string, followed by a time stamp. It must be
  407. a word, terminated by a colon. You can insert a schedule keyword
  408. and a timestamp with `\\[org-schedule]'.")
  409. (defconst org-ds-keyword-length
  410. (+ 2
  411. (apply #'max
  412. (mapcar #'length
  413. (list org-deadline-string org-scheduled-string
  414. org-clock-string org-closed-string))))
  415. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  416. (defconst org-planning-line-re
  417. (concat "^[ \t]*"
  418. (regexp-opt
  419. (list org-closed-string org-deadline-string org-scheduled-string)
  420. t))
  421. "Matches a line with planning info.
  422. Matched keyword is in group 1.")
  423. (defconst org-clock-line-re
  424. (concat "^[ \t]*" org-clock-string)
  425. "Matches a line with clock info.")
  426. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  427. "Matches the DEADLINE keyword.")
  428. (defconst org-deadline-time-regexp
  429. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  430. "Matches the DEADLINE keyword together with a time stamp.")
  431. (defconst org-deadline-time-hour-regexp
  432. (concat "\\<" org-deadline-string
  433. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  434. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  435. (defconst org-deadline-line-regexp
  436. (concat "\\<\\(" org-deadline-string "\\).*")
  437. "Matches the DEADLINE keyword and the rest of the line.")
  438. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  439. "Matches the SCHEDULED keyword.")
  440. (defconst org-scheduled-time-regexp
  441. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  442. "Matches the SCHEDULED keyword together with a time stamp.")
  443. (defconst org-scheduled-time-hour-regexp
  444. (concat "\\<" org-scheduled-string
  445. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  446. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  447. (defconst org-closed-time-regexp
  448. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  449. "Matches the CLOSED keyword together with a time stamp.")
  450. (defconst org-keyword-time-regexp
  451. (concat "\\<"
  452. (regexp-opt
  453. (list org-scheduled-string org-deadline-string org-closed-string
  454. org-clock-string)
  455. t)
  456. " *[[<]\\([^]>]+\\)[]>]")
  457. "Matches any of the 4 keywords, together with the time stamp.")
  458. (defconst org-keyword-time-not-clock-regexp
  459. (concat
  460. "\\<"
  461. (regexp-opt
  462. (list org-scheduled-string org-deadline-string org-closed-string) t)
  463. " *[[<]\\([^]>]+\\)[]>]")
  464. "Matches any of the 3 keywords, together with the time stamp.")
  465. (defconst org-all-time-keywords
  466. (mapcar (lambda (w) (substring w 0 -1))
  467. (list org-scheduled-string org-deadline-string
  468. org-clock-string org-closed-string))
  469. "List of time keywords.")
  470. ;;;; Drawer
  471. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  472. "Matches first or last line of a hidden block.
  473. Group 1 contains drawer's name or \"END\".")
  474. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  475. "Regular expression matching the first line of a property drawer.")
  476. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  477. "Regular expression matching the last line of a property drawer.")
  478. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  479. "Regular expression matching the first line of a clock drawer.")
  480. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  481. "Regular expression matching the last line of a clock drawer.")
  482. (defconst org-logbook-drawer-re
  483. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  484. (*? (0+ nonl) "\n")
  485. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  486. "Matches an entire LOGBOOK drawer.")
  487. (defconst org-property-drawer-re
  488. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  489. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  490. "[ \t]*:END:[ \t]*$")
  491. "Matches an entire property drawer.")
  492. (defconst org-clock-drawer-re
  493. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  494. org-clock-drawer-end-re "\\)\n?")
  495. "Matches an entire clock drawer.")
  496. ;;;; Headline
  497. (defconst org-heading-keyword-regexp-format
  498. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  499. "Printf format for a regexp matching a headline with some keyword.
  500. This regexp will match the headline of any node which has the
  501. exact keyword that is put into the format. The keyword isn't in
  502. any group by default, but the stars and the body are.")
  503. (defconst org-heading-keyword-maybe-regexp-format
  504. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  505. "Printf format for a regexp matching a headline, possibly with some keyword.
  506. This regexp can match any headline with the specified keyword, or
  507. without a keyword. The keyword isn't in any group by default,
  508. but the stars and the body are.")
  509. (defconst org-archive-tag "ARCHIVE"
  510. "The tag that marks a subtree as archived.
  511. An archived subtree does not open during visibility cycling, and does
  512. not contribute to the agenda listings.")
  513. (defconst org-tag-re "[[:alnum:]_@#%]+"
  514. "Regexp matching a single tag.")
  515. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  516. "Regexp matching the tag group at the end of a line, with leading spaces.
  517. Tags are stored in match group 1. Match group 2 stores the tags
  518. without the enclosing colons.")
  519. (defconst org-tag-line-re
  520. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  521. "Regexp matching tags in a headline.
  522. Tags are stored in match group 1. Match group 2 stores the tags
  523. without the enclosing colons.")
  524. (eval-and-compile
  525. (defconst org-comment-string "COMMENT"
  526. "Entries starting with this keyword will never be exported.
  527. \\<org-mode-map>
  528. An entry can be toggled between COMMENT and normal with
  529. `\\[org-toggle-comment]'."))
  530. ;;;; LaTeX Environments and Fragments
  531. (defconst org-latex-regexps
  532. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  533. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  534. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  535. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  536. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  537. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  538. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  539. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  540. "Regular expressions for matching embedded LaTeX.")
  541. ;;;; Node Property
  542. (defconst org-effort-property "Effort"
  543. "The property that is being used to keep track of effort estimates.
  544. Effort estimates given in this property need to be in the format
  545. defined in org-duration.el.")
  546. ;;; The custom variables
  547. (defgroup org nil
  548. "Outline-based notes management and organizer."
  549. :tag "Org"
  550. :group 'outlines
  551. :group 'calendar)
  552. (defcustom org-mode-hook nil
  553. "Mode hook for Org mode, run after the mode was turned on."
  554. :group 'org
  555. :type 'hook)
  556. (defcustom org-load-hook nil
  557. "Hook that is run after org.el has been loaded."
  558. :group 'org
  559. :type 'hook)
  560. (make-obsolete-variable
  561. 'org-load-hook
  562. "use `with-eval-after-load' instead." "Org 9.5")
  563. (defcustom org-log-buffer-setup-hook nil
  564. "Hook that is run after an Org log buffer is created."
  565. :group 'org
  566. :version "24.1"
  567. :type 'hook)
  568. (defvar org-modules) ; defined below
  569. (defvar org-modules-loaded nil
  570. "Have the modules been loaded already?")
  571. ;;;###autoload
  572. (defun org-load-modules-maybe (&optional force)
  573. "Load all extensions listed in `org-modules'."
  574. (when (or force (not org-modules-loaded))
  575. (dolist (ext org-modules)
  576. (condition-case nil (require ext)
  577. (error (message "Problems while trying to load feature `%s'" ext))))
  578. (setq org-modules-loaded t)))
  579. (defun org-set-modules (var value)
  580. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  581. (set var value)
  582. (when (featurep 'org)
  583. (org-load-modules-maybe 'force)
  584. (org-element-cache-reset 'all)))
  585. (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)
  586. "Modules that should always be loaded together with org.el.
  587. If a description starts with <C>, the file is not part of Emacs
  588. and loading it will require that you have downloaded and properly
  589. installed the Org mode distribution.
  590. You can also use this system to load external packages (i.e. neither Org
  591. core modules, nor modules from the CONTRIB directory). Just add symbols
  592. to the end of the list. If the package is called org-xyz.el, then you need
  593. to add the symbol `xyz', and the package must have a call to:
  594. (provide \\='org-xyz)
  595. For export specific modules, see also `org-export-backends'."
  596. :group 'org
  597. :set 'org-set-modules
  598. :package-version '(Org . "9.5")
  599. :type
  600. '(set :greedy t
  601. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  602. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  603. (const :tag " crypt: Encryption of subtrees" org-crypt)
  604. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  605. (const :tag " docview: Links to Docview buffers" ol-docview)
  606. (const :tag " doi: Links to DOI references" ol-doi)
  607. (const :tag " eww: Store link to URL of Eww" ol-eww)
  608. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  609. (const :tag " habit: Track your consistency with habits" org-habit)
  610. (const :tag " id: Global IDs for identifying entries" org-id)
  611. (const :tag " info: Links to Info nodes" ol-info)
  612. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  613. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  614. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  615. (const :tag " mouse: Additional mouse support" org-mouse)
  616. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  617. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  618. (const :tag " tempo: Fast completion for structures" org-tempo)
  619. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  620. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  621. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  622. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  623. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  624. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  625. (const :tag "C collector: Collect properties into tables" org-collector)
  626. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  627. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  628. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  629. (const :tag "C eval: Include command output as text" org-eval)
  630. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  631. (const :tag "C git-link: Links to specific file version" ol-git-link)
  632. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  633. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  634. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  635. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  636. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  637. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  638. (const :tag "C man: Links to man pages in Org mode" ol-man)
  639. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  640. (const :tag "C notify: Notifications for Org mode" org-notify)
  641. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  642. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  643. (const :tag "C registry: A registry for Org links" org-registry)
  644. (const :tag "C screen: Visit screen sessions through links" org-screen)
  645. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  646. (const :tag "C secretary: Team management with Org" org-secretary)
  647. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  648. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  649. (const :tag "C track: Keep up with Org mode development" org-track)
  650. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  651. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  652. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  653. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  654. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  655. (defvar org-export-registered-backends) ; From ox.el.
  656. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  657. (declare-function org-export-backend-name "ox" (backend) t)
  658. (defcustom org-export-backends '(ascii html icalendar latex odt)
  659. "List of export back-ends that should be always available.
  660. If a description starts with <C>, the file is not part of Emacs
  661. and loading it will require that you have downloaded and properly
  662. installed the Org mode distribution.
  663. Unlike to `org-modules', libraries in this list will not be
  664. loaded along with Org, but only once the export framework is
  665. needed.
  666. This variable needs to be set before org.el is loaded. If you
  667. need to make a change while Emacs is running, use the customize
  668. interface or run the following code, where VAL stands for the new
  669. value of the variable, after updating it:
  670. (progn
  671. (setq org-export-registered-backends
  672. (cl-remove-if-not
  673. (lambda (backend)
  674. (let ((name (org-export-backend-name backend)))
  675. (or (memq name val)
  676. (catch \\='parentp
  677. (dolist (b val)
  678. (and (org-export-derived-backend-p b name)
  679. (throw \\='parentp t)))))))
  680. org-export-registered-backends))
  681. (let ((new-list (mapcar #\\='org-export-backend-name
  682. org-export-registered-backends)))
  683. (dolist (backend val)
  684. (cond
  685. ((not (load (format \"ox-%s\" backend) t t))
  686. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  687. backend))
  688. ((not (memq backend new-list)) (push backend new-list))))
  689. (set-default \\='org-export-backends new-list)))
  690. Adding a back-end to this list will also pull the back-end it
  691. depends on, if any."
  692. :group 'org
  693. :group 'org-export
  694. :version "26.1"
  695. :package-version '(Org . "9.0")
  696. :initialize 'custom-initialize-set
  697. :set (lambda (var val)
  698. (if (not (featurep 'ox)) (set-default var val)
  699. ;; Any back-end not required anymore (not present in VAL and not
  700. ;; a parent of any back-end in the new value) is removed from the
  701. ;; list of registered back-ends.
  702. (setq org-export-registered-backends
  703. (cl-remove-if-not
  704. (lambda (backend)
  705. (let ((name (org-export-backend-name backend)))
  706. (or (memq name val)
  707. (catch 'parentp
  708. (dolist (b val)
  709. (and (org-export-derived-backend-p b name)
  710. (throw 'parentp t)))))))
  711. org-export-registered-backends))
  712. ;; Now build NEW-LIST of both new back-ends and required
  713. ;; parents.
  714. (let ((new-list (mapcar #'org-export-backend-name
  715. org-export-registered-backends)))
  716. (dolist (backend val)
  717. (cond
  718. ((not (load (format "ox-%s" backend) t t))
  719. (message "Problems while trying to load export back-end `%s'"
  720. backend))
  721. ((not (memq backend new-list)) (push backend new-list))))
  722. ;; Set VAR to that list with fixed dependencies.
  723. (set-default var new-list))))
  724. :type '(set :greedy t
  725. (const :tag " ascii Export buffer to ASCII format" ascii)
  726. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  727. (const :tag " html Export buffer to HTML format" html)
  728. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  729. (const :tag " latex Export buffer to LaTeX format" latex)
  730. (const :tag " man Export buffer to MAN format" man)
  731. (const :tag " md Export buffer to Markdown format" md)
  732. (const :tag " odt Export buffer to ODT format" odt)
  733. (const :tag " org Export buffer to Org format" org)
  734. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  735. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  736. (const :tag "C deck Export buffer to deck.js presentations" deck)
  737. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  738. (const :tag "C groff Export buffer to Groff format" groff)
  739. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  740. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  741. (const :tag "C s5 Export buffer to s5 presentations" s5)
  742. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  743. (eval-after-load 'ox
  744. '(dolist (backend org-export-backends)
  745. (condition-case nil (require (intern (format "ox-%s" backend)))
  746. (error (message "Problems while trying to load export back-end `%s'"
  747. backend)))))
  748. (defcustom org-support-shift-select nil
  749. "Non-nil means make shift-cursor commands select text when possible.
  750. \\<org-mode-map>
  751. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  752. start selecting a region, or enlarge regions started in this way.
  753. In Org mode, in special contexts, these same keys are used for
  754. other purposes, important enough to compete with shift selection.
  755. Org tries to balance these needs by supporting `shift-select-mode'
  756. outside these special contexts, under control of this variable.
  757. The default of this variable is nil, to avoid confusing behavior. Shifted
  758. cursor keys will then execute Org commands in the following contexts:
  759. - on a headline, changing TODO state (left/right) and priority (up/down)
  760. - on a time stamp, changing the time
  761. - in a plain list item, changing the bullet type
  762. - in a property definition line, switching between allowed values
  763. - in the BEGIN line of a clock table (changing the time block).
  764. - in a table, moving the cell in the specified direction.
  765. Outside these contexts, the commands will throw an error.
  766. When this variable is t and the cursor is not in a special
  767. context, Org mode will support shift-selection for making and
  768. enlarging regions. To make this more effective, the bullet
  769. cycling will no longer happen anywhere in an item line, but only
  770. if the cursor is exactly on the bullet.
  771. If you set this variable to the symbol `always', then the keys
  772. will not be special in headlines, property lines, item lines, and
  773. table cells, to make shift selection work there as well. If this is
  774. what you want, you can use the following alternative commands:
  775. `\\[org-todo]' and `\\[org-priority]' \
  776. to change TODO state and priority,
  777. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  778. can be used to switch TODO sets,
  779. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  780. and properties can be edited by hand or in column view.
  781. However, when the cursor is on a timestamp, shift-cursor commands
  782. will still edit the time stamp - this is just too good to give up."
  783. :group 'org
  784. :type '(choice
  785. (const :tag "Never" nil)
  786. (const :tag "When outside special context" t)
  787. (const :tag "Everywhere except timestamps" always)))
  788. (defcustom org-loop-over-headlines-in-active-region t
  789. "Shall some commands act upon headlines in the active region?
  790. When set to t, some commands will be performed in all headlines
  791. within the active region.
  792. When set to `start-level', some commands will be performed in all
  793. headlines within the active region, provided that these headlines
  794. are of the same level than the first one.
  795. When set to a string, those commands will be performed on the
  796. matching headlines within the active region. Such string must be
  797. a tags/property/todo match as it is used in the agenda tags view.
  798. The list of commands is: `org-schedule', `org-deadline',
  799. `org-todo', `org-set-tags-command', `org-archive-subtree',
  800. `org-archive-set-tag', `org-toggle-archive-tag' and
  801. `org-archive-to-archive-sibling'. The archiving commands skip
  802. already archived entries.
  803. See `org-agenda-loop-over-headlines-in-active-region' for the
  804. equivalent option for agenda views."
  805. :type '(choice (const :tag "Don't loop" nil)
  806. (const :tag "All headlines in active region" t)
  807. (const :tag "In active region, headlines at the same level than the first one" start-level)
  808. (string :tag "Tags/Property/Todo matcher"))
  809. :package-version '(Org . "9.4")
  810. :group 'org-todo
  811. :group 'org-archive)
  812. (defcustom org-startup-folded 'showeverything
  813. "Non-nil means entering Org mode will switch to OVERVIEW.
  814. This can also be configured on a per-file basis by adding one of
  815. the following lines anywhere in the buffer:
  816. #+STARTUP: fold (or `overview', this is equivalent)
  817. #+STARTUP: nofold (or `showall', this is equivalent)
  818. #+STARTUP: content
  819. #+STARTUP: show<n>levels (<n> = 2..5)
  820. #+STARTUP: showeverything
  821. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  822. to ignore this option when Org opens agenda files for the first
  823. time."
  824. :group 'org-startup
  825. :package-version '(Org . "9.4")
  826. :type '(choice
  827. (const :tag "nofold: show all" nil)
  828. (const :tag "fold: overview" t)
  829. (const :tag "fold: show two levels" show2levels)
  830. (const :tag "fold: show three levels" show3levels)
  831. (const :tag "fold: show four levels" show4evels)
  832. (const :tag "fold: show five levels" show5levels)
  833. (const :tag "content: all headlines" content)
  834. (const :tag "show everything, even drawers" showeverything)))
  835. (defcustom org-startup-truncated t
  836. "Non-nil means entering Org mode will set `truncate-lines'.
  837. This is useful since some lines containing links can be very long and
  838. uninteresting. Also tables look terrible when wrapped.
  839. The variable `org-startup-truncated' allows to configure
  840. truncation for Org mode different to the other modes that use the
  841. variable `truncate-lines' and as a shortcut instead of putting
  842. the variable `truncate-lines' into the `org-mode-hook'. If one
  843. wants to configure truncation for Org mode not statically but
  844. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  845. the variable `truncate-lines' has to be used because in such a
  846. case it is too late to set the variable `org-startup-truncated'."
  847. :group 'org-startup
  848. :type 'boolean)
  849. (defcustom org-startup-indented nil
  850. "Non-nil means turn on `org-indent-mode' on startup.
  851. This can also be configured on a per-file basis by adding one of
  852. the following lines anywhere in the buffer:
  853. #+STARTUP: indent
  854. #+STARTUP: noindent"
  855. :group 'org-structure
  856. :type '(choice
  857. (const :tag "Not" nil)
  858. (const :tag "Globally (slow on startup in large files)" t)))
  859. (defcustom org-startup-numerated nil
  860. "Non-nil means turn on `org-num-mode' on startup.
  861. This can also be configured on a per-file basis by adding one of
  862. the following lines anywhere in the buffer:
  863. #+STARTUP: num
  864. #+STARTUP: nonum"
  865. :group 'org-structure
  866. :package-version '(Org . "9.4")
  867. :type '(choice
  868. (const :tag "Not" nil)
  869. (const :tag "Globally" t)))
  870. (defcustom org-use-sub-superscripts t
  871. "Non-nil means interpret \"_\" and \"^\" for display.
  872. If you want to control how Org exports those characters, see
  873. `org-export-with-sub-superscripts'.
  874. When this option is turned on, you can use TeX-like syntax for
  875. sub- and superscripts within the buffer. Several characters after
  876. \"_\" or \"^\" will be considered as a single item - so grouping
  877. with {} is normally not needed. For example, the following things
  878. will be parsed as single sub- or superscripts:
  879. 10^24 or 10^tau several digits will be considered 1 item.
  880. 10^-12 or 10^-tau a leading sign with digits or a word
  881. x^2-y^3 will be read as x^2 - y^3, because items are
  882. terminated by almost any nonword/nondigit char.
  883. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  884. Still, ambiguity is possible. So when in doubt, use {} to enclose
  885. the sub/superscript. If you set this variable to the symbol `{}',
  886. the braces are *required* in order to trigger interpretations as
  887. sub/superscript. This can be helpful in documents that need \"_\"
  888. frequently in plain text."
  889. :group 'org-startup
  890. :version "24.4"
  891. :package-version '(Org . "8.0")
  892. :type '(choice
  893. (const :tag "Always interpret" t)
  894. (const :tag "Only with braces" {})
  895. (const :tag "Never interpret" nil)))
  896. (defcustom org-startup-with-beamer-mode nil
  897. "Non-nil means turn on `org-beamer-mode' on startup.
  898. This can also be configured on a per-file basis by adding one of
  899. the following lines anywhere in the buffer:
  900. #+STARTUP: beamer"
  901. :group 'org-startup
  902. :version "24.1"
  903. :type 'boolean)
  904. (defcustom org-startup-align-all-tables nil
  905. "Non-nil means align all tables when visiting a file.
  906. This can also be configured on a per-file basis by adding one of
  907. the following lines anywhere in the buffer:
  908. #+STARTUP: align
  909. #+STARTUP: noalign"
  910. :group 'org-startup
  911. :type 'boolean)
  912. (defcustom org-startup-shrink-all-tables nil
  913. "Non-nil means shrink all table columns with a width cookie.
  914. This can also be configured on a per-file basis by adding one of
  915. the following lines anywhere in the buffer:
  916. #+STARTUP: shrink"
  917. :group 'org-startup
  918. :type 'boolean
  919. :version "27.1"
  920. :package-version '(Org . "9.2")
  921. :safe #'booleanp)
  922. (defcustom org-startup-with-inline-images nil
  923. "Non-nil means show inline images when loading a new Org file.
  924. This can also be configured on a per-file basis by adding one of
  925. the following lines anywhere in the buffer:
  926. #+STARTUP: inlineimages
  927. #+STARTUP: noinlineimages"
  928. :group 'org-startup
  929. :version "24.1"
  930. :type 'boolean)
  931. (defcustom org-startup-with-latex-preview nil
  932. "Non-nil means preview LaTeX fragments when loading a new Org file.
  933. This can also be configured on a per-file basis by adding one of
  934. the following lines anywhere in the buffer:
  935. #+STARTUP: latexpreview
  936. #+STARTUP: nolatexpreview"
  937. :group 'org-startup
  938. :version "24.4"
  939. :package-version '(Org . "8.0")
  940. :type 'boolean)
  941. (defcustom org-insert-mode-line-in-empty-file nil
  942. "Non-nil means insert the first line setting Org mode in empty files.
  943. When the function `org-mode' is called interactively in an empty file, this
  944. normally means that the file name does not automatically trigger Org mode.
  945. To ensure that the file will always be in Org mode in the future, a
  946. line enforcing Org mode will be inserted into the buffer, if this option
  947. has been set."
  948. :group 'org-startup
  949. :type 'boolean)
  950. (defcustom org-ellipsis nil
  951. "The ellipsis to use in the Org mode outline.
  952. When nil, just use the standard three dots. When a non-empty string,
  953. use that string instead.
  954. The change affects only Org mode (which will then use its own display table).
  955. Changing this requires executing `\\[org-mode]' in a buffer to become
  956. effective. It cannot be set as a local variable."
  957. :group 'org-startup
  958. :type '(choice (const :tag "Default" nil)
  959. (string :tag "String" :value "...#")))
  960. (defvar org-display-table nil
  961. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  962. (defcustom org-directory "~/org"
  963. "Directory with Org files.
  964. This is just a default location to look for Org files. There is no need
  965. at all to put your files into this directory. It is used in the
  966. following situations:
  967. 1. When a capture template specifies a target file that is not an
  968. absolute path. The path will then be interpreted relative to
  969. `org-directory'
  970. 2. When the value of variable `org-agenda-files' is a single file, any
  971. relative paths in this file will be taken as relative to
  972. `org-directory'."
  973. :group 'org-refile
  974. :group 'org-capture
  975. :type 'directory)
  976. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  977. "Default target for storing notes.
  978. Used as a fall back file for org-capture.el, for templates that
  979. do not specify a target file."
  980. :group 'org-refile
  981. :group 'org-capture
  982. :type 'file)
  983. (defcustom org-reverse-note-order nil
  984. "Non-nil means store new notes at the beginning of a file or entry.
  985. When nil, new notes will be filed to the end of a file or entry.
  986. This can also be a list with cons cells of regular expressions that
  987. are matched against file names, and values."
  988. :group 'org-capture
  989. :group 'org-refile
  990. :type '(choice
  991. (const :tag "Reverse always" t)
  992. (const :tag "Reverse never" nil)
  993. (repeat :tag "By file name regexp"
  994. (cons regexp boolean))))
  995. (defgroup org-keywords nil
  996. "Keywords in Org mode."
  997. :tag "Org Keywords"
  998. :group 'org)
  999. (defcustom org-closed-keep-when-no-todo nil
  1000. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1001. :group 'org-todo
  1002. :group 'org-keywords
  1003. :version "24.4"
  1004. :package-version '(Org . "8.0")
  1005. :type 'boolean)
  1006. (defgroup org-structure nil
  1007. "Options concerning the general structure of Org files."
  1008. :tag "Org Structure"
  1009. :group 'org)
  1010. (defgroup org-reveal-location nil
  1011. "Options about how to make context of a location visible."
  1012. :tag "Org Reveal Location"
  1013. :group 'org-structure)
  1014. (defcustom org-show-context-detail '((agenda . local)
  1015. (bookmark-jump . lineage)
  1016. (isearch . lineage)
  1017. (default . ancestors))
  1018. "Alist between context and visibility span when revealing a location.
  1019. \\<org-mode-map>Some actions may move point into invisible
  1020. locations. As a consequence, Org always exposes a neighborhood
  1021. around point. How much is shown depends on the initial action,
  1022. or context. Valid contexts are
  1023. agenda when exposing an entry from the agenda
  1024. org-goto when using the command `org-goto' (`\\[org-goto]')
  1025. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1026. tags-tree when constructing a sparse tree based on tags matches
  1027. link-search when exposing search matches associated with a link
  1028. mark-goto when exposing the jump goal of a mark
  1029. bookmark-jump when exposing a bookmark location
  1030. isearch when exiting from an incremental search
  1031. default default for all contexts not set explicitly
  1032. Allowed visibility spans are
  1033. minimal show current headline; if point is not on headline,
  1034. also show entry
  1035. local show current headline, entry and next headline
  1036. ancestors show current headline and its direct ancestors; if
  1037. point is not on headline, also show entry
  1038. ancestors-full show current subtree and its direct ancestors
  1039. lineage show current headline, its direct ancestors and all
  1040. their children; if point is not on headline, also show
  1041. entry and first child
  1042. tree show current headline, its direct ancestors and all
  1043. their children; if point is not on headline, also show
  1044. entry and all children
  1045. canonical show current headline, its direct ancestors along with
  1046. their entries and children; if point is not located on
  1047. the headline, also show current entry and all children
  1048. As special cases, a nil or t value means show all contexts in
  1049. `minimal' or `canonical' view, respectively.
  1050. Some views can make displayed information very compact, but also
  1051. make it harder to edit the location of the match. In such
  1052. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1053. more context."
  1054. :group 'org-reveal-location
  1055. :version "26.1"
  1056. :package-version '(Org . "9.0")
  1057. :type '(choice
  1058. (const :tag "Canonical" t)
  1059. (const :tag "Minimal" nil)
  1060. (repeat :greedy t :tag "Individual contexts"
  1061. (cons
  1062. (choice :tag "Context"
  1063. (const agenda)
  1064. (const org-goto)
  1065. (const occur-tree)
  1066. (const tags-tree)
  1067. (const link-search)
  1068. (const mark-goto)
  1069. (const bookmark-jump)
  1070. (const isearch)
  1071. (const default))
  1072. (choice :tag "Detail level"
  1073. (const minimal)
  1074. (const local)
  1075. (const ancestors)
  1076. (const ancestors-full)
  1077. (const lineage)
  1078. (const tree)
  1079. (const canonical))))))
  1080. (defcustom org-indirect-buffer-display 'other-window
  1081. "How should indirect tree buffers be displayed?
  1082. This applies to indirect buffers created with the commands
  1083. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1084. Valid values are:
  1085. current-window Display in the current window
  1086. other-window Just display in another window.
  1087. dedicated-frame Create one new frame, and re-use it each time.
  1088. new-frame Make a new frame each time. Note that in this case
  1089. previously-made indirect buffers are kept, and you need to
  1090. kill these buffers yourself."
  1091. :group 'org-structure
  1092. :group 'org-agenda-windows
  1093. :type '(choice
  1094. (const :tag "In current window" current-window)
  1095. (const :tag "In current frame, other window" other-window)
  1096. (const :tag "Each time a new frame" new-frame)
  1097. (const :tag "One dedicated frame" dedicated-frame)))
  1098. (defconst org-file-apps-gnu
  1099. '((remote . emacs)
  1100. (system . mailcap)
  1101. (t . mailcap))
  1102. "Default file applications on a UNIX or GNU/Linux system.
  1103. See `org-file-apps'.")
  1104. (defconst org-file-apps-macos
  1105. '((remote . emacs)
  1106. (system . "open %s")
  1107. ("ps.gz" . "gv %s")
  1108. ("eps.gz" . "gv %s")
  1109. ("dvi" . "xdvi %s")
  1110. ("fig" . "xfig %s")
  1111. (t . "open %s"))
  1112. "Default file applications on a macOS system.
  1113. The system \"open\" is known as a default, but we use X11 applications
  1114. for some files for which the OS does not have a good default.
  1115. See `org-file-apps'.")
  1116. (defconst org-file-apps-windowsnt
  1117. (list '(remote . emacs)
  1118. (cons 'system (lambda (file _path)
  1119. (with-no-warnings (w32-shell-execute "open" file))))
  1120. (cons t (lambda (file _path)
  1121. (with-no-warnings (w32-shell-execute "open" file)))))
  1122. "Default file applications on a Windows NT system.
  1123. The system \"open\" is used for most files.
  1124. See `org-file-apps'.")
  1125. (defcustom org-file-apps
  1126. '((auto-mode . emacs)
  1127. (directory . emacs)
  1128. ("\\.mm\\'" . default)
  1129. ("\\.x?html?\\'" . default)
  1130. ("\\.pdf\\'" . default))
  1131. "Applications for opening `file:path' items in a document.
  1132. \\<org-mode-map>
  1133. Org mode uses system defaults for different file types, but you
  1134. can use this variable to set the application for a given file
  1135. extension. The entries in this list are cons cells where the car
  1136. identifies files and the cdr the corresponding command.
  1137. Possible values for the file identifier are:
  1138. \"string\" A string as a file identifier can be interpreted in different
  1139. ways, depending on its contents:
  1140. - Alphanumeric characters only:
  1141. Match links with this file extension.
  1142. Example: (\"pdf\" . \"evince %s\")
  1143. to open PDFs with evince.
  1144. - Regular expression: Match links where the
  1145. filename matches the regexp. If you want to
  1146. use groups here, use shy groups.
  1147. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1148. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1149. to open *.html and *.xhtml with firefox.
  1150. - Regular expression which contains (non-shy) groups:
  1151. Match links where the whole link, including \"::\", and
  1152. anything after that, matches the regexp.
  1153. In a custom command string, %1, %2, etc. are replaced with
  1154. the parts of the link that were matched by the groups.
  1155. For backwards compatibility, if a command string is given
  1156. that does not use any of the group matches, this case is
  1157. handled identically to the second one (i.e. match against
  1158. file name only).
  1159. In a custom function, you can access the group matches with
  1160. (match-string n link).
  1161. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1162. \"evince -p %1 %s\")
  1163. to open [[file:document.pdf::5]] with evince at page 5.
  1164. `directory' Matches a directory
  1165. `remote' Matches a remote file, accessible through tramp or efs.
  1166. Remote files most likely should be visited through Emacs
  1167. because external applications cannot handle such paths.
  1168. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1169. so all files Emacs knows how to handle. Using this with
  1170. command `emacs' will open most files in Emacs. Beware that this
  1171. will also open html files inside Emacs, unless you add
  1172. (\"html\" . default) to the list as well.
  1173. `system' The system command to open files, like `open' on Windows
  1174. and macOS, and mailcap under GNU/Linux. This is the command
  1175. that will be selected if you call `org-open-at-point' with a
  1176. double prefix argument (`\\[universal-argument] \
  1177. \\[universal-argument] \\[org-open-at-point]').
  1178. t Default for files not matched by any of the other options.
  1179. Possible values for the command are:
  1180. `emacs' The file will be visited by the current Emacs process.
  1181. `default' Use the default application for this file type, which is the
  1182. association for t in the list, most likely in the system-specific
  1183. part. This can be used to overrule an unwanted setting in the
  1184. system-specific variable.
  1185. `system' Use the system command for opening files, like \"open\".
  1186. This command is specified by the entry whose car is `system'.
  1187. Most likely, the system-specific version of this variable
  1188. does define this command, but you can overrule/replace it
  1189. here.
  1190. `mailcap' Use command specified in the mailcaps.
  1191. string A command to be executed by a shell; %s will be replaced
  1192. by the path to the file.
  1193. function A Lisp function, which will be called with two arguments:
  1194. the file path and the original link string, without the
  1195. \"file:\" prefix.
  1196. For more examples, see the system specific constants
  1197. `org-file-apps-macos'
  1198. `org-file-apps-windowsnt'
  1199. `org-file-apps-gnu'."
  1200. :group 'org
  1201. :package-version '(Org . "9.4")
  1202. :type '(repeat
  1203. (cons (choice :value ""
  1204. (string :tag "Extension")
  1205. (const :tag "System command to open files" system)
  1206. (const :tag "Default for unrecognized files" t)
  1207. (const :tag "Remote file" remote)
  1208. (const :tag "Links to a directory" directory)
  1209. (const :tag "Any files that have Emacs modes"
  1210. auto-mode))
  1211. (choice :value ""
  1212. (const :tag "Visit with Emacs" emacs)
  1213. (const :tag "Use default" default)
  1214. (const :tag "Use the system command" system)
  1215. (string :tag "Command")
  1216. (function :tag "Function")))))
  1217. (defcustom org-open-non-existing-files nil
  1218. "Non-nil means `org-open-file' opens non-existing files.
  1219. When nil, an error is thrown.
  1220. This variable applies only to external applications because they
  1221. might choke on non-existing files. If the link is to a file that
  1222. will be opened in Emacs, the variable is ignored."
  1223. :group 'org
  1224. :type 'boolean
  1225. :safe #'booleanp)
  1226. (defcustom org-open-directory-means-index-dot-org nil
  1227. "When non-nil a link to a directory really means to \"index.org\".
  1228. When nil, following a directory link runs Dired or opens
  1229. a finder/explorer window on that directory."
  1230. :group 'org
  1231. :type 'boolean
  1232. :safe #'booleanp)
  1233. (defcustom org-bookmark-names-plist
  1234. '(:last-capture "org-capture-last-stored"
  1235. :last-refile "org-refile-last-stored"
  1236. :last-capture-marker "org-capture-last-stored-marker")
  1237. "Names for bookmarks automatically set by some Org commands.
  1238. This can provide strings as names for a number of bookmarks Org sets
  1239. automatically. The following keys are currently implemented:
  1240. :last-capture
  1241. :last-capture-marker
  1242. :last-refile
  1243. When a key does not show up in the property list, the corresponding bookmark
  1244. is not set."
  1245. :group 'org-structure
  1246. :type 'plist)
  1247. (defgroup org-cycle nil
  1248. "Options concerning visibility cycling in Org mode."
  1249. :tag "Org Cycle"
  1250. :group 'org-structure)
  1251. (defcustom org-cycle-skip-children-state-if-no-children t
  1252. "Non-nil means skip CHILDREN state in entries that don't have any."
  1253. :group 'org-cycle
  1254. :type 'boolean)
  1255. (defcustom org-cycle-max-level nil
  1256. "Maximum level which should still be subject to visibility cycling.
  1257. Levels higher than this will, for cycling, be treated as text, not a headline.
  1258. When `org-odd-levels-only' is set, a value of N in this variable actually
  1259. means 2N-1 stars as the limiting headline.
  1260. When nil, cycle all levels.
  1261. Note that the limiting level of cycling is also influenced by
  1262. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1263. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1264. than its value."
  1265. :group 'org-cycle
  1266. :type '(choice
  1267. (const :tag "No limit" nil)
  1268. (integer :tag "Maximum level")))
  1269. (defcustom org-hide-block-startup nil
  1270. "Non-nil means entering Org mode will fold all blocks.
  1271. This can also be set in on a per-file basis with
  1272. #+STARTUP: hideblocks
  1273. #+STARTUP: showblocks"
  1274. :group 'org-startup
  1275. :group 'org-cycle
  1276. :type 'boolean)
  1277. (defcustom org-cycle-global-at-bob nil
  1278. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1279. This makes it possible to do global cycling without having to use `S-TAB'
  1280. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1281. line of the buffer
  1282. must not be a headline -- it may be empty or some other text.
  1283. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1284. sure the cursor stays at the beginning of the buffer.
  1285. When this option is nil, don't do anything special at the beginning of
  1286. the buffer."
  1287. :group 'org-cycle
  1288. :type 'boolean)
  1289. (defcustom org-cycle-level-after-item/entry-creation t
  1290. "Non-nil means cycle entry level or item indentation in new empty entries.
  1291. When the cursor is at the end of an empty headline, i.e., with only stars
  1292. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1293. and then all possible ancestor states, before returning to the original state.
  1294. This makes data entry extremely fast: M-RET to create a new headline,
  1295. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1296. When the cursor is at the end of an empty plain list item, one TAB will
  1297. make it a subitem, two or more tabs will back up to make this an item
  1298. higher up in the item hierarchy."
  1299. :group 'org-cycle
  1300. :type 'boolean)
  1301. (defcustom org-cycle-emulate-tab t
  1302. "Where should `org-cycle' emulate TAB.
  1303. nil Never
  1304. white Only in completely white lines
  1305. whitestart Only at the beginning of lines, before the first non-white char
  1306. t Everywhere except in headlines
  1307. exc-hl-bol Everywhere except at the start of a headline
  1308. If TAB is used in a place where it does not emulate TAB, the current subtree
  1309. visibility is cycled."
  1310. :group 'org-cycle
  1311. :type '(choice (const :tag "Never" nil)
  1312. (const :tag "Only in completely white lines" white)
  1313. (const :tag "Before first char in a line" whitestart)
  1314. (const :tag "Everywhere except in headlines" t)
  1315. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1316. (defcustom org-cycle-separator-lines 2
  1317. "Number of empty lines needed to keep an empty line between collapsed trees.
  1318. If you leave an empty line between the end of a subtree and the following
  1319. headline, this empty line is hidden when the subtree is folded.
  1320. Org mode will leave (exactly) one empty line visible if the number of
  1321. empty lines is equal or larger to the number given in this variable.
  1322. So the default 2 means at least 2 empty lines after the end of a subtree
  1323. are needed to produce free space between a collapsed subtree and the
  1324. following headline.
  1325. If the number is negative, and the number of empty lines is at least -N,
  1326. all empty lines are shown.
  1327. Special case: when 0, never leave empty lines in collapsed view."
  1328. :group 'org-cycle
  1329. :type 'integer)
  1330. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1331. (defcustom org-pre-cycle-hook nil
  1332. "Hook that is run before visibility cycling is happening.
  1333. The function(s) in this hook must accept a single argument which indicates
  1334. the new state that will be set right after running this hook. The
  1335. argument is a symbol. Before a global state change, it can have the values
  1336. `overview', `content', or `all'. Before a local state change, it can have
  1337. the values `folded', `children', or `subtree'."
  1338. :group 'org-cycle
  1339. :type 'hook)
  1340. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1341. org-cycle-hide-drawers
  1342. org-cycle-show-empty-lines
  1343. org-optimize-window-after-visibility-change)
  1344. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1345. The function(s) in this hook must accept a single argument which indicates
  1346. the new state that was set by the most recent `org-cycle' command. The
  1347. argument is a symbol. After a global state change, it can have the values
  1348. `overview', `contents', or `all'. After a local state change, it can have
  1349. the values `folded', `children', or `subtree'."
  1350. :group 'org-cycle
  1351. :package-version '(Org . "9.4")
  1352. :type 'hook)
  1353. (defgroup org-edit-structure nil
  1354. "Options concerning structure editing in Org mode."
  1355. :tag "Org Edit Structure"
  1356. :group 'org-structure)
  1357. (defcustom org-odd-levels-only nil
  1358. "Non-nil means skip even levels and only use odd levels for the outline.
  1359. This has the effect that two stars are being added/taken away in
  1360. promotion/demotion commands. It also influences how levels are
  1361. handled by the exporters.
  1362. Changing it requires restart of `font-lock-mode' to become effective
  1363. for fontification also in regions already fontified.
  1364. You may also set this on a per-file basis by adding one of the following
  1365. lines to the buffer:
  1366. #+STARTUP: odd
  1367. #+STARTUP: oddeven"
  1368. :group 'org-edit-structure
  1369. :group 'org-appearance
  1370. :type 'boolean)
  1371. (defcustom org-adapt-indentation nil
  1372. "Non-nil means adapt indentation to outline node level.
  1373. When set to t, Org assumes that you write outlines by indenting
  1374. text in each node to align with the headline, after the stars.
  1375. When this variable is set to `headline-data', Org only adapts the
  1376. indentation of the data lines right below the headline, such as
  1377. planning/clock lines and property/logbook drawers.
  1378. The following issues are influenced by this variable:
  1379. - The indentation is increased by one space in a demotion
  1380. command, and decreased by one in a promotion command. However,
  1381. in the latter case, if shifting some line in the entry body
  1382. would alter document structure (e.g., insert a new headline),
  1383. indentation is not changed at all.
  1384. - Property drawers and planning information is inserted indented
  1385. when this variable is set. When nil, they will not be indented.
  1386. - TAB indents a line relative to current level. The lines below
  1387. a headline will be indented when this variable is set to t.
  1388. Note that this is all about true indentation, by adding and
  1389. removing space characters. See also \"org-indent.el\" which does
  1390. level-dependent indentation in a virtual way, i.e. at display
  1391. time in Emacs."
  1392. :group 'org-edit-structure
  1393. :type '(choice
  1394. (const :tag "Adapt indentation for all lines" t)
  1395. (const :tag "Adapt indentation for headline data lines"
  1396. headline-data)
  1397. (const :tag "Do not adapt indentation at all" nil))
  1398. :safe (lambda (x) (memq x '(t nil headline-data))))
  1399. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1400. (defcustom org-special-ctrl-a/e nil
  1401. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1402. When t, `C-a' will bring back the cursor to the beginning of the
  1403. headline text, i.e. after the stars and after a possible TODO
  1404. keyword. In an item, this will be the position after bullet and
  1405. check-box, if any. When the cursor is already at that position,
  1406. another `C-a' will bring it to the beginning of the line.
  1407. `C-e' will jump to the end of the headline, ignoring the presence
  1408. of tags in the headline. A second `C-e' will then jump to the
  1409. true end of the line, after any tags. This also means that, when
  1410. this variable is non-nil, `C-e' also will never jump beyond the
  1411. end of the heading of a folded section, i.e. not after the
  1412. ellipses.
  1413. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1414. normally, going to the true line boundary first. Only a directly
  1415. following, identical keypress will bring the cursor to the
  1416. special positions.
  1417. This may also be a cons cell where the behavior for `C-a' and
  1418. `C-e' is set separately."
  1419. :group 'org-edit-structure
  1420. :type '(choice
  1421. (const :tag "off" nil)
  1422. (const :tag "on: after stars/bullet and before tags first" t)
  1423. (const :tag "reversed: true line boundary first" reversed)
  1424. (cons :tag "Set C-a and C-e separately"
  1425. (choice :tag "Special C-a"
  1426. (const :tag "off" nil)
  1427. (const :tag "on: after stars/bullet first" t)
  1428. (const :tag "reversed: before stars/bullet first" reversed))
  1429. (choice :tag "Special C-e"
  1430. (const :tag "off" nil)
  1431. (const :tag "on: before tags first" t)
  1432. (const :tag "reversed: after tags first" reversed)))))
  1433. (defcustom org-special-ctrl-k nil
  1434. "Non-nil means `C-k' will behave specially in headlines.
  1435. When nil, `C-k' will call the default `kill-line' command.
  1436. When t, the following will happen while the cursor is in the headline:
  1437. - When at the beginning of a headline, kill the entire subtree.
  1438. - When in the middle of the headline text, kill the text up to the tags.
  1439. - When after the headline text and before the tags, kill all the tags."
  1440. :group 'org-edit-structure
  1441. :type 'boolean)
  1442. (defcustom org-ctrl-k-protect-subtree nil
  1443. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1444. When set to the symbol `error', simply throw an error when `C-k' is
  1445. used to kill (part-of) a headline that has hidden text behind it.
  1446. Any other non-nil value will result in a query to the user, if it is
  1447. OK to kill that hidden subtree. When nil, kill without remorse."
  1448. :group 'org-edit-structure
  1449. :version "24.1"
  1450. :type '(choice
  1451. (const :tag "Do not protect hidden subtrees" nil)
  1452. (const :tag "Protect hidden subtrees with a security query" t)
  1453. (const :tag "Never kill a hidden subtree with C-k" error)))
  1454. (defcustom org-special-ctrl-o t
  1455. "Non-nil means, make `C-o' insert a row in tables."
  1456. :group 'org-edit-structure
  1457. :type 'boolean)
  1458. (defcustom org-catch-invisible-edits nil
  1459. "Check if in invisible region before inserting or deleting a character.
  1460. Valid values are:
  1461. nil Do not check, so just do invisible edits.
  1462. error Throw an error and do nothing.
  1463. show Make point visible, and do the requested edit.
  1464. show-and-error Make point visible, then throw an error and abort the edit.
  1465. smart Make point visible, and do insertion/deletion if it is
  1466. adjacent to visible text and the change feels predictable.
  1467. Never delete a previously invisible character or add in the
  1468. middle or right after an invisible region. Basically, this
  1469. allows insertion and backward-delete right before ellipses.
  1470. FIXME: maybe in this case we should not even show?"
  1471. :group 'org-edit-structure
  1472. :version "24.1"
  1473. :type '(choice
  1474. (const :tag "Do not check" nil)
  1475. (const :tag "Throw error when trying to edit" error)
  1476. (const :tag "Unhide, but do not do the edit" show-and-error)
  1477. (const :tag "Show invisible part and do the edit" show)
  1478. (const :tag "Be smart and do the right thing" smart)))
  1479. (defcustom org-yank-folded-subtrees t
  1480. "Non-nil means when yanking subtrees, fold them.
  1481. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1482. it starts with a heading and all other headings in it are either children
  1483. or siblings, then fold all the subtrees. However, do this only if no
  1484. text after the yank would be swallowed into a folded tree by this action."
  1485. :group 'org-edit-structure
  1486. :type 'boolean)
  1487. (defcustom org-yank-adjusted-subtrees nil
  1488. "Non-nil means when yanking subtrees, adjust the level.
  1489. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1490. this function for details."
  1491. :group 'org-edit-structure
  1492. :type 'boolean)
  1493. (defcustom org-M-RET-may-split-line '((default . t))
  1494. "Non-nil means M-RET will split the line at the cursor position.
  1495. When nil, it will go to the end of the line before making a
  1496. new line.
  1497. You may also set this option in a different way for different
  1498. contexts. Valid contexts are:
  1499. headline when creating a new headline
  1500. item when creating a new item
  1501. table in a table field
  1502. default the value to be used for all contexts not explicitly
  1503. customized"
  1504. :group 'org-structure
  1505. :group 'org-table
  1506. :type '(choice
  1507. (const :tag "Always" t)
  1508. (const :tag "Never" nil)
  1509. (repeat :greedy t :tag "Individual contexts"
  1510. (cons
  1511. (choice :tag "Context"
  1512. (const headline)
  1513. (const item)
  1514. (const table)
  1515. (const default))
  1516. (boolean)))))
  1517. (defcustom org-insert-heading-respect-content nil
  1518. "Non-nil means insert new headings after the current subtree.
  1519. \\<org-mode-map>
  1520. When nil, the new heading is created directly after the current line.
  1521. The commands `\\[org-insert-heading-respect-content]' and \
  1522. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1523. for the duration of the command."
  1524. :group 'org-structure
  1525. :type 'boolean)
  1526. (defcustom org-blank-before-new-entry '((heading . auto)
  1527. (plain-list-item . auto))
  1528. "Should `org-insert-heading' leave a blank line before new heading/item?
  1529. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1530. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1531. which case Org will look at the surrounding headings/items and try to
  1532. make an intelligent decision whether to insert a blank line or not."
  1533. :group 'org-edit-structure
  1534. :type '(list
  1535. (cons (const heading)
  1536. (choice (const :tag "Never" nil)
  1537. (const :tag "Always" t)
  1538. (const :tag "Auto" auto)))
  1539. (cons (const plain-list-item)
  1540. (choice (const :tag "Never" nil)
  1541. (const :tag "Always" t)
  1542. (const :tag "Auto" auto)))))
  1543. (defcustom org-insert-heading-hook nil
  1544. "Hook being run after inserting a new heading."
  1545. :group 'org-edit-structure
  1546. :type 'hook)
  1547. (defgroup org-sparse-trees nil
  1548. "Options concerning sparse trees in Org mode."
  1549. :tag "Org Sparse Trees"
  1550. :group 'org-structure)
  1551. (defcustom org-highlight-sparse-tree-matches t
  1552. "Non-nil means highlight all matches that define a sparse tree.
  1553. The highlights will automatically disappear the next time the buffer is
  1554. changed by an edit command."
  1555. :group 'org-sparse-trees
  1556. :type 'boolean)
  1557. (defcustom org-remove-highlights-with-change t
  1558. "Non-nil means any change to the buffer will remove temporary highlights.
  1559. \\<org-mode-map>\
  1560. Such highlights are created by `org-occur' and `org-clock-display'.
  1561. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1562. to get rid of the highlights.
  1563. The highlights created by `org-latex-preview' always need
  1564. `\\[org-latex-preview]' to be removed."
  1565. :group 'org-sparse-trees
  1566. :group 'org-time
  1567. :type 'boolean)
  1568. (defcustom org-occur-case-fold-search t
  1569. "Non-nil means `org-occur' should be case-insensitive.
  1570. If set to `smart' the search will be case-insensitive only if it
  1571. doesn't specify any upper case character."
  1572. :group 'org-sparse-trees
  1573. :version "26.1"
  1574. :type '(choice
  1575. (const :tag "Case-sensitive" nil)
  1576. (const :tag "Case-insensitive" t)
  1577. (const :tag "Case-insensitive for lower case searches only" smart)))
  1578. (defcustom org-occur-hook '(org-first-headline-recenter)
  1579. "Hook that is run after `org-occur' has constructed a sparse tree.
  1580. This can be used to recenter the window to show as much of the structure
  1581. as possible."
  1582. :group 'org-sparse-trees
  1583. :type 'hook)
  1584. (defcustom org-self-insert-cluster-for-undo nil
  1585. "Non-nil means cluster self-insert commands for undo when possible.
  1586. If this is set, then, like in the Emacs command loop, 20 consecutive
  1587. characters will be undone together.
  1588. This is configurable, because there is some impact on typing performance."
  1589. :group 'org-table
  1590. :type 'boolean)
  1591. (defvaralias 'org-activate-links 'org-highlight-links)
  1592. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1593. "Types of links that should be highlighted in Org files.
  1594. This is a list of symbols, each one of them leading to the
  1595. highlighting of a certain link type.
  1596. You can still open links that are not highlighted.
  1597. In principle, it does not hurt to turn on highlighting for all
  1598. link types. There may be a small gain when turning off unused
  1599. link types. The types are:
  1600. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1601. angle Links in angular brackets that may contain whitespace like
  1602. <bbdb:Carsten Dominik>.
  1603. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1604. radio Text that is matched by a radio target, see manual for details.
  1605. tag Tag settings in a headline (link to tag search).
  1606. date Time stamps (link to calendar).
  1607. footnote Footnote labels.
  1608. If you set this variable during an Emacs session, use `org-mode-restart'
  1609. in the Org buffer so that the change takes effect."
  1610. :group 'org-appearance
  1611. :type '(set :greedy t
  1612. (const :tag "Double bracket links" bracket)
  1613. (const :tag "Angular bracket links" angle)
  1614. (const :tag "Plain text links" plain)
  1615. (const :tag "Radio target matches" radio)
  1616. (const :tag "Tags" tag)
  1617. (const :tag "Timestamps" date)
  1618. (const :tag "Footnotes" footnote)))
  1619. (defcustom org-mark-ring-length 4
  1620. "Number of different positions to be recorded in the ring.
  1621. Changing this requires a restart of Emacs to work correctly."
  1622. :group 'org-link-follow
  1623. :type 'integer)
  1624. (defgroup org-todo nil
  1625. "Options concerning TODO items in Org mode."
  1626. :tag "Org TODO"
  1627. :group 'org)
  1628. (defgroup org-progress nil
  1629. "Options concerning Progress logging in Org mode."
  1630. :tag "Org Progress"
  1631. :group 'org-time)
  1632. (defvar org-todo-interpretation-widgets
  1633. '((:tag "Sequence (cycling hits every state)" sequence)
  1634. (:tag "Type (cycling directly to DONE)" type))
  1635. "The available interpretation symbols for customizing `org-todo-keywords'.
  1636. Interested libraries should add to this list.")
  1637. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1638. "List of TODO entry keyword sequences and their interpretation.
  1639. \\<org-mode-map>This is a list of sequences.
  1640. Each sequence starts with a symbol, either `sequence' or `type',
  1641. indicating if the keywords should be interpreted as a sequence of
  1642. action steps, or as different types of TODO items. The first
  1643. keywords are states requiring action - these states will select a headline
  1644. for inclusion into the global TODO list Org produces. If one of the
  1645. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1646. signify that no further action is necessary. If \"|\" is not found,
  1647. the last keyword is treated as the only DONE state of the sequence.
  1648. The command `\\[org-todo]' cycles an entry through these states, and one
  1649. additional state where no keyword is present. For details about this
  1650. cycling, see the manual.
  1651. TODO keywords and interpretation can also be set on a per-file basis with
  1652. the special #+SEQ_TODO and #+TYP_TODO lines.
  1653. Each keyword can optionally specify a character for fast state selection
  1654. \(in combination with the variable `org-use-fast-todo-selection')
  1655. and specifiers for state change logging, using the same syntax that
  1656. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1657. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1658. indicates to record a time stamp each time this state is selected.
  1659. Each keyword may also specify if a timestamp or a note should be
  1660. recorded when entering or leaving the state, by adding additional
  1661. characters in the parenthesis after the keyword. This looks like this:
  1662. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1663. record only the time of the state change. With X and Y being either
  1664. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1665. Y when leaving the state if and only if the *target* state does not
  1666. define X. You may omit any of the fast-selection key or X or /Y,
  1667. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1668. For backward compatibility, this variable may also be just a list
  1669. of keywords. In this case the interpretation (sequence or type) will be
  1670. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1671. :group 'org-todo
  1672. :group 'org-keywords
  1673. :type '(choice
  1674. (repeat :tag "Old syntax, just keywords"
  1675. (string :tag "Keyword"))
  1676. (repeat :tag "New syntax"
  1677. (cons
  1678. (choice
  1679. :tag "Interpretation"
  1680. ;;Quick and dirty way to see
  1681. ;;`org-todo-interpretation'. This takes the
  1682. ;;place of item arguments
  1683. :convert-widget
  1684. (lambda (widget)
  1685. (widget-put widget
  1686. :args (mapcar
  1687. (lambda (x)
  1688. (widget-convert
  1689. (cons 'const x)))
  1690. org-todo-interpretation-widgets))
  1691. widget))
  1692. (repeat
  1693. (string :tag "Keyword"))))))
  1694. (defvar-local org-todo-keywords-1 nil
  1695. "All TODO and DONE keywords active in a buffer.")
  1696. (defvar org-todo-keywords-for-agenda nil)
  1697. (defvar org-done-keywords-for-agenda nil)
  1698. (defvar org-todo-keyword-alist-for-agenda nil)
  1699. (defvar org-tag-alist-for-agenda nil
  1700. "Alist of all tags from all agenda files.")
  1701. (defvar org-tag-groups-alist-for-agenda nil
  1702. "Alist of all groups tags from all current agenda files.")
  1703. (defvar-local org-tag-groups-alist nil)
  1704. (defvar org-agenda-contributing-files nil)
  1705. (defvar-local org-current-tag-alist nil
  1706. "Alist of all tag groups in current buffer.
  1707. This variable takes into consideration `org-tag-alist',
  1708. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1709. (defvar-local org-not-done-keywords nil)
  1710. (defvar-local org-done-keywords nil)
  1711. (defvar-local org-todo-heads nil)
  1712. (defvar-local org-todo-sets nil)
  1713. (defvar-local org-todo-log-states nil)
  1714. (defvar-local org-todo-kwd-alist nil)
  1715. (defvar-local org-todo-key-alist nil)
  1716. (defvar-local org-todo-key-trigger nil)
  1717. (defcustom org-todo-interpretation 'sequence
  1718. "Controls how TODO keywords are interpreted.
  1719. This variable is in principle obsolete and is only used for
  1720. backward compatibility, if the interpretation of todo keywords is
  1721. not given already in `org-todo-keywords'. See that variable for
  1722. more information."
  1723. :group 'org-todo
  1724. :group 'org-keywords
  1725. :type '(choice (const sequence)
  1726. (const type)))
  1727. (defcustom org-use-fast-todo-selection 'auto
  1728. "\\<org-mode-map>\
  1729. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1730. This variable describes if and under what circumstances the cycling
  1731. mechanism for TODO keywords will be replaced by a single-key, direct
  1732. selection scheme, where the choices are displayed in a little window.
  1733. When nil, fast selection is never used. This means that the command
  1734. will always switch to the next state.
  1735. When it is the symbol `auto', fast selection is whenever selection
  1736. keys have been defined.
  1737. `expert' is like `auto', but no special window with the keyword
  1738. will be shown, choices will only be listed in the prompt.
  1739. In all cases, the special interface is only used if access keys have
  1740. actually been assigned by the user, i.e. if keywords in the configuration
  1741. are followed by a letter in parenthesis, like TODO(t)."
  1742. :group 'org-todo
  1743. :set (lambda (var val)
  1744. (cond
  1745. ((eq var t) (set var 'auto))
  1746. ((eq var 'prefix) (set var nil))
  1747. (t (set var val))))
  1748. :type '(choice
  1749. (const :tag "Never" nil)
  1750. (const :tag "Automatically, when key letter have been defined" auto)
  1751. (const :tag "Automatically, but don't show the selection window" expert)))
  1752. (defcustom org-provide-todo-statistics t
  1753. "Non-nil means update todo statistics after insert and toggle.
  1754. ALL-HEADLINES means update todo statistics by including headlines
  1755. with no TODO keyword as well, counting them as not done.
  1756. A list of TODO keywords means the same, but skip keywords that are
  1757. not in this list.
  1758. When set to a list of two lists, the first list contains keywords
  1759. to consider as TODO keywords, the second list contains keywords
  1760. to consider as DONE keywords.
  1761. When this is set, todo statistics is updated in the parent of the
  1762. current entry each time a todo state is changed."
  1763. :group 'org-todo
  1764. :type '(choice
  1765. (const :tag "Yes, only for TODO entries" t)
  1766. (const :tag "Yes, including all entries" all-headlines)
  1767. (repeat :tag "Yes, for TODOs in this list"
  1768. (string :tag "TODO keyword"))
  1769. (list :tag "Yes, for TODOs and DONEs in these lists"
  1770. (repeat (string :tag "TODO keyword"))
  1771. (repeat (string :tag "DONE keyword")))
  1772. (other :tag "No TODO statistics" nil)))
  1773. (defcustom org-hierarchical-todo-statistics t
  1774. "Non-nil means TODO statistics covers just direct children.
  1775. When nil, all entries in the subtree are considered.
  1776. This has only an effect if `org-provide-todo-statistics' is set.
  1777. To set this to nil for only a single subtree, use a COOKIE_DATA
  1778. property and include the word \"recursive\" into the value."
  1779. :group 'org-todo
  1780. :type 'boolean)
  1781. (defcustom org-after-todo-state-change-hook nil
  1782. "Hook which is run after the state of a TODO item was changed.
  1783. The new state (a string with a TODO keyword, or nil) is available in the
  1784. Lisp variable `org-state'."
  1785. :group 'org-todo
  1786. :type 'hook)
  1787. (defvar org-blocker-hook nil
  1788. "Hook for functions that are allowed to block a state change.
  1789. Functions in this hook should not modify the buffer.
  1790. Each function gets as its single argument a property list,
  1791. see `org-trigger-hook' for more information about this list.
  1792. If any of the functions in this hook returns nil, the state change
  1793. is blocked.")
  1794. (defvar org-trigger-hook nil
  1795. "Hook for functions that are triggered by a state change.
  1796. Each function gets as its single argument a property list with at
  1797. least the following elements:
  1798. (:type type-of-change :position pos-at-entry-start
  1799. :from old-state :to new-state)
  1800. Depending on the type, more properties may be present.
  1801. This mechanism is currently implemented for:
  1802. TODO state changes
  1803. ------------------
  1804. :type todo-state-change
  1805. :from previous state (keyword as a string), or nil, or a symbol
  1806. `todo' or `done', to indicate the general type of state.
  1807. :to new state, like in :from")
  1808. (defcustom org-enforce-todo-dependencies nil
  1809. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1810. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1811. be blocked if any prior sibling is not yet done.
  1812. Finally, if the parent is blocked because of ordered siblings of its own,
  1813. the child will also be blocked."
  1814. :set (lambda (var val)
  1815. (set var val)
  1816. (if val
  1817. (add-hook 'org-blocker-hook
  1818. 'org-block-todo-from-children-or-siblings-or-parent)
  1819. (remove-hook 'org-blocker-hook
  1820. 'org-block-todo-from-children-or-siblings-or-parent)))
  1821. :group 'org-todo
  1822. :type 'boolean)
  1823. (defcustom org-enforce-todo-checkbox-dependencies nil
  1824. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1825. When this is nil, checkboxes have no influence on switching TODO states.
  1826. When non-nil, you first need to check off all check boxes before the TODO
  1827. entry can be switched to DONE.
  1828. This variable needs to be set before org.el is loaded, and you need to
  1829. restart Emacs after a change to make the change effective. The only way
  1830. to change it while Emacs is running is through the customize interface."
  1831. :set (lambda (var val)
  1832. (set var val)
  1833. (if val
  1834. (add-hook 'org-blocker-hook
  1835. 'org-block-todo-from-checkboxes)
  1836. (remove-hook 'org-blocker-hook
  1837. 'org-block-todo-from-checkboxes)))
  1838. :group 'org-todo
  1839. :type 'boolean)
  1840. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1841. "Non-nil means inserting a TODO heading is treated as state change.
  1842. So when the command `\\[org-insert-todo-heading]' is used, state change
  1843. logging will apply if appropriate. When nil, the new TODO item will
  1844. be inserted directly, and no logging will take place."
  1845. :group 'org-todo
  1846. :type 'boolean)
  1847. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1848. "Non-nil means switching TODO states with S-cursor counts as state change.
  1849. This is the default behavior. However, setting this to nil allows a
  1850. convenient way to select a TODO state and bypass any logging associated
  1851. with that."
  1852. :group 'org-todo
  1853. :type 'boolean)
  1854. (defcustom org-todo-state-tags-triggers nil
  1855. "Tag changes that should be triggered by TODO state changes.
  1856. This is a list. Each entry is
  1857. (state-change (tag . flag) .......)
  1858. State-change can be a string with a state, and empty string to indicate the
  1859. state that has no TODO keyword, or it can be one of the symbols `todo'
  1860. or `done', meaning any not-done or done state, respectively."
  1861. :group 'org-todo
  1862. :group 'org-tags
  1863. :type '(repeat
  1864. (cons (choice :tag "When changing to"
  1865. (const :tag "Not-done state" todo)
  1866. (const :tag "Done state" done)
  1867. (string :tag "State"))
  1868. (repeat
  1869. (cons :tag "Tag action"
  1870. (string :tag "Tag")
  1871. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1872. (defcustom org-log-done nil
  1873. "Information to record when a task moves to the DONE state.
  1874. Possible values are:
  1875. nil Don't add anything, just change the keyword
  1876. time Add a time stamp to the task
  1877. note Prompt for a note and add it with template `org-log-note-headings'
  1878. This option can also be set with on a per-file-basis with
  1879. #+STARTUP: nologdone
  1880. #+STARTUP: logdone
  1881. #+STARTUP: lognotedone
  1882. You can have local logging settings for a subtree by setting the LOGGING
  1883. property to one or more of these keywords."
  1884. :group 'org-todo
  1885. :group 'org-progress
  1886. :type '(choice
  1887. (const :tag "No logging" nil)
  1888. (const :tag "Record CLOSED timestamp" time)
  1889. (const :tag "Record CLOSED timestamp with note." note)))
  1890. ;; Normalize old uses of org-log-done.
  1891. (cond
  1892. ((eq org-log-done t) (setq org-log-done 'time))
  1893. ((and (listp org-log-done) (memq 'done org-log-done))
  1894. (setq org-log-done 'note)))
  1895. (defcustom org-log-reschedule nil
  1896. "Information to record when the scheduling date of a task is modified.
  1897. Possible values are:
  1898. nil Don't add anything, just change the date
  1899. time Add a time stamp to the task
  1900. note Prompt for a note and add it with template `org-log-note-headings'
  1901. This option can also be set with on a per-file-basis with
  1902. #+STARTUP: nologreschedule
  1903. #+STARTUP: logreschedule
  1904. #+STARTUP: lognotereschedule
  1905. You can have local logging settings for a subtree by setting the LOGGING
  1906. property to one or more of these keywords.
  1907. This variable has an effect when calling `org-schedule' or
  1908. `org-agenda-schedule' only."
  1909. :group 'org-todo
  1910. :group 'org-progress
  1911. :type '(choice
  1912. (const :tag "No logging" nil)
  1913. (const :tag "Record timestamp" time)
  1914. (const :tag "Record timestamp with note" note)))
  1915. (defcustom org-log-redeadline nil
  1916. "Information to record when the deadline date of a task is modified.
  1917. Possible values are:
  1918. nil Don't add anything, just change the date
  1919. time Add a time stamp to the task
  1920. note Prompt for a note and add it with template `org-log-note-headings'
  1921. This option can also be set with on a per-file-basis with
  1922. #+STARTUP: nologredeadline
  1923. #+STARTUP: logredeadline
  1924. #+STARTUP: lognoteredeadline
  1925. You can have local logging settings for a subtree by setting the LOGGING
  1926. property to one or more of these keywords.
  1927. This variable has an effect when calling `org-deadline' or
  1928. `org-agenda-deadline' only."
  1929. :group 'org-todo
  1930. :group 'org-progress
  1931. :type '(choice
  1932. (const :tag "No logging" nil)
  1933. (const :tag "Record timestamp" time)
  1934. (const :tag "Record timestamp with note." note)))
  1935. (defcustom org-log-note-clock-out nil
  1936. "Non-nil means record a note when clocking out of an item.
  1937. This can also be configured on a per-file basis by adding one of
  1938. the following lines anywhere in the buffer:
  1939. #+STARTUP: lognoteclock-out
  1940. #+STARTUP: nolognoteclock-out"
  1941. :group 'org-todo
  1942. :group 'org-progress
  1943. :type 'boolean)
  1944. (defcustom org-log-done-with-time t
  1945. "Non-nil means the CLOSED time stamp will contain date and time.
  1946. When nil, only the date will be recorded."
  1947. :group 'org-progress
  1948. :type 'boolean)
  1949. (defcustom org-log-note-headings
  1950. '((done . "CLOSING NOTE %t")
  1951. (state . "State %-12s from %-12S %t")
  1952. (note . "Note taken on %t")
  1953. (reschedule . "Rescheduled from %S on %t")
  1954. (delschedule . "Not scheduled, was %S on %t")
  1955. (redeadline . "New deadline from %S on %t")
  1956. (deldeadline . "Removed deadline, was %S on %t")
  1957. (refile . "Refiled on %t")
  1958. (clock-out . ""))
  1959. "Headings for notes added to entries.
  1960. The value is an alist, with the car being a symbol indicating the
  1961. note context, and the cdr is the heading to be used. The heading
  1962. may also be the empty string. The following placeholders can be
  1963. used:
  1964. %t a time stamp.
  1965. %T an active time stamp instead the default inactive one
  1966. %d a short-format time stamp.
  1967. %D an active short-format time stamp.
  1968. %s the new TODO state or time stamp (inactive), in double quotes.
  1969. %S the old TODO state or time stamp (inactive), in double quotes.
  1970. %u the user name.
  1971. %U full user name.
  1972. In fact, it is not a good idea to change the `state' entry,
  1973. because Agenda Log mode depends on the format of these entries."
  1974. :group 'org-todo
  1975. :group 'org-progress
  1976. :type '(list :greedy t
  1977. (cons (const :tag "Heading when closing an item" done) string)
  1978. (cons (const :tag
  1979. "Heading when changing todo state (todo sequence only)"
  1980. state) string)
  1981. (cons (const :tag "Heading when just taking a note" note) string)
  1982. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1983. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1984. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1985. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1986. (cons (const :tag "Heading when refiling" refile) string)
  1987. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1988. (unless (assq 'note org-log-note-headings)
  1989. (push '(note . "%t") org-log-note-headings))
  1990. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1991. (defcustom org-log-into-drawer nil
  1992. "Non-nil means insert state change notes and time stamps into a drawer.
  1993. When nil, state changes notes will be inserted after the headline and
  1994. any scheduling and clock lines, but not inside a drawer.
  1995. The value of this variable should be the name of the drawer to use.
  1996. LOGBOOK is proposed as the default drawer for this purpose, you can
  1997. also set this to a string to define the drawer of your choice.
  1998. A value of t is also allowed, representing \"LOGBOOK\".
  1999. A value of t or nil can also be set with on a per-file-basis with
  2000. #+STARTUP: logdrawer
  2001. #+STARTUP: nologdrawer
  2002. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2003. will be ignored.
  2004. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2005. a subtree.
  2006. Do not check directly this variable in a Lisp program. Call
  2007. function `org-log-into-drawer' instead."
  2008. :group 'org-todo
  2009. :group 'org-progress
  2010. :type '(choice
  2011. (const :tag "Not into a drawer" nil)
  2012. (const :tag "LOGBOOK" t)
  2013. (string :tag "Other")))
  2014. (defun org-log-into-drawer ()
  2015. "Name of the log drawer, as a string, or nil.
  2016. This is the value of `org-log-into-drawer'. However, if the
  2017. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2018. be used instead of the default value."
  2019. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2020. (cond ((equal p "nil") nil)
  2021. ((equal p "t") "LOGBOOK")
  2022. ((stringp p) p)
  2023. (p "LOGBOOK")
  2024. ((stringp org-log-into-drawer) org-log-into-drawer)
  2025. (org-log-into-drawer "LOGBOOK"))))
  2026. (defcustom org-log-state-notes-insert-after-drawers nil
  2027. "Non-nil means insert state change notes after any drawers in entry.
  2028. Only the drawers that *immediately* follow the headline and the
  2029. deadline/scheduled line are skipped.
  2030. When nil, insert notes right after the heading and perhaps the line
  2031. with deadline/scheduling if present.
  2032. This variable will have no effect if `org-log-into-drawer' is
  2033. set."
  2034. :group 'org-todo
  2035. :group 'org-progress
  2036. :type 'boolean)
  2037. (defcustom org-log-states-order-reversed t
  2038. "Non-nil means the latest state note will be directly after heading.
  2039. When nil, the state change notes will be ordered according to time.
  2040. This option can also be set with on a per-file-basis with
  2041. #+STARTUP: logstatesreversed
  2042. #+STARTUP: nologstatesreversed"
  2043. :group 'org-todo
  2044. :group 'org-progress
  2045. :type 'boolean)
  2046. (defcustom org-todo-repeat-to-state nil
  2047. "The TODO state to which a repeater should return the repeating task.
  2048. By default this is the first task of a TODO sequence or the
  2049. previous state of a TYPE_TODO set. But you can specify to use
  2050. the previous state in a TODO sequence or a string.
  2051. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2052. entry, which has precedence over this option."
  2053. :group 'org-todo
  2054. :version "24.1"
  2055. :type '(choice (const :tag "Use the previous TODO state" t)
  2056. (const :tag "Use the head of the TODO sequence" nil)
  2057. (string :tag "Use a specific TODO state")))
  2058. (defcustom org-log-repeat 'time
  2059. "Non-nil means record moving through the DONE state when triggering repeat.
  2060. An auto-repeating task is immediately switched back to TODO when
  2061. marked DONE. If you are not logging state changes (by adding \"@\"
  2062. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2063. record a closing note, there will be no record of the task moving
  2064. through DONE. This variable forces taking a note anyway.
  2065. nil Don't force a record
  2066. time Record a time stamp
  2067. note Prompt for a note and add it with template `org-log-note-headings'
  2068. This option can also be set with on a per-file-basis with
  2069. #+STARTUP: nologrepeat
  2070. #+STARTUP: logrepeat
  2071. #+STARTUP: lognoterepeat
  2072. You can have local logging settings for a subtree by setting the LOGGING
  2073. property to one or more of these keywords."
  2074. :group 'org-todo
  2075. :group 'org-progress
  2076. :type '(choice
  2077. (const :tag "Don't force a record" nil)
  2078. (const :tag "Force recording the DONE state" time)
  2079. (const :tag "Force recording a note with the DONE state" note)))
  2080. (defcustom org-todo-repeat-hook nil
  2081. "Hook that is run after a task has been repeated."
  2082. :package-version '(Org . "9.2")
  2083. :group 'org-todo
  2084. :type 'hook)
  2085. (defgroup org-priorities nil
  2086. "Priorities in Org mode."
  2087. :tag "Org Priorities"
  2088. :group 'org-todo)
  2089. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2090. (defcustom org-priority-enable-commands t
  2091. "Non-nil means priority commands are active.
  2092. When nil, these commands will be disabled, so that you never accidentally
  2093. set a priority."
  2094. :group 'org-priorities
  2095. :type 'boolean)
  2096. (defvaralias 'org-highest-priority 'org-priority-highest)
  2097. (defcustom org-priority-highest ?A
  2098. "The highest priority of TODO items.
  2099. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2100. The default is the character ?A, which is 65 as a numeric value.
  2101. If you set `org-priority-highest' to a numeric value inferior to
  2102. 65, Org assumes you want to use digits for the priority cookie.
  2103. If you set it to >=65, Org assumes you want to use alphabetical
  2104. characters.
  2105. In both cases, the value of `org-priority-highest' must be
  2106. smaller than `org-priority-lowest': for example, if \"A\" is the
  2107. highest priority, it is smaller than the lowest \"C\" priority:
  2108. 65 < 67."
  2109. :group 'org-priorities
  2110. :type '(choice
  2111. (character :tag "Character")
  2112. (integer :tag "Integer (< 65)")))
  2113. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2114. (defcustom org-priority-lowest ?C
  2115. "The lowest priority of TODO items.
  2116. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  2117. The default is the character ?C, which is 67 as a numeric value.
  2118. If you set `org-priority-lowest' to a numeric value inferior to
  2119. 65, Org assumes you want to use digits for the priority cookie.
  2120. If you set it to >=65, Org assumes you want to use alphabetical
  2121. characters.
  2122. In both cases, the value of `org-priority-lowest' must be greater
  2123. than `org-priority-highest': for example, if \"C\" is the lowest
  2124. priority, it is greater than the highest \"A\" priority: 67 >
  2125. 65."
  2126. :group 'org-priorities
  2127. :type '(choice
  2128. (character :tag "Character")
  2129. (integer :tag "Integer (< 65)")))
  2130. (defvaralias 'org-default-priority 'org-priority-default)
  2131. (defcustom org-priority-default ?B
  2132. "The default priority of TODO items.
  2133. This is the priority an item gets if no explicit priority is given.
  2134. When starting to cycle on an empty priority the first step in the cycle
  2135. depends on `org-priority-start-cycle-with-default'. The resulting first
  2136. step priority must not exceed the range from `org-priority-highest' to
  2137. `org-priority-lowest' which means that `org-priority-default' has to be
  2138. in this range exclusive or inclusive to the range boundaries. Else the
  2139. first step refuses to set the default and the second will fall back on
  2140. \(depending on the command used) the highest or lowest priority."
  2141. :group 'org-priorities
  2142. :type '(choice
  2143. (character :tag "Character")
  2144. (integer :tag "Integer (< 65)")))
  2145. (defcustom org-priority-start-cycle-with-default t
  2146. "Non-nil means start with default priority when starting to cycle.
  2147. When this is nil, the first step in the cycle will be (depending on the
  2148. command used) one higher or lower than the default priority.
  2149. See also `org-priority-default'."
  2150. :group 'org-priorities
  2151. :type 'boolean)
  2152. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2153. (defcustom org-priority-get-priority-function nil
  2154. "Function to extract the priority from a string.
  2155. The string is normally the headline. If this is nil, Org
  2156. computes the priority from the priority cookie like [#A] in the
  2157. headline. It returns an integer, increasing by 1000 for each
  2158. priority level.
  2159. The user can set a different function here, which should take a
  2160. string as an argument and return the numeric priority."
  2161. :group 'org-priorities
  2162. :version "24.1"
  2163. :type '(choice
  2164. (const nil)
  2165. (function)))
  2166. (defgroup org-time nil
  2167. "Options concerning time stamps and deadlines in Org mode."
  2168. :tag "Org Time"
  2169. :group 'org)
  2170. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2171. "Number of minutes to round time stamps to.
  2172. \\<org-mode-map>\
  2173. These are two values, the first applies when first creating a time stamp.
  2174. The second applies when changing it with the commands `S-up' and `S-down'.
  2175. When changing the time stamp, this means that it will change in steps
  2176. of N minutes, as given by the second value.
  2177. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2178. numbers should be factors of 60, so for example 5, 10, 15.
  2179. When this is larger than 1, you can still force an exact time stamp by using
  2180. a double prefix argument to a time stamp command like \
  2181. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2182. and by using a prefix arg to `S-up/down' to specify the exact number
  2183. of minutes to shift."
  2184. :group 'org-time
  2185. :get (lambda (var) ; Make sure both elements are there
  2186. (if (integerp (default-value var))
  2187. (list (default-value var) 5)
  2188. (default-value var)))
  2189. :type '(list
  2190. (integer :tag "when inserting times")
  2191. (integer :tag "when modifying times")))
  2192. ;; Normalize old customizations of this variable.
  2193. (when (integerp org-time-stamp-rounding-minutes)
  2194. (setq org-time-stamp-rounding-minutes
  2195. (list org-time-stamp-rounding-minutes
  2196. org-time-stamp-rounding-minutes)))
  2197. (defcustom org-display-custom-times nil
  2198. "Non-nil means overlay custom formats over all time stamps.
  2199. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2200. To turn this on on a per-file basis, insert anywhere in the file:
  2201. #+STARTUP: customtime"
  2202. :group 'org-time
  2203. :set 'set-default
  2204. :type 'sexp)
  2205. (make-variable-buffer-local 'org-display-custom-times)
  2206. (defcustom org-time-stamp-custom-formats
  2207. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2208. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2209. These are overlaid over the default ISO format if the variable
  2210. `org-display-custom-times' is set. Time like %H:%M should be at the
  2211. end of the second format. The custom formats are also honored by export
  2212. commands, if custom time display is turned on at the time of export."
  2213. :group 'org-time
  2214. :type 'sexp)
  2215. (defun org-time-stamp-format (&optional long inactive)
  2216. "Get the right format for a time string."
  2217. (let ((f (if long (cdr org-time-stamp-formats)
  2218. (car org-time-stamp-formats))))
  2219. (if inactive
  2220. (concat "[" (substring f 1 -1) "]")
  2221. f)))
  2222. (defcustom org-deadline-warning-days 14
  2223. "Number of days before expiration during which a deadline becomes active.
  2224. This variable governs the display in sparse trees and in the agenda.
  2225. When 0 or negative, it means use this number (the absolute value of it)
  2226. even if a deadline has a different individual lead time specified.
  2227. Custom commands can set this variable in the options section."
  2228. :group 'org-time
  2229. :group 'org-agenda-daily/weekly
  2230. :type 'integer)
  2231. (defcustom org-scheduled-delay-days 0
  2232. "Number of days before a scheduled item becomes active.
  2233. This variable governs the display in sparse trees and in the agenda.
  2234. The default value (i.e. 0) means: don't delay scheduled item.
  2235. When negative, it means use this number (the absolute value of it)
  2236. even if a scheduled item has a different individual delay time
  2237. specified.
  2238. Custom commands can set this variable in the options section."
  2239. :group 'org-time
  2240. :group 'org-agenda-daily/weekly
  2241. :version "24.4"
  2242. :package-version '(Org . "8.0")
  2243. :type 'integer)
  2244. (defcustom org-read-date-prefer-future t
  2245. "Non-nil means assume future for incomplete date input from user.
  2246. This affects the following situations:
  2247. 1. The user gives a month but not a year.
  2248. For example, if it is April and you enter \"feb 2\", this will be read
  2249. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2250. 2. The user gives a day, but no month.
  2251. For example, if today is the 15th, and you enter \"3\", Org will read
  2252. this as the third of *next* month. However, if you enter \"17\",
  2253. it will be considered as *this* month.
  2254. If you set this variable to the symbol `time', then also the following
  2255. will work:
  2256. 3. If the user gives a time.
  2257. If the time is before now, it will be interpreted as tomorrow.
  2258. Currently none of this works for ISO week specifications.
  2259. When this option is nil, the current day, month and year will always be
  2260. used as defaults.
  2261. See also `org-agenda-jump-prefer-future'."
  2262. :group 'org-time
  2263. :type '(choice
  2264. (const :tag "Never" nil)
  2265. (const :tag "Check month and day" t)
  2266. (const :tag "Check month, day, and time" time)))
  2267. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2268. "Should the agenda jump command prefer the future for incomplete dates?
  2269. The default is to do the same as configured in `org-read-date-prefer-future'.
  2270. But you can also set a deviating value here.
  2271. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2272. :group 'org-agenda
  2273. :group 'org-time
  2274. :version "24.1"
  2275. :type '(choice
  2276. (const :tag "Use org-read-date-prefer-future"
  2277. org-read-date-prefer-future)
  2278. (const :tag "Never" nil)
  2279. (const :tag "Always" t)))
  2280. (defcustom org-read-date-force-compatible-dates t
  2281. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2282. Depending on the system Emacs is running on, certain dates cannot
  2283. be represented with the type used internally to represent time.
  2284. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2285. correctly. Some systems allow for earlier dates, some for later,
  2286. some for both. One way to find out is to insert any date into an
  2287. Org buffer, putting the cursor on the year and hitting S-up and
  2288. S-down to test the range.
  2289. When this variable is set to t, the date/time prompt will not let
  2290. you specify dates outside the 1970-2037 range, so it is certain that
  2291. these dates will work in whatever version of Emacs you are
  2292. running, and also that you can move a file from one Emacs implementation
  2293. to another. Whenever Org is forcing the year for you, it will display
  2294. a message and beep.
  2295. When this variable is nil, Org will check if the date is
  2296. representable in the specific Emacs implementation you are using.
  2297. If not, it will force a year, usually the current year, and beep
  2298. to remind you. Currently this setting is not recommended because
  2299. the likelihood that you will open your Org files in an Emacs that
  2300. has limited date range is not negligible.
  2301. A workaround for this problem is to use diary sexp dates for time
  2302. stamps outside of this range."
  2303. :group 'org-time
  2304. :version "24.1"
  2305. :type 'boolean)
  2306. (defcustom org-read-date-display-live t
  2307. "Non-nil means display current interpretation of date prompt live.
  2308. This display will be in an overlay, in the minibuffer. Note that
  2309. live display is only active when `org-read-date-popup-calendar'
  2310. is non-nil."
  2311. :group 'org-time
  2312. :type 'boolean)
  2313. (defvaralias 'org-popup-calendar-for-date-prompt
  2314. 'org-read-date-popup-calendar)
  2315. (defcustom org-read-date-popup-calendar t
  2316. "Non-nil means pop up a calendar when prompting for a date.
  2317. In the calendar, the date can be selected with mouse-1. However, the
  2318. minibuffer will also be active, and you can simply enter the date as well.
  2319. When nil, only the minibuffer will be available."
  2320. :group 'org-time
  2321. :type 'boolean)
  2322. (defcustom org-extend-today-until 0
  2323. "The hour when your day really ends. Must be an integer.
  2324. This has influence for the following applications:
  2325. - When switching the agenda to \"today\". If it is still earlier than
  2326. the time given here, the day recognized as TODAY is actually yesterday.
  2327. - When a date is read from the user and it is still before the time given
  2328. here, the current date and time will be assumed to be yesterday, 23:59.
  2329. Also, timestamps inserted in capture templates follow this rule.
  2330. IMPORTANT: This is a feature whose implementation is and likely will
  2331. remain incomplete. Really, it is only here because past midnight seems to
  2332. be the favorite working time of John Wiegley :-)"
  2333. :group 'org-time
  2334. :type 'integer)
  2335. (defcustom org-use-effective-time nil
  2336. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2337. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2338. \"effective time\" of any timestamps between midnight and 8am will be
  2339. 23:59 of the previous day."
  2340. :group 'org-time
  2341. :version "24.1"
  2342. :type 'boolean)
  2343. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2344. "When non-nil, use the last clock out time for `org-todo'.
  2345. Note that this option has precedence over the combined use of
  2346. `org-use-effective-time' and `org-extend-today-until'."
  2347. :group 'org-time
  2348. :version "24.4"
  2349. :package-version '(Org . "8.0")
  2350. :type 'boolean)
  2351. (defcustom org-edit-timestamp-down-means-later nil
  2352. "Non-nil means S-down will increase the time in a time stamp.
  2353. When nil, S-up will increase."
  2354. :group 'org-time
  2355. :type 'boolean)
  2356. (defcustom org-calendar-follow-timestamp-change t
  2357. "Non-nil means make the calendar window follow timestamp changes.
  2358. When a timestamp is modified and the calendar window is visible, it will be
  2359. moved to the new date."
  2360. :group 'org-time
  2361. :type 'boolean)
  2362. (defgroup org-tags nil
  2363. "Options concerning tags in Org mode."
  2364. :tag "Org Tags"
  2365. :group 'org)
  2366. (defcustom org-tag-alist nil
  2367. "Default tags available in Org files.
  2368. The value of this variable is an alist. Associations either:
  2369. (TAG)
  2370. (TAG . SELECT)
  2371. (SPECIAL)
  2372. where TAG is a tag as a string, SELECT is character, used to
  2373. select that tag through the fast tag selection interface, and
  2374. SPECIAL is one of the following keywords: `:startgroup',
  2375. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2376. `:newline'. These keywords are used to define a hierarchy of
  2377. tags. See manual for details.
  2378. When this variable is nil, Org mode bases tag input on what is
  2379. already in the buffer. The value can be overridden locally by
  2380. using a TAGS keyword, e.g.,
  2381. #+TAGS: tag1 tag2
  2382. See also `org-tag-persistent-alist' to sidestep this behavior."
  2383. :group 'org-tags
  2384. :type '(repeat
  2385. (choice
  2386. (cons :tag "Tag with key"
  2387. (string :tag "Tag name")
  2388. (character :tag "Access char"))
  2389. (list :tag "Tag" (string :tag "Tag name"))
  2390. (const :tag "Start radio group" (:startgroup))
  2391. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2392. (const :tag "Group tags delimiter" (:grouptags))
  2393. (const :tag "End radio group" (:endgroup))
  2394. (const :tag "End tag group, non distinct" (:endgrouptag))
  2395. (const :tag "New line" (:newline)))))
  2396. (defcustom org-tag-persistent-alist nil
  2397. "Tags always available in Org files.
  2398. The value of this variable is an alist. Associations either:
  2399. (TAG)
  2400. (TAG . SELECT)
  2401. (SPECIAL)
  2402. where TAG is a tag as a string, SELECT is a character, used to
  2403. select that tag through the fast tag selection interface, and
  2404. SPECIAL is one of the following keywords: `:startgroup',
  2405. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2406. `:newline'. These keywords are used to define a hierarchy of
  2407. tags. See manual for details.
  2408. Unlike to `org-tag-alist', tags defined in this variable do not
  2409. depend on a local TAGS keyword. Instead, to disable these tags
  2410. on a per-file basis, insert anywhere in the file:
  2411. #+STARTUP: noptag"
  2412. :group 'org-tags
  2413. :type '(repeat
  2414. (choice
  2415. (cons :tag "Tag with key"
  2416. (string :tag "Tag name")
  2417. (character :tag "Access char"))
  2418. (list :tag "Tag" (string :tag "Tag name"))
  2419. (const :tag "Start radio group" (:startgroup))
  2420. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2421. (const :tag "Group tags delimiter" (:grouptags))
  2422. (const :tag "End radio group" (:endgroup))
  2423. (const :tag "End tag group, non distinct" (:endgrouptag))
  2424. (const :tag "New line" (:newline)))))
  2425. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2426. "If non-nil, always offer completion for all tags of all agenda files.
  2427. Setting this variable locally allows for dynamic generation of tag
  2428. completions in capture buffers.
  2429. (add-hook \\='org-capture-mode-hook
  2430. (lambda ()
  2431. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2432. :group 'org-tags
  2433. :version "24.1"
  2434. :type 'boolean)
  2435. (defvar org-file-tags nil
  2436. "List of tags that can be inherited by all entries in the file.
  2437. The tags will be inherited if the variable `org-use-tag-inheritance'
  2438. says they should be.
  2439. This variable is populated from #+FILETAGS lines.")
  2440. (defcustom org-use-fast-tag-selection 'auto
  2441. "Non-nil means use fast tag selection scheme.
  2442. This is a special interface to select and deselect tags with single keys.
  2443. When nil, fast selection is never used.
  2444. When the symbol `auto', fast selection is used if and only if selection
  2445. characters for tags have been configured, either through the variable
  2446. `org-tag-alist' or through a #+TAGS line in the buffer.
  2447. When t, fast selection is always used and selection keys are assigned
  2448. automatically if necessary."
  2449. :group 'org-tags
  2450. :type '(choice
  2451. (const :tag "Always" t)
  2452. (const :tag "Never" nil)
  2453. (const :tag "When selection characters are configured" auto)))
  2454. (defcustom org-fast-tag-selection-single-key nil
  2455. "Non-nil means fast tag selection exits after first change.
  2456. When nil, you have to press RET to exit it.
  2457. During fast tag selection, you can toggle this flag with `C-c'.
  2458. This variable can also have the value `expert'. In this case, the window
  2459. displaying the tags menu is not even shown, until you press `C-c' again."
  2460. :group 'org-tags
  2461. :type '(choice
  2462. (const :tag "No" nil)
  2463. (const :tag "Yes" t)
  2464. (const :tag "Expert" expert)))
  2465. (defvar org-fast-tag-selection-include-todo nil
  2466. "Non-nil means fast tags selection interface will also offer TODO states.
  2467. This is an undocumented feature, you should not rely on it.")
  2468. (defcustom org-tags-column -77
  2469. "The column to which tags should be indented in a headline.
  2470. If this number is positive, it specifies the column. If it is negative,
  2471. it means that the tags should be flushright to that column. For example,
  2472. -80 works well for a normal 80 character screen.
  2473. When 0, place tags directly after headline text, with only one space in
  2474. between."
  2475. :group 'org-tags
  2476. :type 'integer)
  2477. (defcustom org-auto-align-tags t
  2478. "Non-nil keeps tags aligned when modifying headlines.
  2479. Some operations (i.e. demoting) change the length of a headline and
  2480. therefore shift the tags around. With this option turned on, after
  2481. each such operation the tags are again aligned to `org-tags-column'."
  2482. :group 'org-tags
  2483. :type 'boolean)
  2484. (defcustom org-use-tag-inheritance t
  2485. "Non-nil means tags in levels apply also for sublevels.
  2486. When nil, only the tags directly given in a specific line apply there.
  2487. This may also be a list of tags that should be inherited, or a regexp that
  2488. matches tags that should be inherited. Additional control is possible
  2489. with the variable `org-tags-exclude-from-inheritance' which gives an
  2490. explicit list of tags to be excluded from inheritance, even if the value of
  2491. `org-use-tag-inheritance' would select it for inheritance.
  2492. If this option is t, a match early-on in a tree can lead to a large
  2493. number of matches in the subtree when constructing the agenda or creating
  2494. a sparse tree. If you only want to see the first match in a tree during
  2495. a search, check out the variable `org-tags-match-list-sublevels'."
  2496. :group 'org-tags
  2497. :type '(choice
  2498. (const :tag "Not" nil)
  2499. (const :tag "Always" t)
  2500. (repeat :tag "Specific tags" (string :tag "Tag"))
  2501. (regexp :tag "Tags matched by regexp")))
  2502. (defcustom org-tags-exclude-from-inheritance nil
  2503. "List of tags that should never be inherited.
  2504. This is a way to exclude a few tags from inheritance. For way to do
  2505. the opposite, to actively allow inheritance for selected tags,
  2506. see the variable `org-use-tag-inheritance'."
  2507. :group 'org-tags
  2508. :type '(repeat (string :tag "Tag")))
  2509. (defun org-tag-inherit-p (tag)
  2510. "Check if TAG is one that should be inherited."
  2511. (cond
  2512. ((member tag org-tags-exclude-from-inheritance) nil)
  2513. ((eq org-use-tag-inheritance t) t)
  2514. ((not org-use-tag-inheritance) nil)
  2515. ((stringp org-use-tag-inheritance)
  2516. (string-match org-use-tag-inheritance tag))
  2517. ((listp org-use-tag-inheritance)
  2518. (member tag org-use-tag-inheritance))
  2519. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2520. (defcustom org-tags-match-list-sublevels t
  2521. "Non-nil means list also sublevels of headlines matching a search.
  2522. This variable applies to tags/property searches, and also to stuck
  2523. projects because this search is based on a tags match as well.
  2524. When set to the symbol `indented', sublevels are indented with
  2525. leading dots.
  2526. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2527. the sublevels of a headline matching a tag search often also match
  2528. the same search. Listing all of them can create very long lists.
  2529. Setting this variable to nil causes subtrees of a match to be skipped.
  2530. This variable is semi-obsolete and probably should always be true. It
  2531. is better to limit inheritance to certain tags using the variables
  2532. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2533. :group 'org-tags
  2534. :type '(choice
  2535. (const :tag "No, don't list them" nil)
  2536. (const :tag "Yes, do list them" t)
  2537. (const :tag "List them, indented with leading dots" indented)))
  2538. (defcustom org-tags-sort-function nil
  2539. "When set, tags are sorted using this function as a comparator."
  2540. :group 'org-tags
  2541. :type '(choice
  2542. (const :tag "No sorting" nil)
  2543. (const :tag "Alphabetical" org-string-collate-lessp)
  2544. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2545. (function :tag "Custom function" nil)))
  2546. (defvar org-tags-history nil
  2547. "History of minibuffer reads for tags.")
  2548. (defvar org-last-tags-completion-table nil
  2549. "The last used completion table for tags.")
  2550. (defvar org-after-tags-change-hook nil
  2551. "Hook that is run after the tags in a line have changed.")
  2552. (defgroup org-properties nil
  2553. "Options concerning properties in Org mode."
  2554. :tag "Org Properties"
  2555. :group 'org)
  2556. (defcustom org-property-format "%-10s %s"
  2557. "How property key/value pairs should be formatted by `indent-line'.
  2558. When `indent-line' hits a property definition, it will format the line
  2559. according to this format, mainly to make sure that the values are
  2560. lined-up with respect to each other."
  2561. :group 'org-properties
  2562. :type 'string)
  2563. (defcustom org-properties-postprocess-alist nil
  2564. "Alist of properties and functions to adjust inserted values.
  2565. Elements of this alist must be of the form
  2566. ([string] [function])
  2567. where [string] must be a property name and [function] must be a
  2568. lambda expression: this lambda expression must take one argument,
  2569. the value to adjust, and return the new value as a string.
  2570. For example, this element will allow the property \"Remaining\"
  2571. to be updated wrt the relation between the \"Effort\" property
  2572. and the clock summary:
  2573. ((\"Remaining\" (lambda(value)
  2574. (let ((clocksum (org-clock-sum-current-item))
  2575. (effort (org-duration-to-minutes
  2576. (org-entry-get (point) \"Effort\"))))
  2577. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2578. :group 'org-properties
  2579. :version "24.1"
  2580. :type '(alist :key-type (string :tag "Property")
  2581. :value-type (function :tag "Function")))
  2582. (defcustom org-use-property-inheritance nil
  2583. "Non-nil means properties apply also for sublevels.
  2584. This setting is chiefly used during property searches. Turning it on can
  2585. cause significant overhead when doing a search, which is why it is not
  2586. on by default.
  2587. When nil, only the properties directly given in the current entry count.
  2588. When t, every property is inherited. The value may also be a list of
  2589. properties that should have inheritance, or a regular expression matching
  2590. properties that should be inherited.
  2591. However, note that some special properties use inheritance under special
  2592. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2593. and the properties ending in \"_ALL\" when they are used as descriptor
  2594. for valid values of a property.
  2595. Note for programmers:
  2596. When querying an entry with `org-entry-get', you can control if inheritance
  2597. should be used. By default, `org-entry-get' looks only at the local
  2598. properties. You can request inheritance by setting the inherit argument
  2599. to t (to force inheritance) or to `selective' (to respect the setting
  2600. in this variable)."
  2601. :group 'org-properties
  2602. :type '(choice
  2603. (const :tag "Not" nil)
  2604. (const :tag "Always" t)
  2605. (repeat :tag "Specific properties" (string :tag "Property"))
  2606. (regexp :tag "Properties matched by regexp")))
  2607. (defun org-property-inherit-p (property)
  2608. "Return a non-nil value if PROPERTY should be inherited."
  2609. (cond
  2610. ((eq org-use-property-inheritance t) t)
  2611. ((not org-use-property-inheritance) nil)
  2612. ((stringp org-use-property-inheritance)
  2613. (string-match org-use-property-inheritance property))
  2614. ((listp org-use-property-inheritance)
  2615. (member-ignore-case property org-use-property-inheritance))
  2616. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2617. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2618. "The default column format, if no other format has been defined.
  2619. This variable can be set on the per-file basis by inserting a line
  2620. #+COLUMNS: %25ITEM ....."
  2621. :group 'org-properties
  2622. :type 'string)
  2623. (defcustom org-columns-default-format-for-agenda nil
  2624. "The default column format in an agenda buffer.
  2625. This will be used for column view in the agenda unless a format has
  2626. been set by adding `org-overriding-columns-format' to the local
  2627. settings list of a custom agenda view. When nil, the columns format
  2628. for the first item in the agenda list will be used, or as a fall-back,
  2629. `org-columns-default-format'."
  2630. :group 'org-properties
  2631. :type '(choice
  2632. (const :tag "No default" nil)
  2633. (string :tag "Format string")))
  2634. (defcustom org-columns-ellipses ".."
  2635. "The ellipses to be used when a field in column view is truncated.
  2636. When this is the empty string, as many characters as possible are shown,
  2637. but then there will be no visual indication that the field has been truncated.
  2638. When this is a string of length N, the last N characters of a truncated
  2639. field are replaced by this string. If the column is narrower than the
  2640. ellipses string, only part of the ellipses string will be shown."
  2641. :group 'org-properties
  2642. :type 'string)
  2643. (defconst org-global-properties-fixed
  2644. '(("VISIBILITY_ALL" . "folded children content all")
  2645. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2646. "List of property/value pairs that can be inherited by any entry.
  2647. These are fixed values, for the preset properties. The user variable
  2648. that can be used to add to this list is `org-global-properties'.
  2649. The entries in this list are cons cells where the car is a property
  2650. name and cdr is a string with the value. If the value represents
  2651. multiple items like an \"_ALL\" property, separate the items by
  2652. spaces.")
  2653. (defcustom org-global-properties nil
  2654. "List of property/value pairs that can be inherited by any entry.
  2655. This list will be combined with the constant `org-global-properties-fixed'.
  2656. The entries in this list are cons cells where the car is a property
  2657. name and cdr is a string with the value.
  2658. Buffer local properties are added either by a document property drawer
  2659. :PROPERTIES:
  2660. :NAME: VALUE
  2661. :END:
  2662. or by adding lines like
  2663. #+PROPERTY: NAME VALUE"
  2664. :group 'org-properties
  2665. :type '(repeat
  2666. (cons (string :tag "Property")
  2667. (string :tag "Value"))))
  2668. (defvar-local org-keyword-properties nil
  2669. "List of property/value pairs inherited by any entry.
  2670. Valid for the current buffer. This variable is populated from
  2671. PROPERTY keywords.
  2672. Note that properties are defined also in property drawers.
  2673. Properties defined there take precedence over properties defined
  2674. as keywords.")
  2675. (defgroup org-agenda nil
  2676. "Options concerning agenda views in Org mode."
  2677. :tag "Org Agenda"
  2678. :group 'org)
  2679. (defvar-local org-category nil
  2680. "Variable used by Org files to set a category for agenda display.
  2681. There are multiple ways to set the category. One way is to set
  2682. it in the document property drawer. For example:
  2683. :PROPERTIES:
  2684. :CATEGORY: ELisp
  2685. :END:
  2686. Other ways to define it is as an emacs file variable, for example
  2687. # -*- mode: org; org-category: \"ELisp\"
  2688. or for the file to contain a special line:
  2689. #+CATEGORY: ELisp
  2690. If the file does not specify a category, then file's base name
  2691. is used instead.")
  2692. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2693. (defcustom org-agenda-files nil
  2694. "The files to be used for agenda display.
  2695. If an entry is a directory, all files in that directory that are matched
  2696. by `org-agenda-file-regexp' will be part of the file list.
  2697. If the value of the variable is not a list but a single file name, then
  2698. the list of agenda files is actually stored and maintained in that file,
  2699. one agenda file per line. In this file paths can be given relative to
  2700. `org-directory'. Tilde expansion and environment variable substitution
  2701. are also made.
  2702. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2703. and removed with `\\[org-remove-file]'."
  2704. :group 'org-agenda
  2705. :type '(choice
  2706. (repeat :tag "List of files and directories" file)
  2707. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2708. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2709. "Regular expression to match files for `org-agenda-files'.
  2710. If any element in the list in that variable contains a directory instead
  2711. of a normal file, all files in that directory that are matched by this
  2712. regular expression will be included."
  2713. :group 'org-agenda
  2714. :type 'regexp)
  2715. (defvaralias 'org-agenda-multi-occur-extra-files
  2716. 'org-agenda-text-search-extra-files)
  2717. (defcustom org-agenda-text-search-extra-files nil
  2718. "List of extra files to be searched by text search commands.
  2719. These files will be searched in addition to the agenda files by the
  2720. commands `org-search-view' (`\\[org-agenda] s') \
  2721. and `org-occur-in-agenda-files'.
  2722. Note that these files will only be searched for text search commands,
  2723. not for the other agenda views like todo lists, tag searches or the weekly
  2724. agenda. This variable is intended to list notes and possibly archive files
  2725. that should also be searched by these two commands.
  2726. In fact, if the first element in the list is the symbol `agenda-archives',
  2727. then all archive files of all agenda files will be added to the search
  2728. scope."
  2729. :group 'org-agenda
  2730. :type '(set :greedy t
  2731. (const :tag "Agenda Archives" agenda-archives)
  2732. (repeat :inline t (file))))
  2733. (defcustom org-agenda-skip-unavailable-files nil
  2734. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2735. A nil value means to remove them, after a query, from the list."
  2736. :group 'org-agenda
  2737. :type 'boolean)
  2738. (defgroup org-latex nil
  2739. "Options for embedding LaTeX code into Org mode."
  2740. :tag "Org LaTeX"
  2741. :group 'org)
  2742. (defcustom org-format-latex-options
  2743. '(:foreground default :background default :scale 1.0
  2744. :html-foreground "Black" :html-background "Transparent"
  2745. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2746. "Options for creating images from LaTeX fragments.
  2747. This is a property list with the following properties:
  2748. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2749. `default' means use the foreground of the default face.
  2750. `auto' means use the foreground from the text face.
  2751. :background the background color, or \"Transparent\".
  2752. `default' means use the background of the default face.
  2753. `auto' means use the background from the text face.
  2754. :scale a scaling factor for the size of the images, to get more pixels
  2755. :html-foreground, :html-background, :html-scale
  2756. the same numbers for HTML export.
  2757. :matchers a list indicating which matchers should be used to
  2758. find LaTeX fragments. Valid members of this list are:
  2759. \"begin\" find environments
  2760. \"$1\" find single characters surrounded by $.$
  2761. \"$\" find math expressions surrounded by $...$
  2762. \"$$\" find math expressions surrounded by $$....$$
  2763. \"\\(\" find math expressions surrounded by \\(...\\)
  2764. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2765. :group 'org-latex
  2766. :type 'plist)
  2767. (defcustom org-format-latex-signal-error t
  2768. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2769. When nil, just push out a message."
  2770. :group 'org-latex
  2771. :version "24.1"
  2772. :type 'boolean)
  2773. (defcustom org-latex-to-mathml-jar-file nil
  2774. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2775. Use this to specify additional executable file say a jar file.
  2776. When using MathToWeb as the converter, specify the full-path to
  2777. your mathtoweb.jar file."
  2778. :group 'org-latex
  2779. :version "24.1"
  2780. :type '(choice
  2781. (const :tag "None" nil)
  2782. (file :tag "JAR file" :must-match t)))
  2783. (defcustom org-latex-to-mathml-convert-command nil
  2784. "Command to convert LaTeX fragments to MathML.
  2785. Replace format-specifiers in the command as noted below and use
  2786. `shell-command' to convert LaTeX to MathML.
  2787. %j: Executable file in fully expanded form as specified by
  2788. `org-latex-to-mathml-jar-file'.
  2789. %I: Input LaTeX file in fully expanded form.
  2790. %i: The latex fragment to be converted.
  2791. %o: Output MathML file.
  2792. This command is used by `org-create-math-formula'.
  2793. When using MathToWeb as the converter, set this option to
  2794. \"java -jar %j -unicode -force -df %o %I\".
  2795. When using LaTeXML set this option to
  2796. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2797. :group 'org-latex
  2798. :version "24.1"
  2799. :type '(choice
  2800. (const :tag "None" nil)
  2801. (string :tag "\nShell command")))
  2802. (defcustom org-latex-to-html-convert-command nil
  2803. "Command to convert LaTeX fragments to HTML.
  2804. This command is very open-ended: the output of the command will
  2805. directly replace the LaTeX fragment in the resulting HTML.
  2806. Replace format-specifiers in the command as noted below and use
  2807. `shell-command' to convert LaTeX to HTML.
  2808. %i: The LaTeX fragment to be converted.
  2809. For example, this could be used with LaTeXML as
  2810. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2811. :group 'org-latex
  2812. :package-version '(Org . "9.4")
  2813. :type '(choice
  2814. (const :tag "None" nil)
  2815. (string :tag "Shell command")))
  2816. (defcustom org-preview-latex-default-process 'dvipng
  2817. "The default process to convert LaTeX fragments to image files.
  2818. All available processes and theirs documents can be found in
  2819. `org-preview-latex-process-alist', which see."
  2820. :group 'org-latex
  2821. :version "26.1"
  2822. :package-version '(Org . "9.0")
  2823. :type 'symbol)
  2824. (defcustom org-preview-latex-process-alist
  2825. '((dvipng
  2826. :programs ("latex" "dvipng")
  2827. :description "dvi > png"
  2828. :message "you need to install the programs: latex and dvipng."
  2829. :image-input-type "dvi"
  2830. :image-output-type "png"
  2831. :image-size-adjust (1.0 . 1.0)
  2832. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2833. :image-converter ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2834. (dvisvgm
  2835. :programs ("latex" "dvisvgm")
  2836. :description "dvi > svg"
  2837. :message "you need to install the programs: latex and dvisvgm."
  2838. :image-input-type "dvi"
  2839. :image-output-type "svg"
  2840. :image-size-adjust (1.7 . 1.5)
  2841. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2842. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2843. (imagemagick
  2844. :programs ("latex" "convert")
  2845. :description "pdf > png"
  2846. :message "you need to install the programs: latex and imagemagick."
  2847. :image-input-type "pdf"
  2848. :image-output-type "png"
  2849. :image-size-adjust (1.0 . 1.0)
  2850. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2851. :image-converter
  2852. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2853. "Definitions of external processes for LaTeX previewing.
  2854. Org mode can use some external commands to generate TeX snippet's images for
  2855. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2856. `org-create-formula-image' how to call them.
  2857. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2858. PROPERTIES accepts the following attributes:
  2859. :programs list of strings, required programs.
  2860. :description string, describe the process.
  2861. :message string, message it when required programs cannot be found.
  2862. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2863. :image-output-type string, output file type of image converter (e.g., \"png\").
  2864. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2865. image size showed in buffer and the cdr element is for
  2866. HTML file. This option is only useful for process
  2867. developers, users should use variable
  2868. `org-format-latex-options' instead.
  2869. :post-clean list of strings, files matched are to be cleaned up once
  2870. the image is generated. When nil, the files with \".dvi\",
  2871. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2872. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2873. be cleaned up.
  2874. :latex-header list of strings, the LaTeX header of the snippet file.
  2875. When nil, the fallback value is used instead, which is
  2876. controlled by `org-format-latex-header',
  2877. `org-latex-default-packages-alist' and
  2878. `org-latex-packages-alist', which see.
  2879. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2880. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2881. replaced with values defined below.
  2882. :image-converter list of image converter commands strings. Each of them is
  2883. given to the shell and supports any of the following
  2884. place-holders defined below.
  2885. Place-holders used by `:image-converter' and `:latex-compiler':
  2886. %f input file name
  2887. %b base name of input file
  2888. %o base directory of input file
  2889. %O absolute output file name
  2890. Place-holders only used by `:image-converter':
  2891. %D dpi, which is used to adjust image size by some processing commands.
  2892. %S the image size scale ratio, which is used to adjust image size by some
  2893. processing commands."
  2894. :group 'org-latex
  2895. :version "26.1"
  2896. :package-version '(Org . "9.0")
  2897. :type '(alist :tag "LaTeX to image backends"
  2898. :value-type (plist)))
  2899. (defcustom org-preview-latex-image-directory "ltximg/"
  2900. "Path to store latex preview images.
  2901. A relative path here creates many directories relative to the
  2902. processed Org files paths. An absolute path puts all preview
  2903. images at the same place."
  2904. :group 'org-latex
  2905. :version "26.1"
  2906. :package-version '(Org . "9.0")
  2907. :type 'string)
  2908. (defun org-format-latex-mathml-available-p ()
  2909. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2910. (save-match-data
  2911. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2912. org-latex-to-mathml-convert-command)
  2913. (let ((executable (car (split-string
  2914. org-latex-to-mathml-convert-command))))
  2915. (when (executable-find executable)
  2916. (if (string-match
  2917. "%j" org-latex-to-mathml-convert-command)
  2918. (file-readable-p org-latex-to-mathml-jar-file)
  2919. t))))))
  2920. (defcustom org-format-latex-header "\\documentclass{article}
  2921. \\usepackage[usenames]{color}
  2922. \[PACKAGES]
  2923. \[DEFAULT-PACKAGES]
  2924. \\pagestyle{empty} % do not remove
  2925. % The settings below are copied from fullpage.sty
  2926. \\setlength{\\textwidth}{\\paperwidth}
  2927. \\addtolength{\\textwidth}{-3cm}
  2928. \\setlength{\\oddsidemargin}{1.5cm}
  2929. \\addtolength{\\oddsidemargin}{-2.54cm}
  2930. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2931. \\setlength{\\textheight}{\\paperheight}
  2932. \\addtolength{\\textheight}{-\\headheight}
  2933. \\addtolength{\\textheight}{-\\headsep}
  2934. \\addtolength{\\textheight}{-\\footskip}
  2935. \\addtolength{\\textheight}{-3cm}
  2936. \\setlength{\\topmargin}{1.5cm}
  2937. \\addtolength{\\topmargin}{-2.54cm}"
  2938. "The document header used for processing LaTeX fragments.
  2939. It is imperative that this header make sure that no page number
  2940. appears on the page. The package defined in the variables
  2941. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2942. will either replace the placeholder \"[PACKAGES]\" in this
  2943. header, or they will be appended."
  2944. :group 'org-latex
  2945. :type 'string)
  2946. (defun org-set-packages-alist (var val)
  2947. "Set the packages alist and make sure it has 3 elements per entry."
  2948. (set var (mapcar (lambda (x)
  2949. (if (and (consp x) (= (length x) 2))
  2950. (list (car x) (nth 1 x) t)
  2951. x))
  2952. val)))
  2953. (defun org-get-packages-alist (var)
  2954. "Get the packages alist and make sure it has 3 elements per entry."
  2955. (mapcar (lambda (x)
  2956. (if (and (consp x) (= (length x) 2))
  2957. (list (car x) (nth 1 x) t)
  2958. x))
  2959. (default-value var)))
  2960. (defcustom org-latex-default-packages-alist
  2961. '(("AUTO" "inputenc" t ("pdflatex"))
  2962. ("T1" "fontenc" t ("pdflatex"))
  2963. ("" "graphicx" t)
  2964. ("" "grffile" t)
  2965. ("" "longtable" nil)
  2966. ("" "wrapfig" nil)
  2967. ("" "rotating" nil)
  2968. ("normalem" "ulem" t)
  2969. ("" "amsmath" t)
  2970. ("" "textcomp" t)
  2971. ("" "amssymb" t)
  2972. ("" "capt-of" nil)
  2973. ("" "hyperref" nil))
  2974. "Alist of default packages to be inserted in the header.
  2975. Change this only if one of the packages here causes an
  2976. incompatibility with another package you are using.
  2977. The packages in this list are needed by one part or another of
  2978. Org mode to function properly:
  2979. - inputenc, fontenc: for basic font and character selection
  2980. - graphicx: for including images
  2981. - grffile: allow periods and spaces in graphics file names
  2982. - longtable: For multipage tables
  2983. - wrapfig: for figure placement
  2984. - rotating: for sideways figures and tables
  2985. - ulem: for underline and strike-through
  2986. - amsmath: for subscript and superscript and math environments
  2987. - textcomp, amssymb: for various symbols used
  2988. for interpreting the entities in `org-entities'. You can skip
  2989. some of these packages if you don't use any of their symbols.
  2990. - capt-of: for captions outside of floats
  2991. - hyperref: for cross references
  2992. Therefore you should not modify this variable unless you know
  2993. what you are doing. The one reason to change it anyway is that
  2994. you might be loading some other package that conflicts with one
  2995. of the default packages. Each element is either a cell or
  2996. a string.
  2997. A cell is of the format
  2998. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2999. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3000. when compiling LaTeX snippets into images for inclusion into
  3001. non-LaTeX output.
  3002. COMPILERS is a list of compilers that should include the package,
  3003. see `org-latex-compiler'. If the document compiler is not in the
  3004. list, and the list is non-nil, the package will not be inserted
  3005. in the final document.
  3006. A string will be inserted as-is in the header of the document."
  3007. :group 'org-latex
  3008. :group 'org-export-latex
  3009. :set 'org-set-packages-alist
  3010. :get 'org-get-packages-alist
  3011. :version "26.1"
  3012. :package-version '(Org . "8.3")
  3013. :type '(repeat
  3014. (choice
  3015. (list :tag "options/package pair"
  3016. (string :tag "options")
  3017. (string :tag "package")
  3018. (boolean :tag "Snippet")
  3019. (choice
  3020. (const :tag "For all compilers" nil)
  3021. (repeat :tag "Allowed compiler" string)))
  3022. (string :tag "A line of LaTeX"))))
  3023. (defcustom org-latex-packages-alist nil
  3024. "Alist of packages to be inserted in every LaTeX header.
  3025. These will be inserted after `org-latex-default-packages-alist'.
  3026. Each element is either a cell or a string.
  3027. A cell is of the format:
  3028. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3029. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3030. needed when turning LaTeX snippets into images for inclusion into
  3031. non-LaTeX output.
  3032. COMPILERS is a list of compilers that should include the package,
  3033. see `org-latex-compiler'. If the document compiler is not in the
  3034. list, and the list is non-nil, the package will not be inserted
  3035. in the final document.
  3036. A string will be inserted as-is in the header of the document.
  3037. Make sure that you only list packages here which:
  3038. - you want in every file;
  3039. - do not conflict with the setup in `org-format-latex-header';
  3040. - do not conflict with the default packages in
  3041. `org-latex-default-packages-alist'."
  3042. :group 'org-latex
  3043. :group 'org-export-latex
  3044. :set 'org-set-packages-alist
  3045. :get 'org-get-packages-alist
  3046. :type '(repeat
  3047. (choice
  3048. (list :tag "options/package pair"
  3049. (string :tag "options")
  3050. (string :tag "package")
  3051. (boolean :tag "Snippet"))
  3052. (string :tag "A line of LaTeX"))))
  3053. (defgroup org-appearance nil
  3054. "Settings for Org mode appearance."
  3055. :tag "Org Appearance"
  3056. :group 'org)
  3057. (defcustom org-level-color-stars-only nil
  3058. "Non-nil means fontify only the stars in each headline.
  3059. When nil, the entire headline is fontified.
  3060. Changing it requires restart of `font-lock-mode' to become effective
  3061. also in regions already fontified."
  3062. :group 'org-appearance
  3063. :type 'boolean)
  3064. (defcustom org-hide-leading-stars nil
  3065. "Non-nil means hide the first N-1 stars in a headline.
  3066. This works by using the face `org-hide' for these stars. This
  3067. face is white for a light background, and black for a dark
  3068. background. You may have to customize the face `org-hide' to
  3069. make this work.
  3070. Changing it requires restart of `font-lock-mode' to become effective
  3071. also in regions already fontified.
  3072. You may also set this on a per-file basis by adding one of the following
  3073. lines to the buffer:
  3074. #+STARTUP: hidestars
  3075. #+STARTUP: showstars"
  3076. :group 'org-appearance
  3077. :type 'boolean)
  3078. (defcustom org-hidden-keywords nil
  3079. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3080. For example, a value \\='(title) for this list makes the document's title
  3081. appear in the buffer without the initial \"#+TITLE:\" part."
  3082. :group 'org-appearance
  3083. :package-version '(Org . "9.5")
  3084. :type '(set (const :tag "#+AUTHOR" author)
  3085. (const :tag "#+DATE" date)
  3086. (const :tag "#+EMAIL" email)
  3087. (const :tag "#+SUBTITLE" subtitle)
  3088. (const :tag "#+TITLE" title)))
  3089. (defcustom org-custom-properties nil
  3090. "List of properties (as strings) with a special meaning.
  3091. The default use of these custom properties is to let the user
  3092. hide them with `org-toggle-custom-properties-visibility'."
  3093. :group 'org-properties
  3094. :group 'org-appearance
  3095. :version "24.3"
  3096. :type '(repeat (string :tag "Property Name")))
  3097. (defcustom org-fontify-todo-headline nil
  3098. "Non-nil means change the face of a headline if it is marked as TODO.
  3099. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3100. When this is non-nil, the headline after the keyword is set to the
  3101. `org-headline-todo' as an additional indication."
  3102. :group 'org-appearance
  3103. :package-version '(Org . "9.4")
  3104. :type 'boolean
  3105. :safe t)
  3106. (defcustom org-fontify-done-headline t
  3107. "Non-nil means change the face of a headline if it is marked DONE.
  3108. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3109. When this is non-nil, the headline after the keyword is set to the
  3110. `org-headline-done' as an additional indication."
  3111. :group 'org-appearance
  3112. :package-version '(Org . "9.4")
  3113. :type 'boolean)
  3114. (defcustom org-fontify-emphasized-text t
  3115. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3116. Changing this variable requires a restart of Emacs to take effect."
  3117. :group 'org-appearance
  3118. :type 'boolean)
  3119. (defcustom org-fontify-whole-heading-line nil
  3120. "Non-nil means fontify the whole line for headings.
  3121. This is useful when setting a background color for the
  3122. org-level-* faces."
  3123. :group 'org-appearance
  3124. :type 'boolean)
  3125. (defcustom org-fontify-whole-block-delimiter-line t
  3126. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3127. This is useful when setting a background color for the
  3128. org-block-begin-line and org-block-end-line faces."
  3129. :group 'org-appearance
  3130. :type 'boolean)
  3131. (defcustom org-highlight-latex-and-related nil
  3132. "Non-nil means highlight LaTeX related syntax in the buffer.
  3133. When non-nil, the value should be a list containing any of the
  3134. following symbols:
  3135. `native' Highlight LaTeX snippets and environments natively.
  3136. `latex' Highlight LaTeX snippets and environments.
  3137. `script' Highlight subscript and superscript.
  3138. `entities' Highlight entities."
  3139. :group 'org-appearance
  3140. :version "24.4"
  3141. :package-version '(Org . "8.0")
  3142. :type '(choice
  3143. (const :tag "No highlighting" nil)
  3144. (set :greedy t :tag "Highlight"
  3145. (const :tag "LaTeX snippets and environments (native)" native)
  3146. (const :tag "LaTeX snippets and environments" latex)
  3147. (const :tag "Subscript and superscript" script)
  3148. (const :tag "Entities" entities))))
  3149. (defcustom org-hide-emphasis-markers nil
  3150. "Non-nil mean font-lock should hide the emphasis marker characters."
  3151. :group 'org-appearance
  3152. :type 'boolean
  3153. :safe #'booleanp)
  3154. (defcustom org-hide-macro-markers nil
  3155. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3156. :group 'org-appearance
  3157. :type 'boolean)
  3158. (defcustom org-pretty-entities nil
  3159. "Non-nil means show entities as UTF8 characters.
  3160. When nil, the \\name form remains in the buffer."
  3161. :group 'org-appearance
  3162. :version "24.1"
  3163. :type 'boolean)
  3164. (defcustom org-pretty-entities-include-sub-superscripts t
  3165. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3166. :group 'org-appearance
  3167. :version "24.1"
  3168. :type 'boolean)
  3169. (defvar org-emph-re nil
  3170. "Regular expression for matching emphasis.
  3171. After a match, the match groups contain these elements:
  3172. 0 The match of the full regular expression, including the characters
  3173. before and after the proper match
  3174. 1 The character before the proper match, or empty at beginning of line
  3175. 2 The proper match, including the leading and trailing markers
  3176. 3 The leading marker like * or /, indicating the type of highlighting
  3177. 4 The text between the emphasis markers, not including the markers
  3178. 5 The character after the match, empty at the end of a line")
  3179. (defvar org-verbatim-re nil
  3180. "Regular expression for matching verbatim text.")
  3181. (defvar org-emphasis-regexp-components) ; defined just below
  3182. (defvar org-emphasis-alist) ; defined just below
  3183. (defun org-set-emph-re (var val)
  3184. "Set variable and compute the emphasis regular expression."
  3185. (set var val)
  3186. (when (and (boundp 'org-emphasis-alist)
  3187. (boundp 'org-emphasis-regexp-components)
  3188. org-emphasis-alist org-emphasis-regexp-components)
  3189. (pcase-let*
  3190. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3191. (body (if (<= nl 0) body
  3192. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3193. (template
  3194. (format (concat "\\([%s]\\|^\\)" ;before markers
  3195. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3196. "\\([%s]\\|$\\)") ;after markers
  3197. pre border border body border post)))
  3198. (setq org-emph-re (format template "*/_+"))
  3199. (setq org-verbatim-re (format template "=~")))))
  3200. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3201. ;; set this option proved cumbersome. See this message/thread:
  3202. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3203. (defvar org-emphasis-regexp-components
  3204. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3205. "Components used to build the regular expression for emphasis.
  3206. This is a list with five entries. Terminology: In an emphasis string
  3207. like \" *strong word* \", we call the initial space PREMATCH, the final
  3208. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3209. and \"trong wor\" is the body. The different components in this variable
  3210. specify what is allowed/forbidden in each part:
  3211. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3212. post Chars allowed as postmatch. End of line will be allowed too.
  3213. border The chars *forbidden* as border characters.
  3214. body-regexp A regexp like \".\" to match a body character. Don't use
  3215. non-shy groups here, and don't allow newline here.
  3216. newline The maximum number of newlines allowed in an emphasis exp.
  3217. You need to reload Org or to restart Emacs after setting this.")
  3218. (defcustom org-emphasis-alist
  3219. '(("*" bold)
  3220. ("/" italic)
  3221. ("_" underline)
  3222. ("=" org-verbatim verbatim)
  3223. ("~" org-code verbatim)
  3224. ("+" (:strike-through t)))
  3225. "Alist of characters and faces to emphasize text.
  3226. Text starting and ending with a special character will be emphasized,
  3227. for example *bold*, _underlined_ and /italic/. This variable sets the
  3228. marker characters and the face to be used by font-lock for highlighting
  3229. in Org buffers.
  3230. You need to reload Org or to restart Emacs after customizing this."
  3231. :group 'org-appearance
  3232. :set 'org-set-emph-re
  3233. :version "24.4"
  3234. :package-version '(Org . "8.0")
  3235. :type '(repeat
  3236. (list
  3237. (string :tag "Marker character")
  3238. (choice
  3239. (face :tag "Font-lock-face")
  3240. (plist :tag "Face property list"))
  3241. (option (const verbatim)))))
  3242. (defvar org-protecting-blocks '("src" "example" "export")
  3243. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3244. This is needed for font-lock setup.")
  3245. ;;; Functions and variables from their packages
  3246. ;; Declared here to avoid compiler warnings
  3247. (defvar mark-active)
  3248. ;; Various packages
  3249. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3250. (declare-function calendar-forward-day "cal-move" (arg))
  3251. (declare-function calendar-goto-date "cal-move" (date))
  3252. (declare-function calendar-goto-today "cal-move" ())
  3253. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3254. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3255. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3256. (declare-function cdlatex-tab "ext:cdlatex" ())
  3257. (declare-function dired-get-filename
  3258. "dired"
  3259. (&optional localp no-error-if-not-filep))
  3260. (declare-function iswitchb-read-buffer
  3261. "iswitchb"
  3262. (prompt &optional
  3263. default require-match _predicate start matches-set))
  3264. (declare-function org-agenda-change-all-lines
  3265. "org-agenda"
  3266. (newhead hdmarker &optional fixface just-this))
  3267. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3268. "org-agenda"
  3269. (&optional end))
  3270. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3271. (declare-function org-agenda-format-item
  3272. "org-agenda"
  3273. (extra txt &optional level category tags dotime
  3274. remove-re habitp))
  3275. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3276. (declare-function org-agenda-save-markers-for-cut-and-paste
  3277. "org-agenda"
  3278. (beg end))
  3279. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3280. (declare-function org-agenda-skip "org-agenda" ())
  3281. (declare-function org-attach-expand "org-attach" (file))
  3282. (declare-function org-attach-reveal "org-attach" ())
  3283. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3284. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3285. (declare-function org-indent-mode "org-indent" (&optional arg))
  3286. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3287. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3288. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3289. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3290. (declare-function parse-time-string "parse-time" (string))
  3291. (defvar align-mode-rules-list)
  3292. (defvar calc-embedded-close-formula)
  3293. (defvar calc-embedded-open-formula)
  3294. (defvar calc-embedded-open-mode)
  3295. (defvar font-lock-unfontify-region-function)
  3296. (defvar iswitchb-temp-buflist)
  3297. (defvar org-agenda-tags-todo-honor-ignore-options)
  3298. (defvar remember-data-file)
  3299. (defvar texmathp-why)
  3300. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3301. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3302. (declare-function org-resolve-clocks "org-clock"
  3303. (&optional also-non-dangling-p prompt last-valid))
  3304. (defvar org-clock-start-time)
  3305. (defvar org-clock-marker (make-marker)
  3306. "Marker recording the last clock-in.")
  3307. (defvar org-clock-hd-marker (make-marker)
  3308. "Marker recording the last clock-in, but the headline position.")
  3309. (defvar org-clock-heading ""
  3310. "The heading of the current clock entry.")
  3311. (defun org-clocking-buffer ()
  3312. "Return the buffer where the clock is currently running.
  3313. Return nil if no clock is running."
  3314. (marker-buffer org-clock-marker))
  3315. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3316. (defun org-check-running-clock ()
  3317. "Check if the current buffer contains the running clock.
  3318. If yes, offer to stop it and to save the buffer with the changes."
  3319. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3320. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3321. (buffer-name))))
  3322. (org-clock-out)
  3323. (when (y-or-n-p "Save changed buffer?")
  3324. (save-buffer))))
  3325. (defun org-clocktable-try-shift (dir n)
  3326. "Check if this line starts a clock table, if yes, shift the time block."
  3327. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3328. (org-clocktable-shift dir n)))
  3329. ;;;###autoload
  3330. (defun org-clock-persistence-insinuate ()
  3331. "Set up hooks for clock persistence."
  3332. (require 'org-clock)
  3333. (add-hook 'org-mode-hook 'org-clock-load)
  3334. (add-hook 'kill-emacs-hook 'org-clock-save))
  3335. (defun org-clock-auto-clockout-insinuate ()
  3336. "Set up hook for auto clocking out when Emacs is idle.
  3337. See `org-clock-auto-clockout-timer'.
  3338. This function is meant to be added to the user configuration."
  3339. (require 'org-clock)
  3340. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3341. (defgroup org-archive nil
  3342. "Options concerning archiving in Org mode."
  3343. :tag "Org Archive"
  3344. :group 'org-structure)
  3345. (defcustom org-archive-location "%s_archive::"
  3346. "The location where subtrees should be archived.
  3347. The value of this variable is a string, consisting of two parts,
  3348. separated by a double-colon. The first part is a filename and
  3349. the second part is a headline.
  3350. When the filename is omitted, archiving happens in the same file.
  3351. %s in the filename will be replaced by the current file
  3352. name (without the directory part). Archiving to a different file
  3353. is useful to keep archived entries from contributing to the
  3354. Org Agenda.
  3355. The archived entries will be filed as subtrees of the specified
  3356. headline. When the headline is omitted, the subtrees are simply
  3357. filed away at the end of the file, as top-level entries. Also in
  3358. the heading you can use %s to represent the file name, this can be
  3359. useful when using the same archive for a number of different files.
  3360. Here are a few examples:
  3361. \"%s_archive::\"
  3362. If the current file is Projects.org, archive in file
  3363. Projects.org_archive, as top-level trees. This is the default.
  3364. \"::* Archived Tasks\"
  3365. Archive in the current file, under the top-level headline
  3366. \"* Archived Tasks\".
  3367. \"~/org/archive.org::\"
  3368. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3369. \"~/org/archive.org::* From %s\"
  3370. Archive in file ~/org/archive.org (absolute path), under headlines
  3371. \"From FILENAME\" where file name is the current file name.
  3372. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3373. The \"datetree/\" string is special, signifying to archive
  3374. items to the datetree. Items are placed in either the CLOSED
  3375. date of the item, or the current date if there is no CLOSED date.
  3376. The heading will be a subentry to the current date. There doesn't
  3377. need to be a heading, but there always needs to be a slash after
  3378. datetree. For example, to store archived items directly in the
  3379. datetree, use \"~/org/datetree.org::datetree/\".
  3380. \"basement::** Finished Tasks\"
  3381. Archive in file ./basement (relative path), as level 3 trees
  3382. below the level 2 heading \"** Finished Tasks\".
  3383. You may define it locally by setting an ARCHIVE property. If
  3384. such a property is found in the file or in an entry, and anywhere
  3385. up the hierarchy, it will be used.
  3386. You can also set it for the whole file using the keyword-syntax:
  3387. #+ARCHIVE: basement::** Finished Tasks"
  3388. :group 'org-archive
  3389. :type 'string)
  3390. (defcustom org-agenda-skip-archived-trees t
  3391. "Non-nil means the agenda will skip any items located in archived trees.
  3392. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3393. variable is no longer recommended, you should leave it at the value t.
  3394. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3395. :group 'org-archive
  3396. :group 'org-agenda-skip
  3397. :type 'boolean)
  3398. (defcustom org-columns-skip-archived-trees t
  3399. "Non-nil means ignore archived trees when creating column view."
  3400. :group 'org-archive
  3401. :group 'org-properties
  3402. :type 'boolean)
  3403. (defcustom org-cycle-open-archived-trees nil
  3404. "Non-nil means `org-cycle' will open archived trees.
  3405. An archived tree is a tree marked with the tag ARCHIVE.
  3406. When nil, archived trees will stay folded. You can still open them with
  3407. normal outline commands like `show-all', but not with the cycling commands."
  3408. :group 'org-archive
  3409. :group 'org-cycle
  3410. :type 'boolean)
  3411. (defcustom org-sparse-tree-open-archived-trees nil
  3412. "Non-nil means sparse tree construction shows matches in archived trees.
  3413. When nil, matches in these trees are highlighted, but the trees are kept in
  3414. collapsed state."
  3415. :group 'org-archive
  3416. :group 'org-sparse-trees
  3417. :type 'boolean)
  3418. (defcustom org-sparse-tree-default-date-type nil
  3419. "The default date type when building a sparse tree.
  3420. When this is nil, a date is a scheduled or a deadline timestamp.
  3421. Otherwise, these types are allowed:
  3422. all: all timestamps
  3423. active: only active timestamps (<...>)
  3424. inactive: only inactive timestamps ([...])
  3425. scheduled: only scheduled timestamps
  3426. deadline: only deadline timestamps"
  3427. :type '(choice (const :tag "Scheduled or deadline" nil)
  3428. (const :tag "All timestamps" all)
  3429. (const :tag "Only active timestamps" active)
  3430. (const :tag "Only inactive timestamps" inactive)
  3431. (const :tag "Only scheduled timestamps" scheduled)
  3432. (const :tag "Only deadline timestamps" deadline)
  3433. (const :tag "Only closed timestamps" closed))
  3434. :version "26.1"
  3435. :package-version '(Org . "8.3")
  3436. :group 'org-sparse-trees)
  3437. (defun org-cycle-hide-archived-subtrees (state)
  3438. "Re-hide all archived subtrees after a visibility state change.
  3439. STATE should be one of the symbols listed in the docstring of
  3440. `org-cycle-hook'."
  3441. (when (and (not org-cycle-open-archived-trees)
  3442. (not (memq state '(overview folded))))
  3443. (save-excursion
  3444. (let* ((globalp (memq state '(contents all)))
  3445. (beg (if globalp (point-min) (point)))
  3446. (end (if globalp (point-max) (org-end-of-subtree t))))
  3447. (org-hide-archived-subtrees beg end)
  3448. (goto-char beg)
  3449. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3450. (message "%s" (substitute-command-keys
  3451. "Subtree is archived and stays closed. Use \
  3452. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3453. (defun org-force-cycle-archived ()
  3454. "Cycle subtree even if it is archived."
  3455. (interactive)
  3456. (setq this-command 'org-cycle)
  3457. (let ((org-cycle-open-archived-trees t))
  3458. (call-interactively 'org-cycle)))
  3459. (defun org-hide-archived-subtrees (beg end)
  3460. "Re-hide all archived subtrees after a visibility state change."
  3461. (org-with-wide-buffer
  3462. (let ((case-fold-search nil)
  3463. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3464. (goto-char beg)
  3465. ;; Include headline point is currently on.
  3466. (beginning-of-line)
  3467. (while (and (< (point) end) (re-search-forward re end t))
  3468. (when (member org-archive-tag (org-get-tags nil t))
  3469. (org-flag-subtree t)
  3470. (org-end-of-subtree t))))))
  3471. (defun org-flag-subtree (flag)
  3472. (save-excursion
  3473. (org-back-to-heading t)
  3474. (org-flag-region (line-end-position)
  3475. (progn (org-end-of-subtree t) (point))
  3476. flag
  3477. 'outline)))
  3478. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3479. ;; Declare Column View Code
  3480. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3481. (declare-function org-columns-compute "org-colview" (property))
  3482. ;; Declare ID code
  3483. (declare-function org-id-store-link "org-id")
  3484. (declare-function org-id-locations-load "org-id")
  3485. (declare-function org-id-locations-save "org-id")
  3486. (defvar org-id-track-globally)
  3487. ;;; Variables for pre-computed regular expressions, all buffer local
  3488. (defvar-local org-todo-regexp nil
  3489. "Matches any of the TODO state keywords.
  3490. Since TODO keywords are case-sensitive, `case-fold-search' is
  3491. expected to be bound to nil when matching against this regexp.")
  3492. (defvar-local org-not-done-regexp nil
  3493. "Matches any of the TODO state keywords except the last one.
  3494. Since TODO keywords are case-sensitive, `case-fold-search' is
  3495. expected to be bound to nil when matching against this regexp.")
  3496. (defvar-local org-not-done-heading-regexp nil
  3497. "Matches a TODO headline that is not done.
  3498. Since TODO keywords are case-sensitive, `case-fold-search' is
  3499. expected to be bound to nil when matching against this regexp.")
  3500. (defvar-local org-todo-line-regexp nil
  3501. "Matches a headline and puts TODO state into group 2 if present.
  3502. Since TODO keywords are case-sensitive, `case-fold-search' is
  3503. expected to be bound to nil when matching against this regexp.")
  3504. (defvar-local org-complex-heading-regexp nil
  3505. "Matches a headline and puts everything into groups:
  3506. group 1: Stars
  3507. group 2: The TODO keyword, maybe
  3508. group 3: Priority cookie
  3509. group 4: True headline
  3510. group 5: Tags
  3511. Since TODO keywords are case-sensitive, `case-fold-search' is
  3512. expected to be bound to nil when matching against this regexp.")
  3513. (defvar-local org-complex-heading-regexp-format nil
  3514. "Printf format to make regexp to match an exact headline.
  3515. This regexp will match the headline of any node which has the
  3516. exact headline text that is put into the format, but may have any
  3517. TODO state, priority and tags.")
  3518. (defvar-local org-todo-line-tags-regexp nil
  3519. "Matches a headline and puts TODO state into group 2 if present.
  3520. Also put tags into group 4 if tags are present.")
  3521. (defconst org-plain-time-of-day-regexp
  3522. (concat
  3523. "\\(\\<[012]?[0-9]"
  3524. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3525. "\\(--?"
  3526. "\\(\\<[012]?[0-9]"
  3527. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3528. "\\)?")
  3529. "Regular expression to match a plain time or time range.
  3530. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3531. groups carry important information:
  3532. 0 the full match
  3533. 1 the first time, range or not
  3534. 8 the second time, if it is a range.")
  3535. (defconst org-plain-time-extension-regexp
  3536. (concat
  3537. "\\(\\<[012]?[0-9]"
  3538. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3539. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3540. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3541. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3542. groups carry important information:
  3543. 0 the full match
  3544. 7 hours of duration
  3545. 9 minutes of duration")
  3546. (defconst org-stamp-time-of-day-regexp
  3547. (concat
  3548. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3549. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3550. "\\(--?"
  3551. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3552. "Regular expression to match a timestamp time or time range.
  3553. After a match, the following groups carry important information:
  3554. 0 the full match
  3555. 1 date plus weekday, for back referencing to make sure
  3556. both times are on the same day
  3557. 2 the first time, range or not
  3558. 4 the second time, if it is a range.")
  3559. (defconst org-startup-options
  3560. '(("fold" org-startup-folded t)
  3561. ("overview" org-startup-folded t)
  3562. ("nofold" org-startup-folded nil)
  3563. ("showall" org-startup-folded nil)
  3564. ("show2levels" org-startup-folded show2levels)
  3565. ("show3levels" org-startup-folded show3levels)
  3566. ("show4levels" org-startup-folded show4levels)
  3567. ("show5levels" org-startup-folded show5levels)
  3568. ("showeverything" org-startup-folded showeverything)
  3569. ("content" org-startup-folded content)
  3570. ("indent" org-startup-indented t)
  3571. ("noindent" org-startup-indented nil)
  3572. ("num" org-startup-numerated t)
  3573. ("nonum" org-startup-numerated nil)
  3574. ("hidestars" org-hide-leading-stars t)
  3575. ("showstars" org-hide-leading-stars nil)
  3576. ("odd" org-odd-levels-only t)
  3577. ("oddeven" org-odd-levels-only nil)
  3578. ("align" org-startup-align-all-tables t)
  3579. ("noalign" org-startup-align-all-tables nil)
  3580. ("shrink" org-startup-shrink-all-tables t)
  3581. ("inlineimages" org-startup-with-inline-images t)
  3582. ("noinlineimages" org-startup-with-inline-images nil)
  3583. ("latexpreview" org-startup-with-latex-preview t)
  3584. ("nolatexpreview" org-startup-with-latex-preview nil)
  3585. ("customtime" org-display-custom-times t)
  3586. ("logdone" org-log-done time)
  3587. ("lognotedone" org-log-done note)
  3588. ("nologdone" org-log-done nil)
  3589. ("lognoteclock-out" org-log-note-clock-out t)
  3590. ("nolognoteclock-out" org-log-note-clock-out nil)
  3591. ("logrepeat" org-log-repeat state)
  3592. ("lognoterepeat" org-log-repeat note)
  3593. ("logdrawer" org-log-into-drawer t)
  3594. ("nologdrawer" org-log-into-drawer nil)
  3595. ("logstatesreversed" org-log-states-order-reversed t)
  3596. ("nologstatesreversed" org-log-states-order-reversed nil)
  3597. ("nologrepeat" org-log-repeat nil)
  3598. ("logreschedule" org-log-reschedule time)
  3599. ("lognotereschedule" org-log-reschedule note)
  3600. ("nologreschedule" org-log-reschedule nil)
  3601. ("logredeadline" org-log-redeadline time)
  3602. ("lognoteredeadline" org-log-redeadline note)
  3603. ("nologredeadline" org-log-redeadline nil)
  3604. ("logrefile" org-log-refile time)
  3605. ("lognoterefile" org-log-refile note)
  3606. ("nologrefile" org-log-refile nil)
  3607. ("fninline" org-footnote-define-inline t)
  3608. ("nofninline" org-footnote-define-inline nil)
  3609. ("fnlocal" org-footnote-section nil)
  3610. ("fnauto" org-footnote-auto-label t)
  3611. ("fnprompt" org-footnote-auto-label nil)
  3612. ("fnconfirm" org-footnote-auto-label confirm)
  3613. ("fnplain" org-footnote-auto-label plain)
  3614. ("fnadjust" org-footnote-auto-adjust t)
  3615. ("nofnadjust" org-footnote-auto-adjust nil)
  3616. ("constcgs" constants-unit-system cgs)
  3617. ("constSI" constants-unit-system SI)
  3618. ("noptag" org-tag-persistent-alist nil)
  3619. ("hideblocks" org-hide-block-startup t)
  3620. ("nohideblocks" org-hide-block-startup nil)
  3621. ("beamer" org-startup-with-beamer-mode t)
  3622. ("entitiespretty" org-pretty-entities t)
  3623. ("entitiesplain" org-pretty-entities nil))
  3624. "Variable associated with STARTUP options for Org.
  3625. Each element is a list of three items: the startup options (as written
  3626. in the #+STARTUP line), the corresponding variable, and the value to set
  3627. this variable to if the option is found. An optional fourth element PUSH
  3628. means to push this value onto the list in the variable.")
  3629. (defcustom org-group-tags t
  3630. "When non-nil (the default), use group tags.
  3631. This can be turned on/off through `org-toggle-tags-groups'."
  3632. :group 'org-tags
  3633. :group 'org-startup
  3634. :type 'boolean)
  3635. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3636. (defun org-toggle-tags-groups ()
  3637. "Toggle support for group tags.
  3638. Support for group tags is controlled by the option
  3639. `org-group-tags', which is non-nil by default."
  3640. (interactive)
  3641. (setq org-group-tags (not org-group-tags))
  3642. (cond ((and (derived-mode-p 'org-agenda-mode)
  3643. org-group-tags)
  3644. (org-agenda-redo))
  3645. ((derived-mode-p 'org-mode)
  3646. (let ((org-inhibit-startup t)) (org-mode))))
  3647. (message "Groups tags support has been turned %s"
  3648. (if org-group-tags "on" "off")))
  3649. (defun org--tag-add-to-alist (alist1 alist2)
  3650. "Merge tags from ALIST1 into ALIST2.
  3651. Duplicates tags outside a group are removed. Keywords and order
  3652. are preserved.
  3653. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3654. See `org-tag-alist' for their structure."
  3655. (cond
  3656. ((null alist2) alist1)
  3657. ((null alist1) alist2)
  3658. (t
  3659. (let ((to-add nil)
  3660. (group-flag nil))
  3661. (dolist (tag-pair alist1)
  3662. (pcase tag-pair
  3663. (`(,(or :startgrouptag :startgroup))
  3664. (setq group-flag t)
  3665. (push tag-pair to-add))
  3666. (`(,(or :endgrouptag :endgroup))
  3667. (setq group-flag nil)
  3668. (push tag-pair to-add))
  3669. (`(,(or :grouptags :newline))
  3670. (push tag-pair to-add))
  3671. (`(,tag . ,_)
  3672. ;; Remove duplicates from ALIST1, unless they are in
  3673. ;; a group. Indeed, it makes sense to have a tag appear in
  3674. ;; multiple groups.
  3675. (when (or group-flag (not (assoc tag alist2)))
  3676. (push tag-pair to-add)))
  3677. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3678. ;; Preserve order of ALIST1.
  3679. (append (nreverse to-add) alist2)))))
  3680. (defun org-priority-to-value (s)
  3681. "Convert priority string S to its numeric value."
  3682. (or (save-match-data
  3683. (and (string-match "\\([0-9]+\\)" s)
  3684. (string-to-number (match-string 1 s))))
  3685. (string-to-char s)))
  3686. (defun org-set-regexps-and-options (&optional tags-only)
  3687. "Precompute regular expressions used in the current buffer.
  3688. When optional argument TAGS-ONLY is non-nil, only compute tags
  3689. related expressions."
  3690. (when (derived-mode-p 'org-mode)
  3691. (let ((alist (org-collect-keywords
  3692. (append '("FILETAGS" "TAGS")
  3693. (and (not tags-only)
  3694. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3695. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3696. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3697. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3698. ;; Startup options. Get this early since it does change
  3699. ;; behavior for other options (e.g., tags).
  3700. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3701. (cdr (assoc "STARTUP" alist)))))
  3702. (dolist (option startup)
  3703. (pcase (assoc-string option org-startup-options t)
  3704. (`(,_ ,variable ,value t)
  3705. (unless (listp (symbol-value variable))
  3706. (set (make-local-variable variable) nil))
  3707. (add-to-list variable value))
  3708. (`(,_ ,variable ,value . ,_)
  3709. (set (make-local-variable variable) value))
  3710. (_ nil))))
  3711. (setq-local org-file-tags
  3712. (mapcar #'org-add-prop-inherited
  3713. (cl-mapcan (lambda (value)
  3714. (cl-mapcan
  3715. (lambda (k) (org-split-string k ":"))
  3716. (split-string value)))
  3717. (cdr (assoc "FILETAGS" alist)))))
  3718. (setq org-current-tag-alist
  3719. (org--tag-add-to-alist
  3720. org-tag-persistent-alist
  3721. (let ((tags (cdr (assoc "TAGS" alist))))
  3722. (if tags
  3723. (org-tag-string-to-alist
  3724. (mapconcat #'identity tags "\n"))
  3725. org-tag-alist))))
  3726. (setq org-tag-groups-alist
  3727. (org-tag-alist-to-groups org-current-tag-alist))
  3728. (unless tags-only
  3729. ;; Properties.
  3730. (let ((properties nil))
  3731. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3732. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3733. (setq properties (org--update-property-plist
  3734. (match-string-no-properties 1 value)
  3735. (match-string-no-properties 2 value)
  3736. properties))))
  3737. (setq-local org-keyword-properties properties))
  3738. ;; Archive location.
  3739. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3740. (when archive (setq-local org-archive-location archive)))
  3741. ;; Category.
  3742. (let ((category (cdr (assoc "CATEGORY" alist))))
  3743. (when category
  3744. (setq-local org-category (intern category))
  3745. (setq-local org-keyword-properties
  3746. (org--update-property-plist
  3747. "CATEGORY" category org-keyword-properties))))
  3748. ;; Columns.
  3749. (let ((column (cdr (assoc "COLUMNS" alist))))
  3750. (when column (setq-local org-columns-default-format column)))
  3751. ;; Constants.
  3752. (let ((store nil))
  3753. (dolist (pair (cl-mapcan #'split-string
  3754. (cdr (assoc "CONSTANTS" alist))))
  3755. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3756. (let* ((name (match-string 1 pair))
  3757. (value (match-string 2 pair))
  3758. (old (assoc name store)))
  3759. (if old (setcdr old value)
  3760. (push (cons name value) store)))))
  3761. (setq org-table-formula-constants-local store))
  3762. ;; Link abbreviations.
  3763. (let ((links
  3764. (delq nil
  3765. (mapcar
  3766. (lambda (value)
  3767. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3768. (cons (match-string-no-properties 1 value)
  3769. (match-string-no-properties 2 value))))
  3770. (cdr (assoc "LINK" alist))))))
  3771. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3772. ;; Priorities.
  3773. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3774. (pcase (and value (split-string value))
  3775. (`(,high ,low ,default . ,_)
  3776. (setq-local org-priority-highest (org-priority-to-value high))
  3777. (setq-local org-priority-lowest (org-priority-to-value low))
  3778. (setq-local org-priority-default (org-priority-to-value default)))))
  3779. ;; Scripts.
  3780. (let ((value (cdr (assoc "OPTIONS" alist))))
  3781. (dolist (option value)
  3782. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3783. (setq-local org-use-sub-superscripts
  3784. (read (match-string 1 option))))))
  3785. ;; TODO keywords.
  3786. (setq-local org-todo-kwd-alist nil)
  3787. (setq-local org-todo-key-alist nil)
  3788. (setq-local org-todo-key-trigger nil)
  3789. (setq-local org-todo-keywords-1 nil)
  3790. (setq-local org-done-keywords nil)
  3791. (setq-local org-todo-heads nil)
  3792. (setq-local org-todo-sets nil)
  3793. (setq-local org-todo-log-states nil)
  3794. (let ((todo-sequences
  3795. (or (append (mapcar (lambda (value)
  3796. (cons 'type (split-string value)))
  3797. (cdr (assoc "TYP_TODO" alist)))
  3798. (mapcar (lambda (value)
  3799. (cons 'sequence (split-string value)))
  3800. (append (cdr (assoc "TODO" alist))
  3801. (cdr (assoc "SEQ_TODO" alist)))))
  3802. (let ((d (default-value 'org-todo-keywords)))
  3803. (if (not (stringp (car d))) d
  3804. ;; XXX: Backward compatibility code.
  3805. (list (cons org-todo-interpretation d)))))))
  3806. (dolist (sequence todo-sequences)
  3807. (let* ((sequence (or (run-hook-with-args-until-success
  3808. 'org-todo-setup-filter-hook sequence)
  3809. sequence))
  3810. (sequence-type (car sequence))
  3811. (keywords (cdr sequence))
  3812. (sep (member "|" keywords))
  3813. names alist)
  3814. (dolist (k (remove "|" keywords))
  3815. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3816. k)
  3817. (error "Invalid TODO keyword %s" k))
  3818. (let ((name (match-string 1 k))
  3819. (key (match-string 2 k))
  3820. (log (org-extract-log-state-settings k)))
  3821. (push name names)
  3822. (push (cons name (and key (string-to-char key))) alist)
  3823. (when log (push log org-todo-log-states))))
  3824. (let* ((names (nreverse names))
  3825. (done (if sep (org-remove-keyword-keys (cdr sep))
  3826. (last names)))
  3827. (head (car names))
  3828. (tail (list sequence-type head (car done) (org-last done))))
  3829. (add-to-list 'org-todo-heads head 'append)
  3830. (push names org-todo-sets)
  3831. (setq org-done-keywords (append org-done-keywords done nil))
  3832. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3833. (setq org-todo-key-alist
  3834. (append org-todo-key-alist
  3835. (and alist
  3836. (append '((:startgroup))
  3837. (nreverse alist)
  3838. '((:endgroup))))))
  3839. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3840. (setq org-todo-sets (nreverse org-todo-sets)
  3841. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3842. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3843. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3844. ;; Compute the regular expressions and other local variables.
  3845. ;; Using `org-outline-regexp-bol' would complicate them much,
  3846. ;; because of the fixed white space at the end of that string.
  3847. (unless org-done-keywords
  3848. (setq org-done-keywords
  3849. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3850. (setq org-not-done-keywords
  3851. (org-delete-all org-done-keywords
  3852. (copy-sequence org-todo-keywords-1))
  3853. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3854. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3855. org-not-done-heading-regexp
  3856. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3857. org-todo-line-regexp
  3858. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3859. org-complex-heading-regexp
  3860. (concat "^\\(\\*+\\)"
  3861. "\\(?: +" org-todo-regexp "\\)?"
  3862. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3863. "\\(?: +\\(.*?\\)\\)??"
  3864. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3865. "[ \t]*$")
  3866. org-complex-heading-regexp-format
  3867. (concat "^\\(\\*+\\)"
  3868. "\\(?: +" org-todo-regexp "\\)?"
  3869. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3870. "\\(?: +"
  3871. ;; Stats cookies can be stuck to body.
  3872. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3873. "\\(%s\\)"
  3874. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3875. "\\)"
  3876. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3877. "[ \t]*$")
  3878. org-todo-line-tags-regexp
  3879. (concat "^\\(\\*+\\)"
  3880. "\\(?: +" org-todo-regexp "\\)?"
  3881. "\\(?: +\\(.*?\\)\\)??"
  3882. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3883. "[ \t]*$"))
  3884. (org-compute-latex-and-related-regexp)))))
  3885. (defun org-collect-keywords (keywords &optional unique directory)
  3886. "Return values for KEYWORDS in current buffer, as an alist.
  3887. KEYWORDS is a list of strings. Return value is a list of
  3888. elements with the pattern:
  3889. (NAME . LIST-OF-VALUES)
  3890. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3891. is a list of non-empty values, as strings, in order of appearance
  3892. in the buffer.
  3893. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3894. value, empty or not, appearing in the buffer, as a string.
  3895. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3896. (VALUE . DIRECTORY)
  3897. where VALUE is the regular value, and DIRECTORY is the variable
  3898. `default-directory' for the buffer containing the keyword. This
  3899. is important for values containing relative file names, since the
  3900. function follows SETUPFILE keywords, and may change its working
  3901. directory."
  3902. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3903. (unique (mapcar #'upcase unique))
  3904. (alist (org--collect-keywords-1
  3905. keywords unique directory
  3906. (and buffer-file-name (list buffer-file-name))
  3907. nil)))
  3908. ;; Re-order results.
  3909. (dolist (entry alist)
  3910. (pcase entry
  3911. (`(,_ . ,(and value (pred consp)))
  3912. (setcdr entry (nreverse value)))))
  3913. (nreverse alist)))
  3914. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3915. (org-with-point-at 1
  3916. (let ((case-fold-search t)
  3917. (regexp (org-make-options-regexp keywords)))
  3918. (while (and keywords (re-search-forward regexp nil t))
  3919. (let ((element (org-element-at-point)))
  3920. (when (eq 'keyword (org-element-type element))
  3921. (let ((value (org-element-property :value element)))
  3922. (pcase (org-element-property :key element)
  3923. ("SETUPFILE"
  3924. (when (and (org-string-nw-p value)
  3925. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3926. (let* ((uri (org-strip-quotes value))
  3927. (uri-is-url (org-file-url-p uri))
  3928. (uri (if uri-is-url
  3929. uri
  3930. (expand-file-name uri))))
  3931. (unless (member uri files)
  3932. (with-temp-buffer
  3933. (unless uri-is-url
  3934. (setq default-directory (file-name-directory uri)))
  3935. (let ((contents (org-file-contents uri :noerror)))
  3936. (when contents
  3937. (insert contents)
  3938. ;; Fake Org mode: `org-element-at-point'
  3939. ;; doesn't need full set-up.
  3940. (let ((major-mode 'org-mode))
  3941. (setq alist
  3942. (org--collect-keywords-1
  3943. keywords unique directory
  3944. (cons uri files)
  3945. alist))))))))))
  3946. (keyword
  3947. (let ((entry (assoc keyword alist))
  3948. (final
  3949. (cond ((not (member keyword directory)) value)
  3950. (buffer-file-name
  3951. (cons value
  3952. (file-name-directory buffer-file-name)))
  3953. (t (cons value default-directory)))))
  3954. (cond ((member keyword unique)
  3955. (push (cons keyword final) alist)
  3956. (setq keywords (remove keyword keywords))
  3957. (setq regexp (org-make-options-regexp keywords)))
  3958. ((null entry) (push (list keyword final) alist))
  3959. (t (push final (cdr entry)))))))))))
  3960. alist)))
  3961. (defun org-tag-string-to-alist (s)
  3962. "Return tag alist associated to string S.
  3963. S is a value for TAGS keyword or produced with
  3964. `org-tag-alist-to-string'. Return value is an alist suitable for
  3965. `org-tag-alist' or `org-tag-persistent-alist'."
  3966. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3967. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3968. "\\(?:(\\(.\\))\\)?\\'"))
  3969. alist group-flag)
  3970. (dolist (tokens lines (cdr (nreverse alist)))
  3971. (push '(:newline) alist)
  3972. (while tokens
  3973. (let ((token (pop tokens)))
  3974. (pcase token
  3975. ("{"
  3976. (push '(:startgroup) alist)
  3977. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3978. ("}"
  3979. (push '(:endgroup) alist)
  3980. (setq group-flag nil))
  3981. ("["
  3982. (push '(:startgrouptag) alist)
  3983. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3984. ("]"
  3985. (push '(:endgrouptag) alist)
  3986. (setq group-flag nil))
  3987. (":"
  3988. (push '(:grouptags) alist))
  3989. ((guard (string-match tag-re token))
  3990. (let ((tag (match-string 1 token))
  3991. (key (and (match-beginning 2)
  3992. (string-to-char (match-string 2 token)))))
  3993. ;; Push all tags in groups, no matter if they already
  3994. ;; appear somewhere else in the list.
  3995. (when (or group-flag (not (assoc tag alist)))
  3996. (push (cons tag key) alist))))))))))
  3997. (defun org-tag-alist-to-string (alist &optional skip-key)
  3998. "Return tag string associated to ALIST.
  3999. ALIST is an alist, as defined in `org-tag-alist' or
  4000. `org-tag-persistent-alist', or produced with
  4001. `org-tag-string-to-alist'.
  4002. Return value is a string suitable as a value for \"TAGS\"
  4003. keyword.
  4004. When optional argument SKIP-KEY is non-nil, skip selection keys
  4005. next to tags."
  4006. (mapconcat (lambda (token)
  4007. (pcase token
  4008. (`(:startgroup) "{")
  4009. (`(:endgroup) "}")
  4010. (`(:startgrouptag) "[")
  4011. (`(:endgrouptag) "]")
  4012. (`(:grouptags) ":")
  4013. (`(:newline) "\\n")
  4014. ((and
  4015. (guard (not skip-key))
  4016. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4017. (format "%s(%c)" tag key))
  4018. (`(,(and tag (pred stringp)) . ,_) tag)
  4019. (_ (user-error "Invalid tag token: %S" token))))
  4020. alist
  4021. " "))
  4022. (defun org-tag-alist-to-groups (alist)
  4023. "Return group alist from tag ALIST.
  4024. ALIST is an alist, as defined in `org-tag-alist' or
  4025. `org-tag-persistent-alist', or produced with
  4026. `org-tag-string-to-alist'. Return value is an alist following
  4027. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4028. a string, summarizing TAGS, as a list of strings."
  4029. (let (groups group-status current-group)
  4030. (dolist (token alist (nreverse groups))
  4031. (pcase token
  4032. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4033. (`(,(or :endgroup :endgrouptag))
  4034. (when (eq group-status 'append)
  4035. (push (nreverse current-group) groups))
  4036. (setq group-status nil current-group nil))
  4037. (`(:grouptags) (setq group-status 'append))
  4038. ((and `(,tag . ,_) (guard group-status))
  4039. (if (eq group-status 'append) (push tag current-group)
  4040. (setq current-group (list tag))))
  4041. (_ nil)))))
  4042. (defvar org--file-cache (make-hash-table :test #'equal)
  4043. "Hash table to store contents of files referenced via a URL.
  4044. This is the cache of file URLs read using `org-file-contents'.")
  4045. (defun org-reset-file-cache ()
  4046. "Reset the cache of files downloaded by `org-file-contents'."
  4047. (clrhash org--file-cache))
  4048. (defun org-file-url-p (file)
  4049. "Non-nil if FILE is a URL."
  4050. (require 'ffap)
  4051. (string-match-p ffap-url-regexp file))
  4052. (defun org-file-contents (file &optional noerror nocache)
  4053. "Return the contents of FILE, as a string.
  4054. FILE can be a file name or URL.
  4055. If FILE is a URL, download the contents. If the URL contents are
  4056. already cached in the `org--file-cache' hash table, the download step
  4057. is skipped.
  4058. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4059. from file or URL, and return nil.
  4060. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4061. is available. This option applies only if FILE is a URL."
  4062. (let* ((is-url (org-file-url-p file))
  4063. (cache (and is-url
  4064. (not nocache)
  4065. (gethash file org--file-cache))))
  4066. (cond
  4067. (cache)
  4068. (is-url
  4069. (with-current-buffer (url-retrieve-synchronously file)
  4070. (goto-char (point-min))
  4071. ;; Move point to after the url-retrieve header.
  4072. (search-forward "\n\n" nil :move)
  4073. ;; Search for the success code only in the url-retrieve header.
  4074. (if (save-excursion
  4075. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4076. ;; Update the cache `org--file-cache' and return contents.
  4077. (puthash file
  4078. (buffer-substring-no-properties (point) (point-max))
  4079. org--file-cache)
  4080. (funcall (if noerror #'message #'user-error)
  4081. "Unable to fetch file from %S"
  4082. file)
  4083. nil)))
  4084. (t
  4085. (with-temp-buffer
  4086. (condition-case nil
  4087. (progn
  4088. (insert-file-contents file)
  4089. (buffer-string))
  4090. (file-error
  4091. (funcall (if noerror #'message #'user-error)
  4092. "Unable to read file %S"
  4093. file)
  4094. nil)))))))
  4095. (defun org-extract-log-state-settings (x)
  4096. "Extract the log state setting from a TODO keyword string.
  4097. This will extract info from a string like \"WAIT(w@/!)\"."
  4098. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4099. (let ((kw (match-string 1 x))
  4100. (log1 (and (match-end 3) (match-string 3 x)))
  4101. (log2 (and (match-end 4) (match-string 4 x))))
  4102. (and (or log1 log2)
  4103. (list kw
  4104. (and log1 (if (equal log1 "!") 'time 'note))
  4105. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4106. (defun org-remove-keyword-keys (list)
  4107. "Remove a pair of parenthesis at the end of each string in LIST."
  4108. (mapcar (lambda (x)
  4109. (if (string-match "(.*)$" x)
  4110. (substring x 0 (match-beginning 0))
  4111. x))
  4112. list))
  4113. (defun org-assign-fast-keys (alist)
  4114. "Assign fast keys to a keyword-key alist.
  4115. Respect keys that are already there."
  4116. (let (new e (alt ?0))
  4117. (while (setq e (pop alist))
  4118. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4119. (cdr e)) ;; Key already assigned.
  4120. (push e new)
  4121. (let ((clist (string-to-list (downcase (car e))))
  4122. (used (append new alist)))
  4123. (when (= (car clist) ?@)
  4124. (pop clist))
  4125. (while (and clist (rassoc (car clist) used))
  4126. (pop clist))
  4127. (unless clist
  4128. (while (rassoc alt used)
  4129. (cl-incf alt)))
  4130. (push (cons (car e) (or (car clist) alt)) new))))
  4131. (nreverse new)))
  4132. ;;; Some variables used in various places
  4133. (defvar org-window-configuration nil
  4134. "Used in various places to store a window configuration.")
  4135. (defvar org-selected-window nil
  4136. "Used in various places to store a window configuration.")
  4137. (defvar org-finish-function nil
  4138. "Function to be called when `C-c C-c' is used.
  4139. This is for getting out of special buffers like capture.")
  4140. (defvar org-last-state)
  4141. ;; Defined somewhere in this file, but used before definition.
  4142. (defvar org-entities) ;; defined in org-entities.el
  4143. (defvar org-struct-menu)
  4144. (defvar org-org-menu)
  4145. (defvar org-tbl-menu)
  4146. ;;;; Define the Org mode
  4147. (defun org-before-change-function (_beg _end)
  4148. "Every change indicates that a table might need an update."
  4149. (setq org-table-may-need-update t))
  4150. (defvar org-mode-map)
  4151. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4152. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4153. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4154. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4155. (defvar bidi-paragraph-direction)
  4156. (defvar buffer-face-mode-face)
  4157. (require 'outline)
  4158. ;; Other stuff we need.
  4159. (require 'time-date)
  4160. (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
  4161. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4162. (require 'easymenu))
  4163. (require 'org-entities)
  4164. (require 'org-faces)
  4165. (require 'org-list)
  4166. (require 'org-pcomplete)
  4167. (require 'org-src)
  4168. (require 'org-footnote)
  4169. (require 'org-macro)
  4170. ;; babel
  4171. (require 'ob)
  4172. ;;;###autoload
  4173. (define-derived-mode org-mode outline-mode "Org"
  4174. "Outline-based notes management and organizer, alias
  4175. \"Carsten's outline-mode for keeping track of everything.\"
  4176. Org mode develops organizational tasks around a NOTES file which
  4177. contains information about projects as plain text. Org mode is
  4178. implemented on top of Outline mode, which is ideal to keep the content
  4179. of large files well structured. It supports ToDo items, deadlines and
  4180. time stamps, which magically appear in the diary listing of the Emacs
  4181. calendar. Tables are easily created with a built-in table editor.
  4182. Plain text URL-like links connect to websites, emails (VM), Usenet
  4183. messages (Gnus), BBDB entries, and any files related to the project.
  4184. For printing and sharing of notes, an Org file (or a part of it)
  4185. can be exported as a structured ASCII or HTML file.
  4186. The following commands are available:
  4187. \\{org-mode-map}"
  4188. (org-load-modules-maybe)
  4189. (org-install-agenda-files-menu)
  4190. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4191. (make-local-variable 'org-link-descriptive)
  4192. (add-to-invisibility-spec '(org-hide-block . t))
  4193. (setq-local outline-regexp org-outline-regexp)
  4194. (setq-local outline-level 'org-outline-level)
  4195. (setq bidi-paragraph-direction 'left-to-right)
  4196. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4197. (unless org-display-table
  4198. (setq org-display-table (make-display-table)))
  4199. (set-display-table-slot
  4200. org-display-table 4
  4201. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4202. org-ellipsis)))
  4203. (setq buffer-display-table org-display-table))
  4204. (org-set-regexps-and-options)
  4205. (org-set-font-lock-defaults)
  4206. (when (and org-tag-faces (not org-tags-special-faces-re))
  4207. ;; tag faces set outside customize.... force initialization.
  4208. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4209. ;; Calc embedded
  4210. (setq-local calc-embedded-open-mode "# ")
  4211. ;; Modify a few syntax entries
  4212. (modify-syntax-entry ?\" "\"")
  4213. (modify-syntax-entry ?\\ "_")
  4214. (modify-syntax-entry ?~ "_")
  4215. (modify-syntax-entry ?< "(>")
  4216. (modify-syntax-entry ?> ")<")
  4217. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4218. ;; Activate before-change-function
  4219. (setq-local org-table-may-need-update t)
  4220. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4221. ;; Check for running clock before killing a buffer
  4222. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4223. ;; Initialize macros templates.
  4224. (org-macro-initialize-templates)
  4225. ;; Initialize radio targets.
  4226. (org-update-radio-target-regexp)
  4227. ;; Indentation.
  4228. (setq-local indent-line-function 'org-indent-line)
  4229. (setq-local indent-region-function 'org-indent-region)
  4230. ;; Filling and auto-filling.
  4231. (org-setup-filling)
  4232. ;; Comments.
  4233. (org-setup-comments-handling)
  4234. ;; Initialize cache.
  4235. (org-element-cache-reset)
  4236. ;; Beginning/end of defun
  4237. (setq-local beginning-of-defun-function 'org-backward-element)
  4238. (setq-local end-of-defun-function
  4239. (lambda ()
  4240. (if (not (org-at-heading-p))
  4241. (org-forward-element)
  4242. (org-forward-element)
  4243. (forward-char -1))))
  4244. ;; Next error for sparse trees
  4245. (setq-local next-error-function 'org-occur-next-match)
  4246. ;; Make commit log messages from Org documents easier.
  4247. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4248. ;; Make sure dependence stuff works reliably, even for users who set it
  4249. ;; too late :-(
  4250. (if org-enforce-todo-dependencies
  4251. (add-hook 'org-blocker-hook
  4252. 'org-block-todo-from-children-or-siblings-or-parent)
  4253. (remove-hook 'org-blocker-hook
  4254. 'org-block-todo-from-children-or-siblings-or-parent))
  4255. (if org-enforce-todo-checkbox-dependencies
  4256. (add-hook 'org-blocker-hook
  4257. 'org-block-todo-from-checkboxes)
  4258. (remove-hook 'org-blocker-hook
  4259. 'org-block-todo-from-checkboxes))
  4260. ;; Align options lines
  4261. (setq-local
  4262. align-mode-rules-list
  4263. '((org-in-buffer-settings
  4264. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4265. (modes . '(org-mode)))))
  4266. ;; Setup the pcomplete hooks
  4267. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4268. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4269. (setq-local pcomplete-default-completion-function #'ignore)
  4270. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4271. (setq-local pcomplete-termination-string "")
  4272. (add-hook 'completion-at-point-functions
  4273. #'pcomplete-completions-at-point nil t)
  4274. (setq-local buffer-face-mode-face 'org-default)
  4275. ;; If empty file that did not turn on Org mode automatically, make
  4276. ;; it to.
  4277. (when (and org-insert-mode-line-in-empty-file
  4278. (called-interactively-p 'any)
  4279. (= (point-min) (point-max)))
  4280. (insert "# -*- mode: org -*-\n\n"))
  4281. (unless org-inhibit-startup
  4282. (org-unmodified
  4283. (when org-startup-with-beamer-mode (org-beamer-mode))
  4284. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4285. (org-table-map-tables
  4286. (cond ((and org-startup-align-all-tables
  4287. org-startup-shrink-all-tables)
  4288. (lambda () (org-table-align) (org-table-shrink)))
  4289. (org-startup-align-all-tables #'org-table-align)
  4290. (t #'org-table-shrink))
  4291. t))
  4292. (when org-startup-with-inline-images (org-display-inline-images))
  4293. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4294. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4295. (when org-startup-truncated (setq truncate-lines t))
  4296. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4297. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4298. ;; Add a custom keymap for `visual-line-mode' so that activating
  4299. ;; this minor mode does not override Org's keybindings.
  4300. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4301. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4302. (newmap (make-sparse-keymap)))
  4303. (set-keymap-parent newmap oldmap)
  4304. (define-key newmap [remap move-beginning-of-line] nil)
  4305. (define-key newmap [remap move-end-of-line] nil)
  4306. (define-key newmap [remap kill-line] nil)
  4307. (make-local-variable 'minor-mode-overriding-map-alist)
  4308. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4309. ;; Activate `org-table-header-line-mode'
  4310. (when org-table-header-line-p
  4311. (org-table-header-line-mode 1))
  4312. ;; Try to set `org-hide' face correctly.
  4313. (let ((foreground (org-find-invisible-foreground)))
  4314. (when foreground
  4315. (set-face-foreground 'org-hide foreground)))
  4316. ;; Set face extension as requested.
  4317. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4318. org-fontify-whole-block-delimiter-line)
  4319. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4320. ;; Update `customize-package-emacs-version-alist'
  4321. (add-to-list 'customize-package-emacs-version-alist
  4322. '(Org ("8.0" . "24.4")
  4323. ("8.1" . "24.4")
  4324. ("8.2" . "24.4")
  4325. ("8.2.7" . "24.4")
  4326. ("8.3" . "26.1")
  4327. ("9.0" . "26.1")
  4328. ("9.1" . "26.1")
  4329. ("9.2" . "27.1")
  4330. ("9.3" . "27.1")
  4331. ("9.4" . "27.2")
  4332. ("9.5" . "28.1")))
  4333. (defvar org-mode-transpose-word-syntax-table
  4334. (let ((st (make-syntax-table text-mode-syntax-table)))
  4335. (dolist (c org-emphasis-alist st)
  4336. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4337. (when (fboundp 'abbrev-table-put)
  4338. (abbrev-table-put org-mode-abbrev-table
  4339. :parents (list text-mode-abbrev-table)))
  4340. (defun org-find-invisible-foreground ()
  4341. (let ((candidates (remove
  4342. "unspecified-bg"
  4343. (nconc
  4344. (list (face-background 'default)
  4345. (face-background 'org-default))
  4346. (mapcar
  4347. (lambda (alist)
  4348. (when (boundp alist)
  4349. (cdr (assq 'background-color (symbol-value alist)))))
  4350. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4351. (list (face-foreground 'org-hide))))))
  4352. (car (remove nil candidates))))
  4353. (defun org-current-time (&optional rounding-minutes past)
  4354. "Current time, possibly rounded to ROUNDING-MINUTES.
  4355. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4356. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4357. the rounding returns a past time."
  4358. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4359. (car org-time-stamp-rounding-minutes)))
  4360. (now (current-time)))
  4361. (if (< r 1)
  4362. now
  4363. (let* ((time (decode-time now))
  4364. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4365. (nthcdr 2 time))))
  4366. (if (or (not past) (org-time-less-p res now))
  4367. res
  4368. (org-time-subtract res (* r 60)))))))
  4369. (defun org-today ()
  4370. "Return today date, considering `org-extend-today-until'."
  4371. (time-to-days
  4372. (org-time-since (* 3600 org-extend-today-until))))
  4373. ;;;; Font-Lock stuff, including the activators
  4374. (defconst org-match-sexp-depth 3
  4375. "Number of stacked braces for sub/superscript matching.")
  4376. (defun org-create-multibrace-regexp (left right n)
  4377. "Create a regular expression which will match a balanced sexp.
  4378. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4379. as single character strings.
  4380. The regexp returned will match the entire expression including the
  4381. delimiters. It will also define a single group which contains the
  4382. match except for the outermost delimiters. The maximum depth of
  4383. stacked delimiters is N. Escaping delimiters is not possible."
  4384. (let* ((nothing (concat "[^" left right "]*?"))
  4385. (or "\\|")
  4386. (re nothing)
  4387. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4388. (while (> n 1)
  4389. (setq n (1- n)
  4390. re (concat re or next)
  4391. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4392. (concat left "\\(" re "\\)" right)))
  4393. (defconst org-match-substring-regexp
  4394. (concat
  4395. "\\(\\S-\\)\\([_^]\\)\\("
  4396. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4397. "\\|"
  4398. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4399. "\\|"
  4400. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4401. "The regular expression matching a sub- or superscript.")
  4402. (defconst org-match-substring-with-braces-regexp
  4403. (concat
  4404. "\\(\\S-\\)\\([_^]\\)"
  4405. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4406. "The regular expression matching a sub- or superscript, forcing braces.")
  4407. (defvar org-emph-face nil)
  4408. (defun org-do-emphasis-faces (limit)
  4409. "Run through the buffer and emphasize strings."
  4410. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4411. (car org-emphasis-regexp-components))))
  4412. (catch :exit
  4413. (while (re-search-forward quick-re limit t)
  4414. (let* ((marker (match-string 2))
  4415. (verbatim? (member marker '("~" "="))))
  4416. (when (save-excursion
  4417. (goto-char (match-beginning 0))
  4418. (and
  4419. ;; Do not match table hlines.
  4420. (not (and (equal marker "+")
  4421. (org-match-line
  4422. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4423. ;; Do not match headline stars. Do not consider
  4424. ;; stars of a headline as closing marker for bold
  4425. ;; markup either.
  4426. (not (and (equal marker "*")
  4427. (save-excursion
  4428. (forward-char)
  4429. (skip-chars-backward "*")
  4430. (looking-at-p org-outline-regexp-bol))))
  4431. ;; Match full emphasis markup regexp.
  4432. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4433. ;; Do not span over paragraph boundaries.
  4434. (not (string-match-p org-element-paragraph-separate
  4435. (match-string 2)))
  4436. ;; Do not span over cells in table rows.
  4437. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4438. (string-match-p "|" (match-string 4))))))
  4439. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4440. (m (if org-hide-emphasis-markers 4 2)))
  4441. (font-lock-prepend-text-property
  4442. (match-beginning m) (match-end m) 'face face)
  4443. (when verbatim?
  4444. (org-remove-flyspell-overlays-in
  4445. (match-beginning 0) (match-end 0))
  4446. (remove-text-properties (match-beginning 2) (match-end 2)
  4447. '(display t invisible t intangible t)))
  4448. (add-text-properties (match-beginning 2) (match-end 2)
  4449. '(font-lock-multiline t org-emphasis t))
  4450. (when (and org-hide-emphasis-markers
  4451. (not (org-at-comment-p)))
  4452. (add-text-properties (match-end 4) (match-beginning 5)
  4453. '(invisible t))
  4454. (add-text-properties (match-beginning 3) (match-end 3)
  4455. '(invisible t)))
  4456. (throw :exit t))))))))
  4457. (defun org-emphasize (&optional char)
  4458. "Insert or change an emphasis, i.e. a font like bold or italic.
  4459. If there is an active region, change that region to a new emphasis.
  4460. If there is no region, just insert the marker characters and position
  4461. the cursor between them.
  4462. CHAR should be the marker character. If it is a space, it means to
  4463. remove the emphasis of the selected region.
  4464. If CHAR is not given (for example in an interactive call) it will be
  4465. prompted for."
  4466. (interactive)
  4467. (let ((erc org-emphasis-regexp-components)
  4468. (string "") beg end move s)
  4469. (if (org-region-active-p)
  4470. (setq beg (region-beginning)
  4471. end (region-end)
  4472. string (buffer-substring beg end))
  4473. (setq move t))
  4474. (unless char
  4475. (message "Emphasis marker or tag: [%s]"
  4476. (mapconcat #'car org-emphasis-alist ""))
  4477. (setq char (read-char-exclusive)))
  4478. (if (equal char ?\s)
  4479. (setq s ""
  4480. move nil)
  4481. (unless (assoc (char-to-string char) org-emphasis-alist)
  4482. (user-error "No such emphasis marker: \"%c\"" char))
  4483. (setq s (char-to-string char)))
  4484. (while (and (> (length string) 1)
  4485. (equal (substring string 0 1) (substring string -1))
  4486. (assoc (substring string 0 1) org-emphasis-alist))
  4487. (setq string (substring string 1 -1)))
  4488. (setq string (concat s string s))
  4489. (when beg (delete-region beg end))
  4490. (unless (or (bolp)
  4491. (string-match (concat "[" (nth 0 erc) "\n]")
  4492. (char-to-string (char-before (point)))))
  4493. (insert " "))
  4494. (unless (or (eobp)
  4495. (string-match (concat "[" (nth 1 erc) "\n]")
  4496. (char-to-string (char-after (point)))))
  4497. (insert " ") (backward-char 1))
  4498. (insert string)
  4499. (and move (backward-char 1))))
  4500. (defconst org-nonsticky-props
  4501. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4502. (defsubst org-rear-nonsticky-at (pos)
  4503. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4504. (defun org-activate-links (limit)
  4505. "Add link properties to links.
  4506. This includes angle, plain, and bracket links."
  4507. (catch :exit
  4508. (while (re-search-forward org-link-any-re limit t)
  4509. (let* ((start (match-beginning 0))
  4510. (end (match-end 0))
  4511. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4512. (visible-end (or (match-end 3) (match-end 2)))
  4513. (style (cond ((eq ?< (char-after start)) 'angle)
  4514. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4515. (t 'plain))))
  4516. (when (and (memq style org-highlight-links)
  4517. ;; Do not span over paragraph boundaries.
  4518. (not (string-match-p org-element-paragraph-separate
  4519. (match-string 0)))
  4520. ;; Do not confuse plain links with tags.
  4521. (not (and (eq style 'plain)
  4522. (let ((face (get-text-property
  4523. (max (1- start) (point-min)) 'face)))
  4524. (if (consp face) (memq 'org-tag face)
  4525. (eq 'org-tag face))))))
  4526. (let* ((link-object (save-excursion
  4527. (goto-char start)
  4528. (save-match-data (org-element-link-parser))))
  4529. (link (org-element-property :raw-link link-object))
  4530. (type (org-element-property :type link-object))
  4531. (path (org-element-property :path link-object))
  4532. (face-property (pcase (org-link-get-parameter type :face)
  4533. ((and (pred functionp) face) (funcall face path))
  4534. ((and (pred facep) face) face)
  4535. ((and (pred consp) face) face) ;anonymous
  4536. (_ 'org-link)))
  4537. (properties ;for link's visible part
  4538. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4539. 'highlight)
  4540. 'keymap (or (org-link-get-parameter type :keymap)
  4541. org-mouse-map)
  4542. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4543. ((and (pred stringp) echo) echo)
  4544. ((and (pred functionp) echo) echo)
  4545. (_ (concat "LINK: " link)))
  4546. 'htmlize-link (pcase (org-link-get-parameter type
  4547. :htmlize-link)
  4548. ((and (pred functionp) f) (funcall f))
  4549. (_ `(:uri ,link)))
  4550. 'font-lock-multiline t)))
  4551. (org-remove-flyspell-overlays-in start end)
  4552. (org-rear-nonsticky-at end)
  4553. (if (not (eq 'bracket style))
  4554. (progn
  4555. (add-face-text-property start end face-property)
  4556. (add-text-properties start end properties))
  4557. ;; Handle invisible parts in bracket links.
  4558. (remove-text-properties start end '(invisible nil))
  4559. (let ((hidden
  4560. (append `(invisible
  4561. ,(or (org-link-get-parameter type :display)
  4562. 'org-link))
  4563. properties)))
  4564. (add-text-properties start visible-start hidden)
  4565. (add-face-text-property visible-start visible-end face-property)
  4566. (add-text-properties visible-start visible-end properties)
  4567. (add-text-properties visible-end end hidden)
  4568. (org-rear-nonsticky-at visible-start)
  4569. (org-rear-nonsticky-at visible-end)))
  4570. (let ((f (org-link-get-parameter type :activate-func)))
  4571. (when (functionp f)
  4572. (funcall f start end path (eq style 'bracket))))
  4573. (throw :exit t))))) ;signal success
  4574. nil))
  4575. (defun org-activate-code (limit)
  4576. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4577. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4578. (remove-text-properties (match-beginning 0) (match-end 0)
  4579. '(display t invisible t intangible t))
  4580. t))
  4581. (defcustom org-src-fontify-natively t
  4582. "When non-nil, fontify code in code blocks.
  4583. See also the `org-block' face."
  4584. :type 'boolean
  4585. :version "26.1"
  4586. :package-version '(Org . "8.3")
  4587. :group 'org-appearance
  4588. :group 'org-babel)
  4589. (defcustom org-allow-promoting-top-level-subtree nil
  4590. "When non-nil, allow promoting a top level subtree.
  4591. The leading star of the top level headline will be replaced
  4592. by a #."
  4593. :type 'boolean
  4594. :version "24.1"
  4595. :group 'org-appearance)
  4596. (defun org-fontify-meta-lines-and-blocks (limit)
  4597. (condition-case nil
  4598. (org-fontify-meta-lines-and-blocks-1 limit)
  4599. (error (message "Org mode fontification error in %S at %d"
  4600. (current-buffer)
  4601. (line-number-at-pos)))))
  4602. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4603. "Fontify #+ lines and blocks."
  4604. (let ((case-fold-search t))
  4605. (when (re-search-forward
  4606. (rx bol (group (zero-or-more (any " \t")) "#"
  4607. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4608. (any " \t")
  4609. eol))
  4610. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4611. (zero-or-more (any " \t"))
  4612. (group (group (zero-or-more (not (any " \t\n"))))
  4613. (zero-or-more (any " \t"))
  4614. (group (zero-or-more any)))))
  4615. limit t)
  4616. (let ((beg (match-beginning 0))
  4617. (end-of-beginline (match-end 0))
  4618. ;; Including \n at end of #+begin line will include \n
  4619. ;; after the end of block content.
  4620. (block-start (match-end 0))
  4621. (block-end nil)
  4622. (lang (match-string 7)) ; The language, if it is a source block.
  4623. (bol-after-beginline (line-beginning-position 2))
  4624. (dc1 (downcase (match-string 2)))
  4625. (dc3 (downcase (match-string 3)))
  4626. (whole-blockline org-fontify-whole-block-delimiter-line)
  4627. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4628. (cond
  4629. ((and (match-end 4) (equal dc3 "+begin"))
  4630. ;; Truly a block
  4631. (setq block-type (downcase (match-string 5))
  4632. ;; Src, example, export, maybe more.
  4633. quoting (member block-type org-protecting-blocks))
  4634. (when (re-search-forward
  4635. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4636. (seq (zero-or-more (any " \t"))
  4637. "#+end"
  4638. ,(match-string 4)
  4639. word-end
  4640. (zero-or-more any)))))
  4641. ;; We look further than LIMIT on purpose.
  4642. nil t)
  4643. ;; We do have a matching #+end line.
  4644. (setq beg-of-endline (match-beginning 0)
  4645. end-of-endline (match-end 0)
  4646. nl-before-endline (1- (match-beginning 0)))
  4647. (setq block-end (match-beginning 0)) ; Include the final newline.
  4648. (when quoting
  4649. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4650. (remove-text-properties beg end-of-endline
  4651. '(display t invisible t intangible t)))
  4652. (add-text-properties
  4653. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4654. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4655. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4656. (cond
  4657. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4658. (org-src-font-lock-fontify-block lang block-start block-end)
  4659. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4660. (quoting
  4661. (add-text-properties
  4662. bol-after-beginline beg-of-endline
  4663. (list 'face
  4664. (list :inherit
  4665. (let ((face-name
  4666. (intern (format "org-block-%s" lang))))
  4667. (append (and (facep face-name) (list face-name))
  4668. '(org-block)))))))
  4669. ((not org-fontify-quote-and-verse-blocks))
  4670. ((string= block-type "quote")
  4671. (add-face-text-property
  4672. bol-after-beginline beg-of-endline 'org-quote t))
  4673. ((string= block-type "verse")
  4674. (add-face-text-property
  4675. bol-after-beginline beg-of-endline 'org-verse t)))
  4676. ;; Fontify the #+begin and #+end lines of the blocks
  4677. (add-text-properties
  4678. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4679. '(face org-block-begin-line))
  4680. (unless (eq (char-after beg-of-endline) ?*)
  4681. (add-text-properties
  4682. beg-of-endline
  4683. (if whole-blockline
  4684. (let ((beg-of-next-line (1+ end-of-endline)))
  4685. (min (point-max) beg-of-next-line))
  4686. (min (point-max) end-of-endline))
  4687. '(face org-block-end-line)))
  4688. t))
  4689. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4690. (org-remove-flyspell-overlays-in
  4691. (match-beginning 0)
  4692. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4693. (add-text-properties
  4694. beg (match-end 3)
  4695. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4696. '(font-lock-fontified t invisible t)
  4697. '(font-lock-fontified t face org-document-info-keyword)))
  4698. (add-text-properties
  4699. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4700. (if (string-equal dc1 "+title:")
  4701. '(font-lock-fontified t face org-document-title)
  4702. '(font-lock-fontified t face org-document-info))))
  4703. ((string-prefix-p "+caption" dc1)
  4704. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4705. (remove-text-properties (match-beginning 0) (match-end 0)
  4706. '(display t invisible t intangible t))
  4707. ;; Handle short captions
  4708. (save-excursion
  4709. (beginning-of-line)
  4710. (looking-at (rx (group (zero-or-more (any " \t"))
  4711. "#+caption"
  4712. (optional "[" (zero-or-more any) "]")
  4713. ":")
  4714. (zero-or-more (any " \t")))))
  4715. (add-text-properties (line-beginning-position) (match-end 1)
  4716. '(font-lock-fontified t face org-meta-line))
  4717. (add-text-properties (match-end 0) (line-end-position)
  4718. '(font-lock-fontified t face org-block))
  4719. t)
  4720. ((member dc3 '(" " ""))
  4721. ;; Just a comment, the plus was not there
  4722. (org-remove-flyspell-overlays-in beg (match-end 0))
  4723. (add-text-properties
  4724. beg (match-end 0)
  4725. '(font-lock-fontified t face font-lock-comment-face)))
  4726. (t ;; Just any other in-buffer setting, but not indented
  4727. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4728. (remove-text-properties (match-beginning 0) (match-end 0)
  4729. '(display t invisible t intangible t))
  4730. (add-text-properties beg (match-end 0)
  4731. '(font-lock-fontified t face org-meta-line))
  4732. t))))))
  4733. (defun org-fontify-drawers (limit)
  4734. "Fontify drawers."
  4735. (when (re-search-forward org-drawer-regexp limit t)
  4736. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4737. '(font-lock-fontified t face org-drawer))
  4738. (org-remove-flyspell-overlays-in
  4739. (line-beginning-position) (line-beginning-position 2))
  4740. t))
  4741. (defun org-fontify-macros (limit)
  4742. "Fontify macros."
  4743. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4744. (let ((begin (match-beginning 0))
  4745. (opening-end (match-beginning 1)))
  4746. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4747. (match-string 1))
  4748. (let ((end (match-end 1))
  4749. (closing-start (match-beginning 1)))
  4750. (add-text-properties
  4751. begin end
  4752. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4753. (org-remove-flyspell-overlays-in begin end)
  4754. (when org-hide-macro-markers
  4755. (add-text-properties begin opening-end '(invisible t))
  4756. (add-text-properties closing-start end '(invisible t)))
  4757. t)))))
  4758. (defun org-fontify-extend-region (beg end _old-len)
  4759. (let ((begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4760. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4761. (extend (lambda (r1 r2 dir)
  4762. (let ((re (replace-regexp-in-string "\\(begin\\|end\\)" r1
  4763. (replace-regexp-in-string "[][]" r2
  4764. (match-string-no-properties 0)))))
  4765. (re-search-forward (regexp-quote re) nil t dir)))))
  4766. (save-match-data
  4767. (save-excursion
  4768. (goto-char beg)
  4769. (back-to-indentation)
  4770. (cond ((looking-at end-re)
  4771. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4772. ((looking-at begin-re)
  4773. (cons beg (or (funcall extend "end" "]" 1) end)))
  4774. (t (cons beg end)))))))
  4775. (defun org-activate-footnote-links (limit)
  4776. "Add text properties for footnotes."
  4777. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4778. (when fn
  4779. (let* ((beg (nth 1 fn))
  4780. (end (nth 2 fn))
  4781. (label (car fn))
  4782. (referencep (/= (line-beginning-position) beg)))
  4783. (when (and referencep (nth 3 fn))
  4784. (save-excursion
  4785. (goto-char beg)
  4786. (search-forward (or label "fn:"))
  4787. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4788. (add-text-properties beg end
  4789. (list 'mouse-face 'highlight
  4790. 'keymap org-mouse-map
  4791. 'help-echo
  4792. (if referencep "Footnote reference"
  4793. "Footnote definition")
  4794. 'font-lock-fontified t
  4795. 'font-lock-multiline t
  4796. 'face 'org-footnote))))))
  4797. (defun org-activate-dates (limit)
  4798. "Add text properties for dates."
  4799. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4800. (not (equal (char-before (match-beginning 0)) 91)))
  4801. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4802. (add-text-properties (match-beginning 0) (match-end 0)
  4803. (list 'mouse-face 'highlight
  4804. 'keymap org-mouse-map))
  4805. (org-rear-nonsticky-at (match-end 0))
  4806. (when org-display-custom-times
  4807. ;; If it's a date range, activate custom time for second date.
  4808. (when (match-end 3)
  4809. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4810. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4811. t))
  4812. (defun org-activate-target-links (limit)
  4813. "Add text properties for target matches."
  4814. (when org-target-link-regexp
  4815. (let ((case-fold-search t))
  4816. ;; `org-target-link-regexp' matches one character before the
  4817. ;; actual target.
  4818. (unless (bolp) (forward-char -1))
  4819. (when (re-search-forward org-target-link-regexp limit t)
  4820. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4821. (add-text-properties (match-beginning 1) (match-end 1)
  4822. (list 'mouse-face 'highlight
  4823. 'keymap org-mouse-map
  4824. 'help-echo "Radio target link"
  4825. 'org-linked-text t))
  4826. (org-rear-nonsticky-at (match-end 1))
  4827. t))))
  4828. (defvar org-latex-and-related-regexp nil
  4829. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4830. (defun org-compute-latex-and-related-regexp ()
  4831. "Compute regular expression for LaTeX, entities and sub/superscript.
  4832. Result depends on variable `org-highlight-latex-and-related'."
  4833. (let ((re-sub
  4834. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4835. ((eq org-use-sub-superscripts '{})
  4836. (list org-match-substring-with-braces-regexp))
  4837. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4838. (re-latex
  4839. (when (or (memq 'latex org-highlight-latex-and-related)
  4840. (memq 'native org-highlight-latex-and-related))
  4841. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4842. (delq nil
  4843. (mapcar (lambda (x)
  4844. (and (member (car x) matchers) (nth 1 x)))
  4845. org-latex-regexps)))))
  4846. (re-entities
  4847. (when (memq 'entities org-highlight-latex-and-related)
  4848. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4849. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4850. (setq-local org-latex-and-related-regexp
  4851. (mapconcat #'identity
  4852. (append re-latex re-entities re-sub)
  4853. "\\|"))))
  4854. (defun org-do-latex-and-related (limit)
  4855. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4856. Stop at first highlighted object, if any. Return t if some
  4857. highlighting was done, nil otherwise."
  4858. (when (org-string-nw-p org-latex-and-related-regexp)
  4859. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4860. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4861. (catch 'found
  4862. (while (and (< (point) limit)
  4863. (re-search-forward org-latex-and-related-regexp nil t))
  4864. (cond
  4865. ((>= (match-beginning 0) limit)
  4866. (throw 'found nil))
  4867. ((cl-some (lambda (f)
  4868. (memq f '(org-code org-verbatim underline
  4869. org-special-keyword)))
  4870. (save-excursion
  4871. (goto-char (1+ (match-beginning 0)))
  4872. (face-at-point nil t))))
  4873. ;; Try to limit false positives. In this case, ignore
  4874. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4875. ;; contain an empty line.
  4876. ((save-excursion
  4877. (goto-char (match-beginning 0))
  4878. (and (looking-at-p latex-prefix-re)
  4879. (save-match-data
  4880. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4881. (t
  4882. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4883. '(?_ ?^))
  4884. 1
  4885. 0))
  4886. (start (+ offset (match-beginning 0)))
  4887. (end (match-end 0)))
  4888. (if (memq 'native org-highlight-latex-and-related)
  4889. (org-src-font-lock-fontify-block "latex" start end)
  4890. (font-lock-prepend-text-property start end
  4891. 'face 'org-latex-and-related))
  4892. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4893. '(font-lock-multiline t))
  4894. (throw 'found t)))))
  4895. nil))))
  4896. (defun org-restart-font-lock ()
  4897. "Restart `font-lock-mode', to force refontification."
  4898. (when font-lock-mode
  4899. (font-lock-mode -1)
  4900. (font-lock-mode 1)))
  4901. (defun org-activate-tags (limit)
  4902. (when (re-search-forward org-tag-line-re limit t)
  4903. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4904. (add-text-properties (match-beginning 1) (match-end 1)
  4905. (list 'mouse-face 'highlight
  4906. 'keymap org-mouse-map))
  4907. (org-rear-nonsticky-at (match-end 1))
  4908. t))
  4909. (defun org-outline-level ()
  4910. "Compute the outline level of the heading at point.
  4911. If this is called at a normal headline, the level is the number
  4912. of stars. Use `org-reduced-level' to remove the effect of
  4913. `org-odd-levels'. Unlike to `org-current-level', this function
  4914. takes into consideration inlinetasks."
  4915. (org-with-wide-buffer
  4916. (end-of-line)
  4917. (if (re-search-backward org-outline-regexp-bol nil t)
  4918. (1- (- (match-end 0) (match-beginning 0)))
  4919. 0)))
  4920. (defvar org-font-lock-keywords nil)
  4921. (defsubst org-re-property (property &optional literal allow-null value)
  4922. "Return a regexp matching a PROPERTY line.
  4923. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4924. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4925. non-nil, match properties even without a value.
  4926. Match group 3 is set to the value when it exists. If there is no
  4927. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4928. With optional argument VALUE, match only property lines with
  4929. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4930. unless LITERAL is non-nil."
  4931. (concat
  4932. "^\\(?4:[ \t]*\\)"
  4933. (format "\\(?1::\\(?2:%s\\):\\)"
  4934. (if literal property (regexp-quote property)))
  4935. (cond (value
  4936. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4937. (if literal value (regexp-quote value))))
  4938. (allow-null
  4939. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4940. (t
  4941. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4942. (defconst org-property-re
  4943. (org-re-property "\\S-+" 'literal t)
  4944. "Regular expression matching a property line.
  4945. There are four matching groups:
  4946. 1: :PROPKEY: including the leading and trailing colon,
  4947. 2: PROPKEY without the leading and trailing colon,
  4948. 3: PROPVAL without leading or trailing spaces,
  4949. 4: the indentation of the current line,
  4950. 5: trailing whitespace.")
  4951. (defvar org-font-lock-hook nil
  4952. "Functions to be called for special font lock stuff.")
  4953. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4954. (defvar org-font-lock-set-keywords-hook nil
  4955. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4956. This is called after `org-font-lock-extra-keywords' is defined, but before
  4957. it is installed to be used by font lock. This can be useful if something
  4958. needs to be inserted at a specific position in the font-lock sequence.")
  4959. (defun org-font-lock-hook (limit)
  4960. "Run `org-font-lock-hook' within LIMIT."
  4961. (run-hook-with-args 'org-font-lock-hook limit))
  4962. (defun org-set-font-lock-defaults ()
  4963. "Set font lock defaults for the current buffer."
  4964. (let ((org-font-lock-extra-keywords
  4965. (list
  4966. ;; Call the hook
  4967. '(org-font-lock-hook)
  4968. ;; Headlines
  4969. `(,(if org-fontify-whole-heading-line
  4970. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4971. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4972. (1 (org-get-level-face 1))
  4973. (2 (org-get-level-face 2))
  4974. (3 (org-get-level-face 3)))
  4975. ;; Table lines
  4976. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4977. (1 'org-table t))
  4978. ;; Table internals
  4979. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4980. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4981. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4982. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4983. ;; Properties
  4984. (list org-property-re
  4985. '(1 'org-special-keyword t)
  4986. '(3 'org-property-value t))
  4987. ;; Drawers
  4988. '(org-fontify-drawers)
  4989. ;; Link related fontification.
  4990. '(org-activate-links)
  4991. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  4992. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  4993. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  4994. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  4995. ;; Targets.
  4996. (list org-radio-target-regexp '(0 'org-target t))
  4997. (list org-target-regexp '(0 'org-target t))
  4998. ;; Diary sexps.
  4999. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5000. ;; Macro
  5001. '(org-fontify-macros)
  5002. ;; TODO keyword
  5003. (list (format org-heading-keyword-regexp-format
  5004. org-todo-regexp)
  5005. '(2 (org-get-todo-face 2) prepend))
  5006. ;; TODO
  5007. (when org-fontify-todo-headline
  5008. (list (format org-heading-keyword-regexp-format
  5009. (concat
  5010. "\\(?:"
  5011. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5012. "\\)"))
  5013. '(2 'org-headline-todo prepend)))
  5014. ;; DONE
  5015. (when org-fontify-done-headline
  5016. (list (format org-heading-keyword-regexp-format
  5017. (concat
  5018. "\\(?:"
  5019. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5020. "\\)"))
  5021. '(2 'org-headline-done prepend)))
  5022. ;; Priorities
  5023. '(org-font-lock-add-priority-faces)
  5024. ;; Tags
  5025. '(org-font-lock-add-tag-faces)
  5026. ;; Tags groups
  5027. (when (and org-group-tags org-tag-groups-alist)
  5028. (list (concat org-outline-regexp-bol ".+\\(:"
  5029. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5030. ":\\).*$")
  5031. '(1 'org-tag-group prepend)))
  5032. ;; Special keywords
  5033. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5034. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5035. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5036. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5037. ;; Emphasis
  5038. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5039. ;; Checkboxes
  5040. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5041. 1 'org-checkbox prepend)
  5042. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5043. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5044. (0 (org-get-checkbox-statistics-face) prepend)))
  5045. ;; Description list items
  5046. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5047. 1 'org-list-dt prepend)
  5048. ;; Inline export snippets
  5049. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5050. (1 'font-lock-comment-face t)
  5051. (2 'org-tag t)
  5052. (3 'font-lock-comment-face t))
  5053. ;; ARCHIVEd headings
  5054. (list (concat
  5055. org-outline-regexp-bol
  5056. "\\(.*:" org-archive-tag ":.*\\)")
  5057. '(1 'org-archived prepend))
  5058. ;; Specials
  5059. '(org-do-latex-and-related)
  5060. '(org-fontify-entities)
  5061. '(org-raise-scripts)
  5062. ;; Code
  5063. '(org-activate-code (1 'org-code t))
  5064. ;; COMMENT
  5065. (list (format
  5066. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5067. org-todo-regexp
  5068. org-comment-string)
  5069. '(9 'org-special-keyword t))
  5070. ;; Blocks and meta lines
  5071. '(org-fontify-meta-lines-and-blocks))))
  5072. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5073. (run-hooks 'org-font-lock-set-keywords-hook)
  5074. ;; Now set the full font-lock-keywords
  5075. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5076. (setq-local font-lock-defaults
  5077. '(org-font-lock-keywords t nil nil backward-paragraph))
  5078. (setq-local font-lock-extend-after-change-region-function
  5079. #'org-fontify-extend-region)
  5080. (kill-local-variable 'font-lock-keywords)
  5081. nil))
  5082. (defun org-toggle-pretty-entities ()
  5083. "Toggle the composition display of entities as UTF8 characters."
  5084. (interactive)
  5085. (setq-local org-pretty-entities (not org-pretty-entities))
  5086. (org-restart-font-lock)
  5087. (if org-pretty-entities
  5088. (message "Entities are now displayed as UTF8 characters")
  5089. (save-restriction
  5090. (widen)
  5091. (decompose-region (point-min) (point-max))
  5092. (message "Entities are now displayed as plain text"))))
  5093. (defvar-local org-custom-properties-overlays nil
  5094. "List of overlays used for custom properties.")
  5095. (defun org-toggle-custom-properties-visibility ()
  5096. "Display or hide properties in `org-custom-properties'."
  5097. (interactive)
  5098. (if org-custom-properties-overlays
  5099. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5100. (setq org-custom-properties-overlays nil))
  5101. (when org-custom-properties
  5102. (org-with-wide-buffer
  5103. (goto-char (point-min))
  5104. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5105. (while (re-search-forward regexp nil t)
  5106. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5107. (when (and end (< (point) end))
  5108. ;; Hide first custom property in current drawer.
  5109. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5110. (overlay-put o 'invisible t)
  5111. (overlay-put o 'org-custom-property t)
  5112. (push o org-custom-properties-overlays))
  5113. ;; Hide additional custom properties in the same drawer.
  5114. (while (re-search-forward regexp end t)
  5115. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5116. (overlay-put o 'invisible t)
  5117. (overlay-put o 'org-custom-property t)
  5118. (push o org-custom-properties-overlays)))))
  5119. ;; Each entry is limited to a single property drawer.
  5120. (outline-next-heading)))))))
  5121. (defun org-fontify-entities (limit)
  5122. "Find an entity to fontify."
  5123. (let (ee)
  5124. (when org-pretty-entities
  5125. (catch 'match
  5126. ;; "\_ "-family is left out on purpose. Only the first one,
  5127. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5128. ;; confusing when adding a second white space character.
  5129. (while (re-search-forward
  5130. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5131. limit t)
  5132. (when (and (not (org-at-comment-p))
  5133. (setq ee (org-entity-get (match-string 1)))
  5134. (= (length (nth 6 ee)) 1))
  5135. (let* ((end (if (equal (match-string 2) "{}")
  5136. (match-end 2)
  5137. (match-end 1))))
  5138. (add-text-properties
  5139. (match-beginning 0) end
  5140. (list 'font-lock-fontified t))
  5141. (compose-region (match-beginning 0) end
  5142. (nth 6 ee) nil)
  5143. (backward-char 1)
  5144. (throw 'match t))))
  5145. nil))))
  5146. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5147. "Fontify string S like in Org mode."
  5148. (with-temp-buffer
  5149. (insert s)
  5150. (let ((org-odd-levels-only odd-levels))
  5151. (org-mode)
  5152. (org-font-lock-ensure)
  5153. (buffer-string))))
  5154. (defun org-get-level-face (n)
  5155. "Get the right face for match N in font-lock matching of headlines."
  5156. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5157. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5158. (org-f (if org-cycle-level-faces
  5159. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5160. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5161. (cond
  5162. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5163. ((eq n 2) org-f)
  5164. (t (unless org-level-color-stars-only org-f)))))
  5165. (defun org-face-from-face-or-color (context inherit face-or-color)
  5166. "Create a face list that inherits INHERIT, but sets the foreground color.
  5167. When FACE-OR-COLOR is not a string, just return it."
  5168. (if (stringp face-or-color)
  5169. (list :inherit inherit
  5170. (cdr (assoc context org-faces-easy-properties))
  5171. face-or-color)
  5172. face-or-color))
  5173. (defun org-get-todo-face (kwd)
  5174. "Get the right face for a TODO keyword KWD.
  5175. If KWD is a number, get the corresponding match group."
  5176. (when (numberp kwd) (setq kwd (match-string kwd)))
  5177. (or (org-face-from-face-or-color
  5178. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5179. (and (member kwd org-done-keywords) 'org-done)
  5180. 'org-todo))
  5181. (defun org-get-priority-face (priority)
  5182. "Get the right face for PRIORITY.
  5183. PRIORITY is a character."
  5184. (or (org-face-from-face-or-color
  5185. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5186. 'org-priority))
  5187. (defun org-get-tag-face (tag)
  5188. "Get the right face for TAG.
  5189. If TAG is a number, get the corresponding match group."
  5190. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5191. (or (org-face-from-face-or-color
  5192. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5193. 'org-tag)))
  5194. (defvar org-priority-regexp) ; defined later in the file
  5195. (defun org-font-lock-add-priority-faces (limit)
  5196. "Add the special priority faces."
  5197. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5198. (let ((beg (match-beginning 1))
  5199. (end (1+ (match-end 2))))
  5200. (add-face-text-property
  5201. beg end
  5202. (org-get-priority-face (string-to-char (match-string 2))))
  5203. (add-text-properties
  5204. beg end
  5205. (list 'font-lock-fontified t)))))
  5206. (defun org-font-lock-add-tag-faces (limit)
  5207. "Add the special tag faces."
  5208. (when (and org-tag-faces org-tags-special-faces-re)
  5209. (while (re-search-forward org-tags-special-faces-re limit t)
  5210. (add-face-text-property
  5211. (match-beginning 1)
  5212. (match-end 1)
  5213. (org-get-tag-face 1))
  5214. (add-text-properties (match-beginning 1) (match-end 1)
  5215. (list 'font-lock-fontified t))
  5216. (backward-char 1))))
  5217. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5218. "Remove fontification and activation overlays from links."
  5219. (font-lock-default-unfontify-region beg end)
  5220. (let* ((buffer-undo-list t)
  5221. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5222. (inhibit-modification-hooks t)
  5223. deactivate-mark buffer-file-name buffer-file-truename)
  5224. (decompose-region beg end)
  5225. (remove-text-properties beg end
  5226. '(mouse-face t keymap t org-linked-text t
  5227. invisible t intangible t
  5228. org-emphasis t))
  5229. (org-remove-font-lock-display-properties beg end)))
  5230. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5231. ((raise 0.3) (height 0.7))
  5232. ((raise -0.5))
  5233. ((raise 0.5)))
  5234. "Display properties for showing superscripts and subscripts.")
  5235. (defun org-remove-font-lock-display-properties (beg end)
  5236. "Remove specific display properties that have been added by font lock.
  5237. The will remove the raise properties that are used to show superscripts
  5238. and subscripts."
  5239. (let (next prop)
  5240. (while (< beg end)
  5241. (setq next (next-single-property-change beg 'display nil end)
  5242. prop (get-text-property beg 'display))
  5243. (when (member prop org-script-display)
  5244. (put-text-property beg next 'display nil))
  5245. (setq beg next))))
  5246. (defun org-raise-scripts (limit)
  5247. "Add raise properties to sub/superscripts."
  5248. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5249. (re-search-forward
  5250. (if (eq org-use-sub-superscripts t)
  5251. org-match-substring-regexp
  5252. org-match-substring-with-braces-regexp)
  5253. limit t))
  5254. (let* ((pos (point)) table-p comment-p
  5255. (mpos (match-beginning 3))
  5256. (emph-p (get-text-property mpos 'org-emphasis))
  5257. (link-p (get-text-property mpos 'mouse-face))
  5258. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5259. (goto-char (point-at-bol))
  5260. (setq table-p (looking-at-p org-table-dataline-regexp)
  5261. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5262. (goto-char pos)
  5263. ;; Handle a_b^c
  5264. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5265. (unless (or comment-p emph-p link-p keyw-p)
  5266. (put-text-property (match-beginning 3) (match-end 0)
  5267. 'display
  5268. (if (equal (char-after (match-beginning 2)) ?^)
  5269. (nth (if table-p 3 1) org-script-display)
  5270. (nth (if table-p 2 0) org-script-display)))
  5271. (add-text-properties (match-beginning 2) (match-end 2)
  5272. (list 'invisible t))
  5273. (when (and (eq (char-after (match-beginning 3)) ?{)
  5274. (eq (char-before (match-end 3)) ?}))
  5275. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5276. (list 'invisible t))
  5277. (add-text-properties (1- (match-end 3)) (match-end 3)
  5278. (list 'invisible t))))
  5279. t)))
  5280. (defun org-remove-empty-overlays-at (pos)
  5281. "Remove outline overlays that do not contain non-white stuff."
  5282. (dolist (o (overlays-at pos))
  5283. (and (eq 'outline (overlay-get o 'invisible))
  5284. (not (string-match-p "\\S-" (buffer-substring (overlay-start o)
  5285. (overlay-end o))))
  5286. (delete-overlay o))))
  5287. (defun org-show-empty-lines-in-parent ()
  5288. "Move to the parent and re-show empty lines before visible headlines."
  5289. (save-excursion
  5290. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5291. (org-cycle-show-empty-lines context))))
  5292. (defun org-files-list ()
  5293. "Return `org-agenda-files' list, plus all open Org files.
  5294. This is useful for operations that need to scan all of a user's
  5295. open and agenda-wise Org files."
  5296. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5297. (dolist (buf (buffer-list))
  5298. (with-current-buffer buf
  5299. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5300. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5301. :test #'equal))))
  5302. files))
  5303. (defsubst org-entry-beginning-position ()
  5304. "Return the beginning position of the current entry."
  5305. (save-excursion (org-back-to-heading t) (point)))
  5306. (defsubst org-entry-end-position ()
  5307. "Return the end position of the current entry."
  5308. (save-excursion (outline-next-heading) (point)))
  5309. (defun org-subtree-end-visible-p ()
  5310. "Is the end of the current subtree visible?"
  5311. (pos-visible-in-window-p
  5312. (save-excursion (org-end-of-subtree t) (point))))
  5313. (defun org-first-headline-recenter ()
  5314. "Move cursor to the first headline and recenter the headline."
  5315. (let ((window (get-buffer-window)))
  5316. (when window
  5317. (goto-char (point-min))
  5318. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5319. (set-window-start window (line-beginning-position))))))
  5320. ;;; Visibility (headlines, blocks, drawers)
  5321. ;;;; Headlines visibility
  5322. (defun org-show-entry ()
  5323. "Show the body directly following its heading.
  5324. Show the heading too, if it is currently invisible."
  5325. (interactive)
  5326. (save-excursion
  5327. (org-back-to-heading-or-point-min t)
  5328. (org-flag-region
  5329. (line-end-position 0)
  5330. (save-excursion
  5331. (if (re-search-forward
  5332. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5333. (match-beginning 1)
  5334. (point-max)))
  5335. nil
  5336. 'outline)
  5337. (org-cycle-hide-drawers 'children)))
  5338. (defun org-hide-entry ()
  5339. "Hide the body directly following its heading."
  5340. (interactive)
  5341. (save-excursion
  5342. (org-back-to-heading-or-point-min t)
  5343. (when (org-at-heading-p) (forward-line))
  5344. (org-flag-region
  5345. (line-end-position 0)
  5346. (save-excursion
  5347. (if (re-search-forward
  5348. (concat "[\r\n]" org-outline-regexp) nil t)
  5349. (line-end-position 0)
  5350. (point-max)))
  5351. t
  5352. 'outline)))
  5353. (defun org-show-children (&optional level)
  5354. "Show all direct subheadings of this heading.
  5355. Prefix arg LEVEL is how many levels below the current level
  5356. should be shown. Default is enough to cause the following
  5357. heading to appear."
  5358. (interactive "p")
  5359. (unless (org-before-first-heading-p)
  5360. (save-excursion
  5361. (org-with-limited-levels (org-back-to-heading t))
  5362. (let* ((current-level (funcall outline-level))
  5363. (max-level (org-get-valid-level
  5364. current-level
  5365. (if level (prefix-numeric-value level) 1)))
  5366. (end (save-excursion (org-end-of-subtree t t)))
  5367. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5368. (past-first-child nil)
  5369. ;; Make sure to skip inlinetasks.
  5370. (re (format regexp-fmt
  5371. current-level
  5372. (cond
  5373. ((not (featurep 'org-inlinetask)) "")
  5374. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5375. 3))
  5376. (t (1- org-inlinetask-min-level))))))
  5377. ;; Display parent heading.
  5378. (org-flag-heading nil)
  5379. (forward-line)
  5380. ;; Display children. First child may be deeper than expected
  5381. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5382. ;; MAX-LEVEL accordingly.
  5383. (while (re-search-forward re end t)
  5384. (unless past-first-child
  5385. (setq re (format regexp-fmt
  5386. current-level
  5387. (max (funcall outline-level) max-level)))
  5388. (setq past-first-child t))
  5389. (org-flag-heading nil))))))
  5390. (defun org-show-subtree ()
  5391. "Show everything after this heading at deeper levels."
  5392. (interactive)
  5393. (org-flag-region
  5394. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5395. ;;;; Blocks and drawers visibility
  5396. (defun org--hide-wrapper-toggle (element category force no-error)
  5397. "Toggle visibility for ELEMENT.
  5398. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5399. either `block' or `drawer'. When FORCE is `off', show the block
  5400. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5401. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5402. Return a non-nil value when toggling is successful."
  5403. (let ((type (org-element-type element)))
  5404. (cond
  5405. ((memq type
  5406. (pcase category
  5407. (`drawer '(drawer property-drawer))
  5408. (`block '(center-block
  5409. comment-block dynamic-block example-block export-block
  5410. quote-block special-block src-block verse-block))
  5411. (_ (error "Unknown category: %S" category))))
  5412. (let* ((post (org-element-property :post-affiliated element))
  5413. (start (save-excursion
  5414. (goto-char post)
  5415. (line-end-position)))
  5416. (end (save-excursion
  5417. (goto-char (org-element-property :end element))
  5418. (skip-chars-backward " \t\n")
  5419. (line-end-position))))
  5420. ;; Do nothing when not before or at the block opening line or
  5421. ;; at the block closing line.
  5422. (unless (let ((eol (line-end-position)))
  5423. (and (> eol start) (/= eol end)))
  5424. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5425. (flag
  5426. (cond ((eq force 'off) nil)
  5427. (force t)
  5428. ((eq spec (get-char-property start 'invisible)) nil)
  5429. (t t))))
  5430. (org-flag-region start end flag spec))
  5431. ;; When the block is hidden away, make sure point is left in
  5432. ;; a visible part of the buffer.
  5433. (when (invisible-p (max (1- (point)) (point-min)))
  5434. (goto-char post))
  5435. ;; Signal success.
  5436. t)))
  5437. (no-error nil)
  5438. (t
  5439. (user-error (if (eq category 'drawer)
  5440. "Not at a drawer"
  5441. "Not at a block"))))))
  5442. (defun org-hide-block-toggle (&optional force no-error element)
  5443. "Toggle the visibility of the current block.
  5444. When optional argument FORCE is `off', make block visible. If it
  5445. is non-nil, hide it unconditionally. Throw an error when not at
  5446. a block, unless NO-ERROR is non-nil. When optional argument
  5447. ELEMENT is provided, consider it instead of the current block.
  5448. Return a non-nil value when toggling is successful."
  5449. (interactive)
  5450. (org--hide-wrapper-toggle
  5451. (or element (org-element-at-point)) 'block force no-error))
  5452. (defun org-hide-drawer-toggle (&optional force no-error element)
  5453. "Toggle the visibility of the current drawer.
  5454. When optional argument FORCE is `off', make drawer visible. If
  5455. it is non-nil, hide it unconditionally. Throw an error when not
  5456. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5457. ELEMENT is provided, consider it instead of the current drawer.
  5458. Return a non-nil value when toggling is successful."
  5459. (interactive)
  5460. (org--hide-wrapper-toggle
  5461. (or element (org-element-at-point)) 'drawer force no-error))
  5462. (defun org-hide-block-all ()
  5463. "Fold all blocks in the current buffer."
  5464. (interactive)
  5465. (org-show-all '(blocks))
  5466. (org-block-map 'org-hide-block-toggle))
  5467. (defun org-hide-drawer-all ()
  5468. "Fold all drawers in the current buffer."
  5469. (let ((begin (point-min))
  5470. (end (point-max)))
  5471. (org--hide-drawers begin end)))
  5472. (defun org-cycle-hide-drawers (state)
  5473. "Re-hide all drawers after a visibility state change.
  5474. STATE should be one of the symbols listed in the docstring of
  5475. `org-cycle-hook'."
  5476. (when (derived-mode-p 'org-mode)
  5477. (cond ((not (memq state '(overview folded contents)))
  5478. (let* ((global? (eq state 'all))
  5479. (beg (if global? (point-min) (line-beginning-position)))
  5480. (end (cond (global? (point-max))
  5481. ((eq state 'children) (org-entry-end-position))
  5482. (t (save-excursion (org-end-of-subtree t t))))))
  5483. (org--hide-drawers beg end)))
  5484. ((memq state '(overview contents))
  5485. ;; Hide drawers before first heading.
  5486. (let ((beg (point-min))
  5487. (end (save-excursion
  5488. (goto-char (point-min))
  5489. (if (org-before-first-heading-p)
  5490. (org-entry-end-position)
  5491. (point-min)))))
  5492. (when (< beg end)
  5493. (org--hide-drawers beg end)))))))
  5494. (defun org--hide-drawers (begin end)
  5495. "Hide all drawers between BEGIN and END."
  5496. (save-excursion
  5497. (goto-char begin)
  5498. (while (re-search-forward org-drawer-regexp end t)
  5499. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5500. 'invisible))
  5501. (o (cdr-safe pair)))
  5502. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5503. (pcase (get-char-property-and-overlay (point) 'invisible)
  5504. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5505. (_
  5506. (let* ((drawer (org-element-at-point))
  5507. (type (org-element-type drawer)))
  5508. (when (memq type '(drawer property-drawer))
  5509. (org-hide-drawer-toggle t nil drawer)
  5510. ;; Make sure to skip drawer entirely or we might flag it
  5511. ;; another time when matching its ending line with
  5512. ;; `org-drawer-regexp'.
  5513. (goto-char (org-element-property :end drawer)))))))))))
  5514. ;;;; Visibility cycling
  5515. (defvar-local org-cycle-global-status nil)
  5516. (put 'org-cycle-global-status 'org-state t)
  5517. (defvar-local org-cycle-subtree-status nil)
  5518. (put 'org-cycle-subtree-status 'org-state t)
  5519. (defun org-show-all (&optional types)
  5520. "Show all contents in the visible part of the buffer.
  5521. By default, the function expands headings, blocks and drawers.
  5522. When optional argument TYPE is a list of symbols among `blocks',
  5523. `drawers' and `headings', to only expand one specific type."
  5524. (interactive)
  5525. (let ((types (or types '(blocks drawers headings))))
  5526. (when (memq 'blocks types)
  5527. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5528. (cond
  5529. ;; Fast path. Since headings and drawers share the same
  5530. ;; invisible spec, clear everything in one go.
  5531. ((and (memq 'headings types)
  5532. (memq 'drawers types))
  5533. (org-flag-region (point-min) (point-max) nil 'outline))
  5534. ((memq 'headings types)
  5535. (org-flag-region (point-min) (point-max) nil 'outline)
  5536. (org-cycle-hide-drawers 'all))
  5537. ((memq 'drawers types)
  5538. (save-excursion
  5539. (goto-char (point-min))
  5540. (while (re-search-forward org-drawer-regexp nil t)
  5541. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5542. 'invisible))
  5543. (o (cdr-safe pair)))
  5544. (if (overlayp o) (goto-char (overlay-end o))
  5545. (pcase (get-char-property-and-overlay (point) 'invisible)
  5546. (`(outline . ,o)
  5547. (goto-char (overlay-end o))
  5548. (delete-overlay o))
  5549. (_ nil))))))))))
  5550. ;;;###autoload
  5551. (defun org-cycle (&optional arg)
  5552. "TAB-action and visibility cycling for Org mode.
  5553. This is the command invoked in Org mode by the `TAB' key. Its main
  5554. purpose is outline visibility cycling, but it also invokes other actions
  5555. in special contexts.
  5556. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5557. the entire
  5558. buffer through 3 states (global cycling)
  5559. 1. OVERVIEW: Show only top-level headlines.
  5560. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5561. 3. SHOW ALL: Show everything.
  5562. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5563. switch to the startup visibility,
  5564. determined by the variable `org-startup-folded', and by any VISIBILITY
  5565. properties in the buffer.
  5566. With a `\\[universal-argument] \\[universal-argument] \
  5567. \\[universal-argument]' prefix argument, show the entire buffer, including
  5568. any drawers.
  5569. When inside a table, re-align the table and move to the next field.
  5570. When point is at the beginning of a headline, rotate the subtree started
  5571. by this line through 3 different states (local cycling)
  5572. 1. FOLDED: Only the main headline is shown.
  5573. 2. CHILDREN: The main headline and the direct children are shown.
  5574. From this state, you can move to one of the children
  5575. and zoom in further.
  5576. 3. SUBTREE: Show the entire subtree, including body text.
  5577. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5578. When point is at the beginning of an empty headline and the variable
  5579. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5580. of the headline by demoting and promoting it to likely levels. This
  5581. speeds up creation document structure by pressing `TAB' once or several
  5582. times right after creating a new headline.
  5583. When there is a numeric prefix, go up to a heading with level ARG, do
  5584. a `show-subtree' and return to the previous cursor position. If ARG
  5585. is negative, go up that many levels.
  5586. When point is not at the beginning of a headline, execute the global
  5587. binding for `TAB', which is re-indenting the line. See the option
  5588. `org-cycle-emulate-tab' for details.
  5589. As a special case, if point is at the very beginning of the buffer, if
  5590. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5591. is non-nil, this function acts as if called with prefix argument \
  5592. \(`\\[universal-argument] TAB',
  5593. same as `S-TAB') also when called without prefix argument."
  5594. (interactive "P")
  5595. (org-load-modules-maybe)
  5596. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5597. (and org-cycle-level-after-item/entry-creation
  5598. (or (org-cycle-level)
  5599. (org-cycle-item-indentation))))
  5600. (let* ((limit-level
  5601. (or org-cycle-max-level
  5602. (and (boundp 'org-inlinetask-min-level)
  5603. org-inlinetask-min-level
  5604. (1- org-inlinetask-min-level))))
  5605. (nstars
  5606. (and limit-level
  5607. (if org-odd-levels-only
  5608. (1- (* 2 limit-level))
  5609. limit-level)))
  5610. (org-outline-regexp
  5611. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5612. (cond
  5613. ((equal arg '(16))
  5614. (setq last-command 'dummy)
  5615. (org-set-startup-visibility)
  5616. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5617. ((equal arg '(64))
  5618. (org-show-all)
  5619. (org-unlogged-message "Entire buffer visible, including drawers"))
  5620. ((equal arg '(4)) (org-cycle-internal-global))
  5621. ;; Show-subtree, ARG levels up from here.
  5622. ((integerp arg)
  5623. (save-excursion
  5624. (org-back-to-heading)
  5625. (outline-up-heading (if (< arg 0) (- arg)
  5626. (- (funcall outline-level) arg)))
  5627. (org-show-subtree)))
  5628. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5629. ((and org-cycle-global-at-bob
  5630. (bobp)
  5631. (not (looking-at org-outline-regexp)))
  5632. (let ((org-cycle-hook
  5633. (remq 'org-optimize-window-after-visibility-change
  5634. org-cycle-hook)))
  5635. (org-cycle-internal-global)))
  5636. ;; Try CDLaTeX TAB completion.
  5637. ((org-try-cdlatex-tab))
  5638. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5639. ((and (featurep 'org-inlinetask)
  5640. (org-inlinetask-at-task-p)
  5641. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5642. (org-inlinetask-toggle-visibility))
  5643. (t
  5644. (let ((pos (point))
  5645. (element (org-element-at-point)))
  5646. (cond
  5647. ;; Try toggling visibility for block at point.
  5648. ((org-hide-block-toggle nil t element))
  5649. ;; Try toggling visibility for drawer at point.
  5650. ((org-hide-drawer-toggle nil t element))
  5651. ;; Table: enter it or move to the next field.
  5652. ((and (org-match-line "[ \t]*[|+]")
  5653. (org-element-lineage element '(table) t))
  5654. (if (and (eq 'table (org-element-type element))
  5655. (eq 'table.el (org-element-property :type element)))
  5656. (message (substitute-command-keys "\\<org-mode-map>\
  5657. Use `\\[org-edit-special]' to edit table.el tables"))
  5658. (org-table-justify-field-maybe)
  5659. (call-interactively #'org-table-next-field)))
  5660. ((run-hook-with-args-until-success
  5661. 'org-tab-after-check-for-table-hook))
  5662. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5663. ((and (or (and org-cycle-include-plain-lists
  5664. (let ((item (org-element-lineage element
  5665. '(item plain-list)
  5666. t)))
  5667. (and item
  5668. (= (line-beginning-position)
  5669. (org-element-property :post-affiliated
  5670. item)))))
  5671. (org-match-line org-outline-regexp))
  5672. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5673. (org-cycle-internal-local))
  5674. ;; From there: TAB emulation and template completion.
  5675. (buffer-read-only (org-back-to-heading))
  5676. ((run-hook-with-args-until-success
  5677. 'org-tab-after-check-for-cycling-hook))
  5678. ((run-hook-with-args-until-success
  5679. 'org-tab-before-tab-emulation-hook))
  5680. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5681. (or (not (bolp))
  5682. (not (looking-at org-outline-regexp))))
  5683. (call-interactively (global-key-binding (kbd "TAB"))))
  5684. ((or (eq org-cycle-emulate-tab t)
  5685. (and (memq org-cycle-emulate-tab '(white whitestart))
  5686. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5687. (or (and (eq org-cycle-emulate-tab 'white)
  5688. (= (match-end 0) (point-at-eol)))
  5689. (and (eq org-cycle-emulate-tab 'whitestart)
  5690. (>= (match-end 0) pos)))))
  5691. (call-interactively (global-key-binding (kbd "TAB"))))
  5692. (t
  5693. (save-excursion
  5694. (org-back-to-heading)
  5695. (org-cycle))))))))))
  5696. (defun org-cycle-internal-global ()
  5697. "Do the global cycling action."
  5698. ;; Hack to avoid display of messages for .org attachments in Gnus
  5699. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5700. (cond
  5701. ((and (eq last-command this-command)
  5702. (eq org-cycle-global-status 'overview))
  5703. ;; We just created the overview - now do table of contents
  5704. ;; This can be slow in very large buffers, so indicate action
  5705. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5706. (unless ga (org-unlogged-message "CONTENTS..."))
  5707. (org-content)
  5708. (unless ga (org-unlogged-message "CONTENTS...done"))
  5709. (setq org-cycle-global-status 'contents)
  5710. (run-hook-with-args 'org-cycle-hook 'contents))
  5711. ((and (eq last-command this-command)
  5712. (eq org-cycle-global-status 'contents))
  5713. ;; We just showed the table of contents - now show everything
  5714. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5715. (org-show-all '(headings blocks))
  5716. (unless ga (org-unlogged-message "SHOW ALL"))
  5717. (setq org-cycle-global-status 'all)
  5718. (run-hook-with-args 'org-cycle-hook 'all))
  5719. (t
  5720. ;; Default action: go to overview
  5721. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5722. (org-overview)
  5723. (unless ga (org-unlogged-message "OVERVIEW"))
  5724. (setq org-cycle-global-status 'overview)
  5725. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5726. (defvar org-called-with-limited-levels nil
  5727. "Non-nil when `org-with-limited-levels' is currently active.")
  5728. (defun org-cycle-internal-local ()
  5729. "Do the local cycling action."
  5730. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5731. ;; First, determine end of headline (EOH), end of subtree or item
  5732. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5733. (save-excursion
  5734. (if (org-at-item-p)
  5735. (progn
  5736. (beginning-of-line)
  5737. (setq struct (org-list-struct))
  5738. (setq eoh (point-at-eol))
  5739. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5740. (setq has-children (org-list-has-child-p (point) struct)))
  5741. (org-back-to-heading)
  5742. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5743. (setq eos (save-excursion
  5744. (org-end-of-subtree t t)
  5745. (unless (eobp) (forward-char -1))
  5746. (point)))
  5747. (setq has-children
  5748. (or
  5749. (save-excursion
  5750. (let ((level (funcall outline-level)))
  5751. (outline-next-heading)
  5752. (and (org-at-heading-p t)
  5753. (> (funcall outline-level) level))))
  5754. (and (eq org-cycle-include-plain-lists 'integrate)
  5755. (save-excursion
  5756. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5757. ;; Determine end invisible part of buffer (EOL)
  5758. (beginning-of-line 2)
  5759. (while (and (not (eobp)) ;this is like `next-line'
  5760. (get-char-property (1- (point)) 'invisible))
  5761. (goto-char (next-single-char-property-change (point) 'invisible))
  5762. (and (eolp) (beginning-of-line 2)))
  5763. (setq eol (point)))
  5764. ;; Find out what to do next and set `this-command'
  5765. (cond
  5766. ((= eos eoh)
  5767. ;; Nothing is hidden behind this heading
  5768. (unless (org-before-first-heading-p)
  5769. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5770. (org-unlogged-message "EMPTY ENTRY")
  5771. (setq org-cycle-subtree-status nil)
  5772. (save-excursion
  5773. (goto-char eos)
  5774. (outline-next-heading)
  5775. (when (org-invisible-p) (org-flag-heading nil))))
  5776. ((and (or (>= eol eos)
  5777. (not (string-match "\\S-" (buffer-substring eol eos))))
  5778. (or has-children
  5779. (not (setq children-skipped
  5780. org-cycle-skip-children-state-if-no-children))))
  5781. ;; Entire subtree is hidden in one line: children view
  5782. (unless (org-before-first-heading-p)
  5783. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5784. (if (org-at-item-p)
  5785. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5786. (org-show-entry)
  5787. (org-with-limited-levels (org-show-children))
  5788. (org-show-set-visibility 'tree)
  5789. ;; Fold every list in subtree to top-level items.
  5790. (when (eq org-cycle-include-plain-lists 'integrate)
  5791. (save-excursion
  5792. (org-back-to-heading)
  5793. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5794. (beginning-of-line 1)
  5795. (let* ((struct (org-list-struct))
  5796. (prevs (org-list-prevs-alist struct))
  5797. (end (org-list-get-bottom-point struct)))
  5798. (dolist (e (org-list-get-all-items (point) struct prevs))
  5799. (org-list-set-item-visibility e struct 'folded))
  5800. (goto-char (if (< end eos) end eos)))))))
  5801. (org-unlogged-message "CHILDREN")
  5802. (save-excursion
  5803. (goto-char eos)
  5804. (outline-next-heading)
  5805. (when (org-invisible-p) (org-flag-heading nil)))
  5806. (setq org-cycle-subtree-status 'children)
  5807. (unless (org-before-first-heading-p)
  5808. (run-hook-with-args 'org-cycle-hook 'children)))
  5809. ((or children-skipped
  5810. (and (eq last-command this-command)
  5811. (eq org-cycle-subtree-status 'children)))
  5812. ;; We just showed the children, or no children are there,
  5813. ;; now show everything.
  5814. (unless (org-before-first-heading-p)
  5815. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5816. (org-flag-region eoh eos nil 'outline)
  5817. (org-unlogged-message
  5818. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5819. (setq org-cycle-subtree-status 'subtree)
  5820. (unless (org-before-first-heading-p)
  5821. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5822. (t
  5823. ;; Default action: hide the subtree.
  5824. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5825. (org-flag-region eoh eos t 'outline)
  5826. (org-unlogged-message "FOLDED")
  5827. (setq org-cycle-subtree-status 'folded)
  5828. (unless (org-before-first-heading-p)
  5829. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5830. ;;;###autoload
  5831. (defun org-global-cycle (&optional arg)
  5832. "Cycle the global visibility. For details see `org-cycle'.
  5833. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5834. With a numeric prefix, show all headlines up to that level."
  5835. (interactive "P")
  5836. (cond
  5837. ((integerp arg)
  5838. (org-content arg)
  5839. (setq org-cycle-global-status 'contents))
  5840. ((equal arg '(4))
  5841. (org-set-startup-visibility)
  5842. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5843. (t
  5844. (org-cycle '(4)))))
  5845. (defun org-set-startup-visibility ()
  5846. "Set the visibility required by startup options and properties."
  5847. (cond
  5848. ((eq org-startup-folded t)
  5849. (org-overview))
  5850. ((eq org-startup-folded 'content)
  5851. (org-content))
  5852. ((eq org-startup-folded 'show2levels)
  5853. (org-content 2))
  5854. ((eq org-startup-folded 'show3levels)
  5855. (org-content 3))
  5856. ((eq org-startup-folded 'show4levels)
  5857. (org-content 4))
  5858. ((eq org-startup-folded 'show5levels)
  5859. (org-content 5))
  5860. ((or (eq org-startup-folded 'showeverything)
  5861. (eq org-startup-folded nil))
  5862. (org-show-all)))
  5863. (unless (eq org-startup-folded 'showeverything)
  5864. (when org-hide-block-startup (org-hide-block-all))
  5865. (org-set-visibility-according-to-property)
  5866. (org-cycle-hide-archived-subtrees 'all)
  5867. (org-cycle-hide-drawers 'all)
  5868. (org-cycle-show-empty-lines t)))
  5869. (defun org-set-visibility-according-to-property ()
  5870. "Switch subtree visibility according to VISIBILITY property."
  5871. (interactive)
  5872. (let ((regexp (org-re-property "VISIBILITY")))
  5873. (org-with-point-at 1
  5874. (while (re-search-forward regexp nil t)
  5875. (let ((state (match-string 3)))
  5876. (if (not (org-at-property-p)) (outline-next-heading)
  5877. (save-excursion
  5878. (org-back-to-heading t)
  5879. (org-flag-subtree t)
  5880. (org-reveal)
  5881. (pcase state
  5882. ("folded"
  5883. (org-flag-subtree t))
  5884. ("children"
  5885. (org-show-hidden-entry)
  5886. (org-show-children))
  5887. ("content"
  5888. (save-excursion
  5889. (save-restriction
  5890. (org-narrow-to-subtree)
  5891. (org-content))))
  5892. ((or "all" "showall")
  5893. (outline-show-subtree))
  5894. (_ nil)))
  5895. (org-end-of-subtree)))))))
  5896. (defun org-overview ()
  5897. "Switch to overview mode, showing only top-level headlines."
  5898. (interactive)
  5899. (org-show-all '(headings drawers))
  5900. (save-excursion
  5901. (goto-char (point-min))
  5902. (when (re-search-forward org-outline-regexp-bol nil t)
  5903. (let* ((last (line-end-position))
  5904. (level (- (match-end 0) (match-beginning 0) 1))
  5905. (regexp (format "^\\*\\{1,%d\\} " level)))
  5906. (while (re-search-forward regexp nil :move)
  5907. (org-flag-region last (line-end-position 0) t 'outline)
  5908. (setq last (line-end-position))
  5909. (setq level (- (match-end 0) (match-beginning 0) 1))
  5910. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5911. (org-flag-region last (point) t 'outline)))))
  5912. (defun org-content (&optional arg)
  5913. "Show all headlines in the buffer, like a table of contents.
  5914. With numerical argument N, show content up to level N."
  5915. (interactive "p")
  5916. (org-show-all '(headings drawers))
  5917. (save-excursion
  5918. (goto-char (point-max))
  5919. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5920. (format "^\\*\\{1,%d\\} " arg)
  5921. "^\\*+ "))
  5922. (last (point)))
  5923. (while (re-search-backward regexp nil t)
  5924. (org-flag-region (line-end-position) last t 'outline)
  5925. (setq last (line-end-position 0))))))
  5926. (defvar org-scroll-position-to-restore nil
  5927. "Temporarily store scroll position to restore.")
  5928. (defun org-optimize-window-after-visibility-change (state)
  5929. "Adjust the window after a change in outline visibility.
  5930. This function is the default value of the hook `org-cycle-hook'."
  5931. (when (get-buffer-window (current-buffer))
  5932. (let ((repeat (eq last-command this-command)))
  5933. (unless repeat
  5934. (setq org-scroll-position-to-restore nil))
  5935. (cond
  5936. ((eq state 'content) nil)
  5937. ((eq state 'all) nil)
  5938. ((and org-scroll-position-to-restore repeat
  5939. (eq state 'folded))
  5940. (set-window-start nil org-scroll-position-to-restore))
  5941. ((eq state 'folded) nil)
  5942. ((eq state 'children)
  5943. (setq org-scroll-position-to-restore (window-start))
  5944. (or (org-subtree-end-visible-p) (recenter 1)))
  5945. ((eq state 'subtree)
  5946. (unless repeat
  5947. (setq org-scroll-position-to-restore (window-start)))
  5948. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5949. (defun org-clean-visibility-after-subtree-move ()
  5950. "Fix visibility issues after moving a subtree."
  5951. ;; First, find a reasonable region to look at:
  5952. ;; Start two siblings above, end three below
  5953. (let* ((beg (save-excursion
  5954. (and (org-get-last-sibling)
  5955. (org-get-last-sibling))
  5956. (point)))
  5957. (end (save-excursion
  5958. (and (org-get-next-sibling)
  5959. (org-get-next-sibling)
  5960. (org-get-next-sibling))
  5961. (if (org-at-heading-p)
  5962. (point-at-eol)
  5963. (point))))
  5964. (level (looking-at "\\*+"))
  5965. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5966. (save-excursion
  5967. (save-restriction
  5968. (narrow-to-region beg end)
  5969. (when re
  5970. ;; Properly fold already folded siblings
  5971. (goto-char (point-min))
  5972. (while (re-search-forward re nil t)
  5973. (when (and (not (org-invisible-p))
  5974. (org-invisible-p (line-end-position)))
  5975. (outline-hide-entry))))
  5976. (org-cycle-hide-drawers 'all)
  5977. (org-cycle-show-empty-lines 'overview)))))
  5978. (defun org-cycle-show-empty-lines (state)
  5979. "Show empty lines above all visible headlines.
  5980. The region to be covered depends on STATE when called through
  5981. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5982. entire buffer covered. Note that an empty line is only shown if there
  5983. are at least `org-cycle-separator-lines' empty lines before the headline."
  5984. (when (/= org-cycle-separator-lines 0)
  5985. (save-excursion
  5986. (let* ((n (abs org-cycle-separator-lines))
  5987. (re (cond
  5988. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5989. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5990. (t (let ((ns (number-to-string (- n 2))))
  5991. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  5992. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  5993. beg end)
  5994. (cond
  5995. ((memq state '(overview contents t))
  5996. (setq beg (point-min) end (point-max)))
  5997. ((memq state '(children folded))
  5998. (setq beg (point)
  5999. end (progn (org-end-of-subtree t t)
  6000. (line-beginning-position 2)))))
  6001. (when beg
  6002. (goto-char beg)
  6003. (while (re-search-forward re end t)
  6004. (unless (get-char-property (match-end 1) 'invisible)
  6005. (let ((e (match-end 1))
  6006. (b (if (>= org-cycle-separator-lines 0)
  6007. (match-beginning 1)
  6008. (save-excursion
  6009. (goto-char (match-beginning 0))
  6010. (skip-chars-backward " \t\n")
  6011. (line-end-position)))))
  6012. (org-flag-region b e nil 'outline))))))))
  6013. ;; Never hide empty lines at the end of the file.
  6014. (save-excursion
  6015. (goto-char (point-max))
  6016. (outline-previous-heading)
  6017. (outline-end-of-heading)
  6018. (when (and (looking-at "[ \t\n]+")
  6019. (= (match-end 0) (point-max)))
  6020. (org-flag-region (point) (match-end 0) nil 'outline))))
  6021. ;;;; Reveal point location
  6022. (defun org-show-context (&optional key)
  6023. "Make sure point and context are visible.
  6024. Optional argument KEY, when non-nil, is a symbol. See
  6025. `org-show-context-detail' for allowed values and how much is to
  6026. be shown."
  6027. (org-show-set-visibility
  6028. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6029. ((cdr (assq key org-show-context-detail)))
  6030. (t (cdr (assq 'default org-show-context-detail))))))
  6031. (defun org-show-set-visibility (detail)
  6032. "Set visibility around point according to DETAIL.
  6033. DETAIL is either nil, `minimal', `local', `ancestors',
  6034. `ancestors-full', `lineage', `tree', `canonical' or t. See
  6035. `org-show-context-detail' for more information."
  6036. ;; Show current heading and possibly its entry, following headline
  6037. ;; or all children.
  6038. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6039. (org-flag-heading nil)
  6040. (org-show-entry)
  6041. ;; If point is hidden within a drawer or a block, make sure to
  6042. ;; expose it.
  6043. (dolist (o (overlays-at (point)))
  6044. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6045. (delete-overlay o)))
  6046. (unless (org-before-first-heading-p)
  6047. (org-with-limited-levels
  6048. (cl-case detail
  6049. ((tree canonical t) (org-show-children))
  6050. ((nil minimal ancestors ancestors-full))
  6051. (t (save-excursion
  6052. (outline-next-heading)
  6053. (org-flag-heading nil)))))))
  6054. ;; Show whole subtree.
  6055. (when (eq detail 'ancestors-full) (org-show-subtree))
  6056. ;; Show all siblings.
  6057. (when (eq detail 'lineage) (org-show-siblings))
  6058. ;; Show ancestors, possibly with their children.
  6059. (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
  6060. (save-excursion
  6061. (while (org-up-heading-safe)
  6062. (org-flag-heading nil)
  6063. (when (memq detail '(canonical t)) (org-show-entry))
  6064. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6065. (defvar org-reveal-start-hook nil
  6066. "Hook run before revealing a location.")
  6067. (defun org-reveal (&optional siblings)
  6068. "Show current entry, hierarchy above it, and the following headline.
  6069. This can be used to show a consistent set of context around
  6070. locations exposed with `org-show-context'.
  6071. With optional argument SIBLINGS, on each level of the hierarchy all
  6072. siblings are shown. This repairs the tree structure to what it would
  6073. look like when opened with hierarchical calls to `org-cycle'.
  6074. With a \\[universal-argument] \\[universal-argument] prefix, \
  6075. go to the parent and show the entire tree."
  6076. (interactive "P")
  6077. (run-hooks 'org-reveal-start-hook)
  6078. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6079. ((equal siblings '(16))
  6080. (save-excursion
  6081. (when (org-up-heading-safe)
  6082. (org-show-subtree)
  6083. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6084. (t (org-show-set-visibility 'lineage))))
  6085. ;;; Indirect buffer display of subtrees
  6086. (defvar org-indirect-dedicated-frame nil
  6087. "This is the frame being used for indirect tree display.")
  6088. (defvar org-last-indirect-buffer nil)
  6089. (defun org-tree-to-indirect-buffer (&optional arg)
  6090. "Create indirect buffer and narrow it to current subtree.
  6091. With a numerical prefix ARG, go up to this level and then take that tree.
  6092. If ARG is negative, go up that many levels.
  6093. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6094. indirect buffer previously made with this command, to avoid proliferation of
  6095. indirect buffers. However, when you call the command with a \
  6096. `\\[universal-argument]' prefix, or
  6097. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6098. so that you can work with several indirect buffers at the same time. If
  6099. `org-indirect-buffer-display' is `dedicated-frame', the \
  6100. `\\[universal-argument]' prefix also
  6101. requests that a new frame be made for the new buffer, so that the dedicated
  6102. frame is not changed."
  6103. (interactive "P")
  6104. (let ((cbuf (current-buffer))
  6105. (cwin (selected-window))
  6106. (pos (point))
  6107. beg end level heading ibuf)
  6108. (save-excursion
  6109. (org-back-to-heading t)
  6110. (when (numberp arg)
  6111. (setq level (org-outline-level))
  6112. (when (< arg 0) (setq arg (+ level arg)))
  6113. (while (> (setq level (org-outline-level)) arg)
  6114. (org-up-heading-safe)))
  6115. (setq beg (point)
  6116. heading (org-get-heading 'no-tags))
  6117. (org-end-of-subtree t t)
  6118. (when (org-at-heading-p) (backward-char 1))
  6119. (setq end (point)))
  6120. (when (and (buffer-live-p org-last-indirect-buffer)
  6121. (not (eq org-indirect-buffer-display 'new-frame))
  6122. (not arg))
  6123. (kill-buffer org-last-indirect-buffer))
  6124. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6125. org-last-indirect-buffer ibuf)
  6126. (cond
  6127. ((or (eq org-indirect-buffer-display 'new-frame)
  6128. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6129. (select-frame (make-frame))
  6130. (delete-other-windows)
  6131. (pop-to-buffer-same-window ibuf)
  6132. (org-set-frame-title heading))
  6133. ((eq org-indirect-buffer-display 'dedicated-frame)
  6134. (raise-frame
  6135. (select-frame (or (and org-indirect-dedicated-frame
  6136. (frame-live-p org-indirect-dedicated-frame)
  6137. org-indirect-dedicated-frame)
  6138. (setq org-indirect-dedicated-frame (make-frame)))))
  6139. (delete-other-windows)
  6140. (pop-to-buffer-same-window ibuf)
  6141. (org-set-frame-title (concat "Indirect: " heading)))
  6142. ((eq org-indirect-buffer-display 'current-window)
  6143. (pop-to-buffer-same-window ibuf))
  6144. ((eq org-indirect-buffer-display 'other-window)
  6145. (pop-to-buffer ibuf))
  6146. (t (error "Invalid value")))
  6147. (narrow-to-region beg end)
  6148. (org-show-all '(headings drawers blocks))
  6149. (goto-char pos)
  6150. (run-hook-with-args 'org-cycle-hook 'all)
  6151. (and (window-live-p cwin) (select-window cwin))))
  6152. (defun org-get-indirect-buffer (&optional buffer heading)
  6153. (setq buffer (or buffer (current-buffer)))
  6154. (let ((n 1) (base (buffer-name buffer)) bname)
  6155. (while (buffer-live-p
  6156. (get-buffer
  6157. (setq bname
  6158. (concat base "-"
  6159. (if heading (concat heading "-" (number-to-string n))
  6160. (number-to-string n))))))
  6161. (setq n (1+ n)))
  6162. (condition-case nil
  6163. (make-indirect-buffer buffer bname 'clone)
  6164. (error (make-indirect-buffer buffer bname)))))
  6165. (defun org-set-frame-title (title)
  6166. "Set the title of the current frame to the string TITLE."
  6167. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6168. ;;;; Structure editing
  6169. ;;; Inserting headlines
  6170. (defun org--blank-before-heading-p (&optional parent)
  6171. "Non-nil when an empty line should precede a new heading here.
  6172. When optional argument PARENT is non-nil, consider parent
  6173. headline instead of current one."
  6174. (pcase (assq 'heading org-blank-before-new-entry)
  6175. (`(heading . auto)
  6176. (save-excursion
  6177. (org-with-limited-levels
  6178. (unless (and (org-before-first-heading-p)
  6179. (not (outline-next-heading)))
  6180. (org-back-to-heading t)
  6181. (when parent (org-up-heading-safe))
  6182. (cond ((not (bobp))
  6183. (org-previous-line-empty-p))
  6184. ((outline-next-heading)
  6185. (org-previous-line-empty-p))
  6186. ;; Ignore trailing spaces on last buffer line.
  6187. ((progn (skip-chars-backward " \t") (bolp))
  6188. (org-previous-line-empty-p))
  6189. (t nil))))))
  6190. (`(heading . ,value) value)
  6191. (_ nil)))
  6192. (defun org-insert-heading (&optional arg invisible-ok top)
  6193. "Insert a new heading or an item with the same depth at point.
  6194. If point is at the beginning of a heading, insert a new heading
  6195. or a new headline above the current one. When at the beginning
  6196. of a regular line of text, turn it into a heading.
  6197. If point is in the middle of a line, split it and create a new
  6198. headline with the text in the current line after point (see
  6199. `org-M-RET-may-split-line' on how to modify this behavior). As
  6200. a special case, on a headline, splitting can only happen on the
  6201. title itself. E.g., this excludes breaking stars or tags.
  6202. With a `\\[universal-argument]' prefix, set \
  6203. `org-insert-heading-respect-content' to
  6204. a non-nil value for the duration of the command. This forces the
  6205. insertion of a heading after the current subtree, independently
  6206. on the location of point.
  6207. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6208. insert the heading at the end of the tree
  6209. above the current heading. For example, if point is within a
  6210. 2nd-level heading, then it will insert a 2nd-level heading at
  6211. the end of the 1st-level parent subtree.
  6212. When INVISIBLE-OK is set, stop at invisible headlines when going
  6213. back. This is important for non-interactive uses of the
  6214. command.
  6215. When optional argument TOP is non-nil, insert a level 1 heading,
  6216. unconditionally."
  6217. (interactive "P")
  6218. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6219. (level (org-current-level))
  6220. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6221. (cond
  6222. ((or org-insert-heading-respect-content
  6223. (member arg '((4) (16)))
  6224. (and (not invisible-ok)
  6225. (invisible-p (max (1- (point)) (point-min)))))
  6226. ;; Position point at the location of insertion. Make sure we
  6227. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6228. (org-with-limited-levels
  6229. (if (not level) (outline-next-heading) ;before first headline
  6230. (org-back-to-heading invisible-ok)
  6231. (when (equal arg '(16)) (org-up-heading-safe))
  6232. (org-end-of-subtree)))
  6233. (unless (bolp) (insert "\n"))
  6234. (when (and blank? (save-excursion
  6235. (backward-char)
  6236. (org-before-first-heading-p)))
  6237. (insert "\n")
  6238. (backward-char))
  6239. (unless level (backward-char))
  6240. (unless (and blank? (org-previous-line-empty-p))
  6241. (org-N-empty-lines-before-current (if blank? 1 0)))
  6242. (insert stars " ")
  6243. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6244. ;; is visible.
  6245. (unless invisible-ok
  6246. (pcase (get-char-property-and-overlay (point) 'invisible)
  6247. (`(outline . ,o)
  6248. (move-overlay o (overlay-start o) (line-end-position 0)))
  6249. (_ nil))))
  6250. ;; At a headline...
  6251. ((org-at-heading-p)
  6252. (cond ((bolp)
  6253. (when blank? (save-excursion (insert "\n")))
  6254. (save-excursion (insert stars " \n"))
  6255. (unless (and blank? (org-previous-line-empty-p))
  6256. (org-N-empty-lines-before-current (if blank? 1 0)))
  6257. (end-of-line))
  6258. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6259. (org-match-line org-complex-heading-regexp)
  6260. (org-pos-in-match-range (point) 4))
  6261. ;; Grab the text that should moved to the new headline.
  6262. ;; Preserve tags.
  6263. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6264. (if (looking-at "[ \t]*$") (replace-match "")
  6265. (org-align-tags))
  6266. (end-of-line)
  6267. (when blank? (insert "\n"))
  6268. (insert "\n" stars " ")
  6269. (when (org-string-nw-p split) (insert split))))
  6270. (t
  6271. (end-of-line)
  6272. (when blank? (insert "\n"))
  6273. (insert "\n" stars " "))))
  6274. ;; On regular text, turn line into a headline or split, if
  6275. ;; appropriate.
  6276. ((bolp)
  6277. (insert stars " ")
  6278. (unless (and blank? (org-previous-line-empty-p))
  6279. (org-N-empty-lines-before-current (if blank? 1 0))))
  6280. (t
  6281. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6282. (end-of-line))
  6283. (insert "\n" stars " ")
  6284. (unless (and blank? (org-previous-line-empty-p))
  6285. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6286. (run-hooks 'org-insert-heading-hook))
  6287. (defun org-N-empty-lines-before-current (n)
  6288. "Make the number of empty lines before current exactly N.
  6289. So this will delete or add empty lines."
  6290. (let ((column (current-column)))
  6291. (beginning-of-line)
  6292. (unless (bobp)
  6293. (let ((start (save-excursion
  6294. (skip-chars-backward " \r\t\n")
  6295. (line-end-position))))
  6296. (delete-region start (line-end-position 0))))
  6297. (insert (make-string n ?\n))
  6298. (move-to-column column)))
  6299. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6300. "Return the heading of the current entry, without the stars.
  6301. When NO-TAGS is non-nil, don't include tags.
  6302. When NO-TODO is non-nil, don't include TODO keywords.
  6303. When NO-PRIORITY is non-nil, don't include priority cookie.
  6304. When NO-COMMENT is non-nil, don't include COMMENT string.
  6305. Return nil before first heading."
  6306. (unless (org-before-first-heading-p)
  6307. (save-excursion
  6308. (org-back-to-heading t)
  6309. (let ((case-fold-search nil))
  6310. (looking-at org-complex-heading-regexp)
  6311. (let ((todo (and (not no-todo) (match-string 2)))
  6312. (priority (and (not no-priority) (match-string 3)))
  6313. (headline (pcase (match-string 4)
  6314. (`nil "")
  6315. ((and (guard no-comment) h)
  6316. (replace-regexp-in-string
  6317. (eval-when-compile
  6318. (format "\\`%s[ \t]+" org-comment-string))
  6319. "" h))
  6320. (h h)))
  6321. (tags (and (not no-tags) (match-string 5))))
  6322. (mapconcat #'identity
  6323. (delq nil (list todo priority headline tags))
  6324. " "))))))
  6325. (defun org-heading-components ()
  6326. "Return the components of the current heading.
  6327. This is a list with the following elements:
  6328. - the level as an integer
  6329. - the reduced level, different if `org-odd-levels-only' is set.
  6330. - the TODO keyword, or nil
  6331. - the priority character, like ?A, or nil if no priority is given
  6332. - the headline text itself, or the tags string if no headline text
  6333. - the tags string, or nil."
  6334. (save-excursion
  6335. (org-back-to-heading t)
  6336. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6337. (list (length (match-string 1))
  6338. (org-reduced-level (length (match-string 1)))
  6339. (match-string-no-properties 2)
  6340. (and (match-end 3) (aref (match-string 3) 2))
  6341. (match-string-no-properties 4)
  6342. (match-string-no-properties 5)))))
  6343. (defun org-get-entry ()
  6344. "Get the entry text, after heading, entire subtree."
  6345. (save-excursion
  6346. (org-back-to-heading t)
  6347. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6348. (defun org-edit-headline (&optional heading)
  6349. "Edit the current headline.
  6350. Set it to HEADING when provided."
  6351. (interactive)
  6352. (org-with-wide-buffer
  6353. (org-back-to-heading t)
  6354. (let ((case-fold-search nil))
  6355. (when (looking-at org-complex-heading-regexp)
  6356. (let* ((old (match-string-no-properties 4))
  6357. (new (save-match-data
  6358. (org-trim (or heading (read-string "Edit: " old))))))
  6359. (unless (equal old new)
  6360. (if old (replace-match new t t nil 4)
  6361. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6362. (insert " " new))
  6363. (org-align-tags)
  6364. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6365. (defun org-insert-heading-after-current ()
  6366. "Insert a new heading with same level as current, after current subtree."
  6367. (interactive)
  6368. (org-back-to-heading)
  6369. (org-insert-heading)
  6370. (org-move-subtree-down)
  6371. (end-of-line 1))
  6372. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6373. "Insert heading with `org-insert-heading-respect-content' set to t."
  6374. (interactive)
  6375. (org-insert-heading '(4) invisible-ok))
  6376. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6377. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6378. (interactive)
  6379. (org-insert-todo-heading force-state '(4)))
  6380. (defun org-insert-todo-heading (arg &optional force-heading)
  6381. "Insert a new heading with the same level and TODO state as current heading.
  6382. If the heading has no TODO state, or if the state is DONE, use
  6383. the first state (TODO by default). Also with one prefix arg,
  6384. force first state. With two prefix args, force inserting at the
  6385. end of the parent subtree.
  6386. When called at a plain list item, insert a new item with an
  6387. unchecked check box."
  6388. (interactive "P")
  6389. (when (or force-heading (not (org-insert-item 'checkbox)))
  6390. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6391. force-heading))
  6392. (save-excursion
  6393. (org-forward-heading-same-level -1)
  6394. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6395. (let* ((new-mark-x
  6396. (if (or (equal arg '(4))
  6397. (not (match-beginning 2))
  6398. (member (match-string 2) org-done-keywords))
  6399. (car org-todo-keywords-1)
  6400. (match-string 2)))
  6401. (new-mark
  6402. (or
  6403. (run-hook-with-args-until-success
  6404. 'org-todo-get-default-hook new-mark-x nil)
  6405. new-mark-x)))
  6406. (beginning-of-line 1)
  6407. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6408. (if org-treat-insert-todo-heading-as-state-change
  6409. (org-todo new-mark)
  6410. (insert new-mark " "))))
  6411. (when org-provide-todo-statistics
  6412. (org-update-parent-todo-statistics))))
  6413. (defun org-insert-subheading (arg)
  6414. "Insert a new subheading and demote it.
  6415. Works for outline headings and for plain lists alike."
  6416. (interactive "P")
  6417. (org-insert-heading arg)
  6418. (cond
  6419. ((org-at-heading-p) (org-do-demote))
  6420. ((org-at-item-p) (org-indent-item))))
  6421. (defun org-insert-todo-subheading (arg)
  6422. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6423. Works for outline headings and for plain lists alike."
  6424. (interactive "P")
  6425. (org-insert-todo-heading arg)
  6426. (cond
  6427. ((org-at-heading-p) (org-do-demote))
  6428. ((org-at-item-p) (org-indent-item))))
  6429. ;;; Promotion and Demotion
  6430. (defvar org-after-demote-entry-hook nil
  6431. "Hook run after an entry has been demoted.
  6432. The cursor will be at the beginning of the entry.
  6433. When a subtree is being demoted, the hook will be called for each node.")
  6434. (defvar org-after-promote-entry-hook nil
  6435. "Hook run after an entry has been promoted.
  6436. The cursor will be at the beginning of the entry.
  6437. When a subtree is being promoted, the hook will be called for each node.")
  6438. (defun org-promote-subtree ()
  6439. "Promote the entire subtree.
  6440. See also `org-promote'."
  6441. (interactive)
  6442. (save-excursion
  6443. (org-with-limited-levels (org-map-tree 'org-promote)))
  6444. (org-fix-position-after-promote))
  6445. (defun org-demote-subtree ()
  6446. "Demote the entire subtree.
  6447. See `org-demote' and `org-promote'."
  6448. (interactive)
  6449. (save-excursion
  6450. (org-with-limited-levels (org-map-tree 'org-demote)))
  6451. (org-fix-position-after-promote))
  6452. (defun org-do-promote ()
  6453. "Promote the current heading higher up the tree.
  6454. If the region is active in `transient-mark-mode', promote all
  6455. headings in the region."
  6456. (interactive)
  6457. (save-excursion
  6458. (if (org-region-active-p)
  6459. (org-map-region 'org-promote (region-beginning) (region-end))
  6460. (org-promote)))
  6461. (org-fix-position-after-promote))
  6462. (defun org-do-demote ()
  6463. "Demote the current heading lower down the tree.
  6464. If the region is active in `transient-mark-mode', demote all
  6465. headings in the region."
  6466. (interactive)
  6467. (save-excursion
  6468. (if (org-region-active-p)
  6469. (org-map-region 'org-demote (region-beginning) (region-end))
  6470. (org-demote)))
  6471. (org-fix-position-after-promote))
  6472. (defun org-fix-position-after-promote ()
  6473. "Fix cursor position and indentation after demoting/promoting."
  6474. (let ((pos (point)))
  6475. (when (save-excursion
  6476. (beginning-of-line)
  6477. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6478. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6479. (cond ((eobp) (insert " "))
  6480. ((eolp) (insert " "))
  6481. ((equal (char-after) ?\s) (forward-char 1))))))
  6482. (defun org-current-level ()
  6483. "Return the level of the current entry, or nil if before the first headline.
  6484. The level is the number of stars at the beginning of the
  6485. headline. Use `org-reduced-level' to remove the effect of
  6486. `org-odd-levels'. Unlike to `org-outline-level', this function
  6487. ignores inlinetasks."
  6488. (let ((level (org-with-limited-levels (org-outline-level))))
  6489. (and (> level 0) level)))
  6490. (defun org-get-previous-line-level ()
  6491. "Return the outline depth of the last headline before the current line.
  6492. Returns 0 for the first headline in the buffer, and nil if before the
  6493. first headline."
  6494. (and (org-current-level)
  6495. (or (and (/= (line-beginning-position) (point-min))
  6496. (save-excursion (beginning-of-line 0) (org-current-level)))
  6497. 0)))
  6498. (defun org-reduced-level (l)
  6499. "Compute the effective level of a heading.
  6500. This takes into account the setting of `org-odd-levels-only'."
  6501. (cond
  6502. ((zerop l) 0)
  6503. (org-odd-levels-only (1+ (floor (/ l 2))))
  6504. (t l)))
  6505. (defun org-level-increment ()
  6506. "Return the number of stars that will be added or removed at a
  6507. time to headlines when structure editing, based on the value of
  6508. `org-odd-levels-only'."
  6509. (if org-odd-levels-only 2 1))
  6510. (defun org-get-valid-level (level &optional change)
  6511. "Rectify a level change under the influence of `org-odd-levels-only'.
  6512. LEVEL is a current level, CHANGE is by how much the level should
  6513. be modified. Even if CHANGE is nil, LEVEL may be returned
  6514. modified because even level numbers will become the next higher
  6515. odd number. Returns values greater than 0."
  6516. (if org-odd-levels-only
  6517. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6518. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6519. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6520. (max 1 (+ level (or change 0)))))
  6521. (defun org-promote ()
  6522. "Promote the current heading higher up the tree."
  6523. (org-with-wide-buffer
  6524. (org-back-to-heading t)
  6525. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6526. after-change-functions))
  6527. (level (save-match-data (funcall outline-level)))
  6528. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6529. (diff (abs (- level (length up-head) -1))))
  6530. (cond
  6531. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6532. (replace-match "# " nil t))
  6533. ((= level 1)
  6534. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6535. (t (replace-match up-head nil t)))
  6536. (unless (= level 1)
  6537. (when org-auto-align-tags (org-align-tags))
  6538. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6539. (run-hooks 'org-after-promote-entry-hook))))
  6540. (defun org-demote ()
  6541. "Demote the current heading lower down the tree."
  6542. (org-with-wide-buffer
  6543. (org-back-to-heading t)
  6544. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6545. after-change-functions))
  6546. (level (save-match-data (funcall outline-level)))
  6547. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6548. (diff (abs (- level (length down-head) -1))))
  6549. (replace-match down-head nil t)
  6550. (when org-auto-align-tags (org-align-tags))
  6551. (when org-adapt-indentation (org-fixup-indentation diff))
  6552. (run-hooks 'org-after-demote-entry-hook))))
  6553. (defun org-cycle-level ()
  6554. "Cycle the level of an empty headline through possible states.
  6555. This goes first to child, then to parent, level, then up the hierarchy.
  6556. After top level, it switches back to sibling level."
  6557. (interactive)
  6558. (let ((org-adapt-indentation nil))
  6559. (when (org-point-at-end-of-empty-headline)
  6560. (setq this-command 'org-cycle-level) ; Only needed for caching
  6561. (let ((cur-level (org-current-level))
  6562. (prev-level (org-get-previous-line-level)))
  6563. (cond
  6564. ;; If first headline in file, promote to top-level.
  6565. ((= prev-level 0)
  6566. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6567. do (org-do-promote)))
  6568. ;; If same level as prev, demote one.
  6569. ((= prev-level cur-level)
  6570. (org-do-demote))
  6571. ;; If parent is top-level, promote to top level if not already.
  6572. ((= prev-level 1)
  6573. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6574. do (org-do-promote)))
  6575. ;; If top-level, return to prev-level.
  6576. ((= cur-level 1)
  6577. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6578. do (org-do-demote)))
  6579. ;; If less than prev-level, promote one.
  6580. ((< cur-level prev-level)
  6581. (org-do-promote))
  6582. ;; If deeper than prev-level, promote until higher than
  6583. ;; prev-level.
  6584. ((> cur-level prev-level)
  6585. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6586. do (org-do-promote))))
  6587. t))))
  6588. (defun org-map-tree (fun)
  6589. "Call FUN for every heading underneath the current one."
  6590. (org-back-to-heading t)
  6591. (let ((level (funcall outline-level)))
  6592. (save-excursion
  6593. (funcall fun)
  6594. (while (and (progn
  6595. (outline-next-heading)
  6596. (> (funcall outline-level) level))
  6597. (not (eobp)))
  6598. (funcall fun)))))
  6599. (defun org-map-region (fun beg end)
  6600. "Call FUN for every heading between BEG and END."
  6601. (let ((org-ignore-region t))
  6602. (save-excursion
  6603. (setq end (copy-marker end))
  6604. (goto-char beg)
  6605. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6606. (< (point) end))
  6607. (funcall fun))
  6608. (while (and (progn
  6609. (outline-next-heading)
  6610. (< (point) end))
  6611. (not (eobp)))
  6612. (funcall fun)))))
  6613. (defun org-fixup-indentation (diff)
  6614. "Change the indentation in the current entry by DIFF.
  6615. DIFF is an integer. Indentation is done according to the
  6616. following rules:
  6617. - Planning information and property drawers are always indented
  6618. according to the new level of the headline;
  6619. - Footnote definitions and their contents are ignored;
  6620. - Inlinetasks' boundaries are not shifted;
  6621. - Empty lines are ignored;
  6622. - Other lines' indentation are shifted by DIFF columns, unless
  6623. it would introduce a structural change in the document, in
  6624. which case no shifting is done at all.
  6625. Assume point is at a heading or an inlinetask beginning."
  6626. (org-with-wide-buffer
  6627. (narrow-to-region (line-beginning-position)
  6628. (save-excursion
  6629. (if (org-with-limited-levels (org-at-heading-p))
  6630. (org-with-limited-levels (outline-next-heading))
  6631. (org-inlinetask-goto-end))
  6632. (point)))
  6633. (forward-line)
  6634. ;; Indent properly planning info and property drawer.
  6635. (when (looking-at-p org-planning-line-re)
  6636. (org-indent-line)
  6637. (forward-line))
  6638. (when (looking-at org-property-drawer-re)
  6639. (goto-char (match-end 0))
  6640. (forward-line)
  6641. (org-indent-region (match-beginning 0) (match-end 0)))
  6642. (when (looking-at org-logbook-drawer-re)
  6643. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6644. (col (+ (current-indentation) diff)))
  6645. (when (wholenump col)
  6646. (while (< (point) end-marker)
  6647. (if (natnump diff)
  6648. (insert (make-string diff 32))
  6649. (delete-char (abs diff)))
  6650. (forward-line)))))
  6651. (catch 'no-shift
  6652. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6653. (throw 'no-shift nil))
  6654. ;; If DIFF is negative, first check if a shift is possible at all
  6655. ;; (e.g., it doesn't break structure). This can only happen if
  6656. ;; some contents are not properly indented.
  6657. (let ((case-fold-search t))
  6658. (when (< diff 0)
  6659. (let ((diff (- diff))
  6660. (forbidden-re (concat org-outline-regexp
  6661. "\\|"
  6662. (substring org-footnote-definition-re 1))))
  6663. (save-excursion
  6664. (while (not (eobp))
  6665. (cond
  6666. ((looking-at-p "[ \t]*$") (forward-line))
  6667. ((and (looking-at-p org-footnote-definition-re)
  6668. (let ((e (org-element-at-point)))
  6669. (and (eq (org-element-type e) 'footnote-definition)
  6670. (goto-char (org-element-property :end e))))))
  6671. ((looking-at-p org-outline-regexp) (forward-line))
  6672. ;; Give up if shifting would move before column 0 or
  6673. ;; if it would introduce a headline or a footnote
  6674. ;; definition.
  6675. (t
  6676. (skip-chars-forward " \t")
  6677. (let ((ind (current-column)))
  6678. (when (or (< ind diff)
  6679. (and (= ind diff) (looking-at-p forbidden-re)))
  6680. (throw 'no-shift nil)))
  6681. ;; Ignore contents of example blocks and source
  6682. ;; blocks if their indentation is meant to be
  6683. ;; preserved. Jump to block's closing line.
  6684. (beginning-of-line)
  6685. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6686. (let ((e (org-element-at-point)))
  6687. (and (memq (org-element-type e)
  6688. '(example-block src-block))
  6689. (or org-src-preserve-indentation
  6690. (org-element-property :preserve-indent e))
  6691. (goto-char (org-element-property :end e))
  6692. (progn (skip-chars-backward " \r\t\n")
  6693. (beginning-of-line)
  6694. t))))
  6695. (forward-line))))))))
  6696. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6697. ;; by DIFF. Also skip contents of source or example blocks
  6698. ;; when indentation is meant to be preserved.
  6699. (while (not (eobp))
  6700. (cond
  6701. ((and (looking-at-p org-footnote-definition-re)
  6702. (let ((e (org-element-at-point)))
  6703. (and (eq (org-element-type e) 'footnote-definition)
  6704. (goto-char (org-element-property :end e))))))
  6705. ((looking-at-p org-outline-regexp) (forward-line))
  6706. ((looking-at-p "[ \t]*$") (forward-line))
  6707. (t
  6708. (indent-line-to (+ (current-indentation) diff))
  6709. (beginning-of-line)
  6710. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6711. (let ((e (org-element-at-point)))
  6712. (and (memq (org-element-type e)
  6713. '(example-block src-block))
  6714. (or org-src-preserve-indentation
  6715. (org-element-property :preserve-indent e))
  6716. (goto-char (org-element-property :end e))
  6717. (progn (skip-chars-backward " \r\t\n")
  6718. (beginning-of-line)
  6719. t))))
  6720. (forward-line)))))))))
  6721. (defun org-convert-to-odd-levels ()
  6722. "Convert an Org file with all levels allowed to one with odd levels.
  6723. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6724. level 5 etc."
  6725. (interactive)
  6726. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6727. (let ((outline-level 'org-outline-level)
  6728. (org-odd-levels-only nil) n)
  6729. (save-excursion
  6730. (goto-char (point-min))
  6731. (while (re-search-forward "^\\*\\*+ " nil t)
  6732. (setq n (- (length (match-string 0)) 2))
  6733. (while (>= (setq n (1- n)) 0)
  6734. (org-demote))
  6735. (end-of-line 1))))))
  6736. (defun org-convert-to-oddeven-levels ()
  6737. "Convert an Org file with only odd levels to one with odd/even levels.
  6738. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6739. file contains a section with an even level, conversion would
  6740. destroy the structure of the file. An error is signaled in this
  6741. case."
  6742. (interactive)
  6743. (goto-char (point-min))
  6744. ;; First check if there are no even levels
  6745. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6746. (org-show-set-visibility 'canonical)
  6747. (error "Not all levels are odd in this file. Conversion not possible"))
  6748. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6749. (let ((outline-regexp org-outline-regexp)
  6750. (outline-level 'org-outline-level)
  6751. (org-odd-levels-only nil) n)
  6752. (save-excursion
  6753. (goto-char (point-min))
  6754. (while (re-search-forward "^\\*\\*+ " nil t)
  6755. (setq n (/ (1- (length (match-string 0))) 2))
  6756. (while (>= (setq n (1- n)) 0)
  6757. (org-promote))
  6758. (end-of-line 1))))))
  6759. (defun org-tr-level (n)
  6760. "Make N odd if required."
  6761. (if org-odd-levels-only (1+ (/ n 2)) n))
  6762. ;;; Vertical tree motion, cutting and pasting of subtrees
  6763. (defun org-move-subtree-up (&optional arg)
  6764. "Move the current subtree up past ARG headlines of the same level."
  6765. (interactive "p")
  6766. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6767. (defun org-move-subtree-down (&optional arg)
  6768. "Move the current subtree down past ARG headlines of the same level."
  6769. (interactive "p")
  6770. (setq arg (prefix-numeric-value arg))
  6771. (org-preserve-local-variables
  6772. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6773. 'org-get-last-sibling))
  6774. (ins-point (make-marker))
  6775. (cnt (abs arg))
  6776. (col (current-column))
  6777. beg end txt folded)
  6778. ;; Select the tree
  6779. (org-back-to-heading)
  6780. (setq beg (point))
  6781. (save-match-data
  6782. (save-excursion (outline-end-of-heading)
  6783. (setq folded (org-invisible-p)))
  6784. (progn (org-end-of-subtree nil t)
  6785. (unless (eobp) (backward-char))))
  6786. (outline-next-heading)
  6787. (setq end (point))
  6788. (goto-char beg)
  6789. ;; Find insertion point, with error handling
  6790. (while (> cnt 0)
  6791. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6792. (goto-char beg)
  6793. (user-error "Cannot move past superior level or buffer limit"))
  6794. (setq cnt (1- cnt)))
  6795. (when (> arg 0)
  6796. ;; Moving forward - still need to move over subtree
  6797. (org-end-of-subtree t t)
  6798. (save-excursion
  6799. (org-back-over-empty-lines)
  6800. (or (bolp) (newline))))
  6801. (move-marker ins-point (point))
  6802. (setq txt (buffer-substring beg end))
  6803. (org-save-markers-in-region beg end)
  6804. (delete-region beg end)
  6805. (org-remove-empty-overlays-at beg)
  6806. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6807. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6808. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6809. (let ((bbb (point)))
  6810. (insert-before-markers txt)
  6811. (org-reinstall-markers-in-region bbb)
  6812. (move-marker ins-point bbb))
  6813. (or (bolp) (insert "\n"))
  6814. (goto-char ins-point)
  6815. (org-skip-whitespace)
  6816. (move-marker ins-point nil)
  6817. (if folded
  6818. (org-flag-subtree t)
  6819. (org-show-entry)
  6820. (org-show-children))
  6821. (org-clean-visibility-after-subtree-move)
  6822. ;; move back to the initial column we were at
  6823. (move-to-column col))))
  6824. (defvar org-subtree-clip ""
  6825. "Clipboard for cut and paste of subtrees.
  6826. This is actually only a copy of the kill, because we use the normal kill
  6827. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6828. (defvar org-subtree-clip-folded nil
  6829. "Was the last copied subtree folded?
  6830. This is used to fold the tree back after pasting.")
  6831. (defun org-cut-subtree (&optional n)
  6832. "Cut the current subtree into the clipboard.
  6833. With prefix arg N, cut this many sequential subtrees.
  6834. This is a short-hand for marking the subtree and then cutting it."
  6835. (interactive "p")
  6836. (org-copy-subtree n 'cut))
  6837. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6838. "Copy the current subtree into the clipboard.
  6839. With prefix arg N, copy this many sequential subtrees.
  6840. This is a short-hand for marking the subtree and then copying it.
  6841. If CUT is non-nil, actually cut the subtree.
  6842. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6843. of some markers in the region, even if CUT is non-nil. This is
  6844. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6845. (interactive "p")
  6846. (org-preserve-local-variables
  6847. (let (beg end folded (beg0 (point)))
  6848. (if (called-interactively-p 'any)
  6849. (org-back-to-heading nil) ; take what looks like a subtree
  6850. (org-back-to-heading t)) ; take what is really there
  6851. (setq beg (point))
  6852. (skip-chars-forward " \t\r\n")
  6853. (save-match-data
  6854. (if nosubtrees
  6855. (outline-next-heading)
  6856. (save-excursion (outline-end-of-heading)
  6857. (setq folded (org-invisible-p)))
  6858. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6859. (org-end-of-subtree t t)))
  6860. ;; Include the end of an inlinetask
  6861. (when (and (featurep 'org-inlinetask)
  6862. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6863. "END[ \t]*$")))
  6864. (end-of-line))
  6865. (setq end (point))
  6866. (goto-char beg0)
  6867. (when (> end beg)
  6868. (setq org-subtree-clip-folded folded)
  6869. (when (or cut force-store-markers)
  6870. (org-save-markers-in-region beg end))
  6871. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6872. (setq org-subtree-clip (current-kill 0))
  6873. (message "%s: Subtree(s) with %d characters"
  6874. (if cut "Cut" "Copied")
  6875. (length org-subtree-clip))))))
  6876. (defun org-paste-subtree (&optional level tree for-yank remove)
  6877. "Paste the clipboard as a subtree, with modification of headline level.
  6878. The entire subtree is promoted or demoted in order to match a new headline
  6879. level.
  6880. If the cursor is at the beginning of a headline, the same level as
  6881. that headline is used to paste the tree.
  6882. If not, the new level is derived from the *visible* headings
  6883. before and after the insertion point, and taken to be the inferior headline
  6884. level of the two. So if the previous visible heading is level 3 and the
  6885. next is level 4 (or vice versa), level 4 will be used for insertion.
  6886. This makes sure that the subtree remains an independent subtree and does
  6887. not swallow low level entries.
  6888. You can also force a different level, either by using a numeric prefix
  6889. argument, or by inserting the heading marker by hand. For example, if the
  6890. cursor is after \"*****\", then the tree will be shifted to level 5.
  6891. If optional TREE is given, use this text instead of the kill ring.
  6892. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6893. move back over whitespace before inserting, and move point to the end of
  6894. the inserted text when done.
  6895. When REMOVE is non-nil, remove the subtree from the clipboard."
  6896. (interactive "P")
  6897. (setq tree (or tree (and kill-ring (current-kill 0))))
  6898. (unless (org-kill-is-subtree-p tree)
  6899. (user-error
  6900. (substitute-command-keys
  6901. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6902. (org-with-limited-levels
  6903. (let* ((visp (not (org-invisible-p)))
  6904. (txt tree)
  6905. (old-level (if (string-match org-outline-regexp-bol txt)
  6906. (- (match-end 0) (match-beginning 0) 1)
  6907. -1))
  6908. (force-level
  6909. (cond
  6910. (level (prefix-numeric-value level))
  6911. ;; When point is after the stars in an otherwise empty
  6912. ;; headline, use the number of stars as the forced level.
  6913. ((and (org-match-line "^\\*+[ \t]*$")
  6914. (not (eq ?* (char-after))))
  6915. (org-outline-level))
  6916. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6917. (previous-level
  6918. (save-excursion
  6919. (org-previous-visible-heading 1)
  6920. (if (org-at-heading-p) (org-outline-level) 1)))
  6921. (next-level
  6922. (save-excursion
  6923. (if (org-at-heading-p) (org-outline-level)
  6924. (org-next-visible-heading 1)
  6925. (if (org-at-heading-p) (org-outline-level) 1))))
  6926. (new-level (or force-level (max previous-level next-level)))
  6927. (shift (if (or (= old-level -1)
  6928. (= new-level -1)
  6929. (= old-level new-level))
  6930. 0
  6931. (- new-level old-level)))
  6932. (delta (if (> shift 0) -1 1))
  6933. (func (if (> shift 0) #'org-demote #'org-promote))
  6934. (org-odd-levels-only nil)
  6935. beg end newend)
  6936. ;; Remove the forced level indicator.
  6937. (when (and force-level (not level))
  6938. (delete-region (line-beginning-position) (point)))
  6939. ;; Paste before the next visible heading or at end of buffer,
  6940. ;; unless point is at the beginning of a headline.
  6941. (unless (and (bolp) (org-at-heading-p))
  6942. (org-next-visible-heading 1)
  6943. (unless (bolp) (insert "\n")))
  6944. (setq beg (point))
  6945. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6946. (insert-before-markers txt)
  6947. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6948. (setq newend (point))
  6949. (org-reinstall-markers-in-region beg)
  6950. (setq end (point))
  6951. (goto-char beg)
  6952. (skip-chars-forward " \t\n\r")
  6953. (setq beg (point))
  6954. (when (and (org-invisible-p) visp)
  6955. (save-excursion (outline-show-heading)))
  6956. ;; Shift if necessary.
  6957. (unless (= shift 0)
  6958. (save-restriction
  6959. (narrow-to-region beg end)
  6960. (while (not (= shift 0))
  6961. (org-map-region func (point-min) (point-max))
  6962. (setq shift (+ delta shift)))
  6963. (goto-char (point-min))
  6964. (setq newend (point-max))))
  6965. (when (or for-yank (called-interactively-p 'interactive))
  6966. (message "Clipboard pasted as level %d subtree" new-level))
  6967. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6968. kill-ring
  6969. (equal org-subtree-clip (current-kill 0))
  6970. org-subtree-clip-folded)
  6971. ;; The tree was folded before it was killed/copied
  6972. (org-flag-subtree t))
  6973. (when for-yank (goto-char newend))
  6974. (when remove (pop kill-ring)))))
  6975. (defun org-kill-is-subtree-p (&optional txt)
  6976. "Check if the current kill is an outline subtree, or a set of trees.
  6977. Returns nil if kill does not start with a headline, or if the first
  6978. headline level is not the largest headline level in the tree.
  6979. So this will actually accept several entries of equal levels as well,
  6980. which is OK for `org-paste-subtree'.
  6981. If optional TXT is given, check this string instead of the current kill."
  6982. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6983. (re (org-get-limited-outline-regexp))
  6984. (^re (concat "^" re))
  6985. (start-level (and kill
  6986. (string-match
  6987. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6988. kill)
  6989. (- (match-end 2) (match-beginning 2) 1)))
  6990. (start (1+ (or (match-beginning 2) -1))))
  6991. (if (not start-level)
  6992. (progn
  6993. nil) ;; does not even start with a heading
  6994. (catch 'exit
  6995. (while (setq start (string-match ^re kill (1+ start)))
  6996. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6997. (throw 'exit nil)))
  6998. t))))
  6999. (defvar org-markers-to-move nil
  7000. "Markers that should be moved with a cut-and-paste operation.
  7001. Those markers are stored together with their positions relative to
  7002. the start of the region.")
  7003. (defun org-save-markers-in-region (beg end)
  7004. "Check markers in region.
  7005. If these markers are between BEG and END, record their position relative
  7006. to BEG, so that after moving the block of text, we can put the markers back
  7007. into place.
  7008. This function gets called just before an entry or tree gets cut from the
  7009. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7010. called immediately, to move the markers with the entries."
  7011. (setq org-markers-to-move nil)
  7012. (when (featurep 'org-clock)
  7013. (org-clock-save-markers-for-cut-and-paste beg end))
  7014. (when (featurep 'org-agenda)
  7015. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7016. (defun org-check-and-save-marker (marker beg end)
  7017. "Check if MARKER is between BEG and END.
  7018. If yes, remember the marker and the distance to BEG."
  7019. (when (and (marker-buffer marker)
  7020. (equal (marker-buffer marker) (current-buffer))
  7021. (>= marker beg) (< marker end))
  7022. (push (cons marker (- marker beg)) org-markers-to-move)))
  7023. (defun org-reinstall-markers-in-region (beg)
  7024. "Move all remembered markers to their position relative to BEG."
  7025. (dolist (x org-markers-to-move)
  7026. (move-marker (car x) (+ beg (cdr x))))
  7027. (setq org-markers-to-move nil))
  7028. (defun org-narrow-to-subtree ()
  7029. "Narrow buffer to the current subtree."
  7030. (interactive)
  7031. (save-excursion
  7032. (save-match-data
  7033. (org-with-limited-levels
  7034. (narrow-to-region
  7035. (progn (org-back-to-heading t) (point))
  7036. (progn (org-end-of-subtree t t)
  7037. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7038. (point)))))))
  7039. (defun org-toggle-narrow-to-subtree ()
  7040. "Narrow to the subtree at point or widen a narrowed buffer."
  7041. (interactive)
  7042. (if (buffer-narrowed-p)
  7043. (progn (widen) (message "Buffer widen"))
  7044. (org-narrow-to-subtree)
  7045. (message "Buffer narrowed to current subtree")))
  7046. (defun org-narrow-to-block ()
  7047. "Narrow buffer to the current block."
  7048. (interactive)
  7049. (let* ((case-fold-search t)
  7050. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7051. "^[ \t]*#\\+end_.*")))
  7052. (if blockp
  7053. (narrow-to-region (car blockp) (cdr blockp))
  7054. (user-error "Not in a block"))))
  7055. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7056. "Clone the task (subtree) at point N times.
  7057. The clones will be inserted as siblings.
  7058. In interactive use, the user will be prompted for the number of
  7059. clones to be produced. If the entry has a timestamp, the user
  7060. will also be prompted for a time shift, which may be a repeater
  7061. as used in time stamps, for example `+3d'. To disable this,
  7062. you can call the function with a universal prefix argument.
  7063. When a valid repeater is given and the entry contains any time
  7064. stamps, the clones will become a sequence in time, with time
  7065. stamps in the subtree shifted for each clone produced. If SHIFT
  7066. is nil or the empty string, time stamps will be left alone. The
  7067. ID property of the original subtree is removed.
  7068. In each clone, all the CLOCK entries will be removed. This
  7069. prevents Org from considering that the clocked times overlap.
  7070. If the original subtree did contain time stamps with a repeater,
  7071. the following will happen:
  7072. - the repeater will be removed in each clone
  7073. - an additional clone will be produced, with the current, unshifted
  7074. date(s) in the entry.
  7075. - the original entry will be placed *after* all the clones, with
  7076. repeater intact.
  7077. - the start days in the repeater in the original entry will be shifted
  7078. to past the last clone.
  7079. In this way you can spell out a number of instances of a repeating task,
  7080. and still retain the repeater to cover future instances of the task.
  7081. As described above, N+1 clones are produced when the original
  7082. subtree has a repeater. Setting N to 0, then, can be used to
  7083. remove the repeater from a subtree and create a shifted clone
  7084. with the original repeater."
  7085. (interactive "nNumber of clones to produce: ")
  7086. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7087. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7088. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7089. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7090. (shift
  7091. (or shift
  7092. (if (and (not (equal current-prefix-arg '(4)))
  7093. (save-excursion
  7094. (goto-char beg)
  7095. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7096. (read-from-minibuffer
  7097. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7098. ""))) ;No time shift
  7099. (doshift
  7100. (and (org-string-nw-p shift)
  7101. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7102. shift)
  7103. (user-error "Invalid shift specification %s" shift)))))
  7104. (goto-char end-of-tree)
  7105. (unless (bolp) (insert "\n"))
  7106. (let* ((end (point))
  7107. (template (buffer-substring beg end))
  7108. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7109. (shift-what (pcase (and doshift (match-string 2 shift))
  7110. (`nil nil)
  7111. ("h" 'hour)
  7112. ("d" 'day)
  7113. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7114. ("m" 'month)
  7115. ("y" 'year)
  7116. (_ (error "Unsupported time unit"))))
  7117. (nmin 1)
  7118. (nmax n)
  7119. (n-no-remove -1)
  7120. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7121. (idprop (org-entry-get beg "ID")))
  7122. (when (and doshift
  7123. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7124. template))
  7125. (delete-region beg end)
  7126. (setq end beg)
  7127. (setq nmin 0)
  7128. (setq nmax (1+ nmax))
  7129. (setq n-no-remove nmax))
  7130. (goto-char end)
  7131. (cl-loop for n from nmin to nmax do
  7132. (insert
  7133. ;; Prepare clone.
  7134. (with-temp-buffer
  7135. (insert template)
  7136. (org-mode)
  7137. (goto-char (point-min))
  7138. (org-show-subtree)
  7139. (and idprop (if org-clone-delete-id
  7140. (org-entry-delete nil "ID")
  7141. (org-id-get-create t)))
  7142. (unless (= n 0)
  7143. (while (re-search-forward org-clock-line-re nil t)
  7144. (delete-region (line-beginning-position)
  7145. (line-beginning-position 2)))
  7146. (goto-char (point-min))
  7147. (while (re-search-forward org-drawer-regexp nil t)
  7148. (org-remove-empty-drawer-at (point))))
  7149. (goto-char (point-min))
  7150. (when doshift
  7151. (while (re-search-forward org-ts-regexp-both nil t)
  7152. (org-timestamp-change (* n shift-n) shift-what))
  7153. (unless (= n n-no-remove)
  7154. (goto-char (point-min))
  7155. (while (re-search-forward org-ts-regexp nil t)
  7156. (save-excursion
  7157. (goto-char (match-beginning 0))
  7158. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7159. (delete-region (match-beginning 1) (match-end 1)))))))
  7160. (buffer-string)))))
  7161. (goto-char beg)))
  7162. ;;; Outline path
  7163. (defvar org-outline-path-cache nil
  7164. "Alist between buffer positions and outline paths.
  7165. It value is an alist (POSITION . PATH) where POSITION is the
  7166. buffer position at the beginning of an entry and PATH is a list
  7167. of strings describing the outline path for that entry, in reverse
  7168. order.")
  7169. (defun org--get-outline-path-1 (&optional use-cache)
  7170. "Return outline path to current headline.
  7171. Outline path is a list of strings, in reverse order. When
  7172. optional argument USE-CACHE is non-nil, make use of a cache. See
  7173. `org-get-outline-path' for details.
  7174. Assume buffer is widened and point is on a headline."
  7175. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7176. (let ((p (point))
  7177. (heading (let ((case-fold-search nil))
  7178. (looking-at org-complex-heading-regexp)
  7179. (if (not (match-end 4)) ""
  7180. ;; Remove statistics cookies.
  7181. (org-trim
  7182. (org-link-display-format
  7183. (replace-regexp-in-string
  7184. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7185. (match-string-no-properties 4))))))))
  7186. (if (org-up-heading-safe)
  7187. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7188. (when use-cache
  7189. (push (cons p path) org-outline-path-cache))
  7190. path)
  7191. ;; This is a new root node. Since we assume we are moving
  7192. ;; forward, we can drop previous cache so as to limit number
  7193. ;; of associations there.
  7194. (let ((path (list heading)))
  7195. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7196. path)))))
  7197. (defun org-get-outline-path (&optional with-self use-cache)
  7198. "Return the outline path to the current entry.
  7199. An outline path is a list of ancestors for current headline, as
  7200. a list of strings. Statistics cookies are removed and links are
  7201. replaced with their description, if any, or their path otherwise.
  7202. When optional argument WITH-SELF is non-nil, the path also
  7203. includes the current headline.
  7204. When optional argument USE-CACHE is non-nil, cache outline paths
  7205. between calls to this function so as to avoid backtracking. This
  7206. argument is useful when planning to find more than one outline
  7207. path in the same document. In that case, there are two
  7208. conditions to satisfy:
  7209. - `org-outline-path-cache' is set to nil before starting the
  7210. process;
  7211. - outline paths are computed by increasing buffer positions."
  7212. (org-with-wide-buffer
  7213. (and (or (and with-self (org-back-to-heading t))
  7214. (org-up-heading-safe))
  7215. (reverse (org--get-outline-path-1 use-cache)))))
  7216. (defun org-format-outline-path (path &optional width prefix separator)
  7217. "Format the outline path PATH for display.
  7218. WIDTH is the maximum number of characters that is available.
  7219. PREFIX is a prefix to be included in the returned string,
  7220. such as the file name.
  7221. SEPARATOR is inserted between the different parts of the path,
  7222. the default is \"/\"."
  7223. (setq width (or width 79))
  7224. (setq path (delq nil path))
  7225. (unless (> width 0)
  7226. (user-error "Argument `width' must be positive"))
  7227. (setq separator (or separator "/"))
  7228. (let* ((org-odd-levels-only nil)
  7229. (fpath (concat
  7230. prefix (and prefix path separator)
  7231. (mapconcat
  7232. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7233. (cl-loop for head in path
  7234. for n from 0
  7235. collect (org-add-props
  7236. head nil 'face
  7237. (nth (% n org-n-level-faces) org-level-faces)))
  7238. separator))))
  7239. (when (> (length fpath) width)
  7240. (if (< width 7)
  7241. ;; It's unlikely that `width' will be this small, but don't
  7242. ;; waste characters by adding ".." if it is.
  7243. (setq fpath (substring fpath 0 width))
  7244. (setf (substring fpath (- width 2)) "..")))
  7245. fpath))
  7246. (defun org-display-outline-path (&optional file current separator just-return-string)
  7247. "Display the current outline path in the echo area.
  7248. If FILE is non-nil, prepend the output with the file name.
  7249. If CURRENT is non-nil, append the current heading to the output.
  7250. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7251. the different parts of the path and defaults to \"/\".
  7252. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7253. (interactive "P")
  7254. (let* (case-fold-search
  7255. (bfn (buffer-file-name (buffer-base-buffer)))
  7256. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7257. res)
  7258. (when current (setq path (append path
  7259. (save-excursion
  7260. (org-back-to-heading t)
  7261. (when (looking-at org-complex-heading-regexp)
  7262. (list (match-string 4)))))))
  7263. (setq res
  7264. (org-format-outline-path
  7265. path
  7266. (1- (frame-width))
  7267. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7268. separator))
  7269. (add-face-text-property 0 (length res)
  7270. `(:height ,(face-attribute 'default :height))
  7271. nil res)
  7272. (if just-return-string
  7273. res
  7274. (org-unlogged-message "%s" res))))
  7275. ;;; Outline Sorting
  7276. (defun org-sort (&optional with-case)
  7277. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7278. Optional argument WITH-CASE means sort case-sensitively."
  7279. (interactive "P")
  7280. (org-call-with-arg
  7281. (cond ((org-at-table-p) #'org-table-sort-lines)
  7282. ((org-at-item-p) #'org-sort-list)
  7283. (t #'org-sort-entries))
  7284. with-case))
  7285. (defun org-sort-remove-invisible (s)
  7286. "Remove emphasis markers and any invisible property from string S.
  7287. Assume S may contain only objects."
  7288. ;; org-element-interpret-data clears any text property, including
  7289. ;; invisible part.
  7290. (org-element-interpret-data
  7291. (let ((tree (org-element-parse-secondary-string
  7292. s (org-element-restriction 'paragraph))))
  7293. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  7294. (lambda (o)
  7295. (pcase (org-element-type o)
  7296. ;; Terminal object. Replace it with its value.
  7297. ((or `code `verbatim)
  7298. (let ((new (org-element-property :value o)))
  7299. (org-element-insert-before new o)
  7300. (org-element-put-property
  7301. new :post-blank (org-element-property :post-blank o))))
  7302. ;; Non-terminal objects. Splice contents.
  7303. (type
  7304. (let ((contents
  7305. (or (org-element-contents o)
  7306. (and (eq type 'link)
  7307. (list (org-element-property :raw-link o)))))
  7308. (c nil))
  7309. (while contents
  7310. (setq c (pop contents))
  7311. (org-element-insert-before c o))
  7312. (org-element-put-property
  7313. c :post-blank (org-element-property :post-blank o)))))
  7314. (org-element-extract-element o)))
  7315. ;; Return modified tree.
  7316. tree)))
  7317. (defvar org-after-sorting-entries-or-items-hook nil
  7318. "Hook that is run after a bunch of entries or items have been sorted.
  7319. When children are sorted, the cursor is in the parent line when this
  7320. hook gets called. When a region or a plain list is sorted, the cursor
  7321. will be in the first entry of the sorted region/list.")
  7322. (defun org-sort-entries
  7323. (&optional with-case sorting-type getkey-func compare-func property
  7324. interactive?)
  7325. "Sort entries on a certain level of an outline tree.
  7326. If there is an active region, the entries in the region are sorted.
  7327. Else, if the cursor is before the first entry, sort the top-level items.
  7328. Else, the children of the entry at point are sorted.
  7329. Sorting can be alphabetically, numerically, by date/time as given by
  7330. a time stamp, by a property, by priority order, or by a custom function.
  7331. The command prompts for the sorting type unless it has been given to the
  7332. function through the SORTING-TYPE argument, which needs to be a character,
  7333. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7334. the precise meaning of each character:
  7335. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7336. c By creation time, which is assumed to be the first inactive time stamp
  7337. at the beginning of a line.
  7338. d By deadline date/time.
  7339. k By clocking time.
  7340. n Numerically, by converting the beginning of the entry/item to a number.
  7341. o By order of TODO keywords.
  7342. p By priority according to the cookie.
  7343. r By the value of a property.
  7344. s By scheduled date/time.
  7345. t By date/time, either the first active time stamp in the entry, or, if
  7346. none exist, by the first inactive one.
  7347. Capital letters will reverse the sort order.
  7348. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7349. called with point at the beginning of the record. It must return a
  7350. value that is compatible with COMPARE-FUNC, the function used to
  7351. compare entries.
  7352. Comparing entries ignores case by default. However, with an optional argument
  7353. WITH-CASE, the sorting considers case as well.
  7354. Sorting is done against the visible part of the headlines, it ignores hidden
  7355. links.
  7356. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7357. A non-nil value for INTERACTIVE? is used to signal that this
  7358. function is being called interactively."
  7359. (interactive (list current-prefix-arg nil nil nil nil t))
  7360. (let ((case-func (if with-case 'identity 'downcase))
  7361. start beg end stars re re2
  7362. txt what tmp)
  7363. ;; Find beginning and end of region to sort
  7364. (cond
  7365. ((org-region-active-p)
  7366. ;; we will sort the region
  7367. (setq end (region-end)
  7368. what "region")
  7369. (goto-char (region-beginning))
  7370. (unless (org-at-heading-p) (outline-next-heading))
  7371. (setq start (point)))
  7372. ((or (org-at-heading-p)
  7373. (ignore-errors (progn (org-back-to-heading) t)))
  7374. ;; we will sort the children of the current headline
  7375. (org-back-to-heading)
  7376. (setq start (point)
  7377. end (progn (org-end-of-subtree t t)
  7378. (or (bolp) (insert "\n"))
  7379. (when (>= (org-back-over-empty-lines) 1)
  7380. (forward-line 1))
  7381. (point))
  7382. what "children")
  7383. (goto-char start)
  7384. (outline-show-subtree)
  7385. (outline-next-heading))
  7386. (t
  7387. ;; we will sort the top-level entries in this file
  7388. (goto-char (point-min))
  7389. (or (org-at-heading-p) (outline-next-heading))
  7390. (setq start (point))
  7391. (goto-char (point-max))
  7392. (beginning-of-line 1)
  7393. (when (looking-at ".*?\\S-")
  7394. ;; File ends in a non-white line
  7395. (end-of-line 1)
  7396. (insert "\n"))
  7397. (setq end (point-max))
  7398. (setq what "top-level")
  7399. (goto-char start)
  7400. (org-show-all '(headings drawers blocks))))
  7401. (setq beg (point))
  7402. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7403. (looking-at "\\(\\*+\\)")
  7404. (setq stars (match-string 1)
  7405. re (concat "^" (regexp-quote stars) " +")
  7406. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7407. txt (buffer-substring beg end))
  7408. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7409. (when (and (not (equal stars "*")) (string-match re2 txt))
  7410. (user-error "Region to sort contains a level above the first entry"))
  7411. (unless sorting-type
  7412. (message
  7413. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7414. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7415. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7416. what)
  7417. (setq sorting-type (read-char-exclusive)))
  7418. (unless getkey-func
  7419. (and (= (downcase sorting-type) ?f)
  7420. (setq getkey-func
  7421. (or (and interactive?
  7422. (org-read-function
  7423. "Function for extracting keys: "))
  7424. (error "Missing key extractor")))))
  7425. (and (= (downcase sorting-type) ?r)
  7426. (not property)
  7427. (setq property
  7428. (completing-read "Property: "
  7429. (mapcar #'list (org-buffer-property-keys t))
  7430. nil t)))
  7431. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7432. (message "Sorting entries...")
  7433. (save-restriction
  7434. (narrow-to-region start end)
  7435. (let ((restore-clock?
  7436. ;; The clock marker is lost when using `sort-subr'; mark
  7437. ;; the clock with temporary `:org-clock-marker-backup'
  7438. ;; text property.
  7439. (when (and (eq (org-clocking-buffer) (current-buffer))
  7440. (<= start (marker-position org-clock-marker))
  7441. (>= end (marker-position org-clock-marker)))
  7442. (with-silent-modifications
  7443. (put-text-property (1- org-clock-marker) org-clock-marker
  7444. :org-clock-marker-backup t))
  7445. t))
  7446. (dcst (downcase sorting-type))
  7447. (case-fold-search nil)
  7448. (now (current-time)))
  7449. (org-preserve-local-variables
  7450. (sort-subr
  7451. (/= dcst sorting-type)
  7452. ;; This function moves to the beginning character of the
  7453. ;; "record" to be sorted.
  7454. (lambda nil
  7455. (if (re-search-forward re nil t)
  7456. (goto-char (match-beginning 0))
  7457. (goto-char (point-max))))
  7458. ;; This function moves to the last character of the "record" being
  7459. ;; sorted.
  7460. (lambda nil
  7461. (save-match-data
  7462. (condition-case nil
  7463. (outline-forward-same-level 1)
  7464. (error
  7465. (goto-char (point-max))))))
  7466. ;; This function returns the value that gets sorted against.
  7467. (lambda ()
  7468. (cond
  7469. ((= dcst ?n)
  7470. (string-to-number
  7471. (org-sort-remove-invisible (org-get-heading t t t t))))
  7472. ((= dcst ?a)
  7473. (funcall case-func
  7474. (org-sort-remove-invisible (org-get-heading t t t t))))
  7475. ((= dcst ?k)
  7476. (or (get-text-property (point) :org-clock-minutes) 0))
  7477. ((= dcst ?t)
  7478. (let ((end (save-excursion (outline-next-heading) (point))))
  7479. (if (or (re-search-forward org-ts-regexp end t)
  7480. (re-search-forward org-ts-regexp-both end t))
  7481. (org-time-string-to-seconds (match-string 0))
  7482. (float-time now))))
  7483. ((= dcst ?c)
  7484. (let ((end (save-excursion (outline-next-heading) (point))))
  7485. (if (re-search-forward
  7486. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7487. end t)
  7488. (org-time-string-to-seconds (match-string 0))
  7489. (float-time now))))
  7490. ((= dcst ?s)
  7491. (let ((end (save-excursion (outline-next-heading) (point))))
  7492. (if (re-search-forward org-scheduled-time-regexp end t)
  7493. (org-time-string-to-seconds (match-string 1))
  7494. (float-time now))))
  7495. ((= dcst ?d)
  7496. (let ((end (save-excursion (outline-next-heading) (point))))
  7497. (if (re-search-forward org-deadline-time-regexp end t)
  7498. (org-time-string-to-seconds (match-string 1))
  7499. (float-time now))))
  7500. ((= dcst ?p)
  7501. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7502. (string-to-char (match-string 2))
  7503. org-priority-default))
  7504. ((= dcst ?r)
  7505. (or (org-entry-get nil property) ""))
  7506. ((= dcst ?o)
  7507. (when (looking-at org-complex-heading-regexp)
  7508. (let* ((m (match-string 2))
  7509. (s (if (member m org-done-keywords) '- '+)))
  7510. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7511. ((= dcst ?f)
  7512. (if getkey-func
  7513. (progn
  7514. (setq tmp (funcall getkey-func))
  7515. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7516. tmp)
  7517. (error "Invalid key function `%s'" getkey-func)))
  7518. (t (error "Invalid sorting type `%c'" sorting-type))))
  7519. nil
  7520. (cond
  7521. ((= dcst ?a) 'org-string-collate-lessp)
  7522. ((= dcst ?f)
  7523. (or compare-func
  7524. (and interactive?
  7525. (org-read-function
  7526. (concat "Function for comparing keys "
  7527. "(empty for default `sort-subr' predicate): ")
  7528. 'allow-empty))))
  7529. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7530. (org-cycle-hide-drawers 'all)
  7531. (when restore-clock?
  7532. (move-marker org-clock-marker
  7533. (1+ (next-single-property-change
  7534. start :org-clock-marker-backup)))
  7535. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7536. '(:org-clock-marker-backup t)))))
  7537. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7538. (message "Sorting entries...done")))
  7539. (defun org-contextualize-keys (alist contexts)
  7540. "Return valid elements in ALIST depending on CONTEXTS.
  7541. `org-agenda-custom-commands' or `org-capture-templates' are the
  7542. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7543. or `org-capture-templates-contexts' are the associated contexts
  7544. definitions."
  7545. (let ((contexts
  7546. ;; normalize contexts
  7547. (mapcar
  7548. (lambda(c) (cond ((listp (cadr c))
  7549. (list (car c) (car c) (nth 1 c)))
  7550. ((string= "" (cadr c))
  7551. (list (car c) (car c) (nth 2 c)))
  7552. (t c)))
  7553. contexts))
  7554. (a alist) r s)
  7555. ;; loop over all commands or templates
  7556. (dolist (c a)
  7557. (let (vrules repl)
  7558. (cond
  7559. ((not (assoc (car c) contexts))
  7560. (push c r))
  7561. ((and (assoc (car c) contexts)
  7562. (setq vrules (org-contextualize-validate-key
  7563. (car c) contexts)))
  7564. (mapc (lambda (vr)
  7565. (unless (equal (car vr) (cadr vr))
  7566. (setq repl vr)))
  7567. vrules)
  7568. (if (not repl) (push c r)
  7569. (push (cadr repl) s)
  7570. (push
  7571. (cons (car c)
  7572. (cdr (or (assoc (cadr repl) alist)
  7573. (error "Undefined key `%s' as contextual replacement for `%s'"
  7574. (cadr repl) (car c)))))
  7575. r))))))
  7576. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7577. (delq
  7578. nil
  7579. (delete-dups
  7580. (mapcar (lambda (x)
  7581. (let ((tpl (car x)))
  7582. (unless (delq
  7583. nil
  7584. (mapcar (lambda (y)
  7585. (equal y tpl))
  7586. s))
  7587. x)))
  7588. (reverse r))))))
  7589. (defun org-contextualize-validate-key (key contexts)
  7590. "Check CONTEXTS for agenda or capture KEY."
  7591. (let (res)
  7592. (dolist (r contexts)
  7593. (dolist (rr (car (last r)))
  7594. (when
  7595. (and (equal key (car r))
  7596. (if (functionp rr) (funcall rr)
  7597. (or (and (eq (car rr) 'in-file)
  7598. (buffer-file-name)
  7599. (string-match (cdr rr) (buffer-file-name)))
  7600. (and (eq (car rr) 'in-mode)
  7601. (string-match (cdr rr) (symbol-name major-mode)))
  7602. (and (eq (car rr) 'in-buffer)
  7603. (string-match (cdr rr) (buffer-name)))
  7604. (when (and (eq (car rr) 'not-in-file)
  7605. (buffer-file-name))
  7606. (not (string-match (cdr rr) (buffer-file-name))))
  7607. (when (eq (car rr) 'not-in-mode)
  7608. (not (string-match (cdr rr) (symbol-name major-mode))))
  7609. (when (eq (car rr) 'not-in-buffer)
  7610. (not (string-match (cdr rr) (buffer-name)))))))
  7611. (push r res))))
  7612. (delete-dups (delq nil res))))
  7613. ;; Defined to provide a value for defcustom, since there is no
  7614. ;; string-collate-greaterp in Emacs.
  7615. (defun org-string-collate-greaterp (s1 s2)
  7616. "Return non-nil if S1 is greater than S2 in collation order."
  7617. (not (org-string-collate-lessp s1 s2)))
  7618. ;;;###autoload
  7619. (defun org-run-like-in-org-mode (cmd)
  7620. "Run a command, pretending that the current buffer is in Org mode.
  7621. This will temporarily bind local variables that are typically bound in
  7622. Org mode to the values they have in Org mode, and then interactively
  7623. call CMD."
  7624. (org-load-modules-maybe)
  7625. (let (binds)
  7626. (dolist (var (org-get-local-variables))
  7627. (when (or (not (boundp (car var)))
  7628. (eq (symbol-value (car var))
  7629. (default-value (car var))))
  7630. (push (list (car var) `(quote ,(cadr var))) binds)))
  7631. (eval `(let ,binds
  7632. (call-interactively (quote ,cmd))))))
  7633. (defun org-get-category (&optional pos force-refresh)
  7634. "Get the category applying to position POS."
  7635. (save-match-data
  7636. (when force-refresh (org-refresh-category-properties))
  7637. (let ((pos (or pos (point))))
  7638. (or (get-text-property pos 'org-category)
  7639. (progn (org-refresh-category-properties)
  7640. (get-text-property pos 'org-category))))))
  7641. ;;; Refresh properties
  7642. (defun org-refresh-properties (dprop tprop)
  7643. "Refresh buffer text properties.
  7644. DPROP is the drawer property and TPROP is either the
  7645. corresponding text property to set, or an alist with each element
  7646. being a text property (as a symbol) and a function to apply to
  7647. the value of the drawer property."
  7648. (let* ((case-fold-search t)
  7649. (inhibit-read-only t)
  7650. (inherit? (org-property-inherit-p dprop))
  7651. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7652. (global-or-keyword (and inherit?
  7653. (org--property-global-or-keyword-value dprop nil))))
  7654. (with-silent-modifications
  7655. (org-with-point-at 1
  7656. ;; Set global and keyword based values to the whole buffer.
  7657. (when global-or-keyword
  7658. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7659. ;; Set values based on property-drawers throughout the document.
  7660. (while (re-search-forward property-re nil t)
  7661. (when (org-at-property-p)
  7662. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7663. (outline-next-heading))))))
  7664. (defun org-refresh-property (tprop p &optional inherit)
  7665. "Refresh the buffer text property TPROP from the drawer property P.
  7666. The refresh happens only for the current entry, or the whole
  7667. sub-tree if optional argument INHERIT is non-nil.
  7668. If point is before first headline, the function applies to the
  7669. part before the first headline. In that particular case, when
  7670. optional argument INHERIT is non-nil, it refreshes properties for
  7671. the whole buffer."
  7672. (save-excursion
  7673. (org-back-to-heading-or-point-min t)
  7674. (let ((start (point))
  7675. (end (save-excursion
  7676. (cond ((and inherit (org-before-first-heading-p))
  7677. (point-max))
  7678. (inherit
  7679. (org-end-of-subtree t t))
  7680. ((outline-next-heading))
  7681. ((point-max))))))
  7682. (if (symbolp tprop)
  7683. ;; TPROP is a text property symbol.
  7684. (put-text-property start end tprop p)
  7685. ;; TPROP is an alist with (property . function) elements.
  7686. (pcase-dolist (`(,prop . ,f) tprop)
  7687. (put-text-property start end prop (funcall f p)))))))
  7688. (defun org-refresh-category-properties ()
  7689. "Refresh category text properties in the buffer."
  7690. (let ((case-fold-search t)
  7691. (inhibit-read-only t)
  7692. (default-category
  7693. (cond ((null org-category)
  7694. (if buffer-file-name
  7695. (file-name-sans-extension
  7696. (file-name-nondirectory buffer-file-name))
  7697. "???"))
  7698. ((symbolp org-category) (symbol-name org-category))
  7699. (t org-category))))
  7700. (with-silent-modifications
  7701. (org-with-wide-buffer
  7702. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7703. ;; keyword. If none is found, fall-back to `org-category' or
  7704. ;; buffer file name, or set it by the document property drawer.
  7705. (put-text-property
  7706. (point-min) (point-max)
  7707. 'org-category
  7708. (catch 'buffer-category
  7709. (goto-char (point-max))
  7710. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7711. (let ((element (org-element-at-point)))
  7712. (when (eq (org-element-type element) 'keyword)
  7713. (throw 'buffer-category
  7714. (org-element-property :value element)))))
  7715. default-category))
  7716. ;; Set categories from the document property drawer or
  7717. ;; property drawers in the outline. If category is found in
  7718. ;; the property drawer for the whole buffer that value
  7719. ;; overrides the keyword-based value set above.
  7720. (goto-char (point-min))
  7721. (let ((regexp (org-re-property "CATEGORY")))
  7722. (while (re-search-forward regexp nil t)
  7723. (let ((value (match-string-no-properties 3)))
  7724. (when (org-at-property-p)
  7725. (put-text-property
  7726. (save-excursion (org-back-to-heading-or-point-min t))
  7727. (save-excursion (if (org-before-first-heading-p)
  7728. (point-max)
  7729. (org-end-of-subtree t t)))
  7730. 'org-category
  7731. value)))))))))
  7732. (defun org-refresh-stats-properties ()
  7733. "Refresh stats text properties in the buffer."
  7734. (with-silent-modifications
  7735. (org-with-point-at 1
  7736. (let ((regexp (concat org-outline-regexp-bol
  7737. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7738. (while (re-search-forward regexp nil t)
  7739. (let* ((numerator (string-to-number (match-string 1)))
  7740. (denominator (and (match-end 2)
  7741. (string-to-number (match-string 2))))
  7742. (stats (cond ((not denominator) numerator) ;percent
  7743. ((= denominator 0) 0)
  7744. (t (/ (* numerator 100) denominator)))))
  7745. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7746. 'org-stats stats)))))))
  7747. (defun org-refresh-effort-properties ()
  7748. "Refresh effort properties."
  7749. (org-refresh-properties
  7750. org-effort-property
  7751. '((effort . identity)
  7752. (effort-minutes . org-duration-to-minutes))))
  7753. (defun org-find-file-at-mouse (ev)
  7754. "Open file link or URL at mouse."
  7755. (interactive "e")
  7756. (mouse-set-point ev)
  7757. (org-open-at-point 'in-emacs))
  7758. (defun org-open-at-mouse (ev)
  7759. "Open file link or URL at mouse.
  7760. See the docstring of `org-open-file' for details."
  7761. (interactive "e")
  7762. (mouse-set-point ev)
  7763. (when (eq major-mode 'org-agenda-mode)
  7764. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7765. (org-open-at-point))
  7766. (defvar org-window-config-before-follow-link nil
  7767. "The window configuration before following a link.
  7768. This is saved in case the need arises to restore it.")
  7769. (defun org--file-default-apps ()
  7770. "Return the default applications for this operating system."
  7771. (pcase system-type
  7772. (`darwin org-file-apps-macos)
  7773. (`windows-nt org-file-apps-windowsnt)
  7774. (_ org-file-apps-gnu)))
  7775. (defun org--file-apps-entry-dlink-p (entry)
  7776. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7777. It assumes that is the case when the entry uses a regular
  7778. expression which has at least one grouping construct and the
  7779. action is either a Lisp form or a command string containing
  7780. \"%1\", i.e., using at least one subexpression match as
  7781. a parameter."
  7782. (pcase entry
  7783. (`(,selector . ,action)
  7784. (and (stringp selector)
  7785. (> (regexp-opt-depth selector) 0)
  7786. (or (and (stringp action)
  7787. (string-match "%[0-9]" action))
  7788. (consp action))))
  7789. (_ nil)))
  7790. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7791. "Convert extensions to regular expressions in the cars of LIST.
  7792. Also, weed out any non-string entries, because the return value
  7793. is used only for regexp matching.
  7794. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7795. point to the symbol `emacs', indicating that the file should be
  7796. opened in Emacs."
  7797. (append
  7798. (delq nil
  7799. (mapcar (lambda (x)
  7800. (unless (not (stringp (car x)))
  7801. (if (string-match "\\W" (car x))
  7802. x
  7803. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7804. list))
  7805. (when add-auto-mode
  7806. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7807. ;;;###autoload
  7808. (defun org-open-file (path &optional in-emacs line search)
  7809. "Open the file at PATH.
  7810. First, this expands any special file name abbreviations. Then the
  7811. configuration variable `org-file-apps' is checked if it contains an
  7812. entry for this file type, and if yes, the corresponding command is launched.
  7813. If no application is found, Emacs simply visits the file.
  7814. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7815. With a double \\[universal-argument] \\[universal-argument] \
  7816. prefix arg, Org tries to avoid opening in Emacs
  7817. and to use an external application to visit the file.
  7818. Optional LINE specifies a line to go to, optional SEARCH a string
  7819. to search for. If LINE or SEARCH is given, the file will be
  7820. opened in Emacs, unless an entry from `org-file-apps' that makes
  7821. use of groups in a regexp matches.
  7822. If you want to change the way frames are used when following a
  7823. link, please customize `org-link-frame-setup'.
  7824. If the file does not exist, throw an error."
  7825. (let* ((file (if (equal path "") buffer-file-name
  7826. (substitute-in-file-name (expand-file-name path))))
  7827. (file-apps (append org-file-apps (org--file-default-apps)))
  7828. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7829. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7830. file-apps))
  7831. (remp (and (assq 'remote apps) (file-remote-p file)))
  7832. (dirp (unless remp (file-directory-p file)))
  7833. (file (if (and dirp org-open-directory-means-index-dot-org)
  7834. (concat (file-name-as-directory file) "index.org")
  7835. file))
  7836. (a-m-a-p (assq 'auto-mode apps))
  7837. (dfile (downcase file))
  7838. ;; Reconstruct the original link from the PATH, LINE and
  7839. ;; SEARCH args.
  7840. (link (cond (line (concat file "::" (number-to-string line)))
  7841. (search (concat file "::" search))
  7842. (t file)))
  7843. (dlink (downcase link))
  7844. (ext
  7845. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7846. (match-string 1 dfile)))
  7847. (save-position-maybe
  7848. (let ((old-buffer (current-buffer))
  7849. (old-pos (point))
  7850. (old-mode major-mode))
  7851. (lambda ()
  7852. (and (derived-mode-p 'org-mode)
  7853. (eq old-mode 'org-mode)
  7854. (or (not (eq old-buffer (current-buffer)))
  7855. (not (eq old-pos (point))))
  7856. (org-mark-ring-push old-pos old-buffer)))))
  7857. cmd link-match-data)
  7858. (cond
  7859. ((member in-emacs '((16) system))
  7860. (setq cmd (cdr (assq 'system apps))))
  7861. (in-emacs (setq cmd 'emacs))
  7862. (t
  7863. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7864. (and dirp (cdr (assq 'directory apps)))
  7865. ;; First, try matching against apps-dlink if we
  7866. ;; get a match here, store the match data for
  7867. ;; later.
  7868. (let ((match (assoc-default dlink apps-dlink
  7869. 'string-match)))
  7870. (if match
  7871. (progn (setq link-match-data (match-data))
  7872. match)
  7873. (progn (setq in-emacs (or in-emacs line search))
  7874. nil))) ; if we have no match in apps-dlink,
  7875. ; always open the file in emacs if line or search
  7876. ; is given (for backwards compatibility)
  7877. (assoc-default dfile
  7878. (org--file-apps-regexp-alist apps a-m-a-p)
  7879. 'string-match)
  7880. (cdr (assoc ext apps))
  7881. (cdr (assq t apps))))))
  7882. (when (eq cmd 'system)
  7883. (setq cmd (cdr (assq 'system apps))))
  7884. (when (eq cmd 'default)
  7885. (setq cmd (cdr (assoc t apps))))
  7886. (when (eq cmd 'mailcap)
  7887. (require 'mailcap)
  7888. (mailcap-parse-mailcaps)
  7889. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7890. (command (mailcap-mime-info mime-type)))
  7891. (if (stringp command)
  7892. (setq cmd command)
  7893. (setq cmd 'emacs))))
  7894. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7895. (not (file-exists-p file))
  7896. (not org-open-non-existing-files))
  7897. (user-error "No such file: %s" file))
  7898. (cond
  7899. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7900. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7901. (while (string-match "['\"]%s['\"]" cmd)
  7902. (setq cmd (replace-match "%s" t t cmd)))
  7903. (setq cmd (replace-regexp-in-string
  7904. "%s"
  7905. (shell-quote-argument (convert-standard-filename file))
  7906. cmd
  7907. nil t))
  7908. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7909. (save-match-data
  7910. (let ((match-index 1)
  7911. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7912. (set-match-data link-match-data)
  7913. (while (<= match-index number-of-groups)
  7914. (let ((regex (concat "%" (number-to-string match-index)))
  7915. (replace-with (match-string match-index dlink)))
  7916. (while (string-match regex cmd)
  7917. (setq cmd (replace-match replace-with t t cmd))))
  7918. (setq match-index (+ match-index 1)))))
  7919. (save-window-excursion
  7920. (message "Running %s...done" cmd)
  7921. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7922. ;; and exit immediately. Use pipe connnection type instead of pty to
  7923. ;; avoid killing children processes with SIGHUP when temporary terminal
  7924. ;; session is finished.
  7925. ;;
  7926. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7927. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7928. ;; error messages.
  7929. (let ((process-connection-type nil))
  7930. (start-process-shell-command cmd nil cmd))
  7931. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7932. ((or (stringp cmd)
  7933. (eq cmd 'emacs))
  7934. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7935. (widen)
  7936. (cond (line (org-goto-line line)
  7937. (when (derived-mode-p 'org-mode) (org-reveal)))
  7938. (search (condition-case err
  7939. (org-link-search search)
  7940. ;; Save position before error-ing out so user
  7941. ;; can easily move back to the original buffer.
  7942. (error (funcall save-position-maybe)
  7943. (error (nth 1 err)))))))
  7944. ((functionp cmd)
  7945. (save-match-data
  7946. (set-match-data link-match-data)
  7947. (condition-case nil
  7948. (funcall cmd file link)
  7949. ;; FIXME: Remove this check when most default installations
  7950. ;; of Emacs have at least Org 9.0.
  7951. ((debug wrong-number-of-arguments wrong-type-argument
  7952. invalid-function)
  7953. (user-error "Please see Org News for version 9.0 about \
  7954. `org-file-apps'--Lisp error: %S" cmd)))))
  7955. ((consp cmd)
  7956. ;; FIXME: Remove this check when most default installations of
  7957. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7958. ;; fall back to `org-link-frame-setup' for an old usage of
  7959. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7960. (user-error "Please see Org News for version 9.0 about \
  7961. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7962. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7963. (funcall save-position-maybe)))
  7964. ;;;###autoload
  7965. (defun org-open-at-point-global ()
  7966. "Follow a link or a time-stamp like Org mode does.
  7967. Also follow links and emails as seen by `thing-at-point'.
  7968. This command can be called in any mode to follow an external
  7969. link or a time-stamp that has Org mode syntax. Its behavior
  7970. is undefined when called on internal links like fuzzy links.
  7971. Raise a user error when there is nothing to follow."
  7972. (interactive)
  7973. (let ((tap-url (thing-at-point 'url))
  7974. (tap-email (thing-at-point 'email)))
  7975. (cond ((org-in-regexp org-link-any-re)
  7976. (org-link-open-from-string (match-string-no-properties 0)))
  7977. ((or (org-in-regexp org-ts-regexp-both nil t)
  7978. (org-in-regexp org-tsr-regexp-both nil t))
  7979. (org-follow-timestamp-link))
  7980. (tap-url (org-link-open-from-string tap-url))
  7981. (tap-email (org-link-open-from-string
  7982. (concat "mailto:" tap-email)))
  7983. (t (user-error "No link found")))))
  7984. (defvar org-open-at-point-functions nil
  7985. "Hook that is run when following a link at point.
  7986. Functions in this hook must return t if they identify and follow
  7987. a link at point. If they don't find anything interesting at point,
  7988. they must return nil.")
  7989. (defun org-open-at-point (&optional arg)
  7990. "Open link, timestamp, footnote or tags at point.
  7991. When point is on a link, follow it. Normally, files will be
  7992. opened by an appropriate application. If the optional prefix
  7993. argument ARG is non-nil, Emacs will visit the file. With
  7994. a double prefix argument, try to open outside of Emacs, in the
  7995. application the system uses for this file type.
  7996. When point is on a timestamp, open the agenda at the day
  7997. specified.
  7998. When point is a footnote definition, move to the first reference
  7999. found. If it is on a reference, move to the associated
  8000. definition.
  8001. When point is on a headline, display a list of every link in the
  8002. entry, so it is possible to pick one, or all, of them. If point
  8003. is on a tag, call `org-tags-view' instead.
  8004. On top of syntactically correct links, this function also tries
  8005. to open links and time-stamps in comments, node properties, and
  8006. keywords if point is on something looking like a timestamp or
  8007. a link."
  8008. (interactive "P")
  8009. (org-load-modules-maybe)
  8010. (setq org-window-config-before-follow-link (current-window-configuration))
  8011. (org-remove-occur-highlights nil nil t)
  8012. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8013. (let* ((context
  8014. ;; Only consider supported types, even if they are not the
  8015. ;; closest one.
  8016. (org-element-lineage
  8017. (org-element-context)
  8018. '(clock comment comment-block footnote-definition
  8019. footnote-reference headline inline-src-block inlinetask
  8020. keyword link node-property planning src-block timestamp)
  8021. t))
  8022. (type (org-element-type context))
  8023. (value (org-element-property :value context)))
  8024. (cond
  8025. ((not type) (user-error "No link found"))
  8026. ;; No valid link at point. For convenience, look if something
  8027. ;; looks like a link under point in some specific places.
  8028. ((memq type '(comment comment-block node-property keyword))
  8029. (call-interactively #'org-open-at-point-global))
  8030. ;; On a headline or an inlinetask, but not on a timestamp,
  8031. ;; a link, a footnote reference.
  8032. ((memq type '(headline inlinetask))
  8033. (org-match-line org-complex-heading-regexp)
  8034. (let ((tags-beg (match-beginning 5))
  8035. (tags-end (match-end 5)))
  8036. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  8037. ;; On tags.
  8038. (org-tags-view
  8039. arg
  8040. (save-excursion
  8041. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  8042. (end-tag (search-forward ":" tags-end nil 2)))
  8043. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  8044. ;; Not on tags.
  8045. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  8046. (`(nil . ,_)
  8047. (require 'org-attach)
  8048. (when (org-attach-dir)
  8049. (message "Opening attachment")
  8050. (if (equal arg '(4))
  8051. (org-attach-reveal-in-emacs)
  8052. (org-attach-reveal))))
  8053. (`(,links . ,links-end)
  8054. (dolist (link (if (stringp links) (list links) links))
  8055. (search-forward link nil links-end)
  8056. (goto-char (match-beginning 0))
  8057. (org-open-at-point arg)))))))
  8058. ;; On a footnote reference or at definition's label.
  8059. ((or (eq type 'footnote-reference)
  8060. (and (eq type 'footnote-definition)
  8061. (save-excursion
  8062. ;; Do not validate action when point is on the
  8063. ;; spaces right after the footnote label, in order
  8064. ;; to be on par with behavior on links.
  8065. (skip-chars-forward " \t")
  8066. (let ((begin
  8067. (org-element-property :contents-begin context)))
  8068. (if begin (< (point) begin)
  8069. (= (org-element-property :post-affiliated context)
  8070. (line-beginning-position)))))))
  8071. (org-footnote-action))
  8072. ;; On a planning line. Check if we are really on a timestamp.
  8073. ((and (eq type 'planning)
  8074. (org-in-regexp org-ts-regexp-both nil t))
  8075. (org-follow-timestamp-link))
  8076. ;; On a clock line, make sure point is on the timestamp
  8077. ;; before opening it.
  8078. ((and (eq type 'clock)
  8079. value
  8080. (>= (point) (org-element-property :begin value))
  8081. (<= (point) (org-element-property :end value)))
  8082. (org-follow-timestamp-link))
  8083. ((eq type 'src-block) (org-babel-open-src-block-result))
  8084. ;; Do nothing on white spaces after an object.
  8085. ((>= (point)
  8086. (save-excursion
  8087. (goto-char (org-element-property :end context))
  8088. (skip-chars-backward " \t")
  8089. (point)))
  8090. (user-error "No link found"))
  8091. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8092. ((eq type 'timestamp) (org-follow-timestamp-link))
  8093. ((eq type 'link) (org-link-open context arg))
  8094. (t (user-error "No link found")))))
  8095. (run-hook-with-args 'org-follow-link-hook))
  8096. ;;;###autoload
  8097. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8098. "Offer links in the current entry and return the selected link.
  8099. If there is only one link, return it.
  8100. If NTH is an integer, return the NTH link found.
  8101. If ZERO is a string, check also this string for a link, and if
  8102. there is one, return it."
  8103. (with-current-buffer buffer
  8104. (org-with-wide-buffer
  8105. (goto-char marker)
  8106. (let ((cnt ?0)
  8107. have-zero end links link c)
  8108. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8109. (push (match-string 0 zero) links)
  8110. (setq cnt (1- cnt) have-zero t))
  8111. (save-excursion
  8112. (org-back-to-heading t)
  8113. (setq end (save-excursion (outline-next-heading) (point)))
  8114. (while (re-search-forward org-link-any-re end t)
  8115. (push (match-string 0) links))
  8116. (setq links (org-uniquify (reverse links))))
  8117. (cond
  8118. ((null links)
  8119. (message "No links"))
  8120. ((equal (length links) 1)
  8121. (setq link (car links)))
  8122. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8123. (setq link (nth (if have-zero nth (1- nth)) links)))
  8124. (t ; we have to select a link
  8125. (save-excursion
  8126. (save-window-excursion
  8127. (delete-other-windows)
  8128. (with-output-to-temp-buffer "*Select Link*"
  8129. (dolist (l links)
  8130. (cond
  8131. ((not (string-match org-link-bracket-re l))
  8132. (princ (format "[%c] %s\n" (cl-incf cnt)
  8133. (org-unbracket-string "<" ">" l))))
  8134. ((match-end 2)
  8135. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8136. (match-string 2 l) (match-string 1 l))))
  8137. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8138. (match-string 1 l)))))))
  8139. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8140. (message "Select link to open, RET to open all:")
  8141. (setq c (read-char-exclusive))
  8142. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8143. (when (equal c ?q) (user-error "Abort"))
  8144. (if (equal c ?\C-m)
  8145. (setq link links)
  8146. (setq nth (- c ?0))
  8147. (when have-zero (setq nth (1+ nth)))
  8148. (unless (and (integerp nth) (>= (length links) nth))
  8149. (user-error "Invalid link selection"))
  8150. (setq link (nth (1- nth) links)))))
  8151. (cons link end)))))
  8152. ;;; File search
  8153. (defun org-do-occur (regexp &optional cleanup)
  8154. "Call the Emacs command `occur'.
  8155. If CLEANUP is non-nil, remove the printout of the regular expression
  8156. in the *Occur* buffer. This is useful if the regex is long and not useful
  8157. to read."
  8158. (occur regexp)
  8159. (when cleanup
  8160. (let ((cwin (selected-window)) win beg end)
  8161. (when (setq win (get-buffer-window "*Occur*"))
  8162. (select-window win))
  8163. (goto-char (point-min))
  8164. (when (re-search-forward "match[a-z]+" nil t)
  8165. (setq beg (match-end 0))
  8166. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8167. (setq end (1- (match-beginning 0)))))
  8168. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8169. (goto-char (point-min))
  8170. (select-window cwin))))
  8171. ;;; The Mark Ring
  8172. (defvar org-mark-ring nil
  8173. "Mark ring for positions before jumps in Org mode.")
  8174. (defvar org-mark-ring-last-goto nil
  8175. "Last position in the mark ring used to go back.")
  8176. ;; Fill and close the ring
  8177. (setq org-mark-ring nil)
  8178. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8179. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8180. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8181. org-mark-ring)
  8182. (defun org-mark-ring-push (&optional pos buffer)
  8183. "Put the current position into the mark ring and rotate it.
  8184. Also push position into the Emacs mark ring. If optional
  8185. argument POS and BUFFER are not nil, mark this location instead."
  8186. (interactive)
  8187. (let ((pos (or pos (point)))
  8188. (buffer (or buffer (current-buffer))))
  8189. (with-current-buffer buffer
  8190. (org-with-point-at pos (push-mark nil t)))
  8191. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8192. (move-marker (car org-mark-ring) pos buffer))
  8193. (message
  8194. (substitute-command-keys
  8195. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8196. (defun org-mark-ring-goto (&optional n)
  8197. "Jump to the previous position in the mark ring.
  8198. With prefix arg N, jump back that many stored positions. When
  8199. called several times in succession, walk through the entire ring.
  8200. Org mode commands jumping to a different position in the current file,
  8201. or to another Org file, automatically push the old position onto the ring."
  8202. (interactive "p")
  8203. (let (p m)
  8204. (if (eq last-command this-command)
  8205. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8206. (setq p org-mark-ring))
  8207. (setq org-mark-ring-last-goto p)
  8208. (setq m (car p))
  8209. (pop-to-buffer-same-window (marker-buffer m))
  8210. (goto-char m)
  8211. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8212. ;;; Following specific links
  8213. (defvar org-agenda-buffer-tmp-name)
  8214. (defvar org-agenda-start-on-weekday)
  8215. (defun org-follow-timestamp-link ()
  8216. "Open an agenda view for the time-stamp date/range at point."
  8217. (cond
  8218. ((org-at-date-range-p t)
  8219. (let ((org-agenda-start-on-weekday)
  8220. (t1 (match-string 1))
  8221. (t2 (match-string 2)) tt1 tt2)
  8222. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8223. tt2 (time-to-days (org-time-string-to-time t2)))
  8224. (let ((org-agenda-buffer-tmp-name
  8225. (format "*Org Agenda(a:%s)"
  8226. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8227. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8228. ((org-at-timestamp-p 'lax)
  8229. (let ((org-agenda-buffer-tmp-name
  8230. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8231. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8232. (substring (match-string 1) 0 10)))
  8233. 1)))
  8234. (t (error "This should not happen"))))
  8235. ;;; Following file links
  8236. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8237. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8238. (declare-function mailcap-mime-info
  8239. "mailcap" (string &optional request no-decode))
  8240. (defvar org-wait nil)
  8241. ;;;; Refiling
  8242. (defun org-get-org-file ()
  8243. "Read a filename, with default directory `org-directory'."
  8244. (let ((default (or org-default-notes-file remember-data-file)))
  8245. (read-file-name (format "File name [%s]: " default)
  8246. (file-name-as-directory org-directory)
  8247. default)))
  8248. (defun org-notes-order-reversed-p ()
  8249. "Check if the current file should receive notes in reversed order."
  8250. (cond
  8251. ((not org-reverse-note-order) nil)
  8252. ((eq t org-reverse-note-order) t)
  8253. ((not (listp org-reverse-note-order)) nil)
  8254. (t (catch 'exit
  8255. (dolist (entry org-reverse-note-order)
  8256. (when (string-match (car entry) buffer-file-name)
  8257. (throw 'exit (cdr entry))))))))
  8258. (defvar org-agenda-new-buffers nil
  8259. "Buffers created to visit agenda files.")
  8260. (declare-function org-string-nw-p "org-macs" (s))
  8261. ;;;; Dynamic blocks
  8262. (defun org-find-dblock (name)
  8263. "Find the first dynamic block with name NAME in the buffer.
  8264. If not found, stay at current position and return nil."
  8265. (let ((case-fold-search t) pos)
  8266. (save-excursion
  8267. (goto-char (point-min))
  8268. (setq pos (and (re-search-forward
  8269. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8270. (match-beginning 0))))
  8271. (when pos (goto-char pos))
  8272. pos))
  8273. (defun org-create-dblock (plist)
  8274. "Create a dynamic block section, with parameters taken from PLIST.
  8275. PLIST must contain a :name entry which is used as the name of the block."
  8276. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8277. (end-of-line 1)
  8278. (newline))
  8279. (let ((col (current-column))
  8280. (name (plist-get plist :name)))
  8281. (insert "#+BEGIN: " name)
  8282. (while plist
  8283. (if (eq (car plist) :name)
  8284. (setq plist (cddr plist))
  8285. (insert " " (prin1-to-string (pop plist)))))
  8286. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8287. (beginning-of-line -2)))
  8288. (defun org-prepare-dblock ()
  8289. "Prepare dynamic block for refresh.
  8290. This empties the block, puts the cursor at the insert position and returns
  8291. the property list including an extra property :name with the block name."
  8292. (unless (looking-at org-dblock-start-re)
  8293. (user-error "Not at a dynamic block"))
  8294. (let* ((begdel (1+ (match-end 0)))
  8295. (name (org-no-properties (match-string 1)))
  8296. (params (append (list :name name)
  8297. (read (concat "(" (match-string 3) ")")))))
  8298. (save-excursion
  8299. (beginning-of-line 1)
  8300. (skip-chars-forward " \t")
  8301. (setq params (plist-put params :indentation-column (current-column))))
  8302. (unless (re-search-forward org-dblock-end-re nil t)
  8303. (error "Dynamic block not terminated"))
  8304. (setq params
  8305. (append params
  8306. (list :content (buffer-substring
  8307. begdel (match-beginning 0)))))
  8308. (delete-region begdel (match-beginning 0))
  8309. (goto-char begdel)
  8310. (open-line 1)
  8311. params))
  8312. (defun org-map-dblocks (&optional command)
  8313. "Apply COMMAND to all dynamic blocks in the current buffer.
  8314. If COMMAND is not given, use `org-update-dblock'."
  8315. (let ((cmd (or command 'org-update-dblock)))
  8316. (save-excursion
  8317. (goto-char (point-min))
  8318. (while (re-search-forward org-dblock-start-re nil t)
  8319. (goto-char (match-beginning 0))
  8320. (save-excursion
  8321. (condition-case nil
  8322. (funcall cmd)
  8323. (error (message "Error during update of dynamic block"))))
  8324. (unless (re-search-forward org-dblock-end-re nil t)
  8325. (error "Dynamic block not terminated"))))))
  8326. (defvar org-dynamic-block-alist nil
  8327. "Alist defining all the Org dynamic blocks.
  8328. The key is the dynamic block type name, as a string. The value
  8329. is the function used to insert the dynamic block.
  8330. Use `org-dynamic-block-define' to populate it.")
  8331. (defun org-dynamic-block-function (type)
  8332. "Return function associated to a given dynamic block type.
  8333. TYPE is the dynamic block type, as a string."
  8334. (cdr (assoc type org-dynamic-block-alist)))
  8335. (defun org-dynamic-block-types ()
  8336. "List all defined dynamic block types."
  8337. (mapcar #'car org-dynamic-block-alist))
  8338. (defun org-dynamic-block-define (type func)
  8339. "Define dynamic block TYPE with FUNC.
  8340. TYPE is a string. FUNC is the function creating the dynamic
  8341. block of such type."
  8342. (pcase (assoc type org-dynamic-block-alist)
  8343. (`nil (push (cons type func) org-dynamic-block-alist))
  8344. (def (setcdr def func))))
  8345. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8346. "Insert a dynamic block of type TYPE.
  8347. When used interactively, select the dynamic block types among
  8348. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8349. is non-nil, call the dynamic block function interactively."
  8350. (interactive (list (completing-read "Dynamic block: "
  8351. (org-dynamic-block-types))
  8352. t))
  8353. (pcase (org-dynamic-block-function type)
  8354. (`nil (error "No such dynamic block: %S" type))
  8355. ((and f (pred functionp))
  8356. (if interactive-p (call-interactively f) (funcall f)))
  8357. (_ (error "Invalid function for dynamic block %S" type))))
  8358. (defun org-dblock-update (&optional arg)
  8359. "User command for updating dynamic blocks.
  8360. Update the dynamic block at point. With prefix ARG, update all dynamic
  8361. blocks in the buffer."
  8362. (interactive "P")
  8363. (if arg
  8364. (org-update-all-dblocks)
  8365. (or (looking-at org-dblock-start-re)
  8366. (org-beginning-of-dblock))
  8367. (org-update-dblock)))
  8368. (defun org-update-dblock ()
  8369. "Update the dynamic block at point.
  8370. This means to empty the block, parse for parameters and then call
  8371. the correct writing function."
  8372. (interactive)
  8373. (save-excursion
  8374. (let* ((win (selected-window))
  8375. (pos (point))
  8376. (line (org-current-line))
  8377. (params (org-prepare-dblock))
  8378. (name (plist-get params :name))
  8379. (indent (plist-get params :indentation-column))
  8380. (cmd (intern (concat "org-dblock-write:" name))))
  8381. (message "Updating dynamic block `%s' at line %d..." name line)
  8382. (funcall cmd params)
  8383. (message "Updating dynamic block `%s' at line %d...done" name line)
  8384. (goto-char pos)
  8385. (when (and indent (> indent 0))
  8386. (setq indent (make-string indent ?\ ))
  8387. (save-excursion
  8388. (select-window win)
  8389. (org-beginning-of-dblock)
  8390. (forward-line 1)
  8391. (while (not (looking-at org-dblock-end-re))
  8392. (insert indent)
  8393. (beginning-of-line 2))
  8394. (when (looking-at org-dblock-end-re)
  8395. (and (looking-at "[ \t]+")
  8396. (replace-match ""))
  8397. (insert indent)))))))
  8398. (defun org-beginning-of-dblock ()
  8399. "Find the beginning of the dynamic block at point.
  8400. Error if there is no such block at point."
  8401. (let ((pos (point))
  8402. beg)
  8403. (end-of-line 1)
  8404. (if (and (re-search-backward org-dblock-start-re nil t)
  8405. (setq beg (match-beginning 0))
  8406. (re-search-forward org-dblock-end-re nil t)
  8407. (> (match-end 0) pos))
  8408. (goto-char beg)
  8409. (goto-char pos)
  8410. (error "Not in a dynamic block"))))
  8411. (defun org-update-all-dblocks ()
  8412. "Update all dynamic blocks in the buffer.
  8413. This function can be used in a hook."
  8414. (interactive)
  8415. (when (derived-mode-p 'org-mode)
  8416. (org-map-dblocks 'org-update-dblock)))
  8417. ;;;; Completion
  8418. (declare-function org-export-backend-options "ox" (cl-x) t)
  8419. (defun org-get-export-keywords ()
  8420. "Return a list of all currently understood export keywords.
  8421. Export keywords include options, block names, attributes and
  8422. keywords relative to each registered export back-end."
  8423. (let (keywords)
  8424. (dolist (backend
  8425. (bound-and-true-p org-export-registered-backends)
  8426. (delq nil keywords))
  8427. ;; Back-end name (for keywords, like #+LATEX:)
  8428. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8429. (dolist (option-entry (org-export-backend-options backend))
  8430. ;; Back-end options.
  8431. (push (nth 1 option-entry) keywords)))))
  8432. (defconst org-options-keywords
  8433. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8434. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8435. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8436. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8437. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8438. (defcustom org-structure-template-alist
  8439. '(("a" . "export ascii")
  8440. ("c" . "center")
  8441. ("C" . "comment")
  8442. ("e" . "example")
  8443. ("E" . "export")
  8444. ("h" . "export html")
  8445. ("l" . "export latex")
  8446. ("q" . "quote")
  8447. ("s" . "src")
  8448. ("v" . "verse"))
  8449. "An alist of keys and block types.
  8450. `org-insert-structure-template' will display a menu with this
  8451. list of templates to choose from. The block type is inserted,
  8452. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8453. The menu keys are defined by the car of each entry in this alist.
  8454. If two entries have the keys \"a\" and \"aa\" respectively, the
  8455. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8456. latter will be inserted by typing \"aa\". If an entry with the
  8457. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8458. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8459. block can be inserted by pressing TAB after the string \"<KEY\"."
  8460. :group 'org-edit-structure
  8461. :type '(repeat
  8462. (cons (string :tag "Key")
  8463. (string :tag "Template")))
  8464. :package-version '(Org . "9.2"))
  8465. (defun org--check-org-structure-template-alist (&optional checklist)
  8466. "Check whether `org-structure-template-alist' is set up correctly.
  8467. In particular, check if the Org 9.2 format is used as opposed to
  8468. previous format."
  8469. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8470. (or (eval checklist)
  8471. org-structure-template-alist))))
  8472. (when elm
  8473. (org-display-warning
  8474. (format "
  8475. Please update the entries of `%s'.
  8476. In Org 9.2 the format was changed from something like
  8477. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8478. to something like
  8479. (\"s\" . \"src\")
  8480. Please refer to the documentation of `org-structure-template-alist'.
  8481. The following entries must be updated:
  8482. %s"
  8483. (or checklist 'org-structure-template-alist)
  8484. (pp-to-string elm))))))
  8485. (defun org--insert-structure-template-mks ()
  8486. "Present `org-structure-template-alist' with `org-mks'.
  8487. Menus are added if keys require more than one keystroke. Tabs
  8488. are added to single key entries when more than one stroke is
  8489. needed. Keys longer than two characters are reduced to two
  8490. characters."
  8491. (org--check-org-structure-template-alist)
  8492. (let* (case-fold-search
  8493. (templates (append org-structure-template-alist
  8494. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8495. (keys (mapcar #'car templates))
  8496. (start-letters
  8497. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8498. ;; Sort each element of `org-structure-template-alist' into
  8499. ;; sublists according to the first letter.
  8500. (superlist
  8501. (mapcar (lambda (letter)
  8502. (list letter
  8503. (cl-remove-if-not
  8504. (apply-partially #'string-match-p (concat "^" letter))
  8505. templates :key #'car)))
  8506. start-letters)))
  8507. (org-mks
  8508. (apply #'append
  8509. ;; Make an `org-mks' table. If only one element is
  8510. ;; present in a sublist, make it part of the top-menu,
  8511. ;; otherwise make a submenu according to the starting
  8512. ;; letter and populate it.
  8513. (mapcar (lambda (sublist)
  8514. (if (eq 1 (length (cadr sublist)))
  8515. (mapcar (lambda (elm)
  8516. (list (substring (car elm) 0 1)
  8517. (cdr elm) ""))
  8518. (cadr sublist))
  8519. ;; Create submenu.
  8520. (let* ((topkey (car sublist))
  8521. (elms (cadr sublist))
  8522. (keys (mapcar #'car elms))
  8523. (long (> (length elms) 3)))
  8524. (append
  8525. (list
  8526. ;; Make a description of the submenu.
  8527. (list topkey
  8528. (concat
  8529. (mapconcat #'cdr
  8530. (cl-subseq elms 0 (if long 3 (length elms)))
  8531. ", ")
  8532. (when long ", ..."))))
  8533. ;; List of entries in submenu.
  8534. (cl-mapcar #'list
  8535. (org--insert-structure-template-unique-keys keys)
  8536. (mapcar #'cdr elms)
  8537. (make-list (length elms) ""))))))
  8538. superlist))
  8539. "Select a key\n============"
  8540. "Key: ")))
  8541. (defun org--insert-structure-template-unique-keys (keys)
  8542. "Make a list of unique, two characters long elements from KEYS.
  8543. Elements of length one have a tab appended. Elements of length
  8544. two are kept as is. Longer elements are truncated to length two.
  8545. If an element cannot be made unique, an error is raised."
  8546. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8547. menu-keys)
  8548. (dolist (key ordered-keys)
  8549. (let ((potential-key
  8550. (cl-case (length key)
  8551. (1 (concat key "\t"))
  8552. (2 key)
  8553. (otherwise
  8554. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8555. (mapcar (apply-partially #'concat (substring key 0 1))
  8556. (split-string (substring key 1) "" t)))))))
  8557. (if (or (not potential-key) (assoc potential-key menu-keys))
  8558. (user-error "Could not make unique key for %s." key)
  8559. (push (cons potential-key key) menu-keys))))
  8560. (mapcar #'car
  8561. (cl-sort menu-keys #'<
  8562. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8563. (defun org-insert-structure-template (type)
  8564. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8565. Select a block from `org-structure-template-alist' then type
  8566. either RET, TAB or SPC to write the block type. With an active
  8567. region, wrap the region in the block. Otherwise, insert an empty
  8568. block."
  8569. (interactive
  8570. (list (pcase (org--insert-structure-template-mks)
  8571. (`("\t" . ,_) (read-string "Structure type: "))
  8572. (`(,_ ,choice . ,_) choice))))
  8573. (let* ((region? (use-region-p))
  8574. (region-start (and region? (region-beginning)))
  8575. (region-end (and region? (copy-marker (region-end))))
  8576. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8577. (verbatim? (string-match-p
  8578. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8579. type)))
  8580. (when region? (goto-char region-start))
  8581. (let ((column (current-indentation)))
  8582. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8583. (beginning-of-line)
  8584. (insert "\n"))
  8585. (save-excursion
  8586. (indent-to column)
  8587. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8588. (when region?
  8589. (when verbatim? (org-escape-code-in-region (point) region-end))
  8590. (goto-char region-end)
  8591. ;; Ignore empty lines at the end of the region.
  8592. (skip-chars-backward " \r\t\n")
  8593. (end-of-line))
  8594. (unless (bolp) (insert "\n"))
  8595. (indent-to column)
  8596. (insert (format "#+end_%s" (car (split-string type))))
  8597. (if (looking-at "[ \t]*$") (replace-match "")
  8598. (insert "\n"))
  8599. (when (and (eobp) (not (bolp))) (insert "\n")))
  8600. (if extended? (end-of-line)
  8601. (forward-line)
  8602. (skip-chars-forward " \t")))))
  8603. ;;;; TODO, DEADLINE, Comments
  8604. (defun org-toggle-comment ()
  8605. "Change the COMMENT state of an entry."
  8606. (interactive)
  8607. (save-excursion
  8608. (org-back-to-heading)
  8609. (let ((case-fold-search nil))
  8610. (looking-at org-complex-heading-regexp))
  8611. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8612. (skip-chars-forward " \t")
  8613. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8614. (if (org-in-commented-heading-p t)
  8615. (delete-region (point)
  8616. (progn (search-forward " " (line-end-position) 'move)
  8617. (skip-chars-forward " \t")
  8618. (point)))
  8619. (insert org-comment-string)
  8620. (unless (eolp) (insert " ")))))
  8621. (defvar org-last-todo-state-is-todo nil
  8622. "This is non-nil when the last TODO state change led to a TODO state.
  8623. If the last change removed the TODO tag or switched to DONE, then
  8624. this is nil.")
  8625. (defvar org-todo-setup-filter-hook nil
  8626. "Hook for functions that pre-filter todo specs.
  8627. Each function takes a todo spec and returns either nil or the spec
  8628. transformed into canonical form." )
  8629. (defvar org-todo-get-default-hook nil
  8630. "Hook for functions that get a default item for todo.
  8631. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8632. nil or a string to be used for the todo mark." )
  8633. (defvar org-agenda-headline-snapshot-before-repeat)
  8634. (defun org-current-effective-time ()
  8635. "Return current time adjusted for `org-extend-today-until' variable."
  8636. (let* ((ct (org-current-time))
  8637. (dct (decode-time ct))
  8638. (ct1
  8639. (cond
  8640. (org-use-last-clock-out-time-as-effective-time
  8641. (or (org-clock-get-last-clock-out-time) ct))
  8642. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8643. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8644. (t ct))))
  8645. ct1))
  8646. (defun org-todo-yesterday (&optional arg)
  8647. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8648. (interactive "P")
  8649. (if (eq major-mode 'org-agenda-mode)
  8650. (apply 'org-agenda-todo-yesterday arg)
  8651. (let* ((org-use-effective-time t)
  8652. (hour (nth 2 (decode-time (org-current-time))))
  8653. (org-extend-today-until (1+ hour)))
  8654. (org-todo arg))))
  8655. (defvar org-block-entry-blocking ""
  8656. "First entry preventing the TODO state change.")
  8657. (defun org-cancel-repeater ()
  8658. "Cancel a repeater by setting its numeric value to zero."
  8659. (interactive)
  8660. (save-excursion
  8661. (org-back-to-heading t)
  8662. (let ((bound1 (point))
  8663. (bound0 (save-excursion (outline-next-heading) (point))))
  8664. (when (and (re-search-forward
  8665. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8666. org-deadline-time-regexp "\\)\\|\\("
  8667. org-ts-regexp "\\)")
  8668. bound0 t)
  8669. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8670. bound1 t))
  8671. (replace-match "0" t nil nil 1)))))
  8672. (defvar org-state)
  8673. (defvar org-blocked-by-checkboxes)
  8674. (defun org-todo (&optional arg)
  8675. "Change the TODO state of an item.
  8676. The state of an item is given by a keyword at the start of the heading,
  8677. like
  8678. *** TODO Write paper
  8679. *** DONE Call mom
  8680. The different keywords are specified in the variable `org-todo-keywords'.
  8681. By default the available states are \"TODO\" and \"DONE\". So, for this
  8682. example: when the item starts with TODO, it is changed to DONE.
  8683. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8684. DONE are present, add TODO at the beginning of the heading.
  8685. You can set up single-character keys to fast-select the new state. See the
  8686. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8687. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8688. and take a
  8689. logging note.
  8690. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8691. next set of TODO \
  8692. keywords (nextset).
  8693. Another way to achieve this is `S-C-<right>'.
  8694. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8695. prefix, circumvent any state blocking.
  8696. With numeric prefix arg, switch to the Nth state.
  8697. With a numeric prefix arg of 0, inhibit note taking for the change.
  8698. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8699. When called through ELisp, arg is also interpreted in the following way:
  8700. `none' -> empty state
  8701. \"\" -> switch to empty state
  8702. `done' -> switch to DONE
  8703. `nextset' -> switch to the next set of keywords
  8704. `previousset' -> switch to the previous set of keywords
  8705. \"WAITING\" -> switch to the specified keyword, but only if it
  8706. really is a member of `org-todo-keywords'."
  8707. (interactive "P")
  8708. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8709. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8710. 'region-start-level 'region))
  8711. org-loop-over-headlines-in-active-region)
  8712. (org-map-entries
  8713. (lambda () (org-todo arg))
  8714. nil cl
  8715. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8716. (when (equal arg '(16)) (setq arg 'nextset))
  8717. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8718. (let ((org-blocker-hook org-blocker-hook)
  8719. commentp
  8720. case-fold-search)
  8721. (when (equal arg '(64))
  8722. (setq arg nil org-blocker-hook nil))
  8723. (when (and org-blocker-hook
  8724. (or org-inhibit-blocking
  8725. (org-entry-get nil "NOBLOCKING")))
  8726. (setq org-blocker-hook nil))
  8727. (save-excursion
  8728. (catch 'exit
  8729. (org-back-to-heading t)
  8730. (when (org-in-commented-heading-p t)
  8731. (org-toggle-comment)
  8732. (setq commentp t))
  8733. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8734. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8735. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8736. (let* ((match-data (match-data))
  8737. (startpos (copy-marker (line-beginning-position)))
  8738. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8739. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8740. (org-log-done org-log-done)
  8741. (org-log-repeat org-log-repeat)
  8742. (org-todo-log-states org-todo-log-states)
  8743. (org-inhibit-logging
  8744. (if (equal arg 0)
  8745. (progn (setq arg nil) 'note) org-inhibit-logging))
  8746. (this (match-string 1))
  8747. (hl-pos (match-beginning 0))
  8748. (head (org-get-todo-sequence-head this))
  8749. (ass (assoc head org-todo-kwd-alist))
  8750. (interpret (nth 1 ass))
  8751. (done-word (nth 3 ass))
  8752. (final-done-word (nth 4 ass))
  8753. (org-last-state (or this ""))
  8754. (completion-ignore-case t)
  8755. (member (member this org-todo-keywords-1))
  8756. (tail (cdr member))
  8757. (org-state (cond
  8758. ((eq arg 'right)
  8759. ;; Next state
  8760. (if this
  8761. (if tail (car tail) nil)
  8762. (car org-todo-keywords-1)))
  8763. ((eq arg 'left)
  8764. ;; Previous state
  8765. (unless (equal member org-todo-keywords-1)
  8766. (if this
  8767. (nth (- (length org-todo-keywords-1)
  8768. (length tail) 2)
  8769. org-todo-keywords-1)
  8770. (org-last org-todo-keywords-1))))
  8771. (arg
  8772. ;; User or caller requests a specific state.
  8773. (cond
  8774. ((equal arg "") nil)
  8775. ((eq arg 'none) nil)
  8776. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8777. ((eq arg 'nextset)
  8778. (or (car (cdr (member head org-todo-heads)))
  8779. (car org-todo-heads)))
  8780. ((eq arg 'previousset)
  8781. (let ((org-todo-heads (reverse org-todo-heads)))
  8782. (or (car (cdr (member head org-todo-heads)))
  8783. (car org-todo-heads))))
  8784. ((car (member arg org-todo-keywords-1)))
  8785. ((stringp arg)
  8786. (user-error "State `%s' not valid in this file" arg))
  8787. ((nth (1- (prefix-numeric-value arg))
  8788. org-todo-keywords-1))))
  8789. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8790. ;; Use fast selection.
  8791. (org-fast-todo-selection this))
  8792. ((null member) (or head (car org-todo-keywords-1)))
  8793. ((equal this final-done-word) nil) ;-> make empty
  8794. ((null tail) nil) ;-> first entry
  8795. ((memq interpret '(type priority))
  8796. (if (eq this-command last-command)
  8797. (car tail)
  8798. (if (> (length tail) 0)
  8799. (or done-word (car org-done-keywords))
  8800. nil)))
  8801. (t
  8802. (car tail))))
  8803. (org-state (or
  8804. (run-hook-with-args-until-success
  8805. 'org-todo-get-default-hook org-state org-last-state)
  8806. org-state))
  8807. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8808. (change-plist (list :type 'todo-state-change :from this :to org-state
  8809. :position startpos))
  8810. dolog now-done-p)
  8811. (when org-blocker-hook
  8812. (let (org-blocked-by-checkboxes block-reason)
  8813. (setq org-last-todo-state-is-todo
  8814. (not (member this org-done-keywords)))
  8815. (unless (save-excursion
  8816. (save-match-data
  8817. (org-with-wide-buffer
  8818. (run-hook-with-args-until-failure
  8819. 'org-blocker-hook change-plist))))
  8820. (setq block-reason (if org-blocked-by-checkboxes
  8821. "contained checkboxes"
  8822. (format "\"%s\"" org-block-entry-blocking)))
  8823. (if (called-interactively-p 'interactive)
  8824. (user-error "TODO state change from %s to %s blocked (by %s)"
  8825. this org-state block-reason)
  8826. ;; Fail silently.
  8827. (message "TODO state change from %s to %s blocked (by %s)"
  8828. this org-state block-reason)
  8829. (throw 'exit nil)))))
  8830. (store-match-data match-data)
  8831. (replace-match next t t)
  8832. (cond ((and org-state (equal this org-state))
  8833. (message "TODO state was already %s" (org-trim next)))
  8834. ((not (pos-visible-in-window-p hl-pos))
  8835. (message "TODO state changed to %s" (org-trim next))))
  8836. (unless head
  8837. (setq head (org-get-todo-sequence-head org-state)
  8838. ass (assoc head org-todo-kwd-alist)
  8839. interpret (nth 1 ass)
  8840. done-word (nth 3 ass)
  8841. final-done-word (nth 4 ass)))
  8842. (when (memq arg '(nextset previousset))
  8843. (message "Keyword-Set %d/%d: %s"
  8844. (- (length org-todo-sets) -1
  8845. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8846. (length org-todo-sets)
  8847. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8848. (setq org-last-todo-state-is-todo
  8849. (not (member org-state org-done-keywords)))
  8850. (setq now-done-p (and (member org-state org-done-keywords)
  8851. (not (member this org-done-keywords))))
  8852. (and logging (org-local-logging logging))
  8853. (when (or (and (or org-todo-log-states org-log-done)
  8854. (not (eq org-inhibit-logging t))
  8855. (not (memq arg '(nextset previousset))))
  8856. force-log)
  8857. ;; We need to look at recording a time and note.
  8858. (setq dolog (or (if force-log 'note)
  8859. (nth 1 (assoc org-state org-todo-log-states))
  8860. (nth 2 (assoc this org-todo-log-states))))
  8861. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8862. (setq dolog 'time))
  8863. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8864. (and org-state
  8865. (member org-state org-not-done-keywords)
  8866. (not (member this org-not-done-keywords))))
  8867. ;; This is now a todo state and was not one before
  8868. ;; If there was a CLOSED time stamp, get rid of it.
  8869. (org-add-planning-info nil nil 'closed))
  8870. (when (and now-done-p org-log-done)
  8871. ;; It is now done, and it was not done before.
  8872. (org-add-planning-info 'closed (org-current-effective-time))
  8873. (when (and (not dolog) (eq 'note org-log-done))
  8874. (org-add-log-setup 'done org-state this 'note)))
  8875. (when (and org-state dolog)
  8876. ;; This is a non-nil state, and we need to log it.
  8877. (org-add-log-setup 'state org-state this dolog)))
  8878. ;; Fixup tag positioning.
  8879. (org-todo-trigger-tag-changes org-state)
  8880. (when org-auto-align-tags (org-align-tags))
  8881. (when org-provide-todo-statistics
  8882. (org-update-parent-todo-statistics))
  8883. (when (bound-and-true-p org-clock-out-when-done)
  8884. (org-clock-out-if-current))
  8885. (run-hooks 'org-after-todo-state-change-hook)
  8886. (when (and arg (not (member org-state org-done-keywords)))
  8887. (setq head (org-get-todo-sequence-head org-state)))
  8888. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8889. ;; Do we need to trigger a repeat?
  8890. (when now-done-p
  8891. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8892. ;; This is for the agenda, take a snapshot of the headline.
  8893. (save-match-data
  8894. (setq org-agenda-headline-snapshot-before-repeat
  8895. (org-get-heading))))
  8896. (org-auto-repeat-maybe org-state))
  8897. ;; Fixup cursor location if close to the keyword.
  8898. (when (and (outline-on-heading-p)
  8899. (not (bolp))
  8900. (save-excursion (beginning-of-line 1)
  8901. (looking-at org-todo-line-regexp))
  8902. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8903. (goto-char (or (match-end 2) (match-end 1)))
  8904. (and (looking-at " ")
  8905. (not (looking-at " *:"))
  8906. (just-one-space)))
  8907. (when org-trigger-hook
  8908. (save-excursion
  8909. (run-hook-with-args 'org-trigger-hook change-plist)))
  8910. (when commentp (org-toggle-comment))))))))
  8911. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8912. "Block turning an entry into a TODO, using the hierarchy.
  8913. This checks whether the current task should be blocked from state
  8914. changes. Such blocking occurs when:
  8915. 1. The task has children which are not all in a completed state.
  8916. 2. A task has a parent with the property :ORDERED:, and there
  8917. are siblings prior to the current task with incomplete
  8918. status.
  8919. 3. The parent of the task is blocked because it has siblings that should
  8920. be done first, or is child of a block grandparent TODO entry."
  8921. (if (not org-enforce-todo-dependencies)
  8922. t ; if locally turned off don't block
  8923. (catch 'dont-block
  8924. ;; If this is not a todo state change, or if this entry is already DONE,
  8925. ;; do not block
  8926. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8927. (member (plist-get change-plist :from)
  8928. (cons 'done org-done-keywords))
  8929. (member (plist-get change-plist :to)
  8930. (cons 'todo org-not-done-keywords))
  8931. (not (plist-get change-plist :to)))
  8932. (throw 'dont-block t))
  8933. ;; If this task has children, and any are undone, it's blocked
  8934. (save-excursion
  8935. (org-back-to-heading t)
  8936. (let ((this-level (funcall outline-level)))
  8937. (outline-next-heading)
  8938. (let ((child-level (funcall outline-level)))
  8939. (while (and (not (eobp))
  8940. (> child-level this-level))
  8941. ;; this todo has children, check whether they are all
  8942. ;; completed
  8943. (when (and (not (org-entry-is-done-p))
  8944. (org-entry-is-todo-p))
  8945. (setq org-block-entry-blocking (org-get-heading))
  8946. (throw 'dont-block nil))
  8947. (outline-next-heading)
  8948. (setq child-level (funcall outline-level))))))
  8949. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8950. ;; any previous siblings are undone, it's blocked
  8951. (save-excursion
  8952. (org-back-to-heading t)
  8953. (let* ((pos (point))
  8954. (parent-pos (and (org-up-heading-safe) (point)))
  8955. (case-fold-search nil))
  8956. (unless parent-pos (throw 'dont-block t)) ; no parent
  8957. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8958. (forward-line 1)
  8959. (re-search-forward org-not-done-heading-regexp pos t))
  8960. (setq org-block-entry-blocking (match-string 0))
  8961. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8962. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8963. (while t
  8964. (goto-char parent-pos)
  8965. (unless (looking-at org-not-done-heading-regexp)
  8966. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8967. (setq pos (point))
  8968. (setq parent-pos (and (org-up-heading-safe) (point)))
  8969. (unless parent-pos (throw 'dont-block t)) ; no parent
  8970. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8971. (forward-line 1)
  8972. (re-search-forward org-not-done-heading-regexp pos t)
  8973. (setq org-block-entry-blocking (org-get-heading)))
  8974. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8975. (defcustom org-track-ordered-property-with-tag nil
  8976. "Should the ORDERED property also be shown as a tag?
  8977. The ORDERED property decides if an entry should require subtasks to be
  8978. completed in sequence. Since a property is not very visible, setting
  8979. this option means that toggling the ORDERED property with the command
  8980. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8981. not relevant for the behavior, but it makes things more visible.
  8982. Note that toggling the tag with tags commands will not change the property
  8983. and therefore not influence behavior!
  8984. This can be t, meaning the tag ORDERED should be used. It can also be a
  8985. string to select a different tag for this task."
  8986. :group 'org-todo
  8987. :type '(choice
  8988. (const :tag "No tracking" nil)
  8989. (const :tag "Track with ORDERED tag" t)
  8990. (string :tag "Use other tag")))
  8991. (defun org-toggle-ordered-property ()
  8992. "Toggle the ORDERED property of the current entry.
  8993. For better visibility, you can track the value of this property with a tag.
  8994. See variable `org-track-ordered-property-with-tag'."
  8995. (interactive)
  8996. (let* ((t1 org-track-ordered-property-with-tag)
  8997. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8998. (save-excursion
  8999. (org-back-to-heading)
  9000. (if (org-entry-get nil "ORDERED")
  9001. (progn
  9002. (org-delete-property "ORDERED")
  9003. (and tag (org-toggle-tag tag 'off))
  9004. (message "Subtasks can be completed in arbitrary order"))
  9005. (org-entry-put nil "ORDERED" "t")
  9006. (and tag (org-toggle-tag tag 'on))
  9007. (message "Subtasks must be completed in sequence")))))
  9008. (defun org-block-todo-from-checkboxes (change-plist)
  9009. "Block turning an entry into a TODO, using checkboxes.
  9010. This checks whether the current task should be blocked from state
  9011. changes because there are unchecked boxes in this entry."
  9012. (if (not org-enforce-todo-checkbox-dependencies)
  9013. t ; if locally turned off don't block
  9014. (catch 'dont-block
  9015. ;; If this is not a todo state change, or if this entry is already DONE,
  9016. ;; do not block
  9017. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9018. (member (plist-get change-plist :from)
  9019. (cons 'done org-done-keywords))
  9020. (member (plist-get change-plist :to)
  9021. (cons 'todo org-not-done-keywords))
  9022. (not (plist-get change-plist :to)))
  9023. (throw 'dont-block t))
  9024. ;; If this task has checkboxes that are not checked, it's blocked
  9025. (save-excursion
  9026. (org-back-to-heading t)
  9027. (let ((beg (point)) end)
  9028. (outline-next-heading)
  9029. (setq end (point))
  9030. (goto-char beg)
  9031. (when (org-list-search-forward
  9032. (concat (org-item-beginning-re)
  9033. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9034. "\\[[- ]\\]")
  9035. end t)
  9036. (when (boundp 'org-blocked-by-checkboxes)
  9037. (setq org-blocked-by-checkboxes t))
  9038. (throw 'dont-block nil))))
  9039. t))) ; do not block
  9040. (defun org-entry-blocked-p ()
  9041. "Non-nil if entry at point is blocked."
  9042. (and (not (org-entry-get nil "NOBLOCKING"))
  9043. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9044. (not (run-hook-with-args-until-failure
  9045. 'org-blocker-hook
  9046. (list :type 'todo-state-change
  9047. :position (point)
  9048. :from 'todo
  9049. :to 'done)))))
  9050. (defun org-update-statistics-cookies (all)
  9051. "Update the statistics cookie, either from TODO or from checkboxes.
  9052. This should be called with the cursor in a line with a statistics
  9053. cookie. When called with a \\[universal-argument] prefix, update
  9054. all statistics cookies in the buffer."
  9055. (interactive "P")
  9056. (if all
  9057. (progn
  9058. (org-update-checkbox-count 'all)
  9059. (org-map-entries 'org-update-parent-todo-statistics))
  9060. (if (not (org-at-heading-p))
  9061. (org-update-checkbox-count)
  9062. (let ((pos (point-marker))
  9063. end l1 l2)
  9064. (ignore-errors (org-back-to-heading t))
  9065. (if (not (org-at-heading-p))
  9066. (org-update-checkbox-count)
  9067. (setq l1 (org-outline-level))
  9068. (setq end (save-excursion
  9069. (outline-next-heading)
  9070. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9071. (point)))
  9072. (if (and (save-excursion
  9073. (re-search-forward
  9074. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9075. (not (save-excursion (re-search-forward
  9076. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9077. (org-update-checkbox-count)
  9078. (if (and l2 (> l2 l1))
  9079. (progn
  9080. (goto-char end)
  9081. (org-update-parent-todo-statistics))
  9082. (goto-char pos)
  9083. (beginning-of-line 1)
  9084. (while (re-search-forward
  9085. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9086. (point-at-eol) t)
  9087. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9088. (goto-char pos)
  9089. (move-marker pos nil)))))
  9090. (defvar org-entry-property-inherited-from) ;; defined below
  9091. (defun org-update-parent-todo-statistics ()
  9092. "Update any statistics cookie in the parent of the current headline.
  9093. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9094. the entire subtree and this will travel up the hierarchy and update
  9095. statistics everywhere."
  9096. (let* ((prop (save-excursion (org-up-heading-safe)
  9097. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9098. (recursive (or (not org-hierarchical-todo-statistics)
  9099. (and prop (string-match "\\<recursive\\>" prop))))
  9100. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9101. 0))
  9102. (first t)
  9103. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9104. level ltoggle l1 new ndel
  9105. (cnt-all 0) (cnt-done 0) is-percent kwd
  9106. checkbox-beg cookie-present)
  9107. (catch 'exit
  9108. (save-excursion
  9109. (beginning-of-line 1)
  9110. (setq ltoggle (funcall outline-level))
  9111. ;; Three situations are to consider:
  9112. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9113. ;; to the top-level ancestor on the headline;
  9114. ;; 2. If parent has "recursive" property, repeat up to the
  9115. ;; headline setting that property, taking inheritance into
  9116. ;; account;
  9117. ;; 3. Else, move up to direct parent and proceed only once.
  9118. (while (and (setq level (org-up-heading-safe))
  9119. (or recursive first)
  9120. (>= (point) lim))
  9121. (setq first nil cookie-present nil)
  9122. (unless (and level
  9123. (not (string-match
  9124. "\\<checkbox\\>"
  9125. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9126. "")))))
  9127. (throw 'exit nil))
  9128. (while (re-search-forward box-re (point-at-eol) t)
  9129. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9130. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9131. (save-match-data
  9132. (unless (outline-next-heading) (throw 'exit nil))
  9133. (while (and (looking-at org-complex-heading-regexp)
  9134. (> (setq l1 (length (match-string 1))) level))
  9135. (setq kwd (and (or recursive (= l1 ltoggle))
  9136. (match-string 2)))
  9137. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9138. (and (eq org-provide-todo-statistics t)
  9139. (or (member kwd org-done-keywords)))
  9140. (and (listp org-provide-todo-statistics)
  9141. (stringp (car org-provide-todo-statistics))
  9142. (or (member kwd org-provide-todo-statistics)
  9143. (member kwd org-done-keywords)))
  9144. (and (listp org-provide-todo-statistics)
  9145. (listp (car org-provide-todo-statistics))
  9146. (or (member kwd (car org-provide-todo-statistics))
  9147. (and (member kwd org-done-keywords)
  9148. (member kwd (cadr org-provide-todo-statistics))))))
  9149. (setq cnt-all (1+ cnt-all))
  9150. (and (eq org-provide-todo-statistics t)
  9151. kwd
  9152. (setq cnt-all (1+ cnt-all))))
  9153. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9154. (member kwd org-done-keywords))
  9155. (and (listp org-provide-todo-statistics)
  9156. (listp (car org-provide-todo-statistics))
  9157. (member kwd org-done-keywords)
  9158. (member kwd (cadr org-provide-todo-statistics)))
  9159. (and (listp org-provide-todo-statistics)
  9160. (stringp (car org-provide-todo-statistics))
  9161. (member kwd org-done-keywords)))
  9162. (setq cnt-done (1+ cnt-done)))
  9163. (outline-next-heading)))
  9164. (setq new
  9165. (if is-percent
  9166. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9167. (max 1 cnt-all)))
  9168. (format "[%d/%d]" cnt-done cnt-all))
  9169. ndel (- (match-end 0) checkbox-beg))
  9170. (goto-char checkbox-beg)
  9171. (insert new)
  9172. (delete-region (point) (+ (point) ndel))
  9173. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9174. (when cookie-present
  9175. (run-hook-with-args 'org-after-todo-statistics-hook
  9176. cnt-done (- cnt-all cnt-done))))))
  9177. (run-hooks 'org-todo-statistics-hook)))
  9178. (defvar org-after-todo-statistics-hook nil
  9179. "Hook that is called after a TODO statistics cookie has been updated.
  9180. Each function is called with two arguments: the number of not-done entries
  9181. and the number of done entries.
  9182. For example, the following function, when added to this hook, will switch
  9183. an entry to DONE when all children are done, and back to TODO when new
  9184. entries are set to a TODO status. Note that this hook is only called
  9185. when there is a statistics cookie in the headline!
  9186. (defun org-summary-todo (n-done n-not-done)
  9187. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9188. (let (org-log-done org-log-states) ; turn off logging
  9189. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9190. (defvar org-todo-statistics-hook nil
  9191. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9192. This hook runs even if there is no statistics cookie present, in which case
  9193. `org-after-todo-statistics-hook' would not run.")
  9194. (defun org-todo-trigger-tag-changes (state)
  9195. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9196. (let ((l org-todo-state-tags-triggers)
  9197. changes)
  9198. (when (or (not state) (equal state ""))
  9199. (setq changes (append changes (cdr (assoc "" l)))))
  9200. (when (and (stringp state) (> (length state) 0))
  9201. (setq changes (append changes (cdr (assoc state l)))))
  9202. (when (member state org-not-done-keywords)
  9203. (setq changes (append changes (cdr (assq 'todo l)))))
  9204. (when (member state org-done-keywords)
  9205. (setq changes (append changes (cdr (assq 'done l)))))
  9206. (dolist (c changes)
  9207. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9208. (defun org-local-logging (value)
  9209. "Get logging settings from a property VALUE."
  9210. ;; Directly set the variables, they are already local.
  9211. (setq org-log-done nil
  9212. org-log-repeat nil
  9213. org-todo-log-states nil)
  9214. (dolist (w (split-string value))
  9215. (let (a)
  9216. (cond
  9217. ((setq a (assoc w org-startup-options))
  9218. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9219. (set (nth 1 a) (nth 2 a))))
  9220. ((setq a (org-extract-log-state-settings w))
  9221. (and (member (car a) org-todo-keywords-1)
  9222. (push a org-todo-log-states)))))))
  9223. (defun org-get-todo-sequence-head (kwd)
  9224. "Return the head of the TODO sequence to which KWD belongs.
  9225. If KWD is not set, check if there is a text property remembering the
  9226. right sequence."
  9227. (let (p)
  9228. (cond
  9229. ((not kwd)
  9230. (or (get-text-property (point-at-bol) 'org-todo-head)
  9231. (progn
  9232. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9233. nil (point-at-eol)))
  9234. (get-text-property p 'org-todo-head))))
  9235. ((not (member kwd org-todo-keywords-1))
  9236. (car org-todo-keywords-1))
  9237. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9238. (defun org-fast-todo-selection (&optional current-state)
  9239. "Fast TODO keyword selection with single keys.
  9240. Returns the new TODO keyword, or nil if no state change should occur.
  9241. When CURRENT-STATE is given and selection letters are not unique globally,
  9242. prefer a state in the current sequence over on in another sequence."
  9243. (let* ((fulltable org-todo-key-alist)
  9244. (head (org-get-todo-sequence-head current-state))
  9245. (done-keywords org-done-keywords) ;; needed for the faces.
  9246. (maxlen (apply 'max (mapcar
  9247. (lambda (x)
  9248. (if (stringp (car x)) (string-width (car x)) 0))
  9249. fulltable)))
  9250. (expert (equal org-use-fast-todo-selection 'expert))
  9251. (prompt "")
  9252. (fwidth (+ maxlen 3 1 3))
  9253. (ncol (/ (- (window-width) 4) fwidth))
  9254. tg cnt e c tbl subtable
  9255. groups ingroup in-current-sequence)
  9256. (save-excursion
  9257. (save-window-excursion
  9258. (if expert
  9259. (set-buffer (get-buffer-create " *Org todo*"))
  9260. (delete-other-windows)
  9261. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9262. (org-switch-to-buffer-other-window " *Org todo*"))
  9263. (erase-buffer)
  9264. (setq-local org-done-keywords done-keywords)
  9265. (setq tbl fulltable cnt 0)
  9266. (while (setq e (pop tbl))
  9267. (cond
  9268. ((equal e '(:startgroup))
  9269. (push '() groups) (setq ingroup t)
  9270. (unless (= cnt 0)
  9271. (setq cnt 0)
  9272. (insert "\n"))
  9273. (setq prompt (concat prompt "{"))
  9274. (insert "{ "))
  9275. ((equal e '(:endgroup))
  9276. (setq ingroup nil cnt 0 in-current-sequence nil)
  9277. (setq prompt (concat prompt "}"))
  9278. (insert "}\n"))
  9279. ((equal e '(:newline))
  9280. (unless (= cnt 0)
  9281. (setq cnt 0)
  9282. (insert "\n")
  9283. (setq e (car tbl))
  9284. (while (equal (car tbl) '(:newline))
  9285. (insert "\n")
  9286. (setq tbl (cdr tbl)))))
  9287. (t
  9288. (setq tg (car e) c (cdr e))
  9289. (if (equal tg head) (setq in-current-sequence t))
  9290. (when ingroup (push tg (car groups)))
  9291. (when in-current-sequence (push e subtable))
  9292. (setq tg (org-add-props tg nil 'face
  9293. (org-get-todo-face tg)))
  9294. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9295. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9296. (insert "[" c "] " tg (make-string
  9297. (- fwidth 4 (length tg)) ?\ ))
  9298. (when (and (= (setq cnt (1+ cnt)) ncol)
  9299. ;; Avoid lines with just a closing delimiter.
  9300. (not (equal (car tbl) '(:endgroup))))
  9301. (insert "\n")
  9302. (when ingroup (insert " "))
  9303. (setq cnt 0)))))
  9304. (insert "\n")
  9305. (goto-char (point-min))
  9306. (unless expert (org-fit-window-to-buffer))
  9307. (message (concat "[a-z..]:Set [SPC]:clear"
  9308. (if expert (concat "\n" prompt) "")))
  9309. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9310. (setq subtable (nreverse subtable))
  9311. (cond
  9312. ((or (= c ?\C-g)
  9313. (and (= c ?q) (not (rassoc c fulltable))))
  9314. (setq quit-flag t))
  9315. ((= c ?\ ) nil)
  9316. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9317. tg (car e))
  9318. tg)
  9319. (t (setq quit-flag t)))))))
  9320. (defun org-entry-is-todo-p ()
  9321. (member (org-get-todo-state) org-not-done-keywords))
  9322. (defun org-entry-is-done-p ()
  9323. (member (org-get-todo-state) org-done-keywords))
  9324. (defun org-get-todo-state ()
  9325. "Return the TODO keyword of the current subtree."
  9326. (save-excursion
  9327. (org-back-to-heading t)
  9328. (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9329. (match-end 2)
  9330. (match-string 2))))
  9331. (defun org-at-date-range-p (&optional inactive-ok)
  9332. "Non-nil if point is inside a date range.
  9333. When optional argument INACTIVE-OK is non-nil, also consider
  9334. inactive time ranges.
  9335. When this function returns a non-nil value, match data is set
  9336. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9337. on INACTIVE-OK."
  9338. (interactive)
  9339. (save-excursion
  9340. (catch 'exit
  9341. (let ((pos (point)))
  9342. (skip-chars-backward "^[<\r\n")
  9343. (skip-chars-backward "<[")
  9344. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9345. (>= (match-end 0) pos)
  9346. (throw 'exit t))
  9347. (skip-chars-backward "^<[\r\n")
  9348. (skip-chars-backward "<[")
  9349. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9350. (>= (match-end 0) pos)
  9351. (throw 'exit t)))
  9352. nil)))
  9353. (defun org-get-repeat (&optional timestamp)
  9354. "Check if there is a time-stamp with repeater in this entry.
  9355. Return the repeater, as a string, or nil. Also return nil when
  9356. this function is called before first heading.
  9357. When optional argument TIMESTAMP is a string, extract the
  9358. repeater from there instead."
  9359. (save-match-data
  9360. (cond (timestamp
  9361. (and (string-match org-repeat-re timestamp)
  9362. (match-string-no-properties 1 timestamp)))
  9363. ((org-before-first-heading-p) nil)
  9364. (t
  9365. (save-excursion
  9366. (org-back-to-heading t)
  9367. (let ((end (org-entry-end-position)))
  9368. (catch :repeat
  9369. (while (re-search-forward org-repeat-re end t)
  9370. (when (save-match-data (org-at-timestamp-p 'agenda))
  9371. (throw :repeat (match-string-no-properties 1)))))))))))
  9372. (defvar org-last-changed-timestamp)
  9373. (defvar org-last-inserted-timestamp)
  9374. (defvar org-log-post-message)
  9375. (defvar org-log-note-purpose)
  9376. (defvar org-log-note-how nil)
  9377. (defvar org-log-note-extra)
  9378. (defun org-auto-repeat-maybe (done-word)
  9379. "Check if the current headline contains a repeated time-stamp.
  9380. If yes, set TODO state back to what it was and change the base date
  9381. of repeating deadline/scheduled time stamps to new date.
  9382. This function is run automatically after each state change to a DONE state."
  9383. (let* ((repeat (org-get-repeat))
  9384. (aa (assoc org-last-state org-todo-kwd-alist))
  9385. (interpret (nth 1 aa))
  9386. (head (nth 2 aa))
  9387. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9388. (msg "Entry repeats: ")
  9389. (org-log-done nil)
  9390. (org-todo-log-states nil)
  9391. (end (copy-marker (org-entry-end-position))))
  9392. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9393. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9394. (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9395. (and (stringp org-todo-repeat-to-state)
  9396. org-todo-repeat-to-state)
  9397. (and org-todo-repeat-to-state org-last-state))))
  9398. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9399. to-state)
  9400. ((eq interpret 'type) org-last-state)
  9401. (head)
  9402. (t 'none))))
  9403. (org-back-to-heading t)
  9404. (org-add-planning-info nil nil 'closed)
  9405. ;; When `org-log-repeat' is non-nil or entry contains
  9406. ;; a clock, set LAST_REPEAT property.
  9407. (when (or org-log-repeat
  9408. (catch :clock
  9409. (save-excursion
  9410. (while (re-search-forward org-clock-line-re end t)
  9411. (when (org-at-clock-log-p) (throw :clock t))))))
  9412. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9413. (org-time-stamp-format t t))))
  9414. (when org-log-repeat
  9415. (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
  9416. (memq 'org-add-log-note post-command-hook))
  9417. ;; We are already setup for some record.
  9418. (when (eq org-log-repeat 'note)
  9419. ;; Make sure we take a note, not only a time stamp.
  9420. (setq org-log-note-how 'note))
  9421. ;; Set up for taking a record.
  9422. (org-add-log-setup 'state
  9423. (or done-word (car org-done-keywords))
  9424. org-last-state
  9425. org-log-repeat)))
  9426. ;; Time-stamps without a repeater are usually skipped. However,
  9427. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9428. ;; longer relevant.
  9429. (save-excursion
  9430. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9431. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9432. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9433. ;; Update every time-stamp with a repeater in the entry.
  9434. (let ((planning-re (regexp-opt
  9435. (list org-scheduled-string org-deadline-string))))
  9436. (while (re-search-forward org-repeat-re end t)
  9437. (let* ((ts (match-string 0))
  9438. (type (if (not (org-at-planning-p)) "Plain:"
  9439. (save-excursion
  9440. (re-search-backward
  9441. planning-re (line-beginning-position) t)
  9442. (match-string 0)))))
  9443. (when (and (org-at-timestamp-p 'agenda)
  9444. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9445. (let ((n (string-to-number (match-string 2 ts)))
  9446. (what (match-string 3 ts)))
  9447. (when (equal what "w") (setq n (* n 7) what "d"))
  9448. (when (and (equal what "h")
  9449. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9450. ts)))
  9451. (user-error
  9452. "Cannot repeat in %d hour(s) because no hour has been set"
  9453. n))
  9454. ;; Preparation, see if we need to modify the start
  9455. ;; date for the change.
  9456. (when (match-end 1)
  9457. (let ((time (save-match-data (org-time-string-to-time ts)))
  9458. (repeater-type (match-string 1 ts)))
  9459. (cond
  9460. ((equal "." repeater-type)
  9461. ;; Shift starting date to today, or now if
  9462. ;; repeater is by hours.
  9463. (if (equal what "h")
  9464. (org-timestamp-change
  9465. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9466. (org-timestamp-change
  9467. (- (org-today) (time-to-days time)) 'day)))
  9468. ((equal "+" repeater-type)
  9469. (let ((nshiftmax 10)
  9470. (nshift 0))
  9471. (while (or (= nshift 0)
  9472. (not (org-time-less-p nil time)))
  9473. (when (= nshiftmax (cl-incf nshift))
  9474. (or (y-or-n-p
  9475. (format "%d repeater intervals were not \
  9476. enough to shift date past today. Continue? "
  9477. nshift))
  9478. (user-error "Abort")))
  9479. (org-timestamp-change n (cdr (assoc what whata)))
  9480. (org-in-regexp org-ts-regexp3)
  9481. (setq ts (match-string 1))
  9482. (setq time
  9483. (save-match-data
  9484. (org-time-string-to-time ts)))))
  9485. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9486. ;; Rematch, so that we have everything in place
  9487. ;; for the real shift.
  9488. (org-in-regexp org-ts-regexp3)
  9489. (setq ts (match-string 1))
  9490. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9491. ts)))))
  9492. (save-excursion
  9493. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9494. (setq msg
  9495. (concat msg type " " org-last-changed-timestamp " ")))))))
  9496. (run-hooks 'org-todo-repeat-hook)
  9497. (setq org-log-post-message msg)
  9498. (message msg))))
  9499. (defun org-show-todo-tree (arg)
  9500. "Make a compact tree which shows all headlines marked with TODO.
  9501. The tree will show the lines where the regexp matches, and all higher
  9502. headlines above the match.
  9503. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9504. With a numeric prefix N, construct a sparse tree for the Nth element
  9505. of `org-todo-keywords-1'."
  9506. (interactive "P")
  9507. (let ((case-fold-search nil)
  9508. (kwd-re
  9509. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9510. ((equal arg '(4))
  9511. (let ((kwd
  9512. (completing-read "Keyword (or KWD1|KWD2|...): "
  9513. (mapcar #'list org-todo-keywords-1))))
  9514. (concat "\\("
  9515. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9516. "\\)\\>")))
  9517. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9518. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9519. org-todo-keywords-1)))
  9520. (t (user-error "Invalid prefix argument: %s" arg)))))
  9521. (message "%d TODO entries found"
  9522. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9523. (defun org--deadline-or-schedule (arg type time)
  9524. "Insert DEADLINE or SCHEDULE information in current entry.
  9525. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9526. `org-schedule' for information about ARG and TIME arguments."
  9527. (let* ((deadline? (eq type 'deadline))
  9528. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9529. (log (if deadline? org-log-redeadline org-log-reschedule))
  9530. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9531. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9532. ;; Save repeater cookie from either TIME or current scheduled
  9533. ;; time stamp. We are going to insert it back at the end of
  9534. ;; the process.
  9535. (repeater (or (and (org-string-nw-p time)
  9536. ;; We use `org-repeat-re' because we need
  9537. ;; to tell the difference between a real
  9538. ;; repeater and a time delta, e.g. "+2d".
  9539. (string-match org-repeat-re time)
  9540. (match-string 1 time))
  9541. (and (org-string-nw-p old-date)
  9542. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9543. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9544. old-date)
  9545. (match-string 1 old-date)))))
  9546. (pcase arg
  9547. (`(4)
  9548. (if (not old-date)
  9549. (message (if deadline? "Entry had no deadline to remove"
  9550. "Entry was not scheduled"))
  9551. (when (and old-date log)
  9552. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9553. nil old-date log))
  9554. (org-remove-timestamp-with-keyword keyword)
  9555. (message (if deadline? "Entry no longer has a deadline."
  9556. "Entry is no longer scheduled."))))
  9557. (`(16)
  9558. (save-excursion
  9559. (org-back-to-heading t)
  9560. (let ((regexp (if deadline? org-deadline-time-regexp
  9561. org-scheduled-time-regexp)))
  9562. (if (not (re-search-forward regexp (line-end-position 2) t))
  9563. (user-error (if deadline? "No deadline information to update"
  9564. "No scheduled information to update"))
  9565. (let* ((rpl0 (match-string 1))
  9566. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9567. (msg (if deadline? "Warn starting from" "Delay until")))
  9568. (replace-match
  9569. (concat keyword
  9570. " <" rpl
  9571. (format " -%dd"
  9572. (abs (- (time-to-days
  9573. (save-match-data
  9574. (org-read-date
  9575. nil t nil msg old-date-time)))
  9576. (time-to-days old-date-time))))
  9577. ">") t t))))))
  9578. (_
  9579. (org-add-planning-info type time 'closed)
  9580. (when (and old-date
  9581. log
  9582. (not (equal old-date org-last-inserted-timestamp)))
  9583. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9584. org-last-inserted-timestamp
  9585. old-date
  9586. log))
  9587. (when repeater
  9588. (save-excursion
  9589. (org-back-to-heading t)
  9590. (when (re-search-forward
  9591. (concat keyword " " org-last-inserted-timestamp)
  9592. (line-end-position 2)
  9593. t)
  9594. (goto-char (1- (match-end 0)))
  9595. (insert " " repeater)
  9596. (setq org-last-inserted-timestamp
  9597. (concat (substring org-last-inserted-timestamp 0 -1)
  9598. " " repeater
  9599. (substring org-last-inserted-timestamp -1))))))
  9600. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9601. org-last-inserted-timestamp)))))
  9602. (defun org-deadline (arg &optional time)
  9603. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9604. When called interactively, this command pops up the Emacs calendar to let
  9605. the user select a date.
  9606. With one universal prefix argument, remove any deadline from the item.
  9607. With two universal prefix arguments, prompt for a warning delay.
  9608. With argument TIME, set the deadline at the corresponding date. TIME
  9609. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9610. (interactive "P")
  9611. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9612. (org-map-entries
  9613. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9614. nil
  9615. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9616. 'region-start-level
  9617. 'region)
  9618. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9619. (org--deadline-or-schedule arg 'deadline time)))
  9620. (defun org-schedule (arg &optional time)
  9621. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9622. When called interactively, this command pops up the Emacs calendar to let
  9623. the user select a date.
  9624. With one universal prefix argument, remove any scheduling date from the item.
  9625. With two universal prefix arguments, prompt for a delay cookie.
  9626. With argument TIME, scheduled at the corresponding date. TIME can
  9627. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9628. (interactive "P")
  9629. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9630. (org-map-entries
  9631. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9632. nil
  9633. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9634. 'region-start-level
  9635. 'region)
  9636. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9637. (org--deadline-or-schedule arg 'scheduled time)))
  9638. (defun org-get-scheduled-time (pom &optional inherit)
  9639. "Get the scheduled time as a time tuple, of a format suitable
  9640. for calling org-schedule with, or if there is no scheduling,
  9641. returns nil."
  9642. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9643. (when time
  9644. (org-time-string-to-time time))))
  9645. (defun org-get-deadline-time (pom &optional inherit)
  9646. "Get the deadline as a time tuple, of a format suitable for
  9647. calling org-deadline with, or if there is no scheduling, returns
  9648. nil."
  9649. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9650. (when time
  9651. (org-time-string-to-time time))))
  9652. (defun org-remove-timestamp-with-keyword (keyword)
  9653. "Remove all time stamps with KEYWORD in the current entry."
  9654. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9655. beg)
  9656. (save-excursion
  9657. (org-back-to-heading t)
  9658. (setq beg (point))
  9659. (outline-next-heading)
  9660. (while (re-search-backward re beg t)
  9661. (replace-match "")
  9662. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9663. (equal (char-before) ?\ ))
  9664. (backward-delete-char 1)
  9665. (when (string-match "^[ \t]*$" (buffer-substring
  9666. (point-at-bol) (point-at-eol)))
  9667. (delete-region (point-at-bol)
  9668. (min (point-max) (1+ (point-at-eol))))))))))
  9669. (defvar org-time-was-given) ; dynamically scoped parameter
  9670. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9671. (defun org-at-planning-p ()
  9672. "Non-nil when point is on a planning info line."
  9673. ;; This is as accurate and faster than `org-element-at-point' since
  9674. ;; planning info location is fixed in the section.
  9675. (org-with-wide-buffer
  9676. (beginning-of-line)
  9677. (and (looking-at-p org-planning-line-re)
  9678. (eq (point)
  9679. (ignore-errors
  9680. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9681. (org-back-to-heading t)
  9682. (org-with-limited-levels (org-back-to-heading t)))
  9683. (line-beginning-position 2))))))
  9684. (defun org-add-planning-info (what &optional time &rest remove)
  9685. "Insert new timestamp with keyword in the planning line.
  9686. WHAT indicates what kind of time stamp to add. It is a symbol
  9687. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9688. the time to use. If none is given, the user is prompted for
  9689. a date. REMOVE indicates what kind of entries to remove. An old
  9690. WHAT entry will also be removed."
  9691. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9692. (when (and (memq what '(scheduled deadline))
  9693. (or (not time)
  9694. (and (stringp time)
  9695. (string-match "^[-+]+[0-9]" time))))
  9696. ;; Try to get a default date/time from existing timestamp
  9697. (save-excursion
  9698. (org-back-to-heading t)
  9699. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9700. (when (re-search-forward (if (eq what 'scheduled)
  9701. org-scheduled-time-regexp
  9702. org-deadline-time-regexp)
  9703. end t)
  9704. (setq ts (match-string 1)
  9705. default-time (org-time-string-to-time ts)
  9706. default-input (and ts (org-get-compact-tod ts)))))))
  9707. (when what
  9708. (setq time
  9709. (if (stringp time)
  9710. ;; This is a string (relative or absolute), set
  9711. ;; proper date.
  9712. (apply #'encode-time
  9713. (org-read-date-analyze
  9714. time default-time (decode-time default-time)))
  9715. ;; If necessary, get the time from the user
  9716. (or time (org-read-date nil 'to-time nil
  9717. (cl-case what
  9718. (deadline "DEADLINE")
  9719. (scheduled "SCHEDULED")
  9720. (otherwise nil))
  9721. default-time default-input)))))
  9722. (org-with-wide-buffer
  9723. (org-back-to-heading t)
  9724. (let ((planning? (save-excursion
  9725. (forward-line)
  9726. (looking-at-p org-planning-line-re))))
  9727. (cond
  9728. (planning?
  9729. (forward-line)
  9730. ;; Move to current indentation.
  9731. (skip-chars-forward " \t")
  9732. ;; Check if we have to remove something.
  9733. (dolist (type (if what (cons what remove) remove))
  9734. (save-excursion
  9735. (when (re-search-forward
  9736. (cl-case type
  9737. (closed org-closed-time-regexp)
  9738. (deadline org-deadline-time-regexp)
  9739. (scheduled org-scheduled-time-regexp)
  9740. (otherwise (error "Invalid planning type: %s" type)))
  9741. (line-end-position)
  9742. t)
  9743. ;; Delete until next keyword or end of line.
  9744. (delete-region
  9745. (match-beginning 0)
  9746. (if (re-search-forward org-keyword-time-not-clock-regexp
  9747. (line-end-position)
  9748. t)
  9749. (match-beginning 0)
  9750. (line-end-position))))))
  9751. ;; If there is nothing more to add and no more keyword is
  9752. ;; left, remove the line completely.
  9753. (if (and (looking-at-p "[ \t]*$") (not what))
  9754. (delete-region (line-end-position 0)
  9755. (line-end-position))
  9756. ;; If we removed last keyword, do not leave trailing white
  9757. ;; space at the end of line.
  9758. (let ((p (point)))
  9759. (save-excursion
  9760. (end-of-line)
  9761. (unless (= (skip-chars-backward " \t" p) 0)
  9762. (delete-region (point) (line-end-position)))))))
  9763. (what
  9764. (end-of-line)
  9765. (insert "\n")
  9766. (when org-adapt-indentation
  9767. (indent-to-column (1+ (org-outline-level)))))
  9768. (t nil)))
  9769. (when what
  9770. ;; Insert planning keyword.
  9771. (insert (cl-case what
  9772. (closed org-closed-string)
  9773. (deadline org-deadline-string)
  9774. (scheduled org-scheduled-string)
  9775. (otherwise (error "Invalid planning type: %s" what)))
  9776. " ")
  9777. ;; Insert associated timestamp.
  9778. (let ((ts (org-insert-time-stamp
  9779. time
  9780. (or org-time-was-given
  9781. (and (eq what 'closed) org-log-done-with-time))
  9782. (eq what 'closed)
  9783. nil nil (list org-end-time-was-given))))
  9784. (unless (eolp) (insert " "))
  9785. ts)))))
  9786. (defvar org-log-note-marker (make-marker)
  9787. "Marker pointing at the entry where the note is to be inserted.")
  9788. (defvar org-log-note-purpose nil)
  9789. (defvar org-log-note-state nil)
  9790. (defvar org-log-note-previous-state nil)
  9791. (defvar org-log-note-extra nil)
  9792. (defvar org-log-note-window-configuration nil)
  9793. (defvar org-log-note-return-to (make-marker))
  9794. (defvar org-log-note-effective-time nil
  9795. "Remembered current time.
  9796. So that dynamically scoped `org-extend-today-until' affects
  9797. timestamps in state change log.")
  9798. (defvar org-log-post-message nil
  9799. "Message to be displayed after a log note has been stored.
  9800. The auto-repeater uses this.")
  9801. (defun org-add-note ()
  9802. "Add a note to the current entry.
  9803. This is done in the same way as adding a state change note."
  9804. (interactive)
  9805. (org-add-log-setup 'note))
  9806. (defun org-log-beginning (&optional create)
  9807. "Return expected start of log notes in current entry.
  9808. When optional argument CREATE is non-nil, the function creates
  9809. a drawer to store notes, if necessary. Returned position ignores
  9810. narrowing."
  9811. (org-with-wide-buffer
  9812. (let ((drawer (org-log-into-drawer)))
  9813. (cond
  9814. (drawer
  9815. (org-end-of-meta-data)
  9816. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9817. (end (if (org-at-heading-p) (point)
  9818. (save-excursion (outline-next-heading) (point))))
  9819. (case-fold-search t))
  9820. (catch 'exit
  9821. ;; Try to find existing drawer.
  9822. (while (re-search-forward regexp end t)
  9823. (let ((element (org-element-at-point)))
  9824. (when (eq (org-element-type element) 'drawer)
  9825. (let ((cend (org-element-property :contents-end element)))
  9826. (when (and (not org-log-states-order-reversed) cend)
  9827. (goto-char cend)))
  9828. (throw 'exit nil))))
  9829. ;; No drawer found. Create one, if permitted.
  9830. (when create
  9831. (unless (bolp) (insert "\n"))
  9832. (let ((beg (point)))
  9833. (insert ":" drawer ":\n:END:\n")
  9834. (org-indent-region beg (point))
  9835. (org-flag-region (line-end-position -1) (1- (point)) t 'outline))
  9836. (end-of-line -1)))))
  9837. (t
  9838. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9839. (skip-chars-forward " \t\n")
  9840. (beginning-of-line)
  9841. (unless org-log-states-order-reversed
  9842. (org-skip-over-state-notes)
  9843. (skip-chars-backward " \t\n")
  9844. (forward-line)))))
  9845. (if (bolp) (point) (line-beginning-position 2))))
  9846. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9847. "Set up the post command hook to take a note.
  9848. If this is about to TODO state change, the new state is expected in STATE.
  9849. HOW is an indicator what kind of note should be created.
  9850. EXTRA is additional text that will be inserted into the notes buffer."
  9851. (move-marker org-log-note-marker (point))
  9852. (setq org-log-note-purpose purpose
  9853. org-log-note-state state
  9854. org-log-note-previous-state prev-state
  9855. org-log-note-how how
  9856. org-log-note-extra extra
  9857. org-log-note-effective-time (org-current-effective-time))
  9858. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9859. (defun org-skip-over-state-notes ()
  9860. "Skip past the list of State notes in an entry."
  9861. (when (ignore-errors (goto-char (org-in-item-p)))
  9862. (let* ((struct (org-list-struct))
  9863. (prevs (org-list-prevs-alist struct))
  9864. (regexp
  9865. (concat "[ \t]*- +"
  9866. (replace-regexp-in-string
  9867. " +" " +"
  9868. (org-replace-escapes
  9869. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9870. `(("%d" . ,org-ts-regexp-inactive)
  9871. ("%D" . ,org-ts-regexp)
  9872. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9873. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9874. ("%t" . ,org-ts-regexp-inactive)
  9875. ("%T" . ,org-ts-regexp)
  9876. ("%u" . ".*?")
  9877. ("%U" . ".*?")))))))
  9878. (while (looking-at-p regexp)
  9879. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9880. (org-list-get-item-end (point) struct)))))))
  9881. (defun org-add-log-note (&optional _purpose)
  9882. "Pop up a window for taking a note, and add this note later."
  9883. (remove-hook 'post-command-hook 'org-add-log-note)
  9884. (setq org-log-note-window-configuration (current-window-configuration))
  9885. (delete-other-windows)
  9886. (move-marker org-log-note-return-to (point))
  9887. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9888. (goto-char org-log-note-marker)
  9889. (org-switch-to-buffer-other-window "*Org Note*")
  9890. (erase-buffer)
  9891. (if (memq org-log-note-how '(time state))
  9892. (org-store-log-note)
  9893. (let ((org-inhibit-startup t)) (org-mode))
  9894. (insert (format "# Insert note for %s.
  9895. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9896. (cl-case org-log-note-purpose
  9897. (clock-out "stopped clock")
  9898. (done "closed todo item")
  9899. (reschedule "rescheduling")
  9900. (delschedule "no longer scheduled")
  9901. (redeadline "changing deadline")
  9902. (deldeadline "removing deadline")
  9903. (refile "refiling")
  9904. (note "this entry")
  9905. (state
  9906. (format "state change from \"%s\" to \"%s\""
  9907. (or org-log-note-previous-state "")
  9908. (or org-log-note-state "")))
  9909. (t (error "This should not happen")))))
  9910. (when org-log-note-extra (insert org-log-note-extra))
  9911. (setq-local org-finish-function 'org-store-log-note)
  9912. (run-hooks 'org-log-buffer-setup-hook)))
  9913. (defvar org-note-abort nil) ; dynamically scoped
  9914. (defun org-store-log-note ()
  9915. "Finish taking a log note, and insert it to where it belongs."
  9916. (let ((txt (prog1 (buffer-string)
  9917. (kill-buffer)))
  9918. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9919. lines)
  9920. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9921. (setq txt (replace-match "" t t txt)))
  9922. (when (string-match "\\s-+\\'" txt)
  9923. (setq txt (replace-match "" t t txt)))
  9924. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9925. (when (org-string-nw-p note)
  9926. (setq note
  9927. (org-replace-escapes
  9928. note
  9929. (list (cons "%u" (user-login-name))
  9930. (cons "%U" user-full-name)
  9931. (cons "%t" (format-time-string
  9932. (org-time-stamp-format 'long 'inactive)
  9933. org-log-note-effective-time))
  9934. (cons "%T" (format-time-string
  9935. (org-time-stamp-format 'long nil)
  9936. org-log-note-effective-time))
  9937. (cons "%d" (format-time-string
  9938. (org-time-stamp-format nil 'inactive)
  9939. org-log-note-effective-time))
  9940. (cons "%D" (format-time-string
  9941. (org-time-stamp-format nil nil)
  9942. org-log-note-effective-time))
  9943. (cons "%s" (cond
  9944. ((not org-log-note-state) "")
  9945. ((string-match-p org-ts-regexp
  9946. org-log-note-state)
  9947. (format "\"[%s]\""
  9948. (substring org-log-note-state 1 -1)))
  9949. (t (format "\"%s\"" org-log-note-state))))
  9950. (cons "%S"
  9951. (cond
  9952. ((not org-log-note-previous-state) "")
  9953. ((string-match-p org-ts-regexp
  9954. org-log-note-previous-state)
  9955. (format "\"[%s]\""
  9956. (substring
  9957. org-log-note-previous-state 1 -1)))
  9958. (t (format "\"%s\""
  9959. org-log-note-previous-state)))))))
  9960. (when lines (setq note (concat note " \\\\")))
  9961. (push note lines))
  9962. (when (and lines (not org-note-abort))
  9963. (with-current-buffer (marker-buffer org-log-note-marker)
  9964. (org-with-wide-buffer
  9965. ;; Find location for the new note.
  9966. (goto-char org-log-note-marker)
  9967. (set-marker org-log-note-marker nil)
  9968. ;; Note associated to a clock is to be located right after
  9969. ;; the clock. Do not move point.
  9970. (unless (eq org-log-note-purpose 'clock-out)
  9971. (goto-char (org-log-beginning t)))
  9972. ;; Make sure point is at the beginning of an empty line.
  9973. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  9974. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  9975. ;; In an existing list, add a new item at the top level.
  9976. ;; Otherwise, indent line like a regular one.
  9977. (let ((itemp (org-in-item-p)))
  9978. (if itemp
  9979. (indent-line-to
  9980. (let ((struct (save-excursion
  9981. (goto-char itemp) (org-list-struct))))
  9982. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9983. (org-indent-line)))
  9984. (insert (org-list-bullet-string "-") (pop lines))
  9985. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9986. (dolist (line lines)
  9987. (insert "\n")
  9988. (indent-line-to ind)
  9989. (insert line)))
  9990. (message "Note stored")
  9991. (org-back-to-heading t))
  9992. ;; Fix `buffer-undo-list' when `org-store-log-note' is called
  9993. ;; from within `org-add-log-note' because `buffer-undo-list'
  9994. ;; is then modified outside of `org-with-remote-undo'.
  9995. (when (eq this-command 'org-agenda-todo)
  9996. (setcdr buffer-undo-list (cddr buffer-undo-list))))))
  9997. ;; Don't add undo information when called from `org-agenda-todo'.
  9998. (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
  9999. (set-window-configuration org-log-note-window-configuration)
  10000. (with-current-buffer (marker-buffer org-log-note-return-to)
  10001. (goto-char org-log-note-return-to))
  10002. (move-marker org-log-note-return-to nil)
  10003. (when org-log-post-message (message "%s" org-log-post-message))))
  10004. (defun org-remove-empty-drawer-at (pos)
  10005. "Remove an empty drawer at position POS.
  10006. POS may also be a marker."
  10007. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10008. (org-with-wide-buffer
  10009. (goto-char pos)
  10010. (let ((drawer (org-element-at-point)))
  10011. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10012. (not (org-element-property :contents-begin drawer)))
  10013. (delete-region (org-element-property :begin drawer)
  10014. (progn (goto-char (org-element-property :end drawer))
  10015. (skip-chars-backward " \r\t\n")
  10016. (forward-line)
  10017. (point))))))))
  10018. (defvar org-ts-type nil)
  10019. (defun org-sparse-tree (&optional arg type)
  10020. "Create a sparse tree, prompt for the details.
  10021. This command can create sparse trees. You first need to select the type
  10022. of match used to create the tree:
  10023. t Show all TODO entries.
  10024. T Show entries with a specific TODO keyword.
  10025. m Show entries selected by a tags/property match.
  10026. p Enter a property name and its value (both with completion on existing
  10027. names/values) and show entries with that property.
  10028. r Show entries matching a regular expression (`/' can be used as well).
  10029. b Show deadlines and scheduled items before a date.
  10030. a Show deadlines and scheduled items after a date.
  10031. d Show deadlines due within `org-deadline-warning-days'.
  10032. D Show deadlines and scheduled items between a date range."
  10033. (interactive "P")
  10034. (setq type (or type org-sparse-tree-default-date-type))
  10035. (setq org-ts-type type)
  10036. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10037. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10038. [c]ycle through date types: %s"
  10039. (cl-case type
  10040. (all "all timestamps")
  10041. (scheduled "only scheduled")
  10042. (deadline "only deadline")
  10043. (active "only active timestamps")
  10044. (inactive "only inactive timestamps")
  10045. (closed "with a closed time-stamp")
  10046. (otherwise "scheduled/deadline")))
  10047. (let ((answer (read-char-exclusive)))
  10048. (cl-case answer
  10049. (?c
  10050. (org-sparse-tree
  10051. arg
  10052. (cadr
  10053. (memq type '(nil all scheduled deadline active inactive closed)))))
  10054. (?d (call-interactively 'org-check-deadlines))
  10055. (?b (call-interactively 'org-check-before-date))
  10056. (?a (call-interactively 'org-check-after-date))
  10057. (?D (call-interactively 'org-check-dates-range))
  10058. (?t (call-interactively 'org-show-todo-tree))
  10059. (?T (org-show-todo-tree '(4)))
  10060. (?m (call-interactively 'org-match-sparse-tree))
  10061. ((?p ?P)
  10062. (let* ((kwd (completing-read
  10063. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10064. (value (completing-read
  10065. "Value: " (mapcar #'list (org-property-values kwd)))))
  10066. (unless (string-match "\\`{.*}\\'" value)
  10067. (setq value (concat "\"" value "\"")))
  10068. (org-match-sparse-tree arg (concat kwd "=" value))))
  10069. ((?r ?R ?/) (call-interactively 'org-occur))
  10070. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10071. (defvar-local org-occur-highlights nil
  10072. "List of overlays used for occur matches.")
  10073. (defvar-local org-occur-parameters nil
  10074. "Parameters of the active org-occur calls.
  10075. This is a list, each call to org-occur pushes as cons cell,
  10076. containing the regular expression and the callback, onto the list.
  10077. The list can contain several entries if `org-occur' has been called
  10078. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10079. will only contain one set of parameters. When the highlights are
  10080. removed (for example with `C-c C-c', or with the next edit (depending
  10081. on `org-remove-highlights-with-change'), this variable is emptied
  10082. as well.")
  10083. (defun org-occur (regexp &optional keep-previous callback)
  10084. "Make a compact tree showing all matches of REGEXP.
  10085. The tree will show the lines where the regexp matches, and any other context
  10086. defined in `org-show-context-detail', which see.
  10087. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10088. done by a previous call to `org-occur' will be kept, to allow stacking of
  10089. calls to this command.
  10090. Optional argument CALLBACK can be a function of no argument. In this case,
  10091. it is called with point at the end of the match, match data being set
  10092. accordingly. Current match is shown only if the return value is non-nil.
  10093. The function must neither move point nor alter narrowing."
  10094. (interactive "sRegexp: \nP")
  10095. (when (equal regexp "")
  10096. (user-error "Regexp cannot be empty"))
  10097. (unless keep-previous
  10098. (org-remove-occur-highlights nil nil t))
  10099. (push (cons regexp callback) org-occur-parameters)
  10100. (let ((cnt 0))
  10101. (save-excursion
  10102. (goto-char (point-min))
  10103. (when (or (not keep-previous) ; do not want to keep
  10104. (not org-occur-highlights)) ; no previous matches
  10105. ;; hide everything
  10106. (org-overview))
  10107. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10108. (isearch-no-upper-case-p regexp t)
  10109. org-occur-case-fold-search)))
  10110. (while (re-search-forward regexp nil t)
  10111. (when (or (not callback)
  10112. (save-match-data (funcall callback)))
  10113. (setq cnt (1+ cnt))
  10114. (when org-highlight-sparse-tree-matches
  10115. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10116. (org-show-context 'occur-tree)))))
  10117. (when org-remove-highlights-with-change
  10118. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10119. nil 'local))
  10120. (unless org-sparse-tree-open-archived-trees
  10121. (org-hide-archived-subtrees (point-min) (point-max)))
  10122. (run-hooks 'org-occur-hook)
  10123. (when (called-interactively-p 'interactive)
  10124. (message "%d match(es) for regexp %s" cnt regexp))
  10125. cnt))
  10126. (defun org-occur-next-match (&optional n _reset)
  10127. "Function for `next-error-function' to find sparse tree matches.
  10128. N is the number of matches to move, when negative move backwards.
  10129. This function always goes back to the starting point when no
  10130. match is found."
  10131. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10132. (search-func (if (< n 0)
  10133. 'previous-single-char-property-change
  10134. 'next-single-char-property-change))
  10135. (n (abs n))
  10136. (pos (point))
  10137. p1)
  10138. (catch 'exit
  10139. (while (setq p1 (funcall search-func (point) 'org-type))
  10140. (when (equal p1 limit)
  10141. (goto-char pos)
  10142. (user-error "No more matches"))
  10143. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10144. (setq n (1- n))
  10145. (when (= n 0)
  10146. (goto-char p1)
  10147. (throw 'exit (point))))
  10148. (goto-char p1))
  10149. (goto-char p1)
  10150. (user-error "No more matches"))))
  10151. (defun org-highlight-new-match (beg end)
  10152. "Highlight from BEG to END and mark the highlight is an occur headline."
  10153. (let ((ov (make-overlay beg end)))
  10154. (overlay-put ov 'face 'secondary-selection)
  10155. (overlay-put ov 'org-type 'org-occur)
  10156. (push ov org-occur-highlights)))
  10157. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10158. "Remove the occur highlights from the buffer.
  10159. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10160. from the `before-change-functions' in the current buffer."
  10161. (interactive)
  10162. (unless org-inhibit-highlight-removal
  10163. (mapc #'delete-overlay org-occur-highlights)
  10164. (setq org-occur-highlights nil)
  10165. (setq org-occur-parameters nil)
  10166. (unless noremove
  10167. (remove-hook 'before-change-functions
  10168. 'org-remove-occur-highlights 'local))))
  10169. ;;;; Priorities
  10170. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10171. "Regular expression matching the priority indicator.
  10172. A priority indicator can be e.g. [#A] or [#1].
  10173. This regular expression matches these groups:
  10174. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10175. 1 : the priority cookie, e.g. \"[#A]\"
  10176. 2 : the value of the priority cookie, e.g. \"A\".")
  10177. (defun org-priority-up ()
  10178. "Increase the priority of the current item."
  10179. (interactive)
  10180. (org-priority 'up))
  10181. (defun org-priority-down ()
  10182. "Decrease the priority of the current item."
  10183. (interactive)
  10184. (org-priority 'down))
  10185. (defun org-priority (&optional action show)
  10186. "Change the priority of an item.
  10187. When called interactively with a `\\[universal-argument]' prefix,
  10188. show the priority in the minibuffer instead of changing it.
  10189. When called programmatically, ACTION can be `set', `up', `down',
  10190. or a character."
  10191. (interactive "P")
  10192. (when show
  10193. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10194. ;; passed the SHOW argument should be removed.
  10195. (warn "`org-priority' called with deprecated SHOW argument"))
  10196. (if (equal action '(4))
  10197. (org-priority-show)
  10198. (unless org-priority-enable-commands
  10199. (user-error "Priority commands are disabled"))
  10200. (setq action (or action 'set))
  10201. (let ((nump (< org-priority-lowest 65))
  10202. current new news have remove)
  10203. (save-excursion
  10204. (org-back-to-heading t)
  10205. (when (looking-at org-priority-regexp)
  10206. (let ((ms (match-string 2)))
  10207. (setq current (org-priority-to-value ms)
  10208. have t)))
  10209. (cond
  10210. ((eq action 'remove)
  10211. (setq remove t new ?\ ))
  10212. ((or (eq action 'set)
  10213. (integerp action))
  10214. (if (not (eq action 'set))
  10215. (setq new action)
  10216. (setq
  10217. new
  10218. (if nump
  10219. (let ((msg (format "Priority %s-%s, SPC to remove: "
  10220. (number-to-string org-priority-highest)
  10221. (number-to-string org-priority-lowest))))
  10222. (if (< 9 org-priority-lowest)
  10223. (string-to-number (read-string msg))
  10224. (message msg)
  10225. (string-to-number (char-to-string (read-char-exclusive)))))
  10226. (progn (message "Priority %c-%c, SPC to remove: "
  10227. org-priority-highest org-priority-lowest)
  10228. (save-match-data
  10229. (setq new (read-char-exclusive)))))))
  10230. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10231. (= (upcase org-priority-lowest) org-priority-lowest))
  10232. (setq new (upcase new)))
  10233. (cond ((equal new ?\s) (setq remove t))
  10234. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10235. (user-error
  10236. (if nump
  10237. "Priority must be between `%s' and `%s'"
  10238. "Priority must be between `%c' and `%c'")
  10239. org-priority-highest org-priority-lowest))))
  10240. ((eq action 'up)
  10241. (setq new (if have
  10242. (1- current) ; normal cycling
  10243. ;; last priority was empty
  10244. (if (eq last-command this-command)
  10245. org-priority-lowest ; wrap around empty to lowest
  10246. ;; default
  10247. (if org-priority-start-cycle-with-default
  10248. org-priority-default
  10249. (1- org-priority-default))))))
  10250. ((eq action 'down)
  10251. (setq new (if have
  10252. (1+ current) ; normal cycling
  10253. ;; last priority was empty
  10254. (if (eq last-command this-command)
  10255. org-priority-highest ; wrap around empty to highest
  10256. ;; default
  10257. (if org-priority-start-cycle-with-default
  10258. org-priority-default
  10259. (1+ org-priority-default))))))
  10260. (t (user-error "Invalid action")))
  10261. (when (or (< (upcase new) org-priority-highest)
  10262. (> (upcase new) org-priority-lowest))
  10263. (if (and (memq action '(up down))
  10264. (not have) (not (eq last-command this-command)))
  10265. ;; `new' is from default priority
  10266. (error
  10267. "The default can not be set, see `org-priority-default' why")
  10268. ;; normal cycling: `new' is beyond highest/lowest priority
  10269. ;; and is wrapped around to the empty priority
  10270. (setq remove t)))
  10271. ;; Numerical priorities are limited to 64, beyond that number,
  10272. ;; assume the priority cookie is a character.
  10273. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10274. (if have
  10275. (if remove
  10276. (replace-match "" t t nil 1)
  10277. (replace-match news t t nil 2))
  10278. (if remove
  10279. (user-error "No priority cookie found in line")
  10280. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10281. (if (match-end 2)
  10282. (progn
  10283. (goto-char (match-end 2))
  10284. (insert " [#" news "]"))
  10285. (goto-char (match-beginning 3))
  10286. (insert "[#" news "] "))))
  10287. (org-align-tags))
  10288. (if remove
  10289. (message "Priority removed")
  10290. (message "Priority of current item set to %s" news)))))
  10291. (defalias 'org-show-priority 'org-priority-show)
  10292. (defun org-priority-show ()
  10293. "Show the priority of the current item.
  10294. This priority is composed of the main priority given with the [#A] cookies,
  10295. and by additional input from the age of a schedules or deadline entry."
  10296. (interactive)
  10297. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10298. (org-get-at-bol 'priority)
  10299. (save-excursion
  10300. (save-match-data
  10301. (beginning-of-line)
  10302. (and (looking-at org-heading-regexp)
  10303. (org-get-priority (match-string 0))))))))
  10304. (message "Priority is %d" (if pri pri -1000))))
  10305. (defun org-get-priority (s)
  10306. "Find priority cookie and return priority.
  10307. S is a string against which you can match `org-priority-regexp'.
  10308. If `org-priority-get-priority-function' is set to a custom
  10309. function, use it. Otherwise process S and output the priority
  10310. value, an integer."
  10311. (save-match-data
  10312. (if (functionp org-priority-get-priority-function)
  10313. (funcall org-priority-get-priority-function s)
  10314. (if (not (string-match org-priority-regexp s))
  10315. (* 1000 (- org-priority-lowest org-priority-default))
  10316. (* 1000 (- org-priority-lowest
  10317. (org-priority-to-value (match-string 2 s))))))))
  10318. ;;;; Tags
  10319. (defvar org-agenda-archives-mode)
  10320. (defvar org-map-continue-from nil
  10321. "Position from where mapping should continue.
  10322. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10323. (defvar org-scanner-tags nil
  10324. "The current tag list while the tags scanner is running.")
  10325. (defvar org-trust-scanner-tags nil
  10326. "Should `org-get-tags' use the tags for the scanner.
  10327. This is for internal dynamical scoping only.
  10328. When this is non-nil, the function `org-get-tags' will return the value
  10329. of `org-scanner-tags' instead of building the list by itself. This
  10330. can lead to large speed-ups when the tags scanner is used in a file with
  10331. many entries, and when the list of tags is retrieved, for example to
  10332. obtain a list of properties. Building the tags list for each entry in such
  10333. a file becomes an N^2 operation - but with this variable set, it scales
  10334. as N.")
  10335. (defvar org--matcher-tags-todo-only nil)
  10336. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10337. "Scan headline tags with inheritance and produce output ACTION.
  10338. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10339. or `agenda' to produce an entry list for an agenda view. It can also be
  10340. a Lisp form or a function that should be called at each matched headline, in
  10341. this case the return value is a list of all return values from these calls.
  10342. MATCHER is a function accepting three arguments, returning
  10343. a non-nil value whenever a given set of tags qualifies a headline
  10344. for inclusion. See `org-make-tags-matcher' for more information.
  10345. As a special case, it can also be set to t (respectively nil) in
  10346. order to match all (respectively none) headline.
  10347. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10348. included in the output.
  10349. START-LEVEL can be a string with asterisks, reducing the scope to
  10350. headlines matching this string."
  10351. (require 'org-agenda)
  10352. (let* ((re (concat "^"
  10353. (if start-level
  10354. ;; Get the correct level to match
  10355. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10356. org-outline-regexp)
  10357. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10358. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10359. (props (list 'face 'default
  10360. 'done-face 'org-agenda-done
  10361. 'undone-face 'default
  10362. 'mouse-face 'highlight
  10363. 'org-not-done-regexp org-not-done-regexp
  10364. 'org-todo-regexp org-todo-regexp
  10365. 'org-complex-heading-regexp org-complex-heading-regexp
  10366. 'help-echo
  10367. (format "mouse-2 or RET jump to Org file %S"
  10368. (abbreviate-file-name
  10369. (or (buffer-file-name (buffer-base-buffer))
  10370. (buffer-name (buffer-base-buffer)))))))
  10371. (org-map-continue-from nil)
  10372. lspos tags tags-list
  10373. (tags-alist (list (cons 0 org-file-tags)))
  10374. (llast 0) rtn rtn1 level category i txt
  10375. todo marker entry priority
  10376. ts-date ts-date-type ts-date-pair)
  10377. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10378. (setq action (list 'lambda nil action)))
  10379. (save-excursion
  10380. (goto-char (point-min))
  10381. (when (eq action 'sparse-tree)
  10382. (org-overview)
  10383. (org-remove-occur-highlights))
  10384. (while (let (case-fold-search)
  10385. (re-search-forward re nil t))
  10386. (setq org-map-continue-from nil)
  10387. (catch :skip
  10388. ;; Ignore closing parts of inline tasks.
  10389. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10390. (throw :skip t))
  10391. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10392. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10393. (goto-char (setq lspos (match-beginning 0)))
  10394. (setq level (org-reduced-level (org-outline-level))
  10395. category (org-get-category))
  10396. (when (eq action 'agenda)
  10397. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10398. ts-date (car ts-date-pair)
  10399. ts-date-type (cdr ts-date-pair)))
  10400. (setq i llast llast level)
  10401. ;; remove tag lists from same and sublevels
  10402. (while (>= i level)
  10403. (when (setq entry (assoc i tags-alist))
  10404. (setq tags-alist (delete entry tags-alist)))
  10405. (setq i (1- i)))
  10406. ;; add the next tags
  10407. (when tags
  10408. (setq tags (org-split-string tags ":")
  10409. tags-alist
  10410. (cons (cons level tags) tags-alist)))
  10411. ;; compile tags for current headline
  10412. (setq tags-list
  10413. (if org-use-tag-inheritance
  10414. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10415. tags)
  10416. org-scanner-tags tags-list)
  10417. (when org-use-tag-inheritance
  10418. (setcdr (car tags-alist)
  10419. (mapcar (lambda (x)
  10420. (setq x (copy-sequence x))
  10421. (org-add-prop-inherited x))
  10422. (cdar tags-alist))))
  10423. (when (and tags org-use-tag-inheritance
  10424. (or (not (eq t org-use-tag-inheritance))
  10425. org-tags-exclude-from-inheritance))
  10426. ;; Selective inheritance, remove uninherited ones.
  10427. (setcdr (car tags-alist)
  10428. (org-remove-uninherited-tags (cdar tags-alist))))
  10429. (when (and
  10430. ;; eval matcher only when the todo condition is OK
  10431. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10432. (if (functionp matcher)
  10433. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10434. (funcall matcher todo tags-list level))
  10435. matcher))
  10436. ;; Call the skipper, but return t if it does not
  10437. ;; skip, so that the `and' form continues evaluating.
  10438. (progn
  10439. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10440. t)
  10441. ;; Check if timestamps are deselecting this entry
  10442. (or (not todo-only)
  10443. (and (member todo org-todo-keywords-1)
  10444. (or (not org-agenda-tags-todo-honor-ignore-options)
  10445. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10446. ;; select this headline
  10447. (cond
  10448. ((eq action 'sparse-tree)
  10449. (and org-highlight-sparse-tree-matches
  10450. (org-get-heading) (match-end 0)
  10451. (org-highlight-new-match
  10452. (match-beginning 1) (match-end 1)))
  10453. (org-show-context 'tags-tree))
  10454. ((eq action 'agenda)
  10455. (setq txt (org-agenda-format-item
  10456. ""
  10457. (concat
  10458. (if (eq org-tags-match-list-sublevels 'indented)
  10459. (make-string (1- level) ?.) "")
  10460. (org-get-heading))
  10461. (make-string level ?\s)
  10462. category
  10463. tags-list)
  10464. priority (org-get-priority txt))
  10465. (goto-char lspos)
  10466. (setq marker (org-agenda-new-marker))
  10467. (org-add-props txt props
  10468. 'org-marker marker 'org-hd-marker marker 'org-category category
  10469. 'todo-state todo
  10470. 'ts-date ts-date
  10471. 'priority priority
  10472. 'type (concat "tagsmatch" ts-date-type))
  10473. (push txt rtn))
  10474. ((functionp action)
  10475. (setq org-map-continue-from nil)
  10476. (save-excursion
  10477. (setq rtn1 (funcall action))
  10478. (push rtn1 rtn)))
  10479. (t (user-error "Invalid action")))
  10480. ;; if we are to skip sublevels, jump to end of subtree
  10481. (unless org-tags-match-list-sublevels
  10482. (org-end-of-subtree t)
  10483. (backward-char 1))))
  10484. ;; Get the correct position from where to continue
  10485. (if org-map-continue-from
  10486. (goto-char org-map-continue-from)
  10487. (and (= (point) lspos) (end-of-line 1)))))
  10488. (when (and (eq action 'sparse-tree)
  10489. (not org-sparse-tree-open-archived-trees))
  10490. (org-hide-archived-subtrees (point-min) (point-max)))
  10491. (nreverse rtn)))
  10492. (defun org-remove-uninherited-tags (tags)
  10493. "Remove all tags that are not inherited from the list TAGS."
  10494. (cond
  10495. ((eq org-use-tag-inheritance t)
  10496. (if org-tags-exclude-from-inheritance
  10497. (org-delete-all org-tags-exclude-from-inheritance tags)
  10498. tags))
  10499. ((not org-use-tag-inheritance) nil)
  10500. ((stringp org-use-tag-inheritance)
  10501. (delq nil (mapcar
  10502. (lambda (x)
  10503. (if (and (string-match org-use-tag-inheritance x)
  10504. (not (member x org-tags-exclude-from-inheritance)))
  10505. x nil))
  10506. tags)))
  10507. ((listp org-use-tag-inheritance)
  10508. (delq nil (mapcar
  10509. (lambda (x)
  10510. (if (member x org-use-tag-inheritance) x nil))
  10511. tags)))))
  10512. (defun org-match-sparse-tree (&optional todo-only match)
  10513. "Create a sparse tree according to tags string MATCH.
  10514. MATCH is a string with match syntax. It can contain a selection
  10515. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10516. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10517. those. See the manual for details.
  10518. If optional argument TODO-ONLY is non-nil, only select lines that
  10519. are also TODO tasks."
  10520. (interactive "P")
  10521. (org-agenda-prepare-buffers (list (current-buffer)))
  10522. (let ((org--matcher-tags-todo-only todo-only))
  10523. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10524. org--matcher-tags-todo-only)))
  10525. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10526. (defvar org-cached-props nil)
  10527. (defun org-cached-entry-get (pom property)
  10528. (if (or (eq t org-use-property-inheritance)
  10529. (and (stringp org-use-property-inheritance)
  10530. (let ((case-fold-search t))
  10531. (string-match-p org-use-property-inheritance property)))
  10532. (and (listp org-use-property-inheritance)
  10533. (member-ignore-case property org-use-property-inheritance)))
  10534. ;; Caching is not possible, check it directly.
  10535. (org-entry-get pom property 'inherit)
  10536. ;; Get all properties, so we can do complicated checks easily.
  10537. (cdr (assoc-string property
  10538. (or org-cached-props
  10539. (setq org-cached-props (org-entry-properties pom)))
  10540. t))))
  10541. (defun org-global-tags-completion-table (&optional files)
  10542. "Return the list of all tags in all agenda buffer/files.
  10543. Optional FILES argument is a list of files which can be used
  10544. instead of the agenda files."
  10545. (save-excursion
  10546. (org-uniquify
  10547. (delq nil
  10548. (apply #'append
  10549. (mapcar
  10550. (lambda (file)
  10551. (set-buffer (find-file-noselect file))
  10552. (org--tag-add-to-alist
  10553. (org-get-buffer-tags)
  10554. (mapcar (lambda (x)
  10555. (and (stringp (car-safe x))
  10556. (list (car-safe x))))
  10557. org-current-tag-alist)))
  10558. (if (car-safe files) files
  10559. (org-agenda-files))))))))
  10560. (defun org-make-tags-matcher (match &optional only-local-tags)
  10561. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10562. Returns a cons of the selection string MATCH and a function
  10563. implementing the matcher.
  10564. The matcher is to be called at an Org entry, with point on the
  10565. headline, and returns non-nil if the entry matches the selection
  10566. string MATCH. It must be called with three arguments: the TODO
  10567. keyword at the entry (or nil if none), the list of all tags at
  10568. the entry including inherited ones and the reduced level of the
  10569. headline. Additionally, the category of the entry, if any, must
  10570. be specified as the text property `org-category' on the headline.
  10571. This function sets the variable `org--matcher-tags-todo-only' to
  10572. a non-nil value if the matcher restricts matching to TODO
  10573. entries, otherwise it is not touched.
  10574. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10575. table, only get buffer tags.
  10576. See also `org-scan-tags'."
  10577. (unless match
  10578. ;; Get a new match request, with completion against the global
  10579. ;; tags table and the local tags in current buffer.
  10580. (let ((org-last-tags-completion-table
  10581. (org--tag-add-to-alist
  10582. (org-get-buffer-tags)
  10583. (unless only-local-tags
  10584. (org-global-tags-completion-table)))))
  10585. (setq match
  10586. (completing-read
  10587. "Match: "
  10588. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10589. (let ((match0 match)
  10590. (re (concat
  10591. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10592. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10593. "\\([<>=]\\{1,2\\}\\)"
  10594. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10595. "\\|" org-tag-re "\\)"))
  10596. (start 0)
  10597. tagsmatch todomatch tagsmatcher todomatcher)
  10598. ;; Expand group tags.
  10599. (setq match (org-tags-expand match))
  10600. ;; Check if there is a TODO part of this match, which would be the
  10601. ;; part after a "/". To make sure that this slash is not part of
  10602. ;; a property value to be matched against, we also check that
  10603. ;; there is no / after that slash. First, find the last slash.
  10604. (let ((s 0))
  10605. (while (string-match "/+" match s)
  10606. (setq start (match-beginning 0))
  10607. (setq s (match-end 0))))
  10608. (if (and (string-match "/+" match start)
  10609. (not (string-match-p "\"" match start)))
  10610. ;; Match contains also a TODO-matching request.
  10611. (progn
  10612. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10613. (setq todomatch (substring match (match-end 0)))
  10614. (when (string-prefix-p "!" todomatch)
  10615. (setq org--matcher-tags-todo-only t)
  10616. (setq todomatch (substring todomatch 1)))
  10617. (when (string-match "\\`\\s-*\\'" todomatch)
  10618. (setq todomatch nil)))
  10619. ;; Only matching tags.
  10620. (setq tagsmatch match)
  10621. (setq todomatch nil))
  10622. ;; Make the tags matcher.
  10623. (when (org-string-nw-p tagsmatch)
  10624. (let ((orlist nil)
  10625. (orterms (org-split-string tagsmatch "|"))
  10626. term)
  10627. (while (setq term (pop orterms))
  10628. (while (and (equal (substring term -1) "\\") orterms)
  10629. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10630. (while (string-match re term)
  10631. (let* ((rest (substring term (match-end 0)))
  10632. (minus (and (match-end 1)
  10633. (equal (match-string 1 term) "-")))
  10634. (tag (save-match-data
  10635. (replace-regexp-in-string
  10636. "\\\\-" "-" (match-string 2 term))))
  10637. (regexp (eq (string-to-char tag) ?{))
  10638. (levelp (match-end 4))
  10639. (propp (match-end 5))
  10640. (mm
  10641. (cond
  10642. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10643. (levelp
  10644. `(,(org-op-to-function (match-string 3 term))
  10645. level
  10646. ,(string-to-number (match-string 4 term))))
  10647. (propp
  10648. (let* ((gv (pcase (upcase (match-string 5 term))
  10649. ("CATEGORY"
  10650. '(get-text-property (point) 'org-category))
  10651. ("TODO" 'todo)
  10652. (p `(org-cached-entry-get nil ,p))))
  10653. (pv (match-string 7 term))
  10654. (regexp (eq (string-to-char pv) ?{))
  10655. (strp (eq (string-to-char pv) ?\"))
  10656. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10657. (po (org-op-to-function (match-string 6 term)
  10658. (if timep 'time strp))))
  10659. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10660. (when timep (setq pv (org-matcher-time pv)))
  10661. (cond ((and regexp (eq po '/=))
  10662. `(not (string-match ,pv (or ,gv ""))))
  10663. (regexp `(string-match ,pv (or ,gv "")))
  10664. (strp `(,po (or ,gv "") ,pv))
  10665. (t
  10666. `(,po
  10667. (string-to-number (or ,gv ""))
  10668. ,(string-to-number pv))))))
  10669. (t `(member ,tag tags-list)))))
  10670. (push (if minus `(not ,mm) mm) tagsmatcher)
  10671. (setq term rest)))
  10672. (push `(and ,@tagsmatcher) orlist)
  10673. (setq tagsmatcher nil))
  10674. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10675. ;; Make the TODO matcher.
  10676. (when (org-string-nw-p todomatch)
  10677. (let ((orlist nil))
  10678. (dolist (term (org-split-string todomatch "|"))
  10679. (while (string-match re term)
  10680. (let* ((minus (and (match-end 1)
  10681. (equal (match-string 1 term) "-")))
  10682. (kwd (match-string 2 term))
  10683. (regexp (eq (string-to-char kwd) ?{))
  10684. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10685. `(equal todo ,kwd))))
  10686. (push (if minus `(not ,mm) mm) todomatcher))
  10687. (setq term (substring term (match-end 0))))
  10688. (push (if (> (length todomatcher) 1)
  10689. (cons 'and todomatcher)
  10690. (car todomatcher))
  10691. orlist)
  10692. (setq todomatcher nil))
  10693. (setq todomatcher (cons 'or orlist))))
  10694. ;; Return the string and function of the matcher. If no
  10695. ;; tags-specific or todo-specific matcher exists, match
  10696. ;; everything.
  10697. (let ((matcher (if (and tagsmatcher todomatcher)
  10698. `(and ,tagsmatcher ,todomatcher)
  10699. (or tagsmatcher todomatcher t))))
  10700. (when org--matcher-tags-todo-only
  10701. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10702. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10703. (defun org--tags-expand-group (group tag-groups expanded)
  10704. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10705. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10706. an accumulator used in recursive calls."
  10707. (dolist (tag group)
  10708. (unless (member tag expanded)
  10709. (let ((group (assoc tag tag-groups)))
  10710. (push tag expanded)
  10711. (when group
  10712. (setq expanded
  10713. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10714. expanded)
  10715. (defun org-tags-expand (match &optional single-as-list)
  10716. "Expand group tags in MATCH.
  10717. This replaces every group tag in MATCH with a regexp tag search.
  10718. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10719. will be replaced like this:
  10720. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10721. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10722. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10723. Replacing by a regexp preserves the structure of the match.
  10724. E.g., this expansion
  10725. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10726. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10727. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10728. A group tag in MATCH can contain regular expressions of its own.
  10729. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10730. will be replaced like this:
  10731. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10732. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10733. assumed to be a single group tag, and the function will return
  10734. the list of tags in this group."
  10735. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10736. (let ((tag-groups
  10737. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10738. (cond
  10739. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10740. (org-group-tags
  10741. (let* ((case-fold-search t)
  10742. (tag-syntax org-mode-syntax-table)
  10743. (group-keys (mapcar #'car tag-groups))
  10744. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10745. (return-match match))
  10746. ;; Mark regexp-expressions in the match-expression so that we
  10747. ;; do not replace them later on.
  10748. (let ((s 0))
  10749. (while (string-match "{.+?}" return-match s)
  10750. (setq s (match-end 0))
  10751. (add-text-properties
  10752. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10753. ;; @ and _ are allowed as word-components in tags.
  10754. (modify-syntax-entry ?@ "w" tag-syntax)
  10755. (modify-syntax-entry ?_ "w" tag-syntax)
  10756. ;; For each tag token found in MATCH, compute a regexp and it
  10757. (with-syntax-table tag-syntax
  10758. (replace-regexp-in-string
  10759. key-regexp
  10760. (lambda (m)
  10761. (if (get-text-property (match-beginning 2) 'regexp m)
  10762. m ;regexp tag: ignore
  10763. (let* ((operator (match-string 1 m))
  10764. (tag-token (let ((tag (match-string 2 m)))
  10765. (list tag)))
  10766. regexp-tags regular-tags)
  10767. ;; Partition tags between regexp and regular tags.
  10768. ;; Remove curly bracket syntax from regexp tags.
  10769. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10770. (save-match-data
  10771. (if (string-match "{\\(.+?\\)}" tag)
  10772. (push (match-string 1 tag) regexp-tags)
  10773. (push tag regular-tags))))
  10774. ;; Replace tag token by the appropriate regexp.
  10775. ;; Regular tags need to be regexp-quoted, whereas
  10776. ;; regexp-tags are inserted as-is.
  10777. (let ((regular (regexp-opt regular-tags))
  10778. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10779. (concat operator
  10780. (cond
  10781. ((null regular-tags) (format "{%s}" regexp))
  10782. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10783. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10784. return-match
  10785. t t))))
  10786. (t match))))
  10787. (defun org-op-to-function (op &optional stringp)
  10788. "Turn an operator into the appropriate function."
  10789. (setq op
  10790. (cond
  10791. ((equal op "<" ) '(< org-string< org-time<))
  10792. ((equal op ">" ) '(> org-string> org-time>))
  10793. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10794. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10795. ((member op '("=" "==")) '(= string= org-time=))
  10796. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10797. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10798. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10799. (defvar org-tags-overlay (make-overlay 1 1))
  10800. (delete-overlay org-tags-overlay)
  10801. (defun org-add-prop-inherited (s)
  10802. (add-text-properties 0 (length s) '(inherited t) s)
  10803. s)
  10804. (defun org-toggle-tag (tag &optional onoff)
  10805. "Toggle the tag TAG for the current line.
  10806. If ONOFF is `on' or `off', don't toggle but set to this state."
  10807. (save-excursion
  10808. (org-back-to-heading t)
  10809. (let ((current
  10810. ;; Reverse the tags list so any new tag is appended to the
  10811. ;; current list of tags.
  10812. (nreverse (org-get-tags nil t)))
  10813. res)
  10814. (pcase onoff
  10815. (`off (setq current (delete tag current)))
  10816. ((or `on (guard (not (member tag current))))
  10817. (setq res t)
  10818. (cl-pushnew tag current :test #'equal))
  10819. (_ (setq current (delete tag current))))
  10820. (org-set-tags (nreverse current))
  10821. res)))
  10822. (defun org--align-tags-here (to-col)
  10823. "Align tags on the current headline to TO-COL.
  10824. Assume point is on a headline. Preserve point when aligning
  10825. tags."
  10826. (when (org-match-line org-tag-line-re)
  10827. (let* ((tags-start (match-beginning 1))
  10828. (blank-start (save-excursion
  10829. (goto-char tags-start)
  10830. (skip-chars-backward " \t")
  10831. (point)))
  10832. (new (max (if (>= to-col 0) to-col
  10833. (- (abs to-col) (string-width (match-string 1))))
  10834. ;; Introduce at least one space after the heading
  10835. ;; or the stars.
  10836. (save-excursion
  10837. (goto-char blank-start)
  10838. (1+ (current-column)))))
  10839. (current
  10840. (save-excursion (goto-char tags-start) (current-column)))
  10841. (origin (point-marker))
  10842. (column (current-column))
  10843. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10844. (when (/= new current)
  10845. (delete-region blank-start tags-start)
  10846. (goto-char blank-start)
  10847. (let ((indent-tabs-mode nil)) (indent-to new))
  10848. ;; Try to move back to original position. If point was in the
  10849. ;; blanks before the tags, ORIGIN marker is of no use because
  10850. ;; it now points to BLANK-START. Use COLUMN instead.
  10851. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10852. (defun org-set-tags-command (&optional arg)
  10853. "Set the tags for the current visible entry.
  10854. When called with `\\[universal-argument]' prefix argument ARG, \
  10855. realign all tags
  10856. in the current buffer.
  10857. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10858. unconditionally do not
  10859. offer the fast tag selection interface.
  10860. If a region is active, set tags in the region according to the
  10861. setting of `org-loop-over-headlines-in-active-region'.
  10862. This function is for interactive use only;
  10863. in Lisp code use `org-set-tags' instead."
  10864. (interactive "P")
  10865. (let ((org-use-fast-tag-selection
  10866. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10867. (cond
  10868. ((equal '(4) arg) (org-align-tags t))
  10869. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10870. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10871. (org-map-entries
  10872. #'org-set-tags-command
  10873. nil
  10874. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10875. 'region-start-level
  10876. 'region)
  10877. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10878. (t
  10879. (save-excursion
  10880. (org-back-to-heading)
  10881. (let* ((all-tags (org-get-tags))
  10882. (table (setq org-last-tags-completion-table
  10883. (org--tag-add-to-alist
  10884. (and org-complete-tags-always-offer-all-agenda-tags
  10885. (org-global-tags-completion-table
  10886. (org-agenda-files)))
  10887. (or org-current-tag-alist (org-get-buffer-tags)))))
  10888. (current-tags
  10889. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10890. all-tags))
  10891. (inherited-tags
  10892. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10893. all-tags))
  10894. (tags
  10895. (replace-regexp-in-string
  10896. ;; Ignore all forbidden characters in tags.
  10897. "[^[:alnum:]_@#%]+" ":"
  10898. (if (or (eq t org-use-fast-tag-selection)
  10899. (and org-use-fast-tag-selection
  10900. (delq nil (mapcar #'cdr table))))
  10901. (org-fast-tag-selection
  10902. current-tags
  10903. inherited-tags
  10904. table
  10905. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10906. (let ((org-add-colon-after-tag-completion (< 1 (length table))))
  10907. (org-trim (completing-read
  10908. "Tags: "
  10909. #'org-tags-completion-function
  10910. nil nil (org-make-tag-string current-tags)
  10911. 'org-tags-history)))))))
  10912. (org-set-tags tags)))))
  10913. ;; `save-excursion' may not replace the point at the right
  10914. ;; position.
  10915. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10916. (looking-at-p " "))
  10917. (forward-char))))
  10918. (defun org-align-tags (&optional all)
  10919. "Align tags in current entry.
  10920. When optional argument ALL is non-nil, align all tags in the
  10921. visible part of the buffer."
  10922. (let ((get-indent-column
  10923. (lambda ()
  10924. (let ((offset (if (bound-and-true-p org-indent-mode)
  10925. (* (1- org-indent-indentation-per-level)
  10926. (1- (org-current-level)))
  10927. 0)))
  10928. (+ org-tags-column
  10929. (if (> org-tags-column 0) (- offset) offset))))))
  10930. (if (and (not all) (org-at-heading-p))
  10931. (org--align-tags-here (funcall get-indent-column))
  10932. (save-excursion
  10933. (if all
  10934. (progn
  10935. (goto-char (point-min))
  10936. (while (re-search-forward org-tag-line-re nil t)
  10937. (org--align-tags-here (funcall get-indent-column))))
  10938. (org-back-to-heading t)
  10939. (org--align-tags-here (funcall get-indent-column)))))))
  10940. (defun org-set-tags (tags)
  10941. "Set the tags of the current entry to TAGS, replacing current tags.
  10942. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10943. If TAGS is nil or the empty string, all tags are removed.
  10944. This function assumes point is on a headline."
  10945. (org-with-wide-buffer
  10946. (let ((tags (pcase tags
  10947. ((pred listp) tags)
  10948. ((pred stringp) (split-string (org-trim tags) ":" t))
  10949. (_ (error "Invalid tag specification: %S" tags))))
  10950. (old-tags (org-get-tags nil t))
  10951. (tags-change? nil))
  10952. (when (functionp org-tags-sort-function)
  10953. (setq tags (sort tags org-tags-sort-function)))
  10954. (setq tags-change? (not (equal tags old-tags)))
  10955. (when tags-change?
  10956. ;; Delete previous tags and any trailing white space.
  10957. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10958. (line-end-position)))
  10959. (skip-chars-backward " \t")
  10960. (delete-region (point) (line-end-position))
  10961. ;; Deleting white spaces may break an otherwise empty headline.
  10962. ;; Re-introduce one space in this case.
  10963. (unless (org-at-heading-p) (insert " "))
  10964. (when tags
  10965. (save-excursion (insert " " (org-make-tag-string tags)))
  10966. ;; When text is being inserted on an invisible region
  10967. ;; boundary, it can be inadvertently sucked into
  10968. ;; invisibility.
  10969. (unless (org-invisible-p (line-beginning-position))
  10970. (org-flag-region (point) (line-end-position) nil 'outline))))
  10971. ;; Align tags, if any.
  10972. (when tags (org-align-tags))
  10973. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10974. (defun org-change-tag-in-region (beg end tag off)
  10975. "Add or remove TAG for each entry in the region.
  10976. This works in the agenda, and also in an Org buffer."
  10977. (interactive
  10978. (list (region-beginning) (region-end)
  10979. (let ((org-last-tags-completion-table
  10980. (if (derived-mode-p 'org-mode)
  10981. (org--tag-add-to-alist
  10982. (org-get-buffer-tags)
  10983. (org-global-tags-completion-table))
  10984. (org-global-tags-completion-table))))
  10985. (completing-read
  10986. "Tag: " 'org-tags-completion-function nil nil nil
  10987. 'org-tags-history))
  10988. (progn
  10989. (message "[s]et or [r]emove? ")
  10990. (equal (read-char-exclusive) ?r))))
  10991. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10992. (let ((agendap (equal major-mode 'org-agenda-mode))
  10993. l1 l2 m buf pos newhead (cnt 0))
  10994. (goto-char end)
  10995. (setq l2 (1- (org-current-line)))
  10996. (goto-char beg)
  10997. (setq l1 (org-current-line))
  10998. (cl-loop for l from l1 to l2 do
  10999. (org-goto-line l)
  11000. (setq m (get-text-property (point) 'org-hd-marker))
  11001. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11002. (and agendap m))
  11003. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11004. pos (if agendap m (point)))
  11005. (with-current-buffer buf
  11006. (save-excursion
  11007. (save-restriction
  11008. (goto-char pos)
  11009. (setq cnt (1+ cnt))
  11010. (org-toggle-tag tag (if off 'off 'on))
  11011. (setq newhead (org-get-heading)))))
  11012. (and agendap (org-agenda-change-all-lines newhead m))))
  11013. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11014. (defun org-tags-completion-function (string _predicate &optional flag)
  11015. "Complete tag STRING.
  11016. FLAG specifies the type of completion operation to perform. This
  11017. function is passed as a collection function to `completing-read',
  11018. which see."
  11019. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11020. (confirm (lambda (x) (stringp (car x))))
  11021. (prefix ""))
  11022. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11023. (setq prefix (match-string 1 string))
  11024. (setq string (match-string 2 string)))
  11025. (pcase flag
  11026. (`t (all-completions string org-last-tags-completion-table confirm))
  11027. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11028. (`nil
  11029. (pcase (try-completion string org-last-tags-completion-table confirm)
  11030. ((and completion (pred stringp))
  11031. (concat prefix
  11032. completion
  11033. (if (and org-add-colon-after-tag-completion
  11034. (assoc completion org-last-tags-completion-table))
  11035. ":"
  11036. "")))
  11037. (completion completion)))
  11038. (_ nil))))
  11039. (defun org-fast-tag-insert (kwd tags face &optional end)
  11040. "Insert KWD, and the TAGS, the latter with face FACE.
  11041. Also insert END."
  11042. (insert (format "%-12s" (concat kwd ":"))
  11043. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11044. (or end "")))
  11045. (defun org-fast-tag-show-exit (flag)
  11046. (save-excursion
  11047. (org-goto-line 3)
  11048. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11049. (replace-match ""))
  11050. (when flag
  11051. (end-of-line 1)
  11052. (org-move-to-column (- (window-width) 19) t)
  11053. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11054. (defun org-set-current-tags-overlay (current prefix)
  11055. "Add an overlay to CURRENT tag with PREFIX."
  11056. (let ((s (org-make-tag-string current)))
  11057. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11058. (org-overlay-display org-tags-overlay (concat prefix s))))
  11059. (defvar org-last-tag-selection-key nil)
  11060. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11061. "Fast tag selection with single keys.
  11062. CURRENT is the current list of tags in the headline, INHERITED is the
  11063. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11064. possibly with grouping information. TODO-TABLE is a similar table with
  11065. TODO keywords, should these have keys assigned to them.
  11066. If the keys are nil, a-z are automatically assigned.
  11067. Returns the new tags string, or nil to not change the current settings."
  11068. (let* ((fulltable (append table todo-table))
  11069. (maxlen (if (null fulltable) 0
  11070. (apply #'max
  11071. (mapcar (lambda (x)
  11072. (if (stringp (car x)) (string-width (car x))
  11073. 0))
  11074. fulltable))))
  11075. (buf (current-buffer))
  11076. (expert (eq org-fast-tag-selection-single-key 'expert))
  11077. (tab-tags nil)
  11078. (fwidth (+ maxlen 3 1 3))
  11079. (ncol (/ (- (window-width) 4) fwidth))
  11080. (i-face 'org-done)
  11081. (c-face 'org-todo)
  11082. tg cnt e c char c1 c2 ntable tbl rtn
  11083. ov-start ov-end ov-prefix
  11084. (exit-after-next org-fast-tag-selection-single-key)
  11085. (done-keywords org-done-keywords)
  11086. groups ingroup intaggroup)
  11087. (save-excursion
  11088. (beginning-of-line)
  11089. (if (looking-at org-tag-line-re)
  11090. (setq ov-start (match-beginning 1)
  11091. ov-end (match-end 1)
  11092. ov-prefix "")
  11093. (setq ov-start (1- (point-at-eol))
  11094. ov-end (1+ ov-start))
  11095. (skip-chars-forward "^\n\r")
  11096. (setq ov-prefix
  11097. (concat
  11098. (buffer-substring (1- (point)) (point))
  11099. (if (> (current-column) org-tags-column)
  11100. " "
  11101. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11102. (move-overlay org-tags-overlay ov-start ov-end)
  11103. (save-excursion
  11104. (save-window-excursion
  11105. (if expert
  11106. (set-buffer (get-buffer-create " *Org tags*"))
  11107. (delete-other-windows)
  11108. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11109. (org-switch-to-buffer-other-window " *Org tags*"))
  11110. (erase-buffer)
  11111. (setq-local org-done-keywords done-keywords)
  11112. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11113. (org-fast-tag-insert "Current" current c-face "\n\n")
  11114. (org-fast-tag-show-exit exit-after-next)
  11115. (org-set-current-tags-overlay current ov-prefix)
  11116. (setq tbl fulltable char ?a cnt 0)
  11117. (while (setq e (pop tbl))
  11118. (cond
  11119. ((eq (car e) :startgroup)
  11120. (push '() groups) (setq ingroup t)
  11121. (unless (zerop cnt)
  11122. (setq cnt 0)
  11123. (insert "\n"))
  11124. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11125. ((eq (car e) :endgroup)
  11126. (setq ingroup nil cnt 0)
  11127. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11128. ((eq (car e) :startgrouptag)
  11129. (setq intaggroup t)
  11130. (unless (zerop cnt)
  11131. (setq cnt 0)
  11132. (insert "\n"))
  11133. (insert "[ "))
  11134. ((eq (car e) :endgrouptag)
  11135. (setq intaggroup nil cnt 0)
  11136. (insert "]\n"))
  11137. ((equal e '(:newline))
  11138. (unless (zerop cnt)
  11139. (setq cnt 0)
  11140. (insert "\n")
  11141. (setq e (car tbl))
  11142. (while (equal (car tbl) '(:newline))
  11143. (insert "\n")
  11144. (setq tbl (cdr tbl)))))
  11145. ((equal e '(:grouptags)) (insert " : "))
  11146. (t
  11147. (setq tg (copy-sequence (car e)) c2 nil)
  11148. (if (cdr e)
  11149. (setq c (cdr e))
  11150. ;; automatically assign a character.
  11151. (setq c1 (string-to-char
  11152. (downcase (substring
  11153. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11154. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11155. (while (or (rassoc char ntable) (rassoc char table))
  11156. (setq char (1+ char)))
  11157. (setq c2 c1))
  11158. (setq c (or c2 char)))
  11159. (when ingroup (push tg (car groups)))
  11160. (setq tg (org-add-props tg nil 'face
  11161. (cond
  11162. ((not (assoc tg table))
  11163. (org-get-todo-face tg))
  11164. ((member tg current) c-face)
  11165. ((member tg inherited) i-face))))
  11166. (when (equal (caar tbl) :grouptags)
  11167. (org-add-props tg nil 'face 'org-tag-group))
  11168. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11169. (insert "[" c "] " tg (make-string
  11170. (- fwidth 4 (length tg)) ?\ ))
  11171. (push (cons tg c) ntable)
  11172. (when (= (cl-incf cnt) ncol)
  11173. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11174. (insert "\n")
  11175. (when (or ingroup intaggroup) (insert " ")))
  11176. (setq cnt 0)))))
  11177. (setq ntable (nreverse ntable))
  11178. (insert "\n")
  11179. (goto-char (point-min))
  11180. (unless expert (org-fit-window-to-buffer))
  11181. (setq rtn
  11182. (catch 'exit
  11183. (while t
  11184. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11185. (if (not groups) "no " "")
  11186. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11187. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11188. (setq org-last-tag-selection-key c)
  11189. (cond
  11190. ((= c ?\r) (throw 'exit t))
  11191. ((= c ?!)
  11192. (setq groups (not groups))
  11193. (goto-char (point-min))
  11194. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11195. ((= c ?\C-c)
  11196. (if (not expert)
  11197. (org-fast-tag-show-exit
  11198. (setq exit-after-next (not exit-after-next)))
  11199. (setq expert nil)
  11200. (delete-other-windows)
  11201. (set-window-buffer (split-window-vertically) " *Org tags*")
  11202. (org-switch-to-buffer-other-window " *Org tags*")
  11203. (org-fit-window-to-buffer)))
  11204. ((or (= c ?\C-g)
  11205. (and (= c ?q) (not (rassoc c ntable))))
  11206. (delete-overlay org-tags-overlay)
  11207. (setq quit-flag t))
  11208. ((= c ?\ )
  11209. (setq current nil)
  11210. (when exit-after-next (setq exit-after-next 'now)))
  11211. ((= c ?\t)
  11212. (condition-case nil
  11213. (unless tab-tags
  11214. (setq tab-tags
  11215. (delq nil
  11216. (mapcar (lambda (x)
  11217. (let ((item (car-safe x)))
  11218. (and (stringp item)
  11219. (list item))))
  11220. (org--tag-add-to-alist
  11221. (with-current-buffer buf
  11222. (org-get-buffer-tags))
  11223. table))))))
  11224. (setq tg (completing-read "Tag: " tab-tags))
  11225. (when (string-match "\\S-" tg)
  11226. (cl-pushnew (list tg) tab-tags :test #'equal)
  11227. (if (member tg current)
  11228. (setq current (delete tg current))
  11229. (push tg current)))
  11230. (when exit-after-next (setq exit-after-next 'now)))
  11231. ((setq e (rassoc c todo-table) tg (car e))
  11232. (with-current-buffer buf
  11233. (save-excursion (org-todo tg)))
  11234. (when exit-after-next (setq exit-after-next 'now)))
  11235. ((setq e (rassoc c ntable) tg (car e))
  11236. (if (member tg current)
  11237. (setq current (delete tg current))
  11238. (cl-loop for g in groups do
  11239. (when (member tg g)
  11240. (dolist (x g) (setq current (delete x current)))))
  11241. (push tg current))
  11242. (when exit-after-next (setq exit-after-next 'now))))
  11243. ;; Create a sorted list
  11244. (setq current
  11245. (sort current
  11246. (lambda (a b)
  11247. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11248. (when (eq exit-after-next 'now) (throw 'exit t))
  11249. (goto-char (point-min))
  11250. (beginning-of-line 2)
  11251. (delete-region (point) (point-at-eol))
  11252. (org-fast-tag-insert "Current" current c-face)
  11253. (org-set-current-tags-overlay current ov-prefix)
  11254. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11255. (while (re-search-forward tag-re nil t)
  11256. (let ((tag (match-string 1)))
  11257. (add-text-properties
  11258. (match-beginning 1) (match-end 1)
  11259. (list 'face
  11260. (cond
  11261. ((member tag current) c-face)
  11262. ((member tag inherited) i-face)
  11263. (t (get-text-property (match-beginning 1) '
  11264. face))))))))
  11265. (goto-char (point-min)))))
  11266. (delete-overlay org-tags-overlay)
  11267. (if rtn
  11268. (mapconcat 'identity current ":")
  11269. nil)))))
  11270. (defun org-make-tag-string (tags)
  11271. "Return string associated to TAGS.
  11272. TAGS is a list of strings."
  11273. (if (null tags) ""
  11274. (format ":%s:" (mapconcat #'identity tags ":"))))
  11275. (defun org--get-local-tags ()
  11276. "Return list of tags for the current headline.
  11277. Assume point is at the beginning of the headline."
  11278. (and (looking-at org-tag-line-re)
  11279. (split-string (match-string-no-properties 2) ":" t)))
  11280. (defun org-get-tags (&optional pos local)
  11281. "Get the list of tags specified in the current headline.
  11282. When argument POS is non-nil, retrieve tags for headline at POS.
  11283. According to `org-use-tag-inheritance', tags may be inherited
  11284. from parent headlines, and from the whole document, through
  11285. `org-file-tags'. In this case, the returned list of tags
  11286. contains tags in this order: file tags, tags inherited from
  11287. parent headlines, local tags. If a tag appears multiple times,
  11288. only the most local tag is returned.
  11289. However, when optional argument LOCAL is non-nil, only return
  11290. tags specified at the headline.
  11291. Inherited tags have the `inherited' text property."
  11292. (if (and org-trust-scanner-tags
  11293. (or (not pos) (eq pos (point)))
  11294. (not local))
  11295. org-scanner-tags
  11296. (org-with-point-at (or pos (point))
  11297. (unless (org-before-first-heading-p)
  11298. (org-back-to-heading t)
  11299. (let ((ltags (org--get-local-tags)) itags)
  11300. (if (or local (not org-use-tag-inheritance)) ltags
  11301. (while (org-up-heading-safe)
  11302. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11303. (org--get-local-tags))
  11304. itags)))
  11305. (setq itags (append org-file-tags itags))
  11306. (nreverse
  11307. (delete-dups
  11308. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11309. (defun org-get-buffer-tags ()
  11310. "Get a table of all tags used in the buffer, for completion."
  11311. (org-with-point-at 1
  11312. (let (tags)
  11313. (while (re-search-forward org-tag-line-re nil t)
  11314. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11315. tags)))
  11316. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11317. ;;;; The mapping API
  11318. (defvar org-agenda-skip-comment-trees)
  11319. (defvar org-agenda-skip-function)
  11320. (defun org-map-entries (func &optional match scope &rest skip)
  11321. "Call FUNC at each headline selected by MATCH in SCOPE.
  11322. FUNC is a function or a lisp form. The function will be called without
  11323. arguments, with the cursor positioned at the beginning of the headline.
  11324. The return values of all calls to the function will be collected and
  11325. returned as a list.
  11326. The call to FUNC will be wrapped into a save-excursion form, so FUNC
  11327. does not need to preserve point. After evaluation, the cursor will be
  11328. moved to the end of the line (presumably of the headline of the
  11329. processed entry) and search continues from there. Under some
  11330. circumstances, this may not produce the wanted results. For example,
  11331. if you have removed (e.g. archived) the current (sub)tree it could
  11332. mean that the next entry will be skipped entirely. In such cases, you
  11333. can specify the position from where search should continue by making
  11334. FUNC set the variable `org-map-continue-from' to the desired buffer
  11335. position.
  11336. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11337. Only headlines that are matched by this query will be considered during
  11338. the iteration. When MATCH is nil or t, all headlines will be
  11339. visited by the iteration.
  11340. SCOPE determines the scope of this command. It can be any of:
  11341. nil The current buffer, respecting the restriction if any
  11342. tree The subtree started with the entry at point
  11343. region The entries within the active region, if any
  11344. region-start-level
  11345. The entries within the active region, but only those at
  11346. the same level than the first one.
  11347. file The current buffer, without restriction
  11348. file-with-archives
  11349. The current buffer, and any archives associated with it
  11350. agenda All agenda files
  11351. agenda-with-archives
  11352. All agenda files with any archive files associated with them
  11353. \(file1 file2 ...)
  11354. If this is a list, all files in the list will be scanned
  11355. The remaining args are treated as settings for the skipping facilities of
  11356. the scanner. The following items can be given here:
  11357. archive skip trees with the archive tag
  11358. comment skip trees with the COMMENT keyword
  11359. function or Emacs Lisp form:
  11360. will be used as value for `org-agenda-skip-function', so
  11361. whenever the function returns a position, FUNC will not be
  11362. called for that entry and search will continue from the
  11363. position returned
  11364. If your function needs to retrieve the tags including inherited tags
  11365. at the *current* entry, you can use the value of the variable
  11366. `org-scanner-tags' which will be much faster than getting the value
  11367. with `org-get-tags'. If your function gets properties with
  11368. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11369. to t around the call to `org-entry-properties' to get the same speedup.
  11370. Note that if your function moves around to retrieve tags and properties at
  11371. a *different* entry, you cannot use these techniques."
  11372. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11373. (not (org-region-active-p)))
  11374. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11375. (org-agenda-skip-archived-trees (memq 'archive skip))
  11376. (org-agenda-skip-comment-trees (memq 'comment skip))
  11377. (org-agenda-skip-function
  11378. (car (org-delete-all '(comment archive) skip)))
  11379. (org-tags-match-list-sublevels t)
  11380. (start-level (eq scope 'region-start-level))
  11381. matcher res
  11382. org-todo-keywords-for-agenda
  11383. org-done-keywords-for-agenda
  11384. org-todo-keyword-alist-for-agenda
  11385. org-tag-alist-for-agenda
  11386. org--matcher-tags-todo-only)
  11387. (cond
  11388. ((eq match t) (setq matcher t))
  11389. ((eq match nil) (setq matcher t))
  11390. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11391. (save-excursion
  11392. (save-restriction
  11393. (cond ((eq scope 'tree)
  11394. (org-back-to-heading t)
  11395. (org-narrow-to-subtree)
  11396. (setq scope nil))
  11397. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11398. (org-region-active-p))
  11399. ;; If needed, set start-level to a string like "2"
  11400. (when start-level
  11401. (save-excursion
  11402. (goto-char (region-beginning))
  11403. (unless (org-at-heading-p) (outline-next-heading))
  11404. (setq start-level (org-current-level))))
  11405. (narrow-to-region (region-beginning)
  11406. (save-excursion
  11407. (goto-char (region-end))
  11408. (unless (and (bolp) (org-at-heading-p))
  11409. (outline-next-heading))
  11410. (point)))
  11411. (setq scope nil)))
  11412. (if (not scope)
  11413. (progn
  11414. (org-agenda-prepare-buffers
  11415. (and buffer-file-name (list buffer-file-name)))
  11416. (setq res
  11417. (org-scan-tags
  11418. func matcher org--matcher-tags-todo-only start-level)))
  11419. ;; Get the right scope
  11420. (cond
  11421. ((and scope (listp scope) (symbolp (car scope)))
  11422. (setq scope (eval scope)))
  11423. ((eq scope 'agenda)
  11424. (setq scope (org-agenda-files t)))
  11425. ((eq scope 'agenda-with-archives)
  11426. (setq scope (org-agenda-files t))
  11427. (setq scope (org-add-archive-files scope)))
  11428. ((eq scope 'file)
  11429. (setq scope (and buffer-file-name (list buffer-file-name))))
  11430. ((eq scope 'file-with-archives)
  11431. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11432. (org-agenda-prepare-buffers scope)
  11433. (dolist (file scope)
  11434. (with-current-buffer (org-find-base-buffer-visiting file)
  11435. (org-with-wide-buffer
  11436. (goto-char (point-min))
  11437. (setq res
  11438. (append
  11439. res
  11440. (org-scan-tags
  11441. func matcher org--matcher-tags-todo-only)))))))))
  11442. res)))
  11443. ;;; Properties API
  11444. (defconst org-special-properties
  11445. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11446. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11447. "The special properties valid in Org mode.
  11448. These are properties that are not defined in the property drawer,
  11449. but in some other way.")
  11450. (defconst org-default-properties
  11451. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11452. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11453. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11454. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11455. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11456. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11457. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11458. "Some properties that are used by Org mode for various purposes.
  11459. Being in this list makes sure that they are offered for completion.")
  11460. (defun org--valid-property-p (property)
  11461. "Non-nil when string PROPERTY is a valid property name."
  11462. (not
  11463. (or (equal property "")
  11464. (string-match-p "\\s-" property))))
  11465. (defun org--update-property-plist (key val props)
  11466. "Associate KEY to VAL in alist PROPS.
  11467. Modifications are made by side-effect. Return new alist."
  11468. (let* ((appending (string= (substring key -1) "+"))
  11469. (key (if appending (substring key 0 -1) key))
  11470. (old (assoc-string key props t)))
  11471. (if (not old) (cons (cons key val) props)
  11472. (setcdr old (if appending (concat (cdr old) " " val) val))
  11473. props)))
  11474. (defun org-get-property-block (&optional beg force)
  11475. "Return the (beg . end) range of the body of the property drawer.
  11476. BEG is the beginning of the current subtree or the beginning of
  11477. the document if before the first headline. If it is not given,
  11478. it will be found. If the drawer does not exist, create it if
  11479. FORCE is non-nil, or return nil."
  11480. (org-with-wide-buffer
  11481. (let ((beg (cond (beg (goto-char beg))
  11482. ((or (not (featurep 'org-inlinetask))
  11483. (org-inlinetask-in-task-p))
  11484. (org-back-to-heading-or-point-min t) (point))
  11485. (t (org-with-limited-levels
  11486. (org-back-to-heading-or-point-min t))
  11487. (point)))))
  11488. ;; Move point to its position according to its positional rules.
  11489. (cond ((org-before-first-heading-p)
  11490. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11491. (t (forward-line)
  11492. (when (looking-at-p org-planning-line-re) (forward-line))))
  11493. (cond ((looking-at org-property-drawer-re)
  11494. (forward-line)
  11495. (cons (point) (progn (goto-char (match-end 0))
  11496. (line-beginning-position))))
  11497. (force
  11498. (goto-char beg)
  11499. (org-insert-property-drawer)
  11500. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11501. (line-beginning-position))))
  11502. (cons pos pos)))))))
  11503. (defun org-at-property-drawer-p ()
  11504. "Non-nil when point is at the first line of a property drawer."
  11505. (org-with-wide-buffer
  11506. (beginning-of-line)
  11507. (and (looking-at org-property-drawer-re)
  11508. (or (bobp)
  11509. (progn
  11510. (forward-line -1)
  11511. (cond ((org-at-heading-p))
  11512. ((looking-at org-planning-line-re)
  11513. (forward-line -1)
  11514. (org-at-heading-p))
  11515. ((looking-at org-comment-regexp)
  11516. (forward-line -1)
  11517. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11518. (forward-line -1))
  11519. (looking-at org-comment-regexp))
  11520. (t nil)))))))
  11521. (defun org-at-property-p ()
  11522. "Non-nil when point is inside a property drawer.
  11523. See `org-property-re' for match data, if applicable."
  11524. (save-excursion
  11525. (beginning-of-line)
  11526. (and (looking-at org-property-re)
  11527. (let ((property-drawer (save-match-data (org-get-property-block))))
  11528. (and property-drawer
  11529. (>= (point) (car property-drawer))
  11530. (< (point) (cdr property-drawer)))))))
  11531. (defun org-property-action ()
  11532. "Do an action on properties."
  11533. (interactive)
  11534. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11535. (let ((c (read-char-exclusive)))
  11536. (cl-case c
  11537. (?s (call-interactively #'org-set-property))
  11538. (?d (call-interactively #'org-delete-property))
  11539. (?D (call-interactively #'org-delete-property-globally))
  11540. (?c (call-interactively #'org-compute-property-at-point))
  11541. (otherwise (user-error "No such property action %c" c)))))
  11542. (defun org-inc-effort ()
  11543. "Increment the value of the effort property in the current entry."
  11544. (interactive)
  11545. (org-set-effort t))
  11546. (defvar org-clock-effort) ; Defined in org-clock.el.
  11547. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11548. (defun org-set-effort (&optional increment value)
  11549. "Set the effort property of the current entry.
  11550. If INCREMENT is non-nil, set the property to the next allowed
  11551. value. Otherwise, if optional argument VALUE is provided, use
  11552. it. Eventually, prompt for the new value if none of the previous
  11553. variables is set."
  11554. (interactive "P")
  11555. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11556. (current (org-entry-get nil org-effort-property))
  11557. (value
  11558. (cond
  11559. (increment
  11560. (unless allowed (user-error "Allowed effort values are not set"))
  11561. (or (cl-caadr (member (list current) allowed))
  11562. (user-error "Unknown value %S among allowed values" current)))
  11563. (value
  11564. (if (stringp value) value
  11565. (error "Invalid effort value: %S" value)))
  11566. (t
  11567. (let ((must-match
  11568. (and allowed
  11569. (not (get-text-property 0 'org-unrestricted
  11570. (caar allowed))))))
  11571. (completing-read "Effort: " allowed nil must-match))))))
  11572. ;; Test whether the value can be interpreted as a duration before
  11573. ;; inserting it in the buffer:
  11574. (org-duration-to-minutes value)
  11575. ;; Maybe update the effort value:
  11576. (unless (equal current value)
  11577. (org-entry-put nil org-effort-property value))
  11578. (org-refresh-property '((effort . identity)
  11579. (effort-minutes . org-duration-to-minutes))
  11580. value)
  11581. (when (equal (org-get-heading t t t t)
  11582. (bound-and-true-p org-clock-current-task))
  11583. (setq org-clock-effort value)
  11584. (org-clock-update-mode-line))
  11585. (message "%s is now %s" org-effort-property value)))
  11586. (defun org-entry-properties (&optional pom which)
  11587. "Get all properties of the current entry.
  11588. When POM is a buffer position, get all properties from the entry
  11589. there instead.
  11590. This includes the TODO keyword, the tags, time strings for
  11591. deadline, scheduled, and clocking, and any additional properties
  11592. defined in the entry.
  11593. If WHICH is nil or `all', get all properties. If WHICH is
  11594. `special' or `standard', only get that subclass. If WHICH is
  11595. a string, only get that property.
  11596. Return value is an alist. Keys are properties, as upcased
  11597. strings."
  11598. (org-with-point-at pom
  11599. (when (and (derived-mode-p 'org-mode)
  11600. (org-back-to-heading-or-point-min t))
  11601. (catch 'exit
  11602. (let* ((beg (point))
  11603. (specific (and (stringp which) (upcase which)))
  11604. (which (cond ((not specific) which)
  11605. ((member specific org-special-properties) 'special)
  11606. (t 'standard)))
  11607. props)
  11608. ;; Get the special properties, like TODO and TAGS.
  11609. (when (memq which '(nil all special))
  11610. (when (or (not specific) (string= specific "CLOCKSUM"))
  11611. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11612. (when clocksum
  11613. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11614. props)))
  11615. (when specific (throw 'exit props)))
  11616. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11617. (let ((clocksumt (get-text-property (point)
  11618. :org-clock-minutes-today)))
  11619. (when clocksumt
  11620. (push (cons "CLOCKSUM_T"
  11621. (org-duration-from-minutes clocksumt))
  11622. props)))
  11623. (when specific (throw 'exit props)))
  11624. (when (or (not specific) (string= specific "ITEM"))
  11625. (let ((case-fold-search nil))
  11626. (when (looking-at org-complex-heading-regexp)
  11627. (push (cons "ITEM"
  11628. (let ((title (match-string-no-properties 4)))
  11629. (if (org-string-nw-p title)
  11630. (org-remove-tabs title)
  11631. "")))
  11632. props)))
  11633. (when specific (throw 'exit props)))
  11634. (when (or (not specific) (string= specific "TODO"))
  11635. (let ((case-fold-search nil))
  11636. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11637. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11638. (when specific (throw 'exit props)))
  11639. (when (or (not specific) (string= specific "PRIORITY"))
  11640. (push (cons "PRIORITY"
  11641. (if (looking-at org-priority-regexp)
  11642. (match-string-no-properties 2)
  11643. (char-to-string org-priority-default)))
  11644. props)
  11645. (when specific (throw 'exit props)))
  11646. (when (or (not specific) (string= specific "FILE"))
  11647. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11648. props)
  11649. (when specific (throw 'exit props)))
  11650. (when (or (not specific) (string= specific "TAGS"))
  11651. (let ((tags (org-get-tags nil t)))
  11652. (when tags
  11653. (push (cons "TAGS" (org-make-tag-string tags))
  11654. props)))
  11655. (when specific (throw 'exit props)))
  11656. (when (or (not specific) (string= specific "ALLTAGS"))
  11657. (let ((tags (org-get-tags)))
  11658. (when tags
  11659. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11660. props)))
  11661. (when specific (throw 'exit props)))
  11662. (when (or (not specific) (string= specific "BLOCKED"))
  11663. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11664. (when specific (throw 'exit props)))
  11665. (when (or (not specific)
  11666. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11667. (forward-line)
  11668. (when (looking-at-p org-planning-line-re)
  11669. (end-of-line)
  11670. (let ((bol (line-beginning-position))
  11671. ;; Backward compatibility: time keywords used to
  11672. ;; be configurable (before 8.3). Make sure we
  11673. ;; get the correct keyword.
  11674. (key-assoc `(("CLOSED" . ,org-closed-string)
  11675. ("DEADLINE" . ,org-deadline-string)
  11676. ("SCHEDULED" . ,org-scheduled-string))))
  11677. (dolist (pair (if specific (list (assoc specific key-assoc))
  11678. key-assoc))
  11679. (save-excursion
  11680. (when (search-backward (cdr pair) bol t)
  11681. (goto-char (match-end 0))
  11682. (skip-chars-forward " \t")
  11683. (and (looking-at org-ts-regexp-both)
  11684. (push (cons (car pair)
  11685. (match-string-no-properties 0))
  11686. props)))))))
  11687. (when specific (throw 'exit props)))
  11688. (when (or (not specific)
  11689. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11690. (let ((find-ts
  11691. (lambda (end ts)
  11692. ;; Fix next time-stamp before END. TS is the
  11693. ;; list of time-stamps found so far.
  11694. (let ((ts ts)
  11695. (regexp (cond
  11696. ((string= specific "TIMESTAMP")
  11697. org-ts-regexp)
  11698. ((string= specific "TIMESTAMP_IA")
  11699. org-ts-regexp-inactive)
  11700. ((assoc "TIMESTAMP_IA" ts)
  11701. org-ts-regexp)
  11702. ((assoc "TIMESTAMP" ts)
  11703. org-ts-regexp-inactive)
  11704. (t org-ts-regexp-both))))
  11705. (catch 'next
  11706. (while (re-search-forward regexp end t)
  11707. (backward-char)
  11708. (let ((object (org-element-context)))
  11709. ;; Accept to match timestamps in node
  11710. ;; properties, too.
  11711. (when (memq (org-element-type object)
  11712. '(node-property timestamp))
  11713. (let ((type
  11714. (org-element-property :type object)))
  11715. (cond
  11716. ((and (memq type '(active active-range))
  11717. (not (equal specific "TIMESTAMP_IA")))
  11718. (unless (assoc "TIMESTAMP" ts)
  11719. (push (cons "TIMESTAMP"
  11720. (org-element-property
  11721. :raw-value object))
  11722. ts)
  11723. (when specific (throw 'exit ts))))
  11724. ((and (memq type '(inactive inactive-range))
  11725. (not (string= specific "TIMESTAMP")))
  11726. (unless (assoc "TIMESTAMP_IA" ts)
  11727. (push (cons "TIMESTAMP_IA"
  11728. (org-element-property
  11729. :raw-value object))
  11730. ts)
  11731. (when specific (throw 'exit ts))))))
  11732. ;; Both timestamp types are found,
  11733. ;; move to next part.
  11734. (when (= (length ts) 2) (throw 'next ts)))))
  11735. ts)))))
  11736. (goto-char beg)
  11737. ;; First look for timestamps within headline.
  11738. (let ((ts (funcall find-ts (line-end-position) nil)))
  11739. (if (= (length ts) 2) (setq props (nconc ts props))
  11740. ;; Then find timestamps in the section, skipping
  11741. ;; planning line.
  11742. (let ((end (save-excursion (outline-next-heading))))
  11743. (forward-line)
  11744. (when (looking-at-p org-planning-line-re) (forward-line))
  11745. (setq props (nconc (funcall find-ts end ts) props))))))))
  11746. ;; Get the standard properties, like :PROP:.
  11747. (when (memq which '(nil all standard))
  11748. ;; If we are looking after a specific property, delegate
  11749. ;; to `org-entry-get', which is faster. However, make an
  11750. ;; exception for "CATEGORY", since it can be also set
  11751. ;; through keywords (i.e. #+CATEGORY).
  11752. (if (and specific (not (equal specific "CATEGORY")))
  11753. (let ((value (org-entry-get beg specific nil t)))
  11754. (throw 'exit (and value (list (cons specific value)))))
  11755. (let ((range (org-get-property-block beg)))
  11756. (when range
  11757. (let ((end (cdr range)) seen-base)
  11758. (goto-char (car range))
  11759. ;; Unlike to `org--update-property-plist', we
  11760. ;; handle the case where base values is found
  11761. ;; after its extension. We also forbid standard
  11762. ;; properties to be named as special properties.
  11763. (while (re-search-forward org-property-re end t)
  11764. (let* ((key (upcase (match-string-no-properties 2)))
  11765. (extendp (string-match-p "\\+\\'" key))
  11766. (key-base (if extendp (substring key 0 -1) key))
  11767. (value (match-string-no-properties 3)))
  11768. (cond
  11769. ((member-ignore-case key-base org-special-properties))
  11770. (extendp
  11771. (setq props
  11772. (org--update-property-plist key value props)))
  11773. ((member key seen-base))
  11774. (t (push key seen-base)
  11775. (let ((p (assoc-string key props t)))
  11776. (if p (setcdr p (concat value " " (cdr p)))
  11777. (push (cons key value) props))))))))))))
  11778. (unless (assoc "CATEGORY" props)
  11779. (push (cons "CATEGORY" (org-get-category beg)) props)
  11780. (when (string= specific "CATEGORY") (throw 'exit props)))
  11781. ;; Return value.
  11782. props)))))
  11783. (defun org--property-local-values (property literal-nil)
  11784. "Return value for PROPERTY in current entry.
  11785. Value is a list whose car is the base value for PROPERTY and cdr
  11786. a list of accumulated values. Return nil if neither is found in
  11787. the entry. Also return nil when PROPERTY is set to \"nil\",
  11788. unless LITERAL-NIL is non-nil."
  11789. (let ((range (org-get-property-block)))
  11790. (when range
  11791. (goto-char (car range))
  11792. (let* ((case-fold-search t)
  11793. (end (cdr range))
  11794. (value
  11795. ;; Base value.
  11796. (save-excursion
  11797. (let ((v (and (re-search-forward
  11798. (org-re-property property nil t) end t)
  11799. (match-string-no-properties 3))))
  11800. (list (if literal-nil v (org-not-nil v)))))))
  11801. ;; Find additional values.
  11802. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11803. (while (re-search-forward property+ end t)
  11804. (push (match-string-no-properties 3) value)))
  11805. ;; Return final values.
  11806. (and (not (equal value '(nil))) (nreverse value))))))
  11807. (defun org--property-global-or-keyword-value (property literal-nil)
  11808. "Return value for PROPERTY as defined by global properties or by keyword.
  11809. Return value is a string. Return nil if property is not set
  11810. globally or by keyword. Also return nil when PROPERTY is set to
  11811. \"nil\", unless LITERAL-NIL is non-nil."
  11812. (let ((global
  11813. (cdr (or (assoc-string property org-keyword-properties t)
  11814. (assoc-string property org-global-properties t)
  11815. (assoc-string property org-global-properties-fixed t)))))
  11816. (if literal-nil global (org-not-nil global))))
  11817. (defun org-entry-get (pom property &optional inherit literal-nil)
  11818. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11819. If INHERIT is non-nil and the entry does not have the property,
  11820. then also check higher levels of the hierarchy. If INHERIT is
  11821. the symbol `selective', use inheritance only if the setting in
  11822. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11823. If the property is present but empty, the return value is the
  11824. empty string. If the property is not present at all, nil is
  11825. returned. In any other case, return the value as a string.
  11826. Search is case-insensitive.
  11827. If LITERAL-NIL is set, return the string value \"nil\" as
  11828. a string, do not interpret it as the list atom nil. This is used
  11829. for inheritance when a \"nil\" value can supersede a non-nil
  11830. value higher up the hierarchy."
  11831. (org-with-point-at pom
  11832. (cond
  11833. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11834. ;; We need a special property. Use `org-entry-properties' to
  11835. ;; retrieve it, but specify the wanted property.
  11836. (cdr (assoc-string property (org-entry-properties nil property))))
  11837. ((and inherit
  11838. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11839. (org-entry-get-with-inheritance property literal-nil))
  11840. (t
  11841. (let* ((local (org--property-local-values property literal-nil))
  11842. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11843. (if literal-nil value (org-not-nil value)))))))
  11844. (defun org-property-or-variable-value (var &optional inherit)
  11845. "Check if there is a property fixing the value of VAR.
  11846. If yes, return this value. If not, return the current value of the variable."
  11847. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11848. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11849. (read prop)
  11850. (symbol-value var))))
  11851. (defun org-entry-delete (pom property)
  11852. "Delete PROPERTY from entry at point-or-marker POM.
  11853. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11854. non-nil when a property was removed."
  11855. (org-with-point-at pom
  11856. (pcase (org-get-property-block)
  11857. (`(,begin . ,origin)
  11858. (let* ((end (copy-marker origin))
  11859. (re (org-re-property
  11860. (concat (regexp-quote property) "\\+?") t t)))
  11861. (goto-char begin)
  11862. (while (re-search-forward re end t)
  11863. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11864. ;; If drawer is empty, remove it altogether.
  11865. (when (= begin end)
  11866. (delete-region (line-beginning-position 0)
  11867. (line-beginning-position 2)))
  11868. ;; Return non-nil if some property was removed.
  11869. (prog1 (/= end origin) (set-marker end nil))))
  11870. (_ nil))))
  11871. ;; Multi-values properties are properties that contain multiple values
  11872. ;; These values are assumed to be single words, separated by whitespace.
  11873. (defun org-entry-add-to-multivalued-property (pom property value)
  11874. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11875. (let* ((old (org-entry-get pom property))
  11876. (values (and old (split-string old))))
  11877. (setq value (org-entry-protect-space value))
  11878. (unless (member value values)
  11879. (setq values (append values (list value)))
  11880. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11881. (defun org-entry-remove-from-multivalued-property (pom property value)
  11882. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11883. (let* ((old (org-entry-get pom property))
  11884. (values (and old (split-string old))))
  11885. (setq value (org-entry-protect-space value))
  11886. (when (member value values)
  11887. (setq values (delete value values))
  11888. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11889. (defun org-entry-member-in-multivalued-property (pom property value)
  11890. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11891. (let* ((old (org-entry-get pom property))
  11892. (values (and old (split-string old))))
  11893. (setq value (org-entry-protect-space value))
  11894. (member value values)))
  11895. (defun org-entry-get-multivalued-property (pom property)
  11896. "Return a list of values in a multivalued property."
  11897. (let* ((value (org-entry-get pom property))
  11898. (values (and value (split-string value))))
  11899. (mapcar #'org-entry-restore-space values)))
  11900. (defun org-entry-put-multivalued-property (pom property &rest values)
  11901. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11902. VALUES should be a list of strings. Spaces will be protected."
  11903. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11904. (let* ((value (org-entry-get pom property))
  11905. (values (and value (split-string value))))
  11906. (mapcar #'org-entry-restore-space values)))
  11907. (defun org-entry-protect-space (s)
  11908. "Protect spaces and newline in string S."
  11909. (while (string-match " " s)
  11910. (setq s (replace-match "%20" t t s)))
  11911. (while (string-match "\n" s)
  11912. (setq s (replace-match "%0A" t t s)))
  11913. s)
  11914. (defun org-entry-restore-space (s)
  11915. "Restore spaces and newline in string S."
  11916. (while (string-match "%20" s)
  11917. (setq s (replace-match " " t t s)))
  11918. (while (string-match "%0A" s)
  11919. (setq s (replace-match "\n" t t s)))
  11920. s)
  11921. (defvar org-entry-property-inherited-from (make-marker)
  11922. "Marker pointing to the entry from where a property was inherited.
  11923. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11924. location of the entry where the inheritance search matched. If there was
  11925. no match, the marker will point nowhere.
  11926. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11927. is set.")
  11928. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11929. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11930. The search will stop at the first ancestor which has the property defined.
  11931. If the value found is \"nil\", return nil to show that the property
  11932. should be considered as undefined (this is the meaning of nil here).
  11933. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11934. (move-marker org-entry-property-inherited-from nil)
  11935. (org-with-wide-buffer
  11936. (let (value)
  11937. (catch 'exit
  11938. (while t
  11939. (let ((v (org--property-local-values property literal-nil)))
  11940. (when v
  11941. (setq value
  11942. (concat (mapconcat #'identity (delq nil v) " ")
  11943. (and value " ")
  11944. value)))
  11945. (cond
  11946. ((car v)
  11947. (org-back-to-heading-or-point-min t)
  11948. (move-marker org-entry-property-inherited-from (point))
  11949. (throw 'exit nil))
  11950. ((org-up-heading-or-point-min))
  11951. (t
  11952. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11953. (cond ((not global))
  11954. (value (setq value (concat global " " value)))
  11955. (t (setq value global))))
  11956. (throw 'exit nil))))))
  11957. (if literal-nil value (org-not-nil value)))))
  11958. (defvar org-property-changed-functions nil
  11959. "Hook called when the value of a property has changed.
  11960. Each hook function should accept two arguments, the name of the property
  11961. and the new value.")
  11962. (defun org-entry-put (pom property value)
  11963. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11964. If the value is nil, it is converted to the empty string. If it
  11965. is not a string, an error is raised. Also raise an error on
  11966. invalid property names.
  11967. PROPERTY can be any regular property (see
  11968. `org-special-properties'). It can also be \"TODO\",
  11969. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11970. For the last two properties, VALUE may have any of the special
  11971. values \"earlier\" and \"later\". The function then increases or
  11972. decreases scheduled or deadline date by one day."
  11973. (cond ((null value) (setq value ""))
  11974. ((not (stringp value)) (error "Properties values should be strings"))
  11975. ((not (org--valid-property-p property))
  11976. (user-error "Invalid property name: \"%s\"" property)))
  11977. (org-no-read-only
  11978. (org-with-point-at pom
  11979. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11980. (org-back-to-heading-or-point-min t)
  11981. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11982. (let ((beg (point)))
  11983. (cond
  11984. ((equal property "TODO")
  11985. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11986. ((not (member value org-todo-keywords-1))
  11987. (user-error "\"%s\" is not a valid TODO state" value)))
  11988. (org-todo value)
  11989. (org-align-tags))
  11990. ((equal property "PRIORITY")
  11991. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11992. (org-align-tags))
  11993. ((equal property "SCHEDULED")
  11994. (forward-line)
  11995. (if (and (looking-at-p org-planning-line-re)
  11996. (re-search-forward
  11997. org-scheduled-time-regexp (line-end-position) t))
  11998. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11999. ((string= value "later") (org-timestamp-change 1 'day))
  12000. ((string= value "") (org-schedule '(4)))
  12001. (t (org-schedule nil value)))
  12002. (if (member value '("earlier" "later" ""))
  12003. (call-interactively #'org-schedule)
  12004. (org-schedule nil value))))
  12005. ((equal property "DEADLINE")
  12006. (forward-line)
  12007. (if (and (looking-at-p org-planning-line-re)
  12008. (re-search-forward
  12009. org-deadline-time-regexp (line-end-position) t))
  12010. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12011. ((string= value "later") (org-timestamp-change 1 'day))
  12012. ((string= value "") (org-deadline '(4)))
  12013. (t (org-deadline nil value)))
  12014. (if (member value '("earlier" "later" ""))
  12015. (call-interactively #'org-deadline)
  12016. (org-deadline nil value))))
  12017. ((member property org-special-properties)
  12018. (error "The %s property cannot be set with `org-entry-put'" property))
  12019. (t
  12020. (let* ((range (org-get-property-block beg 'force))
  12021. (end (cdr range))
  12022. (case-fold-search t))
  12023. (goto-char (car range))
  12024. (if (re-search-forward (org-re-property property nil t) end t)
  12025. (progn (delete-region (match-beginning 0) (match-end 0))
  12026. (goto-char (match-beginning 0)))
  12027. (goto-char end)
  12028. (insert "\n")
  12029. (backward-char))
  12030. (insert ":" property ":")
  12031. (when value (insert " " value))
  12032. (org-indent-line)))))
  12033. (run-hook-with-args 'org-property-changed-functions property value))))
  12034. (defun org-buffer-property-keys (&optional specials defaults columns)
  12035. "Get all property keys in the current buffer.
  12036. When SPECIALS is non-nil, also list the special properties that
  12037. reflect things like tags and TODO state.
  12038. When DEFAULTS is non-nil, also include properties that has
  12039. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12040. DESCRIPTION, LOCATION, and LOGGING and others.
  12041. When COLUMNS in non-nil, also include property names given in
  12042. COLUMN formats in the current buffer."
  12043. (let ((case-fold-search t)
  12044. (props (append
  12045. (and specials org-special-properties)
  12046. (and defaults (cons org-effort-property org-default-properties))
  12047. ;; Get property names from #+PROPERTY keywords as well
  12048. (mapcar (lambda (s)
  12049. (nth 0 (split-string s)))
  12050. (cdar (org-collect-keywords '("PROPERTY")))))))
  12051. (org-with-wide-buffer
  12052. (goto-char (point-min))
  12053. (while (re-search-forward org-property-start-re nil t)
  12054. (catch :skip
  12055. (let ((range (org-get-property-block)))
  12056. (unless range (throw :skip nil))
  12057. (goto-char (car range))
  12058. (let ((begin (car range))
  12059. (end (cdr range)))
  12060. ;; Make sure that found property block is not located
  12061. ;; before current point, as it would generate an infloop.
  12062. ;; It can happen, for example, in the following
  12063. ;; situation:
  12064. ;;
  12065. ;; * Headline
  12066. ;; :PROPERTIES:
  12067. ;; ...
  12068. ;; :END:
  12069. ;; *************** Inlinetask
  12070. ;; #+BEGIN_EXAMPLE
  12071. ;; :PROPERTIES:
  12072. ;; #+END_EXAMPLE
  12073. ;;
  12074. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12075. (while (< (point) end)
  12076. (let ((p (progn (looking-at org-property-re)
  12077. (match-string-no-properties 2))))
  12078. ;; Only add true property name, not extension symbol.
  12079. (push (if (not (string-match-p "\\+\\'" p)) p
  12080. (substring p 0 -1))
  12081. props))
  12082. (forward-line))))
  12083. (outline-next-heading)))
  12084. (when columns
  12085. (goto-char (point-min))
  12086. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12087. (let ((element (org-element-at-point)))
  12088. (when (memq (org-element-type element) '(keyword node-property))
  12089. (let ((value (org-element-property :value element))
  12090. (start 0))
  12091. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12092. \\(?:{[^}]+}\\)?"
  12093. value start)
  12094. (setq start (match-end 0))
  12095. (let ((p (match-string-no-properties 1 value)))
  12096. (unless (member-ignore-case p org-special-properties)
  12097. (push p props))))))))))
  12098. (sort (delete-dups
  12099. (append props
  12100. ;; for each xxx_ALL property, make sure the bare
  12101. ;; xxx property is also included
  12102. (delq nil (mapcar (lambda (p)
  12103. (and (string-match-p "._ALL\\'" p)
  12104. (substring p 0 -4)))
  12105. props))))
  12106. (lambda (a b) (string< (upcase a) (upcase b))))))
  12107. (defun org-property-values (key)
  12108. "List all non-nil values of property KEY in current buffer."
  12109. (org-with-wide-buffer
  12110. (goto-char (point-min))
  12111. (let ((case-fold-search t)
  12112. (re (org-re-property key))
  12113. values)
  12114. (while (re-search-forward re nil t)
  12115. (push (org-entry-get (point) key) values))
  12116. (delete-dups values))))
  12117. (defun org-insert-property-drawer ()
  12118. "Insert a property drawer into the current entry.
  12119. Do nothing if the drawer already exists. The newly created
  12120. drawer is immediately hidden."
  12121. (org-with-wide-buffer
  12122. ;; Set point to the position where the drawer should be inserted.
  12123. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12124. (org-back-to-heading-or-point-min t)
  12125. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12126. (if (org-before-first-heading-p)
  12127. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12128. (progn
  12129. (forward-line)
  12130. (when (looking-at-p org-planning-line-re) (forward-line))))
  12131. (unless (looking-at-p org-property-drawer-re)
  12132. ;; Make sure we start editing a line from current entry, not from
  12133. ;; next one. It prevents extending text properties or overlays
  12134. ;; belonging to the latter.
  12135. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12136. (let ((begin (if (bobp) (point) (1+ (point))))
  12137. (inhibit-read-only t))
  12138. (unless (bobp) (insert "\n"))
  12139. (insert ":PROPERTIES:\n:END:")
  12140. (org-flag-region (line-end-position 0) (point) t 'outline)
  12141. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12142. (org-indent-region begin (point))))))
  12143. (defun org-insert-drawer (&optional arg drawer)
  12144. "Insert a drawer at point.
  12145. When optional argument ARG is non-nil, insert a property drawer.
  12146. Optional argument DRAWER, when non-nil, is a string representing
  12147. drawer's name. Otherwise, the user is prompted for a name.
  12148. If a region is active, insert the drawer around that region
  12149. instead.
  12150. Point is left between drawer's boundaries."
  12151. (interactive "P")
  12152. (let* ((drawer (if arg "PROPERTIES"
  12153. (or drawer (read-from-minibuffer "Drawer: ")))))
  12154. (cond
  12155. ;; With C-u, fall back on `org-insert-property-drawer'
  12156. (arg (org-insert-property-drawer))
  12157. ;; Check validity of suggested drawer's name.
  12158. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12159. (user-error "Invalid drawer name"))
  12160. ;; With an active region, insert a drawer at point.
  12161. ((not (org-region-active-p))
  12162. (progn
  12163. (unless (bolp) (insert "\n"))
  12164. (insert (format ":%s:\n\n:END:\n" drawer))
  12165. (forward-line -2)))
  12166. ;; Otherwise, insert the drawer at point
  12167. (t
  12168. (let ((rbeg (region-beginning))
  12169. (rend (copy-marker (region-end))))
  12170. (unwind-protect
  12171. (progn
  12172. (goto-char rbeg)
  12173. (beginning-of-line)
  12174. (when (save-excursion
  12175. (re-search-forward org-outline-regexp-bol rend t))
  12176. (user-error "Drawers cannot contain headlines"))
  12177. ;; Position point at the beginning of the first
  12178. ;; non-blank line in region. Insert drawer's opening
  12179. ;; there, then indent it.
  12180. (org-skip-whitespace)
  12181. (beginning-of-line)
  12182. (insert ":" drawer ":\n")
  12183. (forward-line -1)
  12184. (indent-for-tab-command)
  12185. ;; Move point to the beginning of the first blank line
  12186. ;; after the last non-blank line in region. Insert
  12187. ;; drawer's closing, then indent it.
  12188. (goto-char rend)
  12189. (skip-chars-backward " \r\t\n")
  12190. (insert "\n:END:")
  12191. (deactivate-mark t)
  12192. (indent-for-tab-command)
  12193. (unless (eolp) (insert "\n")))
  12194. ;; Clear marker, whatever the outcome of insertion is.
  12195. (set-marker rend nil)))))))
  12196. (defvar org-property-set-functions-alist nil
  12197. "Property set function alist.
  12198. Each entry should have the following format:
  12199. (PROPERTY . READ-FUNCTION)
  12200. The read function will be called with the same argument as
  12201. `org-completing-read'.")
  12202. (defun org-set-property-function (property)
  12203. "Get the function that should be used to set PROPERTY.
  12204. This is computed according to `org-property-set-functions-alist'."
  12205. (or (cdr (assoc property org-property-set-functions-alist))
  12206. 'org-completing-read))
  12207. (defun org-read-property-value (property &optional pom default)
  12208. "Read value for PROPERTY, as a string.
  12209. When optional argument POM is non-nil, completion uses additional
  12210. information, i.e., allowed or existing values at point or marker
  12211. POM.
  12212. Optional argument DEFAULT provides a default value for PROPERTY."
  12213. (let* ((completion-ignore-case t)
  12214. (allowed
  12215. (or (org-property-get-allowed-values nil property 'table)
  12216. (and pom (org-property-get-allowed-values pom property 'table))))
  12217. (current (org-entry-get nil property))
  12218. (prompt (format "%s value%s: "
  12219. property
  12220. (if (org-string-nw-p current)
  12221. (format " [%s]" current)
  12222. "")))
  12223. (set-function (org-set-property-function property)))
  12224. (org-trim
  12225. (if allowed
  12226. (funcall set-function
  12227. prompt allowed nil
  12228. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12229. default nil default)
  12230. (let ((all (mapcar #'list
  12231. (append (org-property-values property)
  12232. (and pom
  12233. (org-with-point-at pom
  12234. (org-property-values property)))))))
  12235. (funcall set-function prompt all nil nil "" nil current))))))
  12236. (defvar org-last-set-property nil)
  12237. (defvar org-last-set-property-value nil)
  12238. (defun org-read-property-name ()
  12239. "Read a property name."
  12240. (let ((completion-ignore-case t)
  12241. (default-prop (or (and (org-at-property-p)
  12242. (match-string-no-properties 2))
  12243. org-last-set-property)))
  12244. (org-completing-read
  12245. (concat "Property"
  12246. (if default-prop (concat " [" default-prop "]") "")
  12247. ": ")
  12248. (mapcar #'list (org-buffer-property-keys nil t t))
  12249. nil nil nil nil default-prop)))
  12250. (defun org-set-property-and-value (use-last)
  12251. "Allow to set [PROPERTY]: [value] direction from prompt.
  12252. When use-default, don't even ask, just use the last
  12253. \"[PROPERTY]: [value]\" string from the history."
  12254. (interactive "P")
  12255. (let* ((completion-ignore-case t)
  12256. (pv (or (and use-last org-last-set-property-value)
  12257. (org-completing-read
  12258. "Enter a \"[Property]: [value]\" pair: "
  12259. nil nil nil nil nil
  12260. org-last-set-property-value)))
  12261. prop val)
  12262. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12263. (setq prop (match-string 1 pv)
  12264. val (match-string 2 pv))
  12265. (org-set-property prop val))))
  12266. (defun org-set-property (property value)
  12267. "In the current entry, set PROPERTY to VALUE.
  12268. When called interactively, this will prompt for a property name, offering
  12269. completion on existing and default properties. And then it will prompt
  12270. for a value, offering completion either on allowed values (via an inherited
  12271. xxx_ALL property) or on existing values in other instances of this property
  12272. in the current file.
  12273. Throw an error when trying to set a property with an invalid name."
  12274. (interactive (list nil nil))
  12275. (let ((property (or property (org-read-property-name))))
  12276. ;; `org-entry-put' also makes the following check, but this one
  12277. ;; avoids polluting `org-last-set-property' and
  12278. ;; `org-last-set-property-value' needlessly.
  12279. (unless (org--valid-property-p property)
  12280. (user-error "Invalid property name: \"%s\"" property))
  12281. (let ((value (or value (org-read-property-value property)))
  12282. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12283. (setq org-last-set-property property)
  12284. (setq org-last-set-property-value (concat property ": " value))
  12285. ;; Possibly postprocess the inserted value:
  12286. (when fn (setq value (funcall fn value)))
  12287. (unless (equal (org-entry-get nil property) value)
  12288. (org-entry-put nil property value)))))
  12289. (defun org-find-property (property &optional value)
  12290. "Find first entry in buffer that sets PROPERTY.
  12291. When optional argument VALUE is non-nil, only consider an entry
  12292. if it contains PROPERTY set to this value. If PROPERTY should be
  12293. explicitly set to nil, use string \"nil\" for VALUE.
  12294. Return position where the entry begins, or nil if there is no
  12295. such entry. If narrowing is in effect, only search the visible
  12296. part of the buffer."
  12297. (save-excursion
  12298. (goto-char (point-min))
  12299. (let ((case-fold-search t)
  12300. (re (org-re-property property nil (not value) value)))
  12301. (catch 'exit
  12302. (while (re-search-forward re nil t)
  12303. (when (if value (org-at-property-p)
  12304. (org-entry-get (point) property nil t))
  12305. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12306. (point)))))))))
  12307. (defun org-delete-property (property)
  12308. "In the current entry, delete PROPERTY."
  12309. (interactive
  12310. (let* ((completion-ignore-case t)
  12311. (cat (org-entry-get (point) "CATEGORY"))
  12312. (props0 (org-entry-properties nil 'standard))
  12313. (props (if cat props0
  12314. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12315. (prop (if (< 1 (length props))
  12316. (completing-read "Property: " props nil t)
  12317. (caar props))))
  12318. (list prop)))
  12319. (if (not property)
  12320. (message "No property to delete in this entry")
  12321. (org-entry-delete nil property)
  12322. (message "Property \"%s\" deleted" property)))
  12323. (defun org-delete-property-globally (property)
  12324. "Remove PROPERTY globally, from all entries.
  12325. This function ignores narrowing, if any."
  12326. (interactive
  12327. (let* ((completion-ignore-case t)
  12328. (prop (completing-read
  12329. "Globally remove property: "
  12330. (mapcar #'list (org-buffer-property-keys)))))
  12331. (list prop)))
  12332. (org-with-wide-buffer
  12333. (goto-char (point-min))
  12334. (let ((count 0)
  12335. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12336. (while (re-search-forward re nil t)
  12337. (when (org-entry-delete (point) property) (cl-incf count)))
  12338. (message "Property \"%s\" removed from %d entries" property count))))
  12339. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12340. (defun org-compute-property-at-point ()
  12341. "Compute the property at point.
  12342. This looks for an enclosing column format, extracts the operator and
  12343. then applies it to the property in the column format's scope."
  12344. (interactive)
  12345. (unless (org-at-property-p)
  12346. (user-error "Not at a property"))
  12347. (let ((prop (match-string-no-properties 2)))
  12348. (org-columns-get-format-and-top-level)
  12349. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12350. (user-error "No operator defined for property %s" prop))
  12351. (org-columns-compute prop)))
  12352. (defvar org-property-allowed-value-functions nil
  12353. "Hook for functions supplying allowed values for a specific property.
  12354. The functions must take a single argument, the name of the property, and
  12355. return a flat list of allowed values. If \":ETC\" is one of
  12356. the values, this means that these values are intended as defaults for
  12357. completion, but that other values should be allowed too.
  12358. The functions must return nil if they are not responsible for this
  12359. property.")
  12360. (defun org-property-get-allowed-values (pom property &optional table)
  12361. "Get allowed values for the property PROPERTY.
  12362. When TABLE is non-nil, return an alist that can directly be used for
  12363. completion."
  12364. (let (vals)
  12365. (cond
  12366. ((equal property "TODO")
  12367. (setq vals (org-with-point-at pom
  12368. (append org-todo-keywords-1 '("")))))
  12369. ((equal property "PRIORITY")
  12370. (let ((n org-priority-lowest))
  12371. (while (>= n org-priority-highest)
  12372. (push (char-to-string n) vals)
  12373. (setq n (1- n)))))
  12374. ((equal property "CATEGORY"))
  12375. ((member property org-special-properties))
  12376. ((setq vals (run-hook-with-args-until-success
  12377. 'org-property-allowed-value-functions property)))
  12378. (t
  12379. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12380. (when (and vals (string-match "\\S-" vals))
  12381. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12382. (setq vals (mapcar (lambda (x)
  12383. (cond ((stringp x) x)
  12384. ((numberp x) (number-to-string x))
  12385. ((symbolp x) (symbol-name x))
  12386. (t "???")))
  12387. vals)))))
  12388. (when (member ":ETC" vals)
  12389. (setq vals (remove ":ETC" vals))
  12390. (org-add-props (car vals) '(org-unrestricted t)))
  12391. (if table (mapcar 'list vals) vals)))
  12392. (defun org-property-previous-allowed-value (&optional _previous)
  12393. "Switch to the next allowed value for this property."
  12394. (interactive)
  12395. (org-property-next-allowed-value t))
  12396. (defun org-property-next-allowed-value (&optional previous)
  12397. "Switch to the next allowed value for this property."
  12398. (interactive)
  12399. (unless (org-at-property-p)
  12400. (user-error "Not at a property"))
  12401. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12402. (key (match-string 2))
  12403. (value (match-string 3))
  12404. (allowed (or (org-property-get-allowed-values (point) key)
  12405. (and (member value '("[ ]" "[-]" "[X]"))
  12406. '("[ ]" "[X]"))))
  12407. (heading (save-match-data (nth 4 (org-heading-components))))
  12408. nval)
  12409. (unless allowed
  12410. (user-error "Allowed values for this property have not been defined"))
  12411. (when previous (setq allowed (reverse allowed)))
  12412. (when (member value allowed)
  12413. (setq nval (car (cdr (member value allowed)))))
  12414. (setq nval (or nval (car allowed)))
  12415. (when (equal nval value)
  12416. (user-error "Only one allowed value for this property"))
  12417. (org-at-property-p)
  12418. (replace-match (concat " :" key ": " nval) t t)
  12419. (org-indent-line)
  12420. (beginning-of-line 1)
  12421. (skip-chars-forward " \t")
  12422. (when (equal prop org-effort-property)
  12423. (org-refresh-property
  12424. '((effort . identity)
  12425. (effort-minutes . org-duration-to-minutes))
  12426. nval)
  12427. (when (string= org-clock-current-task heading)
  12428. (setq org-clock-effort nval)
  12429. (org-clock-update-mode-line)))
  12430. (run-hook-with-args 'org-property-changed-functions key nval)))
  12431. (defun org-find-olp (path &optional this-buffer)
  12432. "Return a marker pointing to the entry at outline path OLP.
  12433. If anything goes wrong, throw an error, and if you need to do
  12434. something based on this error, you can catch it with
  12435. `condition-case'.
  12436. If THIS-BUFFER is set, the outline path does not contain a file,
  12437. only headings."
  12438. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12439. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12440. (level 1)
  12441. (lmin 1)
  12442. (lmax 1)
  12443. end found flevel)
  12444. (unless buffer (error "File not found :%s" file))
  12445. (with-current-buffer buffer
  12446. (unless (derived-mode-p 'org-mode)
  12447. (error "Buffer %s needs to be in Org mode" buffer))
  12448. (org-with-wide-buffer
  12449. (goto-char (point-min))
  12450. (dolist (heading path)
  12451. (let ((re (format org-complex-heading-regexp-format
  12452. (regexp-quote heading)))
  12453. (cnt 0))
  12454. (while (re-search-forward re end t)
  12455. (setq level (- (match-end 1) (match-beginning 1)))
  12456. (when (and (>= level lmin) (<= level lmax))
  12457. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12458. (when (= cnt 0)
  12459. (error "Heading not found on level %d: %s" lmax heading))
  12460. (when (> cnt 1)
  12461. (error "Heading not unique on level %d: %s" lmax heading))
  12462. (goto-char found)
  12463. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12464. (setq end (save-excursion (org-end-of-subtree t t)))))
  12465. (when (org-at-heading-p)
  12466. (point-marker))))))
  12467. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12468. "Find node HEADING in BUFFER.
  12469. Return a marker to the heading if it was found, or nil if not.
  12470. If POS-ONLY is set, return just the position instead of a marker.
  12471. The heading text must match exact, but it may have a TODO keyword,
  12472. a priority cookie and tags in the standard locations."
  12473. (with-current-buffer (or buffer (current-buffer))
  12474. (org-with-wide-buffer
  12475. (goto-char (point-min))
  12476. (let (case-fold-search)
  12477. (when (re-search-forward
  12478. (format org-complex-heading-regexp-format
  12479. (regexp-quote heading)) nil t)
  12480. (if pos-only
  12481. (match-beginning 0)
  12482. (move-marker (make-marker) (match-beginning 0))))))))
  12483. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12484. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12485. When the target headline is found, return a marker to this location."
  12486. (let ((files (directory-files (or dir default-directory)
  12487. t "\\`[^.#].*\\.org\\'"))
  12488. visiting m buffer)
  12489. (catch 'found
  12490. (dolist (file files)
  12491. (message "trying %s" file)
  12492. (setq visiting (org-find-base-buffer-visiting file))
  12493. (setq buffer (or visiting (find-file-noselect file)))
  12494. (setq m (org-find-exact-headline-in-buffer
  12495. heading buffer))
  12496. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12497. (and m (throw 'found m))))))
  12498. (defun org-find-entry-with-id (ident)
  12499. "Locate the entry that contains the ID property with exact value IDENT.
  12500. IDENT can be a string, a symbol or a number, this function will search for
  12501. the string representation of it.
  12502. Return the position where this entry starts, or nil if there is no such entry."
  12503. (interactive "sID: ")
  12504. (let ((id (cond
  12505. ((stringp ident) ident)
  12506. ((symbolp ident) (symbol-name ident))
  12507. ((numberp ident) (number-to-string ident))
  12508. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12509. (org-with-wide-buffer (org-find-property "ID" id))))
  12510. ;;;; Timestamps
  12511. (defvar org-last-changed-timestamp nil)
  12512. (defvar org-last-inserted-timestamp nil
  12513. "The last time stamp inserted with `org-insert-time-stamp'.")
  12514. (defun org-time-stamp (arg &optional inactive)
  12515. "Prompt for a date/time and insert a time stamp.
  12516. If the user specifies a time like HH:MM or if this command is
  12517. called with at least one prefix argument, the time stamp contains
  12518. the date and the time. Otherwise, only the date is included.
  12519. All parts of a date not specified by the user are filled in from
  12520. the timestamp at point, if any, or the current date/time
  12521. otherwise.
  12522. If there is already a timestamp at the cursor, it is replaced.
  12523. With two universal prefix arguments, insert an active timestamp
  12524. with the current time without prompting the user.
  12525. When called from lisp, the timestamp is inactive if INACTIVE is
  12526. non-nil."
  12527. (interactive "P")
  12528. (let* ((ts (cond
  12529. ((org-at-date-range-p t)
  12530. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12531. ((org-at-timestamp-p 'lax) (match-string 0))))
  12532. ;; Default time is either the timestamp at point or today.
  12533. ;; When entering a range, only the range start is considered.
  12534. (default-time (and ts (org-time-string-to-time ts)))
  12535. (default-input (and ts (org-get-compact-tod ts)))
  12536. (repeater (and ts
  12537. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12538. (match-string 0 ts)))
  12539. org-time-was-given
  12540. org-end-time-was-given
  12541. (time
  12542. (if (equal arg '(16)) (current-time)
  12543. ;; Preserve `this-command' and `last-command'.
  12544. (let ((this-command this-command)
  12545. (last-command last-command))
  12546. (org-read-date
  12547. arg 'totime nil nil default-time default-input
  12548. inactive)))))
  12549. (cond
  12550. ((and ts
  12551. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12552. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12553. (insert "--")
  12554. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12555. (ts
  12556. ;; Make sure we're on a timestamp. When in the middle of a date
  12557. ;; range, move arbitrarily to range end.
  12558. (unless (org-at-timestamp-p 'lax)
  12559. (skip-chars-forward "-")
  12560. (org-at-timestamp-p 'lax))
  12561. (replace-match "")
  12562. (setq org-last-changed-timestamp
  12563. (org-insert-time-stamp
  12564. time (or org-time-was-given arg)
  12565. inactive nil nil (list org-end-time-was-given)))
  12566. (when repeater
  12567. (backward-char)
  12568. (insert " " repeater)
  12569. (setq org-last-changed-timestamp
  12570. (concat (substring org-last-inserted-timestamp 0 -1)
  12571. " " repeater ">")))
  12572. (message "Timestamp updated"))
  12573. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12574. (t (org-insert-time-stamp
  12575. time (or org-time-was-given arg) inactive nil nil
  12576. (list org-end-time-was-given))))))
  12577. ;; FIXME: can we use this for something else, like computing time differences?
  12578. (defun org-get-compact-tod (s)
  12579. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12580. (let* ((t1 (match-string 1 s))
  12581. (h1 (string-to-number (match-string 2 s)))
  12582. (m1 (string-to-number (match-string 3 s)))
  12583. (t2 (and (match-end 4) (match-string 5 s)))
  12584. (h2 (and t2 (string-to-number (match-string 6 s))))
  12585. (m2 (and t2 (string-to-number (match-string 7 s))))
  12586. dh dm)
  12587. (if (not t2)
  12588. t1
  12589. (setq dh (- h2 h1) dm (- m2 m1))
  12590. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12591. (concat t1 "+" (number-to-string dh)
  12592. (and (/= 0 dm) (format ":%02d" dm)))))))
  12593. (defun org-time-stamp-inactive (&optional arg)
  12594. "Insert an inactive time stamp.
  12595. An inactive time stamp is enclosed in square brackets instead of
  12596. angle brackets. It is inactive in the sense that it does not
  12597. trigger agenda entries. So these are more for recording a
  12598. certain time/date.
  12599. If the user specifies a time like HH:MM or if this command is called with
  12600. at least one prefix argument, the time stamp contains the date and the time.
  12601. Otherwise, only the date is included.
  12602. When called with two universal prefix arguments, insert an inactive time stamp
  12603. with the current time without prompting the user."
  12604. (interactive "P")
  12605. (org-time-stamp arg 'inactive))
  12606. (defvar org-date-ovl (make-overlay 1 1))
  12607. (overlay-put org-date-ovl 'face 'org-date-selected)
  12608. (delete-overlay org-date-ovl)
  12609. (defvar org-ans1) ; dynamically scoped parameter
  12610. (defvar org-ans2) ; dynamically scoped parameter
  12611. (defvar org-plain-time-of-day-regexp) ; defined below
  12612. (defvar org-overriding-default-time nil) ; dynamically scoped
  12613. (defvar org-read-date-overlay nil)
  12614. (defvar org-read-date-history nil)
  12615. (defvar org-read-date-final-answer nil)
  12616. (defvar org-read-date-analyze-futurep nil)
  12617. (defvar org-read-date-analyze-forced-year nil)
  12618. (defvar org-read-date-inactive)
  12619. (defvar org-def)
  12620. (defvar org-defdecode)
  12621. (defvar org-with-time)
  12622. (defvar calendar-setup) ; Dynamically scoped.
  12623. (defun org-read-date (&optional with-time to-time from-string prompt
  12624. default-time default-input inactive)
  12625. "Read a date, possibly a time, and make things smooth for the user.
  12626. The prompt will suggest to enter an ISO date, but you can also enter anything
  12627. which will at least partially be understood by `parse-time-string'.
  12628. Unrecognized parts of the date will default to the current day, month, year,
  12629. hour and minute. If this command is called to replace a timestamp at point,
  12630. or to enter the second timestamp of a range, the default time is taken
  12631. from the existing stamp. Furthermore, the command prefers the future,
  12632. so if you are giving a date where the year is not given, and the day-month
  12633. combination is already past in the current year, it will assume you
  12634. mean next year. For details, see the manual. A few examples:
  12635. 3-2-5 --> 2003-02-05
  12636. feb 15 --> currentyear-02-15
  12637. 2/15 --> currentyear-02-15
  12638. sep 12 9 --> 2009-09-12
  12639. 12:45 --> today 12:45
  12640. 22 sept 0:34 --> currentyear-09-22 0:34
  12641. 12 --> currentyear-currentmonth-12
  12642. Fri --> nearest Friday after today
  12643. -Tue --> last Tuesday
  12644. etc.
  12645. Furthermore you can specify a relative date by giving, as the *first* thing
  12646. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12647. change in days weeks, months, years.
  12648. With a single plus or minus, the date is relative to today. With a double
  12649. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12650. +4d --> four days from today
  12651. +4 --> same as above
  12652. +2w --> two weeks from today
  12653. ++5 --> five days from default date
  12654. The function understands only English month and weekday abbreviations.
  12655. While prompting, a calendar is popped up - you can also select the
  12656. date with the mouse (button 1). The calendar shows a period of three
  12657. months. To scroll it to other months, use the keys `>' and `<'.
  12658. If you don't like the calendar, turn it off with
  12659. (setq org-read-date-popup-calendar nil)
  12660. With optional argument TO-TIME, the date will immediately be converted
  12661. to an internal time.
  12662. With an optional argument WITH-TIME, the prompt will suggest to
  12663. also insert a time. Note that when WITH-TIME is not set, you can
  12664. still enter a time, and this function will inform the calling routine
  12665. about this change. The calling routine may then choose to change the
  12666. format used to insert the time stamp into the buffer to include the time.
  12667. With optional argument FROM-STRING, read from this string instead from
  12668. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12669. the time/date that is used for everything that is not specified by the
  12670. user."
  12671. (require 'parse-time)
  12672. (let* ((org-with-time with-time)
  12673. (org-time-stamp-rounding-minutes
  12674. (if (equal org-with-time '(16))
  12675. '(0 0)
  12676. org-time-stamp-rounding-minutes))
  12677. (ct (org-current-time))
  12678. (org-def (or org-overriding-default-time default-time ct))
  12679. (org-defdecode (decode-time org-def))
  12680. (cur-frame (selected-frame))
  12681. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12682. (calendar-setup
  12683. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12684. (calendar-move-hook nil)
  12685. (calendar-view-diary-initially-flag nil)
  12686. (calendar-view-holidays-initially-flag nil)
  12687. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12688. ;; Rationalize `org-def' and `org-defdecode', if required.
  12689. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12690. (setf (nth 2 org-defdecode) -1)
  12691. (setf (nth 1 org-defdecode) 59)
  12692. (setq org-def (apply #'encode-time org-defdecode))
  12693. (setq org-defdecode (decode-time org-def)))
  12694. (let* ((timestr (format-time-string
  12695. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12696. org-def))
  12697. (prompt (concat (if prompt (concat prompt " ") "")
  12698. (format "Date+time [%s]: " timestr))))
  12699. (cond
  12700. (from-string (setq ans from-string))
  12701. (org-read-date-popup-calendar
  12702. (save-excursion
  12703. (save-window-excursion
  12704. (calendar)
  12705. (when (eq calendar-setup 'calendar-only)
  12706. (setq cal-frame
  12707. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12708. (select-frame cal-frame))
  12709. (org-eval-in-calendar '(setq cursor-type nil) t)
  12710. (unwind-protect
  12711. (progn
  12712. (calendar-forward-day (- (time-to-days org-def)
  12713. (calendar-absolute-from-gregorian
  12714. (calendar-current-date))))
  12715. (org-eval-in-calendar nil t)
  12716. (let* ((old-map (current-local-map))
  12717. (map (copy-keymap calendar-mode-map))
  12718. (minibuffer-local-map
  12719. (copy-keymap org-read-date-minibuffer-local-map)))
  12720. (org-defkey map (kbd "RET") 'org-calendar-select)
  12721. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12722. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12723. (unwind-protect
  12724. (progn
  12725. (use-local-map map)
  12726. (setq org-read-date-inactive inactive)
  12727. (add-hook 'post-command-hook 'org-read-date-display)
  12728. (setq org-ans0
  12729. (read-string prompt
  12730. default-input
  12731. 'org-read-date-history
  12732. nil))
  12733. ;; org-ans0: from prompt
  12734. ;; org-ans1: from mouse click
  12735. ;; org-ans2: from calendar motion
  12736. (setq ans
  12737. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12738. (remove-hook 'post-command-hook 'org-read-date-display)
  12739. (use-local-map old-map)
  12740. (when org-read-date-overlay
  12741. (delete-overlay org-read-date-overlay)
  12742. (setq org-read-date-overlay nil)))))
  12743. (bury-buffer "*Calendar*")
  12744. (when cal-frame
  12745. (delete-frame cal-frame)
  12746. (select-frame-set-input-focus cur-frame))))))
  12747. (t ; Naked prompt only
  12748. (unwind-protect
  12749. (setq ans (read-string prompt default-input
  12750. 'org-read-date-history timestr))
  12751. (when org-read-date-overlay
  12752. (delete-overlay org-read-date-overlay)
  12753. (setq org-read-date-overlay nil))))))
  12754. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12755. (when org-read-date-analyze-forced-year
  12756. (message "Year was forced into %s"
  12757. (if org-read-date-force-compatible-dates
  12758. "compatible range (1970-2037)"
  12759. "range representable on this machine"))
  12760. (ding))
  12761. (setq final (apply #'encode-time final))
  12762. (setq org-read-date-final-answer ans)
  12763. (if to-time
  12764. final
  12765. ;; This round-trip gets rid of 34th of August and stuff like that....
  12766. (setq final (decode-time final))
  12767. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12768. (format "%04d-%02d-%02d %02d:%02d"
  12769. (nth 5 final) (nth 4 final) (nth 3 final)
  12770. (nth 2 final) (nth 1 final))
  12771. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12772. (defun org-read-date-display ()
  12773. "Display the current date prompt interpretation in the minibuffer."
  12774. (when org-read-date-display-live
  12775. (when org-read-date-overlay
  12776. (delete-overlay org-read-date-overlay))
  12777. (when (minibufferp (current-buffer))
  12778. (save-excursion
  12779. (end-of-line 1)
  12780. (while (not (equal (buffer-substring
  12781. (max (point-min) (- (point) 4)) (point))
  12782. " "))
  12783. (insert " ")))
  12784. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12785. " " (or org-ans1 org-ans2)))
  12786. (org-end-time-was-given nil)
  12787. (f (org-read-date-analyze ans org-def org-defdecode))
  12788. (fmts (if org-display-custom-times
  12789. org-time-stamp-custom-formats
  12790. org-time-stamp-formats))
  12791. (fmt (if (or org-with-time
  12792. (and (boundp 'org-time-was-given) org-time-was-given))
  12793. (cdr fmts)
  12794. (car fmts)))
  12795. (txt (format-time-string fmt (apply #'encode-time f)))
  12796. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12797. (txt (concat "=> " txt)))
  12798. (when (and org-end-time-was-given
  12799. (string-match org-plain-time-of-day-regexp txt))
  12800. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12801. org-end-time-was-given
  12802. (substring txt (match-end 0)))))
  12803. (when org-read-date-analyze-futurep
  12804. (setq txt (concat txt " (=>F)")))
  12805. (setq org-read-date-overlay
  12806. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12807. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12808. (defun org-read-date-analyze (ans def defdecode)
  12809. "Analyze the combined answer of the date prompt."
  12810. ;; FIXME: cleanup and comment
  12811. (let ((org-def def)
  12812. (org-defdecode defdecode)
  12813. (nowdecode (decode-time))
  12814. delta deltan deltaw deltadef year month day
  12815. hour minute second wday pm h2 m2 tl wday1
  12816. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12817. (setq org-read-date-analyze-futurep nil
  12818. org-read-date-analyze-forced-year nil)
  12819. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12820. (setq ans "+0"))
  12821. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12822. (setq ans (replace-match "" t t ans)
  12823. deltan (car delta)
  12824. deltaw (nth 1 delta)
  12825. deltadef (nth 2 delta)))
  12826. ;; Check if there is an iso week date in there. If yes, store the
  12827. ;; info and postpone interpreting it until the rest of the parsing
  12828. ;; is done.
  12829. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12830. (setq iso-year (when (match-end 1)
  12831. (org-small-year-to-year
  12832. (string-to-number (match-string 1 ans))))
  12833. iso-weekday (when (match-end 3)
  12834. (string-to-number (match-string 3 ans)))
  12835. iso-week (string-to-number (match-string 2 ans)))
  12836. (setq ans (replace-match "" t t ans)))
  12837. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12838. (when (string-match
  12839. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12840. (setq year (if (match-end 2)
  12841. (string-to-number (match-string 2 ans))
  12842. (progn (setq kill-year t)
  12843. (string-to-number (format-time-string "%Y"))))
  12844. month (string-to-number (match-string 3 ans))
  12845. day (string-to-number (match-string 4 ans)))
  12846. (setq year (org-small-year-to-year year))
  12847. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12848. t nil ans)))
  12849. ;; Help matching dotted european dates
  12850. (when (string-match
  12851. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12852. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12853. (setq kill-year t)
  12854. (string-to-number (format-time-string "%Y")))
  12855. day (string-to-number (match-string 1 ans))
  12856. month (string-to-number (match-string 2 ans))
  12857. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12858. t nil ans)))
  12859. ;; Help matching american dates, like 5/30 or 5/30/7
  12860. (when (string-match
  12861. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12862. (setq year (if (match-end 4)
  12863. (string-to-number (match-string 4 ans))
  12864. (progn (setq kill-year t)
  12865. (string-to-number (format-time-string "%Y"))))
  12866. month (string-to-number (match-string 1 ans))
  12867. day (string-to-number (match-string 2 ans)))
  12868. (setq year (org-small-year-to-year year))
  12869. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12870. t nil ans)))
  12871. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12872. ;; If there is a time with am/pm, and *no* time without it, we convert
  12873. ;; so that matching will be successful.
  12874. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12875. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12876. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12877. (setq hour (string-to-number (match-string 1 ans))
  12878. minute (if (match-end 3)
  12879. (string-to-number (match-string 3 ans))
  12880. 0)
  12881. pm (equal ?p
  12882. (string-to-char (downcase (match-string 4 ans)))))
  12883. (if (and (= hour 12) (not pm))
  12884. (setq hour 0)
  12885. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12886. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12887. t t ans))))
  12888. ;; Help matching HHhMM times, similarly as for am/pm times.
  12889. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12890. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12891. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12892. (setq hour (if (match-end 1)
  12893. (string-to-number (match-string 1 ans))
  12894. 0)
  12895. minute (if (match-end 2)
  12896. (string-to-number (match-string 2 ans))
  12897. 0))
  12898. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12899. t t ans))))
  12900. ;; Check if a time range is given as a duration
  12901. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12902. (setq hour (string-to-number (match-string 1 ans))
  12903. h2 (+ hour (string-to-number (match-string 3 ans)))
  12904. minute (string-to-number (match-string 2 ans))
  12905. m2 (+ minute (if (match-end 5) (string-to-number
  12906. (match-string 5 ans))0)))
  12907. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12908. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12909. t t ans)))
  12910. ;; Check if there is a time range
  12911. (when (boundp 'org-end-time-was-given)
  12912. (setq org-time-was-given nil)
  12913. (when (and (string-match org-plain-time-of-day-regexp ans)
  12914. (match-end 8))
  12915. (setq org-end-time-was-given (match-string 8 ans))
  12916. (setq ans (concat (substring ans 0 (match-beginning 7))
  12917. (substring ans (match-end 7))))))
  12918. (setq tl (parse-time-string ans)
  12919. day (or (nth 3 tl) (nth 3 org-defdecode))
  12920. month
  12921. (cond ((nth 4 tl))
  12922. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12923. ;; Day was specified. Make sure DAY+MONTH
  12924. ;; combination happens in the future.
  12925. ((nth 3 tl)
  12926. (setq futurep t)
  12927. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12928. (nth 4 nowdecode)))
  12929. (t (nth 4 org-defdecode)))
  12930. year
  12931. (cond ((and (not kill-year) (nth 5 tl)))
  12932. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12933. ;; Month was guessed in the future and is at least
  12934. ;; equal to NOWDECODE's. Fix year accordingly.
  12935. (futurep
  12936. (if (or (> month (nth 4 nowdecode))
  12937. (>= day (nth 3 nowdecode)))
  12938. (nth 5 nowdecode)
  12939. (1+ (nth 5 nowdecode))))
  12940. ;; Month was specified. Make sure MONTH+YEAR
  12941. ;; combination happens in the future.
  12942. ((nth 4 tl)
  12943. (setq futurep t)
  12944. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12945. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12946. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12947. (t (nth 5 nowdecode))))
  12948. (t (nth 5 org-defdecode)))
  12949. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12950. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12951. second (or (nth 0 tl) 0)
  12952. wday (nth 6 tl))
  12953. (when (and (eq org-read-date-prefer-future 'time)
  12954. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12955. (equal day (nth 3 nowdecode))
  12956. (equal month (nth 4 nowdecode))
  12957. (equal year (nth 5 nowdecode))
  12958. (nth 2 tl)
  12959. (or (< (nth 2 tl) (nth 2 nowdecode))
  12960. (and (= (nth 2 tl) (nth 2 nowdecode))
  12961. (nth 1 tl)
  12962. (< (nth 1 tl) (nth 1 nowdecode)))))
  12963. (setq day (1+ day)
  12964. futurep t))
  12965. ;; Special date definitions below
  12966. (cond
  12967. (iso-week
  12968. ;; There was an iso week
  12969. (require 'cal-iso)
  12970. (setq futurep nil)
  12971. (setq year (or iso-year year)
  12972. day (or iso-weekday wday 1)
  12973. wday nil ; to make sure that the trigger below does not match
  12974. iso-date (calendar-gregorian-from-absolute
  12975. (calendar-iso-to-absolute
  12976. (list iso-week day year))))
  12977. ; FIXME: Should we also push ISO weeks into the future?
  12978. ; (when (and org-read-date-prefer-future
  12979. ; (not iso-year)
  12980. ; (< (calendar-absolute-from-gregorian iso-date)
  12981. ; (time-to-days nil)))
  12982. ; (setq year (1+ year)
  12983. ; iso-date (calendar-gregorian-from-absolute
  12984. ; (calendar-iso-to-absolute
  12985. ; (list iso-week day year)))))
  12986. (setq month (car iso-date)
  12987. year (nth 2 iso-date)
  12988. day (nth 1 iso-date)))
  12989. (deltan
  12990. (setq futurep nil)
  12991. (unless deltadef
  12992. (let ((now (decode-time)))
  12993. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12994. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12995. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12996. ((equal deltaw "m") (setq month (+ month deltan)))
  12997. ((equal deltaw "y") (setq year (+ year deltan)))))
  12998. ((and wday (not (nth 3 tl)))
  12999. ;; Weekday was given, but no day, so pick that day in the week
  13000. ;; on or after the derived date.
  13001. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13002. (unless (equal wday wday1)
  13003. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13004. (when (and (boundp 'org-time-was-given)
  13005. (nth 2 tl))
  13006. (setq org-time-was-given t))
  13007. (when (< year 100) (setq year (+ 2000 year)))
  13008. ;; Check of the date is representable
  13009. (if org-read-date-force-compatible-dates
  13010. (progn
  13011. (when (< year 1970)
  13012. (setq year 1970 org-read-date-analyze-forced-year t))
  13013. (when (> year 2037)
  13014. (setq year 2037 org-read-date-analyze-forced-year t)))
  13015. (condition-case nil
  13016. (ignore (encode-time second minute hour day month year))
  13017. (error
  13018. (setq year (nth 5 org-defdecode))
  13019. (setq org-read-date-analyze-forced-year t))))
  13020. (setq org-read-date-analyze-futurep futurep)
  13021. (list second minute hour day month year)))
  13022. (defvar parse-time-weekdays)
  13023. (defun org-read-date-get-relative (s today default)
  13024. "Check string S for special relative date string.
  13025. TODAY and DEFAULT are internal times, for today and for a default.
  13026. Return shift list (N what def-flag)
  13027. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13028. N is the number of WHATs to shift.
  13029. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13030. the DEFAULT date rather than TODAY."
  13031. (require 'parse-time)
  13032. (when (and
  13033. (string-match
  13034. (concat
  13035. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13036. "\\([0-9]+\\)?"
  13037. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13038. "\\([ \t]\\|$\\)") s)
  13039. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13040. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13041. (string-to-char (substring (match-string 1 s) -1))
  13042. ?+))
  13043. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13044. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13045. (what (if (match-end 3) (match-string 3 s) "d"))
  13046. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13047. (date (if rel default today))
  13048. (wday (nth 6 (decode-time date)))
  13049. delta)
  13050. (if wday1
  13051. (progn
  13052. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13053. (when (= delta 0) (setq delta 7))
  13054. (when (= dir ?-)
  13055. (setq delta (- delta 7))
  13056. (when (= delta 0) (setq delta -7)))
  13057. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13058. (list delta "d" rel))
  13059. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13060. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13061. "Turn a user-specified date into the internal representation.
  13062. The internal representation needed by the calendar is (month day year).
  13063. This is a wrapper to handle the brain-dead convention in calendar that
  13064. user function argument order change dependent on argument order."
  13065. (pcase calendar-date-style
  13066. (`american (list arg1 arg2 arg3))
  13067. (`european (list arg2 arg1 arg3))
  13068. (`iso (list arg2 arg3 arg1))))
  13069. (defun org-eval-in-calendar (form &optional keepdate)
  13070. "Eval FORM in the calendar window and return to current window.
  13071. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13072. (let ((sf (selected-frame))
  13073. (sw (selected-window)))
  13074. (select-window (get-buffer-window "*Calendar*" t))
  13075. (eval form)
  13076. (when (and (not keepdate) (calendar-cursor-to-date))
  13077. (let* ((date (calendar-cursor-to-date))
  13078. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13079. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13080. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13081. (select-window sw)
  13082. (select-frame-set-input-focus sf)))
  13083. (defun org-calendar-select ()
  13084. "Return to `org-read-date' with the date currently selected.
  13085. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13086. (interactive)
  13087. (when (calendar-cursor-to-date)
  13088. (let* ((date (calendar-cursor-to-date))
  13089. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13090. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13091. (when (active-minibuffer-window) (exit-minibuffer))))
  13092. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13093. "Insert a date stamp for the date given by the internal TIME.
  13094. See `format-time-string' for the format of TIME.
  13095. WITH-HM means use the stamp format that includes the time of the day.
  13096. INACTIVE means use square brackets instead of angular ones, so that the
  13097. stamp will not contribute to the agenda.
  13098. PRE and POST are optional strings to be inserted before and after the
  13099. stamp.
  13100. The command returns the inserted time stamp."
  13101. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13102. stamp)
  13103. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13104. (insert-before-markers (or pre ""))
  13105. (when (listp extra)
  13106. (setq extra (car extra))
  13107. (if (and (stringp extra)
  13108. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13109. (setq extra (format "-%02d:%02d"
  13110. (string-to-number (match-string 1 extra))
  13111. (string-to-number (match-string 2 extra))))
  13112. (setq extra nil)))
  13113. (when extra
  13114. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13115. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13116. (insert-before-markers (or post ""))
  13117. (setq org-last-inserted-timestamp stamp)))
  13118. (defun org-toggle-time-stamp-overlays ()
  13119. "Toggle the use of custom time stamp formats."
  13120. (interactive)
  13121. (setq org-display-custom-times (not org-display-custom-times))
  13122. (unless org-display-custom-times
  13123. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13124. (while (setq p (next-single-property-change p 'display))
  13125. (when (and (get-text-property p 'display)
  13126. (eq (get-text-property p 'face) 'org-date))
  13127. (remove-text-properties
  13128. p (setq p (next-single-property-change p 'display))
  13129. '(display t))))
  13130. (set-buffer-modified-p bmp)))
  13131. (org-restart-font-lock)
  13132. (setq org-table-may-need-update t)
  13133. (if org-display-custom-times
  13134. (message "Time stamps are overlaid with custom format")
  13135. (message "Time stamp overlays removed")))
  13136. (defun org-display-custom-time (beg end)
  13137. "Overlay modified time stamp format over timestamp between BEG and END."
  13138. (let* ((ts (buffer-substring beg end))
  13139. t1 with-hm tf time str (off 0))
  13140. (save-match-data
  13141. (setq t1 (org-parse-time-string ts t))
  13142. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13143. (setq off (- (match-end 0) (match-beginning 0)))))
  13144. (setq end (- end off))
  13145. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13146. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13147. time (org-fix-decoded-time t1)
  13148. str (org-add-props
  13149. (format-time-string
  13150. (substring tf 1 -1) (apply 'encode-time time))
  13151. nil 'mouse-face 'highlight))
  13152. (put-text-property beg end 'display str)))
  13153. (defun org-fix-decoded-time (time)
  13154. "Set 0 instead of nil for the first 6 elements of time.
  13155. Don't touch the rest."
  13156. (let ((n 0))
  13157. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13158. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13159. "Difference between TIMESTAMP-STRING and now in days.
  13160. If SECONDS is non-nil, return the difference in seconds."
  13161. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13162. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13163. (funcall fdiff nil))))
  13164. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13165. "Is the time in TIMESTAMP-STRING close to the current date?"
  13166. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13167. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13168. (not (org-entry-is-done-p))))
  13169. (defun org-get-wdays (ts &optional delay zero-delay)
  13170. "Get the deadline lead time appropriate for timestring TS.
  13171. When DELAY is non-nil, get the delay time for scheduled items
  13172. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13173. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13174. don't try to find the delay cookie in the scheduled timestamp."
  13175. (let ((tv (if delay org-scheduled-delay-days
  13176. org-deadline-warning-days)))
  13177. (cond
  13178. ((or (and delay (< tv 0))
  13179. (and delay zero-delay (<= tv 0))
  13180. (and (not delay) (<= tv 0)))
  13181. ;; Enforce this value no matter what
  13182. (- tv))
  13183. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13184. ;; lead time is specified.
  13185. (floor (* (string-to-number (match-string 1 ts))
  13186. (cdr (assoc (match-string 2 ts)
  13187. '(("d" . 1) ("w" . 7)
  13188. ("m" . 30.4) ("y" . 365.25)
  13189. ("h" . 0.041667)))))))
  13190. ;; go for the default.
  13191. (t tv))))
  13192. (defun org-calendar-select-mouse (ev)
  13193. "Return to `org-read-date' with the date currently selected.
  13194. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13195. (interactive "e")
  13196. (mouse-set-point ev)
  13197. (when (calendar-cursor-to-date)
  13198. (let* ((date (calendar-cursor-to-date))
  13199. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13200. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13201. (when (active-minibuffer-window) (exit-minibuffer))))
  13202. (defun org-check-deadlines (ndays)
  13203. "Check if there are any deadlines due or past due.
  13204. A deadline is considered due if it happens within `org-deadline-warning-days'
  13205. days from today's date. If the deadline appears in an entry marked DONE,
  13206. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13207. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13208. are shown."
  13209. (interactive "P")
  13210. (let* ((org-warn-days
  13211. (cond
  13212. ((equal ndays '(4)) 100000)
  13213. (ndays (prefix-numeric-value ndays))
  13214. (t (abs org-deadline-warning-days))))
  13215. (case-fold-search nil)
  13216. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13217. (callback
  13218. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13219. (message "%d deadlines past-due or due within %d days"
  13220. (org-occur regexp nil callback)
  13221. org-warn-days)))
  13222. (defsubst org-re-timestamp (type)
  13223. "Return a regexp for timestamp TYPE.
  13224. Allowed values for TYPE are:
  13225. all: all timestamps
  13226. active: only active timestamps (<...>)
  13227. inactive: only inactive timestamps ([...])
  13228. scheduled: only scheduled timestamps
  13229. deadline: only deadline timestamps
  13230. closed: only closed time-stamps
  13231. When TYPE is nil, fall back on returning a regexp that matches
  13232. both scheduled and deadline timestamps."
  13233. (cl-case type
  13234. (all org-ts-regexp-both)
  13235. (active org-ts-regexp)
  13236. (inactive org-ts-regexp-inactive)
  13237. (scheduled org-scheduled-time-regexp)
  13238. (deadline org-deadline-time-regexp)
  13239. (closed org-closed-time-regexp)
  13240. (otherwise
  13241. (concat "\\<"
  13242. (regexp-opt (list org-deadline-string org-scheduled-string))
  13243. " *<\\([^>]+\\)>"))))
  13244. (defun org-check-before-date (d)
  13245. "Check if there are deadlines or scheduled entries before date D."
  13246. (interactive (list (org-read-date)))
  13247. (let* ((case-fold-search nil)
  13248. (regexp (org-re-timestamp org-ts-type))
  13249. (ts-type org-ts-type)
  13250. (callback
  13251. (lambda ()
  13252. (let ((match (match-string 1)))
  13253. (and (if (memq ts-type '(active inactive all))
  13254. (eq (org-element-type (save-excursion
  13255. (backward-char)
  13256. (org-element-context)))
  13257. 'timestamp)
  13258. (org-at-planning-p))
  13259. (time-less-p
  13260. (org-time-string-to-time match)
  13261. (org-time-string-to-time d)))))))
  13262. (message "%d entries before %s"
  13263. (org-occur regexp nil callback)
  13264. d)))
  13265. (defun org-check-after-date (d)
  13266. "Check if there are deadlines or scheduled entries after date D."
  13267. (interactive (list (org-read-date)))
  13268. (let* ((case-fold-search nil)
  13269. (regexp (org-re-timestamp org-ts-type))
  13270. (ts-type org-ts-type)
  13271. (callback
  13272. (lambda ()
  13273. (let ((match (match-string 1)))
  13274. (and (if (memq ts-type '(active inactive all))
  13275. (eq (org-element-type (save-excursion
  13276. (backward-char)
  13277. (org-element-context)))
  13278. 'timestamp)
  13279. (org-at-planning-p))
  13280. (not (time-less-p
  13281. (org-time-string-to-time match)
  13282. (org-time-string-to-time d))))))))
  13283. (message "%d entries after %s"
  13284. (org-occur regexp nil callback)
  13285. d)))
  13286. (defun org-check-dates-range (start-date end-date)
  13287. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13288. (interactive (list (org-read-date nil nil nil "Range starts")
  13289. (org-read-date nil nil nil "Range end")))
  13290. (let ((case-fold-search nil)
  13291. (regexp (org-re-timestamp org-ts-type))
  13292. (callback
  13293. (let ((type org-ts-type))
  13294. (lambda ()
  13295. (let ((match (match-string 1)))
  13296. (and
  13297. (if (memq type '(active inactive all))
  13298. (eq (org-element-type (save-excursion
  13299. (backward-char)
  13300. (org-element-context)))
  13301. 'timestamp)
  13302. (org-at-planning-p))
  13303. (not (time-less-p
  13304. (org-time-string-to-time match)
  13305. (org-time-string-to-time start-date)))
  13306. (time-less-p
  13307. (org-time-string-to-time match)
  13308. (org-time-string-to-time end-date))))))))
  13309. (message "%d entries between %s and %s"
  13310. (org-occur regexp nil callback) start-date end-date)))
  13311. (defun org-evaluate-time-range (&optional to-buffer)
  13312. "Evaluate a time range by computing the difference between start and end.
  13313. Normally the result is just printed in the echo area, but with prefix arg
  13314. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13315. If the time range is actually in a table, the result is inserted into the
  13316. next column.
  13317. For time difference computation, a year is assumed to be exactly 365
  13318. days in order to avoid rounding problems."
  13319. (interactive "P")
  13320. (or
  13321. (org-clock-update-time-maybe)
  13322. (save-excursion
  13323. (unless (org-at-date-range-p t)
  13324. (goto-char (point-at-bol))
  13325. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13326. (unless (org-at-date-range-p t)
  13327. (user-error "Not at a time-stamp range, and none found in current line")))
  13328. (let* ((ts1 (match-string 1))
  13329. (ts2 (match-string 2))
  13330. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13331. (match-end (match-end 0))
  13332. (time1 (org-time-string-to-time ts1))
  13333. (time2 (org-time-string-to-time ts2))
  13334. (diff (abs (float-time (time-subtract time2 time1))))
  13335. (negative (time-less-p time2 time1))
  13336. ;; (ys (floor (* 365 24 60 60)))
  13337. (ds (* 24 60 60))
  13338. (hs (* 60 60))
  13339. (fy "%dy %dd %02d:%02d")
  13340. (fy1 "%dy %dd")
  13341. (fd "%dd %02d:%02d")
  13342. (fd1 "%dd")
  13343. (fh "%02d:%02d")
  13344. y d h m align)
  13345. (if havetime
  13346. (setq ; y (floor diff ys) diff (mod diff ys)
  13347. y 0
  13348. d (floor diff ds) diff (mod diff ds)
  13349. h (floor diff hs) diff (mod diff hs)
  13350. m (floor diff 60))
  13351. (setq ; y (floor diff ys) diff (mod diff ys)
  13352. y 0
  13353. d (round diff ds)
  13354. h 0 m 0))
  13355. (if (not to-buffer)
  13356. (message "%s" (org-make-tdiff-string y d h m))
  13357. (if (org-at-table-p)
  13358. (progn
  13359. (goto-char match-end)
  13360. (setq align t)
  13361. (and (looking-at " *|") (goto-char (match-end 0))))
  13362. (goto-char match-end))
  13363. (when (looking-at
  13364. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13365. (replace-match ""))
  13366. (when negative (insert " -"))
  13367. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13368. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13369. (insert " " (format fh h m))))
  13370. (when align (org-table-align))
  13371. (message "Time difference inserted")))))
  13372. (defun org-make-tdiff-string (y d h m)
  13373. (let ((fmt "")
  13374. (l nil))
  13375. (when (> y 0)
  13376. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13377. (push y l))
  13378. (when (> d 0)
  13379. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13380. (push d l))
  13381. (when (> h 0)
  13382. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13383. (push h l))
  13384. (when (> m 0)
  13385. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13386. (push m l))
  13387. (apply 'format fmt (nreverse l))))
  13388. (defun org-time-string-to-time (s)
  13389. "Convert timestamp string S into internal time."
  13390. (apply #'encode-time (org-parse-time-string s)))
  13391. (defun org-time-string-to-seconds (s)
  13392. "Convert a timestamp string S into a number of seconds."
  13393. (float-time (org-time-string-to-time s)))
  13394. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13395. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13396. "Convert time stamp S to an absolute day number.
  13397. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13398. stamp, get the closest date to DAYNR. If PREFER is
  13399. `past' (respectively `future') return a date past (respectively
  13400. after) or equal to DAYNR.
  13401. POS is the location of time stamp S, as a buffer position in
  13402. BUFFER.
  13403. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13404. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13405. signaled."
  13406. (cond
  13407. ((string-match "\\`%%\\((.*)\\)" s)
  13408. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13409. ;; only able to match individual dates. If it fails, raise an
  13410. ;; error.
  13411. (if (and daynr
  13412. (org-diary-sexp-entry
  13413. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13414. daynr
  13415. (signal 'org-diary-sexp-no-match (list s))))
  13416. (daynr (org-closest-date s daynr prefer))
  13417. (t (time-to-days
  13418. (condition-case errdata
  13419. (org-time-string-to-time s)
  13420. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13421. s
  13422. (if (not (and buffer pos)) ""
  13423. (format-message " at %d in buffer `%s'" pos buffer))
  13424. (cdr errdata))))))))
  13425. (defun org-days-to-iso-week (days)
  13426. "Return the ISO week number."
  13427. (require 'cal-iso)
  13428. (car (calendar-iso-from-absolute days)))
  13429. (defun org-small-year-to-year (year)
  13430. "Convert 2-digit years into 4-digit years.
  13431. YEAR is expanded into one of the 30 next years, if possible, or
  13432. into a past one. Any year larger than 99 is returned unchanged."
  13433. (if (>= year 100) year
  13434. (let* ((current (string-to-number (format-time-string "%Y")))
  13435. (century (/ current 100))
  13436. (offset (- year (% current 100))))
  13437. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13438. ((> offset -70) (+ (* century 100) year))
  13439. (t (+ (* (1+ century) 100) year))))))
  13440. (defun org-time-from-absolute (d)
  13441. "Return the time corresponding to date D.
  13442. D may be an absolute day number, or a calendar-type list (month day year)."
  13443. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13444. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13445. (defvar org-agenda-current-date)
  13446. (defun org-calendar-holiday ()
  13447. "List of holidays, for Diary display in Org mode."
  13448. (require 'holidays)
  13449. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13450. (and hl (mapconcat #'identity hl "; "))))
  13451. (defun org-diary-sexp-entry (sexp entry d)
  13452. "Process a SEXP diary ENTRY for date D."
  13453. (require 'diary-lib)
  13454. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13455. ;; dynamically.
  13456. (let* ((sexp `(let ((entry ,entry)
  13457. (date ',d))
  13458. ,(car (read-from-string sexp))))
  13459. (result (if calendar-debug-sexp (eval sexp)
  13460. (condition-case nil
  13461. (eval sexp)
  13462. (error
  13463. (beep)
  13464. (message "Bad sexp at line %d in %s: %s"
  13465. (org-current-line)
  13466. (buffer-file-name) sexp)
  13467. (sleep-for 2))))))
  13468. (cond ((stringp result) (split-string result "; "))
  13469. ((and (consp result)
  13470. (not (consp (cdr result)))
  13471. (stringp (cdr result))) (cdr result))
  13472. ((and (consp result)
  13473. (stringp (car result))) result)
  13474. (result entry))))
  13475. (defun org-diary-to-ical-string (frombuf)
  13476. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13477. This uses the icalendar.el library."
  13478. (let* ((tmpdir temporary-file-directory)
  13479. (tmpfile (make-temp-name
  13480. (expand-file-name "orgics" tmpdir)))
  13481. buf rtn b e)
  13482. (with-current-buffer frombuf
  13483. (icalendar-export-region (point-min) (point-max) tmpfile)
  13484. (setq buf (find-buffer-visiting tmpfile))
  13485. (set-buffer buf)
  13486. (goto-char (point-min))
  13487. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13488. (setq b (match-beginning 0)))
  13489. (goto-char (point-max))
  13490. (when (re-search-backward "^END:VEVENT" nil t)
  13491. (setq e (match-end 0)))
  13492. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13493. (kill-buffer buf)
  13494. (delete-file tmpfile)
  13495. rtn))
  13496. (defun org-closest-date (start current prefer)
  13497. "Return closest date to CURRENT starting from START.
  13498. CURRENT and START are both time stamps.
  13499. When PREFER is `past', return a date that is either CURRENT or
  13500. past. When PREFER is `future', return a date that is either
  13501. CURRENT or future.
  13502. Only time stamps with a repeater are modified. Any other time
  13503. stamp stay unchanged. In any case, return value is an absolute
  13504. day number."
  13505. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13506. ;; No repeater. Do not shift time stamp.
  13507. (time-to-days (org-time-string-to-time start))
  13508. (let ((value (string-to-number (match-string 1 start)))
  13509. (type (match-string 2 start)))
  13510. (if (= 0 value)
  13511. ;; Repeater with a 0-value is considered as void.
  13512. (time-to-days (org-time-string-to-time start))
  13513. (let* ((base (org-date-to-gregorian start))
  13514. (target (org-date-to-gregorian current))
  13515. (sday (calendar-absolute-from-gregorian base))
  13516. (cday (calendar-absolute-from-gregorian target))
  13517. n1 n2)
  13518. ;; If START is already past CURRENT, just return START.
  13519. (if (<= cday sday) sday
  13520. ;; Compute closest date before (N1) and closest date past
  13521. ;; (N2) CURRENT.
  13522. (pcase type
  13523. ("h"
  13524. (let ((missing-hours
  13525. (mod (+ (- (* 24 (- cday sday))
  13526. (nth 2 (org-parse-time-string start)))
  13527. org-extend-today-until)
  13528. value)))
  13529. (setf n1 (if (= missing-hours 0) cday
  13530. (- cday (1+ (/ missing-hours 24)))))
  13531. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13532. ((or "d" "w")
  13533. (let ((value (if (equal type "w") (* 7 value) value)))
  13534. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13535. (setf n2 (+ n1 value))))
  13536. ("m"
  13537. (let* ((add-months
  13538. (lambda (d n)
  13539. ;; Add N months to gregorian date D, i.e.,
  13540. ;; a list (MONTH DAY YEAR). Return a valid
  13541. ;; gregorian date.
  13542. (let ((m (+ (nth 0 d) n)))
  13543. (list (mod m 12)
  13544. (nth 1 d)
  13545. (+ (/ m 12) (nth 2 d))))))
  13546. (months ; Complete months to TARGET.
  13547. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13548. (- (nth 0 target) (nth 0 base))
  13549. ;; If START's day is greater than
  13550. ;; TARGET's, remove incomplete month.
  13551. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13552. value)
  13553. value))
  13554. (before (funcall add-months base months)))
  13555. (setf n1 (calendar-absolute-from-gregorian before))
  13556. (setf n2
  13557. (calendar-absolute-from-gregorian
  13558. (funcall add-months before value)))))
  13559. (_
  13560. (let* ((d (nth 1 base))
  13561. (m (nth 0 base))
  13562. (y (nth 2 base))
  13563. (years ; Complete years to TARGET.
  13564. (* (/ (- (nth 2 target)
  13565. y
  13566. ;; If START's month and day are
  13567. ;; greater than TARGET's, remove
  13568. ;; incomplete year.
  13569. (if (or (> (nth 0 target) m)
  13570. (and (= (nth 0 target) m)
  13571. (> (nth 1 target) d)))
  13572. 0
  13573. 1))
  13574. value)
  13575. value))
  13576. (before (list m d (+ y years))))
  13577. (setf n1 (calendar-absolute-from-gregorian before))
  13578. (setf n2 (calendar-absolute-from-gregorian
  13579. (list m d (+ (nth 2 before) value)))))))
  13580. ;; Handle PREFER parameter, if any.
  13581. (cond
  13582. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13583. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13584. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13585. (defun org-date-to-gregorian (d)
  13586. "Turn any specification of date D into a Gregorian date for the calendar."
  13587. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13588. ((and (listp d) (= (length d) 3)) d)
  13589. ((stringp d)
  13590. (let ((d (org-parse-time-string d)))
  13591. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13592. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13593. (defun org-timestamp-up (&optional arg)
  13594. "Increase the date item at the cursor by one.
  13595. If the cursor is on the year, change the year. If it is on the month,
  13596. the day or the time, change that. If the cursor is on the enclosing
  13597. bracket, change the timestamp type.
  13598. With prefix ARG, change by that many units."
  13599. (interactive "p")
  13600. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13601. (defun org-timestamp-down (&optional arg)
  13602. "Decrease the date item at the cursor by one.
  13603. If the cursor is on the year, change the year. If it is on the month,
  13604. the day or the time, change that. If the cursor is on the enclosing
  13605. bracket, change the timestamp type.
  13606. With prefix ARG, change by that many units."
  13607. (interactive "p")
  13608. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13609. (defun org-timestamp-up-day (&optional arg)
  13610. "Increase the date in the time stamp by one day.
  13611. With prefix ARG, change that many days."
  13612. (interactive "p")
  13613. (if (and (not (org-at-timestamp-p 'lax))
  13614. (org-at-heading-p))
  13615. (org-todo 'up)
  13616. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13617. (defun org-timestamp-down-day (&optional arg)
  13618. "Decrease the date in the time stamp by one day.
  13619. With prefix ARG, change that many days."
  13620. (interactive "p")
  13621. (if (and (not (org-at-timestamp-p 'lax))
  13622. (org-at-heading-p))
  13623. (org-todo 'down)
  13624. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13625. (defun org-at-timestamp-p (&optional extended)
  13626. "Non-nil if point is inside a timestamp.
  13627. By default, the function only consider syntactically valid active
  13628. timestamps. However, the caller may have a broader definition
  13629. for timestamps. As a consequence, optional argument EXTENDED can
  13630. be set to the following values
  13631. `inactive'
  13632. Include also syntactically valid inactive timestamps.
  13633. `agenda'
  13634. Include timestamps allowed in Agenda, i.e., those in
  13635. properties drawers, planning lines and clock lines.
  13636. `lax'
  13637. Ignore context. The function matches any part of the
  13638. document looking like a timestamp. This includes comments,
  13639. example blocks...
  13640. For backward-compatibility with Org 9.0, every other non-nil
  13641. value is equivalent to `inactive'.
  13642. When at a timestamp, return the position of the point as a symbol
  13643. among `bracket', `after', `year', `month', `hour', `minute',
  13644. `day' or a number of character from the last know part of the
  13645. time stamp.
  13646. When matching, the match groups are the following:
  13647. group 1: year
  13648. group 2: month
  13649. group 3: day number
  13650. group 4: day name
  13651. group 5: hours, if any
  13652. group 6: minutes, if any"
  13653. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13654. (pos (point))
  13655. (match?
  13656. (let ((boundaries (org-in-regexp regexp)))
  13657. (save-match-data
  13658. (cond ((null boundaries) nil)
  13659. ((eq extended 'lax) t)
  13660. (t
  13661. (or (and (eq extended 'agenda)
  13662. (or (org-at-planning-p)
  13663. (org-at-property-p)
  13664. (and (bound-and-true-p
  13665. org-agenda-include-inactive-timestamps)
  13666. (org-at-clock-log-p))))
  13667. (eq 'timestamp
  13668. (save-excursion
  13669. (when (= pos (cdr boundaries)) (forward-char -1))
  13670. (org-element-type (org-element-context)))))))))))
  13671. (cond
  13672. ((not match?) nil)
  13673. ((= pos (match-beginning 0)) 'bracket)
  13674. ;; Distinguish location right before the closing bracket from
  13675. ;; right after it.
  13676. ((= pos (1- (match-end 0))) 'bracket)
  13677. ((= pos (match-end 0)) 'after)
  13678. ((org-pos-in-match-range pos 2) 'year)
  13679. ((org-pos-in-match-range pos 3) 'month)
  13680. ((org-pos-in-match-range pos 7) 'hour)
  13681. ((org-pos-in-match-range pos 8) 'minute)
  13682. ((or (org-pos-in-match-range pos 4)
  13683. (org-pos-in-match-range pos 5)) 'day)
  13684. ((and (> pos (or (match-end 8) (match-end 5)))
  13685. (< pos (match-end 0)))
  13686. (- pos (or (match-end 8) (match-end 5))))
  13687. (t 'day))))
  13688. (defun org-toggle-timestamp-type ()
  13689. "Toggle the type (<active> or [inactive]) of a time stamp."
  13690. (interactive)
  13691. (when (org-at-timestamp-p 'lax)
  13692. (let ((beg (match-beginning 0)) (end (match-end 0))
  13693. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13694. (save-excursion
  13695. (goto-char beg)
  13696. (while (re-search-forward "[][<>]" end t)
  13697. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13698. t t)))
  13699. (message "Timestamp is now %sactive"
  13700. (if (equal (char-after beg) ?<) "" "in")))))
  13701. (defun org-at-clock-log-p ()
  13702. "Non-nil if point is on a clock log line."
  13703. (and (org-match-line org-clock-line-re)
  13704. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13705. (defvar org-clock-history) ; defined in org-clock.el
  13706. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13707. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13708. "Change the date in the time stamp at point.
  13709. The date is changed by N times WHAT. WHAT can be `day', `month',
  13710. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13711. position in the timestamp determines what is changed.
  13712. When optional argument UPDOWN is non-nil, minutes are rounded
  13713. according to `org-time-stamp-rounding-minutes'.
  13714. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13715. \"--2d\"."
  13716. (let ((origin (point))
  13717. (timestamp? (org-at-timestamp-p 'lax))
  13718. origin-cat
  13719. with-hm inactive
  13720. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13721. extra rem
  13722. ts time time0 fixnext clrgx)
  13723. (unless timestamp? (user-error "Not at a timestamp"))
  13724. (if (and (not what) (eq timestamp? 'bracket))
  13725. (org-toggle-timestamp-type)
  13726. ;; Point isn't on brackets. Remember the part of the time-stamp
  13727. ;; the point was in. Indeed, size of time-stamps may change,
  13728. ;; but point must be kept in the same category nonetheless.
  13729. (setq origin-cat timestamp?)
  13730. (when (and (not what) (not (eq timestamp? 'day))
  13731. org-display-custom-times
  13732. (get-text-property (point) 'display)
  13733. (not (get-text-property (1- (point)) 'display)))
  13734. (setq timestamp? 'day))
  13735. (setq timestamp? (or what timestamp?)
  13736. inactive (= (char-after (match-beginning 0)) ?\[)
  13737. ts (match-string 0))
  13738. (replace-match "")
  13739. (when (string-match
  13740. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13741. ts)
  13742. (setq extra (match-string 1 ts))
  13743. (when suppress-tmp-delay
  13744. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13745. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13746. (setq with-hm t))
  13747. (setq time0 (org-parse-time-string ts))
  13748. (when (and updown
  13749. (eq timestamp? 'minute)
  13750. (not current-prefix-arg))
  13751. ;; This looks like s-up and s-down. Change by one rounding step.
  13752. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13753. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13754. (setcar (cdr time0) (+ (nth 1 time0)
  13755. (if (> n 0) (- rem) (- dm rem))))))
  13756. (setq time
  13757. (apply #'encode-time
  13758. (or (car time0) 0)
  13759. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13760. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13761. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13762. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13763. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13764. (nthcdr 6 time0)))
  13765. (when (and (memq timestamp? '(hour minute))
  13766. extra
  13767. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13768. (setq extra (org-modify-ts-extra
  13769. extra
  13770. (if (eq timestamp? 'hour) 2 5)
  13771. n dm)))
  13772. (when (integerp timestamp?)
  13773. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13774. (when (eq what 'calendar)
  13775. (let ((cal-date (org-get-date-from-calendar)))
  13776. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13777. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13778. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13779. (setcar time0 (or (car time0) 0))
  13780. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13781. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13782. (setq time (apply 'encode-time time0))))
  13783. ;; Insert the new time-stamp, and ensure point stays in the same
  13784. ;; category as before (i.e. not after the last position in that
  13785. ;; category).
  13786. (let ((pos (point)))
  13787. ;; Stay before inserted string. `save-excursion' is of no use.
  13788. (setq org-last-changed-timestamp
  13789. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13790. (goto-char pos))
  13791. (save-match-data
  13792. (looking-at org-ts-regexp3)
  13793. (goto-char
  13794. (pcase origin-cat
  13795. ;; `day' category ends before `hour' if any, or at the end
  13796. ;; of the day name.
  13797. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13798. (`hour (min (match-end 7) origin))
  13799. (`minute (min (1- (match-end 8)) origin))
  13800. ((pred integerp) (min (1- (match-end 0)) origin))
  13801. ;; Point was right after the time-stamp. However, the
  13802. ;; time-stamp length might have changed, so refer to
  13803. ;; (match-end 0) instead.
  13804. (`after (match-end 0))
  13805. ;; `year' and `month' have both fixed size: point couldn't
  13806. ;; have moved into another part.
  13807. (_ origin))))
  13808. ;; Update clock if on a CLOCK line.
  13809. (org-clock-update-time-maybe)
  13810. ;; Maybe adjust the closest clock in `org-clock-history'
  13811. (when org-clock-adjust-closest
  13812. (if (not (and (org-at-clock-log-p)
  13813. (< 1 (length (delq nil (mapcar 'marker-position
  13814. org-clock-history))))))
  13815. (message "No clock to adjust")
  13816. (cond ((save-excursion ; fix previous clock?
  13817. (re-search-backward org-ts-regexp0 nil t)
  13818. (looking-back (concat org-clock-string " \\[")
  13819. (line-beginning-position)))
  13820. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13821. ((save-excursion ; fix next clock?
  13822. (re-search-backward org-ts-regexp0 nil t)
  13823. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13824. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13825. (save-window-excursion
  13826. ;; Find closest clock to point, adjust the previous/next one in history
  13827. (let* ((p (save-excursion (org-back-to-heading t)))
  13828. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13829. (clfixnth
  13830. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13831. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13832. (if (not clfixpos)
  13833. (message "No clock to adjust")
  13834. (save-excursion
  13835. (org-goto-marker-or-bmk clfixpos)
  13836. (org-show-subtree)
  13837. (when (re-search-forward clrgx nil t)
  13838. (goto-char (match-beginning 1))
  13839. (let (org-clock-adjust-closest)
  13840. (org-timestamp-change n timestamp? updown))
  13841. (message "Clock adjusted in %s for heading: %s"
  13842. (file-name-nondirectory (buffer-file-name))
  13843. (org-get-heading t t)))))))))
  13844. ;; Try to recenter the calendar window, if any.
  13845. (when (and org-calendar-follow-timestamp-change
  13846. (get-buffer-window "*Calendar*" t)
  13847. (memq timestamp? '(day month year)))
  13848. (org-recenter-calendar (time-to-days time))))))
  13849. (defun org-modify-ts-extra (s pos n dm)
  13850. "Change the different parts of the lead-time and repeat fields in timestamp."
  13851. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13852. ng h m new rem)
  13853. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13854. (cond
  13855. ((or (org-pos-in-match-range pos 2)
  13856. (org-pos-in-match-range pos 3))
  13857. (setq m (string-to-number (match-string 3 s))
  13858. h (string-to-number (match-string 2 s)))
  13859. (if (org-pos-in-match-range pos 2)
  13860. (setq h (+ h n))
  13861. (setq n (* dm (with-no-warnings (cl-signum n))))
  13862. (unless (= 0 (setq rem (% m dm)))
  13863. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13864. (setq m (+ m n)))
  13865. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13866. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13867. (setq h (mod h 24))
  13868. (setq ng 1 new (format "-%02d:%02d" h m)))
  13869. ((org-pos-in-match-range pos 6)
  13870. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13871. ((org-pos-in-match-range pos 5)
  13872. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13873. ((org-pos-in-match-range pos 9)
  13874. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13875. ((org-pos-in-match-range pos 8)
  13876. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13877. (when ng
  13878. (setq s (concat
  13879. (substring s 0 (match-beginning ng))
  13880. new
  13881. (substring s (match-end ng))))))
  13882. s))
  13883. (defun org-recenter-calendar (d)
  13884. "If the calendar is visible, recenter it to date D."
  13885. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13886. (when cwin
  13887. (let ((calendar-move-hook nil))
  13888. (with-selected-window cwin
  13889. (calendar-goto-date
  13890. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13891. (defun org-goto-calendar (&optional arg)
  13892. "Go to the Emacs calendar at the current date.
  13893. If there is a time stamp in the current line, go to that date.
  13894. A prefix ARG can be used to force the current date."
  13895. (interactive "P")
  13896. (let ((calendar-move-hook nil)
  13897. (calendar-view-holidays-initially-flag nil)
  13898. (calendar-view-diary-initially-flag nil)
  13899. diff)
  13900. (when (or (org-at-timestamp-p 'lax)
  13901. (org-match-line (concat ".*" org-ts-regexp)))
  13902. (let ((d1 (time-to-days nil))
  13903. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13904. (setq diff (- d2 d1))))
  13905. (calendar)
  13906. (calendar-goto-today)
  13907. (when (and diff (not arg)) (calendar-forward-day diff))))
  13908. (defun org-get-date-from-calendar ()
  13909. "Return a list (month day year) of date at point in calendar."
  13910. (with-current-buffer "*Calendar*"
  13911. (save-match-data
  13912. (calendar-cursor-to-date))))
  13913. (defun org-date-from-calendar ()
  13914. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13915. If there is already a time stamp at the cursor position, update it."
  13916. (interactive)
  13917. (if (org-at-timestamp-p 'lax)
  13918. (org-timestamp-change 0 'calendar)
  13919. (let ((cal-date (org-get-date-from-calendar)))
  13920. (org-insert-time-stamp
  13921. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13922. (defcustom org-image-actual-width t
  13923. "When non-nil, use the actual width of images when inlining them.
  13924. When set to a number, use imagemagick (when available) to set the
  13925. image's width to this value.
  13926. When set to a number in a list, try to get the width from any
  13927. #+ATTR.* keyword if it matches a width specification like
  13928. #+ATTR_HTML: :width 300px
  13929. and fall back on that number if none is found.
  13930. When set to nil, try to get the width from an #+ATTR.* keyword
  13931. and fall back on the original width if none is found.
  13932. When set to any other non-nil value, always use the image width.
  13933. This requires Emacs >= 24.1, built with imagemagick support."
  13934. :group 'org-appearance
  13935. :version "24.4"
  13936. :package-version '(Org . "8.0")
  13937. :type '(choice
  13938. (const :tag "Use the image width" t)
  13939. (integer :tag "Use a number of pixels")
  13940. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13941. (const :tag "Use #+ATTR* or don't resize" nil)))
  13942. (defcustom org-agenda-inhibit-startup nil
  13943. "Inhibit startup when preparing agenda buffers.
  13944. When this variable is t, the initialization of the Org agenda
  13945. buffers is inhibited: e.g. the visibility state is not set, the
  13946. tables are not re-aligned, etc."
  13947. :type 'boolean
  13948. :version "24.3"
  13949. :group 'org-agenda)
  13950. (defcustom org-agenda-ignore-properties nil
  13951. "Avoid updating text properties when building the agenda.
  13952. Properties are used to prepare buffers for effort estimates,
  13953. appointments, statistics and subtree-local categories.
  13954. If you don't use these in the agenda, you can add them to this
  13955. list and agenda building will be a bit faster.
  13956. The value is a list, with zero or more of the symbols `effort', `appt',
  13957. `stats' or `category'."
  13958. :type '(set :greedy t
  13959. (const effort)
  13960. (const appt)
  13961. (const stats)
  13962. (const category))
  13963. :version "26.1"
  13964. :package-version '(Org . "8.3")
  13965. :group 'org-agenda)
  13966. ;;;; Files
  13967. (defun org-save-all-org-buffers ()
  13968. "Save all Org buffers without user confirmation."
  13969. (interactive)
  13970. (message "Saving all Org buffers...")
  13971. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13972. (when (featurep 'org-id) (org-id-locations-save))
  13973. (message "Saving all Org buffers... done"))
  13974. (defun org-revert-all-org-buffers ()
  13975. "Revert all Org buffers.
  13976. Prompt for confirmation when there are unsaved changes.
  13977. Be sure you know what you are doing before letting this function
  13978. overwrite your changes.
  13979. This function is useful in a setup where one tracks Org files
  13980. with a version control system, to revert on one machine after pulling
  13981. changes from another. I believe the procedure must be like this:
  13982. 1. M-x org-save-all-org-buffers
  13983. 2. Pull changes from the other machine, resolve conflicts
  13984. 3. M-x org-revert-all-org-buffers"
  13985. (interactive)
  13986. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13987. (user-error "Abort"))
  13988. (save-excursion
  13989. (save-window-excursion
  13990. (dolist (b (buffer-list))
  13991. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13992. (with-current-buffer b buffer-file-name))
  13993. (pop-to-buffer-same-window b)
  13994. (revert-buffer t 'no-confirm)))
  13995. (when (and (featurep 'org-id) org-id-track-globally)
  13996. (org-id-locations-load)))))
  13997. ;;;; Agenda files
  13998. ;;;###autoload
  13999. (defun org-switchb (&optional arg)
  14000. "Switch between Org buffers.
  14001. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14002. With `\\[universal-argument] \\[universal-argument]' \
  14003. prefix, restrict available buffers to agenda files."
  14004. (interactive "P")
  14005. (let ((blist (org-buffer-list
  14006. (cond ((equal arg '(4)) 'files)
  14007. ((equal arg '(16)) 'agenda)))))
  14008. (pop-to-buffer-same-window
  14009. (completing-read "Org buffer: "
  14010. (mapcar #'list (mapcar #'buffer-name blist))
  14011. nil t))))
  14012. (defun org-buffer-list (&optional predicate exclude-tmp)
  14013. "Return a list of Org buffers.
  14014. PREDICATE can be `export', `files' or `agenda'.
  14015. export restrict the list to Export buffers.
  14016. files restrict the list to buffers visiting Org files.
  14017. agenda restrict the list to buffers visiting agenda files.
  14018. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14019. (let* ((bfn nil)
  14020. (agenda-files (and (eq predicate 'agenda)
  14021. (mapcar 'file-truename (org-agenda-files t))))
  14022. (filter
  14023. (cond
  14024. ((eq predicate 'files)
  14025. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14026. ((eq predicate 'export)
  14027. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14028. ((eq predicate 'agenda)
  14029. (lambda (b)
  14030. (with-current-buffer b
  14031. (and (derived-mode-p 'org-mode)
  14032. (setq bfn (buffer-file-name b))
  14033. (member (file-truename bfn) agenda-files)))))
  14034. (t (lambda (b) (with-current-buffer b
  14035. (or (derived-mode-p 'org-mode)
  14036. (string-match "\\*Org .*Export"
  14037. (buffer-name b)))))))))
  14038. (delq nil
  14039. (mapcar
  14040. (lambda(b)
  14041. (if (and (funcall filter b)
  14042. (or (not exclude-tmp)
  14043. (not (string-match "tmp" (buffer-name b)))))
  14044. b
  14045. nil))
  14046. (buffer-list)))))
  14047. (defun org-agenda-files (&optional unrestricted archives)
  14048. "Get the list of agenda files.
  14049. Optional UNRESTRICTED means return the full list even if a restriction
  14050. is currently in place.
  14051. When ARCHIVES is t, include all archive files that are really being
  14052. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14053. `org-agenda-archives-mode' is t."
  14054. (let ((files
  14055. (cond
  14056. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14057. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14058. ((listp org-agenda-files) org-agenda-files)
  14059. (t (error "Invalid value of `org-agenda-files'")))))
  14060. (setq files (apply 'append
  14061. (mapcar (lambda (f)
  14062. (if (file-directory-p f)
  14063. (directory-files
  14064. f t org-agenda-file-regexp)
  14065. (list f)))
  14066. files)))
  14067. (when org-agenda-skip-unavailable-files
  14068. (setq files (delq nil
  14069. (mapcar (lambda (file)
  14070. (and (file-readable-p file) file))
  14071. files))))
  14072. (when (or (eq archives t)
  14073. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14074. (setq files (org-add-archive-files files)))
  14075. files))
  14076. (defun org-agenda-file-p (&optional file)
  14077. "Return non-nil, if FILE is an agenda file.
  14078. If FILE is omitted, use the file associated with the current
  14079. buffer."
  14080. (let ((fname (or file (buffer-file-name))))
  14081. (and fname
  14082. (member (file-truename fname)
  14083. (mapcar #'file-truename (org-agenda-files t))))))
  14084. (defun org-edit-agenda-file-list ()
  14085. "Edit the list of agenda files.
  14086. Depending on setup, this either uses customize to edit the variable
  14087. `org-agenda-files', or it visits the file that is holding the list. In the
  14088. latter case, the buffer is set up in a way that saving it automatically kills
  14089. the buffer and restores the previous window configuration."
  14090. (interactive)
  14091. (if (stringp org-agenda-files)
  14092. (let ((cw (current-window-configuration)))
  14093. (find-file org-agenda-files)
  14094. (setq-local org-window-configuration cw)
  14095. (add-hook 'after-save-hook
  14096. (lambda ()
  14097. (set-window-configuration
  14098. (prog1 org-window-configuration
  14099. (kill-buffer (current-buffer))))
  14100. (org-install-agenda-files-menu)
  14101. (message "New agenda file list installed"))
  14102. nil 'local)
  14103. (message "%s" (substitute-command-keys
  14104. "Edit list and finish with \\[save-buffer]")))
  14105. (customize-variable 'org-agenda-files)))
  14106. (defun org-store-new-agenda-file-list (list)
  14107. "Set new value for the agenda file list and save it correctly."
  14108. (if (stringp org-agenda-files)
  14109. (let ((fe (org-read-agenda-file-list t)) b u)
  14110. (while (setq b (find-buffer-visiting org-agenda-files))
  14111. (kill-buffer b))
  14112. (with-temp-file org-agenda-files
  14113. (insert
  14114. (mapconcat
  14115. (lambda (f) ;; Keep un-expanded entries.
  14116. (if (setq u (assoc f fe))
  14117. (cdr u)
  14118. f))
  14119. list "\n")
  14120. "\n")))
  14121. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14122. (org-insert-mode-line-in-empty-file nil))
  14123. (setq org-agenda-files list)
  14124. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14125. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14126. "Read the list of agenda files from a file.
  14127. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14128. filenames, used by `org-store-new-agenda-file-list' to write back
  14129. un-expanded file names."
  14130. (when (file-directory-p org-agenda-files)
  14131. (error "`org-agenda-files' cannot be a single directory"))
  14132. (when (stringp org-agenda-files)
  14133. (with-temp-buffer
  14134. (insert-file-contents org-agenda-files)
  14135. (mapcar
  14136. (lambda (f)
  14137. (let ((e (expand-file-name (substitute-in-file-name f)
  14138. org-directory)))
  14139. (if pair-with-expansion
  14140. (cons e f)
  14141. e)))
  14142. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14143. ;;;###autoload
  14144. (defun org-cycle-agenda-files ()
  14145. "Cycle through the files in `org-agenda-files'.
  14146. If the current buffer visits an agenda file, find the next one in the list.
  14147. If the current buffer does not, find the first agenda file."
  14148. (interactive)
  14149. (let* ((fs (or (org-agenda-files t)
  14150. (user-error "No agenda files")))
  14151. (files (copy-sequence fs))
  14152. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14153. file)
  14154. (when tcf
  14155. (while (and (setq file (pop files))
  14156. (not (equal (file-truename file) tcf)))))
  14157. (find-file (car (or files fs)))
  14158. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14159. (defun org-agenda-file-to-front (&optional to-end)
  14160. "Move/add the current file to the top of the agenda file list.
  14161. If the file is not present in the list, it is added to the front. If it is
  14162. present, it is moved there. With optional argument TO-END, add/move to the
  14163. end of the list."
  14164. (interactive "P")
  14165. (let ((org-agenda-skip-unavailable-files nil)
  14166. (file-alist (mapcar (lambda (x)
  14167. (cons (file-truename x) x))
  14168. (org-agenda-files t)))
  14169. (ctf (file-truename
  14170. (or buffer-file-name
  14171. (user-error "Please save the current buffer to a file"))))
  14172. x had)
  14173. (setq x (assoc ctf file-alist) had x)
  14174. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14175. (if to-end
  14176. (setq file-alist (append (delq x file-alist) (list x)))
  14177. (setq file-alist (cons x (delq x file-alist))))
  14178. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14179. (org-install-agenda-files-menu)
  14180. (message "File %s to %s of agenda file list"
  14181. (if had "moved" "added") (if to-end "end" "front"))))
  14182. (defun org-remove-file (&optional file)
  14183. "Remove current file from the list of files in variable `org-agenda-files'.
  14184. These are the files which are being checked for agenda entries.
  14185. Optional argument FILE means use this file instead of the current."
  14186. (interactive)
  14187. (let* ((org-agenda-skip-unavailable-files nil)
  14188. (file (or file buffer-file-name
  14189. (user-error "Current buffer does not visit a file")))
  14190. (true-file (file-truename file))
  14191. (afile (abbreviate-file-name file))
  14192. (files (delq nil (mapcar
  14193. (lambda (x)
  14194. (unless (equal true-file
  14195. (file-truename x))
  14196. x))
  14197. (org-agenda-files t)))))
  14198. (if (not (= (length files) (length (org-agenda-files t))))
  14199. (progn
  14200. (org-store-new-agenda-file-list files)
  14201. (org-install-agenda-files-menu)
  14202. (message "Removed from Org Agenda list: %s" afile))
  14203. (message "File was not in list: %s (not removed)" afile))))
  14204. (defun org-file-menu-entry (file)
  14205. (vector file (list 'find-file file) t))
  14206. (defun org-check-agenda-file (file)
  14207. "Make sure FILE exists. If not, ask user what to do."
  14208. (unless (file-exists-p file)
  14209. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14210. (abbreviate-file-name file))
  14211. (let ((r (downcase (read-char-exclusive))))
  14212. (cond
  14213. ((equal r ?r)
  14214. (org-remove-file file)
  14215. (throw 'nextfile t))
  14216. (t (user-error "Abort"))))))
  14217. (defun org-get-agenda-file-buffer (file)
  14218. "Get an agenda buffer visiting FILE.
  14219. If the buffer needs to be created, add it to the list of buffers
  14220. which might be released later."
  14221. (let ((buf (org-find-base-buffer-visiting file)))
  14222. (if buf
  14223. buf ; just return it
  14224. ;; Make a new buffer and remember it
  14225. (setq buf (find-file-noselect file))
  14226. (when buf (push buf org-agenda-new-buffers))
  14227. buf)))
  14228. (defun org-release-buffers (blist)
  14229. "Release all buffers in list, asking the user for confirmation when needed.
  14230. When a buffer is unmodified, it is just killed. When modified, it is saved
  14231. \(if the user agrees) and then killed."
  14232. (let (file)
  14233. (dolist (buf blist)
  14234. (setq file (buffer-file-name buf))
  14235. (when (and (buffer-modified-p buf)
  14236. file
  14237. (y-or-n-p (format "Save file %s? " file)))
  14238. (with-current-buffer buf (save-buffer)))
  14239. (kill-buffer buf))))
  14240. (defun org-agenda-prepare-buffers (files)
  14241. "Create buffers for all agenda files, protect archived trees and comments."
  14242. (interactive)
  14243. (let ((pa '(:org-archived t))
  14244. (pc '(:org-comment t))
  14245. (pall '(:org-archived t :org-comment t))
  14246. (inhibit-read-only t)
  14247. (org-inhibit-startup org-agenda-inhibit-startup)
  14248. (rea (org-make-tag-string (list org-archive-tag)))
  14249. re pos)
  14250. (setq org-tag-alist-for-agenda nil
  14251. org-tag-groups-alist-for-agenda nil)
  14252. (save-excursion
  14253. (save-restriction
  14254. (dolist (file files)
  14255. (catch 'nextfile
  14256. (if (bufferp file)
  14257. (set-buffer file)
  14258. (org-check-agenda-file file)
  14259. (set-buffer (org-get-agenda-file-buffer file)))
  14260. (widen)
  14261. (org-set-regexps-and-options 'tags-only)
  14262. (setq pos (point))
  14263. (or (memq 'category org-agenda-ignore-properties)
  14264. (org-refresh-category-properties))
  14265. (or (memq 'stats org-agenda-ignore-properties)
  14266. (org-refresh-stats-properties))
  14267. (or (memq 'effort org-agenda-ignore-properties)
  14268. (org-refresh-effort-properties))
  14269. (or (memq 'appt org-agenda-ignore-properties)
  14270. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14271. (setq org-todo-keywords-for-agenda
  14272. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14273. (setq org-done-keywords-for-agenda
  14274. (append org-done-keywords-for-agenda org-done-keywords))
  14275. (setq org-todo-keyword-alist-for-agenda
  14276. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14277. (setq org-tag-alist-for-agenda
  14278. (org--tag-add-to-alist
  14279. org-tag-alist-for-agenda
  14280. org-current-tag-alist))
  14281. ;; Merge current file's tag groups into global
  14282. ;; `org-tag-groups-alist-for-agenda'.
  14283. (when org-group-tags
  14284. (dolist (alist org-tag-groups-alist)
  14285. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14286. (if old
  14287. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14288. (push alist org-tag-groups-alist-for-agenda)))))
  14289. (with-silent-modifications
  14290. (save-excursion
  14291. (remove-text-properties (point-min) (point-max) pall)
  14292. (when org-agenda-skip-archived-trees
  14293. (goto-char (point-min))
  14294. (while (re-search-forward rea nil t)
  14295. (when (org-at-heading-p t)
  14296. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14297. (goto-char (point-min))
  14298. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14299. (while (re-search-forward re nil t)
  14300. (when (save-match-data (org-in-commented-heading-p t))
  14301. (add-text-properties
  14302. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14303. (goto-char pos)))))
  14304. (setq org-todo-keywords-for-agenda
  14305. (org-uniquify org-todo-keywords-for-agenda))
  14306. (setq org-todo-keyword-alist-for-agenda
  14307. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14308. ;;;; CDLaTeX minor mode
  14309. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14310. "Keymap for the minor `org-cdlatex-mode'.")
  14311. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14312. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14313. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14314. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14315. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14316. (defvar org-cdlatex-texmathp-advice-is-done nil
  14317. "Flag remembering if we have applied the advice to texmathp already.")
  14318. (define-minor-mode org-cdlatex-mode
  14319. "Toggle the minor `org-cdlatex-mode'.
  14320. This mode supports entering LaTeX environment and math in LaTeX fragments
  14321. in Org mode.
  14322. \\{org-cdlatex-mode-map}"
  14323. :lighter " OCDL"
  14324. (when org-cdlatex-mode
  14325. (require 'cdlatex)
  14326. (run-hooks 'cdlatex-mode-hook)
  14327. (cdlatex-compute-tables))
  14328. (unless org-cdlatex-texmathp-advice-is-done
  14329. (setq org-cdlatex-texmathp-advice-is-done t)
  14330. (defadvice texmathp (around org-math-always-on activate)
  14331. "Always return t in Org buffers.
  14332. This is because we want to insert math symbols without dollars even outside
  14333. the LaTeX math segments. If Org mode thinks that point is actually inside
  14334. an embedded LaTeX fragment, let `texmathp' do its job.
  14335. `\\[org-cdlatex-mode-map]'"
  14336. (interactive)
  14337. (let (p)
  14338. (cond
  14339. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14340. ((eq this-command 'cdlatex-math-symbol)
  14341. (setq ad-return-value t
  14342. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14343. (t
  14344. (let ((p (org-inside-LaTeX-fragment-p)))
  14345. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14346. (setq ad-return-value t
  14347. texmathp-why '("Org mode embedded math" . 0))
  14348. (when p ad-do-it)))))))))
  14349. (defun turn-on-org-cdlatex ()
  14350. "Unconditionally turn on `org-cdlatex-mode'."
  14351. (org-cdlatex-mode 1))
  14352. (defun org-try-cdlatex-tab ()
  14353. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14354. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14355. - inside a LaTeX fragment, or
  14356. - after the first word in a line, where an abbreviation expansion could
  14357. insert a LaTeX environment."
  14358. (when org-cdlatex-mode
  14359. (cond
  14360. ;; Before any word on the line: No expansion possible.
  14361. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14362. ;; Just after first word on the line: Expand it. Make sure it
  14363. ;; cannot happen on headlines, though.
  14364. ((save-excursion
  14365. (skip-chars-backward "a-zA-Z0-9*")
  14366. (skip-chars-backward " \t")
  14367. (and (bolp) (not (org-at-heading-p))))
  14368. (cdlatex-tab) t)
  14369. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14370. (defun org-cdlatex-underscore-caret (&optional _arg)
  14371. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14372. Revert to the normal definition outside of these fragments."
  14373. (interactive "P")
  14374. (if (org-inside-LaTeX-fragment-p)
  14375. (call-interactively 'cdlatex-sub-superscript)
  14376. (let (org-cdlatex-mode)
  14377. (call-interactively (key-binding (vector last-input-event))))))
  14378. (defun org-cdlatex-math-modify (&optional _arg)
  14379. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14380. Revert to the normal definition outside of these fragments."
  14381. (interactive "P")
  14382. (if (org-inside-LaTeX-fragment-p)
  14383. (call-interactively 'cdlatex-math-modify)
  14384. (let (org-cdlatex-mode)
  14385. (call-interactively (key-binding (vector last-input-event))))))
  14386. (defun org-cdlatex-environment-indent (&optional environment item)
  14387. "Execute `cdlatex-environment' and indent the inserted environment.
  14388. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14389. The inserted environment is indented to current indentation
  14390. unless point is at the beginning of the line, in which the
  14391. environment remains unintended."
  14392. (interactive)
  14393. ;; cdlatex-environment always return nil. Therefore, capture output
  14394. ;; first and determine if an environment was selected.
  14395. (let* ((beg (point-marker))
  14396. (end (copy-marker (point) t))
  14397. (inserted (progn
  14398. (ignore-errors (cdlatex-environment environment item))
  14399. (< beg end)))
  14400. ;; Figure out how many lines to move forward after the
  14401. ;; environment has been inserted.
  14402. (lines (when inserted
  14403. (save-excursion
  14404. (- (cl-loop while (< beg (point))
  14405. with x = 0
  14406. do (forward-line -1)
  14407. (cl-incf x)
  14408. finally return x)
  14409. (if (progn (goto-char beg)
  14410. (and (progn (skip-chars-forward " \t") (eolp))
  14411. (progn (skip-chars-backward " \t") (bolp))))
  14412. 1 0)))))
  14413. (env (org-trim (delete-and-extract-region beg end))))
  14414. (when inserted
  14415. ;; Get indentation of next line unless at column 0.
  14416. (let ((ind (if (bolp) 0
  14417. (save-excursion
  14418. (org-return t)
  14419. (prog1 (current-indentation)
  14420. (when (progn (skip-chars-forward " \t") (eolp))
  14421. (delete-region beg (point)))))))
  14422. (bol (progn (skip-chars-backward " \t") (bolp))))
  14423. ;; Insert a newline before environment unless at column zero
  14424. ;; to "escape" the current line. Insert a newline if
  14425. ;; something is one the same line as \end{ENVIRONMENT}.
  14426. (insert
  14427. (concat (unless bol "\n") env
  14428. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14429. (unless (zerop ind)
  14430. (save-excursion
  14431. (goto-char beg)
  14432. (while (< (point) end)
  14433. (unless (eolp) (indent-line-to ind))
  14434. (forward-line))))
  14435. (goto-char beg)
  14436. (forward-line lines)
  14437. (indent-line-to ind)))
  14438. (set-marker beg nil)
  14439. (set-marker end nil)))
  14440. ;;;; LaTeX fragments
  14441. (defun org-inside-LaTeX-fragment-p ()
  14442. "Test if point is inside a LaTeX fragment.
  14443. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14444. sequence appearing also before point.
  14445. Even though the matchers for math are configurable, this function assumes
  14446. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14447. delimiters are skipped when they have been removed by customization.
  14448. The return value is nil, or a cons cell with the delimiter and the
  14449. position of this delimiter.
  14450. This function does a reasonably good job, but can locally be fooled by
  14451. for example currency specifications. For example it will assume being in
  14452. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14453. fragments that are properly closed, but during editing, we have to live
  14454. with the uncertainty caused by missing closing delimiters. This function
  14455. looks only before point, not after."
  14456. (catch 'exit
  14457. (let ((pos (point))
  14458. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14459. (lim (progn
  14460. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14461. 'move)
  14462. (point)))
  14463. dd-on str (start 0) m re)
  14464. (goto-char pos)
  14465. (when dodollar
  14466. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14467. re (nth 1 (assoc "$" org-latex-regexps)))
  14468. (while (string-match re str start)
  14469. (cond
  14470. ((= (match-end 0) (length str))
  14471. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14472. ((= (match-end 0) (- (length str) 5))
  14473. (throw 'exit nil))
  14474. (t (setq start (match-end 0))))))
  14475. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14476. (goto-char pos)
  14477. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14478. (and (match-beginning 2) (throw 'exit nil))
  14479. ;; count $$
  14480. (while (re-search-backward "\\$\\$" lim t)
  14481. (setq dd-on (not dd-on)))
  14482. (goto-char pos)
  14483. (when dd-on (cons "$$" m))))))
  14484. (defun org-inside-latex-macro-p ()
  14485. "Is point inside a LaTeX macro or its arguments?"
  14486. (save-match-data
  14487. (org-in-regexp
  14488. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14489. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14490. "Build an overlay between BEG and END using IMAGE file.
  14491. Argument IMAGETYPE is the extension of the displayed image,
  14492. as a string. It defaults to \"png\"."
  14493. (let ((ov (make-overlay beg end))
  14494. (imagetype (or (intern imagetype) 'png)))
  14495. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14496. (overlay-put ov 'evaporate t)
  14497. (overlay-put ov
  14498. 'modification-hooks
  14499. (list (lambda (o _flag _beg _end &optional _l)
  14500. (delete-overlay o))))
  14501. (overlay-put ov
  14502. 'display
  14503. (list 'image :type imagetype :file image :ascent 'center))))
  14504. (defun org-clear-latex-preview (&optional beg end)
  14505. "Remove all overlays with LaTeX fragment images in current buffer.
  14506. When optional arguments BEG and END are non-nil, remove all
  14507. overlays between them instead. Return a non-nil value when some
  14508. overlays were removed, nil otherwise."
  14509. (let ((overlays
  14510. (cl-remove-if-not
  14511. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14512. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14513. (mapc #'delete-overlay overlays)
  14514. overlays))
  14515. (defun org--latex-preview-region (beg end)
  14516. "Preview LaTeX fragments between BEG and END.
  14517. BEG and END are buffer positions."
  14518. (let ((file (buffer-file-name (buffer-base-buffer))))
  14519. (save-excursion
  14520. (org-format-latex
  14521. (concat org-preview-latex-image-directory "org-ltximg")
  14522. beg end
  14523. ;; Emacs cannot overlay images from remote hosts. Create it in
  14524. ;; `temporary-file-directory' instead.
  14525. (if (or (not file) (file-remote-p file))
  14526. temporary-file-directory
  14527. default-directory)
  14528. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14529. (defun org-latex-preview (&optional arg)
  14530. "Toggle preview of the LaTeX fragment at point.
  14531. If the cursor is on a LaTeX fragment, create the image and
  14532. overlay it over the source code, if there is none. Remove it
  14533. otherwise. If there is no fragment at point, display images for
  14534. all fragments in the current section.
  14535. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14536. for all fragments
  14537. in the current section.
  14538. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14539. argument ARG, display image for all
  14540. fragments in the buffer.
  14541. With a `\\[universal-argument] \\[universal-argument] \
  14542. \\[universal-argument]' prefix argument ARG, clear image for all
  14543. fragments in the buffer."
  14544. (interactive "P")
  14545. (cond
  14546. ((not (display-graphic-p)) nil)
  14547. ;; Clear whole buffer.
  14548. ((equal arg '(64))
  14549. (org-clear-latex-preview (point-min) (point-max))
  14550. (message "LaTeX previews removed from buffer"))
  14551. ;; Preview whole buffer.
  14552. ((equal arg '(16))
  14553. (message "Creating LaTeX previews in buffer...")
  14554. (org--latex-preview-region (point-min) (point-max))
  14555. (message "Creating LaTeX previews in buffer... done."))
  14556. ;; Clear current section.
  14557. ((equal arg '(4))
  14558. (org-clear-latex-preview
  14559. (if (org-before-first-heading-p) (point-min)
  14560. (save-excursion
  14561. (org-with-limited-levels (org-back-to-heading t) (point))))
  14562. (org-with-limited-levels (org-entry-end-position))))
  14563. ;; Toggle preview on LaTeX code at point.
  14564. ((let ((datum (org-element-context)))
  14565. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14566. (let ((beg (org-element-property :begin datum))
  14567. (end (org-element-property :end datum)))
  14568. (if (org-clear-latex-preview beg end)
  14569. (message "LaTeX preview removed")
  14570. (message "Creating LaTeX preview...")
  14571. (org--latex-preview-region beg end)
  14572. (message "Creating LaTeX preview... done."))
  14573. t))))
  14574. ;; Preview current section.
  14575. (t
  14576. (let ((beg (if (org-before-first-heading-p) (point-min)
  14577. (save-excursion
  14578. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14579. (end (org-with-limited-levels (org-entry-end-position))))
  14580. (message "Creating LaTeX previews in section...")
  14581. (org--latex-preview-region beg end)
  14582. (message "Creating LaTeX previews in section... done.")))))
  14583. (defun org-format-latex
  14584. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14585. "Replace LaTeX fragments with links to an image.
  14586. The function takes care of creating the replacement image.
  14587. Only consider fragments between BEG and END when those are
  14588. provided.
  14589. When optional argument OVERLAYS is non-nil, display the image on
  14590. top of the fragment instead of replacing it.
  14591. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14592. Some of the options can be changed using the variable
  14593. `org-format-latex-options', which see."
  14594. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14595. (unless (eq processing-type 'verbatim)
  14596. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14597. (cnt 0)
  14598. checkdir-flag)
  14599. (goto-char (or beg (point-min)))
  14600. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14601. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14602. (overlay-recenter (or end (point-max))))
  14603. (while (re-search-forward math-regexp end t)
  14604. (unless (and overlays
  14605. (eq (get-char-property (point) 'org-overlay-type)
  14606. 'org-latex-overlay))
  14607. (let* ((context (org-element-context))
  14608. (type (org-element-type context)))
  14609. (when (memq type '(latex-environment latex-fragment))
  14610. (let ((block-type (eq type 'latex-environment))
  14611. (value (org-element-property :value context))
  14612. (beg (org-element-property :begin context))
  14613. (end (save-excursion
  14614. (goto-char (org-element-property :end context))
  14615. (skip-chars-backward " \r\t\n")
  14616. (point))))
  14617. (cond
  14618. ((eq processing-type 'mathjax)
  14619. ;; Prepare for MathJax processing.
  14620. (if (not (string-match "\\`\\$\\$?" value))
  14621. (goto-char end)
  14622. (delete-region beg end)
  14623. (if (string= (match-string 0 value) "$$")
  14624. (insert "\\[" (substring value 2 -2) "\\]")
  14625. (insert "\\(" (substring value 1 -1) "\\)"))))
  14626. ((eq processing-type 'html)
  14627. (goto-char beg)
  14628. (delete-region beg end)
  14629. (insert (org-format-latex-as-html value)))
  14630. ((assq processing-type org-preview-latex-process-alist)
  14631. ;; Process to an image.
  14632. (cl-incf cnt)
  14633. (goto-char beg)
  14634. (let* ((processing-info
  14635. (cdr (assq processing-type org-preview-latex-process-alist)))
  14636. (face (face-at-point))
  14637. ;; Get the colors from the face at point.
  14638. (fg
  14639. (let ((color (plist-get org-format-latex-options
  14640. :foreground)))
  14641. (if forbuffer
  14642. (cond
  14643. ((eq color 'auto)
  14644. (face-attribute face :foreground nil 'default))
  14645. ((eq color 'default)
  14646. (face-attribute 'default :foreground nil))
  14647. (t color))
  14648. color)))
  14649. (bg
  14650. (let ((color (plist-get org-format-latex-options
  14651. :background)))
  14652. (if forbuffer
  14653. (cond
  14654. ((eq color 'auto)
  14655. (face-attribute face :background nil 'default))
  14656. ((eq color 'default)
  14657. (face-attribute 'default :background nil))
  14658. (t color))
  14659. color)))
  14660. (hash (sha1 (prin1-to-string
  14661. (list org-format-latex-header
  14662. org-latex-default-packages-alist
  14663. org-latex-packages-alist
  14664. org-format-latex-options
  14665. forbuffer value fg bg))))
  14666. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14667. (absprefix (expand-file-name prefix dir))
  14668. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14669. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14670. (sep (and block-type "\n\n"))
  14671. (link (concat sep "[[file:" linkfile "]]" sep))
  14672. (options
  14673. (org-combine-plists
  14674. org-format-latex-options
  14675. `(:foreground ,fg :background ,bg))))
  14676. (when msg (message msg cnt))
  14677. (unless checkdir-flag ; Ensure the directory exists.
  14678. (setq checkdir-flag t)
  14679. (let ((todir (file-name-directory absprefix)))
  14680. (unless (file-directory-p todir)
  14681. (make-directory todir t))))
  14682. (unless (file-exists-p movefile)
  14683. (org-create-formula-image
  14684. value movefile options forbuffer processing-type))
  14685. (if overlays
  14686. (progn
  14687. (dolist (o (overlays-in beg end))
  14688. (when (eq (overlay-get o 'org-overlay-type)
  14689. 'org-latex-overlay)
  14690. (delete-overlay o)))
  14691. (org--make-preview-overlay beg end movefile imagetype)
  14692. (goto-char end))
  14693. (delete-region beg end)
  14694. (insert
  14695. (org-add-props link
  14696. (list 'org-latex-src
  14697. (replace-regexp-in-string "\"" "" value)
  14698. 'org-latex-src-embed-type
  14699. (if block-type 'paragraph 'character)))))))
  14700. ((eq processing-type 'mathml)
  14701. ;; Process to MathML.
  14702. (unless (org-format-latex-mathml-available-p)
  14703. (user-error "LaTeX to MathML converter not configured"))
  14704. (cl-incf cnt)
  14705. (when msg (message msg cnt))
  14706. (goto-char beg)
  14707. (delete-region beg end)
  14708. (insert (org-format-latex-as-mathml
  14709. value block-type prefix dir)))
  14710. (t
  14711. (error "Unknown conversion process %s for LaTeX fragments"
  14712. processing-type)))))))))))
  14713. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14714. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14715. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14716. successful, return the portion between \"<math...> </math>\"
  14717. elements otherwise return nil. When MATHML-FILE is specified,
  14718. write the results in to that file. When invoked as an
  14719. interactive command, prompt for LATEX-FRAG, with initial value
  14720. set to the current active region and echo the results for user
  14721. inspection."
  14722. (interactive (list (let ((frag (when (org-region-active-p)
  14723. (buffer-substring-no-properties
  14724. (region-beginning) (region-end)))))
  14725. (read-string "LaTeX Fragment: " frag nil frag))))
  14726. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14727. (let* ((tmp-in-file
  14728. (let ((file (file-relative-name
  14729. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14730. (write-region latex-frag nil file)
  14731. file))
  14732. (tmp-out-file (file-relative-name
  14733. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14734. (cmd (format-spec
  14735. org-latex-to-mathml-convert-command
  14736. `((?j . ,(and org-latex-to-mathml-jar-file
  14737. (shell-quote-argument
  14738. (expand-file-name
  14739. org-latex-to-mathml-jar-file))))
  14740. (?I . ,(shell-quote-argument tmp-in-file))
  14741. (?i . ,latex-frag)
  14742. (?o . ,(shell-quote-argument tmp-out-file)))))
  14743. mathml shell-command-output)
  14744. (when (called-interactively-p 'any)
  14745. (unless (org-format-latex-mathml-available-p)
  14746. (user-error "LaTeX to MathML converter not configured")))
  14747. (message "Running %s" cmd)
  14748. (setq shell-command-output (shell-command-to-string cmd))
  14749. (setq mathml
  14750. (when (file-readable-p tmp-out-file)
  14751. (with-current-buffer (find-file-noselect tmp-out-file t)
  14752. (goto-char (point-min))
  14753. (when (re-search-forward
  14754. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14755. (regexp-quote
  14756. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14757. nil t)
  14758. (prog1 (match-string 0) (kill-buffer))))))
  14759. (cond
  14760. (mathml
  14761. (setq mathml
  14762. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14763. (when mathml-file
  14764. (write-region mathml nil mathml-file))
  14765. (when (called-interactively-p 'any)
  14766. (message mathml)))
  14767. ((warn "LaTeX to MathML conversion failed")
  14768. (message shell-command-output)))
  14769. (delete-file tmp-in-file)
  14770. (when (file-exists-p tmp-out-file)
  14771. (delete-file tmp-out-file))
  14772. mathml))
  14773. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14774. prefix &optional dir)
  14775. "Use `org-create-math-formula' but check local cache first."
  14776. (let* ((absprefix (expand-file-name prefix dir))
  14777. (print-length nil) (print-level nil)
  14778. (formula-id (concat
  14779. "formula-"
  14780. (sha1
  14781. (prin1-to-string
  14782. (list latex-frag
  14783. org-latex-to-mathml-convert-command)))))
  14784. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14785. (formula-cache-dir (file-name-directory formula-cache)))
  14786. (unless (file-directory-p formula-cache-dir)
  14787. (make-directory formula-cache-dir t))
  14788. (unless (file-exists-p formula-cache)
  14789. (org-create-math-formula latex-frag formula-cache))
  14790. (if (file-exists-p formula-cache)
  14791. ;; Successful conversion. Return the link to MathML file.
  14792. (org-add-props
  14793. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14794. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14795. 'org-latex-src-embed-type (if latex-frag-type
  14796. 'paragraph 'character)))
  14797. ;; Failed conversion. Return the LaTeX fragment verbatim
  14798. latex-frag)))
  14799. (defun org-format-latex-as-html (latex-fragment)
  14800. "Convert LATEX-FRAGMENT to HTML.
  14801. This uses `org-latex-to-html-convert-command', which see."
  14802. (let ((cmd (format-spec org-latex-to-html-convert-command
  14803. `((?i . ,latex-fragment)))))
  14804. (message "Running %s" cmd)
  14805. (shell-command-to-string cmd)))
  14806. (defun org--get-display-dpi ()
  14807. "Get the DPI of the display.
  14808. The function assumes that the display has the same pixel width in
  14809. the horizontal and vertical directions."
  14810. (if (display-graphic-p)
  14811. (round (/ (display-pixel-height)
  14812. (/ (display-mm-height) 25.4)))
  14813. (error "Attempt to calculate the dpi of a non-graphic display")))
  14814. (defun org-create-formula-image
  14815. (string tofile options buffer &optional processing-type)
  14816. "Create an image from LaTeX source using external processes.
  14817. The LaTeX STRING is saved to a temporary LaTeX file, then
  14818. converted to an image file by process PROCESSING-TYPE defined in
  14819. `org-preview-latex-process-alist'. A nil value defaults to
  14820. `org-preview-latex-default-process'.
  14821. The generated image file is eventually moved to TOFILE.
  14822. The OPTIONS argument controls the size, foreground color and
  14823. background color of the generated image.
  14824. When BUFFER non-nil, this function is used for LaTeX previewing.
  14825. Otherwise, it is used to deal with LaTeX snippets showed in
  14826. a HTML file."
  14827. (let* ((processing-type (or processing-type
  14828. org-preview-latex-default-process))
  14829. (processing-info
  14830. (cdr (assq processing-type org-preview-latex-process-alist)))
  14831. (programs (plist-get processing-info :programs))
  14832. (error-message (or (plist-get processing-info :message) ""))
  14833. (image-input-type (plist-get processing-info :image-input-type))
  14834. (image-output-type (plist-get processing-info :image-output-type))
  14835. (post-clean (or (plist-get processing-info :post-clean)
  14836. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14837. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14838. (latex-header
  14839. (or (plist-get processing-info :latex-header)
  14840. (org-latex-make-preamble
  14841. (org-export-get-environment (org-export-get-backend 'latex))
  14842. org-format-latex-header
  14843. 'snippet)))
  14844. (latex-compiler (plist-get processing-info :latex-compiler))
  14845. (image-converter (plist-get processing-info :image-converter))
  14846. (tmpdir temporary-file-directory)
  14847. (texfilebase (make-temp-name
  14848. (expand-file-name "orgtex" tmpdir)))
  14849. (texfile (concat texfilebase ".tex"))
  14850. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14851. '(1.0 . 1.0)))
  14852. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14853. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14854. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14855. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14856. "Black"))
  14857. (bg (or (plist-get options (if buffer :background :html-background))
  14858. "Transparent"))
  14859. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14860. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14861. (dolist (program programs)
  14862. (org-check-external-command program error-message))
  14863. (if (eq fg 'default)
  14864. (setq fg (org-latex-color :foreground))
  14865. (setq fg (org-latex-color-format fg)))
  14866. (setq bg (cond
  14867. ((eq bg 'default) (org-latex-color :background))
  14868. ((string= bg "Transparent") nil)
  14869. (t (org-latex-color-format bg))))
  14870. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14871. (if (string-suffix-p string "\n")
  14872. (aset string (1- (length string)) ?%)
  14873. (setq string (concat string "%")))
  14874. (with-temp-file texfile
  14875. (insert latex-header)
  14876. (insert "\n\\begin{document}\n"
  14877. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14878. (if bg
  14879. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14880. "\n\\pagecolor{bg}%\n")
  14881. "")
  14882. "\n{\\color{fg}\n"
  14883. string
  14884. "\n}\n"
  14885. "\n\\end{document}\n"))
  14886. (let* ((err-msg (format "Please adjust `%s' part of \
  14887. `org-preview-latex-process-alist'."
  14888. processing-type))
  14889. (image-input-file
  14890. (org-compile-file
  14891. texfile latex-compiler image-input-type err-msg log-buf))
  14892. (image-output-file
  14893. (org-compile-file
  14894. image-input-file image-converter image-output-type err-msg log-buf
  14895. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14896. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14897. (copy-file image-output-file tofile 'replace)
  14898. (dolist (e post-clean)
  14899. (when (file-exists-p (concat texfilebase e))
  14900. (delete-file (concat texfilebase e))))
  14901. image-output-file)))
  14902. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14903. "Fill a LaTeX header template TPL.
  14904. In the template, the following place holders will be recognized:
  14905. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14906. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14907. [PACKAGES] \\usepackage statements for PKG
  14908. [NO-PACKAGES] do not include PKG
  14909. [EXTRA] the string EXTRA
  14910. [NO-EXTRA] do not include EXTRA
  14911. For backward compatibility, if both the positive and the negative place
  14912. holder is missing, the positive one (without the \"NO-\") will be
  14913. assumed to be present at the end of the template.
  14914. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14915. EXTRA is a string.
  14916. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14917. (let (rpl (end ""))
  14918. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14919. (setq rpl (if (or (match-end 1) (not def-pkg))
  14920. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14921. tpl (replace-match rpl t t tpl))
  14922. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14923. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14924. (setq rpl (if (or (match-end 1) (not pkg))
  14925. "" (org-latex-packages-to-string pkg snippets-p t))
  14926. tpl (replace-match rpl t t tpl))
  14927. (when pkg (setq end
  14928. (concat end "\n"
  14929. (org-latex-packages-to-string pkg snippets-p)))))
  14930. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14931. (setq rpl (if (or (match-end 1) (not extra))
  14932. "" (concat extra "\n"))
  14933. tpl (replace-match rpl t t tpl))
  14934. (when (and extra (string-match "\\S-" extra))
  14935. (setq end (concat end "\n" extra))))
  14936. (if (string-match "\\S-" end)
  14937. (concat tpl "\n" end)
  14938. tpl)))
  14939. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14940. "Turn an alist of packages into a string with the \\usepackage macros."
  14941. (setq pkg (mapconcat (lambda(p)
  14942. (cond
  14943. ((stringp p) p)
  14944. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14945. (format "%% Package %s omitted" (cadr p)))
  14946. ((equal "" (car p))
  14947. (format "\\usepackage{%s}" (cadr p)))
  14948. (t
  14949. (format "\\usepackage[%s]{%s}"
  14950. (car p) (cadr p)))))
  14951. pkg
  14952. "\n"))
  14953. (if newline (concat pkg "\n") pkg))
  14954. (defun org-dvipng-color (attr)
  14955. "Return a RGB color specification for dvipng."
  14956. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14957. (defun org-dvipng-color-format (color-name)
  14958. "Convert COLOR-NAME to a RGB color value for dvipng."
  14959. (apply #'format "rgb %s %s %s"
  14960. (mapcar 'org-normalize-color
  14961. (color-values color-name))))
  14962. (defun org-latex-color (attr)
  14963. "Return a RGB color for the LaTeX color package."
  14964. (org-latex-color-format (face-attribute 'default attr nil)))
  14965. (defun org-latex-color-format (color-name)
  14966. "Convert COLOR-NAME to a RGB color value."
  14967. (apply #'format "%s,%s,%s"
  14968. (mapcar 'org-normalize-color
  14969. (color-values color-name))))
  14970. (defun org-normalize-color (value)
  14971. "Return string to be used as color value for an RGB component."
  14972. (format "%g" (/ value 65535.0)))
  14973. ;; Image display
  14974. (defvar-local org-inline-image-overlays nil)
  14975. (defun org-toggle-inline-images (&optional include-linked)
  14976. "Toggle the display of inline images.
  14977. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14978. (interactive "P")
  14979. (if org-inline-image-overlays
  14980. (progn
  14981. (org-remove-inline-images)
  14982. (when (called-interactively-p 'interactive)
  14983. (message "Inline image display turned off")))
  14984. (org-display-inline-images include-linked)
  14985. (when (called-interactively-p 'interactive)
  14986. (message (if org-inline-image-overlays
  14987. (format "%d images displayed inline"
  14988. (length org-inline-image-overlays))
  14989. "No images to display inline")))))
  14990. (defun org-redisplay-inline-images ()
  14991. "Assure display of inline images and refresh them."
  14992. (interactive)
  14993. (org-toggle-inline-images)
  14994. (unless org-inline-image-overlays
  14995. (org-toggle-inline-images)))
  14996. ;; For without-x builds.
  14997. (declare-function image-refresh "image" (spec &optional frame))
  14998. (defcustom org-display-remote-inline-images 'skip
  14999. "How to display remote inline images.
  15000. Possible values of this option are:
  15001. skip Don't display remote images.
  15002. download Always download and display remote images.
  15003. cache Display remote images, and open them in separate buffers
  15004. for caching. Silently update the image buffer when a file
  15005. change is detected."
  15006. :group 'org-appearance
  15007. :package-version '(Org . "9.4")
  15008. :type '(choice
  15009. (const :tag "Ignore remote images" skip)
  15010. (const :tag "Always display remote images" download)
  15011. (const :tag "Display and silently update remote images" cache))
  15012. :safe #'symbolp)
  15013. (defun org--create-inline-image (file width)
  15014. "Create image located at FILE, or return nil.
  15015. WIDTH is the width of the image. The image may not be created
  15016. according to the value of `org-display-remote-inline-images'."
  15017. (let* ((remote? (file-remote-p file))
  15018. (file-or-data
  15019. (pcase org-display-remote-inline-images
  15020. ((guard (not remote?)) file)
  15021. (`download (with-temp-buffer
  15022. (set-buffer-multibyte nil)
  15023. (insert-file-contents-literally file)
  15024. (buffer-string)))
  15025. (`cache (let ((revert-without-query '(".")))
  15026. (with-current-buffer (find-file-noselect file)
  15027. (buffer-string))))
  15028. (`skip nil)
  15029. (other
  15030. (message "Invalid value of `org-display-remote-inline-images': %S"
  15031. other)
  15032. nil))))
  15033. (when file-or-data
  15034. (create-image file-or-data
  15035. (and (image-type-available-p 'imagemagick)
  15036. width
  15037. 'imagemagick)
  15038. remote?
  15039. :width width))))
  15040. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15041. "Display inline images.
  15042. An inline image is a link which follows either of these
  15043. conventions:
  15044. 1. Its path is a file with an extension matching return value
  15045. from `image-file-name-regexp' and it has no contents.
  15046. 2. Its description consists in a single link of the previous
  15047. type. In this case, that link must be a well-formed plain
  15048. or angle link, i.e., it must have an explicit \"file\" type.
  15049. Equip each image with the key-map `image-map'.
  15050. When optional argument INCLUDE-LINKED is non-nil, also links with
  15051. a text description part will be inlined. This can be nice for
  15052. a quick look at those images, but it does not reflect what
  15053. exported files will look like.
  15054. When optional argument REFRESH is non-nil, refresh existing
  15055. images between BEG and END. This will create new image displays
  15056. only if necessary.
  15057. BEG and END define the considered part. They default to the
  15058. buffer boundaries with possible narrowing."
  15059. (interactive "P")
  15060. (when (display-graphic-p)
  15061. (unless refresh
  15062. (org-remove-inline-images)
  15063. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15064. (let ((end (or end (point-max))))
  15065. (org-with-point-at (or beg (point-min))
  15066. (let* ((case-fold-search t)
  15067. (file-extension-re (image-file-name-regexp))
  15068. (link-abbrevs (mapcar #'car
  15069. (append org-link-abbrev-alist-local
  15070. org-link-abbrev-alist)))
  15071. ;; Check absolute, relative file names and explicit
  15072. ;; "file:" links. Also check link abbreviations since
  15073. ;; some might expand to "file" links.
  15074. (file-types-re
  15075. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15076. (if (not link-abbrevs) ""
  15077. (concat "\\|" (regexp-opt link-abbrevs))))))
  15078. (while (re-search-forward file-types-re end t)
  15079. (let* ((link (org-element-lineage
  15080. (save-match-data (org-element-context))
  15081. '(link) t))
  15082. (linktype (org-element-property :type link))
  15083. (inner-start (match-beginning 1))
  15084. (path
  15085. (cond
  15086. ;; No link at point; no inline image.
  15087. ((not link) nil)
  15088. ;; File link without a description. Also handle
  15089. ;; INCLUDE-LINKED here since it should have
  15090. ;; precedence over the next case. I.e., if link
  15091. ;; contains filenames in both the path and the
  15092. ;; description, prioritize the path only when
  15093. ;; INCLUDE-LINKED is non-nil.
  15094. ((or (not (org-element-property :contents-begin link))
  15095. include-linked)
  15096. (and (or (equal "file" linktype)
  15097. (equal "attachment" linktype))
  15098. (org-element-property :path link)))
  15099. ;; Link with a description. Check if description
  15100. ;; is a filename. Even if Org doesn't have syntax
  15101. ;; for those -- clickable image -- constructs, fake
  15102. ;; them, as in `org-export-insert-image-links'.
  15103. ((not inner-start) nil)
  15104. (t
  15105. (org-with-point-at inner-start
  15106. (and (looking-at
  15107. (if (char-equal ?< (char-after inner-start))
  15108. org-link-angle-re
  15109. org-link-plain-re))
  15110. ;; File name must fill the whole
  15111. ;; description.
  15112. (= (org-element-property :contents-end link)
  15113. (match-end 0))
  15114. (match-string 2)))))))
  15115. (when (and path (string-match-p file-extension-re path))
  15116. (let ((file (if (equal "attachment" linktype)
  15117. (progn
  15118. (require 'org-attach)
  15119. (ignore-errors (org-attach-expand path)))
  15120. (expand-file-name path))))
  15121. (when (and file (file-exists-p file))
  15122. (let ((width
  15123. ;; Apply `org-image-actual-width' specifications.
  15124. (cond
  15125. ((eq org-image-actual-width t) nil)
  15126. ((listp org-image-actual-width)
  15127. (or
  15128. ;; First try to find a width among
  15129. ;; attributes associated to the paragraph
  15130. ;; containing link.
  15131. (pcase (org-element-lineage link '(paragraph))
  15132. (`nil nil)
  15133. (p
  15134. (let* ((case-fold-search t)
  15135. (end (org-element-property :post-affiliated p))
  15136. (re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"))
  15137. (when (org-with-point-at
  15138. (org-element-property :begin p)
  15139. (re-search-forward re end t))
  15140. (string-to-number (match-string 1))))))
  15141. ;; Otherwise, fall-back to provided number.
  15142. (car org-image-actual-width)))
  15143. ((numberp org-image-actual-width)
  15144. org-image-actual-width)
  15145. (t nil)))
  15146. (old (get-char-property-and-overlay
  15147. (org-element-property :begin link)
  15148. 'org-image-overlay)))
  15149. (if (and (car-safe old) refresh)
  15150. (image-refresh (overlay-get (cdr old) 'display))
  15151. (let ((image (org--create-inline-image file width)))
  15152. (when image
  15153. (let ((ov (make-overlay
  15154. (org-element-property :begin link)
  15155. (progn
  15156. (goto-char
  15157. (org-element-property :end link))
  15158. (skip-chars-backward " \t")
  15159. (point)))))
  15160. (overlay-put ov 'display image)
  15161. (overlay-put ov 'face 'default)
  15162. (overlay-put ov 'org-image-overlay t)
  15163. (overlay-put
  15164. ov 'modification-hooks
  15165. (list 'org-display-inline-remove-overlay))
  15166. (when (boundp 'image-map)
  15167. (overlay-put ov 'keymap image-map))
  15168. (push ov org-inline-image-overlays))))))))))))))))
  15169. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15170. "Remove inline-display overlay if a corresponding region is modified."
  15171. (let ((inhibit-modification-hooks t))
  15172. (when (and ov after)
  15173. (delete ov org-inline-image-overlays)
  15174. (delete-overlay ov))))
  15175. (defun org-remove-inline-images ()
  15176. "Remove inline display of images."
  15177. (interactive)
  15178. (mapc #'delete-overlay org-inline-image-overlays)
  15179. (setq org-inline-image-overlays nil))
  15180. (defvar org-self-insert-command-undo-counter 0)
  15181. (defvar org-speed-command nil)
  15182. (defun org-self-insert-command (N)
  15183. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15184. If the cursor is in a table looking at whitespace, the whitespace is
  15185. overwritten, and the table is not marked as requiring realignment."
  15186. (interactive "p")
  15187. (org-check-before-invisible-edit 'insert)
  15188. (cond
  15189. ((and org-use-speed-commands
  15190. (let ((kv (this-command-keys-vector)))
  15191. (setq org-speed-command
  15192. (run-hook-with-args-until-success
  15193. 'org-speed-command-hook
  15194. (make-string 1 (aref kv (1- (length kv))))))))
  15195. (cond
  15196. ((commandp org-speed-command)
  15197. (setq this-command org-speed-command)
  15198. (call-interactively org-speed-command))
  15199. ((functionp org-speed-command)
  15200. (funcall org-speed-command))
  15201. ((and org-speed-command (listp org-speed-command))
  15202. (eval org-speed-command))
  15203. (t (let (org-use-speed-commands)
  15204. (call-interactively 'org-self-insert-command)))))
  15205. ((and
  15206. (= N 1)
  15207. (not (org-region-active-p))
  15208. (org-at-table-p)
  15209. (progn
  15210. ;; Check if we blank the field, and if that triggers align.
  15211. (and (featurep 'org-table)
  15212. org-table-auto-blank-field
  15213. (memq last-command
  15214. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15215. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15216. ;; Got extra space, this field does not determine
  15217. ;; column width.
  15218. (let (org-table-may-need-update) (org-table-blank-field))
  15219. ;; No extra space, this field may determine column
  15220. ;; width.
  15221. (org-table-blank-field)))
  15222. t)
  15223. (looking-at "[^|\n]* |"))
  15224. ;; There is room for insertion without re-aligning the table.
  15225. (self-insert-command N)
  15226. (org-table-with-shrunk-field
  15227. (save-excursion
  15228. (skip-chars-forward "^|")
  15229. ;; Do not delete last space, which is
  15230. ;; `org-table-separator-space', but the regular space before
  15231. ;; it.
  15232. (delete-region (- (point) 2) (1- (point))))))
  15233. (t
  15234. (setq org-table-may-need-update t)
  15235. (self-insert-command N)
  15236. (org-fix-tags-on-the-fly)
  15237. (when org-self-insert-cluster-for-undo
  15238. (if (not (eq last-command 'org-self-insert-command))
  15239. (setq org-self-insert-command-undo-counter 1)
  15240. (if (>= org-self-insert-command-undo-counter 20)
  15241. (setq org-self-insert-command-undo-counter 1)
  15242. (and (> org-self-insert-command-undo-counter 0)
  15243. buffer-undo-list (listp buffer-undo-list)
  15244. (not (cadr buffer-undo-list)) ; remove nil entry
  15245. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15246. (setq org-self-insert-command-undo-counter
  15247. (1+ org-self-insert-command-undo-counter))))))))
  15248. (defun org-check-before-invisible-edit (kind)
  15249. "Check if editing kind KIND would be dangerous with invisible text around.
  15250. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15251. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15252. (when (and org-catch-invisible-edits
  15253. (or (not (boundp 'visible-mode)) (not visible-mode))
  15254. (or (get-char-property (point) 'invisible)
  15255. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15256. ;; OK, we need to take a closer look. Do not consider
  15257. ;; invisibility obtained through text properties (e.g., link
  15258. ;; fontification), as it cannot be toggled.
  15259. (let* ((invisible-at-point
  15260. (pcase (get-char-property-and-overlay (point) 'invisible)
  15261. (`(,_ . ,(and (pred overlayp) o)) o)))
  15262. ;; Assume that point cannot land in the middle of an
  15263. ;; overlay, or between two overlays.
  15264. (invisible-before-point
  15265. (and (not invisible-at-point)
  15266. (not (bobp))
  15267. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15268. (`(,_ . ,(and (pred overlayp) o)) o))))
  15269. (border-and-ok-direction
  15270. (or
  15271. ;; Check if we are acting predictably before invisible
  15272. ;; text.
  15273. (and invisible-at-point
  15274. (memq kind '(insert delete-backward)))
  15275. ;; Check if we are acting predictably after invisible text
  15276. ;; This works not well, and I have turned it off. It seems
  15277. ;; better to always show and stop after invisible text.
  15278. ;; (and (not invisible-at-point) invisible-before-point
  15279. ;; (memq kind '(insert delete)))
  15280. )))
  15281. (when (or invisible-at-point invisible-before-point)
  15282. (when (eq org-catch-invisible-edits 'error)
  15283. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15284. (if (and org-custom-properties-overlays
  15285. (y-or-n-p "Display invisible properties in this buffer? "))
  15286. (org-toggle-custom-properties-visibility)
  15287. ;; Make the area visible
  15288. (save-excursion
  15289. (when invisible-before-point
  15290. (goto-char
  15291. (previous-single-char-property-change (point) 'invisible)))
  15292. ;; Remove whatever overlay is currently making yet-to-be
  15293. ;; edited text invisible. Also remove nested invisibility
  15294. ;; related overlays.
  15295. (delete-overlay (or invisible-at-point invisible-before-point))
  15296. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15297. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15298. (`(,_ . ,(and (pred overlayp) o))
  15299. (delete-overlay o)
  15300. t)))))
  15301. (cond
  15302. ((eq org-catch-invisible-edits 'show)
  15303. ;; That's it, we do the edit after showing
  15304. (message
  15305. "Unfolding invisible region around point before editing")
  15306. (sit-for 1))
  15307. ((and (eq org-catch-invisible-edits 'smart)
  15308. border-and-ok-direction)
  15309. (message "Unfolding invisible region around point before editing"))
  15310. (t
  15311. ;; Don't do the edit, make the user repeat it in full visibility
  15312. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15313. (defun org-fix-tags-on-the-fly ()
  15314. "Align tags in headline at point.
  15315. Unlike `org-align-tags', this function does nothing if point is
  15316. either not currently on a tagged headline or on a tag."
  15317. (when (and (org-match-line org-tag-line-re)
  15318. (< (point) (match-beginning 1)))
  15319. (org-align-tags)))
  15320. (defun org-delete-backward-char (N)
  15321. "Like `delete-backward-char', insert whitespace at field end in tables.
  15322. When deleting backwards, in tables this function will insert whitespace in
  15323. front of the next \"|\" separator, to keep the table aligned. The table will
  15324. still be marked for re-alignment if the field did fill the entire column,
  15325. because, in this case the deletion might narrow the column."
  15326. (interactive "p")
  15327. (save-match-data
  15328. (org-check-before-invisible-edit 'delete-backward)
  15329. (if (and (= N 1)
  15330. (not overwrite-mode)
  15331. (not (org-region-active-p))
  15332. (not (eq (char-before) ?|))
  15333. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15334. (looking-at-p ".*?|")
  15335. (org-at-table-p))
  15336. (progn (forward-char -1) (org-delete-char 1))
  15337. (backward-delete-char N)
  15338. (org-fix-tags-on-the-fly))))
  15339. (defun org-delete-char (N)
  15340. "Like `delete-char', but insert whitespace at field end in tables.
  15341. When deleting characters, in tables this function will insert whitespace in
  15342. front of the next \"|\" separator, to keep the table aligned. The table will
  15343. still be marked for re-alignment if the field did fill the entire column,
  15344. because, in this case the deletion might narrow the column."
  15345. (interactive "p")
  15346. (save-match-data
  15347. (org-check-before-invisible-edit 'delete)
  15348. (cond
  15349. ((or (/= N 1)
  15350. (eq (char-after) ?|)
  15351. (save-excursion (skip-chars-backward " \t") (bolp))
  15352. (not (org-at-table-p)))
  15353. (delete-char N)
  15354. (org-fix-tags-on-the-fly))
  15355. ((looking-at ".\\(.*?\\)|")
  15356. (let* ((update? org-table-may-need-update)
  15357. (noalign (looking-at-p ".*? |")))
  15358. (delete-char 1)
  15359. (org-table-with-shrunk-field
  15360. (save-excursion
  15361. ;; Last space is `org-table-separator-space', so insert
  15362. ;; a regular one before it instead.
  15363. (goto-char (- (match-end 0) 2))
  15364. (insert " ")))
  15365. ;; If there were two spaces at the end, this field does not
  15366. ;; determine the width of the column.
  15367. (when noalign (setq org-table-may-need-update update?))))
  15368. (t
  15369. (delete-char N)))))
  15370. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15371. (put 'org-self-insert-command 'delete-selection
  15372. (lambda ()
  15373. (not (run-hook-with-args-until-success
  15374. 'self-insert-uses-region-functions))))
  15375. (put 'orgtbl-self-insert-command 'delete-selection
  15376. (lambda ()
  15377. (not (run-hook-with-args-until-success
  15378. 'self-insert-uses-region-functions))))
  15379. (put 'org-delete-char 'delete-selection 'supersede)
  15380. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15381. (put 'org-yank 'delete-selection 'yank)
  15382. ;; Make `flyspell-mode' delay after some commands
  15383. (put 'org-self-insert-command 'flyspell-delayed t)
  15384. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15385. (put 'org-delete-char 'flyspell-delayed t)
  15386. (put 'org-delete-backward-char 'flyspell-delayed t)
  15387. ;; Make pabbrev-mode expand after Org mode commands
  15388. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15389. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15390. (defun org-transpose-words ()
  15391. "Transpose words for Org.
  15392. This uses the `org-mode-transpose-word-syntax-table' syntax
  15393. table, which interprets characters in `org-emphasis-alist' as
  15394. word constituents."
  15395. (interactive)
  15396. (with-syntax-table org-mode-transpose-word-syntax-table
  15397. (call-interactively 'transpose-words)))
  15398. (defvar org-ctrl-c-ctrl-c-hook nil
  15399. "Hook for functions attaching themselves to `C-c C-c'.
  15400. This can be used to add additional functionality to the `C-c C-c'
  15401. key which executes context-dependent commands. This hook is run
  15402. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15403. run after the last test.
  15404. Each function will be called with no arguments. The function
  15405. must check if the context is appropriate for it to act. If yes,
  15406. it should do its thing and then return a non-nil value. If the
  15407. context is wrong, just do nothing and return nil.")
  15408. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15409. "Hook for functions attaching themselves to `C-c C-c'.
  15410. This can be used to add additional functionality to the `C-c C-c'
  15411. key which executes context-dependent commands. This hook is run
  15412. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15413. before the first test.
  15414. Each function will be called with no arguments. The function
  15415. must check if the context is appropriate for it to act. If yes,
  15416. it should do its thing and then return a non-nil value. If the
  15417. context is wrong, just do nothing and return nil.")
  15418. (defvar org-tab-first-hook nil
  15419. "Hook for functions to attach themselves to TAB.
  15420. See `org-ctrl-c-ctrl-c-hook' for more information.
  15421. This hook runs as the first action when TAB is pressed, even before
  15422. `org-cycle' messes around with the `outline-regexp' to cater for
  15423. inline tasks and plain list item folding.
  15424. If any function in this hook returns t, any other actions that
  15425. would have been caused by TAB (such as table field motion or visibility
  15426. cycling) will not occur.")
  15427. (defvar org-tab-after-check-for-table-hook nil
  15428. "Hook for functions to attach themselves to TAB.
  15429. See `org-ctrl-c-ctrl-c-hook' for more information.
  15430. This hook runs after it has been established that the cursor is not in a
  15431. table, but before checking if the cursor is in a headline or if global cycling
  15432. should be done.
  15433. If any function in this hook returns t, not other actions like visibility
  15434. cycling will be done.")
  15435. (defvar org-tab-after-check-for-cycling-hook nil
  15436. "Hook for functions to attach themselves to TAB.
  15437. See `org-ctrl-c-ctrl-c-hook' for more information.
  15438. This hook runs after it has been established that not table field motion and
  15439. not visibility should be done because of current context. This is probably
  15440. the place where a package like yasnippets can hook in.")
  15441. (defvar org-tab-before-tab-emulation-hook nil
  15442. "Hook for functions to attach themselves to TAB.
  15443. See `org-ctrl-c-ctrl-c-hook' for more information.
  15444. This hook runs after every other options for TAB have been exhausted, but
  15445. before indentation and \t insertion takes place.")
  15446. (defvar org-metaleft-hook nil
  15447. "Hook for functions attaching themselves to `M-left'.
  15448. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15449. (defvar org-metaright-hook nil
  15450. "Hook for functions attaching themselves to `M-right'.
  15451. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15452. (defvar org-metaup-hook nil
  15453. "Hook for functions attaching themselves to `M-up'.
  15454. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15455. (defvar org-metadown-hook nil
  15456. "Hook for functions attaching themselves to `M-down'.
  15457. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15458. (defvar org-shiftmetaleft-hook nil
  15459. "Hook for functions attaching themselves to `M-S-left'.
  15460. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15461. (defvar org-shiftmetaright-hook nil
  15462. "Hook for functions attaching themselves to `M-S-right'.
  15463. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15464. (defvar org-shiftmetaup-hook nil
  15465. "Hook for functions attaching themselves to `M-S-up'.
  15466. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15467. (defvar org-shiftmetadown-hook nil
  15468. "Hook for functions attaching themselves to `M-S-down'.
  15469. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15470. (defvar org-metareturn-hook nil
  15471. "Hook for functions attaching themselves to `M-RET'.
  15472. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15473. (defvar org-shiftup-hook nil
  15474. "Hook for functions attaching themselves to `S-up'.
  15475. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15476. (defvar org-shiftup-final-hook nil
  15477. "Hook for functions attaching themselves to `S-up'.
  15478. This one runs after all other options except shift-select have been excluded.
  15479. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15480. (defvar org-shiftdown-hook nil
  15481. "Hook for functions attaching themselves to `S-down'.
  15482. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15483. (defvar org-shiftdown-final-hook nil
  15484. "Hook for functions attaching themselves to `S-down'.
  15485. This one runs after all other options except shift-select have been excluded.
  15486. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15487. (defvar org-shiftleft-hook nil
  15488. "Hook for functions attaching themselves to `S-left'.
  15489. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15490. (defvar org-shiftleft-final-hook nil
  15491. "Hook for functions attaching themselves to `S-left'.
  15492. This one runs after all other options except shift-select have been excluded.
  15493. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15494. (defvar org-shiftright-hook nil
  15495. "Hook for functions attaching themselves to `S-right'.
  15496. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15497. (defvar org-shiftright-final-hook nil
  15498. "Hook for functions attaching themselves to `S-right'.
  15499. This one runs after all other options except shift-select have been excluded.
  15500. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15501. (defun org-modifier-cursor-error ()
  15502. "Throw an error, a modified cursor command was applied in wrong context."
  15503. (user-error "This command is active in special context like tables, headlines or items"))
  15504. (defun org-shiftselect-error ()
  15505. "Throw an error because Shift-Cursor command was applied in wrong context."
  15506. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15507. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15508. (user-error "This command works only in special context like headlines or timestamps")))
  15509. (defun org-call-for-shift-select (cmd)
  15510. (let ((this-command-keys-shift-translated t))
  15511. (call-interactively cmd)))
  15512. (defun org-shifttab (&optional arg)
  15513. "Global visibility cycling or move to previous table field.
  15514. Call `org-table-previous-field' within a table.
  15515. When ARG is nil, cycle globally through visibility states.
  15516. When ARG is a numeric prefix, show contents of this level."
  15517. (interactive "P")
  15518. (cond
  15519. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15520. ((integerp arg)
  15521. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15522. (message "Content view to level: %d" arg)
  15523. (org-content (prefix-numeric-value arg2))
  15524. (org-cycle-show-empty-lines t)
  15525. (setq org-cycle-global-status 'overview)
  15526. (run-hook-with-args 'org-cycle-hook 'overview)))
  15527. (t (call-interactively 'org-global-cycle))))
  15528. (defun org-shiftmetaleft ()
  15529. "Promote subtree or delete table column.
  15530. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15531. `org-table-delete-column', depending on context. See the
  15532. individual commands for more information."
  15533. (interactive)
  15534. (cond
  15535. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15536. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15537. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15538. ((if (not (org-region-active-p)) (org-at-item-p)
  15539. (save-excursion (goto-char (region-beginning))
  15540. (org-at-item-p)))
  15541. (call-interactively 'org-outdent-item-tree))
  15542. (t (org-modifier-cursor-error))))
  15543. (defun org-shiftmetaright ()
  15544. "Demote subtree or insert table column.
  15545. Calls `org-demote-subtree', `org-indent-item-tree', or
  15546. `org-table-insert-column', depending on context. See the
  15547. individual commands for more information."
  15548. (interactive)
  15549. (cond
  15550. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15551. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15552. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15553. ((if (not (org-region-active-p)) (org-at-item-p)
  15554. (save-excursion (goto-char (region-beginning))
  15555. (org-at-item-p)))
  15556. (call-interactively 'org-indent-item-tree))
  15557. (t (org-modifier-cursor-error))))
  15558. (defun org-shiftmetaup (&optional _arg)
  15559. "Drag the line at point up.
  15560. In a table, kill the current row.
  15561. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15562. but also adjust the previous clocked item in the clock history.
  15563. Everywhere else, drag the line at point up."
  15564. (interactive "P")
  15565. (cond
  15566. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15567. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15568. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15569. (call-interactively 'org-timestamp-up)))
  15570. (t (call-interactively 'org-drag-line-backward))))
  15571. (defun org-shiftmetadown (&optional _arg)
  15572. "Drag the line at point down.
  15573. In a table, insert an empty row at the current line.
  15574. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15575. but also adjust the previous clocked item in the clock history.
  15576. Everywhere else, drag the line at point down."
  15577. (interactive "P")
  15578. (cond
  15579. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15580. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15581. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15582. (call-interactively 'org-timestamp-down)))
  15583. (t (call-interactively 'org-drag-line-forward))))
  15584. (defsubst org-hidden-tree-error ()
  15585. (user-error
  15586. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15587. (defun org-metaleft (&optional _arg)
  15588. "Promote heading, list item at point or move table column left.
  15589. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15590. depending on context. With no specific context, calls the Emacs
  15591. default `backward-word'. See the individual commands for more
  15592. information.
  15593. This function runs the hook `org-metaleft-hook' as a first step,
  15594. and returns at first non-nil value."
  15595. (interactive "P")
  15596. (cond
  15597. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15598. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15599. ((org-with-limited-levels
  15600. (or (org-at-heading-p)
  15601. (and (org-region-active-p)
  15602. (save-excursion
  15603. (goto-char (region-beginning))
  15604. (org-at-heading-p)))))
  15605. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15606. (call-interactively 'org-do-promote))
  15607. ;; At an inline task.
  15608. ((org-at-heading-p)
  15609. (call-interactively 'org-inlinetask-promote))
  15610. ((or (org-at-item-p)
  15611. (and (org-region-active-p)
  15612. (save-excursion
  15613. (goto-char (region-beginning))
  15614. (org-at-item-p))))
  15615. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15616. (call-interactively 'org-outdent-item))
  15617. (t (call-interactively 'backward-word))))
  15618. (defun org-metaright (&optional _arg)
  15619. "Demote heading, list item at point or move table column right.
  15620. In front of a drawer or a block keyword, indent it correctly.
  15621. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15622. `org-indent-drawer' or `org-indent-block' depending on context.
  15623. With no specific context, calls the Emacs default `forward-word'.
  15624. See the individual commands for more information.
  15625. This function runs the hook `org-metaright-hook' as a first step,
  15626. and returns at first non-nil value."
  15627. (interactive "P")
  15628. (cond
  15629. ((run-hook-with-args-until-success 'org-metaright-hook))
  15630. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15631. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15632. ((org-at-block-p) (call-interactively 'org-indent-block))
  15633. ((org-with-limited-levels
  15634. (or (org-at-heading-p)
  15635. (and (org-region-active-p)
  15636. (save-excursion
  15637. (goto-char (region-beginning))
  15638. (org-at-heading-p)))))
  15639. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15640. (call-interactively 'org-do-demote))
  15641. ;; At an inline task.
  15642. ((org-at-heading-p)
  15643. (call-interactively 'org-inlinetask-demote))
  15644. ((or (org-at-item-p)
  15645. (and (org-region-active-p)
  15646. (save-excursion
  15647. (goto-char (region-beginning))
  15648. (org-at-item-p))))
  15649. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15650. (call-interactively 'org-indent-item))
  15651. (t (call-interactively 'forward-word))))
  15652. (defun org-check-for-hidden (what)
  15653. "Check if there are hidden headlines/items in the current visual line.
  15654. WHAT can be either `headlines' or `items'. If the current line is
  15655. an outline or item heading and it has a folded subtree below it,
  15656. this function returns t, nil otherwise."
  15657. (let ((re (cond
  15658. ((eq what 'headlines) org-outline-regexp-bol)
  15659. ((eq what 'items) (org-item-beginning-re))
  15660. (t (error "This should not happen"))))
  15661. beg end)
  15662. (save-excursion
  15663. (catch 'exit
  15664. (unless (org-region-active-p)
  15665. (setq beg (point-at-bol))
  15666. (beginning-of-line 2)
  15667. (while (and (not (eobp)) ;; this is like `next-line'
  15668. (get-char-property (1- (point)) 'invisible))
  15669. (beginning-of-line 2))
  15670. (setq end (point))
  15671. (goto-char beg)
  15672. (goto-char (point-at-eol))
  15673. (setq end (max end (point)))
  15674. (while (re-search-forward re end t)
  15675. (when (get-char-property (match-beginning 0) 'invisible)
  15676. (throw 'exit t))))
  15677. nil))))
  15678. (defun org-metaup (&optional _arg)
  15679. "Move subtree up or move table row up.
  15680. Calls `org-move-subtree-up' or `org-table-move-row' or
  15681. `org-move-item-up', depending on context. See the individual commands
  15682. for more information."
  15683. (interactive "P")
  15684. (cond
  15685. ((run-hook-with-args-until-success 'org-metaup-hook))
  15686. ((org-region-active-p)
  15687. (let* ((a (save-excursion
  15688. (goto-char (min (region-beginning) (region-end)))
  15689. (line-beginning-position)))
  15690. (b (save-excursion
  15691. (goto-char (max (region-beginning) (region-end)))
  15692. (if (bolp) (1- (point)) (line-end-position))))
  15693. (c (save-excursion
  15694. (goto-char a)
  15695. (move-beginning-of-line 0)
  15696. (point)))
  15697. (d (save-excursion
  15698. (goto-char a)
  15699. (move-end-of-line 0)
  15700. (point))))
  15701. (transpose-regions a b c d)
  15702. (goto-char c)))
  15703. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15704. ((and (featurep 'org-inlinetask)
  15705. (org-inlinetask-in-task-p))
  15706. (org-drag-element-backward))
  15707. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15708. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15709. (t (org-drag-element-backward))))
  15710. (defun org-metadown (&optional _arg)
  15711. "Move subtree down or move table row down.
  15712. Calls `org-move-subtree-down' or `org-table-move-row' or
  15713. `org-move-item-down', depending on context. See the individual
  15714. commands for more information."
  15715. (interactive "P")
  15716. (cond
  15717. ((run-hook-with-args-until-success 'org-metadown-hook))
  15718. ((org-region-active-p)
  15719. (let* ((a (save-excursion
  15720. (goto-char (min (region-beginning) (region-end)))
  15721. (line-beginning-position)))
  15722. (b (save-excursion
  15723. (goto-char (max (region-beginning) (region-end)))
  15724. (if (bolp) (1- (point)) (line-end-position))))
  15725. (c (save-excursion
  15726. (goto-char b)
  15727. (move-beginning-of-line (if (bolp) 1 2))
  15728. (point)))
  15729. (d (save-excursion
  15730. (goto-char b)
  15731. (move-end-of-line (if (bolp) 1 2))
  15732. (point))))
  15733. (transpose-regions a b c d)
  15734. (goto-char d)))
  15735. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15736. ((and (featurep 'org-inlinetask)
  15737. (org-inlinetask-in-task-p))
  15738. (org-drag-element-forward))
  15739. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15740. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15741. (t (org-drag-element-forward))))
  15742. (defun org-shiftup (&optional arg)
  15743. "Act on current element according to context.
  15744. Call `org-timestamp-up' or `org-priority-up', or
  15745. `org-previous-item', or `org-table-move-cell-up'. See the
  15746. individual commands for more information."
  15747. (interactive "P")
  15748. (cond
  15749. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15750. ((and org-support-shift-select (org-region-active-p))
  15751. (org-call-for-shift-select 'previous-line))
  15752. ((org-at-timestamp-p 'lax)
  15753. (call-interactively (if org-edit-timestamp-down-means-later
  15754. 'org-timestamp-down 'org-timestamp-up)))
  15755. ((and (not (eq org-support-shift-select 'always))
  15756. org-priority-enable-commands
  15757. (org-at-heading-p))
  15758. (call-interactively 'org-priority-up))
  15759. ((and (not org-support-shift-select) (org-at-item-p))
  15760. (call-interactively 'org-previous-item))
  15761. ((org-clocktable-try-shift 'up arg))
  15762. ((and (not (eq org-support-shift-select 'always))
  15763. (org-at-table-p))
  15764. (org-table-move-cell-up))
  15765. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15766. (org-support-shift-select
  15767. (org-call-for-shift-select 'previous-line))
  15768. (t (org-shiftselect-error))))
  15769. (defun org-shiftdown (&optional arg)
  15770. "Act on current element according to context.
  15771. Call `org-timestamp-down' or `org-priority-down', or
  15772. `org-next-item', or `org-table-move-cell-down'. See the
  15773. individual commands for more information."
  15774. (interactive "P")
  15775. (cond
  15776. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15777. ((and org-support-shift-select (org-region-active-p))
  15778. (org-call-for-shift-select 'next-line))
  15779. ((org-at-timestamp-p 'lax)
  15780. (call-interactively (if org-edit-timestamp-down-means-later
  15781. 'org-timestamp-up 'org-timestamp-down)))
  15782. ((and (not (eq org-support-shift-select 'always))
  15783. org-priority-enable-commands
  15784. (org-at-heading-p))
  15785. (call-interactively 'org-priority-down))
  15786. ((and (not org-support-shift-select) (org-at-item-p))
  15787. (call-interactively 'org-next-item))
  15788. ((org-clocktable-try-shift 'down arg))
  15789. ((and (not (eq org-support-shift-select 'always))
  15790. (org-at-table-p))
  15791. (org-table-move-cell-down))
  15792. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15793. (org-support-shift-select
  15794. (org-call-for-shift-select 'next-line))
  15795. (t (org-shiftselect-error))))
  15796. (defun org-shiftright (&optional arg)
  15797. "Act on the current element according to context.
  15798. This does one of the following:
  15799. - switch a timestamp at point one day into the future
  15800. - on a headline, switch to the next TODO keyword
  15801. - on an item, switch entire list to the next bullet type
  15802. - on a property line, switch to the next allowed value
  15803. - on a clocktable definition line, move time block into the future
  15804. - in a table, move a single cell right"
  15805. (interactive "P")
  15806. (cond
  15807. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15808. ((and org-support-shift-select (org-region-active-p))
  15809. (org-call-for-shift-select 'forward-char))
  15810. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15811. ((and (not (eq org-support-shift-select 'always))
  15812. (org-at-heading-p))
  15813. (let ((org-inhibit-logging
  15814. (not org-treat-S-cursor-todo-selection-as-state-change))
  15815. (org-inhibit-blocking
  15816. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15817. (org-call-with-arg 'org-todo 'right)))
  15818. ((or (and org-support-shift-select
  15819. (not (eq org-support-shift-select 'always))
  15820. (org-at-item-bullet-p))
  15821. (and (not org-support-shift-select) (org-at-item-p)))
  15822. (org-call-with-arg 'org-cycle-list-bullet nil))
  15823. ((and (not (eq org-support-shift-select 'always))
  15824. (org-at-property-p))
  15825. (call-interactively 'org-property-next-allowed-value))
  15826. ((org-clocktable-try-shift 'right arg))
  15827. ((and (not (eq org-support-shift-select 'always))
  15828. (org-at-table-p))
  15829. (org-table-move-cell-right))
  15830. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15831. (org-support-shift-select
  15832. (org-call-for-shift-select 'forward-char))
  15833. (t (org-shiftselect-error))))
  15834. (defun org-shiftleft (&optional arg)
  15835. "Act on current element according to context.
  15836. This does one of the following:
  15837. - switch a timestamp at point one day into the past
  15838. - on a headline, switch to the previous TODO keyword.
  15839. - on an item, switch entire list to the previous bullet type
  15840. - on a property line, switch to the previous allowed value
  15841. - on a clocktable definition line, move time block into the past
  15842. - in a table, move a single cell left"
  15843. (interactive "P")
  15844. (cond
  15845. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15846. ((and org-support-shift-select (org-region-active-p))
  15847. (org-call-for-shift-select 'backward-char))
  15848. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15849. ((and (not (eq org-support-shift-select 'always))
  15850. (org-at-heading-p))
  15851. (let ((org-inhibit-logging
  15852. (not org-treat-S-cursor-todo-selection-as-state-change))
  15853. (org-inhibit-blocking
  15854. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15855. (org-call-with-arg 'org-todo 'left)))
  15856. ((or (and org-support-shift-select
  15857. (not (eq org-support-shift-select 'always))
  15858. (org-at-item-bullet-p))
  15859. (and (not org-support-shift-select) (org-at-item-p)))
  15860. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15861. ((and (not (eq org-support-shift-select 'always))
  15862. (org-at-property-p))
  15863. (call-interactively 'org-property-previous-allowed-value))
  15864. ((org-clocktable-try-shift 'left arg))
  15865. ((and (not (eq org-support-shift-select 'always))
  15866. (org-at-table-p))
  15867. (org-table-move-cell-left))
  15868. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15869. (org-support-shift-select
  15870. (org-call-for-shift-select 'backward-char))
  15871. (t (org-shiftselect-error))))
  15872. (defun org-shiftcontrolright ()
  15873. "Switch to next TODO set."
  15874. (interactive)
  15875. (cond
  15876. ((and org-support-shift-select (org-region-active-p))
  15877. (org-call-for-shift-select 'forward-word))
  15878. ((and (not (eq org-support-shift-select 'always))
  15879. (org-at-heading-p))
  15880. (org-call-with-arg 'org-todo 'nextset))
  15881. (org-support-shift-select
  15882. (org-call-for-shift-select 'forward-word))
  15883. (t (org-shiftselect-error))))
  15884. (defun org-shiftcontrolleft ()
  15885. "Switch to previous TODO set."
  15886. (interactive)
  15887. (cond
  15888. ((and org-support-shift-select (org-region-active-p))
  15889. (org-call-for-shift-select 'backward-word))
  15890. ((and (not (eq org-support-shift-select 'always))
  15891. (org-at-heading-p))
  15892. (org-call-with-arg 'org-todo 'previousset))
  15893. (org-support-shift-select
  15894. (org-call-for-shift-select 'backward-word))
  15895. (t (org-shiftselect-error))))
  15896. (defun org-shiftcontrolup (&optional n)
  15897. "Change timestamps synchronously up in CLOCK log lines.
  15898. Optional argument N tells to change by that many units."
  15899. (interactive "P")
  15900. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15901. (let (org-support-shift-select)
  15902. (org-clock-timestamps-up n))
  15903. (user-error "Not at a clock log")))
  15904. (defun org-shiftcontroldown (&optional n)
  15905. "Change timestamps synchronously down in CLOCK log lines.
  15906. Optional argument N tells to change by that many units."
  15907. (interactive "P")
  15908. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15909. (let (org-support-shift-select)
  15910. (org-clock-timestamps-down n))
  15911. (user-error "Not at a clock log")))
  15912. (defun org-increase-number-at-point (&optional inc)
  15913. "Increment the number at point.
  15914. With an optional prefix numeric argument INC, increment using
  15915. this numeric value."
  15916. (interactive "p")
  15917. (if (not (number-at-point))
  15918. (user-error "Not on a number")
  15919. (unless inc (setq inc 1))
  15920. (let ((pos (point))
  15921. (beg (skip-chars-backward "-+^/*0-9eE."))
  15922. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15923. (setq nap (buffer-substring-no-properties
  15924. (+ pos beg) (+ pos beg end)))
  15925. (delete-region (+ pos beg) (+ pos beg end))
  15926. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15927. (when (org-at-table-p)
  15928. (org-table-align)
  15929. (org-table-end-of-field 1))))
  15930. (defun org-decrease-number-at-point (&optional inc)
  15931. "Decrement the number at point.
  15932. With an optional prefix numeric argument INC, decrement using
  15933. this numeric value."
  15934. (interactive "p")
  15935. (org-increase-number-at-point (- (or inc 1))))
  15936. (defun org-ctrl-c-ret ()
  15937. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15938. (interactive)
  15939. (cond
  15940. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15941. (t (call-interactively 'org-insert-heading))))
  15942. (defun org-copy-visible (beg end)
  15943. "Copy the visible parts of the region."
  15944. (interactive "r")
  15945. (let ((result ""))
  15946. (while (/= beg end)
  15947. (when (get-char-property beg 'invisible)
  15948. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15949. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15950. (setq result (concat result (buffer-substring beg next)))
  15951. (setq beg next)))
  15952. (setq deactivate-mark t)
  15953. (kill-new result)
  15954. (message "Visible strings have been copied to the kill ring.")))
  15955. (defun org-copy-special ()
  15956. "Copy region in table or copy current subtree.
  15957. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15958. context. See the individual commands for more information."
  15959. (interactive)
  15960. (call-interactively
  15961. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15962. (defun org-cut-special ()
  15963. "Cut region in table or cut current subtree.
  15964. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15965. context. See the individual commands for more information."
  15966. (interactive)
  15967. (call-interactively
  15968. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15969. (defun org-paste-special (arg)
  15970. "Paste rectangular region into table, or past subtree relative to level.
  15971. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15972. See the individual commands for more information."
  15973. (interactive "P")
  15974. (if (org-at-table-p)
  15975. (org-table-paste-rectangle)
  15976. (org-paste-subtree arg)))
  15977. (defun org-edit-special (&optional arg)
  15978. "Call a special editor for the element at point.
  15979. When at a table, call the formula editor with `org-table-edit-formulas'.
  15980. When in a source code block, call `org-edit-src-code'.
  15981. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15982. When in an export block, call `org-edit-export-block'.
  15983. When in a LaTeX environment, call `org-edit-latex-environment'.
  15984. When at an #+INCLUDE keyword, visit the included file.
  15985. When at a footnote reference, call `org-edit-footnote-reference'.
  15986. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15987. When at an active timestamp, call `org-time-stamp'.
  15988. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15989. On a link, call `ffap' to visit the link at point.
  15990. Otherwise, return a user error."
  15991. (interactive "P")
  15992. (let ((element (org-element-at-point)))
  15993. (barf-if-buffer-read-only)
  15994. (pcase (org-element-type element)
  15995. (`src-block
  15996. (if (not arg) (org-edit-src-code)
  15997. (let* ((info (org-babel-get-src-block-info))
  15998. (lang (nth 0 info))
  15999. (params (nth 2 info))
  16000. (session (cdr (assq :session params))))
  16001. (if (not session) (org-edit-src-code)
  16002. ;; At a source block with a session and function called
  16003. ;; with an ARG: switch to the buffer related to the
  16004. ;; inferior process.
  16005. (switch-to-buffer
  16006. (funcall (intern (concat "org-babel-prep-session:" lang))
  16007. session params))))))
  16008. (`keyword
  16009. (unless (member (org-element-property :key element)
  16010. '("INCLUDE" "SETUPFILE"))
  16011. (user-error "No special environment to edit here"))
  16012. (let ((value (org-element-property :value element)))
  16013. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16014. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16015. (or (match-string 1 value)
  16016. (match-string 0 value)))))
  16017. (when (org-file-url-p file)
  16018. (user-error "Files located with a URL cannot be edited"))
  16019. (org-link-open-from-string
  16020. (format "[[%s]]" (expand-file-name file))))))
  16021. (`table
  16022. (if (eq (org-element-property :type element) 'table.el)
  16023. (org-edit-table.el)
  16024. (call-interactively 'org-table-edit-formulas)))
  16025. ;; Only Org tables contain `table-row' type elements.
  16026. (`table-row (call-interactively 'org-table-edit-formulas))
  16027. (`example-block (org-edit-src-code))
  16028. (`export-block (org-edit-export-block))
  16029. (`fixed-width (org-edit-fixed-width-region))
  16030. (`latex-environment (org-edit-latex-environment))
  16031. (`planning
  16032. (let ((proplist (cadr element)))
  16033. (mapc #'call-interactively
  16034. (remq nil
  16035. (list
  16036. (when (plist-get proplist :deadline) #'org-deadline)
  16037. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16038. (_
  16039. ;; No notable element at point. Though, we may be at a link or
  16040. ;; a footnote reference, which are objects. Thus, scan deeper.
  16041. (let ((context (org-element-context element)))
  16042. (pcase (org-element-type context)
  16043. (`footnote-reference (org-edit-footnote-reference))
  16044. (`inline-src-block (org-edit-inline-src-code))
  16045. (`latex-fragment (org-edit-latex-fragment))
  16046. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16047. (call-interactively #'org-time-stamp-inactive)
  16048. (call-interactively #'org-time-stamp)))
  16049. (`link (call-interactively #'ffap))
  16050. (_ (user-error "No special environment to edit here"))))))))
  16051. (defun org-ctrl-c-ctrl-c (&optional arg)
  16052. "Set tags in headline, or update according to changed information at point.
  16053. This command does many different things, depending on context:
  16054. - If column view is active, in agenda or org buffers, quit it.
  16055. - If there are highlights, remove them.
  16056. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16057. this is what we do.
  16058. - If the cursor is on a statistics cookie, update it.
  16059. - If the cursor is in a headline, in an agenda or an org buffer,
  16060. prompt for tags and insert them into the current line, aligned
  16061. to `org-tags-column'. When called with prefix arg, realign all
  16062. tags in the current buffer.
  16063. - If the cursor is in one of the special #+KEYWORD lines, this
  16064. triggers scanning the buffer for these lines and updating the
  16065. information.
  16066. - If the cursor is inside a table, realign the table. This command
  16067. works even if the automatic table editor has been turned off.
  16068. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16069. the entire table.
  16070. - If the cursor is at a footnote reference or definition, jump to
  16071. the corresponding definition or references, respectively.
  16072. - If the cursor is a the beginning of a dynamic block, update it.
  16073. - If the current buffer is a capture buffer, close note and file it.
  16074. - If the cursor is on a <<<target>>>, update radio targets and
  16075. corresponding links in this buffer.
  16076. - If the cursor is on a numbered item in a plain list, renumber the
  16077. ordered list.
  16078. - If the cursor is on a checkbox, toggle it.
  16079. - If the cursor is on a code block, evaluate it. The variable
  16080. `org-confirm-babel-evaluate' can be used to control prompting
  16081. before code block evaluation, by default every code block
  16082. evaluation requires confirmation. Code block evaluation can be
  16083. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16084. (interactive "P")
  16085. (cond
  16086. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16087. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16088. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16089. (org-remove-occur-highlights)
  16090. (message "Temporary highlights/overlays removed from current buffer"))
  16091. ((and (local-variable-p 'org-finish-function)
  16092. (fboundp org-finish-function))
  16093. (funcall org-finish-function))
  16094. ((org-babel-hash-at-point))
  16095. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16096. (t
  16097. (let* ((context
  16098. (org-element-lineage
  16099. (org-element-context)
  16100. ;; Limit to supported contexts.
  16101. '(babel-call clock dynamic-block footnote-definition
  16102. footnote-reference inline-babel-call inline-src-block
  16103. inlinetask item keyword node-property paragraph
  16104. plain-list planning property-drawer radio-target
  16105. src-block statistics-cookie table table-cell table-row
  16106. timestamp)
  16107. t))
  16108. (radio-list-p (org-at-radio-list-p))
  16109. (type (org-element-type context)))
  16110. ;; For convenience: at the first line of a paragraph on the same
  16111. ;; line as an item, apply function on that item instead.
  16112. (when (eq type 'paragraph)
  16113. (let ((parent (org-element-property :parent context)))
  16114. (when (and (eq (org-element-type parent) 'item)
  16115. (= (line-beginning-position)
  16116. (org-element-property :begin parent)))
  16117. (setq context parent)
  16118. (setq type 'item))))
  16119. ;; Act according to type of element or object at point.
  16120. ;;
  16121. ;; Do nothing on a blank line, except if it is contained in
  16122. ;; a source block. Hence, we first check if point is in such
  16123. ;; a block and then if it is at a blank line.
  16124. (pcase type
  16125. ((or `inline-src-block `src-block)
  16126. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16127. (org-babel-eval-wipe-error-buffer)
  16128. (org-babel-execute-src-block
  16129. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16130. ((guard (org-match-line "[ \t]*$"))
  16131. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16132. (user-error
  16133. (substitute-command-keys
  16134. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16135. ((or `babel-call `inline-babel-call)
  16136. (let ((info (org-babel-lob-get-info context)))
  16137. (when info (org-babel-execute-src-block nil info))))
  16138. (`clock (org-clock-update-time-maybe))
  16139. (`dynamic-block
  16140. (save-excursion
  16141. (goto-char (org-element-property :post-affiliated context))
  16142. (org-update-dblock)))
  16143. (`footnote-definition
  16144. (goto-char (org-element-property :post-affiliated context))
  16145. (call-interactively 'org-footnote-action))
  16146. (`footnote-reference (call-interactively #'org-footnote-action))
  16147. ((or `headline `inlinetask)
  16148. (save-excursion (goto-char (org-element-property :begin context))
  16149. (call-interactively #'org-set-tags-command)))
  16150. (`item
  16151. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16152. ;; unconditionally, whereas `C-u' will toggle its presence.
  16153. ;; Without a universal argument, if the item has a checkbox,
  16154. ;; toggle it. Otherwise repair the list.
  16155. (if (or radio-list-p
  16156. (and (boundp org-list-checkbox-radio-mode)
  16157. org-list-checkbox-radio-mode))
  16158. (org-toggle-radio-button arg)
  16159. (let* ((box (org-element-property :checkbox context))
  16160. (struct (org-element-property :structure context))
  16161. (old-struct (copy-tree struct))
  16162. (parents (org-list-parents-alist struct))
  16163. (prevs (org-list-prevs-alist struct))
  16164. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16165. (org-list-set-checkbox
  16166. (org-element-property :begin context) struct
  16167. (cond ((equal arg '(16)) "[-]")
  16168. ((and (not box) (equal arg '(4))) "[ ]")
  16169. ((or (not box) (equal arg '(4))) nil)
  16170. ((eq box 'on) "[ ]")
  16171. (t "[X]")))
  16172. ;; Mimic `org-list-write-struct' but with grabbing a return
  16173. ;; value from `org-list-struct-fix-box'.
  16174. (org-list-struct-fix-ind struct parents 2)
  16175. (org-list-struct-fix-item-end struct)
  16176. (org-list-struct-fix-bul struct prevs)
  16177. (org-list-struct-fix-ind struct parents)
  16178. (let ((block-item
  16179. (org-list-struct-fix-box struct parents prevs orderedp)))
  16180. (if (and box (equal struct old-struct))
  16181. (if (equal arg '(16))
  16182. (message "Checkboxes already reset")
  16183. (user-error "Cannot toggle this checkbox: %s"
  16184. (if (eq box 'on)
  16185. "all subitems checked"
  16186. "unchecked subitems")))
  16187. (org-list-struct-apply-struct struct old-struct)
  16188. (org-update-checkbox-count-maybe))
  16189. (when block-item
  16190. (message "Checkboxes were removed due to empty box at line %d"
  16191. (org-current-line block-item)))))))
  16192. (`plain-list
  16193. ;; At a plain list, with a double C-u argument, set
  16194. ;; checkboxes of each item to "[-]", whereas a single one
  16195. ;; will toggle their presence according to the state of the
  16196. ;; first item in the list. Without an argument, repair the
  16197. ;; list.
  16198. (if (or radio-list-p
  16199. (and (boundp org-list-checkbox-radio-mode)
  16200. org-list-checkbox-radio-mode))
  16201. (org-toggle-radio-button arg)
  16202. (let* ((begin (org-element-property :contents-begin context))
  16203. (struct (org-element-property :structure context))
  16204. (old-struct (copy-tree struct))
  16205. (first-box (save-excursion
  16206. (goto-char begin)
  16207. (looking-at org-list-full-item-re)
  16208. (match-string-no-properties 3)))
  16209. (new-box (cond ((equal arg '(16)) "[-]")
  16210. ((equal arg '(4)) (unless first-box "[ ]"))
  16211. ((equal first-box "[X]") "[ ]")
  16212. (t "[X]"))))
  16213. (cond
  16214. (arg
  16215. (dolist (pos
  16216. (org-list-get-all-items
  16217. begin struct (org-list-prevs-alist struct)))
  16218. (org-list-set-checkbox pos struct new-box)))
  16219. ((and first-box (eq (point) begin))
  16220. ;; For convenience, when point is at bol on the first
  16221. ;; item of the list and no argument is provided, simply
  16222. ;; toggle checkbox of that item, if any.
  16223. (org-list-set-checkbox begin struct new-box)))
  16224. (when (equal
  16225. (org-list-write-struct
  16226. struct (org-list-parents-alist struct) old-struct)
  16227. old-struct)
  16228. (message "Cannot update this checkbox"))
  16229. (org-update-checkbox-count-maybe))))
  16230. (`keyword
  16231. (let ((org-inhibit-startup-visibility-stuff t)
  16232. (org-startup-align-all-tables nil))
  16233. (when (boundp 'org-table-coordinate-overlays)
  16234. (mapc #'delete-overlay org-table-coordinate-overlays)
  16235. (setq org-table-coordinate-overlays nil))
  16236. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16237. (message "Local setup has been refreshed"))
  16238. ((or `property-drawer `node-property)
  16239. (call-interactively #'org-property-action))
  16240. (`radio-target
  16241. (call-interactively #'org-update-radio-target-regexp))
  16242. (`statistics-cookie
  16243. (call-interactively #'org-update-statistics-cookies))
  16244. ((or `table `table-cell `table-row)
  16245. ;; At a table, generate a plot if on the #+plot line,
  16246. ;; recalculate every field and align it otherwise. Also
  16247. ;; send the table if necessary.
  16248. (cond
  16249. ((and (org-match-line "[ \t]*#\\+plot:")
  16250. (< (point) (org-element-property :post-affiliated context)))
  16251. (org-plot/gnuplot))
  16252. ;; If the table has a `table.el' type, just give up.
  16253. ((eq (org-element-property :type context) 'table.el)
  16254. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16255. Use `\\[org-edit-special]' to edit table.el tables")))
  16256. ;; At a table row or cell, maybe recalculate line but always
  16257. ;; align table.
  16258. ((or (eq type 'table)
  16259. ;; Check if point is at a TBLFM line.
  16260. (and (eq type 'table-row)
  16261. (= (point) (org-element-property :end context))))
  16262. (save-excursion
  16263. (if (org-at-TBLFM-p)
  16264. (progn (require 'org-table)
  16265. (org-table-calc-current-TBLFM))
  16266. (goto-char (org-element-property :contents-begin context))
  16267. (org-call-with-arg 'org-table-recalculate (or arg t))
  16268. (orgtbl-send-table 'maybe))))
  16269. (t
  16270. (org-table-maybe-eval-formula)
  16271. (cond (arg (call-interactively #'org-table-recalculate))
  16272. ((org-table-maybe-recalculate-line))
  16273. (t (org-table-align))))))
  16274. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16275. (org-timestamp-change 0 'day))
  16276. ((and `nil (guard (org-at-heading-p)))
  16277. ;; When point is on an unsupported object type, we can miss
  16278. ;; the fact that it also is at a heading. Handle it here.
  16279. (call-interactively #'org-set-tags-command))
  16280. ((guard
  16281. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16282. (_
  16283. (user-error
  16284. (substitute-command-keys
  16285. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16286. (defun org-mode-restart ()
  16287. "Restart `org-mode'."
  16288. (interactive)
  16289. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16290. (funcall major-mode)
  16291. (hack-local-variables)
  16292. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16293. (org-indent-mode -1))
  16294. (org-reset-file-cache))
  16295. (message "%s restarted" major-mode))
  16296. (defun org-flag-above-first-heading (&optional arg)
  16297. "Hide from bob up to the first heading.
  16298. Move point to the beginning of first heading or end of buffer."
  16299. (goto-char (point-min))
  16300. (unless (org-at-heading-p)
  16301. (outline-next-heading))
  16302. (unless (bobp)
  16303. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16304. (defun org-show-branches-buffer ()
  16305. "Show all branches in the buffer."
  16306. (org-flag-above-first-heading)
  16307. (outline-hide-sublevels 1)
  16308. (unless (eobp)
  16309. (outline-show-branches)
  16310. (while (outline-get-next-sibling)
  16311. (outline-show-branches)))
  16312. (goto-char (point-min)))
  16313. (defun org-kill-note-or-show-branches ()
  16314. "Abort storing current note, or show just branches."
  16315. (interactive)
  16316. (cond (org-finish-function
  16317. (let ((org-note-abort t)) (funcall org-finish-function)))
  16318. ((org-before-first-heading-p)
  16319. (org-show-branches-buffer)
  16320. (org-hide-archived-subtrees (point-min) (point-max)))
  16321. (t
  16322. (let ((beg (progn (org-back-to-heading) (point)))
  16323. (end (save-excursion (org-end-of-subtree t t) (point))))
  16324. (outline-hide-subtree)
  16325. (outline-show-branches)
  16326. (org-hide-archived-subtrees beg end)))))
  16327. (defun org-delete-indentation (&optional arg)
  16328. "Join current line to previous and fix whitespace at join.
  16329. If previous line is a headline add to headline title. Otherwise
  16330. the function calls `delete-indentation'.
  16331. I.e. with a non-nil optional argument, join the line with the
  16332. following one. If there is a region then join the lines in that
  16333. region."
  16334. (interactive "*P")
  16335. (if (save-excursion
  16336. (beginning-of-line (if arg 1 0))
  16337. (let ((case-fold-search nil))
  16338. (looking-at org-complex-heading-regexp)))
  16339. ;; At headline.
  16340. (let ((tags-column (when (match-beginning 5)
  16341. (save-excursion (goto-char (match-beginning 5))
  16342. (current-column))))
  16343. (string (concat " " (progn (when arg (forward-line 1))
  16344. (org-trim (delete-and-extract-region
  16345. (line-beginning-position)
  16346. (line-end-position)))))))
  16347. (unless (bobp) (delete-region (point) (1- (point))))
  16348. (goto-char (or (match-end 4)
  16349. (match-beginning 5)
  16350. (match-end 0)))
  16351. (skip-chars-backward " \t")
  16352. (save-excursion (insert string))
  16353. ;; Adjust alignment of tags.
  16354. (cond
  16355. ((not tags-column)) ;no tags
  16356. (org-auto-align-tags (org-align-tags))
  16357. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16358. (let ((current-prefix-arg arg))
  16359. (call-interactively #'delete-indentation))))
  16360. (defun org-open-line (n)
  16361. "Insert a new row in tables, call `open-line' elsewhere.
  16362. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16363. As a special case, when a document starts with a table, allow to
  16364. call `open-line' on the very first character."
  16365. (interactive "*p")
  16366. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16367. (org-table-insert-row)
  16368. (open-line n)))
  16369. (defun org--newline (indent arg interactive)
  16370. "Call `newline-and-indent' or just `newline'.
  16371. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16372. indent unconditionally; otherwise, call `newline' with ARG and
  16373. INTERACTIVE, which can trigger indentation if
  16374. `electric-indent-mode' is enabled."
  16375. (if indent
  16376. (org-newline-and-indent arg)
  16377. (newline arg interactive)))
  16378. (defun org-return (&optional indent arg interactive)
  16379. "Goto next table row or insert a newline.
  16380. Calls `org-table-next-row' or `newline', depending on context.
  16381. When optional INDENT argument is non-nil, call
  16382. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16383. and INTERACTIVE.
  16384. When `org-return-follows-link' is non-nil and point is on
  16385. a timestamp or a link, call `org-open-at-point'. However, it
  16386. will not happen if point is in a table or on a \"dead\"
  16387. object (e.g., within a comment). In these case, you need to use
  16388. `org-open-at-point' directly."
  16389. (interactive "i\nP\np")
  16390. (let* ((context (if org-return-follows-link (org-element-context)
  16391. (org-element-at-point)))
  16392. (element-type (org-element-type context)))
  16393. (cond
  16394. ;; In a table, call `org-table-next-row'. However, before first
  16395. ;; column or after last one, split the table.
  16396. ((or (and (eq 'table element-type)
  16397. (not (eq 'table.el (org-element-property :type context)))
  16398. (>= (point) (org-element-property :contents-begin context))
  16399. (< (point) (org-element-property :contents-end context)))
  16400. (org-element-lineage context '(table-row table-cell) t))
  16401. (if (or (looking-at-p "[ \t]*$")
  16402. (save-excursion (skip-chars-backward " \t") (bolp)))
  16403. (insert "\n")
  16404. (org-table-justify-field-maybe)
  16405. (call-interactively #'org-table-next-row)))
  16406. ;; On a link or a timestamp, call `org-open-at-point' if
  16407. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16408. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16409. ((and org-return-follows-link
  16410. (or (and (eq 'link element-type)
  16411. ;; Ensure point is not on the white spaces after
  16412. ;; the link.
  16413. (let ((origin (point)))
  16414. (org-with-point-at (org-element-property :end context)
  16415. (skip-chars-backward " \t")
  16416. (> (point) origin))))
  16417. (org-in-regexp org-ts-regexp-both nil t)
  16418. (org-in-regexp org-tsr-regexp-both nil t)
  16419. (org-in-regexp org-link-any-re nil t)))
  16420. (call-interactively #'org-open-at-point))
  16421. ;; Insert newline in heading, but preserve tags.
  16422. ((and (not (bolp))
  16423. (let ((case-fold-search nil))
  16424. (org-match-line org-complex-heading-regexp)))
  16425. ;; At headline. Split line. However, if point is on keyword,
  16426. ;; priority cookie or tags, do not break any of them: add
  16427. ;; a newline after the headline instead.
  16428. (let ((tags-column (and (match-beginning 5)
  16429. (save-excursion (goto-char (match-beginning 5))
  16430. (current-column))))
  16431. (string
  16432. (when (and (match-end 4) (org-point-in-group (point) 4))
  16433. (delete-and-extract-region (point) (match-end 4)))))
  16434. ;; Adjust tag alignment.
  16435. (cond
  16436. ((not (and tags-column string)))
  16437. (org-auto-align-tags (org-align-tags))
  16438. (t (org--align-tags-here tags-column))) ;preserve tags column
  16439. (end-of-line)
  16440. (org-show-entry)
  16441. (org--newline indent arg interactive)
  16442. (when string (save-excursion (insert (org-trim string))))))
  16443. ;; In a list, make sure indenting keeps trailing text within.
  16444. ((and (not (eolp))
  16445. (org-element-lineage context '(item)))
  16446. (let ((trailing-data
  16447. (delete-and-extract-region (point) (line-end-position))))
  16448. (org--newline indent arg interactive)
  16449. (save-excursion (insert trailing-data))))
  16450. ;; FIXME: In a source block, don't try to indent as it may result
  16451. ;; in weird results due to `electric-indent-mode' being `t'.
  16452. ((eq element-type 'src-block)
  16453. (org--newline nil nil nil))
  16454. (t
  16455. ;; Do not auto-fill when point is in an Org property drawer.
  16456. (let ((auto-fill-function (and (not (org-at-property-p))
  16457. auto-fill-function)))
  16458. (org--newline indent arg interactive))))))
  16459. (defun org-return-and-maybe-indent ()
  16460. "Goto next table row, or insert a newline, maybe indented.
  16461. Call `org-table-next-row' or `org-return', depending on context.
  16462. See the individual commands for more information.
  16463. When inserting a newline, if `org-adapt-indentation' is `t':
  16464. indent the line if `electric-indent-mode' is disabled, don't
  16465. indent it if it is enabled."
  16466. (interactive)
  16467. (org-return (not electric-indent-mode)))
  16468. (defun org-ctrl-c-tab (&optional arg)
  16469. "Toggle columns width in a table, or show children.
  16470. Call `org-table-toggle-column-width' if point is in a table.
  16471. Otherwise provide a compact view of the children. ARG is the
  16472. level to hide."
  16473. (interactive "p")
  16474. (cond
  16475. ((org-at-table-p)
  16476. (call-interactively #'org-table-toggle-column-width))
  16477. ((org-before-first-heading-p)
  16478. (save-excursion
  16479. (org-flag-above-first-heading)
  16480. (outline-hide-sublevels (or arg 1))))
  16481. (t
  16482. (outline-hide-subtree)
  16483. (org-show-children arg))))
  16484. (defun org-ctrl-c-star ()
  16485. "Compute table, or change heading status of lines.
  16486. Calls `org-table-recalculate' or `org-toggle-heading',
  16487. depending on context."
  16488. (interactive)
  16489. (cond
  16490. ((org-at-table-p)
  16491. (call-interactively 'org-table-recalculate))
  16492. (t
  16493. ;; Convert all lines in region to list items
  16494. (call-interactively 'org-toggle-heading))))
  16495. (defun org-ctrl-c-minus ()
  16496. "Insert separator line in table or modify bullet status of line.
  16497. Also turns a plain line or a region of lines into list items.
  16498. Calls `org-table-insert-hline', `org-toggle-item', or
  16499. `org-cycle-list-bullet', depending on context."
  16500. (interactive)
  16501. (cond
  16502. ((org-at-table-p)
  16503. (call-interactively 'org-table-insert-hline))
  16504. ((org-region-active-p)
  16505. (call-interactively 'org-toggle-item))
  16506. ((org-in-item-p)
  16507. (call-interactively 'org-cycle-list-bullet))
  16508. (t
  16509. (call-interactively 'org-toggle-item))))
  16510. (defun org-toggle-heading (&optional nstars)
  16511. "Convert headings to normal text, or items or text to headings.
  16512. If there is no active region, only convert the current line.
  16513. With a `\\[universal-argument]' prefix, convert the whole list at
  16514. point into heading.
  16515. In a region:
  16516. - If the first non blank line is a headline, remove the stars
  16517. from all headlines in the region.
  16518. - If it is a normal line, turn each and every normal line (i.e.,
  16519. not an heading or an item) in the region into headings. If you
  16520. want to convert only the first line of this region, use one
  16521. universal prefix argument.
  16522. - If it is a plain list item, turn all plain list items into headings.
  16523. When converting a line into a heading, the number of stars is chosen
  16524. such that the lines become children of the current entry. However,
  16525. when a numeric prefix argument is given, its value determines the
  16526. number of stars to add."
  16527. (interactive "P")
  16528. (let ((skip-blanks
  16529. ;; Return beginning of first non-blank line, starting from
  16530. ;; line at POS.
  16531. (lambda (pos)
  16532. (save-excursion
  16533. (goto-char pos)
  16534. (while (org-at-comment-p) (forward-line))
  16535. (skip-chars-forward " \r\t\n")
  16536. (point-at-bol))))
  16537. beg end toggled)
  16538. ;; Determine boundaries of changes. If a universal prefix has
  16539. ;; been given, put the list in a region. If region ends at a bol,
  16540. ;; do not consider the last line to be in the region.
  16541. (when (and current-prefix-arg (org-at-item-p))
  16542. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16543. (org-mark-element))
  16544. (if (org-region-active-p)
  16545. (setq beg (funcall skip-blanks (region-beginning))
  16546. end (copy-marker (save-excursion
  16547. (goto-char (region-end))
  16548. (if (bolp) (point) (point-at-eol)))))
  16549. (setq beg (funcall skip-blanks (point-at-bol))
  16550. end (copy-marker (point-at-eol))))
  16551. ;; Ensure inline tasks don't count as headings.
  16552. (org-with-limited-levels
  16553. (save-excursion
  16554. (goto-char beg)
  16555. (cond
  16556. ;; Case 1. Started at an heading: de-star headings.
  16557. ((org-at-heading-p)
  16558. (while (< (point) end)
  16559. (when (org-at-heading-p t)
  16560. (looking-at org-outline-regexp) (replace-match "")
  16561. (setq toggled t))
  16562. (forward-line)))
  16563. ;; Case 2. Started at an item: change items into headlines.
  16564. ;; One star will be added by `org-list-to-subtree'.
  16565. ((org-at-item-p)
  16566. (while (< (point) end)
  16567. (when (org-at-item-p)
  16568. ;; Pay attention to cases when region ends before list.
  16569. (let* ((struct (org-list-struct))
  16570. (list-end
  16571. (min (org-list-get-bottom-point struct) (1+ end))))
  16572. (save-restriction
  16573. (narrow-to-region (point) list-end)
  16574. (insert (org-list-to-subtree
  16575. (org-list-to-lisp t)
  16576. (pcase (org-current-level)
  16577. (`nil 1)
  16578. (l (1+ (org-reduced-level l)))))
  16579. "\n")))
  16580. (setq toggled t))
  16581. (forward-line)))
  16582. ;; Case 3. Started at normal text: make every line an heading,
  16583. ;; skipping headlines and items.
  16584. (t (let* ((stars
  16585. (make-string
  16586. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16587. (add-stars
  16588. (cond (nstars "") ; stars from prefix only
  16589. ((equal stars "") "*") ; before first heading
  16590. (org-odd-levels-only "**") ; inside heading, odd
  16591. (t "*"))) ; inside heading, oddeven
  16592. (rpl (concat stars add-stars " "))
  16593. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16594. (while (< (point) (if (equal nstars '(4)) lend end))
  16595. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16596. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16597. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16598. (forward-line)))))))
  16599. (unless toggled (message "Cannot toggle heading from here"))))
  16600. (defun org-meta-return (&optional arg)
  16601. "Insert a new heading or wrap a region in a table.
  16602. Calls `org-insert-heading', `org-insert-item' or
  16603. `org-table-wrap-region', depending on context. When called with
  16604. an argument, unconditionally call `org-insert-heading'."
  16605. (interactive "P")
  16606. (org-check-before-invisible-edit 'insert)
  16607. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16608. (call-interactively (cond (arg #'org-insert-heading)
  16609. ((org-at-table-p) #'org-table-wrap-region)
  16610. ((org-in-item-p) #'org-insert-item)
  16611. (t #'org-insert-heading)))))
  16612. ;;; Menu entries
  16613. (defsubst org-in-subtree-not-table-p ()
  16614. "Are we in a subtree and not in a table?"
  16615. (and (not (org-before-first-heading-p))
  16616. (not (org-at-table-p))))
  16617. ;; Define the Org mode menus
  16618. (easy-menu-define org-org-menu org-mode-map "Org menu"
  16619. `("Org"
  16620. ("Show/Hide"
  16621. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16622. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16623. ["Sparse Tree..." org-sparse-tree t]
  16624. ["Reveal Context" org-reveal t]
  16625. ["Show All" org-show-all t]
  16626. "--"
  16627. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16628. "--"
  16629. ["New Heading" org-insert-heading t]
  16630. ("Navigate Headings"
  16631. ["Up" outline-up-heading t]
  16632. ["Next" outline-next-visible-heading t]
  16633. ["Previous" outline-previous-visible-heading t]
  16634. ["Next Same Level" outline-forward-same-level t]
  16635. ["Previous Same Level" outline-backward-same-level t]
  16636. "--"
  16637. ["Jump" org-goto t])
  16638. ("Edit Structure"
  16639. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16640. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16641. "--"
  16642. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16643. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16644. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16645. "--"
  16646. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16647. "--"
  16648. ["Copy visible text" org-copy-visible t]
  16649. "--"
  16650. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16651. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16652. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16653. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16654. "--"
  16655. ["Sort Region/Children" org-sort t]
  16656. "--"
  16657. ["Convert to odd levels" org-convert-to-odd-levels t]
  16658. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16659. ("Editing"
  16660. ["Emphasis..." org-emphasize t]
  16661. ["Add block structure" org-insert-structure-template t]
  16662. ["Edit Source Example" org-edit-special t]
  16663. "--"
  16664. ["Footnote new/jump" org-footnote-action t]
  16665. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16666. ("Archive"
  16667. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16668. "--"
  16669. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16670. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16671. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16672. "--"
  16673. ("Hyperlinks"
  16674. ["Store Link (Global)" org-store-link t]
  16675. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16676. ["Insert Link" org-insert-link t]
  16677. ["Follow Link" org-open-at-point t]
  16678. "--"
  16679. ["Next link" org-next-link t]
  16680. ["Previous link" org-previous-link t]
  16681. "--"
  16682. ["Descriptive Links"
  16683. org-toggle-link-display
  16684. :style radio
  16685. :selected org-descriptive-links
  16686. ]
  16687. ["Literal Links"
  16688. org-toggle-link-display
  16689. :style radio
  16690. :selected (not org-descriptive-links)])
  16691. "--"
  16692. ("TODO Lists"
  16693. ["TODO/DONE/-" org-todo t]
  16694. ("Select keyword"
  16695. ["Next keyword" org-shiftright (org-at-heading-p)]
  16696. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16697. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16698. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16699. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16700. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16701. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16702. "--"
  16703. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16704. :selected org-enforce-todo-dependencies :style toggle :active t]
  16705. "Settings for tree at point"
  16706. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16707. :selected (org-entry-get nil "ORDERED")
  16708. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16709. ["Do Children parallel" org-toggle-ordered-property :style radio
  16710. :selected (not (org-entry-get nil "ORDERED"))
  16711. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16712. "--"
  16713. ["Set Priority" org-priority t]
  16714. ["Priority Up" org-shiftup t]
  16715. ["Priority Down" org-shiftdown t]
  16716. "--"
  16717. ["Get news from all feeds" org-feed-update-all t]
  16718. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16719. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16720. ("TAGS and Properties"
  16721. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16722. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16723. "--"
  16724. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16725. ["Column view of properties" org-columns t]
  16726. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16727. ("Dates and Scheduling"
  16728. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16729. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16730. ("Change Date"
  16731. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16732. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16733. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16734. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16735. ["Compute Time Range" org-evaluate-time-range t]
  16736. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16737. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16738. "--"
  16739. ["Custom time format" org-toggle-time-stamp-overlays
  16740. :style radio :selected org-display-custom-times]
  16741. "--"
  16742. ["Goto Calendar" org-goto-calendar t]
  16743. ["Date from Calendar" org-date-from-calendar t]
  16744. "--"
  16745. ["Start/Restart Timer" org-timer-start t]
  16746. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16747. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16748. ["Insert Timer String" org-timer t]
  16749. ["Insert Timer Item" org-timer-item t])
  16750. ("Logging work"
  16751. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16752. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16753. ["Clock out" org-clock-out t]
  16754. ["Clock cancel" org-clock-cancel t]
  16755. "--"
  16756. ["Mark as default task" org-clock-mark-default-task t]
  16757. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16758. ["Goto running clock" org-clock-goto t]
  16759. "--"
  16760. ["Display times" org-clock-display t]
  16761. ["Create clock table" org-clock-report t]
  16762. "--"
  16763. ["Record DONE time"
  16764. (progn (setq org-log-done (not org-log-done))
  16765. (message "Switching to %s will %s record a timestamp"
  16766. (car org-done-keywords)
  16767. (if org-log-done "automatically" "not")))
  16768. :style toggle :selected org-log-done])
  16769. "--"
  16770. ["Agenda Command..." org-agenda t]
  16771. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16772. ("File List for Agenda")
  16773. ("Special views current file"
  16774. ["TODO Tree" org-show-todo-tree t]
  16775. ["Check Deadlines" org-check-deadlines t]
  16776. ["Tags/Property tree" org-match-sparse-tree t])
  16777. "--"
  16778. ["Export/Publish..." org-export-dispatch t]
  16779. ("LaTeX"
  16780. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16781. :style toggle :selected org-cdlatex-mode]
  16782. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16783. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16784. ["Modify math symbol" org-cdlatex-math-modify
  16785. (org-inside-LaTeX-fragment-p)]
  16786. ["Insert citation" org-reftex-citation t])
  16787. "--"
  16788. ("Documentation"
  16789. ["Show Version" org-version t]
  16790. ["Info Documentation" org-info t]
  16791. ["Browse Org News" org-browse-news t])
  16792. ("Customize"
  16793. ["Browse Org Group" org-customize t]
  16794. "--"
  16795. ["Expand This Menu" org-create-customize-menu t])
  16796. ["Send bug report" org-submit-bug-report t]
  16797. "--"
  16798. ("Refresh/Reload"
  16799. ["Refresh setup current buffer" org-mode-restart t]
  16800. ["Reload Org (after update)" org-reload t]
  16801. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16802. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu"
  16803. '("Table"
  16804. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16805. ["Next Field" org-cycle (org-at-table-p)]
  16806. ["Previous Field" org-shifttab (org-at-table-p)]
  16807. ["Next Row" org-return (org-at-table-p)]
  16808. "--"
  16809. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16810. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16811. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16812. "--"
  16813. ("Column"
  16814. ["Move Column Left" org-metaleft (org-at-table-p)]
  16815. ["Move Column Right" org-metaright (org-at-table-p)]
  16816. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16817. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16818. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16819. ("Row"
  16820. ["Move Row Up" org-metaup (org-at-table-p)]
  16821. ["Move Row Down" org-metadown (org-at-table-p)]
  16822. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16823. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16824. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16825. "--"
  16826. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16827. ("Rectangle"
  16828. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16829. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16830. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16831. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16832. "--"
  16833. ("Calculate"
  16834. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16835. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16836. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16837. "--"
  16838. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16839. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16840. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16841. "--"
  16842. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16843. "--"
  16844. ["Sum Column/Rectangle" org-table-sum
  16845. (or (org-at-table-p) (org-region-active-p))]
  16846. ["Which Column?" org-table-current-column (org-at-table-p)])
  16847. ["Debug Formulas"
  16848. org-table-toggle-formula-debugger
  16849. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16850. ["Show Col/Row Numbers"
  16851. org-table-toggle-coordinate-overlays
  16852. :style toggle
  16853. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16854. "--"
  16855. ["Create" org-table-create (not (org-at-table-p))]
  16856. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16857. ["Import from File" org-table-import (not (org-at-table-p))]
  16858. ["Export to File" org-table-export (org-at-table-p)]
  16859. "--"
  16860. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16861. "--"
  16862. ("Plot"
  16863. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16864. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16865. (defun org-info (&optional node)
  16866. "Read documentation for Org in the info system.
  16867. With optional NODE, go directly to that node."
  16868. (interactive)
  16869. (info (format "(org)%s" (or node ""))))
  16870. (defun org-browse-news ()
  16871. "Browse the news for the latest major release."
  16872. (interactive)
  16873. (browse-url "https://orgmode.org/Changes.html"))
  16874. ;;;###autoload
  16875. (defun org-submit-bug-report ()
  16876. "Submit a bug report on Org via mail.
  16877. Don't hesitate to report any problems or inaccurate documentation.
  16878. If you don't have setup sending mail from (X)Emacs, please copy the
  16879. output buffer into your mail program, as it gives us important
  16880. information about your Org version and configuration."
  16881. (interactive)
  16882. (require 'reporter)
  16883. (defvar reporter-prompt-for-summary-p)
  16884. (org-load-modules-maybe)
  16885. (org-require-autoloaded-modules)
  16886. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16887. (reporter-submit-bug-report
  16888. "emacs-orgmode@gnu.org"
  16889. (org-version nil 'full)
  16890. (let (list)
  16891. (save-window-excursion
  16892. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16893. (delete-other-windows)
  16894. (erase-buffer)
  16895. (insert "You are about to submit a bug report to the Org mailing list.
  16896. If your report is about Org installation, please read this section:
  16897. https://orgmode.org/org.html#Installation
  16898. Please read https://orgmode.org/org.html#Feedback on how to make
  16899. a good report, it will help Org contributors fixing your problem.
  16900. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16901. if the issue you are about to raise has already been dealt with.
  16902. We also would like to add your full Org and Outline configuration
  16903. to the bug report. It will help us debugging the issue.
  16904. *HOWEVER*, some variables you have customized may contain private
  16905. information. The names of customers, colleagues, or friends, might
  16906. appear in the form of file names, tags, todo states or search strings.
  16907. If you answer \"yes\" to the prompt, you might want to check and remove
  16908. such private information before sending the email.")
  16909. (add-text-properties (point-min) (point-max) '(face org-warning))
  16910. (when (yes-or-no-p "Include your Org configuration ")
  16911. (mapatoms
  16912. (lambda (v)
  16913. (and (boundp v)
  16914. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16915. (or (and (symbol-value v)
  16916. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16917. (and
  16918. (get v 'custom-type) (get v 'standard-value)
  16919. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16920. (push v list)))))
  16921. (kill-buffer (get-buffer "*Warn about privacy*"))
  16922. list))
  16923. nil nil
  16924. "Remember to cover the basics, that is, what you expected to happen and
  16925. what in fact did happen. You don't know how to make a good report? See
  16926. https://orgmode.org/manual/Feedback.html#Feedback
  16927. Your bug report will be posted to the Org mailing list.
  16928. ------------------------------------------------------------------------")
  16929. (save-excursion
  16930. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16931. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16932. (defun org-install-agenda-files-menu ()
  16933. "Install agenda file menu."
  16934. (let ((bl (buffer-list)))
  16935. (save-excursion
  16936. (while bl
  16937. (set-buffer (pop bl))
  16938. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16939. (when (derived-mode-p 'org-mode)
  16940. (easy-menu-change
  16941. '("Org") "File List for Agenda"
  16942. (append
  16943. (list
  16944. ["Edit File List" (org-edit-agenda-file-list) t]
  16945. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16946. ["Remove Current File from List" org-remove-file t]
  16947. ["Cycle through agenda files" org-cycle-agenda-files t]
  16948. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16949. "--")
  16950. (mapcar 'org-file-menu-entry
  16951. ;; Prevent initialization from failing.
  16952. (ignore-errors (org-agenda-files t)))))))))
  16953. ;;;; Documentation
  16954. (defun org-require-autoloaded-modules ()
  16955. (interactive)
  16956. (mapc #'require
  16957. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16958. org-table org-timer)))
  16959. ;;;###autoload
  16960. (defun org-reload (&optional uncompiled)
  16961. "Reload all Org Lisp files.
  16962. With prefix arg UNCOMPILED, load the uncompiled versions."
  16963. (interactive "P")
  16964. (require 'loadhist)
  16965. (let* ((org-dir (org-find-library-dir "org"))
  16966. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16967. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16968. (remove-re (format "\\`%s\\'"
  16969. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16970. (feats (delete-dups
  16971. (mapcar 'file-name-sans-extension
  16972. (mapcar 'file-name-nondirectory
  16973. (delq nil
  16974. (mapcar 'feature-file
  16975. features))))))
  16976. (lfeat (append
  16977. (sort
  16978. (setq feats
  16979. (delq nil (mapcar
  16980. (lambda (f)
  16981. (if (and (string-match feature-re f)
  16982. (not (string-match remove-re f)))
  16983. f nil))
  16984. feats)))
  16985. 'string-lessp)
  16986. (list "org-version" "org")))
  16987. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16988. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16989. load-uncore load-misses)
  16990. (setq load-misses
  16991. (delq 't
  16992. (mapcar (lambda (f)
  16993. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16994. (and (string= org-dir contrib-dir)
  16995. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16996. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16997. (push f load-uncore)
  16998. 't)
  16999. f))
  17000. lfeat)))
  17001. (when load-uncore
  17002. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17003. (if (> (length load-uncore) 1) "s were" " was")
  17004. (reverse load-uncore)))
  17005. (if load-misses
  17006. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17007. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17008. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17009. ;;;###autoload
  17010. (defun org-customize ()
  17011. "Call the customize function with org as argument."
  17012. (interactive)
  17013. (org-load-modules-maybe)
  17014. (org-require-autoloaded-modules)
  17015. (customize-browse 'org))
  17016. (defun org-create-customize-menu ()
  17017. "Create a full customization menu for Org mode, insert it into the menu."
  17018. (interactive)
  17019. (org-load-modules-maybe)
  17020. (org-require-autoloaded-modules)
  17021. (easy-menu-change
  17022. '("Org") "Customize"
  17023. `(["Browse Org group" org-customize t]
  17024. "--"
  17025. ,(customize-menu-create 'org)
  17026. ["Set" Custom-set t]
  17027. ["Save" Custom-save t]
  17028. ["Reset to Current" Custom-reset-current t]
  17029. ["Reset to Saved" Custom-reset-saved t]
  17030. ["Reset to Standard Settings" Custom-reset-standard t]))
  17031. (message "\"Org\"-menu now contains full customization menu"))
  17032. ;;;; Miscellaneous stuff
  17033. ;;; Generally useful functions
  17034. (defun org-in-clocktable-p ()
  17035. "Check if the cursor is in a clocktable."
  17036. (let ((pos (point)) start)
  17037. (save-excursion
  17038. (end-of-line 1)
  17039. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17040. (setq start (match-beginning 0))
  17041. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17042. (>= (match-end 0) pos)
  17043. start))))
  17044. (defun org-in-verbatim-emphasis ()
  17045. (save-match-data
  17046. (and (org-in-regexp org-verbatim-re 2)
  17047. (>= (point) (match-beginning 3))
  17048. (<= (point) (match-end 4)))))
  17049. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17050. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17051. (if (and marker (marker-buffer marker)
  17052. (buffer-live-p (marker-buffer marker)))
  17053. (progn
  17054. (pop-to-buffer-same-window (marker-buffer marker))
  17055. (when (or (> marker (point-max)) (< marker (point-min)))
  17056. (widen))
  17057. (goto-char marker)
  17058. (org-show-context 'org-goto))
  17059. (if bookmark
  17060. (bookmark-jump bookmark)
  17061. (error "Cannot find location"))))
  17062. (defun org-quote-csv-field (s)
  17063. "Quote field for inclusion in CSV material."
  17064. (if (string-match "[\",]" s)
  17065. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17066. s))
  17067. (defun org-force-self-insert (N)
  17068. "Needed to enforce self-insert under remapping."
  17069. (interactive "p")
  17070. (self-insert-command N))
  17071. (defun org-quote-vert (s)
  17072. "Replace \"|\" with \"\\vert\"."
  17073. (while (string-match "|" s)
  17074. (setq s (replace-match "\\vert" t t s)))
  17075. s)
  17076. (defun org-uuidgen-p (s)
  17077. "Is S an ID created by UUIDGEN?"
  17078. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17079. (defun org-in-src-block-p (&optional inside)
  17080. "Whether point is in a code source block.
  17081. When INSIDE is non-nil, don't consider we are within a source
  17082. block when point is at #+BEGIN_SRC or #+END_SRC."
  17083. (let ((case-fold-search t))
  17084. (or (and (eq (get-char-property (point) 'src-block) t))
  17085. (and (not inside)
  17086. (save-match-data
  17087. (save-excursion
  17088. (beginning-of-line)
  17089. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17090. (defun org-context ()
  17091. "Return a list of contexts of the current cursor position.
  17092. If several contexts apply, all are returned.
  17093. Each context entry is a list with a symbol naming the context, and
  17094. two positions indicating start and end of the context. Possible
  17095. contexts are:
  17096. :headline anywhere in a headline
  17097. :headline-stars on the leading stars in a headline
  17098. :todo-keyword on a TODO keyword (including DONE) in a headline
  17099. :tags on the TAGS in a headline
  17100. :priority on the priority cookie in a headline
  17101. :item on the first line of a plain list item
  17102. :item-bullet on the bullet/number of a plain list item
  17103. :checkbox on the checkbox in a plain list item
  17104. :table in an Org table
  17105. :table-special on a special filed in a table
  17106. :table-table in a table.el table
  17107. :clocktable in a clocktable
  17108. :src-block in a source block
  17109. :link on a hyperlink
  17110. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17111. :latex-fragment on a LaTeX fragment
  17112. :latex-preview on a LaTeX fragment with overlaid preview image
  17113. This function expects the position to be visible because it uses font-lock
  17114. faces as a help to recognize the following contexts: :table-special, :link,
  17115. and :keyword."
  17116. (let* ((f (get-text-property (point) 'face))
  17117. (faces (if (listp f) f (list f)))
  17118. (case-fold-search t)
  17119. (p (point)) clist o)
  17120. ;; First the large context
  17121. (cond
  17122. ((org-at-heading-p t)
  17123. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17124. (when (progn
  17125. (beginning-of-line 1)
  17126. (looking-at org-todo-line-tags-regexp))
  17127. (push (org-point-in-group p 1 :headline-stars) clist)
  17128. (push (org-point-in-group p 2 :todo-keyword) clist)
  17129. (push (org-point-in-group p 4 :tags) clist))
  17130. (goto-char p)
  17131. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17132. (when (looking-at "\\[#[A-Z0-9]\\]")
  17133. (push (org-point-in-group p 0 :priority) clist)))
  17134. ((org-at-item-p)
  17135. (push (org-point-in-group p 2 :item-bullet) clist)
  17136. (push (list :item (point-at-bol)
  17137. (save-excursion (org-end-of-item) (point)))
  17138. clist)
  17139. (and (org-at-item-checkbox-p)
  17140. (push (org-point-in-group p 0 :checkbox) clist)))
  17141. ((org-at-table-p)
  17142. (push (list :table (org-table-begin) (org-table-end)) clist)
  17143. (when (memq 'org-formula faces)
  17144. (push (list :table-special
  17145. (previous-single-property-change p 'face)
  17146. (next-single-property-change p 'face))
  17147. clist)))
  17148. ((org-at-table-p 'any)
  17149. (push (list :table-table) clist)))
  17150. (goto-char p)
  17151. (let ((case-fold-search t))
  17152. ;; New the "medium" contexts: clocktables, source blocks
  17153. (cond ((org-in-clocktable-p)
  17154. (push (list :clocktable
  17155. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17156. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17157. (match-beginning 1))
  17158. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17159. (match-end 0)))
  17160. clist))
  17161. ((org-in-src-block-p)
  17162. (push (list :src-block
  17163. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17164. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17165. (match-beginning 1))
  17166. (and (search-forward "#+END_SRC" nil t)
  17167. (match-beginning 0)))
  17168. clist))))
  17169. (goto-char p)
  17170. ;; Now the small context
  17171. (cond
  17172. ((org-at-timestamp-p)
  17173. (push (org-point-in-group p 0 :timestamp) clist))
  17174. ((memq 'org-link faces)
  17175. (push (list :link
  17176. (previous-single-property-change p 'face)
  17177. (next-single-property-change p 'face))
  17178. clist))
  17179. ((memq 'org-special-keyword faces)
  17180. (push (list :keyword
  17181. (previous-single-property-change p 'face)
  17182. (next-single-property-change p 'face))
  17183. clist))
  17184. ((setq o (cl-some
  17185. (lambda (o)
  17186. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17187. o))
  17188. (overlays-at (point))))
  17189. (push (list :latex-fragment
  17190. (overlay-start o) (overlay-end o))
  17191. clist)
  17192. (push (list :latex-preview
  17193. (overlay-start o) (overlay-end o))
  17194. clist))
  17195. ((org-inside-LaTeX-fragment-p)
  17196. ;; FIXME: positions wrong.
  17197. (push (list :latex-fragment (point) (point)) clist)))
  17198. (setq clist (nreverse (delq nil clist)))
  17199. clist))
  17200. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17201. "Non-nil when point is between matches of START-RE and END-RE.
  17202. Also return a non-nil value when point is on one of the matches.
  17203. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17204. buffer positions. Default values are the positions of headlines
  17205. surrounding the point.
  17206. The functions returns a cons cell whose car (resp. cdr) is the
  17207. position before START-RE (resp. after END-RE)."
  17208. (save-match-data
  17209. (let ((pos (point))
  17210. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17211. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17212. beg end)
  17213. (save-excursion
  17214. ;; Point is on a block when on START-RE or if START-RE can be
  17215. ;; found before it...
  17216. (and (or (org-in-regexp start-re)
  17217. (re-search-backward start-re limit-up t))
  17218. (setq beg (match-beginning 0))
  17219. ;; ... and END-RE after it...
  17220. (goto-char (match-end 0))
  17221. (re-search-forward end-re limit-down t)
  17222. (> (setq end (match-end 0)) pos)
  17223. ;; ... without another START-RE in-between.
  17224. (goto-char (match-beginning 0))
  17225. (not (re-search-backward start-re (1+ beg) t))
  17226. ;; Return value.
  17227. (cons beg end))))))
  17228. (defun org-in-block-p (names)
  17229. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17230. NAMES is a list of strings containing names of blocks.
  17231. Return first block name matched, or nil. Beware that in case of
  17232. nested blocks, the returned name may not belong to the closest
  17233. block from point."
  17234. (save-match-data
  17235. (catch 'exit
  17236. (let ((case-fold-search t)
  17237. (lim-up (save-excursion (outline-previous-heading)))
  17238. (lim-down (save-excursion (outline-next-heading))))
  17239. (dolist (name names)
  17240. (let ((n (regexp-quote name)))
  17241. (when (org-between-regexps-p
  17242. (concat "^[ \t]*#\\+begin_" n)
  17243. (concat "^[ \t]*#\\+end_" n)
  17244. lim-up lim-down)
  17245. (throw 'exit n)))))
  17246. nil)))
  17247. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17248. "Call `multi-occur' with buffers for all agenda files."
  17249. (interactive "sOrg-files matching: ")
  17250. (let* ((files (org-agenda-files))
  17251. (tnames (mapcar #'file-truename files))
  17252. (extra org-agenda-text-search-extra-files))
  17253. (when (eq (car extra) 'agenda-archives)
  17254. (setq extra (cdr extra))
  17255. (setq files (org-add-archive-files files)))
  17256. (dolist (f extra)
  17257. (unless (member (file-truename f) tnames)
  17258. (unless (member f files) (setq files (append files (list f))))
  17259. (setq tnames (append tnames (list (file-truename f))))))
  17260. (multi-occur
  17261. (mapcar (lambda (x)
  17262. (with-current-buffer
  17263. ;; FIXME: Why not just (find-file-noselect x)?
  17264. ;; Is it to avoid the "revert buffer" prompt?
  17265. (or (get-file-buffer x) (find-file-noselect x))
  17266. (widen)
  17267. (current-buffer)))
  17268. files)
  17269. regexp)))
  17270. (add-hook 'occur-mode-find-occurrence-hook
  17271. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17272. (defun org-occur-link-in-agenda-files ()
  17273. "Create a link and search for it in the agendas.
  17274. The link is not stored in `org-stored-links', it is just created
  17275. for the search purpose."
  17276. (interactive)
  17277. (let ((link (condition-case nil
  17278. (org-store-link nil)
  17279. (error "Unable to create a link to here"))))
  17280. (org-occur-in-agenda-files (regexp-quote link))))
  17281. (defun org-back-over-empty-lines ()
  17282. "Move backwards over whitespace, to the beginning of the first empty line.
  17283. Returns the number of empty lines passed."
  17284. (let ((pos (point)))
  17285. (if (cdr (assq 'heading org-blank-before-new-entry))
  17286. (skip-chars-backward " \t\n\r")
  17287. (unless (eobp)
  17288. (forward-line -1)))
  17289. (beginning-of-line 2)
  17290. (goto-char (min (point) pos))
  17291. (count-lines (point) pos)))
  17292. ;;; TODO: Only called once, from ox-odt which should probably use
  17293. ;;; org-export-inline-image-p or something.
  17294. (defun org-file-image-p (file)
  17295. "Return non-nil if FILE is an image."
  17296. (save-match-data
  17297. (string-match (image-file-name-regexp) file)))
  17298. (defun org-get-cursor-date (&optional with-time)
  17299. "Return the date at cursor in as a time.
  17300. This works in the calendar and in the agenda, anywhere else it just
  17301. returns the current time.
  17302. If WITH-TIME is non-nil, returns the time of the event at point (in
  17303. the agenda) or the current time of the day; otherwise returns the
  17304. earliest time on the cursor date that Org treats as that date
  17305. (bearing in mind `org-extend-today-until')."
  17306. (let (date day defd tp hod mod)
  17307. (when with-time
  17308. (setq tp (get-text-property (point) 'time))
  17309. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17310. (setq hod (string-to-number (match-string 1 tp))
  17311. mod (string-to-number (match-string 2 tp))))
  17312. (or tp (let ((now (decode-time)))
  17313. (setq hod (nth 2 now)
  17314. mod (nth 1 now)))))
  17315. (cond
  17316. ((eq major-mode 'calendar-mode)
  17317. (setq date (calendar-cursor-to-date)
  17318. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17319. (nth 1 date) (nth 0 date) (nth 2 date))))
  17320. ((eq major-mode 'org-agenda-mode)
  17321. (setq day (get-text-property (point) 'day))
  17322. (when day
  17323. (setq date (calendar-gregorian-from-absolute day)
  17324. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17325. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17326. (or defd (current-time))))
  17327. (defun org-mark-subtree (&optional up)
  17328. "Mark the current subtree.
  17329. This puts point at the start of the current subtree, and mark at
  17330. the end. If a numeric prefix UP is given, move up into the
  17331. hierarchy of headlines by UP levels before marking the subtree."
  17332. (interactive "P")
  17333. (org-with-limited-levels
  17334. (cond ((org-at-heading-p) (beginning-of-line))
  17335. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17336. (t (outline-previous-visible-heading 1))))
  17337. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17338. (if (called-interactively-p 'any)
  17339. (call-interactively 'org-mark-element)
  17340. (org-mark-element)))
  17341. ;;; Indentation
  17342. (defvar org-element-greater-elements)
  17343. (defun org--get-expected-indentation (element contentsp)
  17344. "Expected indentation column for current line, according to ELEMENT.
  17345. ELEMENT is an element containing point. CONTENTSP is non-nil
  17346. when indentation is to be computed according to contents of
  17347. ELEMENT."
  17348. (let ((type (org-element-type element))
  17349. (start (org-element-property :begin element))
  17350. (post-affiliated (org-element-property :post-affiliated element)))
  17351. (org-with-wide-buffer
  17352. (cond
  17353. (contentsp
  17354. (cl-case type
  17355. ((diary-sexp footnote-definition) 0)
  17356. ((headline inlinetask nil)
  17357. (if (not org-adapt-indentation) 0
  17358. (let ((level (org-current-level)))
  17359. (if level (1+ level) 0))))
  17360. ((item plain-list) (org-list-item-body-column post-affiliated))
  17361. (t
  17362. (goto-char start)
  17363. (current-indentation))))
  17364. ((memq type '(headline inlinetask nil))
  17365. (if (org-match-line "[ \t]*$")
  17366. (org--get-expected-indentation element t)
  17367. 0))
  17368. ((memq type '(diary-sexp footnote-definition)) 0)
  17369. ;; First paragraph of a footnote definition or an item.
  17370. ;; Indent like parent.
  17371. ((< (line-beginning-position) start)
  17372. (org--get-expected-indentation
  17373. (org-element-property :parent element) t))
  17374. ;; At first line: indent according to previous sibling, if any,
  17375. ;; ignoring footnote definitions and inline tasks, or parent's
  17376. ;; contents.
  17377. ((and ( = (line-beginning-position) start)
  17378. (eq org-adapt-indentation t))
  17379. (catch 'exit
  17380. (while t
  17381. (if (= (point-min) start) (throw 'exit 0)
  17382. (goto-char (1- start))
  17383. (let* ((previous (org-element-at-point))
  17384. (parent previous))
  17385. (while (and parent (<= (org-element-property :end parent) start))
  17386. (setq previous parent
  17387. parent (org-element-property :parent parent)))
  17388. (cond
  17389. ((not previous) (throw 'exit 0))
  17390. ((> (org-element-property :end previous) start)
  17391. (throw 'exit (org--get-expected-indentation previous t)))
  17392. ((memq (org-element-type previous)
  17393. '(footnote-definition inlinetask))
  17394. (setq start (org-element-property :begin previous)))
  17395. (t (goto-char (org-element-property :begin previous))
  17396. (throw 'exit
  17397. (if (bolp) (current-indentation)
  17398. ;; At first paragraph in an item or
  17399. ;; a footnote definition.
  17400. (org--get-expected-indentation
  17401. (org-element-property :parent previous) t))))))))))
  17402. ;; Otherwise, move to the first non-blank line above.
  17403. (t
  17404. (beginning-of-line)
  17405. (let ((pos (point)))
  17406. (skip-chars-backward " \r\t\n")
  17407. (cond
  17408. ;; Two blank lines end a footnote definition or a plain
  17409. ;; list. When we indent an empty line after them, the
  17410. ;; containing list or footnote definition is over, so it
  17411. ;; qualifies as a previous sibling. Therefore, we indent
  17412. ;; like its first line.
  17413. ((and (memq type '(footnote-definition plain-list))
  17414. (> (count-lines (point) pos) 2))
  17415. (goto-char start)
  17416. (current-indentation))
  17417. ;; Line above is the first one of a paragraph at the
  17418. ;; beginning of an item or a footnote definition. Indent
  17419. ;; like parent.
  17420. ((< (line-beginning-position) start)
  17421. (org--get-expected-indentation
  17422. (org-element-property :parent element) t))
  17423. ;; Line above is the beginning of an element, i.e., point
  17424. ;; was originally on the blank lines between element's start
  17425. ;; and contents.
  17426. ((= (line-beginning-position) post-affiliated)
  17427. (org--get-expected-indentation element t))
  17428. ;; POS is after contents in a greater element. Indent like
  17429. ;; the beginning of the element.
  17430. ((and (memq type org-element-greater-elements)
  17431. (let ((cend (org-element-property :contents-end element)))
  17432. (and cend (<= cend pos))))
  17433. ;; As a special case, if point is at the end of a footnote
  17434. ;; definition or an item, indent like the very last element
  17435. ;; within. If that last element is an item, indent like
  17436. ;; its contents.
  17437. (if (memq type '(footnote-definition item plain-list))
  17438. (let ((last (org-element-at-point)))
  17439. (goto-char pos)
  17440. (org--get-expected-indentation
  17441. last (eq (org-element-type last) 'item)))
  17442. (goto-char start)
  17443. (current-indentation)))
  17444. ;; In any other case, indent like the current line.
  17445. (t (current-indentation)))))
  17446. ;; Finally, no indentation is needed, fall back to 0.
  17447. (t (current-indentation))))))
  17448. (defun org--align-node-property ()
  17449. "Align node property at point.
  17450. Alignment is done according to `org-property-format', which see."
  17451. (when (save-excursion
  17452. (beginning-of-line)
  17453. (looking-at org-property-re))
  17454. (replace-match
  17455. (concat (match-string 4)
  17456. (org-trim
  17457. (format org-property-format (match-string 1) (match-string 3))))
  17458. t t)))
  17459. (defun org-indent-line ()
  17460. "Indent line depending on context.
  17461. Indentation is done according to the following rules:
  17462. - Footnote definitions, diary sexps, headlines and inline tasks
  17463. have to start at column 0.
  17464. - On the very first line of an element, consider, in order, the
  17465. next rules until one matches:
  17466. 1. If there's a sibling element before, ignoring footnote
  17467. definitions and inline tasks, indent like its first line.
  17468. 2. If element has a parent, indent like its contents. More
  17469. precisely, if parent is an item, indent after the bullet.
  17470. Else, indent like parent's first line.
  17471. 3. Otherwise, indent relatively to current level, if
  17472. `org-adapt-indentation' is `t', or to left margin.
  17473. - On a blank line at the end of an element, indent according to
  17474. the type of the element. More precisely
  17475. 1. If element is a plain list, an item, or a footnote
  17476. definition, indent like the very last element within.
  17477. 2. If element is a paragraph, indent like its last non blank
  17478. line.
  17479. 3. Otherwise, indent like its very first line.
  17480. - In the code part of a source block, use language major mode
  17481. to indent current line if `org-src-tab-acts-natively' is
  17482. non-nil. If it is nil, do nothing.
  17483. - Otherwise, indent like the first non-blank line above.
  17484. The function doesn't indent an item as it could break the whole
  17485. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17486. `\\[org-shiftmetaright]'.
  17487. Also align node properties according to `org-property-format'."
  17488. (interactive)
  17489. (unless (or (org-at-heading-p)
  17490. (and (eq org-adapt-indentation 'headline-data)
  17491. (not (or (org-at-clock-log-p)
  17492. (org-at-planning-p)))
  17493. (save-excursion
  17494. (beginning-of-line 1)
  17495. (skip-chars-backward "\n")
  17496. (or (org-at-heading-p)
  17497. (looking-back ":END:.*" (point-at-bol))))))
  17498. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17499. (type (org-element-type element)))
  17500. (cond ((and (memq type '(plain-list item))
  17501. (= (line-beginning-position)
  17502. (org-element-property :post-affiliated element)))
  17503. nil)
  17504. ((and (eq type 'latex-environment)
  17505. (>= (point) (org-element-property :post-affiliated element))
  17506. (< (point)
  17507. (org-with-point-at (org-element-property :end element)
  17508. (skip-chars-backward " \t\n")
  17509. (line-beginning-position 2))))
  17510. nil)
  17511. ((and (eq type 'src-block)
  17512. org-src-tab-acts-natively
  17513. (> (line-beginning-position)
  17514. (org-element-property :post-affiliated element))
  17515. (< (line-beginning-position)
  17516. (org-with-point-at (org-element-property :end element)
  17517. (skip-chars-backward " \t\n")
  17518. (line-beginning-position))))
  17519. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17520. (t
  17521. (let ((column (org--get-expected-indentation element nil)))
  17522. ;; Preserve current column.
  17523. (if (<= (current-column) (current-indentation))
  17524. (indent-line-to column)
  17525. (save-excursion (indent-line-to column))))
  17526. ;; Align node property. Also preserve current column.
  17527. (when (eq type 'node-property)
  17528. (let ((column (current-column)))
  17529. (org--align-node-property)
  17530. (org-move-to-column column))))))))
  17531. (defun org-indent-region (start end)
  17532. "Indent each non-blank line in the region.
  17533. Called from a program, START and END specify the region to
  17534. indent. The function will not indent contents of example blocks,
  17535. verse blocks and export blocks as leading white spaces are
  17536. assumed to be significant there."
  17537. (interactive "r")
  17538. (save-excursion
  17539. (goto-char start)
  17540. (skip-chars-forward " \r\t\n")
  17541. (unless (eobp) (beginning-of-line))
  17542. (let ((indent-to
  17543. (lambda (ind pos)
  17544. ;; Set IND as indentation for all lines between point and
  17545. ;; POS. Blank lines are ignored. Leave point after POS
  17546. ;; once done.
  17547. (let ((limit (copy-marker pos)))
  17548. (while (< (point) limit)
  17549. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17550. (forward-line))
  17551. (set-marker limit nil))))
  17552. (end (copy-marker end)))
  17553. (while (< (point) end)
  17554. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17555. (let* ((element (org-element-at-point))
  17556. (type (org-element-type element))
  17557. (element-end (copy-marker (org-element-property :end element)))
  17558. (ind (org--get-expected-indentation element nil)))
  17559. (cond
  17560. ;; Element indented as a single block. Example blocks
  17561. ;; preserving indentation are a special case since the
  17562. ;; "contents" must not be indented whereas the block
  17563. ;; boundaries can.
  17564. ((or (memq type '(export-block latex-environment))
  17565. (and (eq type 'example-block)
  17566. (not
  17567. (or org-src-preserve-indentation
  17568. (org-element-property :preserve-indent element)))))
  17569. (let ((offset (- ind (current-indentation))))
  17570. (unless (zerop offset)
  17571. (indent-rigidly (org-element-property :begin element)
  17572. (org-element-property :end element)
  17573. offset)))
  17574. (goto-char element-end))
  17575. ;; Elements indented line wise. Be sure to exclude
  17576. ;; example blocks (preserving indentation) and source
  17577. ;; blocks from this category as they are treated
  17578. ;; specially later.
  17579. ((or (memq type '(paragraph table table-row))
  17580. (not (or (org-element-property :contents-begin element)
  17581. (memq type '(example-block src-block)))))
  17582. (when (eq type 'node-property)
  17583. (org--align-node-property)
  17584. (beginning-of-line))
  17585. (funcall indent-to ind (min element-end end)))
  17586. ;; Elements consisting of three parts: before the
  17587. ;; contents, the contents, and after the contents. The
  17588. ;; contents are treated specially, according to the
  17589. ;; element type, or not indented at all. Other parts are
  17590. ;; indented as a single block.
  17591. (t
  17592. (let* ((post (copy-marker
  17593. (org-element-property :post-affiliated element)))
  17594. (cbeg
  17595. (copy-marker
  17596. (cond
  17597. ((not (org-element-property :contents-begin element))
  17598. ;; Fake contents for source blocks.
  17599. (org-with-wide-buffer
  17600. (goto-char post)
  17601. (line-beginning-position 2)))
  17602. ((memq type '(footnote-definition item plain-list))
  17603. ;; Contents in these elements could start on
  17604. ;; the same line as the beginning of the
  17605. ;; element. Make sure we start indenting
  17606. ;; from the second line.
  17607. (org-with-wide-buffer
  17608. (goto-char post)
  17609. (end-of-line)
  17610. (skip-chars-forward " \r\t\n")
  17611. (if (eobp) (point) (line-beginning-position))))
  17612. (t (org-element-property :contents-begin element)))))
  17613. (cend (copy-marker
  17614. (or (org-element-property :contents-end element)
  17615. ;; Fake contents for source blocks.
  17616. (org-with-wide-buffer
  17617. (goto-char element-end)
  17618. (skip-chars-backward " \r\t\n")
  17619. (line-beginning-position)))
  17620. t)))
  17621. ;; Do not change items indentation individually as it
  17622. ;; might break the list as a whole. On the other
  17623. ;; hand, when at a plain list, indent it as a whole.
  17624. (cond ((eq type 'plain-list)
  17625. (let ((offset (- ind (current-indentation))))
  17626. (unless (zerop offset)
  17627. (indent-rigidly (org-element-property :begin element)
  17628. (org-element-property :end element)
  17629. offset))
  17630. (goto-char cbeg)))
  17631. ((eq type 'item) (goto-char cbeg))
  17632. (t (funcall indent-to ind (min cbeg end))))
  17633. (when (< (point) end)
  17634. (cl-case type
  17635. ((example-block verse-block))
  17636. (src-block
  17637. ;; In a source block, indent source code
  17638. ;; according to language major mode, but only if
  17639. ;; `org-src-tab-acts-natively' is non-nil.
  17640. (when (and (< (point) end) org-src-tab-acts-natively)
  17641. (ignore-errors
  17642. (org-babel-do-in-edit-buffer
  17643. (indent-region (point-min) (point-max))))))
  17644. (t (org-indent-region (point) (min cend end))))
  17645. (goto-char (min cend end))
  17646. (when (< (point) end)
  17647. (funcall indent-to ind (min element-end end))))
  17648. (set-marker post nil)
  17649. (set-marker cbeg nil)
  17650. (set-marker cend nil))))
  17651. (set-marker element-end nil))))
  17652. (set-marker end nil))))
  17653. (defun org-indent-drawer ()
  17654. "Indent the drawer at point."
  17655. (interactive)
  17656. (unless (save-excursion
  17657. (beginning-of-line)
  17658. (looking-at-p org-drawer-regexp))
  17659. (user-error "Not at a drawer"))
  17660. (let ((element (org-element-at-point)))
  17661. (unless (memq (org-element-type element) '(drawer property-drawer))
  17662. (user-error "Not at a drawer"))
  17663. (org-with-wide-buffer
  17664. (org-indent-region (org-element-property :begin element)
  17665. (org-element-property :end element))))
  17666. (message "Drawer at point indented"))
  17667. (defun org-indent-block ()
  17668. "Indent the block at point."
  17669. (interactive)
  17670. (unless (save-excursion
  17671. (beginning-of-line)
  17672. (let ((case-fold-search t))
  17673. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17674. (user-error "Not at a block"))
  17675. (let ((element (org-element-at-point)))
  17676. (unless (memq (org-element-type element)
  17677. '(comment-block center-block dynamic-block example-block
  17678. export-block quote-block special-block
  17679. src-block verse-block))
  17680. (user-error "Not at a block"))
  17681. (org-with-wide-buffer
  17682. (org-indent-region (org-element-property :begin element)
  17683. (org-element-property :end element))))
  17684. (message "Block at point indented"))
  17685. ;;; Filling
  17686. ;; We use our own fill-paragraph and auto-fill functions.
  17687. ;; `org-fill-paragraph' relies on adaptive filling and context
  17688. ;; checking. Appropriate `fill-prefix' is computed with
  17689. ;; `org-adaptive-fill-function'.
  17690. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17691. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17692. ;; `org-adaptive-fill-function' value. Internally,
  17693. ;; `org-comment-line-break-function' breaks the line.
  17694. ;; `org-setup-filling' installs filling and auto-filling related
  17695. ;; variables during `org-mode' initialization.
  17696. (defun org-setup-filling ()
  17697. (require 'org-element)
  17698. ;; Prevent auto-fill from inserting unwanted new items.
  17699. (when (boundp 'fill-nobreak-predicate)
  17700. (setq-local
  17701. fill-nobreak-predicate
  17702. (org-uniquify
  17703. (append fill-nobreak-predicate
  17704. '(org-fill-line-break-nobreak-p
  17705. org-fill-n-macro-as-item-nobreak-p
  17706. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17707. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17708. (setq-local paragraph-start paragraph-ending)
  17709. (setq-local paragraph-separate paragraph-ending))
  17710. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17711. (setq-local auto-fill-inhibit-regexp nil)
  17712. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17713. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17714. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17715. (defun org-fill-line-break-nobreak-p ()
  17716. "Non-nil when a new line at point would create an Org line break."
  17717. (save-excursion
  17718. (skip-chars-backward " \t")
  17719. (skip-chars-backward "\\\\")
  17720. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17721. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17722. "Non-nil when a new line at point would split a timestamp."
  17723. (and (org-at-timestamp-p 'lax)
  17724. (not (looking-at org-ts-regexp-both))))
  17725. (defun org-fill-n-macro-as-item-nobreak-p ()
  17726. "Non-nil when a new line at point would create a new list."
  17727. ;; During export, a "n" macro followed by a dot or a closing
  17728. ;; parenthesis can end up being parsed as a new list item.
  17729. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17730. (defun org-adaptive-fill-function ()
  17731. "Compute a fill prefix for the current line.
  17732. Return fill prefix, as a string, or nil if current line isn't
  17733. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17734. matches in paragraphs or comments, use it."
  17735. (org-with-wide-buffer
  17736. (unless (org-at-heading-p)
  17737. (let* ((p (line-beginning-position))
  17738. (element (save-excursion
  17739. (beginning-of-line)
  17740. (org-element-at-point)))
  17741. (type (org-element-type element))
  17742. (post-affiliated (org-element-property :post-affiliated element)))
  17743. (unless (< p post-affiliated)
  17744. (cl-case type
  17745. (comment
  17746. (save-excursion
  17747. (beginning-of-line)
  17748. (looking-at "[ \t]*")
  17749. (concat (match-string 0) "# ")))
  17750. (footnote-definition "")
  17751. ((item plain-list)
  17752. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17753. (paragraph
  17754. ;; Fill prefix is usually the same as the current line,
  17755. ;; unless the paragraph is at the beginning of an item.
  17756. (let ((parent (org-element-property :parent element)))
  17757. (save-excursion
  17758. (beginning-of-line)
  17759. (cond ((eq (org-element-type parent) 'item)
  17760. (make-string (org-list-item-body-column
  17761. (org-element-property :begin parent))
  17762. ?\s))
  17763. ((and adaptive-fill-regexp
  17764. ;; Locally disable
  17765. ;; `adaptive-fill-function' to let
  17766. ;; `fill-context-prefix' handle
  17767. ;; `adaptive-fill-regexp' variable.
  17768. (let (adaptive-fill-function)
  17769. (fill-context-prefix
  17770. post-affiliated
  17771. (org-element-property :end element)))))
  17772. ((looking-at "[ \t]+") (match-string 0))
  17773. (t "")))))
  17774. (comment-block
  17775. ;; Only fill contents if P is within block boundaries.
  17776. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17777. (forward-line)
  17778. (point)))
  17779. (cend (save-excursion
  17780. (goto-char (org-element-property :end element))
  17781. (skip-chars-backward " \r\t\n")
  17782. (line-beginning-position))))
  17783. (when (and (>= p cbeg) (< p cend))
  17784. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17785. (match-string 0)
  17786. ""))))))))))
  17787. (defun org-fill-element (&optional justify)
  17788. "Fill element at point, when applicable.
  17789. This function only applies to comment blocks, comments, example
  17790. blocks and paragraphs. Also, as a special case, re-align table
  17791. when point is at one.
  17792. If JUSTIFY is non-nil (interactively, with prefix argument),
  17793. justify as well. If `sentence-end-double-space' is non-nil, then
  17794. period followed by one space does not end a sentence, so don't
  17795. break a line there. The variable `fill-column' controls the
  17796. width for filling.
  17797. For convenience, when point is at a plain list, an item or
  17798. a footnote definition, try to fill the first paragraph within."
  17799. (with-syntax-table org-mode-transpose-word-syntax-table
  17800. ;; Move to end of line in order to get the first paragraph within
  17801. ;; a plain list or a footnote definition.
  17802. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17803. ;; First check if point is in a blank line at the beginning of
  17804. ;; the buffer. In that case, ignore filling.
  17805. (cl-case (org-element-type element)
  17806. ;; Use major mode filling function is source blocks.
  17807. (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
  17808. ;; Align Org tables, leave table.el tables as-is.
  17809. (table-row (org-table-align) t)
  17810. (table
  17811. (when (eq (org-element-property :type element) 'org)
  17812. (save-excursion
  17813. (goto-char (org-element-property :post-affiliated element))
  17814. (org-table-align)))
  17815. t)
  17816. (paragraph
  17817. ;; Paragraphs may contain `line-break' type objects.
  17818. (let ((beg (max (point-min)
  17819. (org-element-property :contents-begin element)))
  17820. (end (min (point-max)
  17821. (org-element-property :contents-end element))))
  17822. ;; Do nothing if point is at an affiliated keyword.
  17823. (if (< (line-end-position) beg) t
  17824. ;; Fill paragraph, taking line breaks into account.
  17825. (save-excursion
  17826. (goto-char beg)
  17827. (let ((cuts (list beg)))
  17828. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17829. (when (eq 'line-break
  17830. (org-element-type
  17831. (save-excursion (backward-char)
  17832. (org-element-context))))
  17833. (push (point) cuts)))
  17834. (dolist (c (delq end cuts))
  17835. (fill-region-as-paragraph c end justify)
  17836. (setq end c))))
  17837. t)))
  17838. ;; Contents of `comment-block' type elements should be
  17839. ;; filled as plain text, but only if point is within block
  17840. ;; markers.
  17841. (comment-block
  17842. (let* ((case-fold-search t)
  17843. (beg (save-excursion
  17844. (goto-char (org-element-property :begin element))
  17845. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17846. (forward-line)
  17847. (point)))
  17848. (end (save-excursion
  17849. (goto-char (org-element-property :end element))
  17850. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17851. (line-beginning-position))))
  17852. (if (or (< (point) beg) (> (point) end)) t
  17853. (fill-region-as-paragraph
  17854. (save-excursion (end-of-line)
  17855. (re-search-backward "^[ \t]*$" beg 'move)
  17856. (line-beginning-position))
  17857. (save-excursion (beginning-of-line)
  17858. (re-search-forward "^[ \t]*$" end 'move)
  17859. (line-beginning-position))
  17860. justify))))
  17861. ;; Fill comments.
  17862. (comment
  17863. (let ((begin (org-element-property :post-affiliated element))
  17864. (end (org-element-property :end element)))
  17865. (when (and (>= (point) begin) (<= (point) end))
  17866. (let ((begin (save-excursion
  17867. (end-of-line)
  17868. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17869. (progn (forward-line) (point))
  17870. begin)))
  17871. (end (save-excursion
  17872. (end-of-line)
  17873. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17874. (1- (line-beginning-position))
  17875. (skip-chars-backward " \r\t\n")
  17876. (line-end-position)))))
  17877. ;; Do not fill comments when at a blank line.
  17878. (when (> end begin)
  17879. (let ((fill-prefix
  17880. (save-excursion
  17881. (beginning-of-line)
  17882. (looking-at "[ \t]*#")
  17883. (let ((comment-prefix (match-string 0)))
  17884. (goto-char (match-end 0))
  17885. (if (looking-at adaptive-fill-regexp)
  17886. (concat comment-prefix (match-string 0))
  17887. (concat comment-prefix " "))))))
  17888. (save-excursion
  17889. (fill-region-as-paragraph begin end justify))))))
  17890. t))
  17891. ;; Ignore every other element.
  17892. (otherwise t)))))
  17893. (defun org-fill-paragraph (&optional justify region)
  17894. "Fill element at point, when applicable.
  17895. This function only applies to comment blocks, comments, example
  17896. blocks and paragraphs. Also, as a special case, re-align table
  17897. when point is at one.
  17898. For convenience, when point is at a plain list, an item or
  17899. a footnote definition, try to fill the first paragraph within.
  17900. If JUSTIFY is non-nil (interactively, with prefix argument),
  17901. justify as well. If `sentence-end-double-space' is non-nil, then
  17902. period followed by one space does not end a sentence, so don't
  17903. break a line there. The variable `fill-column' controls the
  17904. width for filling.
  17905. The REGION argument is non-nil if called interactively; in that
  17906. case, if Transient Mark mode is enabled and the mark is active,
  17907. fill each of the elements in the active region, instead of just
  17908. filling the current element."
  17909. (interactive (progn
  17910. (barf-if-buffer-read-only)
  17911. (list (when current-prefix-arg 'full) t)))
  17912. (let ((hash (and (not (buffer-modified-p))
  17913. (org-buffer-hash))))
  17914. (cond
  17915. ((and region transient-mark-mode mark-active
  17916. (not (eq (region-beginning) (region-end))))
  17917. (let ((origin (point-marker))
  17918. (start (region-beginning)))
  17919. (unwind-protect
  17920. (progn
  17921. (goto-char (region-end))
  17922. (skip-chars-backward " \t\n")
  17923. (while (> (point) start)
  17924. (org-fill-element justify)
  17925. (org-backward-paragraph)))
  17926. (goto-char origin)
  17927. (set-marker origin nil))))
  17928. (t
  17929. (save-excursion
  17930. (when (org-match-line "[ \t]*$")
  17931. (skip-chars-forward " \t\n"))
  17932. (org-fill-element justify))))
  17933. ;; If we didn't change anything in the buffer (and the buffer was
  17934. ;; previously unmodified), then flip the modification status back
  17935. ;; to "unchanged".
  17936. (when (and hash (equal hash (org-buffer-hash)))
  17937. (set-buffer-modified-p nil))))
  17938. (defun org-auto-fill-function ()
  17939. "Auto-fill function."
  17940. ;; Check if auto-filling is meaningful.
  17941. (let ((fc (current-fill-column)))
  17942. (when (and fc (> (current-column) fc))
  17943. (let* ((fill-prefix (org-adaptive-fill-function))
  17944. ;; Enforce empty fill prefix, if required. Otherwise, it
  17945. ;; will be computed again.
  17946. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17947. (when fill-prefix (do-auto-fill))))))
  17948. (defun org-comment-line-break-function (&optional soft)
  17949. "Break line at point and indent, continuing comment if within one.
  17950. The inserted newline is marked hard if variable
  17951. `use-hard-newlines' is true, unless optional argument SOFT is
  17952. non-nil."
  17953. (if soft (insert-and-inherit ?\n) (newline 1))
  17954. (save-excursion (forward-char -1) (delete-horizontal-space))
  17955. (delete-horizontal-space)
  17956. (indent-to-left-margin)
  17957. (insert-before-markers-and-inherit fill-prefix))
  17958. ;;; Fixed Width Areas
  17959. (defun org-toggle-fixed-width ()
  17960. "Toggle fixed-width markup.
  17961. Add or remove fixed-width markup on current line, whenever it
  17962. makes sense. Return an error otherwise.
  17963. If a region is active and if it contains only fixed-width areas
  17964. or blank lines, remove all fixed-width markup in it. If the
  17965. region contains anything else, convert all non-fixed-width lines
  17966. to fixed-width ones.
  17967. Blank lines at the end of the region are ignored unless the
  17968. region only contains such lines."
  17969. (interactive)
  17970. (if (not (org-region-active-p))
  17971. ;; No region:
  17972. ;;
  17973. ;; Remove fixed width marker only in a fixed-with element.
  17974. ;;
  17975. ;; Add fixed width maker in paragraphs, in blank lines after
  17976. ;; elements or at the beginning of a headline or an inlinetask,
  17977. ;; and before any one-line elements (e.g., a clock).
  17978. (progn
  17979. (beginning-of-line)
  17980. (let* ((element (org-element-at-point))
  17981. (type (org-element-type element)))
  17982. (cond
  17983. ((and (eq type 'fixed-width)
  17984. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17985. (replace-match
  17986. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17987. ((and (memq type '(babel-call clock comment diary-sexp headline
  17988. horizontal-rule keyword paragraph
  17989. planning))
  17990. (<= (org-element-property :post-affiliated element) (point)))
  17991. (skip-chars-forward " \t")
  17992. (insert ": "))
  17993. ((and (looking-at-p "[ \t]*$")
  17994. (or (eq type 'inlinetask)
  17995. (save-excursion
  17996. (skip-chars-forward " \r\t\n")
  17997. (<= (org-element-property :end element) (point)))))
  17998. (delete-region (point) (line-end-position))
  17999. (org-indent-line)
  18000. (insert ": "))
  18001. (t (user-error "Cannot insert a fixed-width line here")))))
  18002. ;; Region active.
  18003. (let* ((begin (save-excursion
  18004. (goto-char (region-beginning))
  18005. (line-beginning-position)))
  18006. (end (copy-marker
  18007. (save-excursion
  18008. (goto-char (region-end))
  18009. (unless (eolp) (beginning-of-line))
  18010. (if (save-excursion (re-search-backward "\\S-" begin t))
  18011. (progn (skip-chars-backward " \r\t\n") (point))
  18012. (point)))))
  18013. (all-fixed-width-p
  18014. (catch 'not-all-p
  18015. (save-excursion
  18016. (goto-char begin)
  18017. (skip-chars-forward " \r\t\n")
  18018. (when (eobp) (throw 'not-all-p nil))
  18019. (while (< (point) end)
  18020. (let ((element (org-element-at-point)))
  18021. (if (eq (org-element-type element) 'fixed-width)
  18022. (goto-char (org-element-property :end element))
  18023. (throw 'not-all-p nil))))
  18024. t))))
  18025. (if all-fixed-width-p
  18026. (save-excursion
  18027. (goto-char begin)
  18028. (while (< (point) end)
  18029. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18030. (replace-match
  18031. "" nil nil nil
  18032. (if (= (line-end-position) (match-end 0)) 0 1)))
  18033. (forward-line)))
  18034. (let ((min-ind (point-max)))
  18035. ;; Find minimum indentation across all lines.
  18036. (save-excursion
  18037. (goto-char begin)
  18038. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18039. (setq min-ind 0)
  18040. (catch 'zerop
  18041. (while (< (point) end)
  18042. (unless (looking-at-p "[ \t]*$")
  18043. (let ((ind (current-indentation)))
  18044. (setq min-ind (min min-ind ind))
  18045. (when (zerop ind) (throw 'zerop t))))
  18046. (forward-line)))))
  18047. ;; Loop over all lines and add fixed-width markup everywhere
  18048. ;; but in fixed-width lines.
  18049. (save-excursion
  18050. (goto-char begin)
  18051. (while (< (point) end)
  18052. (cond
  18053. ((org-at-heading-p)
  18054. (insert ": ")
  18055. (forward-line)
  18056. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18057. (insert ":")
  18058. (forward-line)))
  18059. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18060. (let* ((element (org-element-at-point))
  18061. (element-end (org-element-property :end element)))
  18062. (if (eq (org-element-type element) 'fixed-width)
  18063. (progn (goto-char element-end)
  18064. (skip-chars-backward " \r\t\n")
  18065. (forward-line))
  18066. (let ((limit (min end element-end)))
  18067. (while (< (point) limit)
  18068. (org-move-to-column min-ind t)
  18069. (insert ": ")
  18070. (forward-line))))))
  18071. (t
  18072. (org-move-to-column min-ind t)
  18073. (insert ": ")
  18074. (forward-line)))))))
  18075. (set-marker end nil))))
  18076. ;;; Blocks
  18077. (defun org-block-map (function &optional start end)
  18078. "Call FUNCTION at the head of all source blocks in the current buffer.
  18079. Optional arguments START and END can be used to limit the range."
  18080. (let ((start (or start (point-min)))
  18081. (end (or end (point-max))))
  18082. (save-excursion
  18083. (goto-char start)
  18084. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18085. (save-excursion
  18086. (save-match-data
  18087. (goto-char (match-beginning 0))
  18088. (funcall function)))))))
  18089. (defun org-next-block (arg &optional backward block-regexp)
  18090. "Jump to the next block.
  18091. With a prefix argument ARG, jump forward ARG many blocks.
  18092. When BACKWARD is non-nil, jump to the previous block.
  18093. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18094. Match data is set according to this regexp when the function
  18095. returns.
  18096. Return point at beginning of the opening line of found block.
  18097. Throw an error if no block is found."
  18098. (interactive "p")
  18099. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18100. (case-fold-search t)
  18101. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18102. (count (or arg 1))
  18103. (origin (point))
  18104. last-element)
  18105. (if backward (beginning-of-line) (end-of-line))
  18106. (while (and (> count 0) (funcall search-fn re nil t))
  18107. (let ((element (save-excursion
  18108. (goto-char (match-beginning 0))
  18109. (save-match-data (org-element-at-point)))))
  18110. (when (and (memq (org-element-type element)
  18111. '(center-block comment-block dynamic-block
  18112. example-block export-block quote-block
  18113. special-block src-block verse-block))
  18114. (<= (match-beginning 0)
  18115. (org-element-property :post-affiliated element)))
  18116. (setq last-element element)
  18117. (cl-decf count))))
  18118. (if (= count 0)
  18119. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18120. (save-match-data (org-show-context)))
  18121. (goto-char origin)
  18122. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18123. (defun org-previous-block (arg &optional block-regexp)
  18124. "Jump to the previous block.
  18125. With a prefix argument ARG, jump backward ARG many source blocks.
  18126. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18127. (interactive "p")
  18128. (org-next-block arg t block-regexp))
  18129. ;;; Comments
  18130. ;; Org comments syntax is quite complex. It requires the entire line
  18131. ;; to be just a comment. Also, even with the right syntax at the
  18132. ;; beginning of line, some elements (e.g., verse-block or
  18133. ;; example-block) don't accept comments. Usual Emacs comment commands
  18134. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18135. ;; Org still relies on `comment-dwim', but cannot trust
  18136. ;; `comment-only-p'. So, `comment-region-function' and
  18137. ;; `uncomment-region-function' both point
  18138. ;; to`org-comment-or-uncomment-region'. Eventually,
  18139. ;; `org-insert-comment' takes care of insertion of comments at the
  18140. ;; beginning of line.
  18141. ;; `org-setup-comments-handling' install comments related variables
  18142. ;; during `org-mode' initialization.
  18143. (defun org-setup-comments-handling ()
  18144. (interactive)
  18145. (setq-local comment-use-syntax nil)
  18146. (setq-local comment-start "# ")
  18147. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18148. (setq-local comment-insert-comment-function 'org-insert-comment)
  18149. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18150. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18151. (defun org-insert-comment ()
  18152. "Insert an empty comment above current line.
  18153. If the line is empty, insert comment at its beginning. When
  18154. point is within a source block, comment according to the related
  18155. major mode."
  18156. (if (let ((element (org-element-at-point)))
  18157. (and (eq (org-element-type element) 'src-block)
  18158. (< (save-excursion
  18159. (goto-char (org-element-property :post-affiliated element))
  18160. (line-end-position))
  18161. (point))
  18162. (> (save-excursion
  18163. (goto-char (org-element-property :end element))
  18164. (skip-chars-backward " \r\t\n")
  18165. (line-beginning-position))
  18166. (point))))
  18167. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18168. (beginning-of-line)
  18169. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18170. (open-line 1))
  18171. (org-indent-line)
  18172. (insert "# ")))
  18173. (defvar comment-empty-lines) ; From newcomment.el.
  18174. (defun org-comment-or-uncomment-region (beg end &rest _)
  18175. "Comment or uncomment each non-blank line in the region.
  18176. Uncomment each non-blank line between BEG and END if it only
  18177. contains commented lines. Otherwise, comment them. If region is
  18178. strictly within a source block, use appropriate comment syntax."
  18179. (if (let ((element (org-element-at-point)))
  18180. (and (eq (org-element-type element) 'src-block)
  18181. (< (save-excursion
  18182. (goto-char (org-element-property :post-affiliated element))
  18183. (line-end-position))
  18184. beg)
  18185. (>= (save-excursion
  18186. (goto-char (org-element-property :end element))
  18187. (skip-chars-backward " \r\t\n")
  18188. (line-beginning-position))
  18189. end)))
  18190. ;; Translate region boundaries for the Org buffer to the source
  18191. ;; buffer.
  18192. (let ((offset (- end beg)))
  18193. (save-excursion
  18194. (goto-char beg)
  18195. (org-babel-do-in-edit-buffer
  18196. (comment-or-uncomment-region (point) (+ offset (point))))))
  18197. (save-restriction
  18198. ;; Restrict region
  18199. (narrow-to-region (save-excursion (goto-char beg)
  18200. (skip-chars-forward " \r\t\n" end)
  18201. (line-beginning-position))
  18202. (save-excursion (goto-char end)
  18203. (skip-chars-backward " \r\t\n" beg)
  18204. (line-end-position)))
  18205. (let ((uncommentp
  18206. ;; UNCOMMENTP is non-nil when every non blank line between
  18207. ;; BEG and END is a comment.
  18208. (save-excursion
  18209. (goto-char (point-min))
  18210. (while (and (not (eobp))
  18211. (let ((element (org-element-at-point)))
  18212. (and (eq (org-element-type element) 'comment)
  18213. (goto-char (min (point-max)
  18214. (org-element-property
  18215. :end element)))))))
  18216. (eobp))))
  18217. (if uncommentp
  18218. ;; Only blank lines and comments in region: uncomment it.
  18219. (save-excursion
  18220. (goto-char (point-min))
  18221. (while (not (eobp))
  18222. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18223. (replace-match "" nil nil nil 1))
  18224. (forward-line)))
  18225. ;; Comment each line in region.
  18226. (let ((min-indent (point-max)))
  18227. ;; First find the minimum indentation across all lines.
  18228. (save-excursion
  18229. (goto-char (point-min))
  18230. (while (and (not (eobp)) (not (zerop min-indent)))
  18231. (unless (looking-at "[ \t]*$")
  18232. (setq min-indent (min min-indent (current-indentation))))
  18233. (forward-line)))
  18234. ;; Then loop over all lines.
  18235. (save-excursion
  18236. (goto-char (point-min))
  18237. (while (not (eobp))
  18238. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18239. ;; Don't get fooled by invisible text (e.g. link path)
  18240. ;; when moving to column MIN-INDENT.
  18241. (let ((buffer-invisibility-spec nil))
  18242. (org-move-to-column min-indent t))
  18243. (insert comment-start))
  18244. (forward-line)))))))))
  18245. (defun org-comment-dwim (_arg)
  18246. "Call the comment command you mean.
  18247. Call `org-toggle-comment' if on a heading, otherwise call
  18248. `comment-dwim', within a source edit buffer if needed."
  18249. (interactive "*P")
  18250. (cond ((org-at-heading-p)
  18251. (call-interactively #'org-toggle-comment))
  18252. ((org-in-src-block-p)
  18253. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18254. (t (call-interactively #'comment-dwim))))
  18255. ;;; Timestamps API
  18256. ;; This section contains tools to operate on, or create, timestamp
  18257. ;; objects, as returned by, e.g. `org-element-context'.
  18258. (defun org-timestamp-from-string (s)
  18259. "Convert Org timestamp S, as a string, into a timestamp object.
  18260. Return nil if S is not a valid timestamp string."
  18261. (when (org-string-nw-p s)
  18262. (with-temp-buffer
  18263. (save-excursion (insert s))
  18264. (org-element-timestamp-parser))))
  18265. (defun org-timestamp-from-time (time &optional with-time inactive)
  18266. "Convert a time value into a timestamp object.
  18267. TIME is an Emacs internal time representation, as returned, e.g.,
  18268. by `current-time'.
  18269. When optional argument WITH-TIME is non-nil, return a timestamp
  18270. object with a time part, i.e., with hours and minutes.
  18271. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18272. return an active timestamp."
  18273. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18274. (org-element-create 'timestamp
  18275. (list :type (if inactive 'inactive 'active)
  18276. :year-start year
  18277. :month-start month
  18278. :day-start day
  18279. :hour-start (and with-time hour)
  18280. :minute-start (and with-time minute)))))
  18281. (defun org-timestamp-to-time (timestamp &optional end)
  18282. "Convert TIMESTAMP object into an Emacs internal time value.
  18283. Use end of date range or time range when END is non-nil.
  18284. Otherwise, use its start."
  18285. (apply #'encode-time 0
  18286. (mapcar
  18287. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18288. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18289. '(:minute-start :hour-start :day-start :month-start
  18290. :year-start)))))
  18291. (defun org-timestamp-has-time-p (timestamp)
  18292. "Non-nil when TIMESTAMP has a time specified."
  18293. (org-element-property :hour-start timestamp))
  18294. (defun org-timestamp-format (timestamp format &optional end utc)
  18295. "Format a TIMESTAMP object into a string.
  18296. FORMAT is a format specifier to be passed to
  18297. `format-time-string'.
  18298. When optional argument END is non-nil, use end of date-range or
  18299. time-range, if possible.
  18300. When optional argument UTC is non-nil, time is be expressed as
  18301. Universal Time."
  18302. (format-time-string format (org-timestamp-to-time timestamp end)
  18303. (and utc t)))
  18304. (defun org-timestamp-split-range (timestamp &optional end)
  18305. "Extract a TIMESTAMP object from a date or time range.
  18306. END, when non-nil, means extract the end of the range.
  18307. Otherwise, extract its start.
  18308. Return a new timestamp object."
  18309. (let ((type (org-element-property :type timestamp)))
  18310. (if (memq type '(active inactive diary)) timestamp
  18311. (let ((split-ts (org-element-copy timestamp)))
  18312. ;; Set new type.
  18313. (org-element-put-property
  18314. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18315. ;; Copy start properties over end properties if END is
  18316. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18317. (let ((p-alist '((:minute-start . :minute-end)
  18318. (:hour-start . :hour-end)
  18319. (:day-start . :day-end)
  18320. (:month-start . :month-end)
  18321. (:year-start . :year-end))))
  18322. (dolist (p-cell p-alist)
  18323. (org-element-put-property
  18324. split-ts
  18325. (funcall (if end #'car #'cdr) p-cell)
  18326. (org-element-property
  18327. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18328. ;; Eventually refresh `:raw-value'.
  18329. (org-element-put-property split-ts :raw-value nil)
  18330. (org-element-put-property
  18331. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18332. (defun org-timestamp-translate (timestamp &optional boundary)
  18333. "Translate TIMESTAMP object to custom format.
  18334. Format string is defined in `org-time-stamp-custom-formats',
  18335. which see.
  18336. When optional argument BOUNDARY is non-nil, it is either the
  18337. symbol `start' or `end'. In this case, only translate the
  18338. starting or ending part of TIMESTAMP if it is a date or time
  18339. range. Otherwise, translate both parts.
  18340. Return timestamp as-is if `org-display-custom-times' is nil or if
  18341. it has a `diary' type."
  18342. (let ((type (org-element-property :type timestamp)))
  18343. (if (or (not org-display-custom-times) (eq type 'diary))
  18344. (org-element-interpret-data timestamp)
  18345. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18346. org-time-stamp-custom-formats)))
  18347. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18348. (concat (org-timestamp-format timestamp fmt)
  18349. "--"
  18350. (org-timestamp-format timestamp fmt t))
  18351. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18352. ;;; Other stuff
  18353. (defvar reftex-docstruct-symbol)
  18354. (defvar org--rds)
  18355. (defun org-reftex-citation ()
  18356. "Use reftex-citation to insert a citation into the buffer.
  18357. This looks for a line like
  18358. #+BIBLIOGRAPHY: foo plain option:-d
  18359. and derives from it that foo.bib is the bibliography file relevant
  18360. for this document. It then installs the necessary environment for RefTeX
  18361. to work in this buffer and calls `reftex-citation' to insert a citation
  18362. into the buffer.
  18363. Export of such citations to both LaTeX and HTML is handled by the contributed
  18364. package ox-bibtex by Taru Karttunen."
  18365. (interactive)
  18366. (let ((reftex-docstruct-symbol 'org--rds)
  18367. org--rds bib)
  18368. (org-with-wide-buffer
  18369. (let ((case-fold-search t)
  18370. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18371. (if (not (save-excursion
  18372. (or (re-search-forward re nil t)
  18373. (re-search-backward re nil t))))
  18374. (user-error "No bibliography defined in file")
  18375. (setq bib (concat (match-string 1) ".bib")
  18376. org--rds (list (list 'bib bib))))))
  18377. (call-interactively 'reftex-citation)))
  18378. ;;;; Functions extending outline functionality
  18379. (defun org-beginning-of-line (&optional n)
  18380. "Go to the beginning of the current visible line.
  18381. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18382. symbol `reversed', on the first attempt move to where the
  18383. headline text starts, and only move to beginning of line when the
  18384. cursor is already before the start of the text of the headline.
  18385. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18386. start of the text on the second attempt.
  18387. With argument N not nil or 1, move forward N - 1 lines first."
  18388. (interactive "^p")
  18389. (let ((origin (point))
  18390. (special (pcase org-special-ctrl-a/e
  18391. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18392. deactivate-mark)
  18393. ;; First move to a visible line.
  18394. (if (bound-and-true-p visual-line-mode)
  18395. (beginning-of-visual-line n)
  18396. (move-beginning-of-line n)
  18397. ;; `move-beginning-of-line' may leave point after invisible
  18398. ;; characters if line starts with such of these (e.g., with
  18399. ;; a link at column 0). Really move to the beginning of the
  18400. ;; current visible line.
  18401. (beginning-of-line))
  18402. (cond
  18403. ;; No special behavior. Point is already at the beginning of
  18404. ;; a line, logical or visual.
  18405. ((not special))
  18406. ;; `beginning-of-visual-line' left point before logical beginning
  18407. ;; of line: point is at the beginning of a visual line. Bail
  18408. ;; out.
  18409. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18410. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18411. ;; At a headline, special position is before the title, but
  18412. ;; after any TODO keyword or priority cookie.
  18413. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18414. (line-end-position)))
  18415. (bol (point)))
  18416. (if (eq special 'reversed)
  18417. (when (and (= origin bol) (eq last-command this-command))
  18418. (goto-char refpos))
  18419. (when (or (> origin refpos) (= origin bol))
  18420. (goto-char refpos)))))
  18421. ((and (looking-at org-list-full-item-re)
  18422. (memq (org-element-type (save-match-data (org-element-at-point)))
  18423. '(item plain-list)))
  18424. ;; Set special position at first white space character after
  18425. ;; bullet, and check-box, if any.
  18426. (let ((after-bullet
  18427. (let ((box (match-end 3)))
  18428. (cond ((not box) (match-end 1))
  18429. ((eq (char-after box) ?\s) (1+ box))
  18430. (t box)))))
  18431. (if (eq special 'reversed)
  18432. (when (and (= (point) origin) (eq last-command this-command))
  18433. (goto-char after-bullet))
  18434. (when (or (> origin after-bullet) (= (point) origin))
  18435. (goto-char after-bullet)))))
  18436. ;; No special context. Point is already at beginning of line.
  18437. (t nil))))
  18438. (defun org-end-of-line (&optional n)
  18439. "Go to the end of the line, but before ellipsis, if any.
  18440. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18441. symbol `reversed', ignore tags on the first attempt, and only
  18442. move to after the tags when the cursor is already beyond the end
  18443. of the headline.
  18444. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18445. on the second attempt.
  18446. With argument N not nil or 1, move forward N - 1 lines first."
  18447. (interactive "^p")
  18448. (let ((origin (point))
  18449. (special (pcase org-special-ctrl-a/e
  18450. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18451. deactivate-mark)
  18452. ;; First move to a visible line.
  18453. (if (bound-and-true-p visual-line-mode)
  18454. (beginning-of-visual-line n)
  18455. (move-beginning-of-line n))
  18456. (cond
  18457. ;; At a headline, with tags.
  18458. ((and special
  18459. (save-excursion
  18460. (beginning-of-line)
  18461. (let ((case-fold-search nil))
  18462. (looking-at org-complex-heading-regexp)))
  18463. (match-end 5))
  18464. (let ((tags (save-excursion
  18465. (goto-char (match-beginning 5))
  18466. (skip-chars-backward " \t")
  18467. (point)))
  18468. (visual-end (and (bound-and-true-p visual-line-mode)
  18469. (save-excursion
  18470. (end-of-visual-line)
  18471. (point)))))
  18472. ;; If `end-of-visual-line' brings us before end of line or
  18473. ;; even tags, i.e., the headline spans over multiple visual
  18474. ;; lines, move there.
  18475. (cond ((and visual-end
  18476. (< visual-end tags)
  18477. (<= origin visual-end))
  18478. (goto-char visual-end))
  18479. ((eq special 'reversed)
  18480. (if (and (= origin (line-end-position))
  18481. (eq this-command last-command))
  18482. (goto-char tags)
  18483. (end-of-line)))
  18484. (t
  18485. (if (or (< origin tags) (= origin (line-end-position)))
  18486. (goto-char tags)
  18487. (end-of-line))))))
  18488. ((bound-and-true-p visual-line-mode)
  18489. (let ((bol (line-beginning-position)))
  18490. (end-of-visual-line)
  18491. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18492. ;; end of a line, backtrack and use `end-of-line' instead.
  18493. (when (/= bol (line-beginning-position))
  18494. (goto-char bol)
  18495. (end-of-line))))
  18496. (t (end-of-line)))))
  18497. (defun org-backward-sentence (&optional _arg)
  18498. "Go to beginning of sentence, or beginning of table field.
  18499. This will call `backward-sentence' or `org-table-beginning-of-field',
  18500. depending on context."
  18501. (interactive)
  18502. (let* ((element (org-element-at-point))
  18503. (contents-begin (org-element-property :contents-begin element))
  18504. (table (org-element-lineage element '(table) t)))
  18505. (if (and table
  18506. (> (point) contents-begin)
  18507. (<= (point) (org-element-property :contents-end table)))
  18508. (call-interactively #'org-table-beginning-of-field)
  18509. (save-restriction
  18510. (when (and contents-begin
  18511. (< (point-min) contents-begin)
  18512. (> (point) contents-begin))
  18513. (narrow-to-region contents-begin
  18514. (org-element-property :contents-end element)))
  18515. (call-interactively #'backward-sentence)))))
  18516. (defun org-forward-sentence (&optional _arg)
  18517. "Go to end of sentence, or end of table field.
  18518. This will call `forward-sentence' or `org-table-end-of-field',
  18519. depending on context."
  18520. (interactive)
  18521. (if (and (org-at-heading-p)
  18522. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18523. (save-restriction
  18524. (narrow-to-region (line-beginning-position) (line-end-position))
  18525. (call-interactively #'forward-sentence))
  18526. (let* ((element (org-element-at-point))
  18527. (contents-end (org-element-property :contents-end element))
  18528. (table (org-element-lineage element '(table) t)))
  18529. (if (and table
  18530. (>= (point) (org-element-property :contents-begin table))
  18531. (< (point) contents-end))
  18532. (call-interactively #'org-table-end-of-field)
  18533. (save-restriction
  18534. (when (and contents-end
  18535. (> (point-max) contents-end)
  18536. ;; Skip blank lines between elements.
  18537. (< (org-element-property :end element)
  18538. (save-excursion (goto-char contents-end)
  18539. (skip-chars-forward " \r\t\n"))))
  18540. (narrow-to-region (org-element-property :contents-begin element)
  18541. contents-end))
  18542. ;; End of heading is considered as the end of a sentence.
  18543. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18544. (call-interactively #'forward-sentence)))))))
  18545. (defun org-kill-line (&optional _arg)
  18546. "Kill line, to tags or end of line."
  18547. (interactive)
  18548. (cond
  18549. ((or (not org-special-ctrl-k)
  18550. (bolp)
  18551. (not (org-at-heading-p)))
  18552. (when (and (get-char-property (line-end-position) 'invisible)
  18553. org-ctrl-k-protect-subtree
  18554. (or (eq org-ctrl-k-protect-subtree 'error)
  18555. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18556. (user-error
  18557. (substitute-command-keys
  18558. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18559. (call-interactively
  18560. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18561. ((org-match-line org-tag-line-re)
  18562. (let ((end (save-excursion
  18563. (goto-char (match-beginning 1))
  18564. (skip-chars-backward " \t")
  18565. (point))))
  18566. (if (<= end (point)) ;on tags part
  18567. (kill-region (point) (line-end-position))
  18568. (kill-region (point) end)))
  18569. ;; Only align tags when we are still on a heading:
  18570. (if (org-at-heading-p) (org-align-tags)))
  18571. (t (kill-region (point) (line-end-position)))))
  18572. (defun org-yank (&optional arg)
  18573. "Yank. If the kill is a subtree, treat it specially.
  18574. This command will look at the current kill and check if is a single
  18575. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18576. cursor is at the beginning of a line or after the stars of a currently
  18577. empty headline, then the yank is handled specially. How exactly depends
  18578. on the value of the following variables.
  18579. `org-yank-folded-subtrees'
  18580. By default, this variable is non-nil, which results in
  18581. subtree(s) being folded after insertion, except if doing so
  18582. would swallow text after the yanked text.
  18583. `org-yank-adjusted-subtrees'
  18584. When non-nil (the default value is nil), the subtree will be
  18585. promoted or demoted in order to fit into the local outline tree
  18586. structure, which means that the level will be adjusted so that it
  18587. becomes the smaller one of the two *visible* surrounding headings.
  18588. Any prefix to this command will cause `yank' to be called directly with
  18589. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18590. will just
  18591. plainly yank the text as it is.
  18592. \[1] The test checks if the first non-white line is a heading
  18593. and if there are no other headings with fewer stars."
  18594. (interactive "P")
  18595. (org-yank-generic 'yank arg))
  18596. (defun org-yank-generic (command arg)
  18597. "Perform some yank-like command.
  18598. This function implements the behavior described in the `org-yank'
  18599. documentation. However, it has been generalized to work for any
  18600. interactive command with similar behavior."
  18601. ;; pretend to be command COMMAND
  18602. (setq this-command command)
  18603. (if arg
  18604. (call-interactively command)
  18605. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18606. (and (org-kill-is-subtree-p)
  18607. (or (bolp)
  18608. (and (looking-at "[ \t]*$")
  18609. (string-match
  18610. "\\`\\*+\\'"
  18611. (buffer-substring (point-at-bol) (point)))))))
  18612. swallowp)
  18613. (cond
  18614. ((and subtreep org-yank-folded-subtrees)
  18615. (let ((beg (point))
  18616. end)
  18617. (if (and subtreep org-yank-adjusted-subtrees)
  18618. (org-paste-subtree nil nil 'for-yank)
  18619. (call-interactively command))
  18620. (setq end (point))
  18621. (goto-char beg)
  18622. (when (and (bolp) subtreep
  18623. (not (setq swallowp
  18624. (org-yank-folding-would-swallow-text beg end))))
  18625. (org-with-limited-levels
  18626. (or (looking-at org-outline-regexp)
  18627. (re-search-forward org-outline-regexp-bol end t))
  18628. (while (and (< (point) end) (looking-at org-outline-regexp))
  18629. (org-flag-subtree t)
  18630. (org-cycle-show-empty-lines 'folded)
  18631. (condition-case nil
  18632. (outline-forward-same-level 1)
  18633. (error (goto-char end))))))
  18634. (when swallowp
  18635. (message
  18636. "Inserted text not folded because that would swallow text"))
  18637. (goto-char end)
  18638. (skip-chars-forward " \t\n\r")
  18639. (beginning-of-line 1)
  18640. (push-mark beg 'nomsg)))
  18641. ((and subtreep org-yank-adjusted-subtrees)
  18642. (let ((beg (point-at-bol)))
  18643. (org-paste-subtree nil nil 'for-yank)
  18644. (push-mark beg 'nomsg)))
  18645. (t
  18646. (call-interactively command))))))
  18647. (defun org-yank-folding-would-swallow-text (beg end)
  18648. "Would hide-subtree at BEG swallow any text after END?"
  18649. (let (level)
  18650. (org-with-limited-levels
  18651. (save-excursion
  18652. (goto-char beg)
  18653. (when (or (looking-at org-outline-regexp)
  18654. (re-search-forward org-outline-regexp-bol end t))
  18655. (setq level (org-outline-level)))
  18656. (goto-char end)
  18657. (skip-chars-forward " \t\r\n\v\f")
  18658. (not (or (eobp)
  18659. (and (bolp) (looking-at-p org-outline-regexp)
  18660. (<= (org-outline-level) level))))))))
  18661. (defun org-back-to-heading (&optional invisible-ok)
  18662. "Call `outline-back-to-heading', but provide a better error message."
  18663. (condition-case nil
  18664. (outline-back-to-heading invisible-ok)
  18665. (error
  18666. (user-error "Before first headline at position %d in buffer %s"
  18667. (point) (current-buffer)))))
  18668. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18669. "Go back to heading or first point in buffer.
  18670. If point is before first heading go to first point in buffer
  18671. instead of back to heading."
  18672. (condition-case nil
  18673. (outline-back-to-heading invisible-ok)
  18674. (error
  18675. (goto-char (point-min)))))
  18676. (defun org-before-first-heading-p ()
  18677. "Before first heading?"
  18678. (org-with-limited-levels
  18679. (save-excursion
  18680. (end-of-line)
  18681. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18682. (defun org-at-heading-p (&optional _)
  18683. "Non-nil when on a headline."
  18684. (outline-on-heading-p t))
  18685. (defun org-in-commented-heading-p (&optional no-inheritance)
  18686. "Non-nil if point is under a commented heading.
  18687. This function also checks ancestors of the current headline,
  18688. unless optional argument NO-INHERITANCE is non-nil."
  18689. (cond
  18690. ((org-before-first-heading-p) nil)
  18691. ((let ((headline (nth 4 (org-heading-components))))
  18692. (and headline
  18693. (let ((case-fold-search nil))
  18694. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18695. headline)))))
  18696. (no-inheritance nil)
  18697. (t
  18698. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18699. (defun org-in-archived-heading-p (&optional no-inheritance)
  18700. "Non-nil if point is under an archived heading.
  18701. This function also checks ancestors of the current headline,
  18702. unless optional argument NO-INHERITANCE is non-nil."
  18703. (cond
  18704. ((org-before-first-heading-p) nil)
  18705. ((let ((tags (org-get-tags nil 'local)))
  18706. (and tags
  18707. (cl-some (apply-partially #'string= org-archive-tag) tags))))
  18708. (no-inheritance nil)
  18709. (t
  18710. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18711. (defun org-at-comment-p nil
  18712. "Return t if cursor is in a commented line."
  18713. (save-excursion
  18714. (save-match-data
  18715. (beginning-of-line)
  18716. (looking-at org-comment-regexp))))
  18717. (defun org-at-keyword-p nil
  18718. "Return t if cursor is at a keyword-line."
  18719. (save-excursion
  18720. (move-beginning-of-line 1)
  18721. (looking-at org-keyword-regexp)))
  18722. (defun org-at-drawer-p nil
  18723. "Return t if cursor is at a drawer keyword."
  18724. (save-excursion
  18725. (move-beginning-of-line 1)
  18726. (looking-at org-drawer-regexp)))
  18727. (defun org-at-block-p nil
  18728. "Return t if cursor is at a block keyword."
  18729. (save-excursion
  18730. (move-beginning-of-line 1)
  18731. (looking-at org-block-regexp)))
  18732. (defun org-point-at-end-of-empty-headline ()
  18733. "If point is at the end of an empty headline, return t, else nil.
  18734. If the heading only contains a TODO keyword, it is still considered
  18735. empty."
  18736. (let ((case-fold-search nil))
  18737. (and (looking-at "[ \t]*$")
  18738. org-todo-line-regexp
  18739. (save-excursion
  18740. (beginning-of-line)
  18741. (looking-at org-todo-line-regexp)
  18742. (string= (match-string 3) "")))))
  18743. (defun org-at-heading-or-item-p ()
  18744. (or (org-at-heading-p) (org-at-item-p)))
  18745. (defun org-up-heading-all (arg)
  18746. "Move to the heading line of which the present line is a subheading.
  18747. This function considers both visible and invisible heading lines.
  18748. With argument, move up ARG levels."
  18749. (outline-up-heading arg t))
  18750. (defvar-local org--up-heading-cache nil
  18751. "Buffer-local `org-up-heading-safe' cache.")
  18752. (defvar-local org--up-heading-cache-tick nil
  18753. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18754. (defun org-up-heading-safe ()
  18755. "Move to the heading line of which the present line is a subheading.
  18756. This version will not throw an error. It will return the level of the
  18757. headline found, or nil if no higher level is found.
  18758. Also, this function will be a lot faster than `outline-up-heading',
  18759. because it relies on stars being the outline starters. This can really
  18760. make a significant difference in outlines with very many siblings."
  18761. (when (ignore-errors (org-back-to-heading t))
  18762. (let (level-cache)
  18763. (unless org--up-heading-cache
  18764. (setq org--up-heading-cache (make-hash-table)))
  18765. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18766. (setq level-cache (gethash (point) org--up-heading-cache)))
  18767. (when (<= (point-min) (car level-cache) (point-max))
  18768. ;; Parent is inside accessible part of the buffer.
  18769. (progn (goto-char (car level-cache))
  18770. (cdr level-cache)))
  18771. ;; Buffer modified. Invalidate cache.
  18772. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18773. (setq-local org--up-heading-cache-tick
  18774. (buffer-chars-modified-tick))
  18775. (clrhash org--up-heading-cache))
  18776. (let* ((level-up (1- (funcall outline-level)))
  18777. (pos (point))
  18778. (result (and (> level-up 0)
  18779. (re-search-backward
  18780. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18781. (funcall outline-level))))
  18782. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18783. result)))))
  18784. (defun org-up-heading-or-point-min ()
  18785. "Move to the heading line of which the present is a subheading, or point-min.
  18786. This version is needed to make point-min behave like a virtual
  18787. heading of level 0 for property-inheritance. It will return the
  18788. level of the headline found (down to 0) or nil if already at a
  18789. point before the first headline or at point-min."
  18790. (when (ignore-errors (org-back-to-heading t))
  18791. (if (< 1 (funcall outline-level))
  18792. (org-up-heading-safe)
  18793. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18794. (defun org-first-sibling-p ()
  18795. "Is this heading the first child of its parents?"
  18796. (interactive)
  18797. (let ((re org-outline-regexp-bol)
  18798. level l)
  18799. (unless (org-at-heading-p t)
  18800. (user-error "Not at a heading"))
  18801. (setq level (funcall outline-level))
  18802. (save-excursion
  18803. (if (not (re-search-backward re nil t))
  18804. t
  18805. (setq l (funcall outline-level))
  18806. (< l level)))))
  18807. (defun org-goto-sibling (&optional previous)
  18808. "Goto the next sibling, even if it is invisible.
  18809. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18810. when a sibling was found. When none is found, return nil and don't
  18811. move point."
  18812. (let ((fun (if previous 're-search-backward 're-search-forward))
  18813. (pos (point))
  18814. (re org-outline-regexp-bol)
  18815. level l)
  18816. (when (ignore-errors (org-back-to-heading t))
  18817. (setq level (funcall outline-level))
  18818. (catch 'exit
  18819. (or previous (forward-char 1))
  18820. (while (funcall fun re nil t)
  18821. (setq l (funcall outline-level))
  18822. (when (< l level) (goto-char pos) (throw 'exit nil))
  18823. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18824. (goto-char pos)
  18825. nil))))
  18826. (defun org-show-siblings ()
  18827. "Show all siblings of the current headline."
  18828. (save-excursion
  18829. (while (org-goto-sibling) (org-flag-heading nil)))
  18830. (save-excursion
  18831. (while (org-goto-sibling 'previous)
  18832. (org-flag-heading nil))))
  18833. (defun org-goto-first-child ()
  18834. "Goto the first child, even if it is invisible.
  18835. Return t when a child was found. Otherwise don't move point and
  18836. return nil."
  18837. (let (level (pos (point)) (re org-outline-regexp-bol))
  18838. (when (org-back-to-heading-or-point-min t)
  18839. (setq level (org-outline-level))
  18840. (forward-char 1)
  18841. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18842. (progn (goto-char (match-beginning 0)) t)
  18843. (goto-char pos) nil))))
  18844. (defun org-show-hidden-entry ()
  18845. "Show an entry where even the heading is hidden."
  18846. (save-excursion
  18847. (org-show-entry)))
  18848. (defun org-flag-heading (flag &optional entry)
  18849. "Flag the current heading. FLAG non-nil means make invisible.
  18850. When ENTRY is non-nil, show the entire entry."
  18851. (save-excursion
  18852. (org-back-to-heading t)
  18853. ;; Check if we should show the entire entry
  18854. (if (not entry)
  18855. (org-flag-region
  18856. (line-end-position 0) (line-end-position) flag 'outline)
  18857. (org-show-entry)
  18858. (save-excursion
  18859. (and (outline-next-heading)
  18860. (org-flag-heading nil))))))
  18861. (defun org-get-next-sibling ()
  18862. "Move to next heading of the same level, and return point.
  18863. If there is no such heading, return nil.
  18864. This is like outline-next-sibling, but invisible headings are ok."
  18865. (let ((level (funcall outline-level)))
  18866. (outline-next-heading)
  18867. (while (and (not (eobp)) (> (funcall outline-level) level))
  18868. (outline-next-heading))
  18869. (unless (or (eobp) (< (funcall outline-level) level))
  18870. (point))))
  18871. (defun org-get-last-sibling ()
  18872. "Move to previous heading of the same level, and return point.
  18873. If there is no such heading, return nil."
  18874. (let ((opoint (point))
  18875. (level (funcall outline-level)))
  18876. (outline-previous-heading)
  18877. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18878. (while (and (> (funcall outline-level) level)
  18879. (not (bobp)))
  18880. (outline-previous-heading))
  18881. (unless (< (funcall outline-level) level)
  18882. (point)))))
  18883. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18884. "Goto to the end of a subtree."
  18885. ;; This contains an exact copy of the original function, but it uses
  18886. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18887. ;; trees and before first headline. And is uses an invisible-ok argument.
  18888. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18889. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18890. ;; with many children and grandchildren etc, this can be much faster
  18891. ;; than the outline version.
  18892. (org-back-to-heading-or-point-min invisible-ok)
  18893. (let ((first t)
  18894. (level (funcall outline-level)))
  18895. (cond ((= level 0)
  18896. (goto-char (point-max)))
  18897. ((and (derived-mode-p 'org-mode) (< level 1000))
  18898. ;; A true heading (not a plain list item), in Org
  18899. ;; This means we can easily find the end by looking
  18900. ;; only for the right number of stars. Using a regexp to do
  18901. ;; this is so much faster than using a Lisp loop.
  18902. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18903. (forward-char 1)
  18904. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18905. (t
  18906. ;; something else, do it the slow way
  18907. (while (and (not (eobp))
  18908. (or first (> (funcall outline-level) level)))
  18909. (setq first nil)
  18910. (outline-next-heading))))
  18911. (unless to-heading
  18912. (when (memq (preceding-char) '(?\n ?\^M))
  18913. ;; Go to end of line before heading
  18914. (forward-char -1)
  18915. (when (memq (preceding-char) '(?\n ?\^M))
  18916. ;; leave blank line before heading
  18917. (forward-char -1)))))
  18918. (point))
  18919. (defun org-end-of-meta-data (&optional full)
  18920. "Skip planning line and properties drawer in current entry.
  18921. When optional argument FULL is t, also skip planning information,
  18922. clocking lines and any kind of drawer.
  18923. When FULL is non-nil but not t, skip planning information,
  18924. clocking lines and only non-regular drawers, i.e. properties and
  18925. logbook drawers."
  18926. (org-back-to-heading t)
  18927. (forward-line)
  18928. ;; Skip planning information.
  18929. (when (looking-at-p org-planning-line-re) (forward-line))
  18930. ;; Skip property drawer.
  18931. (when (looking-at org-property-drawer-re)
  18932. (goto-char (match-end 0))
  18933. (forward-line))
  18934. ;; When FULL is not nil, skip more.
  18935. (when (and full (not (org-at-heading-p)))
  18936. (catch 'exit
  18937. (let ((end (save-excursion (outline-next-heading) (point)))
  18938. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18939. (while (not (eobp))
  18940. (cond ;; Skip clock lines.
  18941. ((looking-at-p re) (forward-line))
  18942. ;; Skip logbook drawer.
  18943. ((looking-at-p org-logbook-drawer-re)
  18944. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18945. (forward-line)
  18946. (throw 'exit t)))
  18947. ;; When FULL is t, skip regular drawer too.
  18948. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18949. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18950. (forward-line)
  18951. (throw 'exit t)))
  18952. (t (throw 'exit t))))))))
  18953. (defun org--line-fully-invisible-p ()
  18954. "Return non-nil if the current line is fully invisible."
  18955. (let ((line-beg (line-beginning-position))
  18956. (line-pos (1- (line-end-position)))
  18957. (is-invisible t))
  18958. (while (and (< line-beg line-pos) is-invisible)
  18959. (setq is-invisible (org-invisible-p line-pos))
  18960. (setq line-pos (1- line-pos)))
  18961. is-invisible))
  18962. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18963. "Move forward to the ARG'th subheading at same level as this one.
  18964. Stop at the first and last subheadings of a superior heading.
  18965. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18966. non-nil it will also look at invisible ones."
  18967. (interactive "p")
  18968. (let ((backward? (and arg (< arg 0))))
  18969. (if (org-before-first-heading-p)
  18970. (if backward? (goto-char (point-min)) (outline-next-heading))
  18971. (org-back-to-heading invisible-ok)
  18972. (unless backward? (end-of-line)) ;do not match current headline
  18973. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18974. (f (if backward? #'re-search-backward #'re-search-forward))
  18975. (count (if arg (abs arg) 1))
  18976. (result (point)))
  18977. (while (and (> count 0)
  18978. (funcall f org-outline-regexp-bol nil 'move))
  18979. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18980. (cond ((< l level) (setq count 0))
  18981. ((and (= l level)
  18982. (or invisible-ok
  18983. ;; FIXME: See commit a700fadd72 and the
  18984. ;; related discussion on why using
  18985. ;; `org--line-fully-invisible-p' is needed
  18986. ;; here, which is to serve the needs of an
  18987. ;; external package. If the change is
  18988. ;; wrong regarding Org itself, it should
  18989. ;; be removed.
  18990. (not (org--line-fully-invisible-p))))
  18991. (cl-decf count)
  18992. (when (= l level) (setq result (point)))))))
  18993. (goto-char result))
  18994. (beginning-of-line))))
  18995. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18996. "Move backward to the ARG'th subheading at same level as this one.
  18997. Stop at the first and last subheadings of a superior heading."
  18998. (interactive "p")
  18999. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19000. (defun org-next-visible-heading (arg)
  19001. "Move to the next visible heading line.
  19002. With ARG, repeats or can move backward if negative."
  19003. (interactive "p")
  19004. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  19005. (if (< arg 0)
  19006. (beginning-of-line)
  19007. (end-of-line))
  19008. (while (and (< arg 0) (re-search-backward regexp nil :move))
  19009. (unless (bobp)
  19010. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19011. (`(outline . ,o)
  19012. (goto-char (overlay-start o))
  19013. (re-search-backward regexp nil :move))
  19014. (_ nil))))
  19015. (cl-incf arg))
  19016. (while (and (> arg 0) (re-search-forward regexp nil t))
  19017. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19018. (`(outline . ,o)
  19019. (goto-char (overlay-end o))
  19020. (re-search-forward regexp nil :move))
  19021. (_
  19022. (end-of-line)
  19023. nil))) ;leave the loop
  19024. (cl-decf arg))
  19025. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  19026. (defun org-previous-visible-heading (arg)
  19027. "Move to the previous visible heading.
  19028. With ARG, repeats or can move forward if negative."
  19029. (interactive "p")
  19030. (org-next-visible-heading (- arg)))
  19031. (defun org-forward-paragraph (&optional arg)
  19032. "Move forward by a paragraph, or equivalent, unit.
  19033. With argument ARG, do it ARG times;
  19034. a negative argument ARG = -N means move backward N paragraphs.
  19035. The function moves point between two structural
  19036. elements (paragraphs, tables, lists, etc.).
  19037. It also provides the following special moves for convenience:
  19038. - on a table or a property drawer, move to its beginning;
  19039. - on comment, example, export, source and verse blocks, stop
  19040. at blank lines;
  19041. - skip consecutive clocks, diary S-exps, and keywords."
  19042. (interactive "^p")
  19043. (unless arg (setq arg 1))
  19044. (if (< arg 0) (org-backward-paragraph (- arg))
  19045. (while (and (> arg 0) (not (eobp)))
  19046. (org--forward-paragraph-once)
  19047. (cl-decf arg))
  19048. ;; Return moves left.
  19049. arg))
  19050. (defun org-backward-paragraph (&optional arg)
  19051. "Move backward by a paragraph, or equivalent, unit.
  19052. With argument ARG, do it ARG times;
  19053. a negative argument ARG = -N means move forward N paragraphs.
  19054. The function moves point between two structural
  19055. elements (paragraphs, tables, lists, etc.).
  19056. It also provides the following special moves for convenience:
  19057. - on a table or a property drawer, move to its beginning;
  19058. - on comment, example, export, source and verse blocks, stop
  19059. at blank lines;
  19060. - skip consecutive clocks, diary S-exps, and keywords."
  19061. (interactive "^p")
  19062. (unless arg (setq arg 1))
  19063. (if (< arg 0) (org-forward-paragraph (- arg))
  19064. (while (and (> arg 0) (not (bobp)))
  19065. (org--backward-paragraph-once)
  19066. (cl-decf arg))
  19067. ;; Return moves left.
  19068. arg))
  19069. (defun org--paragraph-at-point ()
  19070. "Return paragraph, or equivalent, element at point.
  19071. Paragraph element at point is the element at point, with the
  19072. following special cases:
  19073. - treat table rows (resp. node properties) as the table
  19074. \(resp. property drawer) containing them.
  19075. - treat plain lists with an item every line as a whole.
  19076. - treat consecutive keywords, clocks, and diary-sexps as a single
  19077. block.
  19078. Function may return a real element, or a pseudo-element with type
  19079. `pseudo-paragraph'."
  19080. (let* ((e (org-element-at-point))
  19081. (type (org-element-type e))
  19082. ;; If we need to fake a new pseudo-element, triplet is
  19083. ;;
  19084. ;; (BEG END PARENT)
  19085. ;;
  19086. ;; where BEG and END are element boundaries, and PARENT the
  19087. ;; element containing it, or nil.
  19088. (triplet
  19089. (cond
  19090. ((memq type '(table property-drawer))
  19091. (list (org-element-property :begin e)
  19092. (org-element-property :end e)
  19093. (org-element-property :parent e)))
  19094. ((memq type '(node-property table-row))
  19095. (let ((e (org-element-property :parent e)))
  19096. (list (org-element-property :begin e)
  19097. (org-element-property :end e)
  19098. (org-element-property :parent e))))
  19099. ((memq type '(clock diary-sexp keyword))
  19100. (let* ((regexp (pcase type
  19101. (`clock org-clock-line-re)
  19102. (`diary-sexp "%%(")
  19103. (_ org-keyword-regexp)))
  19104. (end (if (< 0 (org-element-property :post-blank e))
  19105. (org-element-property :end e)
  19106. (org-with-wide-buffer
  19107. (forward-line)
  19108. (while (looking-at regexp) (forward-line))
  19109. (skip-chars-forward " \t\n")
  19110. (line-beginning-position))))
  19111. (begin (org-with-point-at (org-element-property :begin e)
  19112. (while (and (not (bobp)) (looking-at regexp))
  19113. (forward-line -1))
  19114. ;; We may have gotten one line too far.
  19115. (if (looking-at regexp)
  19116. (point)
  19117. (line-beginning-position 2)))))
  19118. (list begin end (org-element-property :parent e))))
  19119. ;; Find the full plain list containing point, the check it
  19120. ;; contains exactly one line per item.
  19121. ((let ((l (org-element-lineage e '(plain-list) t)))
  19122. (while (memq (org-element-type (org-element-property :parent l))
  19123. '(item plain-list))
  19124. (setq l (org-element-property :parent l)))
  19125. (and l
  19126. (org-with-point-at (org-element-property :post-affiliated l)
  19127. (forward-line (length (org-element-property :structure l)))
  19128. (= (point) (org-element-property :contents-end l)))
  19129. ;; Return value.
  19130. (list (org-element-property :begin l)
  19131. (org-element-property :end l)
  19132. (org-element-property :parent l)))))
  19133. (t nil)))) ;no triplet: return element
  19134. (pcase triplet
  19135. (`(,b ,e ,p)
  19136. (org-element-create
  19137. 'pseudo-paragraph
  19138. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  19139. (_ e))))
  19140. (defun org--forward-paragraph-once ()
  19141. "Move forward to end of paragraph or equivalent, once.
  19142. See `org-forward-paragraph'."
  19143. (interactive)
  19144. (save-restriction
  19145. (widen)
  19146. (skip-chars-forward " \t\n")
  19147. (cond
  19148. ((eobp) nil)
  19149. ;; When inside a folded part, move out of it.
  19150. ((pcase (get-char-property-and-overlay (point) 'invisible)
  19151. (`(,(or `outline `org-hide-block) . ,o)
  19152. (goto-char (overlay-end o))
  19153. (forward-line)
  19154. t)
  19155. (_ nil)))
  19156. (t
  19157. (let* ((element (org--paragraph-at-point))
  19158. (type (org-element-type element))
  19159. (contents-begin (org-element-property :contents-begin element))
  19160. (end (org-element-property :end element))
  19161. (post-affiliated (org-element-property :post-affiliated element)))
  19162. (cond
  19163. ((eq type 'plain-list)
  19164. (forward-char)
  19165. (org--forward-paragraph-once))
  19166. ;; If the element is folded, skip it altogether.
  19167. ((pcase (org-with-point-at post-affiliated
  19168. (get-char-property-and-overlay (line-end-position)
  19169. 'invisible))
  19170. (`(,(or `outline `org-hide-block) . ,o)
  19171. (goto-char (overlay-end o))
  19172. (forward-line)
  19173. t)
  19174. (_ nil)))
  19175. ;; At a greater element, move inside.
  19176. ((and contents-begin
  19177. (> contents-begin (point))
  19178. (not (eq type 'paragraph)))
  19179. (goto-char contents-begin)
  19180. ;; Items and footnote definitions contents may not start at
  19181. ;; the beginning of the line. In this case, skip until the
  19182. ;; next paragraph.
  19183. (cond
  19184. ((not (bolp)) (org--forward-paragraph-once))
  19185. ((org-previous-line-empty-p) (forward-line -1))
  19186. (t nil)))
  19187. ;; Move between empty lines in some blocks.
  19188. ((memq type '(comment-block example-block export-block src-block
  19189. verse-block))
  19190. (let ((contents-start
  19191. (org-with-point-at post-affiliated
  19192. (line-beginning-position 2))))
  19193. (if (< (point) contents-start)
  19194. (goto-char contents-start)
  19195. (let ((contents-end
  19196. (org-with-point-at end
  19197. (skip-chars-backward " \t\n")
  19198. (line-beginning-position))))
  19199. (cond
  19200. ((>= (point) contents-end)
  19201. (goto-char end)
  19202. (skip-chars-backward " \t\n")
  19203. (forward-line))
  19204. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19205. (forward-line -1))
  19206. (t nil))))))
  19207. (t
  19208. ;; Move to element's end.
  19209. (goto-char end)
  19210. (skip-chars-backward " \t\n")
  19211. (forward-line))))))))
  19212. (defun org--backward-paragraph-once ()
  19213. "Move backward to start of paragraph or equivalent, once.
  19214. See `org-backward-paragraph'."
  19215. (interactive)
  19216. (save-restriction
  19217. (widen)
  19218. (cond
  19219. ((bobp) nil)
  19220. ;; Blank lines at the beginning of the buffer.
  19221. ((and (org-match-line "^[ \t]*$")
  19222. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19223. (goto-char (point-min)))
  19224. ;; When inside a folded part, move out of it.
  19225. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19226. (`(,(or `outline `org-hide-block) . ,o)
  19227. (goto-char (1- (overlay-start o)))
  19228. (org--backward-paragraph-once)
  19229. t)
  19230. (_ nil)))
  19231. (t
  19232. (let* ((element (org--paragraph-at-point))
  19233. (type (org-element-type element))
  19234. (begin (org-element-property :begin element))
  19235. (post-affiliated (org-element-property :post-affiliated element))
  19236. (contents-end (org-element-property :contents-end element))
  19237. (end (org-element-property :end element))
  19238. (parent (org-element-property :parent element))
  19239. (reach
  19240. ;; Move to the visible empty line above position P, or
  19241. ;; to position P. Return t.
  19242. (lambda (p)
  19243. (goto-char p)
  19244. (when (and (org-previous-line-empty-p)
  19245. (let ((end (line-end-position 0)))
  19246. (or (= end (point-min))
  19247. (not (org-invisible-p (1- end))))))
  19248. (forward-line -1))
  19249. t)))
  19250. (cond
  19251. ;; Already at the beginning of an element.
  19252. ((= begin (point))
  19253. (cond
  19254. ;; There is a blank line above. Move there.
  19255. ((and (org-previous-line-empty-p)
  19256. (let ((lep (line-end-position 0)))
  19257. ;; When the first headline start at point 2, don't choke while
  19258. ;; checking with `org-invisible-p'.
  19259. (or (= lep 1)
  19260. (not (org-invisible-p (1- (line-end-position 0)))))))
  19261. (forward-line -1))
  19262. ;; At the beginning of the first element within a greater
  19263. ;; element. Move to the beginning of the greater element.
  19264. ((and parent (= begin (org-element-property :contents-begin parent)))
  19265. (funcall reach (org-element-property :begin parent)))
  19266. ;; Since we have to move anyway, find the beginning
  19267. ;; position of the element above.
  19268. (t
  19269. (forward-char -1)
  19270. (org--backward-paragraph-once))))
  19271. ;; Skip paragraphs at the very beginning of footnote
  19272. ;; definitions or items.
  19273. ((and (eq type 'paragraph)
  19274. (org-with-point-at begin (not (bolp))))
  19275. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19276. ;; If the element is folded, skip it altogether.
  19277. ((org-with-point-at post-affiliated
  19278. (org-invisible-p (line-end-position) t))
  19279. (funcall reach begin))
  19280. ;; At the end of a greater element, move inside.
  19281. ((and contents-end
  19282. (<= contents-end (point))
  19283. (not (eq type 'paragraph)))
  19284. (cond
  19285. ((memq type '(footnote-definition plain-list))
  19286. (skip-chars-backward " \t\n")
  19287. (org--backward-paragraph-once))
  19288. ((= contents-end (point))
  19289. (forward-char -1)
  19290. (org--backward-paragraph-once))
  19291. (t
  19292. (goto-char contents-end))))
  19293. ;; Move between empty lines in some blocks.
  19294. ((and (memq type '(comment-block example-block export-block src-block
  19295. verse-block))
  19296. (let ((contents-start
  19297. (org-with-point-at post-affiliated
  19298. (line-beginning-position 2))))
  19299. (when (> (point) contents-start)
  19300. (let ((contents-end
  19301. (org-with-point-at end
  19302. (skip-chars-backward " \t\n")
  19303. (line-beginning-position))))
  19304. (if (> (point) contents-end)
  19305. (progn (goto-char contents-end) t)
  19306. (skip-chars-backward " \t\n" begin)
  19307. (re-search-backward "^[ \t]*\n" contents-start :move)
  19308. t))))))
  19309. ;; Move to element's start.
  19310. (t
  19311. (funcall reach begin))))))))
  19312. (defun org-forward-element ()
  19313. "Move forward by one element.
  19314. Move to the next element at the same level, when possible."
  19315. (interactive)
  19316. (cond ((eobp) (user-error "Cannot move further down"))
  19317. ((org-with-limited-levels (org-at-heading-p))
  19318. (let ((origin (point)))
  19319. (goto-char (org-end-of-subtree nil t))
  19320. (unless (org-with-limited-levels (org-at-heading-p))
  19321. (goto-char origin)
  19322. (user-error "Cannot move further down"))))
  19323. (t
  19324. (let* ((elem (org-element-at-point))
  19325. (end (org-element-property :end elem))
  19326. (parent (org-element-property :parent elem)))
  19327. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19328. (goto-char (org-element-property :end parent)))
  19329. ((integer-or-marker-p end) (goto-char end))
  19330. (t (message "No element at point")))))))
  19331. (defun org-backward-element ()
  19332. "Move backward by one element.
  19333. Move to the previous element at the same level, when possible."
  19334. (interactive)
  19335. (cond ((bobp) (user-error "Cannot move further up"))
  19336. ((org-with-limited-levels (org-at-heading-p))
  19337. ;; At a headline, move to the previous one, if any, or stay
  19338. ;; here.
  19339. (let ((origin (point)))
  19340. (org-with-limited-levels (org-backward-heading-same-level 1))
  19341. ;; When current headline has no sibling above, move to its
  19342. ;; parent.
  19343. (when (= (point) origin)
  19344. (or (org-with-limited-levels (org-up-heading-safe))
  19345. (progn (goto-char origin)
  19346. (user-error "Cannot move further up"))))))
  19347. (t
  19348. (let* ((elem (org-element-at-point))
  19349. (beg (org-element-property :begin elem)))
  19350. (cond
  19351. ;; Move to beginning of current element if point isn't
  19352. ;; there already.
  19353. ((null beg) (message "No element at point"))
  19354. ((/= (point) beg) (goto-char beg))
  19355. (t (goto-char beg)
  19356. (skip-chars-backward " \r\t\n")
  19357. (unless (bobp)
  19358. (let ((prev (org-element-at-point)))
  19359. (goto-char (org-element-property :begin prev))
  19360. (while (and (setq prev (org-element-property :parent prev))
  19361. (<= (org-element-property :end prev) beg))
  19362. (goto-char (org-element-property :begin prev)))))))))))
  19363. (defun org-up-element ()
  19364. "Move to upper element."
  19365. (interactive)
  19366. (if (org-with-limited-levels (org-at-heading-p))
  19367. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19368. (let* ((elem (org-element-at-point))
  19369. (parent (org-element-property :parent elem)))
  19370. (if parent (goto-char (org-element-property :begin parent))
  19371. (if (org-with-limited-levels (org-before-first-heading-p))
  19372. (user-error "No surrounding element")
  19373. (org-with-limited-levels (org-back-to-heading)))))))
  19374. (defun org-down-element ()
  19375. "Move to inner element."
  19376. (interactive)
  19377. (let ((element (org-element-at-point)))
  19378. (cond
  19379. ((memq (org-element-type element) '(plain-list table))
  19380. (goto-char (org-element-property :contents-begin element))
  19381. (forward-char))
  19382. ((memq (org-element-type element) org-element-greater-elements)
  19383. ;; If contents are hidden, first disclose them.
  19384. (when (org-invisible-p (line-end-position)) (org-cycle))
  19385. (goto-char (or (org-element-property :contents-begin element)
  19386. (user-error "No content for this element"))))
  19387. (t (user-error "No inner element")))))
  19388. (defun org-drag-element-backward ()
  19389. "Move backward element at point."
  19390. (interactive)
  19391. (let ((elem (or (org-element-at-point)
  19392. (user-error "No element at point"))))
  19393. (if (eq (org-element-type elem) 'headline)
  19394. ;; Preserve point when moving a whole tree, even if point was
  19395. ;; on blank lines below the headline.
  19396. (let ((offset (skip-chars-backward " \t\n")))
  19397. (unwind-protect (org-move-subtree-up)
  19398. (forward-char (- offset))))
  19399. (let ((prev-elem
  19400. (save-excursion
  19401. (goto-char (org-element-property :begin elem))
  19402. (skip-chars-backward " \r\t\n")
  19403. (unless (bobp)
  19404. (let* ((beg (org-element-property :begin elem))
  19405. (prev (org-element-at-point))
  19406. (up prev))
  19407. (while (and (setq up (org-element-property :parent up))
  19408. (<= (org-element-property :end up) beg))
  19409. (setq prev up))
  19410. prev)))))
  19411. ;; Error out if no previous element or previous element is
  19412. ;; a parent of the current one.
  19413. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19414. (user-error "Cannot drag element backward")
  19415. (let ((pos (point)))
  19416. (org-element-swap-A-B prev-elem elem)
  19417. (goto-char (+ (org-element-property :begin prev-elem)
  19418. (- pos (org-element-property :begin elem))))))))))
  19419. (defun org-drag-element-forward ()
  19420. "Move forward element at point."
  19421. (interactive)
  19422. (let* ((pos (point))
  19423. (elem (or (org-element-at-point)
  19424. (user-error "No element at point"))))
  19425. (when (= (point-max) (org-element-property :end elem))
  19426. (user-error "Cannot drag element forward"))
  19427. (goto-char (org-element-property :end elem))
  19428. (let ((next-elem (org-element-at-point)))
  19429. (when (or (org-element-nested-p elem next-elem)
  19430. (and (eq (org-element-type next-elem) 'headline)
  19431. (not (eq (org-element-type elem) 'headline))))
  19432. (goto-char pos)
  19433. (user-error "Cannot drag element forward"))
  19434. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19435. ;; body's length (without final blanks) and by the length of
  19436. ;; blanks between ELEM and NEXT-ELEM.
  19437. (let ((size-next (- (save-excursion
  19438. (goto-char (org-element-property :end next-elem))
  19439. (skip-chars-backward " \r\t\n")
  19440. (forward-line)
  19441. ;; Small correction if buffer doesn't end
  19442. ;; with a newline character.
  19443. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19444. (org-element-property :begin next-elem)))
  19445. (size-blank (- (org-element-property :end elem)
  19446. (save-excursion
  19447. (goto-char (org-element-property :end elem))
  19448. (skip-chars-backward " \r\t\n")
  19449. (forward-line)
  19450. (point)))))
  19451. (org-element-swap-A-B elem next-elem)
  19452. (goto-char (+ pos size-next size-blank))))))
  19453. (defun org-drag-line-forward (arg)
  19454. "Drag the line at point ARG lines forward."
  19455. (interactive "p")
  19456. (dotimes (_ (abs arg))
  19457. (let ((c (current-column)))
  19458. (if (< 0 arg)
  19459. (progn
  19460. (beginning-of-line 2)
  19461. (transpose-lines 1)
  19462. (beginning-of-line 0))
  19463. (transpose-lines 1)
  19464. (beginning-of-line -1))
  19465. (org-move-to-column c))))
  19466. (defun org-drag-line-backward (arg)
  19467. "Drag the line at point ARG lines backward."
  19468. (interactive "p")
  19469. (org-drag-line-forward (- arg)))
  19470. (defun org-mark-element ()
  19471. "Put point at beginning of this element, mark at end.
  19472. Interactively, if this command is repeated or (in Transient Mark
  19473. mode) if the mark is active, it marks the next element after the
  19474. ones already marked."
  19475. (interactive)
  19476. (let (deactivate-mark)
  19477. (if (and (called-interactively-p 'any)
  19478. (or (and (eq last-command this-command) (mark t))
  19479. (and transient-mark-mode mark-active)))
  19480. (set-mark
  19481. (save-excursion
  19482. (goto-char (mark))
  19483. (goto-char (org-element-property :end (org-element-at-point)))
  19484. (point)))
  19485. (let ((element (org-element-at-point)))
  19486. (end-of-line)
  19487. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19488. (goto-char (org-element-property :begin element))))))
  19489. (defun org-narrow-to-element ()
  19490. "Narrow buffer to current element."
  19491. (interactive)
  19492. (let ((elem (org-element-at-point)))
  19493. (cond
  19494. ((eq (car elem) 'headline)
  19495. (narrow-to-region
  19496. (org-element-property :begin elem)
  19497. (org-element-property :end elem)))
  19498. ((memq (car elem) org-element-greater-elements)
  19499. (narrow-to-region
  19500. (org-element-property :contents-begin elem)
  19501. (org-element-property :contents-end elem)))
  19502. (t
  19503. (narrow-to-region
  19504. (org-element-property :begin elem)
  19505. (org-element-property :end elem))))))
  19506. (defun org-transpose-element ()
  19507. "Transpose current and previous elements, keeping blank lines between.
  19508. Point is moved after both elements."
  19509. (interactive)
  19510. (org-skip-whitespace)
  19511. (let ((end (org-element-property :end (org-element-at-point))))
  19512. (org-drag-element-backward)
  19513. (goto-char end)))
  19514. (defun org-unindent-buffer ()
  19515. "Un-indent the visible part of the buffer.
  19516. Relative indentation (between items, inside blocks, etc.) isn't
  19517. modified."
  19518. (interactive)
  19519. (unless (eq major-mode 'org-mode)
  19520. (user-error "Cannot un-indent a buffer not in Org mode"))
  19521. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19522. (unindent-tree
  19523. (lambda (contents)
  19524. (dolist (element (reverse contents))
  19525. (if (memq (org-element-type element) '(headline section))
  19526. (funcall unindent-tree (org-element-contents element))
  19527. (save-excursion
  19528. (save-restriction
  19529. (narrow-to-region
  19530. (org-element-property :begin element)
  19531. (org-element-property :end element))
  19532. (org-do-remove-indentation))))))))
  19533. (funcall unindent-tree (org-element-contents parse-tree))))
  19534. (defun org-make-options-regexp (kwds &optional extra)
  19535. "Make a regular expression for keyword lines.
  19536. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19537. when non-nil, is a regexp matching keywords names."
  19538. (concat "^[ \t]*#\\+\\("
  19539. (regexp-opt kwds)
  19540. (and extra (concat (and kwds "\\|") extra))
  19541. "\\):[ \t]*\\(.*\\)"))
  19542. ;;; Conveniently switch to Info nodes
  19543. (defun org-info-find-node (&optional nodename)
  19544. "Find Info documentation NODENAME or Org documentation according context.
  19545. Started from `gnus-info-find-node'."
  19546. (interactive)
  19547. (Info-goto-node
  19548. (or nodename
  19549. (let ((default-org-info-node "(org) Top"))
  19550. (cond
  19551. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19552. ((eq 'org-mode major-mode)
  19553. (let* ((context (org-element-at-point))
  19554. (element-info-nodes ; compare to `org-element-all-elements'.
  19555. `((babel-call . "(org) Evaluating Code Blocks")
  19556. (center-block . "(org) Paragraphs")
  19557. (clock . ,default-org-info-node)
  19558. (comment . "(org) Comment Lines")
  19559. (comment-block . "(org) Comment Lines")
  19560. (diary-sexp . ,default-org-info-node)
  19561. (drawer . "(org) Drawers")
  19562. (dynamic-block . "(org) Dynamic Blocks")
  19563. (example-block . "(org) Literal Examples")
  19564. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19565. (fixed-width . ,default-org-info-node)
  19566. (footnote-definition . "(org) Creating Footnotes")
  19567. (headline . "(org) Document Structure")
  19568. (horizontal-rule . "(org) Built-in Table Editor")
  19569. (inlinetask . ,default-org-info-node)
  19570. (item . "(org) Plain Lists")
  19571. (keyword . "(org) Per-file keywords")
  19572. (latex-environment . "(org) LaTeX Export")
  19573. (node-property . "(org) Properties and Columns")
  19574. (paragraph . "(org) Paragraphs")
  19575. (plain-list . "(org) Plain Lists")
  19576. (planning . "(org) Deadlines and Scheduling")
  19577. (property-drawer . "(org) Properties and Columns")
  19578. (quote-block . "(org) Paragraphs")
  19579. (section . ,default-org-info-node)
  19580. (special-block . ,default-org-info-node)
  19581. (src-block . "(org) Working with Source Code")
  19582. (table . "(org) Tables")
  19583. (table-row . "(org) Tables")
  19584. (verse-block . "(org) Paragraphs"))))
  19585. (or (cdr (assoc (car context) element-info-nodes))
  19586. default-org-info-node)))
  19587. (t default-org-info-node))))))
  19588. ;;; Finish up
  19589. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19590. (lambda () (add-hook 'change-major-mode-hook
  19591. 'org-show-all 'append 'local)))
  19592. (provide 'org)
  19593. (run-hooks 'org-load-hook)
  19594. ;;; org.el ends here