org.el 830 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766
  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 "25.1"))
  10. ;; Version: 9.6-dev
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'oc)
  86. (require 'oc-basic)
  87. (require 'org-table)
  88. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  89. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  90. (defvar org-outline-regexp "\\*+ "
  91. "Regexp to match Org headlines.")
  92. (defvar org-outline-regexp-bol "^\\*+ "
  93. "Regexp to match Org headlines.
  94. This is similar to `org-outline-regexp' but additionally makes
  95. sure that we are at the beginning of the line.")
  96. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  97. "Matches a headline, putting stars and text into groups.
  98. Stars are put in group 1 and the trimmed body in group 2.")
  99. (declare-function calendar-check-holidays "holidays" (date))
  100. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  101. (declare-function cdlatex-math-symbol "ext:cdlatex")
  102. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  103. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  104. (declare-function org-add-archive-files "org-archive" (files))
  105. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  106. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  107. (declare-function org-agenda-redo "org-agenda" (&optional all))
  108. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  109. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  110. (declare-function org-archive-subtree-default "org-archive" ())
  111. (declare-function org-archive-to-archive-sibling "org-archive" ())
  112. (declare-function org-attach "org-attach" ())
  113. (declare-function org-attach-dir "org-attach"
  114. (&optional create-if-not-exists-p no-fs-check))
  115. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  116. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  117. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  118. (declare-function org-clock-auto-clockout "org-clock" ())
  119. (declare-function org-clock-cancel "org-clock" ())
  120. (declare-function org-clock-display "org-clock" (&optional arg))
  121. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  122. (declare-function org-clock-goto "org-clock" (&optional select))
  123. (declare-function org-clock-in "org-clock" (&optional select start-time))
  124. (declare-function org-clock-in-last "org-clock" (&optional arg))
  125. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  126. (declare-function org-clock-out-if-current "org-clock" ())
  127. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  128. (declare-function org-clock-report "org-clock" (&optional arg))
  129. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  130. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  131. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  132. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  133. (declare-function org-clock-update-time-maybe "org-clock" ())
  134. (declare-function org-clocktable-shift "org-clock" (dir n))
  135. (declare-function org-columns-quit "org-colview" ())
  136. (declare-function org-columns-insert-dblock "org-colview" ())
  137. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  138. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  139. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  140. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  141. (declare-function org-element-cache-refresh "org-element" (pos))
  142. (declare-function org-element-cache-reset "org-element" (&optional all))
  143. (declare-function org-element-cache-map "org-element" (func &rest keys))
  144. (declare-function org-element-contents "org-element" (element))
  145. (declare-function org-element-context "org-element" (&optional element))
  146. (declare-function org-element-copy "org-element" (datum))
  147. (declare-function org-element-create "org-element" (type &optional props &rest children))
  148. (declare-function org-element-extract-element "org-element" (element))
  149. (declare-function org-element-insert-before "org-element" (element location))
  150. (declare-function org-element-interpret-data "org-element" (data))
  151. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  152. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  153. (declare-function org-element-link-parser "org-element" ())
  154. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  155. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  156. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  157. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  158. (declare-function org-element-property "org-element" (property element))
  159. (declare-function org-element-put-property "org-element" (element property value))
  160. (declare-function org-element-restriction "org-element" (element))
  161. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  162. (declare-function org-element-timestamp-parser "org-element" ())
  163. (declare-function org-element-type "org-element" (element))
  164. (declare-function org-element--cache-active-p "org-element" ())
  165. (declare-function org-export-dispatch "ox" (&optional arg))
  166. (declare-function org-export-get-backend "ox" (name))
  167. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  168. (declare-function org-feed-goto-inbox "org-feed" (feed))
  169. (declare-function org-feed-update-all "org-feed" ())
  170. (declare-function org-goto "org-goto" (&optional alternative-interface))
  171. (declare-function org-id-find-id-file "org-id" (id))
  172. (declare-function org-id-get-create "org-id" (&optional force))
  173. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  174. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  175. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  176. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  177. (declare-function org-num-mode "org-num" (&optional arg))
  178. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  179. (declare-function org-persist-read "org-persist" (var &optional buffer))
  180. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  181. (declare-function org-timer "org-timer" (&optional restart no-insert))
  182. (declare-function org-timer-item "org-timer" (&optional arg))
  183. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  184. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  185. (declare-function org-timer-start "org-timer" (&optional offset))
  186. (declare-function org-timer-stop "org-timer" ())
  187. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  188. (declare-function org-update-radio-target-regexp "ol" ())
  189. (defvar org-agenda-buffer-name)
  190. (defvar org-element-paragraph-separate)
  191. (defvar org-indent-indentation-per-level)
  192. (defvar org-radio-target-regexp)
  193. (defvar org-target-link-regexp)
  194. (defvar org-target-regexp)
  195. (defvar org-id-overriding-file-name)
  196. ;; load languages based on value of `org-babel-load-languages'
  197. (defvar org-babel-load-languages)
  198. (defvar crm-separator) ; dynamically scoped param
  199. ;;;###autoload
  200. (defun org-babel-do-load-languages (sym value)
  201. "Load the languages defined in `org-babel-load-languages'."
  202. (set-default sym value)
  203. (dolist (pair org-babel-load-languages)
  204. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  205. (if active
  206. (require (intern (concat "ob-" lang)))
  207. (fmakunbound
  208. (intern (concat "org-babel-execute:" lang)))
  209. (fmakunbound
  210. (intern (concat "org-babel-expand-body:" lang)))))))
  211. ;;;###autoload
  212. (defun org-babel-load-file (file &optional compile)
  213. "Load Emacs Lisp source code blocks in the Org FILE.
  214. This function exports the source code using `org-babel-tangle'
  215. and then loads the resulting file using `load-file'. With
  216. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  217. byte-compiled before it is loaded."
  218. (interactive "fFile to load: \nP")
  219. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  220. ;; Tangle only if the Org file is newer than the Elisp file.
  221. (unless (org-file-newer-than-p
  222. tangled-file
  223. (file-attribute-modification-time
  224. (file-attributes (file-truename file))))
  225. (org-babel-tangle-file file
  226. tangled-file
  227. (rx string-start
  228. (or "emacs-lisp" "elisp")
  229. string-end)))
  230. (if compile
  231. (progn
  232. (byte-compile-file tangled-file)
  233. (load tangled-file)
  234. (message "Compiled and loaded %s" tangled-file))
  235. (load-file tangled-file)
  236. (message "Loaded %s" tangled-file))))
  237. (defcustom org-babel-load-languages '((emacs-lisp . t))
  238. "Languages which can be evaluated in Org buffers.
  239. \\<org-mode-map>
  240. This list can be used to load support for any of the languages
  241. below. Each language will depend on a different set of system
  242. executables and/or Emacs modes.
  243. When a language is \"loaded\", code blocks in that language can
  244. be evaluated with `org-babel-execute-src-block', which is bound
  245. by default to \\[org-ctrl-c-ctrl-c].
  246. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  247. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  248. default, only Emacs Lisp is loaded, since it has no specific
  249. requirement."
  250. :group 'org-babel
  251. :set 'org-babel-do-load-languages
  252. :version "24.1"
  253. :type '(alist :tag "Babel Languages"
  254. :key-type
  255. (choice
  256. (const :tag "Awk" awk)
  257. (const :tag "C" C)
  258. (const :tag "R" R)
  259. (const :tag "Calc" calc)
  260. (const :tag "Clojure" clojure)
  261. (const :tag "CSS" css)
  262. (const :tag "Ditaa" ditaa)
  263. (const :tag "Dot" dot)
  264. (const :tag "Emacs Lisp" emacs-lisp)
  265. (const :tag "Forth" forth)
  266. (const :tag "Fortran" fortran)
  267. (const :tag "Gnuplot" gnuplot)
  268. (const :tag "Haskell" haskell)
  269. (const :tag "Java" java)
  270. (const :tag "Javascript" js)
  271. (const :tag "LaTeX" latex)
  272. (const :tag "Lilypond" lilypond)
  273. (const :tag "Lisp" lisp)
  274. (const :tag "Makefile" makefile)
  275. (const :tag "Maxima" maxima)
  276. (const :tag "Matlab" matlab)
  277. (const :tag "Ocaml" ocaml)
  278. (const :tag "Octave" octave)
  279. (const :tag "Org" org)
  280. (const :tag "Perl" perl)
  281. (const :tag "Pico Lisp" picolisp)
  282. (const :tag "PlantUML" plantuml)
  283. (const :tag "Python" python)
  284. (const :tag "Ruby" ruby)
  285. (const :tag "Sass" sass)
  286. (const :tag "Scala" scala)
  287. (const :tag "Scheme" scheme)
  288. (const :tag "Screen" screen)
  289. (const :tag "Shell Script" shell)
  290. (const :tag "Sql" sql)
  291. (const :tag "Sqlite" sqlite)
  292. (const :tag "Stan" stan))
  293. :value-type (boolean :tag "Activate" :value t)))
  294. ;;;; Customization variables
  295. (defcustom org-clone-delete-id nil
  296. "Remove ID property of clones of a subtree.
  297. When non-nil, clones of a subtree don't inherit the ID property.
  298. Otherwise they inherit the ID property with a new unique
  299. identifier."
  300. :type 'boolean
  301. :version "24.1"
  302. :group 'org-id)
  303. ;;; Version
  304. (org-check-version)
  305. ;;;###autoload
  306. (defun org-version (&optional here full message)
  307. "Show the Org version.
  308. Interactively, or when MESSAGE is non-nil, show it in echo area.
  309. With prefix argument, or when HERE is non-nil, insert it at point.
  310. In non-interactive uses, a reduced version string is output unless
  311. FULL is given."
  312. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  313. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  314. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  315. (load-suffixes (list ".el"))
  316. (org-install-dir
  317. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  318. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  319. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  320. (let* ((load-suffixes save-load-suffixes)
  321. (release (org-release))
  322. (git-version (org-git-version))
  323. (version (format "Org mode version %s (%s @ %s)"
  324. release
  325. git-version
  326. (if org-install-dir
  327. (if (string= org-dir org-install-dir)
  328. org-install-dir
  329. (concat "mixed installation! "
  330. org-install-dir
  331. " and "
  332. org-dir))
  333. "org-loaddefs.el can not be found!")))
  334. (version1 (if full version release)))
  335. (when here (insert version1))
  336. (when message (message "%s" version1))
  337. version1)))
  338. (defconst org-version (org-version))
  339. ;;; Syntax Constants
  340. ;;;; Comments
  341. (defconst org-comment-regexp
  342. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  343. "Regular expression for comment lines.")
  344. ;;;; Keyword
  345. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  346. "Regular expression for keyword-lines.")
  347. ;;;; Block
  348. (defconst org-block-regexp
  349. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  350. "Regular expression for hiding blocks.")
  351. (defconst org-dblock-start-re
  352. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  353. "Matches the start line of a dynamic block, with parameters.")
  354. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  355. "Matches the end of a dynamic block.")
  356. ;;;; Timestamp
  357. (defconst org-ts--internal-regexp
  358. (rx (seq
  359. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  360. (optional " " (*? nonl))))
  361. "Regular expression matching the innards of a time stamp.")
  362. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  363. "Regular expression for fast time stamp matching.")
  364. (defconst org-ts-regexp-inactive
  365. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  366. "Regular expression for fast inactive time stamp matching.")
  367. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  368. "Regular expression for fast time stamp matching.")
  369. (defconst org-ts-regexp0
  370. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  371. "Regular expression matching time strings for analysis.
  372. This one does not require the space after the date, so it can be used
  373. on a string that terminates immediately after the date.")
  374. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  375. "Regular expression matching time strings for analysis.")
  376. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  377. "Regular expression matching time stamps, with groups.")
  378. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  379. "Regular expression matching time stamps (also [..]), with groups.")
  380. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  381. "Regular expression matching a time stamp range.")
  382. (defconst org-tr-regexp-both
  383. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  384. "Regular expression matching a time stamp range.")
  385. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  386. org-ts-regexp "\\)?")
  387. "Regular expression matching a time stamp or time stamp range.")
  388. (defconst org-tsr-regexp-both
  389. (concat org-ts-regexp-both "\\(--?-?"
  390. org-ts-regexp-both "\\)?")
  391. "Regular expression matching a time stamp or time stamp range.
  392. The time stamps may be either active or inactive.")
  393. (defconst org-repeat-re
  394. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  395. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  396. "Regular expression for specifying repeated events.
  397. After a match, group 1 contains the repeat expression.")
  398. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  399. "Formats for `format-time-string' which are used for time stamps.")
  400. ;;;; Clock and Planning
  401. (defconst org-clock-string "CLOCK:"
  402. "String used as prefix for timestamps clocking work hours on an item.")
  403. (defvar org-closed-string "CLOSED:"
  404. "String used as the prefix for timestamps logging closing a TODO entry.")
  405. (defvar org-deadline-string "DEADLINE:"
  406. "String to mark deadline entries.
  407. \\<org-mode-map>
  408. A deadline is this string, followed by a time stamp. It must be
  409. a word, terminated by a colon. You can insert a schedule keyword
  410. and a timestamp with `\\[org-deadline]'.")
  411. (defvar org-scheduled-string "SCHEDULED:"
  412. "String to mark scheduled TODO entries.
  413. \\<org-mode-map>
  414. A schedule is this string, followed by a time stamp. It must be
  415. a word, terminated by a colon. You can insert a schedule keyword
  416. and a timestamp with `\\[org-schedule]'.")
  417. (defconst org-ds-keyword-length
  418. (+ 2
  419. (apply #'max
  420. (mapcar #'length
  421. (list org-deadline-string org-scheduled-string
  422. org-clock-string org-closed-string))))
  423. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  424. (defconst org-planning-line-re
  425. (concat "^[ \t]*"
  426. (regexp-opt
  427. (list org-closed-string org-deadline-string org-scheduled-string)
  428. t))
  429. "Matches a line with planning info.
  430. Matched keyword is in group 1.")
  431. (defconst org-clock-line-re
  432. (concat "^[ \t]*" org-clock-string)
  433. "Matches a line with clock info.")
  434. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  435. "Matches the DEADLINE keyword.")
  436. (defconst org-deadline-time-regexp
  437. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  438. "Matches the DEADLINE keyword together with a time stamp.")
  439. (defconst org-deadline-time-hour-regexp
  440. (concat "\\<" org-deadline-string
  441. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  442. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  443. (defconst org-deadline-line-regexp
  444. (concat "\\<\\(" org-deadline-string "\\).*")
  445. "Matches the DEADLINE keyword and the rest of the line.")
  446. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  447. "Matches the SCHEDULED keyword.")
  448. (defconst org-scheduled-time-regexp
  449. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  450. "Matches the SCHEDULED keyword together with a time stamp.")
  451. (defconst org-scheduled-time-hour-regexp
  452. (concat "\\<" org-scheduled-string
  453. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  454. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  455. (defconst org-closed-time-regexp
  456. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  457. "Matches the CLOSED keyword together with a time stamp.")
  458. (defconst org-keyword-time-regexp
  459. (concat "\\<"
  460. (regexp-opt
  461. (list org-scheduled-string org-deadline-string org-closed-string
  462. org-clock-string)
  463. t)
  464. " *[[<]\\([^]>]+\\)[]>]")
  465. "Matches any of the 4 keywords, together with the time stamp.")
  466. (defconst org-keyword-time-not-clock-regexp
  467. (concat
  468. "\\<"
  469. (regexp-opt
  470. (list org-scheduled-string org-deadline-string org-closed-string) t)
  471. " *[[<]\\([^]>]+\\)[]>]")
  472. "Matches any of the 3 keywords, together with the time stamp.")
  473. (defconst org-all-time-keywords
  474. (mapcar (lambda (w) (substring w 0 -1))
  475. (list org-scheduled-string org-deadline-string
  476. org-clock-string org-closed-string))
  477. "List of time keywords.")
  478. ;;;; Drawer
  479. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  480. "Matches first or last line of a hidden block.
  481. Group 1 contains drawer's name or \"END\".")
  482. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  483. "Regular expression matching the first line of a property drawer.")
  484. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  485. "Regular expression matching the last line of a property drawer.")
  486. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  487. "Regular expression matching the first line of a clock drawer.")
  488. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  489. "Regular expression matching the last line of a clock drawer.")
  490. (defconst org-logbook-drawer-re
  491. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  492. (*? (0+ nonl) "\n")
  493. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  494. "Matches an entire LOGBOOK drawer.")
  495. (defconst org-property-drawer-re
  496. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  497. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  498. "[ \t]*:END:[ \t]*$")
  499. "Matches an entire property drawer.")
  500. (defconst org-clock-drawer-re
  501. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  502. org-clock-drawer-end-re "\\)\n?")
  503. "Matches an entire clock drawer.")
  504. ;;;; Headline
  505. (defconst org-heading-keyword-regexp-format
  506. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  507. "Printf format for a regexp matching a headline with some keyword.
  508. This regexp will match the headline of any node which has the
  509. exact keyword that is put into the format. The keyword isn't in
  510. any group by default, but the stars and the body are.")
  511. (defconst org-heading-keyword-maybe-regexp-format
  512. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  513. "Printf format for a regexp matching a headline, possibly with some keyword.
  514. This regexp can match any headline with the specified keyword, or
  515. without a keyword. The keyword isn't in any group by default,
  516. but the stars and the body are.")
  517. (defconst org-archive-tag "ARCHIVE"
  518. "The tag that marks a subtree as archived.
  519. An archived subtree does not open during visibility cycling, and does
  520. not contribute to the agenda listings.")
  521. (defconst org-tag-re "[[:alnum:]_@#%]+"
  522. "Regexp matching a single tag.")
  523. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  524. "Regexp matching the tag group at the end of a line, with leading spaces.
  525. Tags are stored in match group 1. Match group 2 stores the tags
  526. without the enclosing colons.")
  527. (defconst org-tag-line-re
  528. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  529. "Regexp matching tags in a headline.
  530. Tags are stored in match group 1. Match group 2 stores the tags
  531. without the enclosing colons.")
  532. (eval-and-compile
  533. (defconst org-comment-string "COMMENT"
  534. "Entries starting with this keyword will never be exported.
  535. \\<org-mode-map>
  536. An entry can be toggled between COMMENT and normal with
  537. `\\[org-toggle-comment]'."))
  538. ;;;; LaTeX Environments and Fragments
  539. (defconst org-latex-regexps
  540. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  541. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  542. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  543. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  544. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  545. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  546. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  547. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  548. "Regular expressions for matching embedded LaTeX.")
  549. ;;;; Node Property
  550. (defconst org-effort-property "Effort"
  551. "The property that is being used to keep track of effort estimates.
  552. Effort estimates given in this property need to be in the format
  553. defined in org-duration.el.")
  554. ;;; The custom variables
  555. (defgroup org nil
  556. "Outline-based notes management and organizer."
  557. :tag "Org"
  558. :group 'outlines
  559. :group 'calendar)
  560. (defcustom org-mode-hook nil
  561. "Mode hook for Org mode, run after the mode was turned on."
  562. :group 'org
  563. :type 'hook)
  564. (defcustom org-load-hook nil
  565. "Hook that is run after org.el has been loaded."
  566. :group 'org
  567. :type 'hook)
  568. (make-obsolete-variable
  569. 'org-load-hook
  570. "use `with-eval-after-load' instead." "9.5")
  571. (defcustom org-log-buffer-setup-hook nil
  572. "Hook that is run after an Org log buffer is created."
  573. :group 'org
  574. :version "24.1"
  575. :type 'hook)
  576. (defvar org-modules) ; defined below
  577. (defvar org-modules-loaded nil
  578. "Have the modules been loaded already?")
  579. ;;;###autoload
  580. (defun org-load-modules-maybe (&optional force)
  581. "Load all extensions listed in `org-modules'."
  582. (when (or force (not org-modules-loaded))
  583. (dolist (ext org-modules)
  584. (condition-case nil (require ext)
  585. (error (message "Problems while trying to load feature `%s'" ext))))
  586. (setq org-modules-loaded t)))
  587. (defun org-set-modules (var value)
  588. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  589. (set var value)
  590. (when (featurep 'org)
  591. (org-load-modules-maybe 'force)
  592. (org-element-cache-reset 'all)))
  593. (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)
  594. "Modules that should always be loaded together with org.el.
  595. If a description starts with <C>, the file is not part of Emacs and Org mode,
  596. so loading it will require that you have properly installed org-contrib
  597. package from NonGNU Emacs Lisp Package Archive
  598. http://elpa.nongnu.org/nongnu/org-contrib.html
  599. You can also use this system to load external packages (i.e. neither Org
  600. core modules, nor org-contrib modules). Just add symbols
  601. to the end of the list. If the package is called org-xyz.el, then you need
  602. to add the symbol `xyz', and the package must have a call to:
  603. (provide \\='org-xyz)
  604. For export specific modules, see also `org-export-backends'."
  605. :group 'org
  606. :set 'org-set-modules
  607. :package-version '(Org . "9.5")
  608. :type
  609. '(set :greedy t
  610. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  611. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  612. (const :tag " crypt: Encryption of subtrees" org-crypt)
  613. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  614. (const :tag " docview: Links to Docview buffers" ol-docview)
  615. (const :tag " doi: Links to DOI references" ol-doi)
  616. (const :tag " eww: Store link to URL of Eww" ol-eww)
  617. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  618. (const :tag " habit: Track your consistency with habits" org-habit)
  619. (const :tag " id: Global IDs for identifying entries" org-id)
  620. (const :tag " info: Links to Info nodes" ol-info)
  621. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  622. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  623. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  624. (const :tag " mouse: Additional mouse support" org-mouse)
  625. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  626. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  627. (const :tag " tempo: Fast completion for structures" org-tempo)
  628. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  629. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  630. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  631. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  632. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  633. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  634. (const :tag "C collector: Collect properties into tables" org-collector)
  635. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  636. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  637. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  638. (const :tag "C eval: Include command output as text" org-eval)
  639. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  640. (const :tag "C git-link: Links to specific file version" ol-git-link)
  641. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  642. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  643. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  644. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  645. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  646. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  647. (const :tag "C man: Links to man pages in Org mode" ol-man)
  648. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  649. (const :tag "C notify: Notifications for Org mode" org-notify)
  650. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  651. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  652. (const :tag "C registry: A registry for Org links" org-registry)
  653. (const :tag "C screen: Visit screen sessions through links" org-screen)
  654. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  655. (const :tag "C secretary: Team management with Org" org-secretary)
  656. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  657. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  658. (const :tag "C track: Keep up with Org mode development" org-track)
  659. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  660. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  661. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  662. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  663. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  664. (defvar org-export-registered-backends) ; From ox.el.
  665. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  666. (declare-function org-export-backend-name "ox" (backend) t)
  667. (defcustom org-export-backends '(ascii html icalendar latex odt)
  668. "List of export back-ends that should be always available.
  669. If a description starts with <C>, the file is not part of Emacs and Org mode,
  670. so loading it will require that you have properly installed org-contrib
  671. package from NonGNU Emacs Lisp Package Archive
  672. http://elpa.nongnu.org/nongnu/org-contrib.html
  673. Unlike to `org-modules', libraries in this list will not be
  674. loaded along with Org, but only once the export framework is
  675. needed.
  676. This variable needs to be set before org.el is loaded. If you
  677. need to make a change while Emacs is running, use the customize
  678. interface or run the following code, where VAL stands for the new
  679. value of the variable, after updating it:
  680. (progn
  681. (setq org-export-registered-backends
  682. (cl-remove-if-not
  683. (lambda (backend)
  684. (let ((name (org-export-backend-name backend)))
  685. (or (memq name val)
  686. (catch \\='parentp
  687. (dolist (b val)
  688. (and (org-export-derived-backend-p b name)
  689. (throw \\='parentp t)))))))
  690. org-export-registered-backends))
  691. (let ((new-list (mapcar #\\='org-export-backend-name
  692. org-export-registered-backends)))
  693. (dolist (backend val)
  694. (cond
  695. ((not (load (format \"ox-%s\" backend) t t))
  696. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  697. backend))
  698. ((not (memq backend new-list)) (push backend new-list))))
  699. (set-default \\='org-export-backends new-list)))
  700. Adding a back-end to this list will also pull the back-end it
  701. depends on, if any."
  702. :group 'org
  703. :group 'org-export
  704. :version "26.1"
  705. :package-version '(Org . "9.0")
  706. :initialize 'custom-initialize-set
  707. :set (lambda (var val)
  708. (if (not (featurep 'ox)) (set-default var val)
  709. ;; Any back-end not required anymore (not present in VAL and not
  710. ;; a parent of any back-end in the new value) is removed from the
  711. ;; list of registered back-ends.
  712. (setq org-export-registered-backends
  713. (cl-remove-if-not
  714. (lambda (backend)
  715. (let ((name (org-export-backend-name backend)))
  716. (or (memq name val)
  717. (catch 'parentp
  718. (dolist (b val)
  719. (and (org-export-derived-backend-p b name)
  720. (throw 'parentp t)))))))
  721. org-export-registered-backends))
  722. ;; Now build NEW-LIST of both new back-ends and required
  723. ;; parents.
  724. (let ((new-list (mapcar #'org-export-backend-name
  725. org-export-registered-backends)))
  726. (dolist (backend val)
  727. (cond
  728. ((not (load (format "ox-%s" backend) t t))
  729. (message "Problems while trying to load export back-end `%s'"
  730. backend))
  731. ((not (memq backend new-list)) (push backend new-list))))
  732. ;; Set VAR to that list with fixed dependencies.
  733. (set-default var new-list))))
  734. :type '(set :greedy t
  735. (const :tag " ascii Export buffer to ASCII format" ascii)
  736. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  737. (const :tag " html Export buffer to HTML format" html)
  738. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  739. (const :tag " latex Export buffer to LaTeX format" latex)
  740. (const :tag " man Export buffer to MAN format" man)
  741. (const :tag " md Export buffer to Markdown format" md)
  742. (const :tag " odt Export buffer to ODT format" odt)
  743. (const :tag " org Export buffer to Org format" org)
  744. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  745. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  746. (const :tag "C deck Export buffer to deck.js presentations" deck)
  747. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  748. (const :tag "C groff Export buffer to Groff format" groff)
  749. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  750. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  751. (const :tag "C s5 Export buffer to s5 presentations" s5)
  752. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  753. (eval-after-load 'ox
  754. '(dolist (backend org-export-backends)
  755. (condition-case nil (require (intern (format "ox-%s" backend)))
  756. (error (message "Problems while trying to load export back-end `%s'"
  757. backend)))))
  758. (defcustom org-support-shift-select nil
  759. "Non-nil means make shift-cursor commands select text when possible.
  760. \\<org-mode-map>
  761. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  762. start selecting a region, or enlarge regions started in this way.
  763. In Org mode, in special contexts, these same keys are used for
  764. other purposes, important enough to compete with shift selection.
  765. Org tries to balance these needs by supporting `shift-select-mode'
  766. outside these special contexts, under control of this variable.
  767. The default of this variable is nil, to avoid confusing behavior. Shifted
  768. cursor keys will then execute Org commands in the following contexts:
  769. - on a headline, changing TODO state (left/right) and priority (up/down)
  770. - on a time stamp, changing the time
  771. - in a plain list item, changing the bullet type
  772. - in a property definition line, switching between allowed values
  773. - in the BEGIN line of a clock table (changing the time block).
  774. - in a table, moving the cell in the specified direction.
  775. Outside these contexts, the commands will throw an error.
  776. When this variable is t and the cursor is not in a special
  777. context, Org mode will support shift-selection for making and
  778. enlarging regions. To make this more effective, the bullet
  779. cycling will no longer happen anywhere in an item line, but only
  780. if the cursor is exactly on the bullet.
  781. If you set this variable to the symbol `always', then the keys
  782. will not be special in headlines, property lines, item lines, and
  783. table cells, to make shift selection work there as well. If this is
  784. what you want, you can use the following alternative commands:
  785. `\\[org-todo]' and `\\[org-priority]' \
  786. to change TODO state and priority,
  787. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  788. can be used to switch TODO sets,
  789. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  790. and properties can be edited by hand or in column view.
  791. However, when the cursor is on a timestamp, shift-cursor commands
  792. will still edit the time stamp - this is just too good to give up."
  793. :group 'org
  794. :type '(choice
  795. (const :tag "Never" nil)
  796. (const :tag "When outside special context" t)
  797. (const :tag "Everywhere except timestamps" always)))
  798. (defcustom org-loop-over-headlines-in-active-region t
  799. "Shall some commands act upon headlines in the active region?
  800. When set to t, some commands will be performed in all headlines
  801. within the active region.
  802. When set to `start-level', some commands will be performed in all
  803. headlines within the active region, provided that these headlines
  804. are of the same level than the first one.
  805. When set to a string, those commands will be performed on the
  806. matching headlines within the active region. Such string must be
  807. a tags/property/todo match as it is used in the agenda tags view.
  808. The list of commands is: `org-schedule', `org-deadline',
  809. `org-todo', `org-set-tags-command', `org-archive-subtree',
  810. `org-archive-set-tag', `org-toggle-archive-tag' and
  811. `org-archive-to-archive-sibling'. The archiving commands skip
  812. already archived entries.
  813. See `org-agenda-loop-over-headlines-in-active-region' for the
  814. equivalent option for agenda views."
  815. :type '(choice (const :tag "Don't loop" nil)
  816. (const :tag "All headlines in active region" t)
  817. (const :tag "In active region, headlines at the same level than the first one" start-level)
  818. (string :tag "Tags/Property/Todo matcher"))
  819. :package-version '(Org . "9.4")
  820. :group 'org-todo
  821. :group 'org-archive)
  822. (defcustom org-startup-folded 'showeverything
  823. "Non-nil means entering Org mode will switch to OVERVIEW.
  824. This can also be configured on a per-file basis by adding one of
  825. the following lines anywhere in the buffer:
  826. #+STARTUP: fold (or `overview', this is equivalent)
  827. #+STARTUP: nofold (or `showall', this is equivalent)
  828. #+STARTUP: content
  829. #+STARTUP: show<n>levels (<n> = 2..5)
  830. #+STARTUP: showeverything
  831. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  832. to ignore this option when Org opens agenda files for the first
  833. time."
  834. :group 'org-startup
  835. :package-version '(Org . "9.4")
  836. :type '(choice
  837. (const :tag "nofold: show all" nil)
  838. (const :tag "fold: overview" t)
  839. (const :tag "fold: show two levels" show2levels)
  840. (const :tag "fold: show three levels" show3levels)
  841. (const :tag "fold: show four levels" show4evels)
  842. (const :tag "fold: show five levels" show5levels)
  843. (const :tag "content: all headlines" content)
  844. (const :tag "show everything, even drawers" showeverything)))
  845. (defcustom org-startup-truncated t
  846. "Non-nil means entering Org mode will set `truncate-lines'.
  847. This is useful since some lines containing links can be very long and
  848. uninteresting. Also tables look terrible when wrapped.
  849. The variable `org-startup-truncated' allows to configure
  850. truncation for Org mode different to the other modes that use the
  851. variable `truncate-lines' and as a shortcut instead of putting
  852. the variable `truncate-lines' into the `org-mode-hook'. If one
  853. wants to configure truncation for Org mode not statically but
  854. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  855. the variable `truncate-lines' has to be used because in such a
  856. case it is too late to set the variable `org-startup-truncated'."
  857. :group 'org-startup
  858. :type 'boolean)
  859. (defcustom org-startup-indented nil
  860. "Non-nil means turn on `org-indent-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: indent
  864. #+STARTUP: noindent"
  865. :group 'org-structure
  866. :type '(choice
  867. (const :tag "Not" nil)
  868. (const :tag "Globally (slow on startup in large files)" t)))
  869. (defcustom org-startup-numerated nil
  870. "Non-nil means turn on `org-num-mode' on startup.
  871. This can also be configured on a per-file basis by adding one of
  872. the following lines anywhere in the buffer:
  873. #+STARTUP: num
  874. #+STARTUP: nonum"
  875. :group 'org-structure
  876. :package-version '(Org . "9.4")
  877. :type '(choice
  878. (const :tag "Not" nil)
  879. (const :tag "Globally" t)))
  880. (defcustom org-use-sub-superscripts t
  881. "Non-nil means interpret \"_\" and \"^\" for display.
  882. If you want to control how Org exports those characters, see
  883. `org-export-with-sub-superscripts'.
  884. When this option is turned on, you can use TeX-like syntax for
  885. sub- and superscripts within the buffer. Several characters after
  886. \"_\" or \"^\" will be considered as a single item - so grouping
  887. with {} is normally not needed. For example, the following things
  888. will be parsed as single sub- or superscripts:
  889. 10^24 or 10^tau several digits will be considered 1 item.
  890. 10^-12 or 10^-tau a leading sign with digits or a word
  891. x^2-y^3 will be read as x^2 - y^3, because items are
  892. terminated by almost any nonword/nondigit char.
  893. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  894. Still, ambiguity is possible. So when in doubt, use {} to enclose
  895. the sub/superscript. If you set this variable to the symbol `{}',
  896. the braces are *required* in order to trigger interpretations as
  897. sub/superscript. This can be helpful in documents that need \"_\"
  898. frequently in plain text."
  899. :group 'org-startup
  900. :version "24.4"
  901. :package-version '(Org . "8.0")
  902. :type '(choice
  903. (const :tag "Always interpret" t)
  904. (const :tag "Only with braces" {})
  905. (const :tag "Never interpret" nil)))
  906. (defcustom org-startup-with-beamer-mode nil
  907. "Non-nil means turn on `org-beamer-mode' on startup.
  908. This can also be configured on a per-file basis by adding one of
  909. the following lines anywhere in the buffer:
  910. #+STARTUP: beamer"
  911. :group 'org-startup
  912. :version "24.1"
  913. :type 'boolean)
  914. (defcustom org-startup-align-all-tables nil
  915. "Non-nil means align all tables when visiting a file.
  916. This can also be configured on a per-file basis by adding one of
  917. the following lines anywhere in the buffer:
  918. #+STARTUP: align
  919. #+STARTUP: noalign"
  920. :group 'org-startup
  921. :type 'boolean)
  922. (defcustom org-startup-shrink-all-tables nil
  923. "Non-nil means shrink all table columns with a width cookie.
  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: shrink"
  927. :group 'org-startup
  928. :type 'boolean
  929. :version "27.1"
  930. :package-version '(Org . "9.2")
  931. :safe #'booleanp)
  932. (defcustom org-startup-with-inline-images nil
  933. "Non-nil means show inline images when loading a new Org file.
  934. This can also be configured on a per-file basis by adding one of
  935. the following lines anywhere in the buffer:
  936. #+STARTUP: inlineimages
  937. #+STARTUP: noinlineimages"
  938. :group 'org-startup
  939. :version "24.1"
  940. :type 'boolean)
  941. (defcustom org-startup-with-latex-preview nil
  942. "Non-nil means preview LaTeX fragments when loading a new Org file.
  943. This can also be configured on a per-file basis by adding one of
  944. the following lines anywhere in the buffer:
  945. #+STARTUP: latexpreview
  946. #+STARTUP: nolatexpreview"
  947. :group 'org-startup
  948. :version "24.4"
  949. :package-version '(Org . "8.0")
  950. :type 'boolean)
  951. (defcustom org-insert-mode-line-in-empty-file nil
  952. "Non-nil means insert the first line setting Org mode in empty files.
  953. When the function `org-mode' is called interactively in an empty file, this
  954. normally means that the file name does not automatically trigger Org mode.
  955. To ensure that the file will always be in Org mode in the future, a
  956. line enforcing Org mode will be inserted into the buffer, if this option
  957. has been set."
  958. :group 'org-startup
  959. :type 'boolean)
  960. (defcustom org-ellipsis nil
  961. "The ellipsis to use in the Org mode outline.
  962. When nil, just use the standard three dots. When a non-empty string,
  963. use that string instead.
  964. The change affects only Org mode (which will then use its own display table).
  965. Changing this requires executing `\\[org-mode]' in a buffer to become
  966. effective. It cannot be set as a local variable."
  967. :group 'org-startup
  968. :type '(choice (const :tag "Default" nil)
  969. (string :tag "String" :value "...#")))
  970. (defvar org-display-table nil
  971. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  972. (defcustom org-directory "~/org"
  973. "Directory with Org files.
  974. This is just a default location to look for Org files. There is no need
  975. at all to put your files into this directory. It is used in the
  976. following situations:
  977. 1. When a capture template specifies a target file that is not an
  978. absolute path. The path will then be interpreted relative to
  979. `org-directory'
  980. 2. When the value of variable `org-agenda-files' is a single file, any
  981. relative paths in this file will be taken as relative to
  982. `org-directory'."
  983. :group 'org-refile
  984. :group 'org-capture
  985. :type 'directory)
  986. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  987. "Default target for storing notes.
  988. Used as a fall back file for org-capture.el, for templates that
  989. do not specify a target file."
  990. :group 'org-refile
  991. :group 'org-capture
  992. :type 'file)
  993. (defcustom org-reverse-note-order nil
  994. "Non-nil means store new notes at the beginning of a file or entry.
  995. When nil, new notes will be filed to the end of a file or entry.
  996. This can also be a list with cons cells of regular expressions that
  997. are matched against file names, and values."
  998. :group 'org-capture
  999. :group 'org-refile
  1000. :type '(choice
  1001. (const :tag "Reverse always" t)
  1002. (const :tag "Reverse never" nil)
  1003. (repeat :tag "By file name regexp"
  1004. (cons regexp boolean))))
  1005. (defgroup org-keywords nil
  1006. "Keywords in Org mode."
  1007. :tag "Org Keywords"
  1008. :group 'org)
  1009. (defcustom org-closed-keep-when-no-todo nil
  1010. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1011. :group 'org-todo
  1012. :group 'org-keywords
  1013. :version "24.4"
  1014. :package-version '(Org . "8.0")
  1015. :type 'boolean)
  1016. (defgroup org-structure nil
  1017. "Options concerning the general structure of Org files."
  1018. :tag "Org Structure"
  1019. :group 'org)
  1020. (defgroup org-reveal-location nil
  1021. "Options about how to make context of a location visible."
  1022. :tag "Org Reveal Location"
  1023. :group 'org-structure)
  1024. (defcustom org-show-context-detail '((agenda . local)
  1025. (bookmark-jump . lineage)
  1026. (isearch . lineage)
  1027. (default . ancestors))
  1028. "Alist between context and visibility span when revealing a location.
  1029. \\<org-mode-map>Some actions may move point into invisible
  1030. locations. As a consequence, Org always exposes a neighborhood
  1031. around point. How much is shown depends on the initial action,
  1032. or context. Valid contexts are
  1033. agenda when exposing an entry from the agenda
  1034. org-goto when using the command `org-goto' (`\\[org-goto]')
  1035. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1036. tags-tree when constructing a sparse tree based on tags matches
  1037. link-search when exposing search matches associated with a link
  1038. mark-goto when exposing the jump goal of a mark
  1039. bookmark-jump when exposing a bookmark location
  1040. isearch when exiting from an incremental search
  1041. default default for all contexts not set explicitly
  1042. Allowed visibility spans are
  1043. minimal show current headline; if point is not on headline,
  1044. also show entry
  1045. local show current headline, entry and next headline
  1046. ancestors show current headline and its direct ancestors; if
  1047. point is not on headline, also show entry
  1048. ancestors-full show current subtree and its direct ancestors
  1049. lineage show current headline, its direct ancestors and all
  1050. their children; if point is not on headline, also show
  1051. entry and first child
  1052. tree show current headline, its direct ancestors and all
  1053. their children; if point is not on headline, also show
  1054. entry and all children
  1055. canonical show current headline, its direct ancestors along with
  1056. their entries and children; if point is not located on
  1057. the headline, also show current entry and all children
  1058. As special cases, a nil or t value means show all contexts in
  1059. `minimal' or `canonical' view, respectively.
  1060. Some views can make displayed information very compact, but also
  1061. make it harder to edit the location of the match. In such
  1062. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1063. more context."
  1064. :group 'org-reveal-location
  1065. :version "26.1"
  1066. :package-version '(Org . "9.0")
  1067. :type '(choice
  1068. (const :tag "Canonical" t)
  1069. (const :tag "Minimal" nil)
  1070. (repeat :greedy t :tag "Individual contexts"
  1071. (cons
  1072. (choice :tag "Context"
  1073. (const agenda)
  1074. (const org-goto)
  1075. (const occur-tree)
  1076. (const tags-tree)
  1077. (const link-search)
  1078. (const mark-goto)
  1079. (const bookmark-jump)
  1080. (const isearch)
  1081. (const default))
  1082. (choice :tag "Detail level"
  1083. (const minimal)
  1084. (const local)
  1085. (const ancestors)
  1086. (const ancestors-full)
  1087. (const lineage)
  1088. (const tree)
  1089. (const canonical))))))
  1090. (defcustom org-indirect-buffer-display 'other-window
  1091. "How should indirect tree buffers be displayed?
  1092. This applies to indirect buffers created with the commands
  1093. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1094. Valid values are:
  1095. current-window Display in the current window
  1096. other-window Just display in another window.
  1097. dedicated-frame Create one new frame, and re-use it each time.
  1098. new-frame Make a new frame each time. Note that in this case
  1099. previously-made indirect buffers are kept, and you need to
  1100. kill these buffers yourself."
  1101. :group 'org-structure
  1102. :group 'org-agenda-windows
  1103. :type '(choice
  1104. (const :tag "In current window" current-window)
  1105. (const :tag "In current frame, other window" other-window)
  1106. (const :tag "Each time a new frame" new-frame)
  1107. (const :tag "One dedicated frame" dedicated-frame)))
  1108. (defconst org-file-apps-gnu
  1109. '((remote . emacs)
  1110. (system . mailcap)
  1111. (t . mailcap))
  1112. "Default file applications on a UNIX or GNU/Linux system.
  1113. See `org-file-apps'.")
  1114. (defconst org-file-apps-macos
  1115. '((remote . emacs)
  1116. (system . "open %s")
  1117. ("ps.gz" . "gv %s")
  1118. ("eps.gz" . "gv %s")
  1119. ("dvi" . "xdvi %s")
  1120. ("fig" . "xfig %s")
  1121. (t . "open %s"))
  1122. "Default file applications on a macOS system.
  1123. The system \"open\" is known as a default, but we use X11 applications
  1124. for some files for which the OS does not have a good default.
  1125. See `org-file-apps'.")
  1126. (defconst org-file-apps-windowsnt
  1127. (list '(remote . emacs)
  1128. (cons 'system (lambda (file _path)
  1129. (with-no-warnings (w32-shell-execute "open" file))))
  1130. (cons t (lambda (file _path)
  1131. (with-no-warnings (w32-shell-execute "open" file)))))
  1132. "Default file applications on a Windows NT system.
  1133. The system \"open\" is used for most files.
  1134. See `org-file-apps'.")
  1135. (defcustom org-file-apps
  1136. '((auto-mode . emacs)
  1137. (directory . emacs)
  1138. ("\\.mm\\'" . default)
  1139. ("\\.x?html?\\'" . default)
  1140. ("\\.pdf\\'" . default))
  1141. "Applications for opening `file:path' items in a document.
  1142. \\<org-mode-map>
  1143. Org mode uses system defaults for different file types, but you
  1144. can use this variable to set the application for a given file
  1145. extension. The entries in this list are cons cells where the car
  1146. identifies files and the cdr the corresponding command.
  1147. Possible values for the file identifier are:
  1148. \"string\" A string as a file identifier can be interpreted in different
  1149. ways, depending on its contents:
  1150. - Alphanumeric characters only:
  1151. Match links with this file extension.
  1152. Example: (\"pdf\" . \"evince %s\")
  1153. to open PDFs with evince.
  1154. - Regular expression: Match links where the
  1155. filename matches the regexp. If you want to
  1156. use groups here, use shy groups.
  1157. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1158. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1159. to open *.html and *.xhtml with firefox.
  1160. - Regular expression which contains (non-shy) groups:
  1161. Match links where the whole link, including \"::\", and
  1162. anything after that, matches the regexp.
  1163. In a custom command string, %1, %2, etc. are replaced with
  1164. the parts of the link that were matched by the groups.
  1165. For backwards compatibility, if a command string is given
  1166. that does not use any of the group matches, this case is
  1167. handled identically to the second one (i.e. match against
  1168. file name only).
  1169. In a custom function, you can access the group matches with
  1170. (match-string n link).
  1171. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1172. \"evince -p %1 %s\")
  1173. to open [[file:document.pdf::5]] with evince at page 5.
  1174. `directory' Matches a directory
  1175. `remote' Matches a remote file, accessible through tramp or efs.
  1176. Remote files most likely should be visited through Emacs
  1177. because external applications cannot handle such paths.
  1178. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1179. so all files Emacs knows how to handle. Using this with
  1180. command `emacs' will open most files in Emacs. Beware that this
  1181. will also open html files inside Emacs, unless you add
  1182. (\"html\" . default) to the list as well.
  1183. `system' The system command to open files, like `open' on Windows
  1184. and macOS, and mailcap under GNU/Linux. This is the command
  1185. that will be selected if you call `org-open-at-point' with a
  1186. double prefix argument (`\\[universal-argument] \
  1187. \\[universal-argument] \\[org-open-at-point]').
  1188. t Default for files not matched by any of the other options.
  1189. Possible values for the command are:
  1190. `emacs' The file will be visited by the current Emacs process.
  1191. `default' Use the default application for this file type, which is the
  1192. association for t in the list, most likely in the system-specific
  1193. part. This can be used to overrule an unwanted setting in the
  1194. system-specific variable.
  1195. `system' Use the system command for opening files, like \"open\".
  1196. This command is specified by the entry whose car is `system'.
  1197. Most likely, the system-specific version of this variable
  1198. does define this command, but you can overrule/replace it
  1199. here.
  1200. `mailcap' Use command specified in the mailcaps.
  1201. string A command to be executed by a shell; %s will be replaced
  1202. by the path to the file.
  1203. function A Lisp function, which will be called with two arguments:
  1204. the file path and the original link string, without the
  1205. \"file:\" prefix.
  1206. For more examples, see the system specific constants
  1207. `org-file-apps-macos'
  1208. `org-file-apps-windowsnt'
  1209. `org-file-apps-gnu'."
  1210. :group 'org
  1211. :package-version '(Org . "9.4")
  1212. :type '(repeat
  1213. (cons (choice :value ""
  1214. (string :tag "Extension")
  1215. (const :tag "System command to open files" system)
  1216. (const :tag "Default for unrecognized files" t)
  1217. (const :tag "Remote file" remote)
  1218. (const :tag "Links to a directory" directory)
  1219. (const :tag "Any files that have Emacs modes"
  1220. auto-mode))
  1221. (choice :value ""
  1222. (const :tag "Visit with Emacs" emacs)
  1223. (const :tag "Use default" default)
  1224. (const :tag "Use the system command" system)
  1225. (string :tag "Command")
  1226. (function :tag "Function")))))
  1227. (defcustom org-open-non-existing-files nil
  1228. "Non-nil means `org-open-file' opens non-existing files.
  1229. When nil, an error is thrown.
  1230. This variable applies only to external applications because they
  1231. might choke on non-existing files. If the link is to a file that
  1232. will be opened in Emacs, the variable is ignored."
  1233. :group 'org
  1234. :type 'boolean
  1235. :safe #'booleanp)
  1236. (defcustom org-open-directory-means-index-dot-org nil
  1237. "When non-nil a link to a directory really means to \"index.org\".
  1238. When nil, following a directory link runs Dired or opens
  1239. a finder/explorer window on that directory."
  1240. :group 'org
  1241. :type 'boolean
  1242. :safe #'booleanp)
  1243. (defcustom org-bookmark-names-plist
  1244. '(:last-capture "org-capture-last-stored"
  1245. :last-refile "org-refile-last-stored"
  1246. :last-capture-marker "org-capture-last-stored-marker")
  1247. "Names for bookmarks automatically set by some Org commands.
  1248. This can provide strings as names for a number of bookmarks Org sets
  1249. automatically. The following keys are currently implemented:
  1250. :last-capture
  1251. :last-capture-marker
  1252. :last-refile
  1253. When a key does not show up in the property list, the corresponding bookmark
  1254. is not set."
  1255. :group 'org-structure
  1256. :type 'plist)
  1257. (defgroup org-cycle nil
  1258. "Options concerning visibility cycling in Org mode."
  1259. :tag "Org Cycle"
  1260. :group 'org-structure)
  1261. (defcustom org-cycle-skip-children-state-if-no-children t
  1262. "Non-nil means skip CHILDREN state in entries that don't have any."
  1263. :group 'org-cycle
  1264. :type 'boolean)
  1265. (defcustom org-cycle-max-level nil
  1266. "Maximum level which should still be subject to visibility cycling.
  1267. Levels higher than this will, for cycling, be treated as text, not a headline.
  1268. When `org-odd-levels-only' is set, a value of N in this variable actually
  1269. means 2N-1 stars as the limiting headline.
  1270. When nil, cycle all levels.
  1271. Note that the limiting level of cycling is also influenced by
  1272. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1273. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1274. than its value."
  1275. :group 'org-cycle
  1276. :type '(choice
  1277. (const :tag "No limit" nil)
  1278. (integer :tag "Maximum level")))
  1279. (defcustom org-hide-block-startup nil
  1280. "Non-nil means entering Org mode will fold all blocks.
  1281. This can also be set in on a per-file basis with
  1282. #+STARTUP: hideblocks
  1283. #+STARTUP: showblocks"
  1284. :group 'org-startup
  1285. :group 'org-cycle
  1286. :type 'boolean)
  1287. (defcustom org-cycle-global-at-bob nil
  1288. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1289. This makes it possible to do global cycling without having to use `S-TAB'
  1290. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1291. line of the buffer
  1292. must not be a headline -- it may be empty or some other text.
  1293. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1294. sure the cursor stays at the beginning of the buffer.
  1295. When this option is nil, don't do anything special at the beginning of
  1296. the buffer."
  1297. :group 'org-cycle
  1298. :type 'boolean)
  1299. (defcustom org-cycle-level-after-item/entry-creation t
  1300. "Non-nil means cycle entry level or item indentation in new empty entries.
  1301. When the cursor is at the end of an empty headline, i.e., with only stars
  1302. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1303. and then all possible ancestor states, before returning to the original state.
  1304. This makes data entry extremely fast: M-RET to create a new headline,
  1305. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1306. When the cursor is at the end of an empty plain list item, one TAB will
  1307. make it a subitem, two or more tabs will back up to make this an item
  1308. higher up in the item hierarchy."
  1309. :group 'org-cycle
  1310. :type 'boolean)
  1311. (defcustom org-cycle-emulate-tab t
  1312. "Where should `org-cycle' emulate TAB.
  1313. nil Never
  1314. white Only in completely white lines
  1315. whitestart Only at the beginning of lines, before the first non-white char
  1316. t Everywhere except in headlines
  1317. exc-hl-bol Everywhere except at the start of a headline
  1318. If TAB is used in a place where it does not emulate TAB, the current subtree
  1319. visibility is cycled."
  1320. :group 'org-cycle
  1321. :type '(choice (const :tag "Never" nil)
  1322. (const :tag "Only in completely white lines" white)
  1323. (const :tag "Before first char in a line" whitestart)
  1324. (const :tag "Everywhere except in headlines" t)
  1325. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1326. (defcustom org-cycle-separator-lines 2
  1327. "Number of empty lines needed to keep an empty line between collapsed trees.
  1328. If you leave an empty line between the end of a subtree and the following
  1329. headline, this empty line is hidden when the subtree is folded.
  1330. Org mode will leave (exactly) one empty line visible if the number of
  1331. empty lines is equal or larger to the number given in this variable.
  1332. So the default 2 means at least 2 empty lines after the end of a subtree
  1333. are needed to produce free space between a collapsed subtree and the
  1334. following headline.
  1335. If the number is negative, and the number of empty lines is at least -N,
  1336. all empty lines are shown.
  1337. Special case: when 0, never leave empty lines in collapsed view."
  1338. :group 'org-cycle
  1339. :type 'integer)
  1340. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1341. (defcustom org-pre-cycle-hook nil
  1342. "Hook that is run before visibility cycling is happening.
  1343. The function(s) in this hook must accept a single argument which indicates
  1344. the new state that will be set right after running this hook. The
  1345. argument is a symbol. Before a global state change, it can have the values
  1346. `overview', `content', or `all'. Before a local state change, it can have
  1347. the values `folded', `children', or `subtree'."
  1348. :group 'org-cycle
  1349. :type 'hook)
  1350. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1351. org-cycle-hide-drawers
  1352. org-cycle-show-empty-lines
  1353. org-optimize-window-after-visibility-change)
  1354. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1355. The function(s) in this hook must accept a single argument which indicates
  1356. the new state that was set by the most recent `org-cycle' command. The
  1357. argument is a symbol. After a global state change, it can have the values
  1358. `overview', `contents', or `all'. After a local state change, it can have
  1359. the values `folded', `children', or `subtree'."
  1360. :group 'org-cycle
  1361. :package-version '(Org . "9.4")
  1362. :type 'hook)
  1363. (defgroup org-edit-structure nil
  1364. "Options concerning structure editing in Org mode."
  1365. :tag "Org Edit Structure"
  1366. :group 'org-structure)
  1367. (defcustom org-odd-levels-only nil
  1368. "Non-nil means skip even levels and only use odd levels for the outline.
  1369. This has the effect that two stars are being added/taken away in
  1370. promotion/demotion commands. It also influences how levels are
  1371. handled by the exporters.
  1372. Changing it requires restart of `font-lock-mode' to become effective
  1373. for fontification also in regions already fontified.
  1374. You may also set this on a per-file basis by adding one of the following
  1375. lines to the buffer:
  1376. #+STARTUP: odd
  1377. #+STARTUP: oddeven"
  1378. :group 'org-edit-structure
  1379. :group 'org-appearance
  1380. :type 'boolean)
  1381. (defcustom org-adapt-indentation nil
  1382. "Non-nil means adapt indentation to outline node level.
  1383. When set to t, Org assumes that you write outlines by indenting
  1384. text in each node to align with the headline, after the stars.
  1385. When this variable is set to `headline-data', Org only adapts the
  1386. indentation of the data lines right below the headline, such as
  1387. planning/clock lines and property/logbook drawers.
  1388. The following issues are influenced by this variable:
  1389. - The indentation is increased by one space in a demotion
  1390. command, and decreased by one in a promotion command. However,
  1391. in the latter case, if shifting some line in the entry body
  1392. would alter document structure (e.g., insert a new headline),
  1393. indentation is not changed at all.
  1394. - Property drawers and planning information is inserted indented
  1395. when this variable is set. When nil, they will not be indented.
  1396. - TAB indents a line relative to current level. The lines below
  1397. a headline will be indented when this variable is set to t.
  1398. Note that this is all about true indentation, by adding and
  1399. removing space characters. See also \"org-indent.el\" which does
  1400. level-dependent indentation in a virtual way, i.e. at display
  1401. time in Emacs."
  1402. :group 'org-edit-structure
  1403. :type '(choice
  1404. (const :tag "Adapt indentation for all lines" t)
  1405. (const :tag "Adapt indentation for headline data lines"
  1406. headline-data)
  1407. (const :tag "Do not adapt indentation at all" nil))
  1408. :safe (lambda (x) (memq x '(t nil headline-data))))
  1409. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1410. (defcustom org-special-ctrl-a/e nil
  1411. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1412. When t, `C-a' will bring back the cursor to the beginning of the
  1413. headline text, i.e. after the stars and after a possible TODO
  1414. keyword. In an item, this will be the position after bullet and
  1415. check-box, if any. When the cursor is already at that position,
  1416. another `C-a' will bring it to the beginning of the line.
  1417. `C-e' will jump to the end of the headline, ignoring the presence
  1418. of tags in the headline. A second `C-e' will then jump to the
  1419. true end of the line, after any tags. This also means that, when
  1420. this variable is non-nil, `C-e' also will never jump beyond the
  1421. end of the heading of a folded section, i.e. not after the
  1422. ellipses.
  1423. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1424. normally, going to the true line boundary first. Only a directly
  1425. following, identical keypress will bring the cursor to the
  1426. special positions.
  1427. This may also be a cons cell where the behavior for `C-a' and
  1428. `C-e' is set separately."
  1429. :group 'org-edit-structure
  1430. :type '(choice
  1431. (const :tag "off" nil)
  1432. (const :tag "on: after stars/bullet and before tags first" t)
  1433. (const :tag "reversed: true line boundary first" reversed)
  1434. (cons :tag "Set C-a and C-e separately"
  1435. (choice :tag "Special C-a"
  1436. (const :tag "off" nil)
  1437. (const :tag "on: after stars/bullet first" t)
  1438. (const :tag "reversed: before stars/bullet first" reversed))
  1439. (choice :tag "Special C-e"
  1440. (const :tag "off" nil)
  1441. (const :tag "on: before tags first" t)
  1442. (const :tag "reversed: after tags first" reversed)))))
  1443. (defcustom org-special-ctrl-k nil
  1444. "Non-nil means `C-k' will behave specially in headlines.
  1445. When nil, `C-k' will call the default `kill-line' command.
  1446. When t, the following will happen while the cursor is in the headline:
  1447. - When at the beginning of a headline, kill the entire subtree.
  1448. - When in the middle of the headline text, kill the text up to the tags.
  1449. - When after the headline text and before the tags, kill all the tags."
  1450. :group 'org-edit-structure
  1451. :type 'boolean)
  1452. (defcustom org-ctrl-k-protect-subtree nil
  1453. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1454. When set to the symbol `error', simply throw an error when `C-k' is
  1455. used to kill (part-of) a headline that has hidden text behind it.
  1456. Any other non-nil value will result in a query to the user, if it is
  1457. OK to kill that hidden subtree. When nil, kill without remorse."
  1458. :group 'org-edit-structure
  1459. :version "24.1"
  1460. :type '(choice
  1461. (const :tag "Do not protect hidden subtrees" nil)
  1462. (const :tag "Protect hidden subtrees with a security query" t)
  1463. (const :tag "Never kill a hidden subtree with C-k" error)))
  1464. (defcustom org-special-ctrl-o t
  1465. "Non-nil means, make `C-o' insert a row in tables."
  1466. :group 'org-edit-structure
  1467. :type 'boolean)
  1468. (defcustom org-catch-invisible-edits nil
  1469. "Check if in invisible region before inserting or deleting a character.
  1470. Valid values are:
  1471. nil Do not check, so just do invisible edits.
  1472. error Throw an error and do nothing.
  1473. show Make point visible, and do the requested edit.
  1474. show-and-error Make point visible, then throw an error and abort the edit.
  1475. smart Make point visible, and do insertion/deletion if it is
  1476. adjacent to visible text and the change feels predictable.
  1477. Never delete a previously invisible character or add in the
  1478. middle or right after an invisible region. Basically, this
  1479. allows insertion and backward-delete right before ellipses.
  1480. FIXME: maybe in this case we should not even show?"
  1481. :group 'org-edit-structure
  1482. :version "24.1"
  1483. :type '(choice
  1484. (const :tag "Do not check" nil)
  1485. (const :tag "Throw error when trying to edit" error)
  1486. (const :tag "Unhide, but do not do the edit" show-and-error)
  1487. (const :tag "Show invisible part and do the edit" show)
  1488. (const :tag "Be smart and do the right thing" smart)))
  1489. (defcustom org-yank-folded-subtrees t
  1490. "Non-nil means when yanking subtrees, fold them.
  1491. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1492. it starts with a heading and all other headings in it are either children
  1493. or siblings, then fold all the subtrees. However, do this only if no
  1494. text after the yank would be swallowed into a folded tree by this action."
  1495. :group 'org-edit-structure
  1496. :type 'boolean)
  1497. (defcustom org-yank-adjusted-subtrees nil
  1498. "Non-nil means when yanking subtrees, adjust the level.
  1499. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1500. this function for details."
  1501. :group 'org-edit-structure
  1502. :type 'boolean)
  1503. (defcustom org-M-RET-may-split-line '((default . t))
  1504. "Non-nil means M-RET will split the line at the cursor position.
  1505. When nil, it will go to the end of the line before making a
  1506. new line.
  1507. You may also set this option in a different way for different
  1508. contexts. Valid contexts are:
  1509. headline when creating a new headline
  1510. item when creating a new item
  1511. table in a table field
  1512. default the value to be used for all contexts not explicitly
  1513. customized"
  1514. :group 'org-structure
  1515. :group 'org-table
  1516. :type '(choice
  1517. (const :tag "Always" t)
  1518. (const :tag "Never" nil)
  1519. (repeat :greedy t :tag "Individual contexts"
  1520. (cons
  1521. (choice :tag "Context"
  1522. (const headline)
  1523. (const item)
  1524. (const table)
  1525. (const default))
  1526. (boolean)))))
  1527. (defcustom org-insert-heading-respect-content nil
  1528. "Non-nil means insert new headings after the current subtree.
  1529. \\<org-mode-map>
  1530. When nil, the new heading is created directly after the current line.
  1531. The commands `\\[org-insert-heading-respect-content]' and \
  1532. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1533. for the duration of the command."
  1534. :group 'org-structure
  1535. :type 'boolean)
  1536. (defcustom org-blank-before-new-entry '((heading . auto)
  1537. (plain-list-item . auto))
  1538. "Should `org-insert-heading' leave a blank line before new heading/item?
  1539. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1540. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1541. which case Org will look at the surrounding headings/items and try to
  1542. make an intelligent decision whether to insert a blank line or not."
  1543. :group 'org-edit-structure
  1544. :type '(list
  1545. (cons (const heading)
  1546. (choice (const :tag "Never" nil)
  1547. (const :tag "Always" t)
  1548. (const :tag "Auto" auto)))
  1549. (cons (const plain-list-item)
  1550. (choice (const :tag "Never" nil)
  1551. (const :tag "Always" t)
  1552. (const :tag "Auto" auto)))))
  1553. (defcustom org-insert-heading-hook nil
  1554. "Hook being run after inserting a new heading."
  1555. :group 'org-edit-structure
  1556. :type 'hook)
  1557. (defgroup org-sparse-trees nil
  1558. "Options concerning sparse trees in Org mode."
  1559. :tag "Org Sparse Trees"
  1560. :group 'org-structure)
  1561. (defcustom org-highlight-sparse-tree-matches t
  1562. "Non-nil means highlight all matches that define a sparse tree.
  1563. The highlights will automatically disappear the next time the buffer is
  1564. changed by an edit command."
  1565. :group 'org-sparse-trees
  1566. :type 'boolean)
  1567. (defcustom org-remove-highlights-with-change t
  1568. "Non-nil means any change to the buffer will remove temporary highlights.
  1569. \\<org-mode-map>\
  1570. Such highlights are created by `org-occur' and `org-clock-display'.
  1571. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1572. to get rid of the highlights.
  1573. The highlights created by `org-latex-preview' always need
  1574. `\\[org-latex-preview]' to be removed."
  1575. :group 'org-sparse-trees
  1576. :group 'org-time
  1577. :type 'boolean)
  1578. (defcustom org-occur-case-fold-search t
  1579. "Non-nil means `org-occur' should be case-insensitive.
  1580. If set to `smart' the search will be case-insensitive only if it
  1581. doesn't specify any upper case character."
  1582. :group 'org-sparse-trees
  1583. :version "26.1"
  1584. :type '(choice
  1585. (const :tag "Case-sensitive" nil)
  1586. (const :tag "Case-insensitive" t)
  1587. (const :tag "Case-insensitive for lower case searches only" smart)))
  1588. (defcustom org-occur-hook '(org-first-headline-recenter)
  1589. "Hook that is run after `org-occur' has constructed a sparse tree.
  1590. This can be used to recenter the window to show as much of the structure
  1591. as possible."
  1592. :group 'org-sparse-trees
  1593. :type 'hook)
  1594. (defcustom org-self-insert-cluster-for-undo nil
  1595. "Non-nil means cluster self-insert commands for undo when possible.
  1596. If this is set, then, like in the Emacs command loop, 20 consecutive
  1597. characters will be undone together.
  1598. This is configurable, because there is some impact on typing performance."
  1599. :group 'org-table
  1600. :type 'boolean)
  1601. (defvaralias 'org-activate-links 'org-highlight-links)
  1602. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1603. "Types of links that should be highlighted in Org files.
  1604. This is a list of symbols, each one of them leading to the
  1605. highlighting of a certain link type.
  1606. You can still open links that are not highlighted.
  1607. In principle, it does not hurt to turn on highlighting for all
  1608. link types. There may be a small gain when turning off unused
  1609. link types. The types are:
  1610. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1611. angle Links in angular brackets that may contain whitespace like
  1612. <bbdb:Carsten Dominik>.
  1613. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1614. radio Text that is matched by a radio target, see manual for details.
  1615. tag Tag settings in a headline (link to tag search).
  1616. date Time stamps (link to calendar).
  1617. footnote Footnote labels.
  1618. If you set this variable during an Emacs session, use `org-mode-restart'
  1619. in the Org buffer so that the change takes effect."
  1620. :group 'org-appearance
  1621. :type '(set :greedy t
  1622. (const :tag "Double bracket links" bracket)
  1623. (const :tag "Angular bracket links" angle)
  1624. (const :tag "Plain text links" plain)
  1625. (const :tag "Radio target matches" radio)
  1626. (const :tag "Tags" tag)
  1627. (const :tag "Timestamps" date)
  1628. (const :tag "Footnotes" footnote)))
  1629. (defcustom org-mark-ring-length 4
  1630. "Number of different positions to be recorded in the ring.
  1631. Changing this requires a restart of Emacs to work correctly."
  1632. :group 'org-link-follow
  1633. :type 'integer)
  1634. (defgroup org-todo nil
  1635. "Options concerning TODO items in Org mode."
  1636. :tag "Org TODO"
  1637. :group 'org)
  1638. (defgroup org-progress nil
  1639. "Options concerning Progress logging in Org mode."
  1640. :tag "Org Progress"
  1641. :group 'org-time)
  1642. (defvar org-todo-interpretation-widgets
  1643. '((:tag "Sequence (cycling hits every state)" sequence)
  1644. (:tag "Type (cycling directly to DONE)" type))
  1645. "The available interpretation symbols for customizing `org-todo-keywords'.
  1646. Interested libraries should add to this list.")
  1647. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1648. "List of TODO entry keyword sequences and their interpretation.
  1649. \\<org-mode-map>This is a list of sequences.
  1650. Each sequence starts with a symbol, either `sequence' or `type',
  1651. indicating if the keywords should be interpreted as a sequence of
  1652. action steps, or as different types of TODO items. The first
  1653. keywords are states requiring action - these states will select a headline
  1654. for inclusion into the global TODO list Org produces. If one of the
  1655. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1656. signify that no further action is necessary. If \"|\" is not found,
  1657. the last keyword is treated as the only DONE state of the sequence.
  1658. The command `\\[org-todo]' cycles an entry through these states, and one
  1659. additional state where no keyword is present. For details about this
  1660. cycling, see the manual.
  1661. TODO keywords and interpretation can also be set on a per-file basis with
  1662. the special #+SEQ_TODO and #+TYP_TODO lines.
  1663. Each keyword can optionally specify a character for fast state selection
  1664. \(in combination with the variable `org-use-fast-todo-selection')
  1665. and specifiers for state change logging, using the same syntax that
  1666. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1667. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1668. indicates to record a time stamp each time this state is selected.
  1669. Each keyword may also specify if a timestamp or a note should be
  1670. recorded when entering or leaving the state, by adding additional
  1671. characters in the parenthesis after the keyword. This looks like this:
  1672. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1673. record only the time of the state change. With X and Y being either
  1674. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1675. Y when leaving the state if and only if the *target* state does not
  1676. define X. You may omit any of the fast-selection key or X or /Y,
  1677. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1678. For backward compatibility, this variable may also be just a list
  1679. of keywords. In this case the interpretation (sequence or type) will be
  1680. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1681. :group 'org-todo
  1682. :group 'org-keywords
  1683. :type '(choice
  1684. (repeat :tag "Old syntax, just keywords"
  1685. (string :tag "Keyword"))
  1686. (repeat :tag "New syntax"
  1687. (cons
  1688. (choice
  1689. :tag "Interpretation"
  1690. ;;Quick and dirty way to see
  1691. ;;`org-todo-interpretation'. This takes the
  1692. ;;place of item arguments
  1693. :convert-widget
  1694. (lambda (widget)
  1695. (widget-put widget
  1696. :args (mapcar
  1697. (lambda (x)
  1698. (widget-convert
  1699. (cons 'const x)))
  1700. org-todo-interpretation-widgets))
  1701. widget))
  1702. (repeat
  1703. (string :tag "Keyword"))))))
  1704. (defvar-local org-todo-keywords-1 nil
  1705. "All TODO and DONE keywords active in a buffer.")
  1706. (defvar org-todo-keywords-for-agenda nil)
  1707. (defvar org-done-keywords-for-agenda nil)
  1708. (defvar org-todo-keyword-alist-for-agenda nil)
  1709. (defvar org-tag-alist-for-agenda nil
  1710. "Alist of all tags from all agenda files.")
  1711. (defvar org-tag-groups-alist-for-agenda nil
  1712. "Alist of all groups tags from all current agenda files.")
  1713. (defvar-local org-tag-groups-alist nil)
  1714. (defvar org-agenda-contributing-files nil)
  1715. (defvar-local org-current-tag-alist nil
  1716. "Alist of all tag groups in current buffer.
  1717. This variable takes into consideration `org-tag-alist',
  1718. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1719. (defvar-local org-not-done-keywords nil)
  1720. (defvar-local org-done-keywords nil)
  1721. (defvar-local org-todo-heads nil)
  1722. (defvar-local org-todo-sets nil)
  1723. (defvar-local org-todo-log-states nil)
  1724. (defvar-local org-todo-kwd-alist nil)
  1725. (defvar-local org-todo-key-alist nil)
  1726. (defvar-local org-todo-key-trigger nil)
  1727. (defcustom org-todo-interpretation 'sequence
  1728. "Controls how TODO keywords are interpreted.
  1729. This variable is in principle obsolete and is only used for
  1730. backward compatibility, if the interpretation of todo keywords is
  1731. not given already in `org-todo-keywords'. See that variable for
  1732. more information."
  1733. :group 'org-todo
  1734. :group 'org-keywords
  1735. :type '(choice (const sequence)
  1736. (const type)))
  1737. (defcustom org-use-fast-todo-selection 'auto
  1738. "\\<org-mode-map>\
  1739. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1740. This variable describes if and under what circumstances the cycling
  1741. mechanism for TODO keywords will be replaced by a single-key, direct
  1742. selection scheme, where the choices are displayed in a little window.
  1743. When nil, fast selection is never used. This means that the command
  1744. will always switch to the next state.
  1745. When it is the symbol `auto', fast selection is whenever selection
  1746. keys have been defined.
  1747. `expert' is like `auto', but no special window with the keyword
  1748. will be shown, choices will only be listed in the prompt.
  1749. In all cases, the special interface is only used if access keys have
  1750. actually been assigned by the user, i.e. if keywords in the configuration
  1751. are followed by a letter in parenthesis, like TODO(t)."
  1752. :group 'org-todo
  1753. :set (lambda (var val)
  1754. (cond
  1755. ((eq var t) (set var 'auto))
  1756. ((eq var 'prefix) (set var nil))
  1757. (t (set var val))))
  1758. :type '(choice
  1759. (const :tag "Never" nil)
  1760. (const :tag "Automatically, when key letter have been defined" auto)
  1761. (const :tag "Automatically, but don't show the selection window" expert)))
  1762. (defcustom org-provide-todo-statistics t
  1763. "Non-nil means update todo statistics after insert and toggle.
  1764. ALL-HEADLINES means update todo statistics by including headlines
  1765. with no TODO keyword as well, counting them as not done.
  1766. A list of TODO keywords means the same, but skip keywords that are
  1767. not in this list.
  1768. When set to a list of two lists, the first list contains keywords
  1769. to consider as TODO keywords, the second list contains keywords
  1770. to consider as DONE keywords.
  1771. When this is set, todo statistics is updated in the parent of the
  1772. current entry each time a todo state is changed."
  1773. :group 'org-todo
  1774. :type '(choice
  1775. (const :tag "Yes, only for TODO entries" t)
  1776. (const :tag "Yes, including all entries" all-headlines)
  1777. (repeat :tag "Yes, for TODOs in this list"
  1778. (string :tag "TODO keyword"))
  1779. (list :tag "Yes, for TODOs and DONEs in these lists"
  1780. (repeat (string :tag "TODO keyword"))
  1781. (repeat (string :tag "DONE keyword")))
  1782. (other :tag "No TODO statistics" nil)))
  1783. (defcustom org-hierarchical-todo-statistics t
  1784. "Non-nil means TODO statistics covers just direct children.
  1785. When nil, all entries in the subtree are considered.
  1786. This has only an effect if `org-provide-todo-statistics' is set.
  1787. To set this to nil for only a single subtree, use a COOKIE_DATA
  1788. property and include the word \"recursive\" into the value."
  1789. :group 'org-todo
  1790. :type 'boolean)
  1791. (defcustom org-after-todo-state-change-hook nil
  1792. "Hook which is run after the state of a TODO item was changed.
  1793. The new state (a string with a TODO keyword, or nil) is available in the
  1794. Lisp variable `org-state'."
  1795. :group 'org-todo
  1796. :type 'hook)
  1797. (defvar org-blocker-hook nil
  1798. "Hook for functions that are allowed to block a state change.
  1799. Functions in this hook should not modify the buffer.
  1800. Each function gets as its single argument a property list,
  1801. see `org-trigger-hook' for more information about this list.
  1802. If any of the functions in this hook returns nil, the state change
  1803. is blocked.")
  1804. (defvar org-trigger-hook nil
  1805. "Hook for functions that are triggered by a state change.
  1806. Each function gets as its single argument a property list with at
  1807. least the following elements:
  1808. (:type type-of-change :position pos-at-entry-start
  1809. :from old-state :to new-state)
  1810. Depending on the type, more properties may be present.
  1811. This mechanism is currently implemented for:
  1812. TODO state changes
  1813. ------------------
  1814. :type todo-state-change
  1815. :from previous state (keyword as a string), or nil, or a symbol
  1816. `todo' or `done', to indicate the general type of state.
  1817. :to new state, like in :from")
  1818. (defcustom org-enforce-todo-dependencies nil
  1819. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1820. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1821. be blocked if any prior sibling is not yet done.
  1822. Finally, if the parent is blocked because of ordered siblings of its own,
  1823. the child will also be blocked."
  1824. :set (lambda (var val)
  1825. (set var val)
  1826. (if val
  1827. (add-hook 'org-blocker-hook
  1828. 'org-block-todo-from-children-or-siblings-or-parent)
  1829. (remove-hook 'org-blocker-hook
  1830. 'org-block-todo-from-children-or-siblings-or-parent)))
  1831. :group 'org-todo
  1832. :type 'boolean)
  1833. (defcustom org-enforce-todo-checkbox-dependencies nil
  1834. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1835. When this is nil, checkboxes have no influence on switching TODO states.
  1836. When non-nil, you first need to check off all check boxes before the TODO
  1837. entry can be switched to DONE.
  1838. This variable needs to be set before org.el is loaded, and you need to
  1839. restart Emacs after a change to make the change effective. The only way
  1840. to change it while Emacs is running is through the customize interface."
  1841. :set (lambda (var val)
  1842. (set var val)
  1843. (if val
  1844. (add-hook 'org-blocker-hook
  1845. 'org-block-todo-from-checkboxes)
  1846. (remove-hook 'org-blocker-hook
  1847. 'org-block-todo-from-checkboxes)))
  1848. :group 'org-todo
  1849. :type 'boolean)
  1850. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1851. "Non-nil means inserting a TODO heading is treated as state change.
  1852. So when the command `\\[org-insert-todo-heading]' is used, state change
  1853. logging will apply if appropriate. When nil, the new TODO item will
  1854. be inserted directly, and no logging will take place."
  1855. :group 'org-todo
  1856. :type 'boolean)
  1857. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1858. "Non-nil means switching TODO states with S-cursor counts as state change.
  1859. This is the default behavior. However, setting this to nil allows a
  1860. convenient way to select a TODO state and bypass any logging associated
  1861. with that."
  1862. :group 'org-todo
  1863. :type 'boolean)
  1864. (defcustom org-todo-state-tags-triggers nil
  1865. "Tag changes that should be triggered by TODO state changes.
  1866. This is a list. Each entry is
  1867. (state-change (tag . flag) .......)
  1868. State-change can be a string with a state, and empty string to indicate the
  1869. state that has no TODO keyword, or it can be one of the symbols `todo'
  1870. or `done', meaning any not-done or done state, respectively."
  1871. :group 'org-todo
  1872. :group 'org-tags
  1873. :type '(repeat
  1874. (cons (choice :tag "When changing to"
  1875. (const :tag "Not-done state" todo)
  1876. (const :tag "Done state" done)
  1877. (string :tag "State"))
  1878. (repeat
  1879. (cons :tag "Tag action"
  1880. (string :tag "Tag")
  1881. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1882. (defcustom org-log-done nil
  1883. "Information to record when a task moves to the DONE state.
  1884. Possible values are:
  1885. nil Don't add anything, just change the keyword
  1886. time Add a time stamp to the task
  1887. note Prompt for a note and add it with template `org-log-note-headings'
  1888. This option can also be set with on a per-file-basis with
  1889. #+STARTUP: nologdone
  1890. #+STARTUP: logdone
  1891. #+STARTUP: lognotedone
  1892. You can have local logging settings for a subtree by setting the LOGGING
  1893. property to one or more of these keywords."
  1894. :group 'org-todo
  1895. :group 'org-progress
  1896. :type '(choice
  1897. (const :tag "No logging" nil)
  1898. (const :tag "Record CLOSED timestamp" time)
  1899. (const :tag "Record CLOSED timestamp with note." note)))
  1900. ;; Normalize old uses of org-log-done.
  1901. (cond
  1902. ((eq org-log-done t) (setq org-log-done 'time))
  1903. ((and (listp org-log-done) (memq 'done org-log-done))
  1904. (setq org-log-done 'note)))
  1905. (defcustom org-log-reschedule nil
  1906. "Information to record when the scheduling date of a task is modified.
  1907. Possible values are:
  1908. nil Don't add anything, just change the date
  1909. time Add a time stamp to the task
  1910. note Prompt for a note and add it with template `org-log-note-headings'
  1911. This option can also be set with on a per-file-basis with
  1912. #+STARTUP: nologreschedule
  1913. #+STARTUP: logreschedule
  1914. #+STARTUP: lognotereschedule
  1915. You can have local logging settings for a subtree by setting the LOGGING
  1916. property to one or more of these keywords.
  1917. This variable has an effect when calling `org-schedule' or
  1918. `org-agenda-schedule' only."
  1919. :group 'org-todo
  1920. :group 'org-progress
  1921. :type '(choice
  1922. (const :tag "No logging" nil)
  1923. (const :tag "Record timestamp" time)
  1924. (const :tag "Record timestamp with note" note)))
  1925. (defcustom org-log-redeadline nil
  1926. "Information to record when the deadline date of a task is modified.
  1927. Possible values are:
  1928. nil Don't add anything, just change the date
  1929. time Add a time stamp to the task
  1930. note Prompt for a note and add it with template `org-log-note-headings'
  1931. This option can also be set with on a per-file-basis with
  1932. #+STARTUP: nologredeadline
  1933. #+STARTUP: logredeadline
  1934. #+STARTUP: lognoteredeadline
  1935. You can have local logging settings for a subtree by setting the LOGGING
  1936. property to one or more of these keywords.
  1937. This variable has an effect when calling `org-deadline' or
  1938. `org-agenda-deadline' only."
  1939. :group 'org-todo
  1940. :group 'org-progress
  1941. :type '(choice
  1942. (const :tag "No logging" nil)
  1943. (const :tag "Record timestamp" time)
  1944. (const :tag "Record timestamp with note." note)))
  1945. (defcustom org-log-note-clock-out nil
  1946. "Non-nil means record a note when clocking out of an item.
  1947. This can also be configured on a per-file basis by adding one of
  1948. the following lines anywhere in the buffer:
  1949. #+STARTUP: lognoteclock-out
  1950. #+STARTUP: nolognoteclock-out"
  1951. :group 'org-todo
  1952. :group 'org-progress
  1953. :type 'boolean)
  1954. (defcustom org-log-done-with-time t
  1955. "Non-nil means the CLOSED time stamp will contain date and time.
  1956. When nil, only the date will be recorded."
  1957. :group 'org-progress
  1958. :type 'boolean)
  1959. (defcustom org-log-note-headings
  1960. '((done . "CLOSING NOTE %t")
  1961. (state . "State %-12s from %-12S %t")
  1962. (note . "Note taken on %t")
  1963. (reschedule . "Rescheduled from %S on %t")
  1964. (delschedule . "Not scheduled, was %S on %t")
  1965. (redeadline . "New deadline from %S on %t")
  1966. (deldeadline . "Removed deadline, was %S on %t")
  1967. (refile . "Refiled on %t")
  1968. (clock-out . ""))
  1969. "Headings for notes added to entries.
  1970. The value is an alist, with the car being a symbol indicating the
  1971. note context, and the cdr is the heading to be used. The heading
  1972. may also be the empty string. The following placeholders can be
  1973. used:
  1974. %t a time stamp.
  1975. %T an active time stamp instead the default inactive one
  1976. %d a short-format time stamp.
  1977. %D an active short-format time stamp.
  1978. %s the new TODO state or time stamp (inactive), in double quotes.
  1979. %S the old TODO state or time stamp (inactive), in double quotes.
  1980. %u the user name.
  1981. %U full user name.
  1982. In fact, it is not a good idea to change the `state' entry,
  1983. because Agenda Log mode depends on the format of these entries."
  1984. :group 'org-todo
  1985. :group 'org-progress
  1986. :type '(list :greedy t
  1987. (cons (const :tag "Heading when closing an item" done) string)
  1988. (cons (const :tag
  1989. "Heading when changing todo state (todo sequence only)"
  1990. state) string)
  1991. (cons (const :tag "Heading when just taking a note" note) string)
  1992. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1993. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1994. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1995. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1996. (cons (const :tag "Heading when refiling" refile) string)
  1997. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1998. (unless (assq 'note org-log-note-headings)
  1999. (push '(note . "%t") org-log-note-headings))
  2000. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  2001. (defcustom org-log-into-drawer nil
  2002. "Non-nil means insert state change notes and time stamps into a drawer.
  2003. When nil, state changes notes will be inserted after the headline and
  2004. any scheduling and clock lines, but not inside a drawer.
  2005. The value of this variable should be the name of the drawer to use.
  2006. LOGBOOK is proposed as the default drawer for this purpose, you can
  2007. also set this to a string to define the drawer of your choice.
  2008. A value of t is also allowed, representing \"LOGBOOK\".
  2009. A value of t or nil can also be set with on a per-file-basis with
  2010. #+STARTUP: logdrawer
  2011. #+STARTUP: nologdrawer
  2012. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2013. will be ignored.
  2014. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2015. a subtree.
  2016. Do not check directly this variable in a Lisp program. Call
  2017. function `org-log-into-drawer' instead."
  2018. :group 'org-todo
  2019. :group 'org-progress
  2020. :type '(choice
  2021. (const :tag "Not into a drawer" nil)
  2022. (const :tag "LOGBOOK" t)
  2023. (string :tag "Other")))
  2024. (defun org-log-into-drawer ()
  2025. "Name of the log drawer, as a string, or nil.
  2026. This is the value of `org-log-into-drawer'. However, if the
  2027. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2028. be used instead of the default value."
  2029. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2030. (cond ((equal p "nil") nil)
  2031. ((equal p "t") "LOGBOOK")
  2032. ((stringp p) p)
  2033. (p "LOGBOOK")
  2034. ((stringp org-log-into-drawer) org-log-into-drawer)
  2035. (org-log-into-drawer "LOGBOOK"))))
  2036. (defcustom org-log-state-notes-insert-after-drawers nil
  2037. "Non-nil means insert state change notes after any drawers in entry.
  2038. Only the drawers that *immediately* follow the headline and the
  2039. deadline/scheduled line are skipped.
  2040. When nil, insert notes right after the heading and perhaps the line
  2041. with deadline/scheduling if present.
  2042. This variable will have no effect if `org-log-into-drawer' is
  2043. set."
  2044. :group 'org-todo
  2045. :group 'org-progress
  2046. :type 'boolean)
  2047. (defcustom org-log-states-order-reversed t
  2048. "Non-nil means the latest state note will be directly after heading.
  2049. When nil, the state change notes will be ordered according to time.
  2050. This option can also be set with on a per-file-basis with
  2051. #+STARTUP: logstatesreversed
  2052. #+STARTUP: nologstatesreversed"
  2053. :group 'org-todo
  2054. :group 'org-progress
  2055. :type 'boolean)
  2056. (defcustom org-todo-repeat-to-state nil
  2057. "The TODO state to which a repeater should return the repeating task.
  2058. By default this is the first task of a TODO sequence or the
  2059. previous state of a TYPE_TODO set. But you can specify to use
  2060. the previous state in a TODO sequence or a string.
  2061. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2062. entry, which has precedence over this option."
  2063. :group 'org-todo
  2064. :version "24.1"
  2065. :type '(choice (const :tag "Use the previous TODO state" t)
  2066. (const :tag "Use the head of the TODO sequence" nil)
  2067. (string :tag "Use a specific TODO state")))
  2068. (defcustom org-log-repeat 'time
  2069. "Non-nil means record moving through the DONE state when triggering repeat.
  2070. An auto-repeating task is immediately switched back to TODO when
  2071. marked DONE. If you are not logging state changes (by adding \"@\"
  2072. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2073. record a closing note, there will be no record of the task moving
  2074. through DONE. This variable forces taking a note anyway.
  2075. nil Don't force a record
  2076. time Record a time stamp
  2077. note Prompt for a note and add it with template `org-log-note-headings'
  2078. This option can also be set with on a per-file-basis with
  2079. #+STARTUP: nologrepeat
  2080. #+STARTUP: logrepeat
  2081. #+STARTUP: lognoterepeat
  2082. You can have local logging settings for a subtree by setting the LOGGING
  2083. property to one or more of these keywords."
  2084. :group 'org-todo
  2085. :group 'org-progress
  2086. :type '(choice
  2087. (const :tag "Don't force a record" nil)
  2088. (const :tag "Force recording the DONE state" time)
  2089. (const :tag "Force recording a note with the DONE state" note)))
  2090. (defcustom org-todo-repeat-hook nil
  2091. "Hook that is run after a task has been repeated."
  2092. :package-version '(Org . "9.2")
  2093. :group 'org-todo
  2094. :type 'hook)
  2095. (defgroup org-priorities nil
  2096. "Priorities in Org mode."
  2097. :tag "Org Priorities"
  2098. :group 'org-todo)
  2099. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2100. (defcustom org-priority-enable-commands t
  2101. "Non-nil means priority commands are active.
  2102. When nil, these commands will be disabled, so that you never accidentally
  2103. set a priority."
  2104. :group 'org-priorities
  2105. :type 'boolean)
  2106. (defvaralias 'org-highest-priority 'org-priority-highest)
  2107. (defcustom org-priority-highest ?A
  2108. "The highest priority of TODO items.
  2109. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2110. The default is the character ?A, which is 65 as a numeric value.
  2111. If you set `org-priority-highest' to a numeric value inferior to
  2112. 65, Org assumes you want to use digits for the priority cookie.
  2113. If you set it to >=65, Org assumes you want to use alphabetical
  2114. characters.
  2115. In both cases, the value of `org-priority-highest' must be
  2116. smaller than `org-priority-lowest': for example, if \"A\" is the
  2117. highest priority, it is smaller than the lowest \"C\" priority:
  2118. 65 < 67."
  2119. :group 'org-priorities
  2120. :type '(choice
  2121. (character :tag "Character")
  2122. (integer :tag "Integer (< 65)")))
  2123. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2124. (defcustom org-priority-lowest ?C
  2125. "The lowest priority of TODO items.
  2126. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  2127. The default is the character ?C, which is 67 as a numeric value.
  2128. If you set `org-priority-lowest' to a numeric value inferior to
  2129. 65, Org assumes you want to use digits for the priority cookie.
  2130. If you set it to >=65, Org assumes you want to use alphabetical
  2131. characters.
  2132. In both cases, the value of `org-priority-lowest' must be greater
  2133. than `org-priority-highest': for example, if \"C\" is the lowest
  2134. priority, it is greater than the highest \"A\" priority: 67 >
  2135. 65."
  2136. :group 'org-priorities
  2137. :type '(choice
  2138. (character :tag "Character")
  2139. (integer :tag "Integer (< 65)")))
  2140. (defvaralias 'org-default-priority 'org-priority-default)
  2141. (defcustom org-priority-default ?B
  2142. "The default priority of TODO items.
  2143. This is the priority an item gets if no explicit priority is given.
  2144. When starting to cycle on an empty priority the first step in the cycle
  2145. depends on `org-priority-start-cycle-with-default'. The resulting first
  2146. step priority must not exceed the range from `org-priority-highest' to
  2147. `org-priority-lowest' which means that `org-priority-default' has to be
  2148. in this range exclusive or inclusive to the range boundaries. Else the
  2149. first step refuses to set the default and the second will fall back on
  2150. \(depending on the command used) the highest or lowest priority."
  2151. :group 'org-priorities
  2152. :type '(choice
  2153. (character :tag "Character")
  2154. (integer :tag "Integer (< 65)")))
  2155. (defcustom org-priority-start-cycle-with-default t
  2156. "Non-nil means start with default priority when starting to cycle.
  2157. When this is nil, the first step in the cycle will be (depending on the
  2158. command used) one higher or lower than the default priority.
  2159. See also `org-priority-default'."
  2160. :group 'org-priorities
  2161. :type 'boolean)
  2162. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2163. (defcustom org-priority-get-priority-function nil
  2164. "Function to extract the priority from a string.
  2165. The string is normally the headline. If this is nil, Org
  2166. computes the priority from the priority cookie like [#A] in the
  2167. headline. It returns an integer, increasing by 1000 for each
  2168. priority level.
  2169. The user can set a different function here, which should take a
  2170. string as an argument and return the numeric priority."
  2171. :group 'org-priorities
  2172. :version "24.1"
  2173. :type '(choice
  2174. (const nil)
  2175. (function)))
  2176. (defgroup org-time nil
  2177. "Options concerning time stamps and deadlines in Org mode."
  2178. :tag "Org Time"
  2179. :group 'org)
  2180. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2181. "Number of minutes to round time stamps to.
  2182. \\<org-mode-map>\
  2183. These are two values, the first applies when first creating a time stamp.
  2184. The second applies when changing it with the commands `S-up' and `S-down'.
  2185. When changing the time stamp, this means that it will change in steps
  2186. of N minutes, as given by the second value.
  2187. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2188. numbers should be factors of 60, so for example 5, 10, 15.
  2189. When this is larger than 1, you can still force an exact time stamp by using
  2190. a double prefix argument to a time stamp command like \
  2191. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2192. and by using a prefix arg to `S-up/down' to specify the exact number
  2193. of minutes to shift."
  2194. :group 'org-time
  2195. :get (lambda (var) ; Make sure both elements are there
  2196. (if (integerp (default-value var))
  2197. (list (default-value var) 5)
  2198. (default-value var)))
  2199. :type '(list
  2200. (integer :tag "when inserting times")
  2201. (integer :tag "when modifying times")))
  2202. ;; Normalize old customizations of this variable.
  2203. (when (integerp org-time-stamp-rounding-minutes)
  2204. (setq org-time-stamp-rounding-minutes
  2205. (list org-time-stamp-rounding-minutes
  2206. org-time-stamp-rounding-minutes)))
  2207. (defcustom org-display-custom-times nil
  2208. "Non-nil means overlay custom formats over all time stamps.
  2209. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2210. To turn this on on a per-file basis, insert anywhere in the file:
  2211. #+STARTUP: customtime"
  2212. :group 'org-time
  2213. :set 'set-default
  2214. :type 'sexp)
  2215. (make-variable-buffer-local 'org-display-custom-times)
  2216. (defcustom org-time-stamp-custom-formats
  2217. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2218. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2219. These are overlaid over the default ISO format if the variable
  2220. `org-display-custom-times' is set. Time like %H:%M should be at the
  2221. end of the second format. The custom formats are also honored by export
  2222. commands, if custom time display is turned on at the time of export."
  2223. :group 'org-time
  2224. :type 'sexp)
  2225. (defun org-time-stamp-format (&optional long inactive)
  2226. "Get the right format for a time string."
  2227. (let ((f (if long (cdr org-time-stamp-formats)
  2228. (car org-time-stamp-formats))))
  2229. (if inactive
  2230. (concat "[" (substring f 1 -1) "]")
  2231. f)))
  2232. (defcustom org-deadline-warning-days 14
  2233. "Number of days before expiration during which a deadline becomes active.
  2234. This variable governs the display in sparse trees and in the agenda.
  2235. When 0 or negative, it means use this number (the absolute value of it)
  2236. even if a deadline has a different individual lead time specified.
  2237. Custom commands can set this variable in the options section."
  2238. :group 'org-time
  2239. :group 'org-agenda-daily/weekly
  2240. :type 'integer)
  2241. (defcustom org-scheduled-delay-days 0
  2242. "Number of days before a scheduled item becomes active.
  2243. This variable governs the display in sparse trees and in the agenda.
  2244. The default value (i.e. 0) means: don't delay scheduled item.
  2245. When negative, it means use this number (the absolute value of it)
  2246. even if a scheduled item has a different individual delay time
  2247. specified.
  2248. Custom commands can set this variable in the options section."
  2249. :group 'org-time
  2250. :group 'org-agenda-daily/weekly
  2251. :version "24.4"
  2252. :package-version '(Org . "8.0")
  2253. :type 'integer)
  2254. (defcustom org-read-date-prefer-future t
  2255. "Non-nil means assume future for incomplete date input from user.
  2256. This affects the following situations:
  2257. 1. The user gives a month but not a year.
  2258. For example, if it is April and you enter \"feb 2\", this will be read
  2259. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2260. 2. The user gives a day, but no month.
  2261. For example, if today is the 15th, and you enter \"3\", Org will read
  2262. this as the third of *next* month. However, if you enter \"17\",
  2263. it will be considered as *this* month.
  2264. If you set this variable to the symbol `time', then also the following
  2265. will work:
  2266. 3. If the user gives a time.
  2267. If the time is before now, it will be interpreted as tomorrow.
  2268. Currently none of this works for ISO week specifications.
  2269. When this option is nil, the current day, month and year will always be
  2270. used as defaults.
  2271. See also `org-agenda-jump-prefer-future'."
  2272. :group 'org-time
  2273. :type '(choice
  2274. (const :tag "Never" nil)
  2275. (const :tag "Check month and day" t)
  2276. (const :tag "Check month, day, and time" time)))
  2277. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2278. "Should the agenda jump command prefer the future for incomplete dates?
  2279. The default is to do the same as configured in `org-read-date-prefer-future'.
  2280. But you can also set a deviating value here.
  2281. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2282. :group 'org-agenda
  2283. :group 'org-time
  2284. :version "24.1"
  2285. :type '(choice
  2286. (const :tag "Use org-read-date-prefer-future"
  2287. org-read-date-prefer-future)
  2288. (const :tag "Never" nil)
  2289. (const :tag "Always" t)))
  2290. (defcustom org-read-date-force-compatible-dates t
  2291. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2292. Depending on the system Emacs is running on, certain dates cannot
  2293. be represented with the type used internally to represent time.
  2294. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2295. correctly. Some systems allow for earlier dates, some for later,
  2296. some for both. One way to find out is to insert any date into an
  2297. Org buffer, putting the cursor on the year and hitting S-up and
  2298. S-down to test the range.
  2299. When this variable is set to t, the date/time prompt will not let
  2300. you specify dates outside the 1970-2037 range, so it is certain that
  2301. these dates will work in whatever version of Emacs you are
  2302. running, and also that you can move a file from one Emacs implementation
  2303. to another. Whenever Org is forcing the year for you, it will display
  2304. a message and beep.
  2305. When this variable is nil, Org will check if the date is
  2306. representable in the specific Emacs implementation you are using.
  2307. If not, it will force a year, usually the current year, and beep
  2308. to remind you. Currently this setting is not recommended because
  2309. the likelihood that you will open your Org files in an Emacs that
  2310. has limited date range is not negligible.
  2311. A workaround for this problem is to use diary sexp dates for time
  2312. stamps outside of this range."
  2313. :group 'org-time
  2314. :version "24.1"
  2315. :type 'boolean)
  2316. (defcustom org-read-date-display-live t
  2317. "Non-nil means display current interpretation of date prompt live.
  2318. This display will be in an overlay, in the minibuffer. Note that
  2319. live display is only active when `org-read-date-popup-calendar'
  2320. is non-nil."
  2321. :group 'org-time
  2322. :type 'boolean)
  2323. (defvaralias 'org-popup-calendar-for-date-prompt
  2324. 'org-read-date-popup-calendar)
  2325. (defcustom org-read-date-popup-calendar t
  2326. "Non-nil means pop up a calendar when prompting for a date.
  2327. In the calendar, the date can be selected with mouse-1. However, the
  2328. minibuffer will also be active, and you can simply enter the date as well.
  2329. When nil, only the minibuffer will be available."
  2330. :group 'org-time
  2331. :type 'boolean)
  2332. (defcustom org-extend-today-until 0
  2333. "The hour when your day really ends. Must be an integer.
  2334. This has influence for the following applications:
  2335. - When switching the agenda to \"today\". If it is still earlier than
  2336. the time given here, the day recognized as TODAY is actually yesterday.
  2337. - When a date is read from the user and it is still before the time given
  2338. here, the current date and time will be assumed to be yesterday, 23:59.
  2339. Also, timestamps inserted in capture templates follow this rule.
  2340. IMPORTANT: This is a feature whose implementation is and likely will
  2341. remain incomplete. Really, it is only here because past midnight seems to
  2342. be the favorite working time of John Wiegley :-)"
  2343. :group 'org-time
  2344. :type 'integer)
  2345. (defcustom org-use-effective-time nil
  2346. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2347. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2348. \"effective time\" of any timestamps between midnight and 8am will be
  2349. 23:59 of the previous day."
  2350. :group 'org-time
  2351. :version "24.1"
  2352. :type 'boolean)
  2353. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2354. "When non-nil, use the last clock out time for `org-todo'.
  2355. Note that this option has precedence over the combined use of
  2356. `org-use-effective-time' and `org-extend-today-until'."
  2357. :group 'org-time
  2358. :version "24.4"
  2359. :package-version '(Org . "8.0")
  2360. :type 'boolean)
  2361. (defcustom org-edit-timestamp-down-means-later nil
  2362. "Non-nil means S-down will increase the time in a time stamp.
  2363. When nil, S-up will increase."
  2364. :group 'org-time
  2365. :type 'boolean)
  2366. (defcustom org-calendar-follow-timestamp-change t
  2367. "Non-nil means make the calendar window follow timestamp changes.
  2368. When a timestamp is modified and the calendar window is visible, it will be
  2369. moved to the new date."
  2370. :group 'org-time
  2371. :type 'boolean)
  2372. (defgroup org-tags nil
  2373. "Options concerning tags in Org mode."
  2374. :tag "Org Tags"
  2375. :group 'org)
  2376. (defcustom org-tag-alist nil
  2377. "Default tags available in Org files.
  2378. The value of this variable is an alist. Associations either:
  2379. (TAG)
  2380. (TAG . SELECT)
  2381. (SPECIAL)
  2382. where TAG is a tag as a string, SELECT is character, used to
  2383. select that tag through the fast tag selection interface, and
  2384. SPECIAL is one of the following keywords: `:startgroup',
  2385. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2386. `:newline'. These keywords are used to define a hierarchy of
  2387. tags. See manual for details.
  2388. When this variable is nil, Org mode bases tag input on what is
  2389. already in the buffer. The value can be overridden locally by
  2390. using a TAGS keyword, e.g.,
  2391. #+TAGS: tag1 tag2
  2392. See also `org-tag-persistent-alist' to sidestep this behavior."
  2393. :group 'org-tags
  2394. :type '(repeat
  2395. (choice
  2396. (cons :tag "Tag with key"
  2397. (string :tag "Tag name")
  2398. (character :tag "Access char"))
  2399. (list :tag "Tag" (string :tag "Tag name"))
  2400. (const :tag "Start radio group" (:startgroup))
  2401. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2402. (const :tag "Group tags delimiter" (:grouptags))
  2403. (const :tag "End radio group" (:endgroup))
  2404. (const :tag "End tag group, non distinct" (:endgrouptag))
  2405. (const :tag "New line" (:newline)))))
  2406. (defcustom org-tag-persistent-alist nil
  2407. "Tags always available in Org files.
  2408. The value of this variable is an alist. Associations either:
  2409. (TAG)
  2410. (TAG . SELECT)
  2411. (SPECIAL)
  2412. where TAG is a tag as a string, SELECT is a character, used to
  2413. select that tag through the fast tag selection interface, and
  2414. SPECIAL is one of the following keywords: `:startgroup',
  2415. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2416. `:newline'. These keywords are used to define a hierarchy of
  2417. tags. See manual for details.
  2418. Unlike to `org-tag-alist', tags defined in this variable do not
  2419. depend on a local TAGS keyword. Instead, to disable these tags
  2420. on a per-file basis, insert anywhere in the file:
  2421. #+STARTUP: noptag"
  2422. :group 'org-tags
  2423. :type '(repeat
  2424. (choice
  2425. (cons :tag "Tag with key"
  2426. (string :tag "Tag name")
  2427. (character :tag "Access char"))
  2428. (list :tag "Tag" (string :tag "Tag name"))
  2429. (const :tag "Start radio group" (:startgroup))
  2430. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2431. (const :tag "Group tags delimiter" (:grouptags))
  2432. (const :tag "End radio group" (:endgroup))
  2433. (const :tag "End tag group, non distinct" (:endgrouptag))
  2434. (const :tag "New line" (:newline)))))
  2435. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2436. "If non-nil, always offer completion for all tags of all agenda files.
  2437. Setting this variable locally allows for dynamic generation of tag
  2438. completions in capture buffers.
  2439. (add-hook \\='org-capture-mode-hook
  2440. (lambda ()
  2441. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2442. :group 'org-tags
  2443. :version "24.1"
  2444. :type 'boolean)
  2445. (defvar org-file-tags nil
  2446. "List of tags that can be inherited by all entries in the file.
  2447. The tags will be inherited if the variable `org-use-tag-inheritance'
  2448. says they should be.
  2449. This variable is populated from #+FILETAGS lines.")
  2450. (defcustom org-use-fast-tag-selection 'auto
  2451. "Non-nil means use fast tag selection scheme.
  2452. This is a special interface to select and deselect tags with single keys.
  2453. When nil, fast selection is never used.
  2454. When the symbol `auto', fast selection is used if and only if selection
  2455. characters for tags have been configured, either through the variable
  2456. `org-tag-alist' or through a #+TAGS line in the buffer.
  2457. When t, fast selection is always used and selection keys are assigned
  2458. automatically if necessary."
  2459. :group 'org-tags
  2460. :type '(choice
  2461. (const :tag "Always" t)
  2462. (const :tag "Never" nil)
  2463. (const :tag "When selection characters are configured" auto)))
  2464. (defcustom org-fast-tag-selection-single-key nil
  2465. "Non-nil means fast tag selection exits after first change.
  2466. When nil, you have to press RET to exit it.
  2467. During fast tag selection, you can toggle this flag with `C-c'.
  2468. This variable can also have the value `expert'. In this case, the window
  2469. displaying the tags menu is not even shown, until you press `C-c' again."
  2470. :group 'org-tags
  2471. :type '(choice
  2472. (const :tag "No" nil)
  2473. (const :tag "Yes" t)
  2474. (const :tag "Expert" expert)))
  2475. (defvar org-fast-tag-selection-include-todo nil
  2476. "Non-nil means fast tags selection interface will also offer TODO states.
  2477. This is an undocumented feature, you should not rely on it.")
  2478. (defcustom org-tags-column -77
  2479. "The column to which tags should be indented in a headline.
  2480. If this number is positive, it specifies the column. If it is negative,
  2481. it means that the tags should be flushright to that column. For example,
  2482. -80 works well for a normal 80 character screen.
  2483. When 0, place tags directly after headline text, with only one space in
  2484. between."
  2485. :group 'org-tags
  2486. :type 'integer)
  2487. (defcustom org-auto-align-tags t
  2488. "Non-nil keeps tags aligned when modifying headlines.
  2489. Some operations (i.e. demoting) change the length of a headline and
  2490. therefore shift the tags around. With this option turned on, after
  2491. each such operation the tags are again aligned to `org-tags-column'."
  2492. :group 'org-tags
  2493. :type 'boolean)
  2494. (defcustom org-use-tag-inheritance t
  2495. "Non-nil means tags in levels apply also for sublevels.
  2496. When nil, only the tags directly given in a specific line apply there.
  2497. This may also be a list of tags that should be inherited, or a regexp that
  2498. matches tags that should be inherited. Additional control is possible
  2499. with the variable `org-tags-exclude-from-inheritance' which gives an
  2500. explicit list of tags to be excluded from inheritance, even if the value of
  2501. `org-use-tag-inheritance' would select it for inheritance.
  2502. If this option is t, a match early-on in a tree can lead to a large
  2503. number of matches in the subtree when constructing the agenda or creating
  2504. a sparse tree. If you only want to see the first match in a tree during
  2505. a search, check out the variable `org-tags-match-list-sublevels'."
  2506. :group 'org-tags
  2507. :type '(choice
  2508. (const :tag "Not" nil)
  2509. (const :tag "Always" t)
  2510. (repeat :tag "Specific tags" (string :tag "Tag"))
  2511. (regexp :tag "Tags matched by regexp")))
  2512. (defcustom org-tags-exclude-from-inheritance nil
  2513. "List of tags that should never be inherited.
  2514. This is a way to exclude a few tags from inheritance. For way to do
  2515. the opposite, to actively allow inheritance for selected tags,
  2516. see the variable `org-use-tag-inheritance'."
  2517. :group 'org-tags
  2518. :type '(repeat (string :tag "Tag")))
  2519. (defun org-tag-inherit-p (tag)
  2520. "Check if TAG is one that should be inherited."
  2521. (cond
  2522. ((member tag org-tags-exclude-from-inheritance) nil)
  2523. ((eq org-use-tag-inheritance t) t)
  2524. ((not org-use-tag-inheritance) nil)
  2525. ((stringp org-use-tag-inheritance)
  2526. (string-match org-use-tag-inheritance tag))
  2527. ((listp org-use-tag-inheritance)
  2528. (member tag org-use-tag-inheritance))
  2529. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2530. (defcustom org-tags-match-list-sublevels t
  2531. "Non-nil means list also sublevels of headlines matching a search.
  2532. This variable applies to tags/property searches, and also to stuck
  2533. projects because this search is based on a tags match as well.
  2534. When set to the symbol `indented', sublevels are indented with
  2535. leading dots.
  2536. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2537. the sublevels of a headline matching a tag search often also match
  2538. the same search. Listing all of them can create very long lists.
  2539. Setting this variable to nil causes subtrees of a match to be skipped.
  2540. This variable is semi-obsolete and probably should always be true. It
  2541. is better to limit inheritance to certain tags using the variables
  2542. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2543. :group 'org-tags
  2544. :type '(choice
  2545. (const :tag "No, don't list them" nil)
  2546. (const :tag "Yes, do list them" t)
  2547. (const :tag "List them, indented with leading dots" indented)))
  2548. (defcustom org-tags-sort-function nil
  2549. "When set, tags are sorted using this function as a comparator."
  2550. :group 'org-tags
  2551. :type '(choice
  2552. (const :tag "No sorting" nil)
  2553. (const :tag "Alphabetical" string-collate-lessp)
  2554. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2555. (function :tag "Custom function" nil)))
  2556. (defvar org-tags-history nil
  2557. "History of minibuffer reads for tags.")
  2558. (defvar org-last-tags-completion-table nil
  2559. "The last used completion table for tags.")
  2560. (defvar org-after-tags-change-hook nil
  2561. "Hook that is run after the tags in a line have changed.")
  2562. (defgroup org-properties nil
  2563. "Options concerning properties in Org mode."
  2564. :tag "Org Properties"
  2565. :group 'org)
  2566. (defcustom org-property-format "%-10s %s"
  2567. "How property key/value pairs should be formatted by `indent-line'.
  2568. When `indent-line' hits a property definition, it will format the line
  2569. according to this format, mainly to make sure that the values are
  2570. lined-up with respect to each other."
  2571. :group 'org-properties
  2572. :type 'string)
  2573. (defcustom org-properties-postprocess-alist nil
  2574. "Alist of properties and functions to adjust inserted values.
  2575. Elements of this alist must be of the form
  2576. ([string] [function])
  2577. where [string] must be a property name and [function] must be a
  2578. lambda expression: this lambda expression must take one argument,
  2579. the value to adjust, and return the new value as a string.
  2580. For example, this element will allow the property \"Remaining\"
  2581. to be updated wrt the relation between the \"Effort\" property
  2582. and the clock summary:
  2583. ((\"Remaining\" (lambda(value)
  2584. (let ((clocksum (org-clock-sum-current-item))
  2585. (effort (org-duration-to-minutes
  2586. (org-entry-get (point) \"Effort\"))))
  2587. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2588. :group 'org-properties
  2589. :version "24.1"
  2590. :type '(alist :key-type (string :tag "Property")
  2591. :value-type (function :tag "Function")))
  2592. (defcustom org-use-property-inheritance nil
  2593. "Non-nil means properties apply also for sublevels.
  2594. This setting is chiefly used during property searches. Turning it on can
  2595. cause significant overhead when doing a search, which is why it is not
  2596. on by default.
  2597. When nil, only the properties directly given in the current entry count.
  2598. When t, every property is inherited. The value may also be a list of
  2599. properties that should have inheritance, or a regular expression matching
  2600. properties that should be inherited.
  2601. However, note that some special properties use inheritance under special
  2602. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2603. and the properties ending in \"_ALL\" when they are used as descriptor
  2604. for valid values of a property.
  2605. Note for programmers:
  2606. When querying an entry with `org-entry-get', you can control if inheritance
  2607. should be used. By default, `org-entry-get' looks only at the local
  2608. properties. You can request inheritance by setting the inherit argument
  2609. to t (to force inheritance) or to `selective' (to respect the setting
  2610. in this variable)."
  2611. :group 'org-properties
  2612. :type '(choice
  2613. (const :tag "Not" nil)
  2614. (const :tag "Always" t)
  2615. (repeat :tag "Specific properties" (string :tag "Property"))
  2616. (regexp :tag "Properties matched by regexp")))
  2617. (defun org-property-inherit-p (property)
  2618. "Return a non-nil value if PROPERTY should be inherited."
  2619. (cond
  2620. ((eq org-use-property-inheritance t) t)
  2621. ((not org-use-property-inheritance) nil)
  2622. ((stringp org-use-property-inheritance)
  2623. (string-match org-use-property-inheritance property))
  2624. ((listp org-use-property-inheritance)
  2625. (member-ignore-case property org-use-property-inheritance))
  2626. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2627. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2628. "The default column format, if no other format has been defined.
  2629. This variable can be set on the per-file basis by inserting a line
  2630. #+COLUMNS: %25ITEM ....."
  2631. :group 'org-properties
  2632. :type 'string)
  2633. (defcustom org-columns-default-format-for-agenda nil
  2634. "The default column format in an agenda buffer.
  2635. This will be used for column view in the agenda unless a format has
  2636. been set by adding `org-overriding-columns-format' to the local
  2637. settings list of a custom agenda view. When nil, the columns format
  2638. for the first item in the agenda list will be used, or as a fall-back,
  2639. `org-columns-default-format'."
  2640. :group 'org-properties
  2641. :type '(choice
  2642. (const :tag "No default" nil)
  2643. (string :tag "Format string")))
  2644. (defcustom org-columns-ellipses ".."
  2645. "The ellipses to be used when a field in column view is truncated.
  2646. When this is the empty string, as many characters as possible are shown,
  2647. but then there will be no visual indication that the field has been truncated.
  2648. When this is a string of length N, the last N characters of a truncated
  2649. field are replaced by this string. If the column is narrower than the
  2650. ellipses string, only part of the ellipses string will be shown."
  2651. :group 'org-properties
  2652. :type 'string)
  2653. (defconst org-global-properties-fixed
  2654. '(("VISIBILITY_ALL" . "folded children content all")
  2655. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2656. "List of property/value pairs that can be inherited by any entry.
  2657. These are fixed values, for the preset properties. The user variable
  2658. that can be used to add to this list is `org-global-properties'.
  2659. The entries in this list are cons cells where the car is a property
  2660. name and cdr is a string with the value. If the value represents
  2661. multiple items like an \"_ALL\" property, separate the items by
  2662. spaces.")
  2663. (defcustom org-global-properties nil
  2664. "List of property/value pairs that can be inherited by any entry.
  2665. This list will be combined with the constant `org-global-properties-fixed'.
  2666. The entries in this list are cons cells where the car is a property
  2667. name and cdr is a string with the value.
  2668. Buffer local properties are added either by a document property drawer
  2669. :PROPERTIES:
  2670. :NAME: VALUE
  2671. :END:
  2672. or by adding lines like
  2673. #+PROPERTY: NAME VALUE"
  2674. :group 'org-properties
  2675. :type '(repeat
  2676. (cons (string :tag "Property")
  2677. (string :tag "Value"))))
  2678. (defvar-local org-keyword-properties nil
  2679. "List of property/value pairs inherited by any entry.
  2680. Valid for the current buffer. This variable is populated from
  2681. PROPERTY keywords.
  2682. Note that properties are defined also in property drawers.
  2683. Properties defined there take precedence over properties defined
  2684. as keywords.")
  2685. (defgroup org-agenda nil
  2686. "Options concerning agenda views in Org mode."
  2687. :tag "Org Agenda"
  2688. :group 'org)
  2689. (defvar-local org-category nil
  2690. "Variable used by Org files to set a category for agenda display.
  2691. There are multiple ways to set the category. One way is to set
  2692. it in the document property drawer. For example:
  2693. :PROPERTIES:
  2694. :CATEGORY: ELisp
  2695. :END:
  2696. Other ways to define it is as an Emacs file variable, for example
  2697. # -*- mode: org; org-category: \"ELisp\"
  2698. or for the file to contain a special line:
  2699. #+CATEGORY: ELisp
  2700. If the file does not specify a category, then file's base name
  2701. is used instead.")
  2702. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2703. (defcustom org-agenda-files nil
  2704. "The files to be used for agenda display.
  2705. If an entry is a directory, all files in that directory that are matched
  2706. by `org-agenda-file-regexp' will be part of the file list.
  2707. If the value of the variable is not a list but a single file name, then
  2708. the list of agenda files is actually stored and maintained in that file,
  2709. one agenda file per line. In this file paths can be given relative to
  2710. `org-directory'. Tilde expansion and environment variable substitution
  2711. are also made.
  2712. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2713. and removed with `\\[org-remove-file]'."
  2714. :group 'org-agenda
  2715. :type '(choice
  2716. (repeat :tag "List of files and directories" file)
  2717. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2718. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2719. "Regular expression to match files for `org-agenda-files'.
  2720. If any element in the list in that variable contains a directory instead
  2721. of a normal file, all files in that directory that are matched by this
  2722. regular expression will be included."
  2723. :group 'org-agenda
  2724. :type 'regexp)
  2725. (defvaralias 'org-agenda-multi-occur-extra-files
  2726. 'org-agenda-text-search-extra-files)
  2727. (defcustom org-agenda-text-search-extra-files nil
  2728. "List of extra files to be searched by text search commands.
  2729. These files will be searched in addition to the agenda files by the
  2730. commands `org-search-view' (`\\[org-agenda] s') \
  2731. and `org-occur-in-agenda-files'.
  2732. Note that these files will only be searched for text search commands,
  2733. not for the other agenda views like todo lists, tag searches or the weekly
  2734. agenda. This variable is intended to list notes and possibly archive files
  2735. that should also be searched by these two commands.
  2736. In fact, if the first element in the list is the symbol `agenda-archives',
  2737. then all archive files of all agenda files will be added to the search
  2738. scope."
  2739. :group 'org-agenda
  2740. :type '(set :greedy t
  2741. (const :tag "Agenda Archives" agenda-archives)
  2742. (repeat :inline t (file))))
  2743. (defcustom org-agenda-skip-unavailable-files nil
  2744. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2745. A nil value means to remove them, after a query, from the list."
  2746. :group 'org-agenda
  2747. :type 'boolean)
  2748. (defgroup org-latex nil
  2749. "Options for embedding LaTeX code into Org mode."
  2750. :tag "Org LaTeX"
  2751. :group 'org)
  2752. (defcustom org-format-latex-options
  2753. '(:foreground default :background default :scale 1.0
  2754. :html-foreground "Black" :html-background "Transparent"
  2755. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2756. "Options for creating images from LaTeX fragments.
  2757. This is a property list with the following properties:
  2758. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2759. `default' means use the foreground of the default face.
  2760. `auto' means use the foreground from the text face.
  2761. :background the background color, or \"Transparent\".
  2762. `default' means use the background of the default face.
  2763. `auto' means use the background from the text face.
  2764. :scale a scaling factor for the size of the images, to get more pixels
  2765. :html-foreground, :html-background, :html-scale
  2766. the same numbers for HTML export.
  2767. :matchers a list indicating which matchers should be used to
  2768. find LaTeX fragments. Valid members of this list are:
  2769. \"begin\" find environments
  2770. \"$1\" find single characters surrounded by $.$
  2771. \"$\" find math expressions surrounded by $...$
  2772. \"$$\" find math expressions surrounded by $$....$$
  2773. \"\\(\" find math expressions surrounded by \\(...\\)
  2774. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2775. :group 'org-latex
  2776. :type 'plist)
  2777. (defcustom org-format-latex-signal-error t
  2778. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2779. When nil, just push out a message."
  2780. :group 'org-latex
  2781. :version "24.1"
  2782. :type 'boolean)
  2783. (defcustom org-latex-to-mathml-jar-file nil
  2784. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2785. Use this to specify additional executable file say a jar file.
  2786. When using MathToWeb as the converter, specify the full-path to
  2787. your mathtoweb.jar file."
  2788. :group 'org-latex
  2789. :version "24.1"
  2790. :type '(choice
  2791. (const :tag "None" nil)
  2792. (file :tag "JAR file" :must-match t)))
  2793. (defcustom org-latex-to-mathml-convert-command nil
  2794. "Command to convert LaTeX fragments to MathML.
  2795. Replace format-specifiers in the command as noted below and use
  2796. `shell-command' to convert LaTeX to MathML.
  2797. %j: Executable file in fully expanded form as specified by
  2798. `org-latex-to-mathml-jar-file'.
  2799. %I: Input LaTeX file in fully expanded form.
  2800. %i: The latex fragment to be converted.
  2801. %o: Output MathML file.
  2802. This command is used by `org-create-math-formula'.
  2803. When using MathToWeb as the converter, set this option to
  2804. \"java -jar %j -unicode -force -df %o %I\".
  2805. When using LaTeXML set this option to
  2806. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2807. :group 'org-latex
  2808. :version "24.1"
  2809. :type '(choice
  2810. (const :tag "None" nil)
  2811. (string :tag "\nShell command")))
  2812. (defcustom org-latex-to-html-convert-command nil
  2813. "Command to convert LaTeX fragments to HTML.
  2814. This command is very open-ended: the output of the command will
  2815. directly replace the LaTeX fragment in the resulting HTML.
  2816. Replace format-specifiers in the command as noted below and use
  2817. `shell-command' to convert LaTeX to HTML.
  2818. %i: The LaTeX fragment to be converted.
  2819. For example, this could be used with LaTeXML as
  2820. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2821. :group 'org-latex
  2822. :package-version '(Org . "9.4")
  2823. :type '(choice
  2824. (const :tag "None" nil)
  2825. (string :tag "Shell command")))
  2826. (defcustom org-preview-latex-default-process 'dvipng
  2827. "The default process to convert LaTeX fragments to image files.
  2828. All available processes and theirs documents can be found in
  2829. `org-preview-latex-process-alist', which see."
  2830. :group 'org-latex
  2831. :version "26.1"
  2832. :package-version '(Org . "9.0")
  2833. :type 'symbol)
  2834. (defcustom org-preview-latex-process-alist
  2835. '((dvipng
  2836. :programs ("latex" "dvipng")
  2837. :description "dvi > png"
  2838. :message "you need to install the programs: latex and dvipng."
  2839. :image-input-type "dvi"
  2840. :image-output-type "png"
  2841. :image-size-adjust (1.0 . 1.0)
  2842. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2843. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2844. :transparent-image-converter
  2845. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2846. (dvisvgm
  2847. :programs ("latex" "dvisvgm")
  2848. :description "dvi > svg"
  2849. :message "you need to install the programs: latex and dvisvgm."
  2850. :image-input-type "dvi"
  2851. :image-output-type "svg"
  2852. :image-size-adjust (1.7 . 1.5)
  2853. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2854. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2855. (imagemagick
  2856. :programs ("latex" "convert")
  2857. :description "pdf > png"
  2858. :message "you need to install the programs: latex and imagemagick."
  2859. :image-input-type "pdf"
  2860. :image-output-type "png"
  2861. :image-size-adjust (1.0 . 1.0)
  2862. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2863. :image-converter
  2864. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2865. "Definitions of external processes for LaTeX previewing.
  2866. Org mode can use some external commands to generate TeX snippet's images for
  2867. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2868. `org-create-formula-image' how to call them.
  2869. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2870. PROPERTIES accepts the following attributes:
  2871. :programs list of strings, required programs.
  2872. :description string, describe the process.
  2873. :message string, message it when required programs cannot be found.
  2874. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2875. :image-output-type string, output file type of image converter (e.g., \"png\").
  2876. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2877. image size showed in buffer and the cdr element is for
  2878. HTML file. This option is only useful for process
  2879. developers, users should use variable
  2880. `org-format-latex-options' instead.
  2881. :post-clean list of strings, files matched are to be cleaned up once
  2882. the image is generated. When nil, the files with \".dvi\",
  2883. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2884. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2885. be cleaned up.
  2886. :latex-header list of strings, the LaTeX header of the snippet file.
  2887. When nil, the fallback value is used instead, which is
  2888. controlled by `org-format-latex-header',
  2889. `org-latex-default-packages-alist' and
  2890. `org-latex-packages-alist', which see.
  2891. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2892. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2893. replaced with values defined below.
  2894. :image-converter list of image converter commands strings. Each of them is
  2895. given to the shell and supports any of the following
  2896. place-holders defined below.
  2897. If set, :transparent-image-converter is used instead of :image-converter to
  2898. convert an image when the background color is nil or \"Transparent\".
  2899. Place-holders used by `:image-converter' and `:latex-compiler':
  2900. %f input file name
  2901. %b base name of input file
  2902. %o base directory of input file
  2903. %O absolute output file name
  2904. Place-holders only used by `:image-converter':
  2905. %D dpi, which is used to adjust image size by some processing commands.
  2906. %S the image size scale ratio, which is used to adjust image size by some
  2907. processing commands."
  2908. :group 'org-latex
  2909. :version "26.1"
  2910. :package-version '(Org . "9.0")
  2911. :type '(alist :tag "LaTeX to image backends"
  2912. :value-type (plist)))
  2913. (defcustom org-preview-latex-image-directory "ltximg/"
  2914. "Path to store latex preview images.
  2915. A relative path here creates many directories relative to the
  2916. processed Org files paths. An absolute path puts all preview
  2917. images at the same place."
  2918. :group 'org-latex
  2919. :version "26.1"
  2920. :package-version '(Org . "9.0")
  2921. :type 'string)
  2922. (defun org-format-latex-mathml-available-p ()
  2923. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2924. (save-match-data
  2925. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2926. org-latex-to-mathml-convert-command)
  2927. (let ((executable (car (split-string
  2928. org-latex-to-mathml-convert-command))))
  2929. (when (executable-find executable)
  2930. (if (string-match
  2931. "%j" org-latex-to-mathml-convert-command)
  2932. (file-readable-p org-latex-to-mathml-jar-file)
  2933. t))))))
  2934. (defcustom org-format-latex-header "\\documentclass{article}
  2935. \\usepackage[usenames]{color}
  2936. \[PACKAGES]
  2937. \[DEFAULT-PACKAGES]
  2938. \\pagestyle{empty} % do not remove
  2939. % The settings below are copied from fullpage.sty
  2940. \\setlength{\\textwidth}{\\paperwidth}
  2941. \\addtolength{\\textwidth}{-3cm}
  2942. \\setlength{\\oddsidemargin}{1.5cm}
  2943. \\addtolength{\\oddsidemargin}{-2.54cm}
  2944. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2945. \\setlength{\\textheight}{\\paperheight}
  2946. \\addtolength{\\textheight}{-\\headheight}
  2947. \\addtolength{\\textheight}{-\\headsep}
  2948. \\addtolength{\\textheight}{-\\footskip}
  2949. \\addtolength{\\textheight}{-3cm}
  2950. \\setlength{\\topmargin}{1.5cm}
  2951. \\addtolength{\\topmargin}{-2.54cm}"
  2952. "The document header used for processing LaTeX fragments.
  2953. It is imperative that this header make sure that no page number
  2954. appears on the page. The package defined in the variables
  2955. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2956. will either replace the placeholder \"[PACKAGES]\" in this
  2957. header, or they will be appended."
  2958. :group 'org-latex
  2959. :type 'string)
  2960. (defun org-set-packages-alist (var val)
  2961. "Set the packages alist and make sure it has 3 elements per entry."
  2962. (set var (mapcar (lambda (x)
  2963. (if (and (consp x) (= (length x) 2))
  2964. (list (car x) (nth 1 x) t)
  2965. x))
  2966. val)))
  2967. (defun org-get-packages-alist (var)
  2968. "Get the packages alist and make sure it has 3 elements per entry."
  2969. (mapcar (lambda (x)
  2970. (if (and (consp x) (= (length x) 2))
  2971. (list (car x) (nth 1 x) t)
  2972. x))
  2973. (default-value var)))
  2974. (defcustom org-latex-default-packages-alist
  2975. '(("AUTO" "inputenc" t ("pdflatex"))
  2976. ("T1" "fontenc" t ("pdflatex"))
  2977. ("" "graphicx" t)
  2978. ("" "longtable" nil)
  2979. ("" "wrapfig" nil)
  2980. ("" "rotating" nil)
  2981. ("normalem" "ulem" t)
  2982. ("" "amsmath" t)
  2983. ("" "amssymb" t)
  2984. ("" "capt-of" nil)
  2985. ("" "hyperref" nil))
  2986. "Alist of default packages to be inserted in the header.
  2987. Change this only if one of the packages here causes an
  2988. incompatibility with another package you are using.
  2989. The packages in this list are needed by one part or another of
  2990. Org mode to function properly:
  2991. - inputenc, fontenc: for basic font and character selection
  2992. - graphicx: for including images
  2993. - longtable: For multipage tables
  2994. - wrapfig: for figure placement
  2995. - rotating: for sideways figures and tables
  2996. - ulem: for underline and strike-through
  2997. - amsmath: for subscript and superscript and math environments
  2998. - amssymb: for various symbols used for interpreting the entities
  2999. in `org-entities'. You can skip some of this package if you don't
  3000. use any of the symbols.
  3001. - capt-of: for captions outside of floats
  3002. - hyperref: for cross references
  3003. Therefore you should not modify this variable unless you know
  3004. what you are doing. The one reason to change it anyway is that
  3005. you might be loading some other package that conflicts with one
  3006. of the default packages. Each element is either a cell or
  3007. a string.
  3008. A cell is of the format
  3009. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3010. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3011. when compiling LaTeX snippets into images for inclusion into
  3012. non-LaTeX output.
  3013. COMPILERS is a list of compilers that should include the package,
  3014. see `org-latex-compiler'. If the document compiler is not in the
  3015. list, and the list is non-nil, the package will not be inserted
  3016. in the final document.
  3017. A string will be inserted as-is in the header of the document."
  3018. :group 'org-latex
  3019. :group 'org-export-latex
  3020. :set 'org-set-packages-alist
  3021. :get 'org-get-packages-alist
  3022. :version "26.1"
  3023. :package-version '(Org . "8.3")
  3024. :type '(repeat
  3025. (choice
  3026. (list :tag "options/package pair"
  3027. (string :tag "options")
  3028. (string :tag "package")
  3029. (boolean :tag "Snippet")
  3030. (choice
  3031. (const :tag "For all compilers" nil)
  3032. (repeat :tag "Allowed compiler" string)))
  3033. (string :tag "A line of LaTeX"))))
  3034. (defcustom org-latex-packages-alist nil
  3035. "Alist of packages to be inserted in every LaTeX header.
  3036. These will be inserted after `org-latex-default-packages-alist'.
  3037. Each element is either a cell or a string.
  3038. A cell is of the format:
  3039. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3040. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3041. needed when turning LaTeX snippets into images for inclusion into
  3042. non-LaTeX output.
  3043. COMPILERS is a list of compilers that should include the package,
  3044. see `org-latex-compiler'. If the document compiler is not in the
  3045. list, and the list is non-nil, the package will not be inserted
  3046. in the final document.
  3047. A string will be inserted as-is in the header of the document.
  3048. Make sure that you only list packages here which:
  3049. - you want in every file;
  3050. - do not conflict with the setup in `org-format-latex-header';
  3051. - do not conflict with the default packages in
  3052. `org-latex-default-packages-alist'."
  3053. :group 'org-latex
  3054. :group 'org-export-latex
  3055. :set 'org-set-packages-alist
  3056. :get 'org-get-packages-alist
  3057. :type '(repeat
  3058. (choice
  3059. (list :tag "options/package pair"
  3060. (string :tag "options")
  3061. (string :tag "package")
  3062. (boolean :tag "Snippet"))
  3063. (string :tag "A line of LaTeX"))))
  3064. (defgroup org-appearance nil
  3065. "Settings for Org mode appearance."
  3066. :tag "Org Appearance"
  3067. :group 'org)
  3068. (defcustom org-level-color-stars-only nil
  3069. "Non-nil means fontify only the stars in each headline.
  3070. When nil, the entire headline is fontified.
  3071. Changing it requires restart of `font-lock-mode' to become effective
  3072. also in regions already fontified."
  3073. :group 'org-appearance
  3074. :type 'boolean)
  3075. (defcustom org-hide-leading-stars nil
  3076. "Non-nil means hide the first N-1 stars in a headline.
  3077. This works by using the face `org-hide' for these stars. This
  3078. face is white for a light background, and black for a dark
  3079. background. You may have to customize the face `org-hide' to
  3080. make this work.
  3081. Changing it requires restart of `font-lock-mode' to become effective
  3082. also in regions already fontified.
  3083. You may also set this on a per-file basis by adding one of the following
  3084. lines to the buffer:
  3085. #+STARTUP: hidestars
  3086. #+STARTUP: showstars"
  3087. :group 'org-appearance
  3088. :type 'boolean)
  3089. (defcustom org-hidden-keywords nil
  3090. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3091. For example, a value \\='(title) for this list makes the document's title
  3092. appear in the buffer without the initial \"#+TITLE:\" part."
  3093. :group 'org-appearance
  3094. :package-version '(Org . "9.5")
  3095. :type '(set (const :tag "#+AUTHOR" author)
  3096. (const :tag "#+DATE" date)
  3097. (const :tag "#+EMAIL" email)
  3098. (const :tag "#+SUBTITLE" subtitle)
  3099. (const :tag "#+TITLE" title)))
  3100. (defcustom org-custom-properties nil
  3101. "List of properties (as strings) with a special meaning.
  3102. The default use of these custom properties is to let the user
  3103. hide them with `org-toggle-custom-properties-visibility'."
  3104. :group 'org-properties
  3105. :group 'org-appearance
  3106. :version "24.3"
  3107. :type '(repeat (string :tag "Property Name")))
  3108. (defcustom org-fontify-todo-headline nil
  3109. "Non-nil means change the face of a headline if it is marked as TODO.
  3110. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3111. When this is non-nil, the headline after the keyword is set to the
  3112. `org-headline-todo' as an additional indication."
  3113. :group 'org-appearance
  3114. :package-version '(Org . "9.4")
  3115. :type 'boolean
  3116. :safe #'booleanp)
  3117. (defcustom org-fontify-done-headline t
  3118. "Non-nil means change the face of a headline if it is marked DONE.
  3119. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3120. When this is non-nil, the headline after the keyword is set to the
  3121. `org-headline-done' as an additional indication."
  3122. :group 'org-appearance
  3123. :package-version '(Org . "9.4")
  3124. :type 'boolean)
  3125. (defcustom org-fontify-emphasized-text t
  3126. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3127. Changing this variable requires a restart of Emacs to take effect."
  3128. :group 'org-appearance
  3129. :type 'boolean)
  3130. (defcustom org-fontify-whole-heading-line nil
  3131. "Non-nil means fontify the whole line for headings.
  3132. This is useful when setting a background color for the
  3133. org-level-* faces."
  3134. :group 'org-appearance
  3135. :type 'boolean)
  3136. (defcustom org-fontify-whole-block-delimiter-line t
  3137. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3138. This is useful when setting a background color for the
  3139. org-block-begin-line and org-block-end-line faces."
  3140. :group 'org-appearance
  3141. :type 'boolean)
  3142. (defcustom org-highlight-latex-and-related nil
  3143. "Non-nil means highlight LaTeX related syntax in the buffer.
  3144. When non-nil, the value should be a list containing any of the
  3145. following symbols:
  3146. `native' Highlight LaTeX snippets and environments natively.
  3147. `latex' Highlight LaTeX snippets and environments.
  3148. `script' Highlight subscript and superscript.
  3149. `entities' Highlight entities."
  3150. :group 'org-appearance
  3151. :version "24.4"
  3152. :package-version '(Org . "8.0")
  3153. :type '(choice
  3154. (const :tag "No highlighting" nil)
  3155. (set :greedy t :tag "Highlight"
  3156. (const :tag "LaTeX snippets and environments (native)" native)
  3157. (const :tag "LaTeX snippets and environments" latex)
  3158. (const :tag "Subscript and superscript" script)
  3159. (const :tag "Entities" entities))))
  3160. (defcustom org-hide-emphasis-markers nil
  3161. "Non-nil mean font-lock should hide the emphasis marker characters."
  3162. :group 'org-appearance
  3163. :type 'boolean
  3164. :safe #'booleanp)
  3165. (defcustom org-hide-macro-markers nil
  3166. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3167. :group 'org-appearance
  3168. :type 'boolean)
  3169. (defcustom org-pretty-entities nil
  3170. "Non-nil means show entities as UTF8 characters.
  3171. When nil, the \\name form remains in the buffer."
  3172. :group 'org-appearance
  3173. :version "24.1"
  3174. :type 'boolean)
  3175. (defcustom org-pretty-entities-include-sub-superscripts t
  3176. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3177. :group 'org-appearance
  3178. :version "24.1"
  3179. :type 'boolean)
  3180. (defvar org-emph-re nil
  3181. "Regular expression for matching emphasis.
  3182. After a match, the match groups contain these elements:
  3183. 0 The match of the full regular expression, including the characters
  3184. before and after the proper match
  3185. 1 The character before the proper match, or empty at beginning of line
  3186. 2 The proper match, including the leading and trailing markers
  3187. 3 The leading marker like * or /, indicating the type of highlighting
  3188. 4 The text between the emphasis markers, not including the markers
  3189. 5 The character after the match, empty at the end of a line")
  3190. (defvar org-verbatim-re nil
  3191. "Regular expression for matching verbatim text.")
  3192. (defvar org-emphasis-regexp-components) ; defined just below
  3193. (defvar org-emphasis-alist) ; defined just below
  3194. (defun org-set-emph-re (var val)
  3195. "Set variable and compute the emphasis regular expression."
  3196. (set var val)
  3197. (when (and (boundp 'org-emphasis-alist)
  3198. (boundp 'org-emphasis-regexp-components)
  3199. org-emphasis-alist org-emphasis-regexp-components)
  3200. (pcase-let*
  3201. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3202. (body (if (<= nl 0) body
  3203. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3204. (template
  3205. (format (concat "\\([%s]\\|^\\)" ;before markers
  3206. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3207. "\\([%s]\\|$\\)") ;after markers
  3208. pre border border body border post)))
  3209. (setq org-emph-re (format template "*/_+"))
  3210. (setq org-verbatim-re (format template "=~")))))
  3211. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3212. ;; set this option proved cumbersome. See this message/thread:
  3213. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3214. (defvar org-emphasis-regexp-components
  3215. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3216. "Components used to build the regular expression for emphasis.
  3217. This is a list with five entries. Terminology: In an emphasis string
  3218. like \" *strong word* \", we call the initial space PREMATCH, the final
  3219. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3220. and \"trong wor\" is the body. The different components in this variable
  3221. specify what is allowed/forbidden in each part:
  3222. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3223. post Chars allowed as postmatch. End of line will be allowed too.
  3224. border The chars *forbidden* as border characters.
  3225. body-regexp A regexp like \".\" to match a body character. Don't use
  3226. non-shy groups here, and don't allow newline here.
  3227. newline The maximum number of newlines allowed in an emphasis exp.
  3228. You need to reload Org or to restart Emacs after setting this.")
  3229. (defcustom org-emphasis-alist
  3230. '(("*" bold)
  3231. ("/" italic)
  3232. ("_" underline)
  3233. ("=" org-verbatim verbatim)
  3234. ("~" org-code verbatim)
  3235. ("+" (:strike-through t)))
  3236. "Alist of characters and faces to emphasize text.
  3237. Text starting and ending with a special character will be emphasized,
  3238. for example *bold*, _underlined_ and /italic/. This variable sets the
  3239. marker characters and the face to be used by font-lock for highlighting
  3240. in Org buffers.
  3241. You need to reload Org or to restart Emacs after customizing this."
  3242. :group 'org-appearance
  3243. :set 'org-set-emph-re
  3244. :version "24.4"
  3245. :package-version '(Org . "8.0")
  3246. :type '(repeat
  3247. (list
  3248. (string :tag "Marker character")
  3249. (choice
  3250. (face :tag "Font-lock-face")
  3251. (plist :tag "Face property list"))
  3252. (option (const verbatim)))))
  3253. (defvar org-protecting-blocks '("src" "example" "export")
  3254. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3255. This is needed for font-lock setup.")
  3256. ;;; Functions and variables from their packages
  3257. ;; Declared here to avoid compiler warnings
  3258. (defvar mark-active)
  3259. ;; Various packages
  3260. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3261. (declare-function calendar-forward-day "cal-move" (arg))
  3262. (declare-function calendar-goto-date "cal-move" (date))
  3263. (declare-function calendar-goto-today "cal-move" ())
  3264. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3265. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3266. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3267. (declare-function cdlatex-tab "ext:cdlatex" ())
  3268. (declare-function dired-get-filename
  3269. "dired"
  3270. (&optional localp no-error-if-not-filep))
  3271. (declare-function iswitchb-read-buffer
  3272. "iswitchb"
  3273. (prompt &optional
  3274. default require-match _predicate start matches-set))
  3275. (declare-function org-agenda-change-all-lines
  3276. "org-agenda"
  3277. (newhead hdmarker &optional fixface just-this))
  3278. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3279. "org-agenda"
  3280. (&optional end))
  3281. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3282. (declare-function org-agenda-format-item
  3283. "org-agenda"
  3284. (extra txt &optional level category tags dotime
  3285. remove-re habitp))
  3286. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3287. (declare-function org-agenda-save-markers-for-cut-and-paste
  3288. "org-agenda"
  3289. (beg end))
  3290. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3291. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3292. (declare-function org-attach-expand "org-attach" (file))
  3293. (declare-function org-attach-reveal "org-attach" ())
  3294. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3295. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3296. (declare-function org-indent-mode "org-indent" (&optional arg))
  3297. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3298. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3299. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3300. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3301. (declare-function parse-time-string "parse-time" (string))
  3302. (defvar align-mode-rules-list)
  3303. (defvar calc-embedded-close-formula)
  3304. (defvar calc-embedded-open-formula)
  3305. (defvar calc-embedded-open-mode)
  3306. (defvar font-lock-unfontify-region-function)
  3307. (defvar iswitchb-temp-buflist)
  3308. (defvar org-agenda-tags-todo-honor-ignore-options)
  3309. (defvar remember-data-file)
  3310. (defvar texmathp-why)
  3311. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3312. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3313. (declare-function org-resolve-clocks "org-clock"
  3314. (&optional also-non-dangling-p prompt last-valid))
  3315. (defvar org-clock-start-time)
  3316. (defvar org-clock-marker (make-marker)
  3317. "Marker recording the last clock-in.")
  3318. (defvar org-clock-hd-marker (make-marker)
  3319. "Marker recording the last clock-in, but the headline position.")
  3320. (defvar org-clock-heading ""
  3321. "The heading of the current clock entry.")
  3322. (defun org-clocking-buffer ()
  3323. "Return the buffer where the clock is currently running.
  3324. Return nil if no clock is running."
  3325. (marker-buffer org-clock-marker))
  3326. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3327. (defun org-check-running-clock ()
  3328. "Check if the current buffer contains the running clock.
  3329. If yes, offer to stop it and to save the buffer with the changes."
  3330. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3331. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3332. (buffer-name))))
  3333. (org-clock-out)
  3334. (when (y-or-n-p "Save changed buffer?")
  3335. (save-buffer))))
  3336. (defun org-clocktable-try-shift (dir n)
  3337. "Check if this line starts a clock table, if yes, shift the time block."
  3338. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3339. (org-clocktable-shift dir n)))
  3340. ;;;###autoload
  3341. (defun org-clock-persistence-insinuate ()
  3342. "Set up hooks for clock persistence."
  3343. (require 'org-clock)
  3344. (add-hook 'org-mode-hook 'org-clock-load)
  3345. (add-hook 'kill-emacs-hook 'org-clock-save))
  3346. (defun org-clock-auto-clockout-insinuate ()
  3347. "Set up hook for auto clocking out when Emacs is idle.
  3348. See `org-clock-auto-clockout-timer'.
  3349. This function is meant to be added to the user configuration."
  3350. (require 'org-clock)
  3351. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3352. (defgroup org-archive nil
  3353. "Options concerning archiving in Org mode."
  3354. :tag "Org Archive"
  3355. :group 'org-structure)
  3356. (defcustom org-archive-location "%s_archive::"
  3357. "The location where subtrees should be archived.
  3358. The value of this variable is a string, consisting of two parts,
  3359. separated by a double-colon. The first part is a filename and
  3360. the second part is a headline.
  3361. When the filename is omitted, archiving happens in the same file.
  3362. %s in the filename will be replaced by the current file
  3363. name (without the directory part). Archiving to a different file
  3364. is useful to keep archived entries from contributing to the
  3365. Org Agenda.
  3366. The archived entries will be filed as subtrees of the specified
  3367. headline. When the headline is omitted, the subtrees are simply
  3368. filed away at the end of the file, as top-level entries. Also in
  3369. the heading you can use %s to represent the file name, this can be
  3370. useful when using the same archive for a number of different files.
  3371. Here are a few examples:
  3372. \"%s_archive::\"
  3373. If the current file is Projects.org, archive in file
  3374. Projects.org_archive, as top-level trees. This is the default.
  3375. \"::* Archived Tasks\"
  3376. Archive in the current file, under the top-level headline
  3377. \"* Archived Tasks\".
  3378. \"~/org/archive.org::\"
  3379. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3380. \"~/org/archive.org::* From %s\"
  3381. Archive in file ~/org/archive.org (absolute path), under headlines
  3382. \"From FILENAME\" where file name is the current file name.
  3383. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3384. The \"datetree/\" string is special, signifying to archive
  3385. items to the datetree. Items are placed in either the CLOSED
  3386. date of the item, or the current date if there is no CLOSED date.
  3387. The heading will be a subentry to the current date. There doesn't
  3388. need to be a heading, but there always needs to be a slash after
  3389. datetree. For example, to store archived items directly in the
  3390. datetree, use \"~/org/datetree.org::datetree/\".
  3391. \"basement::** Finished Tasks\"
  3392. Archive in file ./basement (relative path), as level 3 trees
  3393. below the level 2 heading \"** Finished Tasks\".
  3394. You may define it locally by setting an ARCHIVE property. If
  3395. such a property is found in the file or in an entry, and anywhere
  3396. up the hierarchy, it will be used.
  3397. You can also set it for the whole file using the keyword-syntax:
  3398. #+ARCHIVE: basement::** Finished Tasks"
  3399. :group 'org-archive
  3400. :type 'string)
  3401. (defcustom org-agenda-skip-archived-trees t
  3402. "Non-nil means the agenda will skip any items located in archived trees.
  3403. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3404. variable is no longer recommended, you should leave it at the value t.
  3405. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3406. :group 'org-archive
  3407. :group 'org-agenda-skip
  3408. :type 'boolean)
  3409. (defcustom org-columns-skip-archived-trees t
  3410. "Non-nil means ignore archived trees when creating column view."
  3411. :group 'org-archive
  3412. :group 'org-properties
  3413. :type 'boolean)
  3414. (defcustom org-cycle-open-archived-trees nil
  3415. "Non-nil means `org-cycle' will open archived trees.
  3416. An archived tree is a tree marked with the tag ARCHIVE.
  3417. When nil, archived trees will stay folded. You can still open them with
  3418. normal outline commands like `show-all', but not with the cycling commands."
  3419. :group 'org-archive
  3420. :group 'org-cycle
  3421. :type 'boolean)
  3422. (defcustom org-sparse-tree-open-archived-trees nil
  3423. "Non-nil means sparse tree construction shows matches in archived trees.
  3424. When nil, matches in these trees are highlighted, but the trees are kept in
  3425. collapsed state."
  3426. :group 'org-archive
  3427. :group 'org-sparse-trees
  3428. :type 'boolean)
  3429. (defcustom org-sparse-tree-default-date-type nil
  3430. "The default date type when building a sparse tree.
  3431. When this is nil, a date is a scheduled or a deadline timestamp.
  3432. Otherwise, these types are allowed:
  3433. all: all timestamps
  3434. active: only active timestamps (<...>)
  3435. inactive: only inactive timestamps ([...])
  3436. scheduled: only scheduled timestamps
  3437. deadline: only deadline timestamps"
  3438. :type '(choice (const :tag "Scheduled or deadline" nil)
  3439. (const :tag "All timestamps" all)
  3440. (const :tag "Only active timestamps" active)
  3441. (const :tag "Only inactive timestamps" inactive)
  3442. (const :tag "Only scheduled timestamps" scheduled)
  3443. (const :tag "Only deadline timestamps" deadline)
  3444. (const :tag "Only closed timestamps" closed))
  3445. :version "26.1"
  3446. :package-version '(Org . "8.3")
  3447. :group 'org-sparse-trees)
  3448. (defun org-cycle-hide-archived-subtrees (state)
  3449. "Re-hide all archived subtrees after a visibility state change.
  3450. STATE should be one of the symbols listed in the docstring of
  3451. `org-cycle-hook'."
  3452. (when (and (not org-cycle-open-archived-trees)
  3453. (not (memq state '(overview folded))))
  3454. (save-excursion
  3455. (let* ((globalp (memq state '(contents all)))
  3456. (beg (if globalp (point-min) (point)))
  3457. (end (if globalp (point-max) (org-end-of-subtree t))))
  3458. (org-hide-archived-subtrees beg end)
  3459. (goto-char beg)
  3460. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3461. (message "%s" (substitute-command-keys
  3462. "Subtree is archived and stays closed. Use \
  3463. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3464. (defun org-force-cycle-archived ()
  3465. "Cycle subtree even if it is archived."
  3466. (interactive)
  3467. (setq this-command 'org-cycle)
  3468. (let ((org-cycle-open-archived-trees t))
  3469. (call-interactively 'org-cycle)))
  3470. (defun org-hide-archived-subtrees (beg end)
  3471. "Re-hide all archived subtrees after a visibility state change."
  3472. (org-with-wide-buffer
  3473. (let ((case-fold-search nil)
  3474. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3475. (goto-char beg)
  3476. ;; Include headline point is currently on.
  3477. (beginning-of-line)
  3478. (while (and (< (point) end) (re-search-forward re end t))
  3479. (when (member org-archive-tag (org-get-tags nil t))
  3480. (org-flag-subtree t)
  3481. (org-end-of-subtree t))))))
  3482. (defun org-flag-subtree (flag)
  3483. (save-excursion
  3484. (org-back-to-heading t)
  3485. (org-flag-region (line-end-position)
  3486. (progn (org-end-of-subtree t) (point))
  3487. flag
  3488. 'outline)))
  3489. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3490. ;; Declare Column View Code
  3491. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3492. (declare-function org-columns-compute "org-colview" (property))
  3493. ;; Declare ID code
  3494. (declare-function org-id-store-link "org-id")
  3495. (declare-function org-id-locations-load "org-id")
  3496. (declare-function org-id-locations-save "org-id")
  3497. (defvar org-id-track-globally)
  3498. ;;; Variables for pre-computed regular expressions, all buffer local
  3499. (defvar-local org-todo-regexp nil
  3500. "Matches any of the TODO state keywords.
  3501. Since TODO keywords are case-sensitive, `case-fold-search' is
  3502. expected to be bound to nil when matching against this regexp.")
  3503. (defvar-local org-not-done-regexp nil
  3504. "Matches any of the TODO state keywords except the last one.
  3505. Since TODO keywords are case-sensitive, `case-fold-search' is
  3506. expected to be bound to nil when matching against this regexp.")
  3507. (defvar-local org-not-done-heading-regexp nil
  3508. "Matches a TODO headline that is not done.
  3509. Since TODO keywords are case-sensitive, `case-fold-search' is
  3510. expected to be bound to nil when matching against this regexp.")
  3511. (defvar-local org-todo-line-regexp nil
  3512. "Matches a headline and puts TODO state into group 2 if present.
  3513. Since TODO keywords are case-sensitive, `case-fold-search' is
  3514. expected to be bound to nil when matching against this regexp.")
  3515. (defvar-local org-complex-heading-regexp nil
  3516. "Matches a headline and puts everything into groups:
  3517. group 1: Stars
  3518. group 2: The TODO keyword, maybe
  3519. group 3: Priority cookie
  3520. group 4: True headline
  3521. group 5: Tags
  3522. Since TODO keywords are case-sensitive, `case-fold-search' is
  3523. expected to be bound to nil when matching against this regexp.")
  3524. (defvar-local org-complex-heading-regexp-format nil
  3525. "Printf format to make regexp to match an exact headline.
  3526. This regexp will match the headline of any node which has the
  3527. exact headline text that is put into the format, but may have any
  3528. TODO state, priority and tags.")
  3529. (defvar-local org-todo-line-tags-regexp nil
  3530. "Matches a headline and puts TODO state into group 2 if present.
  3531. Also put tags into group 4 if tags are present.")
  3532. (defconst org-plain-time-of-day-regexp
  3533. (concat
  3534. "\\(\\<[012]?[0-9]"
  3535. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3536. "\\(--?"
  3537. "\\(\\<[012]?[0-9]"
  3538. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3539. "\\)?")
  3540. "Regular expression to match a plain time or time range.
  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. 1 the first time, range or not
  3545. 8 the second time, if it is a range.")
  3546. (defconst org-plain-time-extension-regexp
  3547. (concat
  3548. "\\(\\<[012]?[0-9]"
  3549. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3550. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3551. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3552. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3553. groups carry important information:
  3554. 0 the full match
  3555. 7 hours of duration
  3556. 9 minutes of duration")
  3557. (defconst org-stamp-time-of-day-regexp
  3558. (concat
  3559. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3560. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3561. "\\(--?"
  3562. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3563. "Regular expression to match a timestamp time or time range.
  3564. After a match, the following groups carry important information:
  3565. 0 the full match
  3566. 1 date plus weekday, for back referencing to make sure
  3567. both times are on the same day
  3568. 2 the first time, range or not
  3569. 4 the second time, if it is a range.")
  3570. (defconst org-startup-options
  3571. '(("fold" org-startup-folded t)
  3572. ("overview" org-startup-folded t)
  3573. ("nofold" org-startup-folded nil)
  3574. ("showall" org-startup-folded nil)
  3575. ("show2levels" org-startup-folded show2levels)
  3576. ("show3levels" org-startup-folded show3levels)
  3577. ("show4levels" org-startup-folded show4levels)
  3578. ("show5levels" org-startup-folded show5levels)
  3579. ("showeverything" org-startup-folded showeverything)
  3580. ("content" org-startup-folded content)
  3581. ("indent" org-startup-indented t)
  3582. ("noindent" org-startup-indented nil)
  3583. ("num" org-startup-numerated t)
  3584. ("nonum" org-startup-numerated nil)
  3585. ("hidestars" org-hide-leading-stars t)
  3586. ("showstars" org-hide-leading-stars nil)
  3587. ("odd" org-odd-levels-only t)
  3588. ("oddeven" org-odd-levels-only nil)
  3589. ("align" org-startup-align-all-tables t)
  3590. ("noalign" org-startup-align-all-tables nil)
  3591. ("shrink" org-startup-shrink-all-tables t)
  3592. ("inlineimages" org-startup-with-inline-images t)
  3593. ("noinlineimages" org-startup-with-inline-images nil)
  3594. ("latexpreview" org-startup-with-latex-preview t)
  3595. ("nolatexpreview" org-startup-with-latex-preview nil)
  3596. ("customtime" org-display-custom-times t)
  3597. ("logdone" org-log-done time)
  3598. ("lognotedone" org-log-done note)
  3599. ("nologdone" org-log-done nil)
  3600. ("lognoteclock-out" org-log-note-clock-out t)
  3601. ("nolognoteclock-out" org-log-note-clock-out nil)
  3602. ("logrepeat" org-log-repeat state)
  3603. ("lognoterepeat" org-log-repeat note)
  3604. ("logdrawer" org-log-into-drawer t)
  3605. ("nologdrawer" org-log-into-drawer nil)
  3606. ("logstatesreversed" org-log-states-order-reversed t)
  3607. ("nologstatesreversed" org-log-states-order-reversed nil)
  3608. ("nologrepeat" org-log-repeat nil)
  3609. ("logreschedule" org-log-reschedule time)
  3610. ("lognotereschedule" org-log-reschedule note)
  3611. ("nologreschedule" org-log-reschedule nil)
  3612. ("logredeadline" org-log-redeadline time)
  3613. ("lognoteredeadline" org-log-redeadline note)
  3614. ("nologredeadline" org-log-redeadline nil)
  3615. ("logrefile" org-log-refile time)
  3616. ("lognoterefile" org-log-refile note)
  3617. ("nologrefile" org-log-refile nil)
  3618. ("fninline" org-footnote-define-inline t)
  3619. ("nofninline" org-footnote-define-inline nil)
  3620. ("fnlocal" org-footnote-section nil)
  3621. ("fnauto" org-footnote-auto-label t)
  3622. ("fnprompt" org-footnote-auto-label nil)
  3623. ("fnconfirm" org-footnote-auto-label confirm)
  3624. ("fnplain" org-footnote-auto-label plain)
  3625. ("fnadjust" org-footnote-auto-adjust t)
  3626. ("nofnadjust" org-footnote-auto-adjust nil)
  3627. ("constcgs" constants-unit-system cgs)
  3628. ("constSI" constants-unit-system SI)
  3629. ("noptag" org-tag-persistent-alist nil)
  3630. ("hideblocks" org-hide-block-startup t)
  3631. ("nohideblocks" org-hide-block-startup nil)
  3632. ("beamer" org-startup-with-beamer-mode t)
  3633. ("entitiespretty" org-pretty-entities t)
  3634. ("entitiesplain" org-pretty-entities nil))
  3635. "Variable associated with STARTUP options for Org.
  3636. Each element is a list of three items: the startup options (as written
  3637. in the #+STARTUP line), the corresponding variable, and the value to set
  3638. this variable to if the option is found. An optional fourth element PUSH
  3639. means to push this value onto the list in the variable.")
  3640. (defcustom org-group-tags t
  3641. "When non-nil (the default), use group tags.
  3642. This can be turned on/off through `org-toggle-tags-groups'."
  3643. :group 'org-tags
  3644. :group 'org-startup
  3645. :type 'boolean)
  3646. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3647. (defun org-toggle-tags-groups ()
  3648. "Toggle support for group tags.
  3649. Support for group tags is controlled by the option
  3650. `org-group-tags', which is non-nil by default."
  3651. (interactive)
  3652. (setq org-group-tags (not org-group-tags))
  3653. (cond ((and (derived-mode-p 'org-agenda-mode)
  3654. org-group-tags)
  3655. (org-agenda-redo))
  3656. ((derived-mode-p 'org-mode)
  3657. (let ((org-inhibit-startup t)) (org-mode))))
  3658. (message "Groups tags support has been turned %s"
  3659. (if org-group-tags "on" "off")))
  3660. (defun org--tag-add-to-alist (alist1 alist2)
  3661. "Merge tags from ALIST1 into ALIST2.
  3662. Duplicates tags outside a group are removed. Keywords and order
  3663. are preserved.
  3664. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3665. See `org-tag-alist' for their structure."
  3666. (cond
  3667. ((null alist2) alist1)
  3668. ((null alist1) alist2)
  3669. (t
  3670. (let ((to-add nil)
  3671. (group-flag nil))
  3672. (dolist (tag-pair alist1)
  3673. (pcase tag-pair
  3674. (`(,(or :startgrouptag :startgroup))
  3675. (setq group-flag t)
  3676. (push tag-pair to-add))
  3677. (`(,(or :endgrouptag :endgroup))
  3678. (setq group-flag nil)
  3679. (push tag-pair to-add))
  3680. (`(,(or :grouptags :newline))
  3681. (push tag-pair to-add))
  3682. (`(,tag . ,_)
  3683. ;; Remove duplicates from ALIST1, unless they are in
  3684. ;; a group. Indeed, it makes sense to have a tag appear in
  3685. ;; multiple groups.
  3686. (when (or group-flag (not (assoc tag alist2)))
  3687. (push tag-pair to-add)))
  3688. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3689. ;; Preserve order of ALIST1.
  3690. (append (nreverse to-add) alist2)))))
  3691. (defun org-priority-to-value (s)
  3692. "Convert priority string S to its numeric value."
  3693. (or (save-match-data
  3694. (and (string-match "\\([0-9]+\\)" s)
  3695. (string-to-number (match-string 1 s))))
  3696. (string-to-char s)))
  3697. (defun org-set-regexps-and-options (&optional tags-only)
  3698. "Precompute regular expressions used in the current buffer.
  3699. When optional argument TAGS-ONLY is non-nil, only compute tags
  3700. related expressions."
  3701. (when (derived-mode-p 'org-mode)
  3702. (let ((alist (org-collect-keywords
  3703. (append '("FILETAGS" "TAGS")
  3704. (and (not tags-only)
  3705. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3706. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3707. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3708. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3709. ;; Startup options. Get this early since it does change
  3710. ;; behavior for other options (e.g., tags).
  3711. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3712. (cdr (assoc "STARTUP" alist)))))
  3713. (dolist (option startup)
  3714. (pcase (assoc-string option org-startup-options t)
  3715. (`(,_ ,variable ,value t)
  3716. (unless (listp (symbol-value variable))
  3717. (set (make-local-variable variable) nil))
  3718. (add-to-list variable value))
  3719. (`(,_ ,variable ,value . ,_)
  3720. (set (make-local-variable variable) value))
  3721. (_ nil))))
  3722. (setq-local org-file-tags
  3723. (mapcar #'org-add-prop-inherited
  3724. (cl-mapcan (lambda (value)
  3725. (cl-mapcan
  3726. (lambda (k) (org-split-string k ":"))
  3727. (split-string value)))
  3728. (cdr (assoc "FILETAGS" alist)))))
  3729. (setq org-current-tag-alist
  3730. (org--tag-add-to-alist
  3731. org-tag-persistent-alist
  3732. (let ((tags (cdr (assoc "TAGS" alist))))
  3733. (if tags
  3734. (org-tag-string-to-alist
  3735. (mapconcat #'identity tags "\n"))
  3736. org-tag-alist))))
  3737. (setq org-tag-groups-alist
  3738. (org-tag-alist-to-groups org-current-tag-alist))
  3739. (unless tags-only
  3740. ;; Properties.
  3741. (let ((properties nil))
  3742. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3743. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3744. (setq properties (org--update-property-plist
  3745. (match-string-no-properties 1 value)
  3746. (match-string-no-properties 2 value)
  3747. properties))))
  3748. (setq-local org-keyword-properties properties))
  3749. ;; Archive location.
  3750. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3751. (when archive (setq-local org-archive-location archive)))
  3752. ;; Category.
  3753. (let ((category (cdr (assoc "CATEGORY" alist))))
  3754. (when category
  3755. (setq-local org-category (intern category))
  3756. (setq-local org-keyword-properties
  3757. (org--update-property-plist
  3758. "CATEGORY" category org-keyword-properties))))
  3759. ;; Columns.
  3760. (let ((column (cdr (assoc "COLUMNS" alist))))
  3761. (when column (setq-local org-columns-default-format column)))
  3762. ;; Constants.
  3763. (let ((store nil))
  3764. (dolist (pair (cl-mapcan #'split-string
  3765. (cdr (assoc "CONSTANTS" alist))))
  3766. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3767. (let* ((name (match-string 1 pair))
  3768. (value (match-string 2 pair))
  3769. (old (assoc name store)))
  3770. (if old (setcdr old value)
  3771. (push (cons name value) store)))))
  3772. (setq org-table-formula-constants-local store))
  3773. ;; Link abbreviations.
  3774. (let ((links
  3775. (delq nil
  3776. (mapcar
  3777. (lambda (value)
  3778. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3779. (cons (match-string-no-properties 1 value)
  3780. (match-string-no-properties 2 value))))
  3781. (cdr (assoc "LINK" alist))))))
  3782. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3783. ;; Priorities.
  3784. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3785. (pcase (and value (split-string value))
  3786. (`(,high ,low ,default . ,_)
  3787. (setq-local org-priority-highest (org-priority-to-value high))
  3788. (setq-local org-priority-lowest (org-priority-to-value low))
  3789. (setq-local org-priority-default (org-priority-to-value default)))))
  3790. ;; Scripts.
  3791. (let ((value (cdr (assoc "OPTIONS" alist))))
  3792. (dolist (option value)
  3793. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3794. (setq-local org-use-sub-superscripts
  3795. (read (match-string 1 option))))))
  3796. ;; TODO keywords.
  3797. (setq-local org-todo-kwd-alist nil)
  3798. (setq-local org-todo-key-alist nil)
  3799. (setq-local org-todo-key-trigger nil)
  3800. (setq-local org-todo-keywords-1 nil)
  3801. (setq-local org-done-keywords nil)
  3802. (setq-local org-todo-heads nil)
  3803. (setq-local org-todo-sets nil)
  3804. (setq-local org-todo-log-states nil)
  3805. (let ((todo-sequences
  3806. (or (append (mapcar (lambda (value)
  3807. (cons 'type (split-string value)))
  3808. (cdr (assoc "TYP_TODO" alist)))
  3809. (mapcar (lambda (value)
  3810. (cons 'sequence (split-string value)))
  3811. (append (cdr (assoc "TODO" alist))
  3812. (cdr (assoc "SEQ_TODO" alist)))))
  3813. (let ((d (default-value 'org-todo-keywords)))
  3814. (if (not (stringp (car d))) d
  3815. ;; XXX: Backward compatibility code.
  3816. (list (cons org-todo-interpretation d)))))))
  3817. (dolist (sequence todo-sequences)
  3818. (let* ((sequence (or (run-hook-with-args-until-success
  3819. 'org-todo-setup-filter-hook sequence)
  3820. sequence))
  3821. (sequence-type (car sequence))
  3822. (keywords (cdr sequence))
  3823. (sep (member "|" keywords))
  3824. names alist)
  3825. (dolist (k (remove "|" keywords))
  3826. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3827. k)
  3828. (error "Invalid TODO keyword %s" k))
  3829. (let ((name (match-string 1 k))
  3830. (key (match-string 2 k))
  3831. (log (org-extract-log-state-settings k)))
  3832. (push name names)
  3833. (push (cons name (and key (string-to-char key))) alist)
  3834. (when log (push log org-todo-log-states))))
  3835. (let* ((names (nreverse names))
  3836. (done (if sep (org-remove-keyword-keys (cdr sep))
  3837. (last names)))
  3838. (head (car names))
  3839. (tail (list sequence-type head (car done) (org-last done))))
  3840. (add-to-list 'org-todo-heads head 'append)
  3841. (push names org-todo-sets)
  3842. (setq org-done-keywords (append org-done-keywords done nil))
  3843. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3844. (setq org-todo-key-alist
  3845. (append org-todo-key-alist
  3846. (and alist
  3847. (append '((:startgroup))
  3848. (nreverse alist)
  3849. '((:endgroup))))))
  3850. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3851. (setq org-todo-sets (nreverse org-todo-sets)
  3852. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3853. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3854. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3855. ;; Compute the regular expressions and other local variables.
  3856. ;; Using `org-outline-regexp-bol' would complicate them much,
  3857. ;; because of the fixed white space at the end of that string.
  3858. (unless org-done-keywords
  3859. (setq org-done-keywords
  3860. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3861. (setq org-not-done-keywords
  3862. (org-delete-all org-done-keywords
  3863. (copy-sequence org-todo-keywords-1))
  3864. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3865. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3866. org-not-done-heading-regexp
  3867. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3868. org-todo-line-regexp
  3869. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3870. org-complex-heading-regexp
  3871. (concat "^\\(\\*+\\)"
  3872. "\\(?: +" org-todo-regexp "\\)?"
  3873. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3874. "\\(?: +\\(.*?\\)\\)??"
  3875. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3876. "[ \t]*$")
  3877. org-complex-heading-regexp-format
  3878. (concat "^\\(\\*+\\)"
  3879. "\\(?: +" org-todo-regexp "\\)?"
  3880. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3881. "\\(?: +"
  3882. ;; Stats cookies can be stuck to body.
  3883. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3884. "\\(%s\\)"
  3885. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3886. "\\)"
  3887. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3888. "[ \t]*$")
  3889. org-todo-line-tags-regexp
  3890. (concat "^\\(\\*+\\)"
  3891. "\\(?: +" org-todo-regexp "\\)?"
  3892. "\\(?: +\\(.*?\\)\\)??"
  3893. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3894. "[ \t]*$"))
  3895. (org-compute-latex-and-related-regexp)))))
  3896. (defun org-collect-keywords (keywords &optional unique directory)
  3897. "Return values for KEYWORDS in current buffer, as an alist.
  3898. KEYWORDS is a list of strings. Return value is a list of
  3899. elements with the pattern:
  3900. (NAME . LIST-OF-VALUES)
  3901. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3902. is a list of non-empty values, as strings, in order of appearance
  3903. in the buffer.
  3904. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3905. value, empty or not, appearing in the buffer, as a string.
  3906. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3907. (VALUE . DIRECTORY)
  3908. where VALUE is the regular value, and DIRECTORY is the variable
  3909. `default-directory' for the buffer containing the keyword. This
  3910. is important for values containing relative file names, since the
  3911. function follows SETUPFILE keywords, and may change its working
  3912. directory."
  3913. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3914. (unique (mapcar #'upcase unique))
  3915. (alist (org--collect-keywords-1
  3916. keywords unique directory
  3917. (and buffer-file-name (list buffer-file-name))
  3918. nil)))
  3919. ;; Re-order results.
  3920. (dolist (entry alist)
  3921. (pcase entry
  3922. (`(,_ . ,(and value (pred consp)))
  3923. (setcdr entry (nreverse value)))))
  3924. (nreverse alist)))
  3925. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3926. (org-with-point-at 1
  3927. (let ((case-fold-search t)
  3928. (regexp (org-make-options-regexp keywords)))
  3929. (while (and keywords (re-search-forward regexp nil t))
  3930. (let ((element (org-element-at-point)))
  3931. (when (eq 'keyword (org-element-type element))
  3932. (let ((value (org-element-property :value element)))
  3933. (pcase (org-element-property :key element)
  3934. ("SETUPFILE"
  3935. (when (and (org-string-nw-p value)
  3936. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3937. (let* ((uri (org-strip-quotes value))
  3938. (uri-is-url (org-url-p uri))
  3939. (uri (if uri-is-url
  3940. uri
  3941. (expand-file-name uri))))
  3942. (unless (member uri files)
  3943. (with-temp-buffer
  3944. (unless uri-is-url
  3945. (setq default-directory (file-name-directory uri)))
  3946. (let ((contents (org-file-contents uri :noerror)))
  3947. (when contents
  3948. (insert contents)
  3949. ;; Fake Org mode: `org-element-at-point'
  3950. ;; doesn't need full set-up.
  3951. (let ((major-mode 'org-mode))
  3952. (setq alist
  3953. (org--collect-keywords-1
  3954. keywords unique directory
  3955. (cons uri files)
  3956. alist))))))))))
  3957. (keyword
  3958. (let ((entry (assoc keyword alist))
  3959. (final
  3960. (cond ((not (member keyword directory)) value)
  3961. (buffer-file-name
  3962. (cons value
  3963. (file-name-directory buffer-file-name)))
  3964. (t (cons value default-directory)))))
  3965. (cond ((member keyword unique)
  3966. (push (cons keyword final) alist)
  3967. (setq keywords (remove keyword keywords))
  3968. (setq regexp (org-make-options-regexp keywords)))
  3969. ((null entry) (push (list keyword final) alist))
  3970. (t (push final (cdr entry)))))))))))
  3971. alist)))
  3972. (defun org-tag-string-to-alist (s)
  3973. "Return tag alist associated to string S.
  3974. S is a value for TAGS keyword or produced with
  3975. `org-tag-alist-to-string'. Return value is an alist suitable for
  3976. `org-tag-alist' or `org-tag-persistent-alist'."
  3977. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3978. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3979. "\\(?:(\\(.\\))\\)?\\'"))
  3980. alist group-flag)
  3981. (dolist (tokens lines (cdr (nreverse alist)))
  3982. (push '(:newline) alist)
  3983. (while tokens
  3984. (let ((token (pop tokens)))
  3985. (pcase token
  3986. ("{"
  3987. (push '(:startgroup) alist)
  3988. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3989. ("}"
  3990. (push '(:endgroup) alist)
  3991. (setq group-flag nil))
  3992. ("["
  3993. (push '(:startgrouptag) alist)
  3994. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3995. ("]"
  3996. (push '(:endgrouptag) alist)
  3997. (setq group-flag nil))
  3998. (":"
  3999. (push '(:grouptags) alist))
  4000. ((guard (string-match tag-re token))
  4001. (let ((tag (match-string 1 token))
  4002. (key (and (match-beginning 2)
  4003. (string-to-char (match-string 2 token)))))
  4004. ;; Push all tags in groups, no matter if they already
  4005. ;; appear somewhere else in the list.
  4006. (when (or group-flag (not (assoc tag alist)))
  4007. (push (cons tag key) alist))))))))))
  4008. (defun org-tag-alist-to-string (alist &optional skip-key)
  4009. "Return tag string associated to ALIST.
  4010. ALIST is an alist, as defined in `org-tag-alist' or
  4011. `org-tag-persistent-alist', or produced with
  4012. `org-tag-string-to-alist'.
  4013. Return value is a string suitable as a value for \"TAGS\"
  4014. keyword.
  4015. When optional argument SKIP-KEY is non-nil, skip selection keys
  4016. next to tags."
  4017. (mapconcat (lambda (token)
  4018. (pcase token
  4019. (`(:startgroup) "{")
  4020. (`(:endgroup) "}")
  4021. (`(:startgrouptag) "[")
  4022. (`(:endgrouptag) "]")
  4023. (`(:grouptags) ":")
  4024. (`(:newline) "\\n")
  4025. ((and
  4026. (guard (not skip-key))
  4027. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4028. (format "%s(%c)" tag key))
  4029. (`(,(and tag (pred stringp)) . ,_) tag)
  4030. (_ (user-error "Invalid tag token: %S" token))))
  4031. alist
  4032. " "))
  4033. (defun org-tag-alist-to-groups (alist)
  4034. "Return group alist from tag ALIST.
  4035. ALIST is an alist, as defined in `org-tag-alist' or
  4036. `org-tag-persistent-alist', or produced with
  4037. `org-tag-string-to-alist'. Return value is an alist following
  4038. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4039. a string, summarizing TAGS, as a list of strings."
  4040. (let (groups group-status current-group)
  4041. (dolist (token alist (nreverse groups))
  4042. (pcase token
  4043. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4044. (`(,(or :endgroup :endgrouptag))
  4045. (when (eq group-status 'append)
  4046. (push (nreverse current-group) groups))
  4047. (setq group-status nil current-group nil))
  4048. (`(:grouptags) (setq group-status 'append))
  4049. ((and `(,tag . ,_) (guard group-status))
  4050. (if (eq group-status 'append) (push tag current-group)
  4051. (setq current-group (list tag))))
  4052. (_ nil)))))
  4053. (defvar org--file-cache (make-hash-table :test #'equal)
  4054. "Hash table to store contents of files referenced via a URL.
  4055. This is the cache of file URLs read using `org-file-contents'.")
  4056. (defun org-reset-file-cache ()
  4057. "Reset the cache of files downloaded by `org-file-contents'."
  4058. (clrhash org--file-cache))
  4059. (defun org-file-contents (file &optional noerror nocache)
  4060. "Return the contents of FILE, as a string.
  4061. FILE can be a file name or URL.
  4062. If FILE is a URL, download the contents. If the URL contents are
  4063. already cached in the `org--file-cache' hash table, the download step
  4064. is skipped.
  4065. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4066. from file or URL, and return nil.
  4067. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4068. is available. This option applies only if FILE is a URL."
  4069. (let* ((is-url (org-url-p file))
  4070. (cache (and is-url
  4071. (not nocache)
  4072. (gethash file org--file-cache))))
  4073. (cond
  4074. (cache)
  4075. (is-url
  4076. (with-current-buffer (url-retrieve-synchronously file)
  4077. (goto-char (point-min))
  4078. ;; Move point to after the url-retrieve header.
  4079. (search-forward "\n\n" nil :move)
  4080. ;; Search for the success code only in the url-retrieve header.
  4081. (if (save-excursion
  4082. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4083. ;; Update the cache `org--file-cache' and return contents.
  4084. (puthash file
  4085. (buffer-substring-no-properties (point) (point-max))
  4086. org--file-cache)
  4087. (funcall (if noerror #'message #'user-error)
  4088. "Unable to fetch file from %S"
  4089. file)
  4090. nil)))
  4091. (t
  4092. (with-temp-buffer
  4093. (condition-case nil
  4094. (progn
  4095. (insert-file-contents file)
  4096. (buffer-string))
  4097. (file-error
  4098. (funcall (if noerror #'message #'user-error)
  4099. "Unable to read file %S"
  4100. file)
  4101. nil)))))))
  4102. (defun org-extract-log-state-settings (x)
  4103. "Extract the log state setting from a TODO keyword string.
  4104. This will extract info from a string like \"WAIT(w@/!)\"."
  4105. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4106. (let ((kw (match-string 1 x))
  4107. (log1 (and (match-end 3) (match-string 3 x)))
  4108. (log2 (and (match-end 4) (match-string 4 x))))
  4109. (and (or log1 log2)
  4110. (list kw
  4111. (and log1 (if (equal log1 "!") 'time 'note))
  4112. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4113. (defun org-remove-keyword-keys (list)
  4114. "Remove a pair of parenthesis at the end of each string in LIST."
  4115. (mapcar (lambda (x)
  4116. (if (string-match "(.*)$" x)
  4117. (substring x 0 (match-beginning 0))
  4118. x))
  4119. list))
  4120. (defun org-assign-fast-keys (alist)
  4121. "Assign fast keys to a keyword-key alist.
  4122. Respect keys that are already there."
  4123. (let (new e (alt ?0))
  4124. (while (setq e (pop alist))
  4125. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4126. (cdr e)) ;; Key already assigned.
  4127. (push e new)
  4128. (let ((clist (string-to-list (downcase (car e))))
  4129. (used (append new alist)))
  4130. (when (= (car clist) ?@)
  4131. (pop clist))
  4132. (while (and clist (rassoc (car clist) used))
  4133. (pop clist))
  4134. (unless clist
  4135. (while (rassoc alt used)
  4136. (cl-incf alt)))
  4137. (push (cons (car e) (or (car clist) alt)) new))))
  4138. (nreverse new)))
  4139. ;;; Some variables used in various places
  4140. (defvar org-window-configuration nil
  4141. "Used in various places to store a window configuration.")
  4142. (defvar org-selected-window nil
  4143. "Used in various places to store a window configuration.")
  4144. (defvar org-finish-function nil
  4145. "Function to be called when `C-c C-c' is used.
  4146. This is for getting out of special buffers like capture.")
  4147. (defvar org-last-state)
  4148. ;; Defined somewhere in this file, but used before definition.
  4149. (defvar org-entities) ;; defined in org-entities.el
  4150. (defvar org-struct-menu)
  4151. (defvar org-org-menu)
  4152. (defvar org-tbl-menu)
  4153. ;;;; Define the Org mode
  4154. (defun org-before-change-function (_beg _end)
  4155. "Every change indicates that a table might need an update."
  4156. (setq org-table-may-need-update t))
  4157. (defvar org-mode-map)
  4158. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4159. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4160. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4161. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4162. (defvar bidi-paragraph-direction)
  4163. (defvar buffer-face-mode-face)
  4164. (require 'outline)
  4165. ;; Other stuff we need.
  4166. (require 'time-date)
  4167. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4168. (require 'easymenu))
  4169. (require 'org-entities)
  4170. (require 'org-faces)
  4171. (require 'org-list)
  4172. (require 'org-pcomplete)
  4173. (require 'org-src)
  4174. (require 'org-footnote)
  4175. (require 'org-macro)
  4176. ;; babel
  4177. (require 'ob)
  4178. (defvar org-element-cache-persistent); Defined in org-element.el
  4179. (defvar org-element-use-cache); Defined in org-element.el
  4180. ;;;###autoload
  4181. (define-derived-mode org-mode outline-mode "Org"
  4182. "Outline-based notes management and organizer, alias
  4183. \"Carsten's outline-mode for keeping track of everything.\"
  4184. Org mode develops organizational tasks around a NOTES file which
  4185. contains information about projects as plain text. Org mode is
  4186. implemented on top of Outline mode, which is ideal to keep the content
  4187. of large files well structured. It supports ToDo items, deadlines and
  4188. time stamps, which magically appear in the diary listing of the Emacs
  4189. calendar. Tables are easily created with a built-in table editor.
  4190. Plain text URL-like links connect to websites, emails (VM), Usenet
  4191. messages (Gnus), BBDB entries, and any files related to the project.
  4192. For printing and sharing of notes, an Org file (or a part of it)
  4193. can be exported as a structured ASCII or HTML file.
  4194. The following commands are available:
  4195. \\{org-mode-map}"
  4196. (org-load-modules-maybe)
  4197. (org-install-agenda-files-menu)
  4198. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4199. (make-local-variable 'org-link-descriptive)
  4200. (add-to-invisibility-spec '(org-hide-block . t))
  4201. (setq-local outline-regexp org-outline-regexp)
  4202. (setq-local outline-level 'org-outline-level)
  4203. (setq bidi-paragraph-direction 'left-to-right)
  4204. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4205. (unless org-display-table
  4206. (setq org-display-table (make-display-table)))
  4207. (set-display-table-slot
  4208. org-display-table 4
  4209. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4210. org-ellipsis)))
  4211. (setq buffer-display-table org-display-table))
  4212. (org-set-regexps-and-options)
  4213. (org-set-font-lock-defaults)
  4214. (when (and org-tag-faces (not org-tags-special-faces-re))
  4215. ;; tag faces set outside customize.... force initialization.
  4216. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4217. ;; Calc embedded
  4218. (setq-local calc-embedded-open-mode "# ")
  4219. ;; Modify a few syntax entries
  4220. (modify-syntax-entry ?\" "\"")
  4221. (modify-syntax-entry ?\\ "_")
  4222. (modify-syntax-entry ?~ "_")
  4223. (modify-syntax-entry ?< "(>")
  4224. (modify-syntax-entry ?> ")<")
  4225. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4226. ;; Activate before-change-function
  4227. (setq-local org-table-may-need-update t)
  4228. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4229. ;; Check for running clock before killing a buffer
  4230. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4231. ;; Initialize macros templates.
  4232. (org-macro-initialize-templates)
  4233. ;; Initialize radio targets.
  4234. (org-update-radio-target-regexp)
  4235. ;; Indentation.
  4236. (setq-local indent-line-function 'org-indent-line)
  4237. (setq-local indent-region-function 'org-indent-region)
  4238. ;; Filling and auto-filling.
  4239. (org-setup-filling)
  4240. ;; Comments.
  4241. (org-setup-comments-handling)
  4242. ;; Initialize cache.
  4243. (org-element-cache-reset)
  4244. (when (and org-element-cache-persistent
  4245. org-element-use-cache)
  4246. (org-persist-read 'org-element--cache (current-buffer)))
  4247. ;; Beginning/end of defun
  4248. (setq-local beginning-of-defun-function 'org-backward-element)
  4249. (setq-local end-of-defun-function
  4250. (lambda ()
  4251. (if (not (org-at-heading-p))
  4252. (org-forward-element)
  4253. (org-forward-element)
  4254. (forward-char -1))))
  4255. ;; Next error for sparse trees
  4256. (setq-local next-error-function 'org-occur-next-match)
  4257. ;; Make commit log messages from Org documents easier.
  4258. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4259. ;; Make sure dependence stuff works reliably, even for users who set it
  4260. ;; too late :-(
  4261. (if org-enforce-todo-dependencies
  4262. (add-hook 'org-blocker-hook
  4263. 'org-block-todo-from-children-or-siblings-or-parent)
  4264. (remove-hook 'org-blocker-hook
  4265. 'org-block-todo-from-children-or-siblings-or-parent))
  4266. (if org-enforce-todo-checkbox-dependencies
  4267. (add-hook 'org-blocker-hook
  4268. 'org-block-todo-from-checkboxes)
  4269. (remove-hook 'org-blocker-hook
  4270. 'org-block-todo-from-checkboxes))
  4271. ;; Align options lines
  4272. (setq-local
  4273. align-mode-rules-list
  4274. '((org-in-buffer-settings
  4275. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4276. (modes . '(org-mode)))))
  4277. ;; Setup the pcomplete hooks
  4278. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4279. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4280. (setq-local pcomplete-default-completion-function #'ignore)
  4281. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4282. (setq-local pcomplete-termination-string "")
  4283. (add-hook 'completion-at-point-functions
  4284. #'pcomplete-completions-at-point nil t)
  4285. (setq-local buffer-face-mode-face 'org-default)
  4286. ;; If empty file that did not turn on Org mode automatically, make
  4287. ;; it to.
  4288. (when (and org-insert-mode-line-in-empty-file
  4289. (called-interactively-p 'any)
  4290. (= (point-min) (point-max)))
  4291. (insert "# -*- mode: org -*-\n\n"))
  4292. (unless org-inhibit-startup
  4293. (org-unmodified
  4294. (when org-startup-with-beamer-mode (org-beamer-mode))
  4295. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4296. (org-table-map-tables
  4297. (cond ((and org-startup-align-all-tables
  4298. org-startup-shrink-all-tables)
  4299. (lambda () (org-table-align) (org-table-shrink)))
  4300. (org-startup-align-all-tables #'org-table-align)
  4301. (t #'org-table-shrink))
  4302. t))
  4303. (when org-startup-with-inline-images (org-display-inline-images))
  4304. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4305. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4306. (when org-startup-truncated (setq truncate-lines t))
  4307. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4308. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4309. ;; Add a custom keymap for `visual-line-mode' so that activating
  4310. ;; this minor mode does not override Org's keybindings.
  4311. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4312. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4313. (newmap (make-sparse-keymap)))
  4314. (set-keymap-parent newmap oldmap)
  4315. (define-key newmap [remap move-beginning-of-line] nil)
  4316. (define-key newmap [remap move-end-of-line] nil)
  4317. (define-key newmap [remap kill-line] nil)
  4318. (make-local-variable 'minor-mode-overriding-map-alist)
  4319. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4320. ;; Activate `org-table-header-line-mode'
  4321. (when org-table-header-line-p
  4322. (org-table-header-line-mode 1))
  4323. ;; Try to set `org-hide' face correctly.
  4324. (let ((foreground (org-find-invisible-foreground)))
  4325. (when foreground
  4326. (set-face-foreground 'org-hide foreground)))
  4327. ;; Set face extension as requested.
  4328. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4329. org-fontify-whole-block-delimiter-line)
  4330. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4331. ;; Update `customize-package-emacs-version-alist'
  4332. (add-to-list 'customize-package-emacs-version-alist
  4333. '(Org ("8.0" . "24.4")
  4334. ("8.1" . "24.4")
  4335. ("8.2" . "24.4")
  4336. ("8.2.7" . "24.4")
  4337. ("8.3" . "26.1")
  4338. ("9.0" . "26.1")
  4339. ("9.1" . "26.1")
  4340. ("9.2" . "27.1")
  4341. ("9.3" . "27.1")
  4342. ("9.4" . "27.2")
  4343. ("9.5" . "28.1")))
  4344. (defvar org-mode-transpose-word-syntax-table
  4345. (let ((st (make-syntax-table text-mode-syntax-table)))
  4346. (dolist (c org-emphasis-alist st)
  4347. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4348. (when (fboundp 'abbrev-table-put)
  4349. (abbrev-table-put org-mode-abbrev-table
  4350. :parents (list text-mode-abbrev-table)))
  4351. (defun org-find-invisible-foreground ()
  4352. (let ((candidates (remove
  4353. "unspecified-bg"
  4354. (nconc
  4355. (list (face-background 'default)
  4356. (face-background 'org-default))
  4357. (mapcar
  4358. (lambda (alist)
  4359. (when (boundp alist)
  4360. (cdr (assq 'background-color (symbol-value alist)))))
  4361. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4362. (list (face-foreground 'org-hide))))))
  4363. (car (remove nil candidates))))
  4364. (defun org-current-time (&optional rounding-minutes past)
  4365. "Current time, possibly rounded to ROUNDING-MINUTES.
  4366. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4367. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4368. the rounding returns a past time."
  4369. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4370. (car org-time-stamp-rounding-minutes)))
  4371. (now (current-time)))
  4372. (if (< r 1)
  4373. now
  4374. (let* ((time (decode-time now))
  4375. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4376. (nthcdr 2 time))))
  4377. (if (or (not past) (time-less-p res now))
  4378. res
  4379. (time-subtract res (* r 60)))))))
  4380. (defun org-today ()
  4381. "Return today date, considering `org-extend-today-until'."
  4382. (time-to-days
  4383. (time-since (* 3600 org-extend-today-until))))
  4384. ;;;; Font-Lock stuff, including the activators
  4385. (defconst org-match-sexp-depth 3
  4386. "Number of stacked braces for sub/superscript matching.")
  4387. (defun org-create-multibrace-regexp (left right n)
  4388. "Create a regular expression which will match a balanced sexp.
  4389. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4390. as single character strings.
  4391. The regexp returned will match the entire expression including the
  4392. delimiters. It will also define a single group which contains the
  4393. match except for the outermost delimiters. The maximum depth of
  4394. stacked delimiters is N. Escaping delimiters is not possible."
  4395. (let* ((nothing (concat "[^" left right "]*?"))
  4396. (or "\\|")
  4397. (re nothing)
  4398. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4399. (while (> n 1)
  4400. (setq n (1- n)
  4401. re (concat re or next)
  4402. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4403. (concat left "\\(" re "\\)" right)))
  4404. (defconst org-match-substring-regexp
  4405. (concat
  4406. "\\(\\S-\\)\\([_^]\\)\\("
  4407. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4408. "\\|"
  4409. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4410. "\\|"
  4411. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4412. "The regular expression matching a sub- or superscript.")
  4413. (defconst org-match-substring-with-braces-regexp
  4414. (concat
  4415. "\\(\\S-\\)\\([_^]\\)"
  4416. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4417. "The regular expression matching a sub- or superscript, forcing braces.")
  4418. (defvar org-emph-face nil)
  4419. (defun org-do-emphasis-faces (limit)
  4420. "Run through the buffer and emphasize strings."
  4421. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4422. (car org-emphasis-regexp-components))))
  4423. (catch :exit
  4424. (while (re-search-forward quick-re limit t)
  4425. (let* ((marker (match-string 2))
  4426. (verbatim? (member marker '("~" "="))))
  4427. (when (save-excursion
  4428. (goto-char (match-beginning 0))
  4429. (and
  4430. ;; Do not match table hlines.
  4431. (not (and (equal marker "+")
  4432. (org-match-line
  4433. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4434. ;; Do not match headline stars. Do not consider
  4435. ;; stars of a headline as closing marker for bold
  4436. ;; markup either.
  4437. (not (and (equal marker "*")
  4438. (save-excursion
  4439. (forward-char)
  4440. (skip-chars-backward "*")
  4441. (looking-at-p org-outline-regexp-bol))))
  4442. ;; Match full emphasis markup regexp.
  4443. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4444. ;; Do not span over paragraph boundaries.
  4445. (not (string-match-p org-element-paragraph-separate
  4446. (match-string 2)))
  4447. ;; Do not span over cells in table rows.
  4448. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4449. (string-match-p "|" (match-string 4))))))
  4450. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4451. (m (if org-hide-emphasis-markers 4 2)))
  4452. (font-lock-prepend-text-property
  4453. (match-beginning m) (match-end m) 'face face)
  4454. (when verbatim?
  4455. (org-remove-flyspell-overlays-in
  4456. (match-beginning 0) (match-end 0))
  4457. (remove-text-properties (match-beginning 2) (match-end 2)
  4458. '(display t invisible t intangible t)))
  4459. (add-text-properties (match-beginning 2) (match-end 2)
  4460. '(font-lock-multiline t org-emphasis t))
  4461. (when (and org-hide-emphasis-markers
  4462. (not (org-at-comment-p)))
  4463. (add-text-properties (match-end 4) (match-beginning 5)
  4464. '(invisible t))
  4465. (add-text-properties (match-beginning 3) (match-end 3)
  4466. '(invisible t)))
  4467. (throw :exit t))))))))
  4468. (defun org-emphasize (&optional char)
  4469. "Insert or change an emphasis, i.e. a font like bold or italic.
  4470. If there is an active region, change that region to a new emphasis.
  4471. If there is no region, just insert the marker characters and position
  4472. the cursor between them.
  4473. CHAR should be the marker character. If it is a space, it means to
  4474. remove the emphasis of the selected region.
  4475. If CHAR is not given (for example in an interactive call) it will be
  4476. prompted for."
  4477. (interactive)
  4478. (let ((erc org-emphasis-regexp-components)
  4479. (string "") beg end move s)
  4480. (if (org-region-active-p)
  4481. (setq beg (region-beginning)
  4482. end (region-end)
  4483. string (buffer-substring beg end))
  4484. (setq move t))
  4485. (unless char
  4486. (message "Emphasis marker or tag: [%s]"
  4487. (mapconcat #'car org-emphasis-alist ""))
  4488. (setq char (read-char-exclusive)))
  4489. (if (equal char ?\s)
  4490. (setq s ""
  4491. move nil)
  4492. (unless (assoc (char-to-string char) org-emphasis-alist)
  4493. (user-error "No such emphasis marker: \"%c\"" char))
  4494. (setq s (char-to-string char)))
  4495. (while (and (> (length string) 1)
  4496. (equal (substring string 0 1) (substring string -1))
  4497. (assoc (substring string 0 1) org-emphasis-alist))
  4498. (setq string (substring string 1 -1)))
  4499. (setq string (concat s string s))
  4500. (when beg (delete-region beg end))
  4501. (unless (or (bolp)
  4502. (string-match (concat "[" (nth 0 erc) "\n]")
  4503. (char-to-string (char-before (point)))))
  4504. (insert " "))
  4505. (unless (or (eobp)
  4506. (string-match (concat "[" (nth 1 erc) "\n]")
  4507. (char-to-string (char-after (point)))))
  4508. (insert " ") (backward-char 1))
  4509. (insert string)
  4510. (and move (backward-char 1))))
  4511. (defconst org-nonsticky-props
  4512. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4513. (defsubst org-rear-nonsticky-at (pos)
  4514. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4515. (defun org-activate-links (limit)
  4516. "Add link properties to links.
  4517. This includes angle, plain, and bracket links."
  4518. (catch :exit
  4519. (while (re-search-forward org-link-any-re limit t)
  4520. (let* ((start (match-beginning 0))
  4521. (end (match-end 0))
  4522. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4523. (visible-end (or (match-end 3) (match-end 2)))
  4524. (style (cond ((eq ?< (char-after start)) 'angle)
  4525. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4526. (t 'plain))))
  4527. (when (and (memq style org-highlight-links)
  4528. ;; Do not span over paragraph boundaries.
  4529. (not (string-match-p org-element-paragraph-separate
  4530. (match-string 0)))
  4531. ;; Do not confuse plain links with tags.
  4532. (not (and (eq style 'plain)
  4533. (let ((face (get-text-property
  4534. (max (1- start) (point-min)) 'face)))
  4535. (if (consp face) (memq 'org-tag face)
  4536. (eq 'org-tag face))))))
  4537. (let* ((link-object (save-excursion
  4538. (goto-char start)
  4539. (save-match-data (org-element-link-parser))))
  4540. (link (org-element-property :raw-link link-object))
  4541. (type (org-element-property :type link-object))
  4542. (path (org-element-property :path link-object))
  4543. (face-property (pcase (org-link-get-parameter type :face)
  4544. ((and (pred functionp) face) (funcall face path))
  4545. ((and (pred facep) face) face)
  4546. ((and (pred consp) face) face) ;anonymous
  4547. (_ 'org-link)))
  4548. (properties ;for link's visible part
  4549. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4550. 'highlight)
  4551. 'keymap (or (org-link-get-parameter type :keymap)
  4552. org-mouse-map)
  4553. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4554. ((and (pred stringp) echo) echo)
  4555. ((and (pred functionp) echo) echo)
  4556. (_ (concat "LINK: " link)))
  4557. 'htmlize-link (pcase (org-link-get-parameter type
  4558. :htmlize-link)
  4559. ((and (pred functionp) f) (funcall f))
  4560. (_ `(:uri ,link)))
  4561. 'font-lock-multiline t)))
  4562. (org-remove-flyspell-overlays-in start end)
  4563. (org-rear-nonsticky-at end)
  4564. (if (not (eq 'bracket style))
  4565. (progn
  4566. (add-face-text-property start end face-property)
  4567. (add-text-properties start end properties))
  4568. ;; Handle invisible parts in bracket links.
  4569. (remove-text-properties start end '(invisible nil))
  4570. (let ((hidden
  4571. (append `(invisible
  4572. ,(or (org-link-get-parameter type :display)
  4573. 'org-link))
  4574. properties)))
  4575. (add-text-properties start visible-start hidden)
  4576. (add-face-text-property start end face-property)
  4577. (add-text-properties visible-start visible-end properties)
  4578. (add-text-properties visible-end end hidden)
  4579. (org-rear-nonsticky-at visible-start)
  4580. (org-rear-nonsticky-at visible-end)))
  4581. (let ((f (org-link-get-parameter type :activate-func)))
  4582. (when (functionp f)
  4583. (funcall f start end path (eq style 'bracket))))
  4584. (throw :exit t))))) ;signal success
  4585. nil))
  4586. (defun org-activate-code (limit)
  4587. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4588. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4589. (remove-text-properties (match-beginning 0) (match-end 0)
  4590. '(display t invisible t intangible t))
  4591. t))
  4592. (defcustom org-src-fontify-natively t
  4593. "When non-nil, fontify code in code blocks.
  4594. See also the `org-block' face."
  4595. :type 'boolean
  4596. :version "26.1"
  4597. :package-version '(Org . "8.3")
  4598. :group 'org-appearance
  4599. :group 'org-babel)
  4600. (defcustom org-allow-promoting-top-level-subtree nil
  4601. "When non-nil, allow promoting a top level subtree.
  4602. The leading star of the top level headline will be replaced
  4603. by a #."
  4604. :type 'boolean
  4605. :version "24.1"
  4606. :group 'org-appearance)
  4607. (defun org-fontify-meta-lines-and-blocks (limit)
  4608. (condition-case nil
  4609. (org-fontify-meta-lines-and-blocks-1 limit)
  4610. (error (message "Org mode fontification error in %S at %d"
  4611. (current-buffer)
  4612. (line-number-at-pos)))))
  4613. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4614. "Fontify #+ lines and blocks."
  4615. (let ((case-fold-search t))
  4616. (when (re-search-forward
  4617. (rx bol (group (zero-or-more (any " \t")) "#"
  4618. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4619. (any " \t")
  4620. eol))
  4621. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4622. (zero-or-more (any " \t"))
  4623. (group (group (zero-or-more (not (any " \t\n"))))
  4624. (zero-or-more (any " \t"))
  4625. (group (zero-or-more any)))))
  4626. limit t)
  4627. (let ((beg (match-beginning 0))
  4628. (end-of-beginline (match-end 0))
  4629. ;; Including \n at end of #+begin line will include \n
  4630. ;; after the end of block content.
  4631. (block-start (match-end 0))
  4632. (block-end nil)
  4633. (lang (match-string 7)) ; The language, if it is a source block.
  4634. (bol-after-beginline (line-beginning-position 2))
  4635. (dc1 (downcase (match-string 2)))
  4636. (dc3 (downcase (match-string 3)))
  4637. (whole-blockline org-fontify-whole-block-delimiter-line)
  4638. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4639. (cond
  4640. ((and (match-end 4) (equal dc3 "+begin"))
  4641. ;; Truly a block
  4642. (setq block-type (downcase (match-string 5))
  4643. ;; Src, example, export, maybe more.
  4644. quoting (member block-type org-protecting-blocks))
  4645. (when (re-search-forward
  4646. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4647. (seq (zero-or-more (any " \t"))
  4648. "#+end"
  4649. ,(match-string 4)
  4650. word-end
  4651. (zero-or-more any)))))
  4652. ;; We look further than LIMIT on purpose.
  4653. nil t)
  4654. ;; We do have a matching #+end line.
  4655. (setq beg-of-endline (match-beginning 0)
  4656. end-of-endline (match-end 0)
  4657. nl-before-endline (1- (match-beginning 0)))
  4658. (setq block-end (match-beginning 0)) ; Include the final newline.
  4659. (when quoting
  4660. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4661. (remove-text-properties beg end-of-endline
  4662. '(display t invisible t intangible t)))
  4663. (add-text-properties
  4664. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4665. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4666. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4667. (cond
  4668. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4669. (save-match-data
  4670. (org-src-font-lock-fontify-block lang block-start block-end))
  4671. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4672. (quoting
  4673. (add-text-properties
  4674. bol-after-beginline beg-of-endline
  4675. (list 'face
  4676. (list :inherit
  4677. (let ((face-name
  4678. (intern (format "org-block-%s" lang))))
  4679. (append (and (facep face-name) (list face-name))
  4680. '(org-block)))))))
  4681. ((not org-fontify-quote-and-verse-blocks))
  4682. ((string= block-type "quote")
  4683. (add-face-text-property
  4684. bol-after-beginline beg-of-endline 'org-quote t))
  4685. ((string= block-type "verse")
  4686. (add-face-text-property
  4687. bol-after-beginline beg-of-endline 'org-verse t)))
  4688. ;; Fontify the #+begin and #+end lines of the blocks
  4689. (add-text-properties
  4690. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4691. '(face org-block-begin-line))
  4692. (unless (eq (char-after beg-of-endline) ?*)
  4693. (add-text-properties
  4694. beg-of-endline
  4695. (if whole-blockline
  4696. (let ((beg-of-next-line (1+ end-of-endline)))
  4697. (min (point-max) beg-of-next-line))
  4698. (min (point-max) end-of-endline))
  4699. '(face org-block-end-line)))
  4700. t))
  4701. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4702. (org-remove-flyspell-overlays-in
  4703. (match-beginning 0)
  4704. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4705. (add-text-properties
  4706. beg (match-end 3)
  4707. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4708. '(font-lock-fontified t invisible t)
  4709. '(font-lock-fontified t face org-document-info-keyword)))
  4710. (add-text-properties
  4711. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4712. (if (string-equal dc1 "+title:")
  4713. '(font-lock-fontified t face org-document-title)
  4714. '(font-lock-fontified t face org-document-info))))
  4715. ((string-prefix-p "+caption" dc1)
  4716. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4717. (remove-text-properties (match-beginning 0) (match-end 0)
  4718. '(display t invisible t intangible t))
  4719. ;; Handle short captions
  4720. (save-excursion
  4721. (beginning-of-line)
  4722. (looking-at (rx (group (zero-or-more (any " \t"))
  4723. "#+caption"
  4724. (optional "[" (zero-or-more any) "]")
  4725. ":")
  4726. (zero-or-more (any " \t")))))
  4727. (add-text-properties (line-beginning-position) (match-end 1)
  4728. '(font-lock-fontified t face org-meta-line))
  4729. (add-text-properties (match-end 0) (line-end-position)
  4730. '(font-lock-fontified t face org-block))
  4731. t)
  4732. ((member dc3 '(" " ""))
  4733. ;; Just a comment, the plus was not there
  4734. (org-remove-flyspell-overlays-in beg (match-end 0))
  4735. (add-text-properties
  4736. beg (match-end 0)
  4737. '(font-lock-fontified t face font-lock-comment-face)))
  4738. (t ;; Just any other in-buffer setting, but not indented
  4739. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4740. (remove-text-properties (match-beginning 0) (match-end 0)
  4741. '(display t invisible t intangible t))
  4742. (add-text-properties beg (match-end 0)
  4743. '(font-lock-fontified t face org-meta-line))
  4744. t))))))
  4745. (defun org-fontify-drawers (limit)
  4746. "Fontify drawers."
  4747. (when (re-search-forward org-drawer-regexp limit t)
  4748. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4749. '(font-lock-fontified t face org-drawer))
  4750. (org-remove-flyspell-overlays-in
  4751. (line-beginning-position) (line-beginning-position 2))
  4752. t))
  4753. (defun org-fontify-macros (limit)
  4754. "Fontify macros."
  4755. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4756. (let ((begin (match-beginning 0))
  4757. (opening-end (match-beginning 1)))
  4758. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4759. (match-string 1))
  4760. (let ((end (match-end 1))
  4761. (closing-start (match-beginning 1)))
  4762. (add-text-properties
  4763. begin end
  4764. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4765. (org-remove-flyspell-overlays-in begin end)
  4766. (when org-hide-macro-markers
  4767. (add-text-properties begin opening-end '(invisible t))
  4768. (add-text-properties closing-start end '(invisible t)))
  4769. t)))))
  4770. (defun org-fontify-extend-region (beg end _old-len)
  4771. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4772. (1+ end) end))
  4773. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4774. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4775. (extend
  4776. (lambda (r1 r2 dir)
  4777. (let ((re (replace-regexp-in-string
  4778. "\\(begin\\|end\\)" r1
  4779. (replace-regexp-in-string
  4780. "[][]" r2
  4781. (match-string-no-properties 0)))))
  4782. (re-search-forward (regexp-quote re) nil t dir)))))
  4783. (goto-char beg)
  4784. (back-to-indentation)
  4785. (save-match-data
  4786. (cond ((looking-at end-re)
  4787. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4788. ((looking-at begin-re)
  4789. (cons beg (or (funcall extend "end" "]" 1) end)))
  4790. (t (cons beg end))))))
  4791. (defun org-activate-footnote-links (limit)
  4792. "Add text properties for footnotes."
  4793. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4794. (when fn
  4795. (let* ((beg (nth 1 fn))
  4796. (end (nth 2 fn))
  4797. (label (car fn))
  4798. (referencep (/= (line-beginning-position) beg)))
  4799. (when (and referencep (nth 3 fn))
  4800. (save-excursion
  4801. (goto-char beg)
  4802. (search-forward (or label "fn:"))
  4803. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4804. (add-text-properties beg end
  4805. (list 'mouse-face 'highlight
  4806. 'keymap org-mouse-map
  4807. 'help-echo
  4808. (if referencep "Footnote reference"
  4809. "Footnote definition")
  4810. 'font-lock-fontified t
  4811. 'font-lock-multiline t
  4812. 'face 'org-footnote))))))
  4813. (defun org-activate-dates (limit)
  4814. "Add text properties for dates."
  4815. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4816. (not (equal (char-before (match-beginning 0)) 91)))
  4817. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4818. (add-text-properties (match-beginning 0) (match-end 0)
  4819. (list 'mouse-face 'highlight
  4820. 'keymap org-mouse-map))
  4821. (org-rear-nonsticky-at (match-end 0))
  4822. (when org-display-custom-times
  4823. ;; If it's a date range, activate custom time for second date.
  4824. (when (match-end 3)
  4825. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4826. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4827. t))
  4828. (defun org-activate-target-links (limit)
  4829. "Add text properties for target matches."
  4830. (when org-target-link-regexp
  4831. (let ((case-fold-search t))
  4832. ;; `org-target-link-regexp' matches one character before the
  4833. ;; actual target.
  4834. (unless (bolp) (forward-char -1))
  4835. (when (re-search-forward org-target-link-regexp limit t)
  4836. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4837. (add-text-properties (match-beginning 1) (match-end 1)
  4838. (list 'mouse-face 'highlight
  4839. 'keymap org-mouse-map
  4840. 'help-echo "Radio target link"
  4841. 'org-linked-text t))
  4842. (org-rear-nonsticky-at (match-end 1))
  4843. t))))
  4844. (defvar org-latex-and-related-regexp nil
  4845. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4846. (defun org-compute-latex-and-related-regexp ()
  4847. "Compute regular expression for LaTeX, entities and sub/superscript.
  4848. Result depends on variable `org-highlight-latex-and-related'."
  4849. (let ((re-sub
  4850. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4851. ((eq org-use-sub-superscripts '{})
  4852. (list org-match-substring-with-braces-regexp))
  4853. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4854. (re-latex
  4855. (when (or (memq 'latex org-highlight-latex-and-related)
  4856. (memq 'native org-highlight-latex-and-related))
  4857. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4858. (delq nil
  4859. (mapcar (lambda (x)
  4860. (and (member (car x) matchers) (nth 1 x)))
  4861. org-latex-regexps)))))
  4862. (re-entities
  4863. (when (memq 'entities org-highlight-latex-and-related)
  4864. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4865. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4866. (setq-local org-latex-and-related-regexp
  4867. (mapconcat #'identity
  4868. (append re-latex re-entities re-sub)
  4869. "\\|"))))
  4870. (defun org-do-latex-and-related (limit)
  4871. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4872. Stop at first highlighted object, if any. Return t if some
  4873. highlighting was done, nil otherwise."
  4874. (when (org-string-nw-p org-latex-and-related-regexp)
  4875. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4876. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4877. (catch 'found
  4878. (while (and (< (point) limit)
  4879. (re-search-forward org-latex-and-related-regexp nil t))
  4880. (cond
  4881. ((>= (match-beginning 0) limit)
  4882. (throw 'found nil))
  4883. ((cl-some (lambda (f)
  4884. (memq f '(org-code org-verbatim underline
  4885. org-special-keyword)))
  4886. (save-excursion
  4887. (goto-char (1+ (match-beginning 0)))
  4888. (face-at-point nil t))))
  4889. ;; Try to limit false positives. In this case, ignore
  4890. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4891. ;; contain an empty line.
  4892. ((save-excursion
  4893. (goto-char (match-beginning 0))
  4894. (and (looking-at-p latex-prefix-re)
  4895. (save-match-data
  4896. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4897. (t
  4898. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4899. '(?_ ?^))
  4900. 1
  4901. 0))
  4902. (start (+ offset (match-beginning 0)))
  4903. (end (match-end 0)))
  4904. (if (memq 'native org-highlight-latex-and-related)
  4905. (org-src-font-lock-fontify-block "latex" start end)
  4906. (font-lock-prepend-text-property start end
  4907. 'face 'org-latex-and-related))
  4908. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4909. '(font-lock-multiline t))
  4910. (throw 'found t)))))
  4911. nil))))
  4912. (defun org-restart-font-lock ()
  4913. "Restart `font-lock-mode', to force refontification."
  4914. (when font-lock-mode
  4915. (font-lock-mode -1)
  4916. (font-lock-mode 1)))
  4917. (defun org-activate-tags (limit)
  4918. (when (re-search-forward org-tag-line-re limit t)
  4919. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4920. (add-text-properties (match-beginning 1) (match-end 1)
  4921. (list 'mouse-face 'highlight
  4922. 'keymap org-mouse-map))
  4923. (org-rear-nonsticky-at (match-end 1))
  4924. t))
  4925. (defun org-outline-level ()
  4926. "Compute the outline level of the heading at point.
  4927. If this is called at a normal headline, the level is the number
  4928. of stars. Use `org-reduced-level' to remove the effect of
  4929. `org-odd-levels'. Unlike to `org-current-level', this function
  4930. takes into consideration inlinetasks."
  4931. (org-with-wide-buffer
  4932. (end-of-line)
  4933. (if (re-search-backward org-outline-regexp-bol nil t)
  4934. (1- (- (match-end 0) (match-beginning 0)))
  4935. 0)))
  4936. (defvar org-font-lock-keywords nil)
  4937. (defsubst org-re-property (property &optional literal allow-null value)
  4938. "Return a regexp matching a PROPERTY line.
  4939. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4940. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4941. non-nil, match properties even without a value.
  4942. Match group 3 is set to the value when it exists. If there is no
  4943. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4944. With optional argument VALUE, match only property lines with
  4945. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4946. unless LITERAL is non-nil."
  4947. (concat
  4948. "^\\(?4:[ \t]*\\)"
  4949. (format "\\(?1::\\(?2:%s\\):\\)"
  4950. (if literal property (regexp-quote property)))
  4951. (cond (value
  4952. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4953. (if literal value (regexp-quote value))))
  4954. (allow-null
  4955. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4956. (t
  4957. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4958. (defconst org-property-re
  4959. (org-re-property "\\S-+" 'literal t)
  4960. "Regular expression matching a property line.
  4961. There are four matching groups:
  4962. 1: :PROPKEY: including the leading and trailing colon,
  4963. 2: PROPKEY without the leading and trailing colon,
  4964. 3: PROPVAL without leading or trailing spaces,
  4965. 4: the indentation of the current line,
  4966. 5: trailing whitespace.")
  4967. (defvar org-font-lock-hook nil
  4968. "Functions to be called for special font lock stuff.")
  4969. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4970. (defvar org-font-lock-set-keywords-hook nil
  4971. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4972. This is called after `org-font-lock-extra-keywords' is defined, but before
  4973. it is installed to be used by font lock. This can be useful if something
  4974. needs to be inserted at a specific position in the font-lock sequence.")
  4975. (defun org-font-lock-hook (limit)
  4976. "Run `org-font-lock-hook' within LIMIT."
  4977. (run-hook-with-args 'org-font-lock-hook limit))
  4978. (defun org-set-font-lock-defaults ()
  4979. "Set font lock defaults for the current buffer."
  4980. (let ((org-font-lock-extra-keywords
  4981. (list
  4982. ;; Call the hook
  4983. '(org-font-lock-hook)
  4984. ;; Headlines
  4985. `(,(if org-fontify-whole-heading-line
  4986. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4987. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4988. (1 (org-get-level-face 1))
  4989. (2 (org-get-level-face 2))
  4990. (3 (org-get-level-face 3)))
  4991. ;; Table lines
  4992. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4993. (1 'org-table t))
  4994. ;; Table internals
  4995. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4996. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4997. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4998. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4999. ;; Properties
  5000. (list org-property-re
  5001. '(1 'org-special-keyword t)
  5002. '(3 'org-property-value t))
  5003. ;; Drawers
  5004. '(org-fontify-drawers)
  5005. ;; Link related fontification.
  5006. '(org-activate-links)
  5007. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  5008. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  5009. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  5010. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5011. ;; Targets.
  5012. (list org-radio-target-regexp '(0 'org-target t))
  5013. (list org-target-regexp '(0 'org-target t))
  5014. ;; Diary sexps.
  5015. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5016. ;; Macro
  5017. '(org-fontify-macros)
  5018. ;; TODO keyword
  5019. (list (format org-heading-keyword-regexp-format
  5020. org-todo-regexp)
  5021. '(2 (org-get-todo-face 2) prepend))
  5022. ;; TODO
  5023. (when org-fontify-todo-headline
  5024. (list (format org-heading-keyword-regexp-format
  5025. (concat
  5026. "\\(?:"
  5027. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5028. "\\)"))
  5029. '(2 'org-headline-todo prepend)))
  5030. ;; DONE
  5031. (when org-fontify-done-headline
  5032. (list (format org-heading-keyword-regexp-format
  5033. (concat
  5034. "\\(?:"
  5035. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5036. "\\)"))
  5037. '(2 'org-headline-done prepend)))
  5038. ;; Priorities
  5039. '(org-font-lock-add-priority-faces)
  5040. ;; Tags
  5041. '(org-font-lock-add-tag-faces)
  5042. ;; Tags groups
  5043. (when (and org-group-tags org-tag-groups-alist)
  5044. (list (concat org-outline-regexp-bol ".+\\(:"
  5045. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5046. ":\\).*$")
  5047. '(1 'org-tag-group prepend)))
  5048. ;; Special keywords
  5049. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5050. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5051. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5052. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5053. ;; Emphasis
  5054. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5055. ;; Checkboxes
  5056. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5057. 1 'org-checkbox prepend)
  5058. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5059. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5060. (0 (org-get-checkbox-statistics-face) prepend)))
  5061. ;; Description list items
  5062. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5063. 1 'org-list-dt prepend)
  5064. ;; Inline export snippets
  5065. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5066. (1 'font-lock-comment-face t)
  5067. (2 'org-tag t)
  5068. (3 'font-lock-comment-face t))
  5069. ;; ARCHIVEd headings
  5070. (list (concat
  5071. org-outline-regexp-bol
  5072. "\\(.*:" org-archive-tag ":.*\\)")
  5073. '(1 'org-archived prepend))
  5074. ;; Specials
  5075. '(org-do-latex-and-related)
  5076. '(org-fontify-entities)
  5077. '(org-raise-scripts)
  5078. ;; Code
  5079. '(org-activate-code (1 'org-code t))
  5080. ;; COMMENT
  5081. (list (format
  5082. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5083. org-todo-regexp
  5084. org-comment-string)
  5085. '(9 'org-special-keyword t))
  5086. ;; Blocks and meta lines
  5087. '(org-fontify-meta-lines-and-blocks)
  5088. ;; Citations
  5089. '(org-cite-activate))))
  5090. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5091. (run-hooks 'org-font-lock-set-keywords-hook)
  5092. ;; Now set the full font-lock-keywords
  5093. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5094. (setq-local font-lock-defaults
  5095. '(org-font-lock-keywords t nil nil backward-paragraph))
  5096. (setq-local font-lock-extend-after-change-region-function
  5097. #'org-fontify-extend-region)
  5098. (kill-local-variable 'font-lock-keywords)
  5099. nil))
  5100. (defun org-toggle-pretty-entities ()
  5101. "Toggle the composition display of entities as UTF8 characters."
  5102. (interactive)
  5103. (setq-local org-pretty-entities (not org-pretty-entities))
  5104. (org-restart-font-lock)
  5105. (if org-pretty-entities
  5106. (message "Entities are now displayed as UTF8 characters")
  5107. (save-restriction
  5108. (widen)
  5109. (decompose-region (point-min) (point-max))
  5110. (message "Entities are now displayed as plain text"))))
  5111. (defvar-local org-custom-properties-overlays nil
  5112. "List of overlays used for custom properties.")
  5113. (defun org-toggle-custom-properties-visibility ()
  5114. "Display or hide properties in `org-custom-properties'."
  5115. (interactive)
  5116. (if org-custom-properties-overlays
  5117. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5118. (setq org-custom-properties-overlays nil))
  5119. (when org-custom-properties
  5120. (org-with-wide-buffer
  5121. (goto-char (point-min))
  5122. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5123. (while (re-search-forward regexp nil t)
  5124. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5125. (when (and end (< (point) end))
  5126. ;; Hide first custom property in current drawer.
  5127. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5128. (overlay-put o 'invisible t)
  5129. (overlay-put o 'org-custom-property t)
  5130. (push o org-custom-properties-overlays))
  5131. ;; Hide additional custom properties in the same drawer.
  5132. (while (re-search-forward regexp end t)
  5133. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5134. (overlay-put o 'invisible t)
  5135. (overlay-put o 'org-custom-property t)
  5136. (push o org-custom-properties-overlays)))))
  5137. ;; Each entry is limited to a single property drawer.
  5138. (outline-next-heading)))))))
  5139. (defun org-fontify-entities (limit)
  5140. "Find an entity to fontify."
  5141. (let (ee)
  5142. (when org-pretty-entities
  5143. (catch 'match
  5144. ;; "\_ "-family is left out on purpose. Only the first one,
  5145. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5146. ;; confusing when adding a second white space character.
  5147. (while (re-search-forward
  5148. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5149. limit t)
  5150. (when (and (not (org-at-comment-p))
  5151. (setq ee (org-entity-get (match-string 1)))
  5152. (= (length (nth 6 ee)) 1))
  5153. (let* ((end (if (equal (match-string 2) "{}")
  5154. (match-end 2)
  5155. (match-end 1))))
  5156. (add-text-properties
  5157. (match-beginning 0) end
  5158. (list 'font-lock-fontified t))
  5159. (compose-region (match-beginning 0) end
  5160. (nth 6 ee) nil)
  5161. (backward-char 1)
  5162. (throw 'match t))))
  5163. nil))))
  5164. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5165. "Fontify string S like in Org mode."
  5166. (with-temp-buffer
  5167. (insert s)
  5168. (let ((org-odd-levels-only odd-levels))
  5169. (org-mode)
  5170. (org-font-lock-ensure)
  5171. (buffer-string))))
  5172. (defun org-get-level-face (n)
  5173. "Get the right face for match N in font-lock matching of headlines."
  5174. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5175. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5176. (org-f (if org-cycle-level-faces
  5177. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5178. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5179. (cond
  5180. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5181. ((eq n 2) org-f)
  5182. (t (unless org-level-color-stars-only org-f)))))
  5183. (defun org-face-from-face-or-color (context inherit face-or-color)
  5184. "Create a face list that inherits INHERIT, but sets the foreground color.
  5185. When FACE-OR-COLOR is not a string, just return it."
  5186. (if (stringp face-or-color)
  5187. (list :inherit inherit
  5188. (cdr (assoc context org-faces-easy-properties))
  5189. face-or-color)
  5190. face-or-color))
  5191. (defun org-get-todo-face (kwd)
  5192. "Get the right face for a TODO keyword KWD.
  5193. If KWD is a number, get the corresponding match group."
  5194. (when (numberp kwd) (setq kwd (match-string kwd)))
  5195. (or (org-face-from-face-or-color
  5196. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5197. (and (member kwd org-done-keywords) 'org-done)
  5198. 'org-todo))
  5199. (defun org-get-priority-face (priority)
  5200. "Get the right face for PRIORITY.
  5201. PRIORITY is a character."
  5202. (or (org-face-from-face-or-color
  5203. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5204. 'org-priority))
  5205. (defun org-get-tag-face (tag)
  5206. "Get the right face for TAG.
  5207. If TAG is a number, get the corresponding match group."
  5208. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5209. (or (org-face-from-face-or-color
  5210. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5211. 'org-tag)))
  5212. (defvar org-priority-regexp) ; defined later in the file
  5213. (defun org-font-lock-add-priority-faces (limit)
  5214. "Add the special priority faces."
  5215. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5216. (let ((beg (match-beginning 1))
  5217. (end (1+ (match-end 2))))
  5218. (add-face-text-property
  5219. beg end
  5220. (org-get-priority-face (string-to-char (match-string 2))))
  5221. (add-text-properties
  5222. beg end
  5223. (list 'font-lock-fontified t)))))
  5224. (defun org-font-lock-add-tag-faces (limit)
  5225. "Add the special tag faces."
  5226. (when (and org-tag-faces org-tags-special-faces-re)
  5227. (while (re-search-forward org-tags-special-faces-re limit t)
  5228. (add-face-text-property
  5229. (match-beginning 1)
  5230. (match-end 1)
  5231. (org-get-tag-face 1))
  5232. (add-text-properties (match-beginning 1) (match-end 1)
  5233. (list 'font-lock-fontified t))
  5234. (backward-char 1))))
  5235. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5236. "Remove fontification and activation overlays from links."
  5237. (font-lock-default-unfontify-region beg end)
  5238. (let* ((buffer-undo-list t)
  5239. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5240. (inhibit-modification-hooks t)
  5241. deactivate-mark buffer-file-name buffer-file-truename)
  5242. (decompose-region beg end)
  5243. (remove-text-properties beg end
  5244. '(mouse-face t keymap t org-linked-text t
  5245. invisible t intangible t
  5246. org-emphasis t))
  5247. (org-remove-font-lock-display-properties beg end)))
  5248. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5249. ((raise 0.3) (height 0.7))
  5250. ((raise -0.5))
  5251. ((raise 0.5)))
  5252. "Display properties for showing superscripts and subscripts.")
  5253. (defun org-remove-font-lock-display-properties (beg end)
  5254. "Remove specific display properties that have been added by font lock.
  5255. The will remove the raise properties that are used to show superscripts
  5256. and subscripts."
  5257. (let (next prop)
  5258. (while (< beg end)
  5259. (setq next (next-single-property-change beg 'display nil end)
  5260. prop (get-text-property beg 'display))
  5261. (when (member prop org-script-display)
  5262. (put-text-property beg next 'display nil))
  5263. (setq beg next))))
  5264. (defun org-raise-scripts (limit)
  5265. "Add raise properties to sub/superscripts."
  5266. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5267. (re-search-forward
  5268. (if (eq org-use-sub-superscripts t)
  5269. org-match-substring-regexp
  5270. org-match-substring-with-braces-regexp)
  5271. limit t))
  5272. (let* ((pos (point)) table-p comment-p
  5273. (mpos (match-beginning 3))
  5274. (emph-p (get-text-property mpos 'org-emphasis))
  5275. (link-p (get-text-property mpos 'mouse-face))
  5276. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5277. (goto-char (point-at-bol))
  5278. (setq table-p (looking-at-p org-table-dataline-regexp)
  5279. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5280. (goto-char pos)
  5281. ;; Handle a_b^c
  5282. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5283. (unless (or comment-p emph-p link-p keyw-p)
  5284. (put-text-property (match-beginning 3) (match-end 0)
  5285. 'display
  5286. (if (equal (char-after (match-beginning 2)) ?^)
  5287. (nth (if table-p 3 1) org-script-display)
  5288. (nth (if table-p 2 0) org-script-display)))
  5289. (add-text-properties (match-beginning 2) (match-end 2)
  5290. (list 'invisible t))
  5291. (when (and (eq (char-after (match-beginning 3)) ?{)
  5292. (eq (char-before (match-end 3)) ?}))
  5293. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5294. (list 'invisible t))
  5295. (add-text-properties (1- (match-end 3)) (match-end 3)
  5296. (list 'invisible t))))
  5297. t)))
  5298. (defun org-remove-empty-overlays-at (pos)
  5299. "Remove outline overlays that do not contain non-white stuff."
  5300. (dolist (o (overlays-at pos))
  5301. (and (eq 'outline (overlay-get o 'invisible))
  5302. (not (string-match-p
  5303. "\\S-" (buffer-substring (overlay-start o)
  5304. (overlay-end o))))
  5305. (delete-overlay o))))
  5306. (defun org-show-empty-lines-in-parent ()
  5307. "Move to the parent and re-show empty lines before visible headlines."
  5308. (save-excursion
  5309. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5310. (org-cycle-show-empty-lines context))))
  5311. (defun org-files-list ()
  5312. "Return `org-agenda-files' list, plus all open Org files.
  5313. This is useful for operations that need to scan all of a user's
  5314. open and agenda-wise Org files."
  5315. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5316. (dolist (buf (buffer-list))
  5317. (with-current-buffer buf
  5318. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5319. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5320. :test #'equal))))
  5321. files))
  5322. (defsubst org-entry-beginning-position ()
  5323. "Return the beginning position of the current entry."
  5324. (save-excursion (org-back-to-heading t) (point)))
  5325. (defsubst org-entry-end-position ()
  5326. "Return the end position of the current entry."
  5327. (save-excursion (outline-next-heading) (point)))
  5328. (defun org-subtree-end-visible-p ()
  5329. "Is the end of the current subtree visible?"
  5330. (pos-visible-in-window-p
  5331. (save-excursion (org-end-of-subtree t) (point))))
  5332. (defun org-first-headline-recenter ()
  5333. "Move cursor to the first headline and recenter the headline."
  5334. (let ((window (get-buffer-window)))
  5335. (when window
  5336. (goto-char (point-min))
  5337. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5338. (set-window-start window (line-beginning-position))))))
  5339. ;;; Visibility (headlines, blocks, drawers)
  5340. ;;;; Headlines visibility
  5341. (defun org-show-entry ()
  5342. "Show the body directly following its heading.
  5343. Show the heading too, if it is currently invisible."
  5344. (interactive)
  5345. (save-excursion
  5346. (org-back-to-heading-or-point-min t)
  5347. (org-flag-region
  5348. (line-end-position 0)
  5349. (save-excursion
  5350. (if (re-search-forward
  5351. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5352. (match-beginning 1)
  5353. (point-max)))
  5354. nil
  5355. 'outline)
  5356. (org-cycle-hide-drawers 'children)))
  5357. (defun org-hide-entry ()
  5358. "Hide the body directly following its heading."
  5359. (interactive)
  5360. (save-excursion
  5361. (org-back-to-heading-or-point-min t)
  5362. (when (org-at-heading-p) (forward-line))
  5363. (org-flag-region
  5364. (line-end-position 0)
  5365. (save-excursion
  5366. (if (re-search-forward
  5367. (concat "[\r\n]" org-outline-regexp) nil t)
  5368. (line-end-position 0)
  5369. (point-max)))
  5370. t
  5371. 'outline)))
  5372. (defun org-show-children (&optional level)
  5373. "Show all direct subheadings of this heading.
  5374. Prefix arg LEVEL is how many levels below the current level
  5375. should be shown. Default is enough to cause the following
  5376. heading to appear."
  5377. (interactive "p")
  5378. (unless (org-before-first-heading-p)
  5379. (save-excursion
  5380. (org-with-limited-levels (org-back-to-heading t))
  5381. (let* ((current-level (funcall outline-level))
  5382. (max-level (org-get-valid-level
  5383. current-level
  5384. (if level (prefix-numeric-value level) 1)))
  5385. (end (save-excursion (org-end-of-subtree t t)))
  5386. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5387. (past-first-child nil)
  5388. ;; Make sure to skip inlinetasks.
  5389. (re (format regexp-fmt
  5390. current-level
  5391. (cond
  5392. ((not (featurep 'org-inlinetask)) "")
  5393. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5394. 3))
  5395. (t (1- org-inlinetask-min-level))))))
  5396. ;; Display parent heading.
  5397. (org-flag-heading nil)
  5398. (forward-line)
  5399. ;; Display children. First child may be deeper than expected
  5400. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5401. ;; MAX-LEVEL accordingly.
  5402. (while (re-search-forward re end t)
  5403. (unless past-first-child
  5404. (setq re (format regexp-fmt
  5405. current-level
  5406. (max (funcall outline-level) max-level)))
  5407. (setq past-first-child t))
  5408. (org-flag-heading nil))))))
  5409. (defun org-show-subtree ()
  5410. "Show everything after this heading at deeper levels."
  5411. (interactive)
  5412. (org-flag-region
  5413. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5414. ;;;; Blocks and drawers visibility
  5415. (defun org--hide-wrapper-toggle (element category force no-error)
  5416. "Toggle visibility for ELEMENT.
  5417. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5418. either `block' or `drawer'. When FORCE is `off', show the block
  5419. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5420. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5421. Return a non-nil value when toggling is successful."
  5422. (let ((type (org-element-type element)))
  5423. (cond
  5424. ((memq type
  5425. (pcase category
  5426. (`drawer '(drawer property-drawer))
  5427. (`block '(center-block
  5428. comment-block dynamic-block example-block export-block
  5429. quote-block special-block src-block verse-block))
  5430. (_ (error "Unknown category: %S" category))))
  5431. (let* ((post (org-element-property :post-affiliated element))
  5432. (start (save-excursion
  5433. (goto-char post)
  5434. (line-end-position)))
  5435. (end (save-excursion
  5436. (goto-char (org-element-property :end element))
  5437. (skip-chars-backward " \t\n")
  5438. (line-end-position))))
  5439. ;; Do nothing when not before or at the block opening line or
  5440. ;; at the block closing line.
  5441. (unless (let ((eol (line-end-position)))
  5442. (and (> eol start) (/= eol end)))
  5443. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5444. (flag
  5445. (cond ((eq force 'off) nil)
  5446. (force t)
  5447. ((eq spec (get-char-property start 'invisible)) nil)
  5448. (t t))))
  5449. (org-flag-region start end flag spec))
  5450. ;; When the block is hidden away, make sure point is left in
  5451. ;; a visible part of the buffer.
  5452. (when (invisible-p (max (1- (point)) (point-min)))
  5453. (goto-char post))
  5454. ;; Signal success.
  5455. t)))
  5456. (no-error nil)
  5457. (t
  5458. (user-error (if (eq category 'drawer)
  5459. "Not at a drawer"
  5460. "Not at a block"))))))
  5461. (defun org-hide-block-toggle (&optional force no-error element)
  5462. "Toggle the visibility of the current block.
  5463. When optional argument FORCE is `off', make block visible. If it
  5464. is non-nil, hide it unconditionally. Throw an error when not at
  5465. a block, unless NO-ERROR is non-nil. When optional argument
  5466. ELEMENT is provided, consider it instead of the current block.
  5467. Return a non-nil value when toggling is successful."
  5468. (interactive)
  5469. (org--hide-wrapper-toggle
  5470. (or element (org-element-at-point)) 'block force no-error))
  5471. (defun org-hide-drawer-toggle (&optional force no-error element)
  5472. "Toggle the visibility of the current drawer.
  5473. When optional argument FORCE is `off', make drawer visible. If
  5474. it is non-nil, hide it unconditionally. Throw an error when not
  5475. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5476. ELEMENT is provided, consider it instead of the current drawer.
  5477. Return a non-nil value when toggling is successful."
  5478. (interactive)
  5479. (org--hide-wrapper-toggle
  5480. (or element (org-element-at-point)) 'drawer force no-error))
  5481. (defun org-hide-block-all ()
  5482. "Fold all blocks in the current buffer."
  5483. (interactive)
  5484. (org-show-all '(blocks))
  5485. (org-block-map 'org-hide-block-toggle))
  5486. (defun org-hide-drawer-all ()
  5487. "Fold all drawers in the current buffer."
  5488. (let ((begin (point-min))
  5489. (end (point-max)))
  5490. (org--hide-drawers begin end)))
  5491. (defun org-cycle-hide-drawers (state)
  5492. "Re-hide all drawers after a visibility state change.
  5493. STATE should be one of the symbols listed in the docstring of
  5494. `org-cycle-hook'."
  5495. (when (derived-mode-p 'org-mode)
  5496. (cond ((not (memq state '(overview folded contents)))
  5497. (let* ((global? (eq state 'all))
  5498. (beg (if global? (point-min) (line-beginning-position)))
  5499. (end (cond (global? (point-max))
  5500. ((eq state 'children) (org-entry-end-position))
  5501. (t (save-excursion (org-end-of-subtree t t))))))
  5502. (org--hide-drawers beg end)))
  5503. ((memq state '(overview contents))
  5504. ;; Hide drawers before first heading.
  5505. (let ((beg (point-min))
  5506. (end (save-excursion
  5507. (goto-char (point-min))
  5508. (if (org-before-first-heading-p)
  5509. (org-entry-end-position)
  5510. (point-min)))))
  5511. (when (< beg end)
  5512. (org--hide-drawers beg end)))))))
  5513. (defun org--hide-drawers (begin end)
  5514. "Hide all drawers between BEGIN and END."
  5515. (save-excursion
  5516. (goto-char begin)
  5517. (while (re-search-forward org-drawer-regexp end t)
  5518. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5519. 'invisible))
  5520. (o (cdr-safe pair)))
  5521. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5522. (pcase (get-char-property-and-overlay (point) 'invisible)
  5523. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5524. (_
  5525. (let* ((drawer (org-element-at-point))
  5526. (type (org-element-type drawer)))
  5527. (when (memq type '(drawer property-drawer))
  5528. (org-hide-drawer-toggle t nil drawer)
  5529. ;; Make sure to skip drawer entirely or we might flag it
  5530. ;; another time when matching its ending line with
  5531. ;; `org-drawer-regexp'.
  5532. (goto-char (org-element-property :end drawer)))))))))))
  5533. ;;;; Visibility cycling
  5534. (defvar-local org-cycle-global-status nil)
  5535. (put 'org-cycle-global-status 'org-state t)
  5536. (defvar-local org-cycle-subtree-status nil)
  5537. (put 'org-cycle-subtree-status 'org-state t)
  5538. (defun org-show-all (&optional types)
  5539. "Show all contents in the visible part of the buffer.
  5540. By default, the function expands headings, blocks and drawers.
  5541. When optional argument TYPE is a list of symbols among `blocks',
  5542. `drawers' and `headings', to only expand one specific type."
  5543. (interactive)
  5544. (let ((types (or types '(blocks drawers headings))))
  5545. (when (memq 'blocks types)
  5546. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5547. (cond
  5548. ;; Fast path. Since headings and drawers share the same
  5549. ;; invisible spec, clear everything in one go.
  5550. ((and (memq 'headings types)
  5551. (memq 'drawers types))
  5552. (org-flag-region (point-min) (point-max) nil 'outline))
  5553. ((memq 'headings types)
  5554. (org-flag-region (point-min) (point-max) nil 'outline)
  5555. (org-cycle-hide-drawers 'all))
  5556. ((memq 'drawers types)
  5557. (save-excursion
  5558. (goto-char (point-min))
  5559. (while (re-search-forward org-drawer-regexp nil t)
  5560. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5561. 'invisible))
  5562. (o (cdr-safe pair)))
  5563. (if (overlayp o) (goto-char (overlay-end o))
  5564. (pcase (get-char-property-and-overlay (point) 'invisible)
  5565. (`(outline . ,o)
  5566. (goto-char (overlay-end o))
  5567. (delete-overlay o))
  5568. (_ nil))))))))))
  5569. ;;;###autoload
  5570. (defun org-cycle (&optional arg)
  5571. "TAB-action and visibility cycling for Org mode.
  5572. This is the command invoked in Org mode by the `TAB' key. Its main
  5573. purpose is outline visibility cycling, but it also invokes other actions
  5574. in special contexts.
  5575. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5576. the entire
  5577. buffer through 3 states (global cycling)
  5578. 1. OVERVIEW: Show only top-level headlines.
  5579. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5580. 3. SHOW ALL: Show everything.
  5581. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5582. switch to the startup visibility,
  5583. determined by the variable `org-startup-folded', and by any VISIBILITY
  5584. properties in the buffer.
  5585. With a `\\[universal-argument] \\[universal-argument] \
  5586. \\[universal-argument]' prefix argument, show the entire buffer, including
  5587. any drawers.
  5588. When inside a table, re-align the table and move to the next field.
  5589. When point is at the beginning of a headline, rotate the subtree started
  5590. by this line through 3 different states (local cycling)
  5591. 1. FOLDED: Only the main headline is shown.
  5592. 2. CHILDREN: The main headline and the direct children are shown.
  5593. From this state, you can move to one of the children
  5594. and zoom in further.
  5595. 3. SUBTREE: Show the entire subtree, including body text.
  5596. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5597. When point is at the beginning of an empty headline and the variable
  5598. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5599. of the headline by demoting and promoting it to likely levels. This
  5600. speeds up creation document structure by pressing `TAB' once or several
  5601. times right after creating a new headline.
  5602. When there is a numeric prefix, go up to a heading with level ARG, do
  5603. a `show-subtree' and return to the previous cursor position. If ARG
  5604. is negative, go up that many levels.
  5605. When point is not at the beginning of a headline, execute the global
  5606. binding for `TAB', which is re-indenting the line. See the option
  5607. `org-cycle-emulate-tab' for details.
  5608. As a special case, if point is at the very beginning of the buffer, if
  5609. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5610. is non-nil, this function acts as if called with prefix argument \
  5611. \(`\\[universal-argument] TAB',
  5612. same as `S-TAB') also when called without prefix argument."
  5613. (interactive "P")
  5614. (org-load-modules-maybe)
  5615. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5616. (and org-cycle-level-after-item/entry-creation
  5617. (or (org-cycle-level)
  5618. (org-cycle-item-indentation))))
  5619. (let* ((limit-level
  5620. (or org-cycle-max-level
  5621. (and (boundp 'org-inlinetask-min-level)
  5622. org-inlinetask-min-level
  5623. (1- org-inlinetask-min-level))))
  5624. (nstars
  5625. (and limit-level
  5626. (if org-odd-levels-only
  5627. (1- (* 2 limit-level))
  5628. limit-level)))
  5629. (org-outline-regexp
  5630. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5631. (cond
  5632. ((equal arg '(16))
  5633. (setq last-command 'dummy)
  5634. (org-set-startup-visibility)
  5635. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5636. ((equal arg '(64))
  5637. (org-show-all)
  5638. (org-unlogged-message "Entire buffer visible, including drawers"))
  5639. ((equal arg '(4)) (org-cycle-internal-global))
  5640. ;; Show-subtree, ARG levels up from here.
  5641. ((integerp arg)
  5642. (save-excursion
  5643. (org-back-to-heading)
  5644. (outline-up-heading (if (< arg 0) (- arg)
  5645. (- (funcall outline-level) arg)))
  5646. (org-show-subtree)))
  5647. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5648. ((and org-cycle-global-at-bob
  5649. (bobp)
  5650. (not (looking-at org-outline-regexp)))
  5651. (let ((org-cycle-hook
  5652. (remq 'org-optimize-window-after-visibility-change
  5653. org-cycle-hook)))
  5654. (org-cycle-internal-global)))
  5655. ;; Try CDLaTeX TAB completion.
  5656. ((org-try-cdlatex-tab))
  5657. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5658. ((and (featurep 'org-inlinetask)
  5659. (org-inlinetask-at-task-p)
  5660. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5661. (org-inlinetask-toggle-visibility))
  5662. (t
  5663. (let ((pos (point))
  5664. (element (org-element-at-point)))
  5665. (cond
  5666. ;; Try toggling visibility for block at point.
  5667. ((org-hide-block-toggle nil t element))
  5668. ;; Try toggling visibility for drawer at point.
  5669. ((org-hide-drawer-toggle nil t element))
  5670. ;; Table: enter it or move to the next field.
  5671. ((and (org-match-line "[ \t]*[|+]")
  5672. (org-element-lineage element '(table) t))
  5673. (if (and (eq 'table (org-element-type element))
  5674. (eq 'table.el (org-element-property :type element)))
  5675. (message (substitute-command-keys "\\<org-mode-map>\
  5676. Use `\\[org-edit-special]' to edit table.el tables"))
  5677. (org-table-justify-field-maybe)
  5678. (call-interactively #'org-table-next-field)))
  5679. ((run-hook-with-args-until-success
  5680. 'org-tab-after-check-for-table-hook))
  5681. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5682. ((and (or (and org-cycle-include-plain-lists
  5683. (let ((item (org-element-lineage element
  5684. '(item plain-list)
  5685. t)))
  5686. (and item
  5687. (= (line-beginning-position)
  5688. (org-element-property :post-affiliated
  5689. item)))))
  5690. (org-match-line org-outline-regexp))
  5691. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5692. (org-cycle-internal-local))
  5693. ;; From there: TAB emulation and template completion.
  5694. (buffer-read-only (org-back-to-heading))
  5695. ((run-hook-with-args-until-success
  5696. 'org-tab-after-check-for-cycling-hook))
  5697. ((run-hook-with-args-until-success
  5698. 'org-tab-before-tab-emulation-hook))
  5699. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5700. (or (not (bolp))
  5701. (not (looking-at org-outline-regexp))))
  5702. (call-interactively (global-key-binding (kbd "TAB"))))
  5703. ((or (eq org-cycle-emulate-tab t)
  5704. (and (memq org-cycle-emulate-tab '(white whitestart))
  5705. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5706. (or (and (eq org-cycle-emulate-tab 'white)
  5707. (= (match-end 0) (point-at-eol)))
  5708. (and (eq org-cycle-emulate-tab 'whitestart)
  5709. (>= (match-end 0) pos)))))
  5710. (call-interactively (global-key-binding (kbd "TAB"))))
  5711. (t
  5712. (save-excursion
  5713. (org-back-to-heading)
  5714. (org-cycle))))))))))
  5715. (defun org-cycle-internal-global ()
  5716. "Do the global cycling action."
  5717. ;; Hack to avoid display of messages for .org attachments in Gnus
  5718. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5719. (cond
  5720. ((and (eq last-command this-command)
  5721. (eq org-cycle-global-status 'overview))
  5722. ;; We just created the overview - now do table of contents
  5723. ;; This can be slow in very large buffers, so indicate action
  5724. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5725. (unless ga (org-unlogged-message "CONTENTS..."))
  5726. (org-content)
  5727. (unless ga (org-unlogged-message "CONTENTS...done"))
  5728. (setq org-cycle-global-status 'contents)
  5729. (run-hook-with-args 'org-cycle-hook 'contents))
  5730. ((and (eq last-command this-command)
  5731. (eq org-cycle-global-status 'contents))
  5732. ;; We just showed the table of contents - now show everything
  5733. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5734. (org-show-all '(headings blocks))
  5735. (unless ga (org-unlogged-message "SHOW ALL"))
  5736. (setq org-cycle-global-status 'all)
  5737. (run-hook-with-args 'org-cycle-hook 'all))
  5738. (t
  5739. ;; Default action: go to overview
  5740. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5741. (org-overview)
  5742. (unless ga (org-unlogged-message "OVERVIEW"))
  5743. (setq org-cycle-global-status 'overview)
  5744. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5745. (defvar org-called-with-limited-levels nil
  5746. "Non-nil when `org-with-limited-levels' is currently active.")
  5747. (defun org-cycle-internal-local ()
  5748. "Do the local cycling action."
  5749. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5750. ;; First, determine end of headline (EOH), end of subtree or item
  5751. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5752. (save-excursion
  5753. (if (org-at-item-p)
  5754. (progn
  5755. (beginning-of-line)
  5756. (setq struct (org-list-struct))
  5757. (setq eoh (point-at-eol))
  5758. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5759. (setq has-children (org-list-has-child-p (point) struct)))
  5760. (org-back-to-heading)
  5761. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5762. (setq eos (save-excursion
  5763. (org-end-of-subtree t t)
  5764. (unless (eobp) (forward-char -1))
  5765. (point)))
  5766. (setq has-children
  5767. (or
  5768. (save-excursion
  5769. (let ((level (funcall outline-level)))
  5770. (outline-next-heading)
  5771. (and (org-at-heading-p t)
  5772. (> (funcall outline-level) level))))
  5773. (and (eq org-cycle-include-plain-lists 'integrate)
  5774. (save-excursion
  5775. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5776. ;; Determine end invisible part of buffer (EOL)
  5777. (beginning-of-line 2)
  5778. (while (and (not (eobp)) ;this is like `next-line'
  5779. (get-char-property (1- (point)) 'invisible))
  5780. (goto-char (next-single-char-property-change (point) 'invisible))
  5781. (and (eolp) (beginning-of-line 2)))
  5782. (setq eol (point)))
  5783. ;; Find out what to do next and set `this-command'
  5784. (cond
  5785. ((= eos eoh)
  5786. ;; Nothing is hidden behind this heading
  5787. (unless (org-before-first-heading-p)
  5788. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5789. (org-unlogged-message "EMPTY ENTRY")
  5790. (setq org-cycle-subtree-status nil)
  5791. (save-excursion
  5792. (goto-char eos)
  5793. (outline-next-heading)
  5794. (when (org-invisible-p) (org-flag-heading nil))))
  5795. ((and (or (>= eol eos)
  5796. (not (string-match "\\S-" (buffer-substring eol eos))))
  5797. (or has-children
  5798. (not (setq children-skipped
  5799. org-cycle-skip-children-state-if-no-children))))
  5800. ;; Entire subtree is hidden in one line: children view
  5801. (unless (org-before-first-heading-p)
  5802. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5803. (if (org-at-item-p)
  5804. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5805. (org-show-entry)
  5806. (org-with-limited-levels (org-show-children))
  5807. (org-show-set-visibility 'tree)
  5808. ;; Fold every list in subtree to top-level items.
  5809. (when (eq org-cycle-include-plain-lists 'integrate)
  5810. (save-excursion
  5811. (org-back-to-heading)
  5812. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5813. (beginning-of-line 1)
  5814. (let* ((struct (org-list-struct))
  5815. (prevs (org-list-prevs-alist struct))
  5816. (end (org-list-get-bottom-point struct)))
  5817. (dolist (e (org-list-get-all-items (point) struct prevs))
  5818. (org-list-set-item-visibility e struct 'folded))
  5819. (goto-char (if (< end eos) end eos)))))))
  5820. (org-unlogged-message "CHILDREN")
  5821. (save-excursion
  5822. (goto-char eos)
  5823. (outline-next-heading)
  5824. (when (org-invisible-p) (org-flag-heading nil)))
  5825. (setq org-cycle-subtree-status 'children)
  5826. (unless (org-before-first-heading-p)
  5827. (run-hook-with-args 'org-cycle-hook 'children)))
  5828. ((or children-skipped
  5829. (and (eq last-command this-command)
  5830. (eq org-cycle-subtree-status 'children)))
  5831. ;; We just showed the children, or no children are there,
  5832. ;; now show everything.
  5833. (unless (org-before-first-heading-p)
  5834. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5835. (org-flag-region eoh eos nil 'outline)
  5836. (org-unlogged-message
  5837. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5838. (setq org-cycle-subtree-status 'subtree)
  5839. (unless (org-before-first-heading-p)
  5840. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5841. (t
  5842. ;; Default action: hide the subtree.
  5843. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5844. (org-flag-region eoh eos t 'outline)
  5845. (org-unlogged-message "FOLDED")
  5846. (setq org-cycle-subtree-status 'folded)
  5847. (unless (org-before-first-heading-p)
  5848. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5849. ;;;###autoload
  5850. (defun org-global-cycle (&optional arg)
  5851. "Cycle the global visibility. For details see `org-cycle'.
  5852. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5853. With a numeric prefix, show all headlines up to that level."
  5854. (interactive "P")
  5855. (cond
  5856. ((integerp arg)
  5857. (org-content arg)
  5858. (setq org-cycle-global-status 'contents))
  5859. ((equal arg '(4))
  5860. (org-set-startup-visibility)
  5861. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5862. (t
  5863. (org-cycle '(4)))))
  5864. (defun org-set-startup-visibility ()
  5865. "Set the visibility required by startup options and properties."
  5866. (cond
  5867. ((eq org-startup-folded t)
  5868. (org-overview))
  5869. ((eq org-startup-folded 'content)
  5870. (org-content))
  5871. ((eq org-startup-folded 'show2levels)
  5872. (org-content 2))
  5873. ((eq org-startup-folded 'show3levels)
  5874. (org-content 3))
  5875. ((eq org-startup-folded 'show4levels)
  5876. (org-content 4))
  5877. ((eq org-startup-folded 'show5levels)
  5878. (org-content 5))
  5879. ((or (eq org-startup-folded 'showeverything)
  5880. (eq org-startup-folded nil))
  5881. (org-show-all)))
  5882. (unless (eq org-startup-folded 'showeverything)
  5883. (when org-hide-block-startup (org-hide-block-all))
  5884. (org-set-visibility-according-to-property)
  5885. (org-cycle-hide-archived-subtrees 'all)
  5886. (org-cycle-hide-drawers 'all)
  5887. (org-cycle-show-empty-lines t)))
  5888. (defun org-set-visibility-according-to-property ()
  5889. "Switch subtree visibility according to VISIBILITY property."
  5890. (interactive)
  5891. (let ((regexp (org-re-property "VISIBILITY")))
  5892. (org-with-point-at 1
  5893. (while (re-search-forward regexp nil t)
  5894. (let ((state (match-string 3)))
  5895. (if (not (org-at-property-p)) (outline-next-heading)
  5896. (save-excursion
  5897. (org-back-to-heading t)
  5898. (org-flag-subtree t)
  5899. (org-reveal)
  5900. (pcase state
  5901. ("folded"
  5902. (org-flag-subtree t))
  5903. ("children"
  5904. (org-show-hidden-entry)
  5905. (org-show-children))
  5906. ("content"
  5907. (save-excursion
  5908. (save-restriction
  5909. (org-narrow-to-subtree)
  5910. (org-content))))
  5911. ((or "all" "showall")
  5912. (outline-show-subtree))
  5913. (_ nil)))
  5914. (org-end-of-subtree)))))))
  5915. (defun org-overview ()
  5916. "Switch to overview mode, showing only top-level headlines."
  5917. (interactive)
  5918. (org-show-all '(headings drawers))
  5919. (save-excursion
  5920. (goto-char (point-min))
  5921. (when (re-search-forward org-outline-regexp-bol nil t)
  5922. (let* ((last (line-end-position))
  5923. (level (- (match-end 0) (match-beginning 0) 1))
  5924. (regexp (format "^\\*\\{1,%d\\} " level)))
  5925. (while (re-search-forward regexp nil :move)
  5926. (org-flag-region last (line-end-position 0) t 'outline)
  5927. (setq last (line-end-position))
  5928. (setq level (- (match-end 0) (match-beginning 0) 1))
  5929. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5930. (org-flag-region last (point) t 'outline)))))
  5931. (defun org-content (&optional arg)
  5932. "Show all headlines in the buffer, like a table of contents.
  5933. With numerical argument N, show content up to level N."
  5934. (interactive "p")
  5935. (org-show-all '(headings drawers))
  5936. (save-excursion
  5937. (goto-char (point-max))
  5938. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5939. (format "^\\*\\{1,%d\\} " arg)
  5940. "^\\*+ "))
  5941. (last (point)))
  5942. (while (re-search-backward regexp nil t)
  5943. (org-flag-region (line-end-position) last t 'outline)
  5944. (setq last (line-end-position 0))))))
  5945. (defvar org-scroll-position-to-restore nil
  5946. "Temporarily store scroll position to restore.")
  5947. (defun org-optimize-window-after-visibility-change (state)
  5948. "Adjust the window after a change in outline visibility.
  5949. This function is the default value of the hook `org-cycle-hook'."
  5950. (when (get-buffer-window (current-buffer))
  5951. (let ((repeat (eq last-command this-command)))
  5952. (unless repeat
  5953. (setq org-scroll-position-to-restore nil))
  5954. (cond
  5955. ((eq state 'content) nil)
  5956. ((eq state 'all) nil)
  5957. ((and org-scroll-position-to-restore repeat
  5958. (eq state 'folded))
  5959. (set-window-start nil org-scroll-position-to-restore))
  5960. ((eq state 'folded) nil)
  5961. ((eq state 'children)
  5962. (setq org-scroll-position-to-restore (window-start))
  5963. (or (org-subtree-end-visible-p) (recenter 1)))
  5964. ((eq state 'subtree)
  5965. (unless repeat
  5966. (setq org-scroll-position-to-restore (window-start)))
  5967. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5968. (defun org-clean-visibility-after-subtree-move ()
  5969. "Fix visibility issues after moving a subtree."
  5970. ;; First, find a reasonable region to look at:
  5971. ;; Start two siblings above, end three below
  5972. (let* ((beg (save-excursion
  5973. (and (org-get-previous-sibling)
  5974. (org-get-previous-sibling))
  5975. (point)))
  5976. (end (save-excursion
  5977. (and (org-get-next-sibling)
  5978. (org-get-next-sibling)
  5979. (org-get-next-sibling))
  5980. (if (org-at-heading-p)
  5981. (point-at-eol)
  5982. (point))))
  5983. (level (looking-at "\\*+"))
  5984. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5985. (save-excursion
  5986. (save-restriction
  5987. (narrow-to-region beg end)
  5988. (when re
  5989. ;; Properly fold already folded siblings
  5990. (goto-char (point-min))
  5991. (while (re-search-forward re nil t)
  5992. (when (and (not (org-invisible-p))
  5993. (org-invisible-p (line-end-position)))
  5994. (outline-hide-entry))))
  5995. (org-cycle-hide-drawers 'all)
  5996. (org-cycle-show-empty-lines 'overview)))))
  5997. (defun org-cycle-show-empty-lines (state)
  5998. "Show empty lines above all visible headlines.
  5999. The region to be covered depends on STATE when called through
  6000. `org-cycle-hook'. Lisp program can use t for STATE to get the
  6001. entire buffer covered. Note that an empty line is only shown if there
  6002. are at least `org-cycle-separator-lines' empty lines before the headline."
  6003. (when (/= org-cycle-separator-lines 0)
  6004. (save-excursion
  6005. (let* ((n (abs org-cycle-separator-lines))
  6006. (re (cond
  6007. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  6008. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  6009. (t (let ((ns (number-to-string (- n 2))))
  6010. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6011. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6012. beg end)
  6013. (cond
  6014. ((memq state '(overview contents t))
  6015. (setq beg (point-min) end (point-max)))
  6016. ((memq state '(children folded))
  6017. (setq beg (point)
  6018. end (progn (org-end-of-subtree t t)
  6019. (line-beginning-position 2)))))
  6020. (when beg
  6021. (goto-char beg)
  6022. (while (re-search-forward re end t)
  6023. (unless (get-char-property (match-end 1) 'invisible)
  6024. (let ((e (match-end 1))
  6025. (b (if (>= org-cycle-separator-lines 0)
  6026. (match-beginning 1)
  6027. (save-excursion
  6028. (goto-char (match-beginning 0))
  6029. (skip-chars-backward " \t\n")
  6030. (line-end-position)))))
  6031. (org-flag-region b e nil 'outline))))))))
  6032. ;; Never hide empty lines at the end of the file.
  6033. (save-excursion
  6034. (goto-char (point-max))
  6035. (outline-previous-heading)
  6036. (outline-end-of-heading)
  6037. (when (and (looking-at "[ \t\n]+")
  6038. (= (match-end 0) (point-max)))
  6039. (org-flag-region (point) (match-end 0) nil 'outline))))
  6040. ;;;; Reveal point location
  6041. (defun org-show-context (&optional key)
  6042. "Make sure point and context are visible.
  6043. Optional argument KEY, when non-nil, is a symbol. See
  6044. `org-show-context-detail' for allowed values and how much is to
  6045. be shown."
  6046. (org-show-set-visibility
  6047. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6048. ((cdr (assq key org-show-context-detail)))
  6049. (t (cdr (assq 'default org-show-context-detail))))))
  6050. (defun org-show-set-visibility (detail)
  6051. "Set visibility around point according to DETAIL.
  6052. DETAIL is either nil, `minimal', `local', `ancestors',
  6053. `ancestors-full', `lineage', `tree', `canonical' or t. See
  6054. `org-show-context-detail' for more information."
  6055. ;; Show current heading and possibly its entry, following headline
  6056. ;; or all children.
  6057. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6058. (org-flag-heading nil)
  6059. (org-show-entry)
  6060. ;; If point is hidden within a drawer or a block, make sure to
  6061. ;; expose it.
  6062. (dolist (o (overlays-at (point)))
  6063. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6064. (delete-overlay o)))
  6065. (unless (org-before-first-heading-p)
  6066. (org-with-limited-levels
  6067. (cl-case detail
  6068. ((tree canonical t) (org-show-children))
  6069. ((nil minimal ancestors ancestors-full))
  6070. (t (save-excursion
  6071. (outline-next-heading)
  6072. (org-flag-heading nil)))))))
  6073. ;; Show whole subtree.
  6074. (when (eq detail 'ancestors-full) (org-show-subtree))
  6075. ;; Show all siblings.
  6076. (when (eq detail 'lineage) (org-show-siblings))
  6077. ;; Show ancestors, possibly with their children.
  6078. (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
  6079. (save-excursion
  6080. (while (org-up-heading-safe)
  6081. (org-flag-heading nil)
  6082. (when (memq detail '(canonical t)) (org-show-entry))
  6083. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6084. (defvar org-reveal-start-hook nil
  6085. "Hook run before revealing a location.")
  6086. (defun org-reveal (&optional siblings)
  6087. "Show current entry, hierarchy above it, and the following headline.
  6088. This can be used to show a consistent set of context around
  6089. locations exposed with `org-show-context'.
  6090. With optional argument SIBLINGS, on each level of the hierarchy all
  6091. siblings are shown. This repairs the tree structure to what it would
  6092. look like when opened with hierarchical calls to `org-cycle'.
  6093. With a \\[universal-argument] \\[universal-argument] prefix, \
  6094. go to the parent and show the entire tree."
  6095. (interactive "P")
  6096. (run-hooks 'org-reveal-start-hook)
  6097. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6098. ((equal siblings '(16))
  6099. (save-excursion
  6100. (when (org-up-heading-safe)
  6101. (org-show-subtree)
  6102. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6103. (t (org-show-set-visibility 'lineage))))
  6104. ;;; Indirect buffer display of subtrees
  6105. (defvar org-indirect-dedicated-frame nil
  6106. "This is the frame being used for indirect tree display.")
  6107. (defvar org-last-indirect-buffer nil)
  6108. (defun org-tree-to-indirect-buffer (&optional arg)
  6109. "Create indirect buffer and narrow it to current subtree.
  6110. With a numerical prefix ARG, go up to this level and then take that tree.
  6111. If ARG is negative, go up that many levels.
  6112. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6113. indirect buffer previously made with this command, to avoid proliferation of
  6114. indirect buffers. However, when you call the command with a \
  6115. `\\[universal-argument]' prefix, or
  6116. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6117. so that you can work with several indirect buffers at the same time. If
  6118. `org-indirect-buffer-display' is `dedicated-frame', the \
  6119. `\\[universal-argument]' prefix also
  6120. requests that a new frame be made for the new buffer, so that the dedicated
  6121. frame is not changed."
  6122. (interactive "P")
  6123. (let ((cbuf (current-buffer))
  6124. (cwin (selected-window))
  6125. (pos (point))
  6126. beg end level heading ibuf)
  6127. (save-excursion
  6128. (org-back-to-heading t)
  6129. (when (numberp arg)
  6130. (setq level (org-outline-level))
  6131. (when (< arg 0) (setq arg (+ level arg)))
  6132. (while (> (setq level (org-outline-level)) arg)
  6133. (org-up-heading-safe)))
  6134. (setq beg (point)
  6135. heading (org-get-heading 'no-tags))
  6136. (org-end-of-subtree t t)
  6137. (when (org-at-heading-p) (backward-char 1))
  6138. (setq end (point)))
  6139. (when (and (buffer-live-p org-last-indirect-buffer)
  6140. (not (eq org-indirect-buffer-display 'new-frame))
  6141. (not arg))
  6142. (kill-buffer org-last-indirect-buffer))
  6143. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6144. org-last-indirect-buffer ibuf)
  6145. (cond
  6146. ((or (eq org-indirect-buffer-display 'new-frame)
  6147. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6148. (select-frame (make-frame))
  6149. (delete-other-windows)
  6150. (pop-to-buffer-same-window ibuf)
  6151. (org-set-frame-title heading))
  6152. ((eq org-indirect-buffer-display 'dedicated-frame)
  6153. (raise-frame
  6154. (select-frame (or (and org-indirect-dedicated-frame
  6155. (frame-live-p org-indirect-dedicated-frame)
  6156. org-indirect-dedicated-frame)
  6157. (setq org-indirect-dedicated-frame (make-frame)))))
  6158. (delete-other-windows)
  6159. (pop-to-buffer-same-window ibuf)
  6160. (org-set-frame-title (concat "Indirect: " heading)))
  6161. ((eq org-indirect-buffer-display 'current-window)
  6162. (pop-to-buffer-same-window ibuf))
  6163. ((eq org-indirect-buffer-display 'other-window)
  6164. (pop-to-buffer ibuf))
  6165. (t (error "Invalid value")))
  6166. (narrow-to-region beg end)
  6167. (org-show-all '(headings drawers blocks))
  6168. (goto-char pos)
  6169. (run-hook-with-args 'org-cycle-hook 'all)
  6170. (and (window-live-p cwin) (select-window cwin))))
  6171. (defun org-get-indirect-buffer (&optional buffer heading)
  6172. (setq buffer (or buffer (current-buffer)))
  6173. (let ((n 1) (base (buffer-name buffer)) bname)
  6174. (while (buffer-live-p
  6175. (get-buffer
  6176. (setq bname
  6177. (concat base "-"
  6178. (if heading (concat heading "-" (number-to-string n))
  6179. (number-to-string n))))))
  6180. (setq n (1+ n)))
  6181. (condition-case nil
  6182. (make-indirect-buffer buffer bname 'clone)
  6183. (error (make-indirect-buffer buffer bname)))))
  6184. (defun org-set-frame-title (title)
  6185. "Set the title of the current frame to the string TITLE."
  6186. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6187. ;;;; Structure editing
  6188. ;;; Inserting headlines
  6189. (defun org--blank-before-heading-p (&optional parent)
  6190. "Non-nil when an empty line should precede a new heading here.
  6191. When optional argument PARENT is non-nil, consider parent
  6192. headline instead of current one."
  6193. (pcase (assq 'heading org-blank-before-new-entry)
  6194. (`(heading . auto)
  6195. (save-excursion
  6196. (org-with-limited-levels
  6197. (unless (and (org-before-first-heading-p)
  6198. (not (outline-next-heading)))
  6199. (org-back-to-heading t)
  6200. (when parent (org-up-heading-safe))
  6201. (cond ((not (bobp))
  6202. (org-previous-line-empty-p))
  6203. ((outline-next-heading)
  6204. (org-previous-line-empty-p))
  6205. ;; Ignore trailing spaces on last buffer line.
  6206. ((progn (skip-chars-backward " \t") (bolp))
  6207. (org-previous-line-empty-p))
  6208. (t nil))))))
  6209. (`(heading . ,value) value)
  6210. (_ nil)))
  6211. (defun org-insert-heading (&optional arg invisible-ok top)
  6212. "Insert a new heading or an item with the same depth at point.
  6213. If point is at the beginning of a heading, insert a new heading
  6214. or a new headline above the current one. When at the beginning
  6215. of a regular line of text, turn it into a heading.
  6216. If point is in the middle of a line, split it and create a new
  6217. headline with the text in the current line after point (see
  6218. `org-M-RET-may-split-line' on how to modify this behavior). As
  6219. a special case, on a headline, splitting can only happen on the
  6220. title itself. E.g., this excludes breaking stars or tags.
  6221. With a `\\[universal-argument]' prefix, set \
  6222. `org-insert-heading-respect-content' to
  6223. a non-nil value for the duration of the command. This forces the
  6224. insertion of a heading after the current subtree, independently
  6225. on the location of point.
  6226. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6227. insert the heading at the end of the tree
  6228. above the current heading. For example, if point is within a
  6229. 2nd-level heading, then it will insert a 2nd-level heading at
  6230. the end of the 1st-level parent subtree.
  6231. When INVISIBLE-OK is set, stop at invisible headlines when going
  6232. back. This is important for non-interactive uses of the
  6233. command.
  6234. When optional argument TOP is non-nil, insert a level 1 heading,
  6235. unconditionally."
  6236. (interactive "P")
  6237. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6238. (level (org-current-level))
  6239. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6240. (cond
  6241. ((or org-insert-heading-respect-content
  6242. (member arg '((4) (16)))
  6243. (and (not invisible-ok)
  6244. (invisible-p (max (1- (point)) (point-min)))))
  6245. ;; Position point at the location of insertion. Make sure we
  6246. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6247. (org-with-limited-levels
  6248. (if (not level) (outline-next-heading) ;before first headline
  6249. (org-back-to-heading invisible-ok)
  6250. (when (equal arg '(16)) (org-up-heading-safe))
  6251. (org-end-of-subtree)))
  6252. (unless (bolp) (insert "\n"))
  6253. (when (and blank? (save-excursion
  6254. (backward-char)
  6255. (org-before-first-heading-p)))
  6256. (insert "\n")
  6257. (backward-char))
  6258. (when (and (not level) (not (eobp)) (not (bobp)))
  6259. (when (org-at-heading-p) (insert "\n"))
  6260. (backward-char))
  6261. (unless (and blank? (org-previous-line-empty-p))
  6262. (org-N-empty-lines-before-current (if blank? 1 0)))
  6263. (insert stars " ")
  6264. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6265. ;; is visible.
  6266. (unless invisible-ok
  6267. (pcase (get-char-property-and-overlay (point) 'invisible)
  6268. (`(outline . ,o)
  6269. (move-overlay o (overlay-start o) (line-end-position 0)))
  6270. (_ nil))))
  6271. ;; At a headline...
  6272. ((org-at-heading-p)
  6273. (cond ((bolp)
  6274. (when blank? (save-excursion (insert "\n")))
  6275. (save-excursion (insert stars " \n"))
  6276. (unless (and blank? (org-previous-line-empty-p))
  6277. (org-N-empty-lines-before-current (if blank? 1 0)))
  6278. (end-of-line))
  6279. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6280. (org-match-line org-complex-heading-regexp)
  6281. (org-pos-in-match-range (point) 4))
  6282. ;; Grab the text that should moved to the new headline.
  6283. ;; Preserve tags.
  6284. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6285. (if (looking-at "[ \t]*$") (replace-match "")
  6286. (org-align-tags))
  6287. (end-of-line)
  6288. (when blank? (insert "\n"))
  6289. (insert "\n" stars " ")
  6290. (when (org-string-nw-p split) (insert split))))
  6291. (t
  6292. (end-of-line)
  6293. (when blank? (insert "\n"))
  6294. (insert "\n" stars " "))))
  6295. ;; On regular text, turn line into a headline or split, if
  6296. ;; appropriate.
  6297. ((bolp)
  6298. (insert stars " ")
  6299. (unless (and blank? (org-previous-line-empty-p))
  6300. (org-N-empty-lines-before-current (if blank? 1 0))))
  6301. (t
  6302. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6303. (end-of-line))
  6304. (insert "\n" stars " ")
  6305. (unless (and blank? (org-previous-line-empty-p))
  6306. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6307. (run-hooks 'org-insert-heading-hook))
  6308. (defun org-N-empty-lines-before-current (n)
  6309. "Make the number of empty lines before current exactly N.
  6310. So this will delete or add empty lines."
  6311. (let ((column (current-column)))
  6312. (beginning-of-line)
  6313. (unless (bobp)
  6314. (let ((start (save-excursion
  6315. (skip-chars-backward " \r\t\n")
  6316. (line-end-position))))
  6317. (delete-region start (line-end-position 0))))
  6318. (insert (make-string n ?\n))
  6319. (move-to-column column)))
  6320. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6321. "Return the heading of the current entry, without the stars.
  6322. When NO-TAGS is non-nil, don't include tags.
  6323. When NO-TODO is non-nil, don't include TODO keywords.
  6324. When NO-PRIORITY is non-nil, don't include priority cookie.
  6325. When NO-COMMENT is non-nil, don't include COMMENT string.
  6326. Return nil before first heading."
  6327. (unless (org-before-first-heading-p)
  6328. (save-excursion
  6329. (org-back-to-heading t)
  6330. (let ((case-fold-search nil))
  6331. (looking-at org-complex-heading-regexp)
  6332. (let ((todo (and (not no-todo) (match-string 2)))
  6333. (priority (and (not no-priority) (match-string 3)))
  6334. (headline (pcase (match-string 4)
  6335. (`nil "")
  6336. ((and (guard no-comment) h)
  6337. (replace-regexp-in-string
  6338. (eval-when-compile
  6339. (format "\\`%s[ \t]+" org-comment-string))
  6340. "" h))
  6341. (h h)))
  6342. (tags (and (not no-tags) (match-string 5))))
  6343. (mapconcat #'identity
  6344. (delq nil (list todo priority headline tags))
  6345. " "))))))
  6346. (defun org-heading-components ()
  6347. "Return the components of the current heading.
  6348. This is a list with the following elements:
  6349. - the level as an integer
  6350. - the reduced level, different if `org-odd-levels-only' is set.
  6351. - the TODO keyword, or nil
  6352. - the priority character, like ?A, or nil if no priority is given
  6353. - the headline text itself, or the tags string if no headline text
  6354. - the tags string, or nil."
  6355. (save-excursion
  6356. (org-back-to-heading t)
  6357. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6358. (list (length (match-string 1))
  6359. (org-reduced-level (length (match-string 1)))
  6360. (match-string-no-properties 2)
  6361. (and (match-end 3) (aref (match-string 3) 2))
  6362. (match-string-no-properties 4)
  6363. (match-string-no-properties 5)))))
  6364. (defun org-get-entry ()
  6365. "Get the entry text, after heading, entire subtree."
  6366. (save-excursion
  6367. (org-back-to-heading t)
  6368. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6369. (defun org-edit-headline (&optional heading)
  6370. "Edit the current headline.
  6371. Set it to HEADING when provided."
  6372. (interactive)
  6373. (org-with-wide-buffer
  6374. (org-back-to-heading t)
  6375. (let ((case-fold-search nil))
  6376. (when (looking-at org-complex-heading-regexp)
  6377. (let* ((old (match-string-no-properties 4))
  6378. (new (save-match-data
  6379. (org-trim (or heading (read-string "Edit: " old))))))
  6380. (unless (equal old new)
  6381. (if old (replace-match new t t nil 4)
  6382. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6383. (insert " " new))
  6384. (org-align-tags)
  6385. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6386. (defun org-insert-heading-after-current ()
  6387. "Insert a new heading with same level as current, after current subtree."
  6388. (interactive)
  6389. (org-back-to-heading)
  6390. (org-insert-heading)
  6391. (org-move-subtree-down)
  6392. (end-of-line 1))
  6393. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6394. "Insert heading with `org-insert-heading-respect-content' set to t."
  6395. (interactive)
  6396. (org-insert-heading '(4) invisible-ok))
  6397. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6398. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6399. (interactive)
  6400. (org-insert-todo-heading force-state '(4)))
  6401. (defun org-insert-todo-heading (arg &optional force-heading)
  6402. "Insert a new heading with the same level and TODO state as current heading.
  6403. If the heading has no TODO state, or if the state is DONE, use
  6404. the first state (TODO by default). Also with one prefix arg,
  6405. force first state. With two prefix args, force inserting at the
  6406. end of the parent subtree.
  6407. When called at a plain list item, insert a new item with an
  6408. unchecked check box."
  6409. (interactive "P")
  6410. (when (or force-heading (not (org-insert-item 'checkbox)))
  6411. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6412. force-heading))
  6413. (save-excursion
  6414. (org-forward-heading-same-level -1)
  6415. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6416. (let* ((new-mark-x
  6417. (if (or (equal arg '(4))
  6418. (not (match-beginning 2))
  6419. (member (match-string 2) org-done-keywords))
  6420. (car org-todo-keywords-1)
  6421. (match-string 2)))
  6422. (new-mark
  6423. (or
  6424. (run-hook-with-args-until-success
  6425. 'org-todo-get-default-hook new-mark-x nil)
  6426. new-mark-x)))
  6427. (beginning-of-line 1)
  6428. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6429. (if org-treat-insert-todo-heading-as-state-change
  6430. (org-todo new-mark)
  6431. (insert new-mark " "))))
  6432. (when org-provide-todo-statistics
  6433. (org-update-parent-todo-statistics))))
  6434. (defun org-insert-subheading (arg)
  6435. "Insert a new subheading and demote it.
  6436. Works for outline headings and for plain lists alike."
  6437. (interactive "P")
  6438. (org-insert-heading arg)
  6439. (cond
  6440. ((org-at-heading-p) (org-do-demote))
  6441. ((org-at-item-p) (org-indent-item))))
  6442. (defun org-insert-todo-subheading (arg)
  6443. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6444. Works for outline headings and for plain lists alike."
  6445. (interactive "P")
  6446. (org-insert-todo-heading arg)
  6447. (cond
  6448. ((org-at-heading-p) (org-do-demote))
  6449. ((org-at-item-p) (org-indent-item))))
  6450. ;;; Promotion and Demotion
  6451. (defvar org-after-demote-entry-hook nil
  6452. "Hook run after an entry has been demoted.
  6453. The cursor will be at the beginning of the entry.
  6454. When a subtree is being demoted, the hook will be called for each node.")
  6455. (defvar org-after-promote-entry-hook nil
  6456. "Hook run after an entry has been promoted.
  6457. The cursor will be at the beginning of the entry.
  6458. When a subtree is being promoted, the hook will be called for each node.")
  6459. (defun org-promote-subtree ()
  6460. "Promote the entire subtree.
  6461. See also `org-promote'."
  6462. (interactive)
  6463. (save-excursion
  6464. (org-back-to-heading t)
  6465. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  6466. (org-with-limited-levels (org-map-tree 'org-promote))))
  6467. (org-fix-position-after-promote))
  6468. (defun org-demote-subtree ()
  6469. "Demote the entire subtree.
  6470. See `org-demote' and `org-promote'."
  6471. (interactive)
  6472. (save-excursion
  6473. (org-back-to-heading t)
  6474. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  6475. (org-with-limited-levels (org-map-tree 'org-demote))))
  6476. (org-fix-position-after-promote))
  6477. (defun org-do-promote ()
  6478. "Promote the current heading higher up the tree.
  6479. If the region is active in `transient-mark-mode', promote all
  6480. headings in the region."
  6481. (interactive)
  6482. (save-excursion
  6483. (if (org-region-active-p)
  6484. (org-map-region 'org-promote (region-beginning) (region-end))
  6485. (org-promote)))
  6486. (org-fix-position-after-promote))
  6487. (defun org-do-demote ()
  6488. "Demote the current heading lower down the tree.
  6489. If the region is active in `transient-mark-mode', demote all
  6490. headings in the region."
  6491. (interactive)
  6492. (save-excursion
  6493. (if (org-region-active-p)
  6494. (org-map-region 'org-demote (region-beginning) (region-end))
  6495. (org-demote)))
  6496. (org-fix-position-after-promote))
  6497. (defun org-fix-position-after-promote ()
  6498. "Fix cursor position and indentation after demoting/promoting."
  6499. (let ((pos (point)))
  6500. (when (save-excursion
  6501. (beginning-of-line)
  6502. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6503. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6504. (cond ((eobp) (insert " "))
  6505. ((eolp) (insert " "))
  6506. ((equal (char-after) ?\s) (forward-char 1))))))
  6507. (defun org-current-level ()
  6508. "Return the level of the current entry, or nil if before the first headline.
  6509. The level is the number of stars at the beginning of the
  6510. headline. Use `org-reduced-level' to remove the effect of
  6511. `org-odd-levels'. Unlike to `org-outline-level', this function
  6512. ignores inlinetasks."
  6513. (let ((level (org-with-limited-levels (org-outline-level))))
  6514. (and (> level 0) level)))
  6515. (defun org-get-previous-line-level ()
  6516. "Return the outline depth of the last headline before the current line.
  6517. Returns 0 for the first headline in the buffer, and nil if before the
  6518. first headline."
  6519. (and (org-current-level)
  6520. (or (and (/= (line-beginning-position) (point-min))
  6521. (save-excursion (beginning-of-line 0) (org-current-level)))
  6522. 0)))
  6523. (defun org-reduced-level (l)
  6524. "Compute the effective level of a heading.
  6525. This takes into account the setting of `org-odd-levels-only'."
  6526. (cond
  6527. ((zerop l) 0)
  6528. (org-odd-levels-only (1+ (floor (/ l 2))))
  6529. (t l)))
  6530. (defun org-level-increment ()
  6531. "Return the number of stars that will be added or removed at a
  6532. time to headlines when structure editing, based on the value of
  6533. `org-odd-levels-only'."
  6534. (if org-odd-levels-only 2 1))
  6535. (defun org-get-valid-level (level &optional change)
  6536. "Rectify a level change under the influence of `org-odd-levels-only'.
  6537. LEVEL is a current level, CHANGE is by how much the level should
  6538. be modified. Even if CHANGE is nil, LEVEL may be returned
  6539. modified because even level numbers will become the next higher
  6540. odd number. Returns values greater than 0."
  6541. (if org-odd-levels-only
  6542. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6543. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6544. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6545. (max 1 (+ level (or change 0)))))
  6546. (defun org-promote ()
  6547. "Promote the current heading higher up the tree."
  6548. (org-with-wide-buffer
  6549. (org-back-to-heading t)
  6550. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6551. after-change-functions))
  6552. (level (save-match-data (funcall outline-level)))
  6553. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6554. (diff (abs (- level (length up-head) -1))))
  6555. (cond
  6556. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6557. (replace-match "# " nil t))
  6558. ((= level 1)
  6559. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6560. (t (replace-match up-head nil t)))
  6561. (unless (= level 1)
  6562. (when org-auto-align-tags (org-align-tags))
  6563. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6564. (run-hooks 'org-after-promote-entry-hook))))
  6565. (defun org-demote ()
  6566. "Demote the current heading lower down the tree."
  6567. (org-with-wide-buffer
  6568. (org-back-to-heading t)
  6569. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6570. after-change-functions))
  6571. (level (save-match-data (funcall outline-level)))
  6572. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6573. (diff (abs (- level (length down-head) -1))))
  6574. (replace-match down-head nil t)
  6575. (when org-auto-align-tags (org-align-tags))
  6576. (when org-adapt-indentation (org-fixup-indentation diff))
  6577. (run-hooks 'org-after-demote-entry-hook))))
  6578. (defun org-cycle-level ()
  6579. "Cycle the level of an empty headline through possible states.
  6580. This goes first to child, then to parent, level, then up the hierarchy.
  6581. After top level, it switches back to sibling level."
  6582. (interactive)
  6583. (let ((org-adapt-indentation nil))
  6584. (when (org-point-at-end-of-empty-headline)
  6585. (setq this-command 'org-cycle-level) ; Only needed for caching
  6586. (let ((cur-level (org-current-level))
  6587. (prev-level (org-get-previous-line-level)))
  6588. (cond
  6589. ;; If first headline in file, promote to top-level.
  6590. ((= prev-level 0)
  6591. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6592. do (org-do-promote)))
  6593. ;; If same level as prev, demote one.
  6594. ((= prev-level cur-level)
  6595. (org-do-demote))
  6596. ;; If parent is top-level, promote to top level if not already.
  6597. ((= prev-level 1)
  6598. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6599. do (org-do-promote)))
  6600. ;; If top-level, return to prev-level.
  6601. ((= cur-level 1)
  6602. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6603. do (org-do-demote)))
  6604. ;; If less than prev-level, promote one.
  6605. ((< cur-level prev-level)
  6606. (org-do-promote))
  6607. ;; If deeper than prev-level, promote until higher than
  6608. ;; prev-level.
  6609. ((> cur-level prev-level)
  6610. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6611. do (org-do-promote))))
  6612. t))))
  6613. (defun org-map-tree (fun)
  6614. "Call FUN for every heading underneath the current one."
  6615. (org-back-to-heading t)
  6616. (let ((level (funcall outline-level)))
  6617. (save-excursion
  6618. (funcall fun)
  6619. (while (and (progn
  6620. (outline-next-heading)
  6621. (> (funcall outline-level) level))
  6622. (not (eobp)))
  6623. (funcall fun)))))
  6624. (defun org-map-region (fun beg end)
  6625. "Call FUN for every heading between BEG and END."
  6626. (let ((org-ignore-region t))
  6627. (save-excursion
  6628. (setq end (copy-marker end))
  6629. (goto-char beg)
  6630. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6631. (< (point) end))
  6632. (funcall fun))
  6633. (while (and (progn
  6634. (outline-next-heading)
  6635. (< (point) end))
  6636. (not (eobp)))
  6637. (funcall fun)))))
  6638. (defun org-fixup-indentation (diff)
  6639. "Change the indentation in the current entry by DIFF.
  6640. DIFF is an integer. Indentation is done according to the
  6641. following rules:
  6642. - Planning information and property drawers are always indented
  6643. according to the new level of the headline;
  6644. - Footnote definitions and their contents are ignored;
  6645. - Inlinetasks' boundaries are not shifted;
  6646. - Empty lines are ignored;
  6647. - Other lines' indentation are shifted by DIFF columns, unless
  6648. it would introduce a structural change in the document, in
  6649. which case no shifting is done at all.
  6650. Assume point is at a heading or an inlinetask beginning."
  6651. (org-with-wide-buffer
  6652. (narrow-to-region (line-beginning-position)
  6653. (save-excursion
  6654. (if (org-with-limited-levels (org-at-heading-p))
  6655. (org-with-limited-levels (outline-next-heading))
  6656. (org-inlinetask-goto-end))
  6657. (point)))
  6658. (forward-line)
  6659. ;; Indent properly planning info and property drawer.
  6660. (when (looking-at-p org-planning-line-re)
  6661. (org-indent-line)
  6662. (forward-line))
  6663. (when (looking-at org-property-drawer-re)
  6664. (goto-char (match-end 0))
  6665. (forward-line)
  6666. (org-indent-region (match-beginning 0) (match-end 0)))
  6667. (when (looking-at org-logbook-drawer-re)
  6668. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6669. (col (+ (current-indentation) diff)))
  6670. (when (wholenump col)
  6671. (while (< (point) end-marker)
  6672. (if (natnump diff)
  6673. (insert (make-string diff 32))
  6674. (delete-char (abs diff)))
  6675. (forward-line)))))
  6676. (catch 'no-shift
  6677. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6678. (throw 'no-shift nil))
  6679. ;; If DIFF is negative, first check if a shift is possible at all
  6680. ;; (e.g., it doesn't break structure). This can only happen if
  6681. ;; some contents are not properly indented.
  6682. (let ((case-fold-search t))
  6683. (when (< diff 0)
  6684. (let ((diff (- diff))
  6685. (forbidden-re (concat org-outline-regexp
  6686. "\\|"
  6687. (substring org-footnote-definition-re 1))))
  6688. (save-excursion
  6689. (while (not (eobp))
  6690. (cond
  6691. ((looking-at-p "[ \t]*$") (forward-line))
  6692. ((and (looking-at-p org-footnote-definition-re)
  6693. (let ((e (org-element-at-point)))
  6694. (and (eq (org-element-type e) 'footnote-definition)
  6695. (goto-char (org-element-property :end e))))))
  6696. ((looking-at-p org-outline-regexp) (forward-line))
  6697. ;; Give up if shifting would move before column 0 or
  6698. ;; if it would introduce a headline or a footnote
  6699. ;; definition.
  6700. (t
  6701. (skip-chars-forward " \t")
  6702. (let ((ind (current-column)))
  6703. (when (or (< ind diff)
  6704. (and (= ind diff) (looking-at-p forbidden-re)))
  6705. (throw 'no-shift nil)))
  6706. ;; Ignore contents of example blocks and source
  6707. ;; blocks if their indentation is meant to be
  6708. ;; preserved. Jump to block's closing line.
  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. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6722. ;; by DIFF. Also skip contents of source or example blocks
  6723. ;; when indentation is meant to be preserved.
  6724. (while (not (eobp))
  6725. (cond
  6726. ((and (looking-at-p org-footnote-definition-re)
  6727. (let ((e (org-element-at-point)))
  6728. (and (eq (org-element-type e) 'footnote-definition)
  6729. (goto-char (org-element-property :end e))))))
  6730. ((looking-at-p org-outline-regexp) (forward-line))
  6731. ((looking-at-p "[ \t]*$") (forward-line))
  6732. (t
  6733. (indent-line-to (+ (current-indentation) diff))
  6734. (beginning-of-line)
  6735. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6736. (let ((e (org-element-at-point)))
  6737. (and (memq (org-element-type e)
  6738. '(example-block src-block))
  6739. (or org-src-preserve-indentation
  6740. (org-element-property :preserve-indent e))
  6741. (goto-char (org-element-property :end e))
  6742. (progn (skip-chars-backward " \r\t\n")
  6743. (beginning-of-line)
  6744. t))))
  6745. (forward-line)))))))))
  6746. (defun org-convert-to-odd-levels ()
  6747. "Convert an Org file with all levels allowed to one with odd levels.
  6748. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6749. level 5 etc."
  6750. (interactive)
  6751. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6752. (let ((outline-level 'org-outline-level)
  6753. (org-odd-levels-only nil) n)
  6754. (save-excursion
  6755. (goto-char (point-min))
  6756. (while (re-search-forward "^\\*\\*+ " nil t)
  6757. (setq n (- (length (match-string 0)) 2))
  6758. (while (>= (setq n (1- n)) 0)
  6759. (org-demote))
  6760. (end-of-line 1))))))
  6761. (defun org-convert-to-oddeven-levels ()
  6762. "Convert an Org file with only odd levels to one with odd/even levels.
  6763. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6764. file contains a section with an even level, conversion would
  6765. destroy the structure of the file. An error is signaled in this
  6766. case."
  6767. (interactive)
  6768. (goto-char (point-min))
  6769. ;; First check if there are no even levels
  6770. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6771. (org-show-set-visibility 'canonical)
  6772. (error "Not all levels are odd in this file. Conversion not possible"))
  6773. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6774. (let ((outline-regexp org-outline-regexp)
  6775. (outline-level 'org-outline-level)
  6776. (org-odd-levels-only nil) n)
  6777. (save-excursion
  6778. (goto-char (point-min))
  6779. (while (re-search-forward "^\\*\\*+ " nil t)
  6780. (setq n (/ (1- (length (match-string 0))) 2))
  6781. (while (>= (setq n (1- n)) 0)
  6782. (org-promote))
  6783. (end-of-line 1))))))
  6784. (defun org-tr-level (n)
  6785. "Make N odd if required."
  6786. (if org-odd-levels-only (1+ (/ n 2)) n))
  6787. ;;; Vertical tree motion, cutting and pasting of subtrees
  6788. (defun org-move-subtree-up (&optional arg)
  6789. "Move the current subtree up past ARG headlines of the same level."
  6790. (interactive "p")
  6791. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6792. (defun org-move-subtree-down (&optional arg)
  6793. "Move the current subtree down past ARG headlines of the same level."
  6794. (interactive "p")
  6795. (setq arg (prefix-numeric-value arg))
  6796. (org-preserve-local-variables
  6797. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6798. 'org-get-previous-sibling))
  6799. (ins-point (make-marker))
  6800. (cnt (abs arg))
  6801. (col (current-column))
  6802. beg end txt folded)
  6803. ;; Select the tree
  6804. (org-back-to-heading)
  6805. (setq beg (point))
  6806. (save-match-data
  6807. (save-excursion (outline-end-of-heading)
  6808. (setq folded (org-invisible-p)))
  6809. (progn (org-end-of-subtree nil t)
  6810. (unless (eobp) (backward-char))))
  6811. (outline-next-heading)
  6812. (setq end (point))
  6813. (goto-char beg)
  6814. ;; Find insertion point, with error handling
  6815. (while (> cnt 0)
  6816. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6817. (goto-char beg)
  6818. (user-error "Cannot move past superior level or buffer limit"))
  6819. (setq cnt (1- cnt)))
  6820. (when (> arg 0)
  6821. ;; Moving forward - still need to move over subtree
  6822. (org-end-of-subtree t t)
  6823. (save-excursion
  6824. (org-back-over-empty-lines)
  6825. (or (bolp) (newline))))
  6826. (move-marker ins-point (point))
  6827. (setq txt (buffer-substring beg end))
  6828. (org-save-markers-in-region beg end)
  6829. (delete-region beg end)
  6830. (org-remove-empty-overlays-at beg)
  6831. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6832. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6833. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6834. (let ((bbb (point)))
  6835. (insert-before-markers txt)
  6836. (org-reinstall-markers-in-region bbb)
  6837. (move-marker ins-point bbb))
  6838. (or (bolp) (insert "\n"))
  6839. (goto-char ins-point)
  6840. (org-skip-whitespace)
  6841. (move-marker ins-point nil)
  6842. (if folded
  6843. (org-flag-subtree t)
  6844. (org-show-entry)
  6845. (org-show-children))
  6846. (org-clean-visibility-after-subtree-move)
  6847. ;; move back to the initial column we were at
  6848. (move-to-column col))))
  6849. (defvar org-subtree-clip ""
  6850. "Clipboard for cut and paste of subtrees.
  6851. This is actually only a copy of the kill, because we use the normal kill
  6852. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6853. (defvar org-subtree-clip-folded nil
  6854. "Was the last copied subtree folded?
  6855. This is used to fold the tree back after pasting.")
  6856. (defun org-cut-subtree (&optional n)
  6857. "Cut the current subtree into the clipboard.
  6858. With prefix arg N, cut this many sequential subtrees.
  6859. This is a short-hand for marking the subtree and then cutting it."
  6860. (interactive "p")
  6861. (org-copy-subtree n 'cut))
  6862. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6863. "Copy the current subtree into the clipboard.
  6864. With prefix arg N, copy this many sequential subtrees.
  6865. This is a short-hand for marking the subtree and then copying it.
  6866. If CUT is non-nil, actually cut the subtree.
  6867. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6868. of some markers in the region, even if CUT is non-nil. This is
  6869. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6870. (interactive "p")
  6871. (org-preserve-local-variables
  6872. (let (beg end folded (beg0 (point)))
  6873. (if (called-interactively-p 'any)
  6874. (org-back-to-heading nil) ; take what looks like a subtree
  6875. (org-back-to-heading t)) ; take what is really there
  6876. (setq beg (point))
  6877. (skip-chars-forward " \t\r\n")
  6878. (save-match-data
  6879. (if nosubtrees
  6880. (outline-next-heading)
  6881. (save-excursion (outline-end-of-heading)
  6882. (setq folded (org-invisible-p)))
  6883. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6884. (org-end-of-subtree t t)))
  6885. ;; Include the end of an inlinetask
  6886. (when (and (featurep 'org-inlinetask)
  6887. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6888. "END[ \t]*$")))
  6889. (end-of-line))
  6890. (setq end (point))
  6891. (goto-char beg0)
  6892. (when (> end beg)
  6893. (setq org-subtree-clip-folded folded)
  6894. (when (or cut force-store-markers)
  6895. (org-save-markers-in-region beg end))
  6896. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6897. (setq org-subtree-clip (current-kill 0))
  6898. (message "%s: Subtree(s) with %d characters"
  6899. (if cut "Cut" "Copied")
  6900. (length org-subtree-clip))))))
  6901. (defun org-paste-subtree (&optional level tree for-yank remove)
  6902. "Paste the clipboard as a subtree, with modification of headline level.
  6903. The entire subtree is promoted or demoted in order to match a new headline
  6904. level.
  6905. If the cursor is at the beginning of a headline, the same level as
  6906. that headline is used to paste the tree.
  6907. If not, the new level is derived from the *visible* headings
  6908. before and after the insertion point, and taken to be the inferior headline
  6909. level of the two. So if the previous visible heading is level 3 and the
  6910. next is level 4 (or vice versa), level 4 will be used for insertion.
  6911. This makes sure that the subtree remains an independent subtree and does
  6912. not swallow low level entries.
  6913. You can also force a different level, either by using a numeric prefix
  6914. argument, or by inserting the heading marker by hand. For example, if the
  6915. cursor is after \"*****\", then the tree will be shifted to level 5.
  6916. If optional TREE is given, use this text instead of the kill ring.
  6917. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6918. move back over whitespace before inserting, and move point to the end of
  6919. the inserted text when done.
  6920. When REMOVE is non-nil, remove the subtree from the clipboard."
  6921. (interactive "P")
  6922. (setq tree (or tree (and kill-ring (current-kill 0))))
  6923. (unless (org-kill-is-subtree-p tree)
  6924. (user-error
  6925. (substitute-command-keys
  6926. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6927. (org-with-limited-levels
  6928. (let* ((visp (not (org-invisible-p)))
  6929. (txt tree)
  6930. (old-level (if (string-match org-outline-regexp-bol txt)
  6931. (- (match-end 0) (match-beginning 0) 1)
  6932. -1))
  6933. (force-level
  6934. (cond
  6935. (level (prefix-numeric-value level))
  6936. ;; When point is after the stars in an otherwise empty
  6937. ;; headline, use the number of stars as the forced level.
  6938. ((and (org-match-line "^\\*+[ \t]*$")
  6939. (not (eq ?* (char-after))))
  6940. (org-outline-level))
  6941. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6942. (previous-level
  6943. (save-excursion
  6944. (org-previous-visible-heading 1)
  6945. (if (org-at-heading-p) (org-outline-level) 1)))
  6946. (next-level
  6947. (save-excursion
  6948. (if (org-at-heading-p) (org-outline-level)
  6949. (org-next-visible-heading 1)
  6950. (if (org-at-heading-p) (org-outline-level) 1))))
  6951. (new-level (or force-level (max previous-level next-level)))
  6952. (shift (if (or (= old-level -1)
  6953. (= new-level -1)
  6954. (= old-level new-level))
  6955. 0
  6956. (- new-level old-level)))
  6957. (delta (if (> shift 0) -1 1))
  6958. (func (if (> shift 0) #'org-demote #'org-promote))
  6959. (org-odd-levels-only nil)
  6960. beg end newend)
  6961. ;; Remove the forced level indicator.
  6962. (when (and force-level (not level))
  6963. (delete-region (line-beginning-position) (point)))
  6964. ;; Paste before the next visible heading or at end of buffer,
  6965. ;; unless point is at the beginning of a headline.
  6966. (unless (and (bolp) (org-at-heading-p))
  6967. (org-next-visible-heading 1)
  6968. (unless (bolp) (insert "\n")))
  6969. (setq beg (point))
  6970. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6971. ;; is inserted and then promoted.
  6972. (combine-change-calls beg beg
  6973. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6974. (insert-before-markers txt)
  6975. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6976. (setq newend (point))
  6977. (org-reinstall-markers-in-region beg)
  6978. (setq end (point))
  6979. (goto-char beg)
  6980. (skip-chars-forward " \t\n\r")
  6981. (setq beg (point))
  6982. (when (and (org-invisible-p) visp)
  6983. (save-excursion (outline-show-heading)))
  6984. ;; Shift if necessary.
  6985. (unless (= shift 0)
  6986. (save-restriction
  6987. (narrow-to-region beg end)
  6988. (while (not (= shift 0))
  6989. (org-map-region func (point-min) (point-max))
  6990. (setq shift (+ delta shift)))
  6991. (goto-char (point-min))
  6992. (setq newend (point-max)))))
  6993. (when (or for-yank (called-interactively-p 'interactive))
  6994. (message "Clipboard pasted as level %d subtree" new-level))
  6995. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6996. kill-ring
  6997. (equal org-subtree-clip (current-kill 0))
  6998. org-subtree-clip-folded)
  6999. ;; The tree was folded before it was killed/copied
  7000. (org-flag-subtree t))
  7001. (when for-yank (goto-char newend))
  7002. (when remove (pop kill-ring)))))
  7003. (defun org-kill-is-subtree-p (&optional txt)
  7004. "Check if the current kill is an outline subtree, or a set of trees.
  7005. Returns nil if kill does not start with a headline, or if the first
  7006. headline level is not the largest headline level in the tree.
  7007. So this will actually accept several entries of equal levels as well,
  7008. which is OK for `org-paste-subtree'.
  7009. If optional TXT is given, check this string instead of the current kill."
  7010. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  7011. (re (org-get-limited-outline-regexp))
  7012. (^re (concat "^" re))
  7013. (start-level (and kill
  7014. (string-match
  7015. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  7016. kill)
  7017. (- (match-end 2) (match-beginning 2) 1)))
  7018. (start (1+ (or (match-beginning 2) -1))))
  7019. (if (not start-level)
  7020. (progn
  7021. nil) ;; does not even start with a heading
  7022. (catch 'exit
  7023. (while (setq start (string-match ^re kill (1+ start)))
  7024. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7025. (throw 'exit nil)))
  7026. t))))
  7027. (defvar org-markers-to-move nil
  7028. "Markers that should be moved with a cut-and-paste operation.
  7029. Those markers are stored together with their positions relative to
  7030. the start of the region.")
  7031. (defun org-save-markers-in-region (beg end)
  7032. "Check markers in region.
  7033. If these markers are between BEG and END, record their position relative
  7034. to BEG, so that after moving the block of text, we can put the markers back
  7035. into place.
  7036. This function gets called just before an entry or tree gets cut from the
  7037. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7038. called immediately, to move the markers with the entries."
  7039. (setq org-markers-to-move nil)
  7040. (when (featurep 'org-clock)
  7041. (org-clock-save-markers-for-cut-and-paste beg end))
  7042. (when (featurep 'org-agenda)
  7043. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7044. (defun org-check-and-save-marker (marker beg end)
  7045. "Check if MARKER is between BEG and END.
  7046. If yes, remember the marker and the distance to BEG."
  7047. (when (and (marker-buffer marker)
  7048. (or (equal (marker-buffer marker) (current-buffer))
  7049. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  7050. (>= marker beg) (< marker end))
  7051. (push (cons marker (- marker beg)) org-markers-to-move)))
  7052. (defun org-reinstall-markers-in-region (beg)
  7053. "Move all remembered markers to their position relative to BEG."
  7054. (dolist (x org-markers-to-move)
  7055. (move-marker (car x) (+ beg (cdr x))))
  7056. (setq org-markers-to-move nil))
  7057. (defun org-narrow-to-subtree (&optional element)
  7058. "Narrow buffer to the current subtree."
  7059. (interactive)
  7060. (if (org-element--cache-active-p)
  7061. (let* ((heading (org-element-lineage
  7062. (or element (org-element-at-point))
  7063. '(headline) t))
  7064. (end (org-element-property :end heading)))
  7065. (if (and heading end)
  7066. (narrow-to-region (org-element-property :begin heading)
  7067. (if (= end (point-max))
  7068. end (1- end)))
  7069. (signal 'outline-before-first-heading nil)))
  7070. (save-excursion
  7071. (save-match-data
  7072. (org-with-limited-levels
  7073. (narrow-to-region
  7074. (progn (org-back-to-heading t) (point))
  7075. (progn (org-end-of-subtree t t)
  7076. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7077. (point))))))))
  7078. (defun org-toggle-narrow-to-subtree ()
  7079. "Narrow to the subtree at point or widen a narrowed buffer."
  7080. (interactive)
  7081. (if (buffer-narrowed-p)
  7082. (progn (widen) (message "Buffer widen"))
  7083. (org-narrow-to-subtree)
  7084. (message "Buffer narrowed to current subtree")))
  7085. (defun org-narrow-to-block ()
  7086. "Narrow buffer to the current block."
  7087. (interactive)
  7088. (let* ((case-fold-search t)
  7089. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7090. "^[ \t]*#\\+end_.*")))
  7091. (if blockp
  7092. (narrow-to-region (car blockp) (cdr blockp))
  7093. (user-error "Not in a block"))))
  7094. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7095. "Clone the task (subtree) at point N times.
  7096. The clones will be inserted as siblings.
  7097. In interactive use, the user will be prompted for the number of
  7098. clones to be produced. If the entry has a timestamp, the user
  7099. will also be prompted for a time shift, which may be a repeater
  7100. as used in time stamps, for example `+3d'. To disable this,
  7101. you can call the function with a universal prefix argument.
  7102. When a valid repeater is given and the entry contains any time
  7103. stamps, the clones will become a sequence in time, with time
  7104. stamps in the subtree shifted for each clone produced. If SHIFT
  7105. is nil or the empty string, time stamps will be left alone. The
  7106. ID property of the original subtree is removed.
  7107. In each clone, all the CLOCK entries will be removed. This
  7108. prevents Org from considering that the clocked times overlap.
  7109. If the original subtree did contain time stamps with a repeater,
  7110. the following will happen:
  7111. - the repeater will be removed in each clone
  7112. - an additional clone will be produced, with the current, unshifted
  7113. date(s) in the entry.
  7114. - the original entry will be placed *after* all the clones, with
  7115. repeater intact.
  7116. - the start days in the repeater in the original entry will be shifted
  7117. to past the last clone.
  7118. In this way you can spell out a number of instances of a repeating task,
  7119. and still retain the repeater to cover future instances of the task.
  7120. As described above, N+1 clones are produced when the original
  7121. subtree has a repeater. Setting N to 0, then, can be used to
  7122. remove the repeater from a subtree and create a shifted clone
  7123. with the original repeater."
  7124. (interactive "nNumber of clones to produce: ")
  7125. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7126. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7127. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7128. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7129. (shift
  7130. (or shift
  7131. (if (and (not (equal current-prefix-arg '(4)))
  7132. (save-excursion
  7133. (goto-char beg)
  7134. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7135. (read-from-minibuffer
  7136. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7137. ""))) ;No time shift
  7138. (doshift
  7139. (and (org-string-nw-p shift)
  7140. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7141. shift)
  7142. (user-error "Invalid shift specification %s" shift)))))
  7143. (goto-char end-of-tree)
  7144. (unless (bolp) (insert "\n"))
  7145. (let* ((end (point))
  7146. (template (buffer-substring beg end))
  7147. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7148. (shift-what (pcase (and doshift (match-string 2 shift))
  7149. (`nil nil)
  7150. ("h" 'hour)
  7151. ("d" 'day)
  7152. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7153. ("m" 'month)
  7154. ("y" 'year)
  7155. (_ (error "Unsupported time unit"))))
  7156. (nmin 1)
  7157. (nmax n)
  7158. (n-no-remove -1)
  7159. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7160. (idprop (org-entry-get beg "ID")))
  7161. (when (and doshift
  7162. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7163. template))
  7164. (delete-region beg end)
  7165. (setq end beg)
  7166. (setq nmin 0)
  7167. (setq nmax (1+ nmax))
  7168. (setq n-no-remove nmax))
  7169. (goto-char end)
  7170. (cl-loop for n from nmin to nmax do
  7171. (insert
  7172. ;; Prepare clone.
  7173. (with-temp-buffer
  7174. (insert template)
  7175. (org-mode)
  7176. (goto-char (point-min))
  7177. (org-show-subtree)
  7178. (and idprop (if org-clone-delete-id
  7179. (org-entry-delete nil "ID")
  7180. (org-id-get-create t)))
  7181. (unless (= n 0)
  7182. (while (re-search-forward org-clock-line-re nil t)
  7183. (delete-region (line-beginning-position)
  7184. (line-beginning-position 2)))
  7185. (goto-char (point-min))
  7186. (while (re-search-forward org-drawer-regexp nil t)
  7187. (org-remove-empty-drawer-at (point))))
  7188. (goto-char (point-min))
  7189. (when doshift
  7190. (while (re-search-forward org-ts-regexp-both nil t)
  7191. (org-timestamp-change (* n shift-n) shift-what))
  7192. (unless (= n n-no-remove)
  7193. (goto-char (point-min))
  7194. (while (re-search-forward org-ts-regexp nil t)
  7195. (save-excursion
  7196. (goto-char (match-beginning 0))
  7197. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7198. (delete-region (match-beginning 1) (match-end 1)))))))
  7199. (buffer-string)))))
  7200. (goto-char beg)))
  7201. ;;; Outline path
  7202. (defvar org-outline-path-cache nil
  7203. "Alist between buffer positions and outline paths.
  7204. It value is an alist (POSITION . PATH) where POSITION is the
  7205. buffer position at the beginning of an entry and PATH is a list
  7206. of strings describing the outline path for that entry, in reverse
  7207. order.")
  7208. (defun org--get-outline-path-1 (&optional use-cache)
  7209. "Return outline path to current headline.
  7210. Outline path is a list of strings, in reverse order. When
  7211. optional argument USE-CACHE is non-nil, make use of a cache. See
  7212. `org-get-outline-path' for details.
  7213. Assume buffer is widened and point is on a headline."
  7214. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7215. (let ((p (point))
  7216. (heading (let ((case-fold-search nil))
  7217. (looking-at org-complex-heading-regexp)
  7218. (if (not (match-end 4)) ""
  7219. ;; Remove statistics cookies.
  7220. (org-trim
  7221. (org-link-display-format
  7222. (replace-regexp-in-string
  7223. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7224. (match-string-no-properties 4))))))))
  7225. (if (org-up-heading-safe)
  7226. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7227. (when use-cache
  7228. (push (cons p path) org-outline-path-cache))
  7229. path)
  7230. ;; This is a new root node. Since we assume we are moving
  7231. ;; forward, we can drop previous cache so as to limit number
  7232. ;; of associations there.
  7233. (let ((path (list heading)))
  7234. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7235. path)))))
  7236. (defun org-get-outline-path (&optional with-self use-cache)
  7237. "Return the outline path to the current entry.
  7238. An outline path is a list of ancestors for current headline, as
  7239. a list of strings. Statistics cookies are removed and links are
  7240. replaced with their description, if any, or their path otherwise.
  7241. When optional argument WITH-SELF is non-nil, the path also
  7242. includes the current headline.
  7243. When optional argument USE-CACHE is non-nil, cache outline paths
  7244. between calls to this function so as to avoid backtracking. This
  7245. argument is useful when planning to find more than one outline
  7246. path in the same document. In that case, there are two
  7247. conditions to satisfy:
  7248. - `org-outline-path-cache' is set to nil before starting the
  7249. process;
  7250. - outline paths are computed by increasing buffer positions."
  7251. (org-with-wide-buffer
  7252. (and (or (and with-self (org-back-to-heading t))
  7253. (org-up-heading-safe))
  7254. (reverse (org--get-outline-path-1 use-cache)))))
  7255. (defun org-format-outline-path (path &optional width prefix separator)
  7256. "Format the outline path PATH for display.
  7257. WIDTH is the maximum number of characters that is available.
  7258. PREFIX is a prefix to be included in the returned string,
  7259. such as the file name.
  7260. SEPARATOR is inserted between the different parts of the path,
  7261. the default is \"/\"."
  7262. (setq width (or width 79))
  7263. (setq path (delq nil path))
  7264. (unless (> width 0)
  7265. (user-error "Argument `width' must be positive"))
  7266. (setq separator (or separator "/"))
  7267. (let* ((org-odd-levels-only nil)
  7268. (fpath (concat
  7269. prefix (and prefix path separator)
  7270. (mapconcat
  7271. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7272. (cl-loop for head in path
  7273. for n from 0
  7274. collect (org-add-props
  7275. head nil 'face
  7276. (nth (% n org-n-level-faces) org-level-faces)))
  7277. separator))))
  7278. (when (> (length fpath) width)
  7279. (if (< width 7)
  7280. ;; It's unlikely that `width' will be this small, but don't
  7281. ;; waste characters by adding ".." if it is.
  7282. (setq fpath (substring fpath 0 width))
  7283. (setf (substring fpath (- width 2)) "..")))
  7284. fpath))
  7285. (defun org-display-outline-path (&optional file current separator just-return-string)
  7286. "Display the current outline path in the echo area.
  7287. If FILE is non-nil, prepend the output with the file name.
  7288. If CURRENT is non-nil, append the current heading to the output.
  7289. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7290. the different parts of the path and defaults to \"/\".
  7291. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7292. (interactive "P")
  7293. (let* (case-fold-search
  7294. (bfn (buffer-file-name (buffer-base-buffer)))
  7295. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7296. res)
  7297. (when current (setq path (append path
  7298. (save-excursion
  7299. (org-back-to-heading t)
  7300. (when (looking-at org-complex-heading-regexp)
  7301. (list (match-string 4)))))))
  7302. (setq res
  7303. (org-format-outline-path
  7304. path
  7305. (1- (frame-width))
  7306. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7307. separator))
  7308. (add-face-text-property 0 (length res)
  7309. `(:height ,(face-attribute 'default :height))
  7310. nil res)
  7311. (if just-return-string
  7312. res
  7313. (org-unlogged-message "%s" res))))
  7314. ;;; Outline Sorting
  7315. (defun org-sort (&optional with-case)
  7316. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7317. Optional argument WITH-CASE means sort case-sensitively."
  7318. (interactive "P")
  7319. (org-call-with-arg
  7320. (cond ((org-at-table-p) #'org-table-sort-lines)
  7321. ((org-at-item-p) #'org-sort-list)
  7322. (t #'org-sort-entries))
  7323. with-case))
  7324. (defun org-sort-remove-invisible (s)
  7325. "Remove emphasis markers and any invisible property from string S.
  7326. Assume S may contain only objects."
  7327. ;; org-element-interpret-data clears any text property, including
  7328. ;; invisible part.
  7329. (org-element-interpret-data
  7330. (let ((tree (org-element-parse-secondary-string
  7331. s (org-element-restriction 'paragraph))))
  7332. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  7333. (lambda (o)
  7334. (pcase (org-element-type o)
  7335. ;; Terminal object. Replace it with its value.
  7336. ((or `code `verbatim)
  7337. (let ((new (org-element-property :value o)))
  7338. (org-element-insert-before new o)
  7339. (org-element-put-property
  7340. new :post-blank (org-element-property :post-blank o))))
  7341. ;; Non-terminal objects. Splice contents.
  7342. (type
  7343. (let ((contents
  7344. (or (org-element-contents o)
  7345. (and (eq type 'link)
  7346. (list (org-element-property :raw-link o)))))
  7347. (c nil))
  7348. (while contents
  7349. (setq c (pop contents))
  7350. (org-element-insert-before c o))
  7351. (org-element-put-property
  7352. c :post-blank (org-element-property :post-blank o)))))
  7353. (org-element-extract-element o)))
  7354. ;; Return modified tree.
  7355. tree)))
  7356. (defvar org-after-sorting-entries-or-items-hook nil
  7357. "Hook that is run after a bunch of entries or items have been sorted.
  7358. When children are sorted, the cursor is in the parent line when this
  7359. hook gets called. When a region or a plain list is sorted, the cursor
  7360. will be in the first entry of the sorted region/list.")
  7361. (defun org-sort-entries
  7362. (&optional with-case sorting-type getkey-func compare-func property
  7363. interactive?)
  7364. "Sort entries on a certain level of an outline tree.
  7365. If there is an active region, the entries in the region are sorted.
  7366. Else, if the cursor is before the first entry, sort the top-level items.
  7367. Else, the children of the entry at point are sorted.
  7368. Sorting can be alphabetically, numerically, by date/time as given by
  7369. a time stamp, by a property, by priority order, or by a custom function.
  7370. The command prompts for the sorting type unless it has been given to the
  7371. function through the SORTING-TYPE argument, which needs to be a character,
  7372. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7373. the precise meaning of each character:
  7374. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7375. c By creation time, which is assumed to be the first inactive time stamp
  7376. at the beginning of a line.
  7377. d By deadline date/time.
  7378. k By clocking time.
  7379. n Numerically, by converting the beginning of the entry/item to a number.
  7380. o By order of TODO keywords.
  7381. p By priority according to the cookie.
  7382. r By the value of a property.
  7383. s By scheduled date/time.
  7384. t By date/time, either the first active time stamp in the entry, or, if
  7385. none exist, by the first inactive one.
  7386. Capital letters will reverse the sort order.
  7387. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7388. called with point at the beginning of the record. It must return a
  7389. value that is compatible with COMPARE-FUNC, the function used to
  7390. compare entries.
  7391. Comparing entries ignores case by default. However, with an optional argument
  7392. WITH-CASE, the sorting considers case as well.
  7393. Sorting is done against the visible part of the headlines, it ignores hidden
  7394. links.
  7395. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7396. A non-nil value for INTERACTIVE? is used to signal that this
  7397. function is being called interactively."
  7398. (interactive (list current-prefix-arg nil nil nil nil t))
  7399. (let ((case-func (if with-case 'identity 'downcase))
  7400. start beg end stars re re2
  7401. txt what tmp)
  7402. ;; Find beginning and end of region to sort
  7403. (cond
  7404. ((org-region-active-p)
  7405. ;; we will sort the region
  7406. (setq end (region-end)
  7407. what "region")
  7408. (goto-char (region-beginning))
  7409. (unless (org-at-heading-p) (outline-next-heading))
  7410. (setq start (point)))
  7411. ((or (org-at-heading-p)
  7412. (ignore-errors (progn (org-back-to-heading) t)))
  7413. ;; we will sort the children of the current headline
  7414. (org-back-to-heading)
  7415. (setq start (point)
  7416. end (progn (org-end-of-subtree t t)
  7417. (or (bolp) (insert "\n"))
  7418. (when (>= (org-back-over-empty-lines) 1)
  7419. (forward-line 1))
  7420. (point))
  7421. what "children")
  7422. (goto-char start)
  7423. (outline-show-subtree)
  7424. (outline-next-heading))
  7425. (t
  7426. ;; we will sort the top-level entries in this file
  7427. (goto-char (point-min))
  7428. (or (org-at-heading-p) (outline-next-heading))
  7429. (setq start (point))
  7430. (goto-char (point-max))
  7431. (beginning-of-line 1)
  7432. (when (looking-at ".*?\\S-")
  7433. ;; File ends in a non-white line
  7434. (end-of-line 1)
  7435. (insert "\n"))
  7436. (setq end (point-max))
  7437. (setq what "top-level")
  7438. (goto-char start)
  7439. (org-show-all '(headings drawers blocks))))
  7440. (setq beg (point))
  7441. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7442. (looking-at "\\(\\*+\\)")
  7443. (setq stars (match-string 1)
  7444. re (concat "^" (regexp-quote stars) " +")
  7445. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7446. txt (buffer-substring beg end))
  7447. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7448. (when (and (not (equal stars "*")) (string-match re2 txt))
  7449. (user-error "Region to sort contains a level above the first entry"))
  7450. (unless sorting-type
  7451. (message
  7452. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7453. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7454. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7455. what)
  7456. (setq sorting-type (read-char-exclusive)))
  7457. (unless getkey-func
  7458. (and (= (downcase sorting-type) ?f)
  7459. (setq getkey-func
  7460. (or (and interactive?
  7461. (org-read-function
  7462. "Function for extracting keys: "))
  7463. (error "Missing key extractor")))))
  7464. (and (= (downcase sorting-type) ?r)
  7465. (not property)
  7466. (setq property
  7467. (completing-read "Property: "
  7468. (mapcar #'list (org-buffer-property-keys t))
  7469. nil t)))
  7470. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7471. (message "Sorting entries...")
  7472. (save-restriction
  7473. (narrow-to-region start end)
  7474. (let ((restore-clock?
  7475. ;; The clock marker is lost when using `sort-subr'; mark
  7476. ;; the clock with temporary `:org-clock-marker-backup'
  7477. ;; text property.
  7478. (when (and (eq (org-clocking-buffer) (current-buffer))
  7479. (<= start (marker-position org-clock-marker))
  7480. (>= end (marker-position org-clock-marker)))
  7481. (with-silent-modifications
  7482. (put-text-property (1- org-clock-marker) org-clock-marker
  7483. :org-clock-marker-backup t))
  7484. t))
  7485. (dcst (downcase sorting-type))
  7486. (case-fold-search nil)
  7487. (now (current-time)))
  7488. (org-preserve-local-variables
  7489. (sort-subr
  7490. (/= dcst sorting-type)
  7491. ;; This function moves to the beginning character of the
  7492. ;; "record" to be sorted.
  7493. (lambda nil
  7494. (if (re-search-forward re nil t)
  7495. (goto-char (match-beginning 0))
  7496. (goto-char (point-max))))
  7497. ;; This function moves to the last character of the "record" being
  7498. ;; sorted.
  7499. (lambda nil
  7500. (save-match-data
  7501. (condition-case nil
  7502. (outline-forward-same-level 1)
  7503. (error
  7504. (goto-char (point-max))))))
  7505. ;; This function returns the value that gets sorted against.
  7506. (lambda ()
  7507. (cond
  7508. ((= dcst ?n)
  7509. (string-to-number
  7510. (org-sort-remove-invisible (org-get-heading t t t t))))
  7511. ((= dcst ?a)
  7512. (funcall case-func
  7513. (org-sort-remove-invisible (org-get-heading t t t t))))
  7514. ((= dcst ?k)
  7515. (or (get-text-property (point) :org-clock-minutes) 0))
  7516. ((= dcst ?t)
  7517. (let ((end (save-excursion (outline-next-heading) (point))))
  7518. (if (or (re-search-forward org-ts-regexp end t)
  7519. (re-search-forward org-ts-regexp-both end t))
  7520. (org-time-string-to-seconds (match-string 0))
  7521. (float-time now))))
  7522. ((= dcst ?c)
  7523. (let ((end (save-excursion (outline-next-heading) (point))))
  7524. (if (re-search-forward
  7525. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7526. end t)
  7527. (org-time-string-to-seconds (match-string 0))
  7528. (float-time now))))
  7529. ((= dcst ?s)
  7530. (let ((end (save-excursion (outline-next-heading) (point))))
  7531. (if (re-search-forward org-scheduled-time-regexp end t)
  7532. (org-time-string-to-seconds (match-string 1))
  7533. (float-time now))))
  7534. ((= dcst ?d)
  7535. (let ((end (save-excursion (outline-next-heading) (point))))
  7536. (if (re-search-forward org-deadline-time-regexp end t)
  7537. (org-time-string-to-seconds (match-string 1))
  7538. (float-time now))))
  7539. ((= dcst ?p)
  7540. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7541. (string-to-char (match-string 2))
  7542. org-priority-default))
  7543. ((= dcst ?r)
  7544. (or (org-entry-get nil property) ""))
  7545. ((= dcst ?o)
  7546. (when (looking-at org-complex-heading-regexp)
  7547. (let* ((m (match-string 2))
  7548. (s (if (member m org-done-keywords) '- '+)))
  7549. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7550. ((= dcst ?f)
  7551. (if getkey-func
  7552. (progn
  7553. (setq tmp (funcall getkey-func))
  7554. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7555. tmp)
  7556. (error "Invalid key function `%s'" getkey-func)))
  7557. (t (error "Invalid sorting type `%c'" sorting-type))))
  7558. nil
  7559. (cond
  7560. ((= dcst ?a) 'string-collate-lessp)
  7561. ((= dcst ?f)
  7562. (or compare-func
  7563. (and interactive?
  7564. (org-read-function
  7565. (concat "Function for comparing keys "
  7566. "(empty for default `sort-subr' predicate): ")
  7567. 'allow-empty))))
  7568. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7569. (org-cycle-hide-drawers 'all)
  7570. (when restore-clock?
  7571. (move-marker org-clock-marker
  7572. (1+ (next-single-property-change
  7573. start :org-clock-marker-backup)))
  7574. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7575. '(:org-clock-marker-backup t)))))
  7576. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7577. (message "Sorting entries...done")))
  7578. (defun org-contextualize-keys (alist contexts)
  7579. "Return valid elements in ALIST depending on CONTEXTS.
  7580. `org-agenda-custom-commands' or `org-capture-templates' are the
  7581. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7582. or `org-capture-templates-contexts' are the associated contexts
  7583. definitions."
  7584. (let ((contexts
  7585. ;; normalize contexts
  7586. (mapcar
  7587. (lambda(c) (cond ((listp (cadr c))
  7588. (list (car c) (car c) (nth 1 c)))
  7589. ((string= "" (cadr c))
  7590. (list (car c) (car c) (nth 2 c)))
  7591. (t c)))
  7592. contexts))
  7593. (a alist) r s)
  7594. ;; loop over all commands or templates
  7595. (dolist (c a)
  7596. (let (vrules repl)
  7597. (cond
  7598. ((not (assoc (car c) contexts))
  7599. (push c r))
  7600. ((and (assoc (car c) contexts)
  7601. (setq vrules (org-contextualize-validate-key
  7602. (car c) contexts)))
  7603. (mapc (lambda (vr)
  7604. (unless (equal (car vr) (cadr vr))
  7605. (setq repl vr)))
  7606. vrules)
  7607. (if (not repl) (push c r)
  7608. (push (cadr repl) s)
  7609. (push
  7610. (cons (car c)
  7611. (cdr (or (assoc (cadr repl) alist)
  7612. (error "Undefined key `%s' as contextual replacement for `%s'"
  7613. (cadr repl) (car c)))))
  7614. r))))))
  7615. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7616. (delq
  7617. nil
  7618. (delete-dups
  7619. (mapcar (lambda (x)
  7620. (let ((tpl (car x)))
  7621. (unless (delq
  7622. nil
  7623. (mapcar (lambda (y)
  7624. (equal y tpl))
  7625. s))
  7626. x)))
  7627. (reverse r))))))
  7628. (defun org-contextualize-validate-key (key contexts)
  7629. "Check CONTEXTS for agenda or capture KEY."
  7630. (let (res)
  7631. (dolist (r contexts)
  7632. (dolist (rr (car (last r)))
  7633. (when
  7634. (and (equal key (car r))
  7635. (if (functionp rr) (funcall rr)
  7636. (or (and (eq (car rr) 'in-file)
  7637. (buffer-file-name)
  7638. (string-match (cdr rr) (buffer-file-name)))
  7639. (and (eq (car rr) 'in-mode)
  7640. (string-match (cdr rr) (symbol-name major-mode)))
  7641. (and (eq (car rr) 'in-buffer)
  7642. (string-match (cdr rr) (buffer-name)))
  7643. (when (and (eq (car rr) 'not-in-file)
  7644. (buffer-file-name))
  7645. (not (string-match (cdr rr) (buffer-file-name))))
  7646. (when (eq (car rr) 'not-in-mode)
  7647. (not (string-match (cdr rr) (symbol-name major-mode))))
  7648. (when (eq (car rr) 'not-in-buffer)
  7649. (not (string-match (cdr rr) (buffer-name)))))))
  7650. (push r res))))
  7651. (delete-dups (delq nil res))))
  7652. ;; Defined to provide a value for defcustom, since there is no
  7653. ;; string-collate-greaterp in Emacs.
  7654. (defun org-string-collate-greaterp (s1 s2)
  7655. "Return non-nil if S1 is greater than S2 in collation order."
  7656. (not (string-collate-lessp s1 s2)))
  7657. ;;;###autoload
  7658. (defun org-run-like-in-org-mode (cmd)
  7659. "Run a command, pretending that the current buffer is in Org mode.
  7660. This will temporarily bind local variables that are typically bound in
  7661. Org mode to the values they have in Org mode, and then interactively
  7662. call CMD."
  7663. (org-load-modules-maybe)
  7664. (let (binds)
  7665. (dolist (var (org-get-local-variables))
  7666. (when (or (not (boundp (car var)))
  7667. (eq (symbol-value (car var))
  7668. (default-value (car var))))
  7669. (push (list (car var) `(quote ,(cadr var))) binds)))
  7670. (eval `(let ,binds
  7671. (call-interactively (quote ,cmd))))))
  7672. (defun org-get-category (&optional pos force-refresh)
  7673. "Get the category applying to position POS."
  7674. (save-match-data
  7675. (when force-refresh (org-refresh-category-properties))
  7676. (let ((pos (or pos (point))))
  7677. (if (org-element--cache-active-p)
  7678. ;; Sync cache.
  7679. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  7680. (or (org-entry-get-with-inheritance "CATEGORY")
  7681. "???"))
  7682. (or (get-text-property pos 'org-category)
  7683. (progn
  7684. (org-refresh-category-properties)
  7685. (get-text-property pos 'org-category)))))))
  7686. ;;; Refresh properties
  7687. (defun org-refresh-properties (dprop tprop)
  7688. "Refresh buffer text properties.
  7689. DPROP is the drawer property and TPROP is either the
  7690. corresponding text property to set, or an alist with each element
  7691. being a text property (as a symbol) and a function to apply to
  7692. the value of the drawer property."
  7693. (let* ((case-fold-search t)
  7694. (inhibit-read-only t)
  7695. (inherit? (org-property-inherit-p dprop))
  7696. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7697. (global-or-keyword (and inherit?
  7698. (org--property-global-or-keyword-value dprop nil))))
  7699. (with-silent-modifications
  7700. (org-with-point-at 1
  7701. ;; Set global and keyword based values to the whole buffer.
  7702. (when global-or-keyword
  7703. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7704. ;; Set values based on property-drawers throughout the document.
  7705. (while (re-search-forward property-re nil t)
  7706. (when (org-at-property-p)
  7707. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7708. (outline-next-heading))))))
  7709. (defun org-refresh-property (tprop p &optional inherit)
  7710. "Refresh the buffer text property TPROP from the drawer property P.
  7711. The refresh happens only for the current entry, or the whole
  7712. sub-tree if optional argument INHERIT is non-nil.
  7713. If point is before first headline, the function applies to the
  7714. part before the first headline. In that particular case, when
  7715. optional argument INHERIT is non-nil, it refreshes properties for
  7716. the whole buffer."
  7717. (save-excursion
  7718. (org-back-to-heading-or-point-min t)
  7719. (let ((start (point))
  7720. (end (save-excursion
  7721. (cond ((and inherit (org-before-first-heading-p))
  7722. (point-max))
  7723. (inherit
  7724. (org-end-of-subtree t t))
  7725. ((outline-next-heading))
  7726. ((point-max))))))
  7727. (with-silent-modifications
  7728. (if (symbolp tprop)
  7729. ;; TPROP is a text property symbol.
  7730. (put-text-property start end tprop p)
  7731. ;; TPROP is an alist with (property . function) elements.
  7732. (pcase-dolist (`(,prop . ,f) tprop)
  7733. (put-text-property start end prop (funcall f p))))))))
  7734. (defun org-refresh-category-properties ()
  7735. "Refresh category text properties in the buffer."
  7736. (unless (org-element--cache-active-p)
  7737. (let ((case-fold-search t)
  7738. (inhibit-read-only t)
  7739. (default-category
  7740. (cond ((null org-category)
  7741. (if buffer-file-name
  7742. (file-name-sans-extension
  7743. (file-name-nondirectory buffer-file-name))
  7744. "???"))
  7745. ((symbolp org-category) (symbol-name org-category))
  7746. (t org-category))))
  7747. (let ((category (catch 'buffer-category
  7748. (org-with-wide-buffer
  7749. (goto-char (point-max))
  7750. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7751. (let ((element (org-element-at-point-no-context)))
  7752. (when (eq (org-element-type element) 'keyword)
  7753. (throw 'buffer-category
  7754. (org-element-property :value element))))))
  7755. default-category)))
  7756. (with-silent-modifications
  7757. (org-with-wide-buffer
  7758. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7759. ;; keyword. If none is found, fall-back to `org-category' or
  7760. ;; buffer file name, or set it by the document property drawer.
  7761. (put-text-property (point-min) (point-max)
  7762. 'org-category category)
  7763. ;; Set categories from the document property drawer or
  7764. ;; property drawers in the outline. If category is found in
  7765. ;; the property drawer for the whole buffer that value
  7766. ;; overrides the keyword-based value set above.
  7767. (goto-char (point-min))
  7768. (let ((regexp (org-re-property "CATEGORY")))
  7769. (while (re-search-forward regexp nil t)
  7770. (let ((value (match-string-no-properties 3)))
  7771. (when (org-at-property-p)
  7772. (put-text-property
  7773. (save-excursion (org-back-to-heading-or-point-min t))
  7774. (save-excursion (if (org-before-first-heading-p)
  7775. (point-max)
  7776. (org-end-of-subtree t t)))
  7777. 'org-category
  7778. value)))))))))))
  7779. (defun org-refresh-stats-properties ()
  7780. "Refresh stats text properties in the buffer."
  7781. (with-silent-modifications
  7782. (org-with-point-at 1
  7783. (let ((regexp (concat org-outline-regexp-bol
  7784. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7785. (while (re-search-forward regexp nil t)
  7786. (let* ((numerator (string-to-number (match-string 1)))
  7787. (denominator (and (match-end 2)
  7788. (string-to-number (match-string 2))))
  7789. (stats (cond ((not denominator) numerator) ;percent
  7790. ((= denominator 0) 0)
  7791. (t (/ (* numerator 100) denominator)))))
  7792. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7793. 'org-stats stats)))))))
  7794. (defun org-refresh-effort-properties ()
  7795. "Refresh effort properties."
  7796. (org-refresh-properties
  7797. org-effort-property
  7798. '((effort . identity)
  7799. (effort-minutes . org-duration-to-minutes))))
  7800. (defun org-find-file-at-mouse (ev)
  7801. "Open file link or URL at mouse."
  7802. (interactive "e")
  7803. (mouse-set-point ev)
  7804. (org-open-at-point 'in-emacs))
  7805. (defun org-open-at-mouse (ev)
  7806. "Open file link or URL at mouse.
  7807. See the docstring of `org-open-file' for details."
  7808. (interactive "e")
  7809. (mouse-set-point ev)
  7810. (when (eq major-mode 'org-agenda-mode)
  7811. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7812. (org-open-at-point))
  7813. (defvar org-window-config-before-follow-link nil
  7814. "The window configuration before following a link.
  7815. This is saved in case the need arises to restore it.")
  7816. (defun org--file-default-apps ()
  7817. "Return the default applications for this operating system."
  7818. (pcase system-type
  7819. (`darwin org-file-apps-macos)
  7820. (`windows-nt org-file-apps-windowsnt)
  7821. (_ org-file-apps-gnu)))
  7822. (defun org--file-apps-entry-dlink-p (entry)
  7823. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7824. It assumes that is the case when the entry uses a regular
  7825. expression which has at least one grouping construct and the
  7826. action is either a Lisp form or a command string containing
  7827. \"%1\", i.e., using at least one subexpression match as
  7828. a parameter."
  7829. (pcase entry
  7830. (`(,selector . ,action)
  7831. (and (stringp selector)
  7832. (> (regexp-opt-depth selector) 0)
  7833. (or (and (stringp action)
  7834. (string-match "%[0-9]" action))
  7835. (consp action))))
  7836. (_ nil)))
  7837. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7838. "Convert extensions to regular expressions in the cars of LIST.
  7839. Also, weed out any non-string entries, because the return value
  7840. is used only for regexp matching.
  7841. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7842. point to the symbol `emacs', indicating that the file should be
  7843. opened in Emacs."
  7844. (append
  7845. (delq nil
  7846. (mapcar (lambda (x)
  7847. (unless (not (stringp (car x)))
  7848. (if (string-match "\\W" (car x))
  7849. x
  7850. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7851. list))
  7852. (when add-auto-mode
  7853. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7854. ;;;###autoload
  7855. (defun org-open-file (path &optional in-emacs line search)
  7856. "Open the file at PATH.
  7857. First, this expands any special file name abbreviations. Then the
  7858. configuration variable `org-file-apps' is checked if it contains an
  7859. entry for this file type, and if yes, the corresponding command is launched.
  7860. If no application is found, Emacs simply visits the file.
  7861. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7862. With a double \\[universal-argument] \\[universal-argument] \
  7863. prefix arg, Org tries to avoid opening in Emacs
  7864. and to use an external application to visit the file.
  7865. Optional LINE specifies a line to go to, optional SEARCH a string
  7866. to search for. If LINE or SEARCH is given, the file will be
  7867. opened in Emacs, unless an entry from `org-file-apps' that makes
  7868. use of groups in a regexp matches.
  7869. If you want to change the way frames are used when following a
  7870. link, please customize `org-link-frame-setup'.
  7871. If the file does not exist, throw an error."
  7872. (let* ((file (if (equal path "") buffer-file-name
  7873. (substitute-in-file-name (expand-file-name path))))
  7874. (file-apps (append org-file-apps (org--file-default-apps)))
  7875. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7876. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7877. file-apps))
  7878. (remp (and (assq 'remote apps) (file-remote-p file)))
  7879. (dirp (unless remp (file-directory-p file)))
  7880. (file (if (and dirp org-open-directory-means-index-dot-org)
  7881. (concat (file-name-as-directory file) "index.org")
  7882. file))
  7883. (a-m-a-p (assq 'auto-mode apps))
  7884. (dfile (downcase file))
  7885. ;; Reconstruct the original link from the PATH, LINE and
  7886. ;; SEARCH args.
  7887. (link (cond (line (concat file "::" (number-to-string line)))
  7888. (search (concat file "::" search))
  7889. (t file)))
  7890. (dlink (downcase link))
  7891. (ext
  7892. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7893. (match-string 1 dfile)))
  7894. (save-position-maybe
  7895. (let ((old-buffer (current-buffer))
  7896. (old-pos (point))
  7897. (old-mode major-mode))
  7898. (lambda ()
  7899. (and (derived-mode-p 'org-mode)
  7900. (eq old-mode 'org-mode)
  7901. (or (not (eq old-buffer (current-buffer)))
  7902. (not (eq old-pos (point))))
  7903. (org-mark-ring-push old-pos old-buffer)))))
  7904. cmd link-match-data)
  7905. (cond
  7906. ((member in-emacs '((16) system))
  7907. (setq cmd (cdr (assq 'system apps))))
  7908. (in-emacs (setq cmd 'emacs))
  7909. (t
  7910. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7911. (and dirp (cdr (assq 'directory apps)))
  7912. ;; First, try matching against apps-dlink if we
  7913. ;; get a match here, store the match data for
  7914. ;; later.
  7915. (let ((match (assoc-default dlink apps-dlink
  7916. 'string-match)))
  7917. (if match
  7918. (progn (setq link-match-data (match-data))
  7919. match)
  7920. (progn (setq in-emacs (or in-emacs line search))
  7921. nil))) ; if we have no match in apps-dlink,
  7922. ; always open the file in emacs if line or search
  7923. ; is given (for backwards compatibility)
  7924. (assoc-default dfile
  7925. (org--file-apps-regexp-alist apps a-m-a-p)
  7926. 'string-match)
  7927. (cdr (assoc ext apps))
  7928. (cdr (assq t apps))))))
  7929. (when (eq cmd 'system)
  7930. (setq cmd (cdr (assq 'system apps))))
  7931. (when (eq cmd 'default)
  7932. (setq cmd (cdr (assoc t apps))))
  7933. (when (eq cmd 'mailcap)
  7934. (require 'mailcap)
  7935. (mailcap-parse-mailcaps)
  7936. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7937. (command (mailcap-mime-info mime-type)))
  7938. (if (stringp command)
  7939. (setq cmd command)
  7940. (setq cmd 'emacs))))
  7941. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7942. (not (file-exists-p file))
  7943. (not org-open-non-existing-files))
  7944. (user-error "No such file: %s" file))
  7945. (cond
  7946. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7947. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7948. (while (string-match "['\"]%s['\"]" cmd)
  7949. (setq cmd (replace-match "%s" t t cmd)))
  7950. (setq cmd (replace-regexp-in-string
  7951. "%s"
  7952. (shell-quote-argument (convert-standard-filename file))
  7953. cmd
  7954. nil t))
  7955. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7956. (save-match-data
  7957. (let ((match-index 1)
  7958. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7959. (set-match-data link-match-data)
  7960. (while (<= match-index number-of-groups)
  7961. (let ((regex (concat "%" (number-to-string match-index)))
  7962. (replace-with (match-string match-index dlink)))
  7963. (while (string-match regex cmd)
  7964. (setq cmd (replace-match replace-with t t cmd))))
  7965. (setq match-index (+ match-index 1)))))
  7966. (save-window-excursion
  7967. (message "Running %s...done" cmd)
  7968. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7969. ;; and exit immediately. Use pipe connection type instead of pty to
  7970. ;; avoid killing children processes with SIGHUP when temporary terminal
  7971. ;; session is finished.
  7972. ;;
  7973. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7974. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7975. ;; error messages.
  7976. (let ((process-connection-type nil))
  7977. (start-process-shell-command cmd nil cmd))
  7978. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7979. ((or (stringp cmd)
  7980. (eq cmd 'emacs))
  7981. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7982. (widen)
  7983. (cond (line (org-goto-line line)
  7984. (when (derived-mode-p 'org-mode) (org-reveal)))
  7985. (search (condition-case err
  7986. (org-link-search search)
  7987. ;; Save position before error-ing out so user
  7988. ;; can easily move back to the original buffer.
  7989. (error (funcall save-position-maybe)
  7990. (error (nth 1 err)))))))
  7991. ((functionp cmd)
  7992. (save-match-data
  7993. (set-match-data link-match-data)
  7994. (condition-case nil
  7995. (funcall cmd file link)
  7996. ;; FIXME: Remove this check when most default installations
  7997. ;; of Emacs have at least Org 9.0.
  7998. ((debug wrong-number-of-arguments wrong-type-argument
  7999. invalid-function)
  8000. (user-error "Please see Org News for version 9.0 about \
  8001. `org-file-apps'--Lisp error: %S" cmd)))))
  8002. ((consp cmd)
  8003. ;; FIXME: Remove this check when most default installations of
  8004. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  8005. ;; fall back to `org-link-frame-setup' for an old usage of
  8006. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  8007. (user-error "Please see Org News for version 9.0 about \
  8008. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  8009. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  8010. (funcall save-position-maybe)))
  8011. ;;;###autoload
  8012. (defun org-open-at-point-global ()
  8013. "Follow a link or a time-stamp like Org mode does.
  8014. Also follow links and emails as seen by `thing-at-point'.
  8015. This command can be called in any mode to follow an external
  8016. link or a time-stamp that has Org mode syntax. Its behavior
  8017. is undefined when called on internal links like fuzzy links.
  8018. Raise a user error when there is nothing to follow."
  8019. (interactive)
  8020. (let ((tap-url (thing-at-point 'url))
  8021. (tap-email (thing-at-point 'email)))
  8022. (cond ((org-in-regexp org-link-any-re)
  8023. (org-link-open-from-string (match-string-no-properties 0)))
  8024. ((or (org-in-regexp org-ts-regexp-both nil t)
  8025. (org-in-regexp org-tsr-regexp-both nil t))
  8026. (org-follow-timestamp-link))
  8027. (tap-url (org-link-open-from-string tap-url))
  8028. (tap-email (org-link-open-from-string
  8029. (concat "mailto:" tap-email)))
  8030. (t (user-error "No link found")))))
  8031. (defvar org-open-at-point-functions nil
  8032. "Hook that is run when following a link at point.
  8033. Functions in this hook must return t if they identify and follow
  8034. a link at point. If they don't find anything interesting at point,
  8035. they must return nil.")
  8036. (defun org-open-at-point (&optional arg)
  8037. "Open link, timestamp, footnote or tags at point.
  8038. When point is on a link, follow it. Normally, files will be
  8039. opened by an appropriate application. If the optional prefix
  8040. argument ARG is non-nil, Emacs will visit the file. With
  8041. a double prefix argument, try to open outside of Emacs, in the
  8042. application the system uses for this file type.
  8043. When point is on a timestamp, open the agenda at the day
  8044. specified.
  8045. When point is a footnote definition, move to the first reference
  8046. found. If it is on a reference, move to the associated
  8047. definition.
  8048. When point is on a headline, display a list of every link in the
  8049. entry, so it is possible to pick one, or all, of them. If point
  8050. is on a tag, call `org-tags-view' instead.
  8051. On top of syntactically correct links, this function also tries
  8052. to open links and time-stamps in comments, node properties, and
  8053. keywords if point is on something looking like a timestamp or
  8054. a link."
  8055. (interactive "P")
  8056. (org-load-modules-maybe)
  8057. (setq org-window-config-before-follow-link (current-window-configuration))
  8058. (org-remove-occur-highlights nil nil t)
  8059. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8060. (let* ((context
  8061. ;; Only consider supported types, even if they are not the
  8062. ;; closest one.
  8063. (org-element-lineage
  8064. (org-element-context)
  8065. '(citation citation-reference clock comment comment-block
  8066. footnote-definition footnote-reference headline
  8067. inline-src-block inlinetask keyword link node-property
  8068. planning src-block timestamp)
  8069. t))
  8070. (type (org-element-type context))
  8071. (value (org-element-property :value context)))
  8072. (cond
  8073. ((not type) (user-error "No link found"))
  8074. ;; No valid link at point. For convenience, look if something
  8075. ;; looks like a link under point in some specific places.
  8076. ((memq type '(comment comment-block node-property keyword))
  8077. (call-interactively #'org-open-at-point-global))
  8078. ;; On a headline or an inlinetask, but not on a timestamp,
  8079. ;; a link, a footnote reference or a citation.
  8080. ((memq type '(headline inlinetask))
  8081. (org-match-line org-complex-heading-regexp)
  8082. (let ((tags-beg (match-beginning 5))
  8083. (tags-end (match-end 5)))
  8084. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  8085. ;; On tags.
  8086. (org-tags-view
  8087. arg
  8088. (save-excursion
  8089. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  8090. (end-tag (search-forward ":" tags-end nil 2)))
  8091. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  8092. ;; Not on tags.
  8093. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  8094. (`(nil . ,_)
  8095. (require 'org-attach)
  8096. (when (org-attach-dir)
  8097. (message "Opening attachment")
  8098. (if (equal arg '(4))
  8099. (org-attach-reveal-in-emacs)
  8100. (org-attach-reveal))))
  8101. (`(,links . ,links-end)
  8102. (dolist (link (if (stringp links) (list links) links))
  8103. (search-forward link nil links-end)
  8104. (goto-char (match-beginning 0))
  8105. (org-open-at-point arg)))))))
  8106. ;; On a footnote reference or at definition's label.
  8107. ((or (eq type 'footnote-reference)
  8108. (and (eq type 'footnote-definition)
  8109. (save-excursion
  8110. ;; Do not validate action when point is on the
  8111. ;; spaces right after the footnote label, in order
  8112. ;; to be on par with behavior on links.
  8113. (skip-chars-forward " \t")
  8114. (let ((begin
  8115. (org-element-property :contents-begin context)))
  8116. (if begin (< (point) begin)
  8117. (= (org-element-property :post-affiliated context)
  8118. (line-beginning-position)))))))
  8119. (org-footnote-action))
  8120. ;; On a planning line. Check if we are really on a timestamp.
  8121. ((and (eq type 'planning)
  8122. (org-in-regexp org-ts-regexp-both nil t))
  8123. (org-follow-timestamp-link))
  8124. ;; On a clock line, make sure point is on the timestamp
  8125. ;; before opening it.
  8126. ((and (eq type 'clock)
  8127. value
  8128. (>= (point) (org-element-property :begin value))
  8129. (<= (point) (org-element-property :end value)))
  8130. (org-follow-timestamp-link))
  8131. ((eq type 'src-block) (org-babel-open-src-block-result))
  8132. ;; Do nothing on white spaces after an object.
  8133. ((>= (point)
  8134. (save-excursion
  8135. (goto-char (org-element-property :end context))
  8136. (skip-chars-backward " \t")
  8137. (point)))
  8138. (user-error "No link found"))
  8139. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8140. ((eq type 'timestamp) (org-follow-timestamp-link))
  8141. ((eq type 'link) (org-link-open context arg))
  8142. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  8143. (t (user-error "No link found")))))
  8144. (run-hook-with-args 'org-follow-link-hook))
  8145. ;;;###autoload
  8146. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8147. "Offer links in the current entry and return the selected link.
  8148. If there is only one link, return it.
  8149. If NTH is an integer, return the NTH link found.
  8150. If ZERO is a string, check also this string for a link, and if
  8151. there is one, return it."
  8152. (with-current-buffer buffer
  8153. (org-with-wide-buffer
  8154. (goto-char marker)
  8155. (let ((cnt ?0)
  8156. have-zero end links link c)
  8157. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8158. (push (match-string 0 zero) links)
  8159. (setq cnt (1- cnt) have-zero t))
  8160. (save-excursion
  8161. (org-back-to-heading t)
  8162. (setq end (save-excursion (outline-next-heading) (point)))
  8163. (while (re-search-forward org-link-any-re end t)
  8164. (push (match-string 0) links))
  8165. (setq links (org-uniquify (reverse links))))
  8166. (cond
  8167. ((null links)
  8168. (message "No links"))
  8169. ((equal (length links) 1)
  8170. (setq link (car links)))
  8171. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8172. (setq link (nth (if have-zero nth (1- nth)) links)))
  8173. (t ; we have to select a link
  8174. (save-excursion
  8175. (save-window-excursion
  8176. (delete-other-windows)
  8177. (with-output-to-temp-buffer "*Select Link*"
  8178. (dolist (l links)
  8179. (cond
  8180. ((not (string-match org-link-bracket-re l))
  8181. (princ (format "[%c] %s\n" (cl-incf cnt)
  8182. (org-unbracket-string "<" ">" l))))
  8183. ((match-end 2)
  8184. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8185. (match-string 2 l) (match-string 1 l))))
  8186. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8187. (match-string 1 l)))))))
  8188. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8189. (message "Select link to open, RET to open all:")
  8190. (setq c (read-char-exclusive))
  8191. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8192. (when (equal c ?q) (user-error "Abort"))
  8193. (if (equal c ?\C-m)
  8194. (setq link links)
  8195. (setq nth (- c ?0))
  8196. (when have-zero (setq nth (1+ nth)))
  8197. (unless (and (integerp nth) (>= (length links) nth))
  8198. (user-error "Invalid link selection"))
  8199. (setq link (nth (1- nth) links)))))
  8200. (cons link end)))))
  8201. ;;; File search
  8202. (defun org-do-occur (regexp &optional cleanup)
  8203. "Call the Emacs command `occur'.
  8204. If CLEANUP is non-nil, remove the printout of the regular expression
  8205. in the *Occur* buffer. This is useful if the regex is long and not useful
  8206. to read."
  8207. (occur regexp)
  8208. (when cleanup
  8209. (let ((cwin (selected-window)) win beg end)
  8210. (when (setq win (get-buffer-window "*Occur*"))
  8211. (select-window win))
  8212. (goto-char (point-min))
  8213. (when (re-search-forward "match[a-z]+" nil t)
  8214. (setq beg (match-end 0))
  8215. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8216. (setq end (1- (match-beginning 0)))))
  8217. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8218. (goto-char (point-min))
  8219. (select-window cwin))))
  8220. ;;; The Mark Ring
  8221. (defvar org-mark-ring nil
  8222. "Mark ring for positions before jumps in Org mode.")
  8223. (defvar org-mark-ring-last-goto nil
  8224. "Last position in the mark ring used to go back.")
  8225. ;; Fill and close the ring
  8226. (setq org-mark-ring nil)
  8227. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8228. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8229. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8230. org-mark-ring)
  8231. (defun org-mark-ring-push (&optional pos buffer)
  8232. "Put the current position into the mark ring and rotate it.
  8233. Also push position into the Emacs mark ring. If optional
  8234. argument POS and BUFFER are not nil, mark this location instead."
  8235. (interactive)
  8236. (let ((pos (or pos (point)))
  8237. (buffer (or buffer (current-buffer))))
  8238. (with-current-buffer buffer
  8239. (org-with-point-at pos (push-mark nil t)))
  8240. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8241. (move-marker (car org-mark-ring) pos buffer))
  8242. (message
  8243. (substitute-command-keys
  8244. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8245. (defun org-mark-ring-goto (&optional n)
  8246. "Jump to the previous position in the mark ring.
  8247. With prefix arg N, jump back that many stored positions. When
  8248. called several times in succession, walk through the entire ring.
  8249. Org mode commands jumping to a different position in the current file,
  8250. or to another Org file, automatically push the old position onto the ring."
  8251. (interactive "p")
  8252. (let (p m)
  8253. (if (eq last-command this-command)
  8254. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8255. (setq p org-mark-ring))
  8256. (setq org-mark-ring-last-goto p)
  8257. (setq m (car p))
  8258. (pop-to-buffer-same-window (marker-buffer m))
  8259. (goto-char m)
  8260. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8261. ;;; Following specific links
  8262. (defvar org-agenda-buffer-tmp-name)
  8263. (defvar org-agenda-start-on-weekday)
  8264. (defvar org-agenda-buffer-name)
  8265. (defun org-follow-timestamp-link ()
  8266. "Open an agenda view for the time-stamp date/range at point."
  8267. ;; Avoid changing the global value.
  8268. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  8269. (cond
  8270. ((org-at-date-range-p t)
  8271. (let ((org-agenda-start-on-weekday)
  8272. (t1 (match-string 1))
  8273. (t2 (match-string 2)) tt1 tt2)
  8274. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8275. tt2 (time-to-days (org-time-string-to-time t2)))
  8276. (let ((org-agenda-buffer-tmp-name
  8277. (format "*Org Agenda(a:%s)"
  8278. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8279. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8280. ((org-at-timestamp-p 'lax)
  8281. (let ((org-agenda-buffer-tmp-name
  8282. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8283. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8284. (substring (match-string 1) 0 10)))
  8285. 1)))
  8286. (t (error "This should not happen")))))
  8287. ;;; Following file links
  8288. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8289. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8290. (declare-function mailcap-mime-info
  8291. "mailcap" (string &optional request no-decode))
  8292. (defvar org-wait nil)
  8293. ;;;; Refiling
  8294. (defun org-get-org-file ()
  8295. "Read a filename, with default directory `org-directory'."
  8296. (let ((default (or org-default-notes-file remember-data-file)))
  8297. (read-file-name (format "File name [%s]: " default)
  8298. (file-name-as-directory org-directory)
  8299. default)))
  8300. (defun org-notes-order-reversed-p ()
  8301. "Check if the current file should receive notes in reversed order."
  8302. (cond
  8303. ((not org-reverse-note-order) nil)
  8304. ((eq t org-reverse-note-order) t)
  8305. ((not (listp org-reverse-note-order)) nil)
  8306. (t (catch 'exit
  8307. (dolist (entry org-reverse-note-order)
  8308. (when (string-match (car entry) buffer-file-name)
  8309. (throw 'exit (cdr entry))))))))
  8310. (defvar org-agenda-new-buffers nil
  8311. "Buffers created to visit agenda files.")
  8312. (declare-function org-string-nw-p "org-macs" (s))
  8313. ;;;; Dynamic blocks
  8314. (defun org-find-dblock (name)
  8315. "Find the first dynamic block with name NAME in the buffer.
  8316. If not found, stay at current position and return nil."
  8317. (let ((case-fold-search t) pos)
  8318. (save-excursion
  8319. (goto-char (point-min))
  8320. (setq pos (and (re-search-forward
  8321. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8322. (match-beginning 0))))
  8323. (when pos (goto-char pos))
  8324. pos))
  8325. (defun org-create-dblock (plist)
  8326. "Create a dynamic block section, with parameters taken from PLIST.
  8327. PLIST must contain a :name entry which is used as the name of the block."
  8328. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8329. (end-of-line 1)
  8330. (newline))
  8331. (let ((col (current-column))
  8332. (name (plist-get plist :name)))
  8333. (insert "#+BEGIN: " name)
  8334. (while plist
  8335. (if (eq (car plist) :name)
  8336. (setq plist (cddr plist))
  8337. (insert " " (prin1-to-string (pop plist)))))
  8338. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8339. (beginning-of-line -2)))
  8340. (defun org-prepare-dblock ()
  8341. "Prepare dynamic block for refresh.
  8342. This empties the block, puts the cursor at the insert position and returns
  8343. the property list including an extra property :name with the block name."
  8344. (unless (looking-at org-dblock-start-re)
  8345. (user-error "Not at a dynamic block"))
  8346. (let* ((begdel (1+ (match-end 0)))
  8347. (name (org-no-properties (match-string 1)))
  8348. (params (append (list :name name)
  8349. (read (concat "(" (match-string 3) ")")))))
  8350. (save-excursion
  8351. (beginning-of-line 1)
  8352. (skip-chars-forward " \t")
  8353. (setq params (plist-put params :indentation-column (current-column))))
  8354. (unless (re-search-forward org-dblock-end-re nil t)
  8355. (error "Dynamic block not terminated"))
  8356. (setq params
  8357. (append params
  8358. (list :content (buffer-substring
  8359. begdel (match-beginning 0)))))
  8360. (delete-region begdel (match-beginning 0))
  8361. (goto-char begdel)
  8362. (open-line 1)
  8363. params))
  8364. (defun org-map-dblocks (&optional command)
  8365. "Apply COMMAND to all dynamic blocks in the current buffer.
  8366. If COMMAND is not given, use `org-update-dblock'."
  8367. (let ((cmd (or command 'org-update-dblock)))
  8368. (save-excursion
  8369. (goto-char (point-min))
  8370. (while (re-search-forward org-dblock-start-re nil t)
  8371. (goto-char (match-beginning 0))
  8372. (save-excursion
  8373. (condition-case nil
  8374. (funcall cmd)
  8375. (error (message "Error during update of dynamic block"))))
  8376. (unless (re-search-forward org-dblock-end-re nil t)
  8377. (error "Dynamic block not terminated"))))))
  8378. (defvar org-dynamic-block-alist nil
  8379. "Alist defining all the Org dynamic blocks.
  8380. The key is the dynamic block type name, as a string. The value
  8381. is the function used to insert the dynamic block.
  8382. Use `org-dynamic-block-define' to populate it.")
  8383. (defun org-dynamic-block-function (type)
  8384. "Return function associated to a given dynamic block type.
  8385. TYPE is the dynamic block type, as a string."
  8386. (cdr (assoc type org-dynamic-block-alist)))
  8387. (defun org-dynamic-block-types ()
  8388. "List all defined dynamic block types."
  8389. (mapcar #'car org-dynamic-block-alist))
  8390. (defun org-dynamic-block-define (type func)
  8391. "Define dynamic block TYPE with FUNC.
  8392. TYPE is a string. FUNC is the function creating the dynamic
  8393. block of such type."
  8394. (pcase (assoc type org-dynamic-block-alist)
  8395. (`nil (push (cons type func) org-dynamic-block-alist))
  8396. (def (setcdr def func))))
  8397. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8398. "Insert a dynamic block of type TYPE.
  8399. When used interactively, select the dynamic block types among
  8400. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8401. is non-nil, call the dynamic block function interactively."
  8402. (interactive (list (completing-read "Dynamic block: "
  8403. (org-dynamic-block-types))
  8404. t))
  8405. (pcase (org-dynamic-block-function type)
  8406. (`nil (error "No such dynamic block: %S" type))
  8407. ((and f (pred functionp))
  8408. (if interactive-p (call-interactively f) (funcall f)))
  8409. (_ (error "Invalid function for dynamic block %S" type))))
  8410. (defun org-dblock-update (&optional arg)
  8411. "User command for updating dynamic blocks.
  8412. Update the dynamic block at point. With prefix ARG, update all dynamic
  8413. blocks in the buffer."
  8414. (interactive "P")
  8415. (if arg
  8416. (org-update-all-dblocks)
  8417. (or (looking-at org-dblock-start-re)
  8418. (org-beginning-of-dblock))
  8419. (org-update-dblock)))
  8420. (defun org-update-dblock ()
  8421. "Update the dynamic block at point.
  8422. This means to empty the block, parse for parameters and then call
  8423. the correct writing function."
  8424. (interactive)
  8425. (save-excursion
  8426. (let* ((win (selected-window))
  8427. (pos (point))
  8428. (line (org-current-line))
  8429. (params (org-prepare-dblock))
  8430. (name (plist-get params :name))
  8431. (indent (plist-get params :indentation-column))
  8432. (cmd (intern (concat "org-dblock-write:" name))))
  8433. (message "Updating dynamic block `%s' at line %d..." name line)
  8434. (funcall cmd params)
  8435. (message "Updating dynamic block `%s' at line %d...done" name line)
  8436. (goto-char pos)
  8437. (when (and indent (> indent 0))
  8438. (setq indent (make-string indent ?\ ))
  8439. (save-excursion
  8440. (select-window win)
  8441. (org-beginning-of-dblock)
  8442. (forward-line 1)
  8443. (while (not (looking-at org-dblock-end-re))
  8444. (insert indent)
  8445. (beginning-of-line 2))
  8446. (when (looking-at org-dblock-end-re)
  8447. (and (looking-at "[ \t]+")
  8448. (replace-match ""))
  8449. (insert indent)))))))
  8450. (defun org-beginning-of-dblock ()
  8451. "Find the beginning of the dynamic block at point.
  8452. Error if there is no such block at point."
  8453. (let ((pos (point))
  8454. beg)
  8455. (end-of-line 1)
  8456. (if (and (re-search-backward org-dblock-start-re nil t)
  8457. (setq beg (match-beginning 0))
  8458. (re-search-forward org-dblock-end-re nil t)
  8459. (> (match-end 0) pos))
  8460. (goto-char beg)
  8461. (goto-char pos)
  8462. (error "Not in a dynamic block"))))
  8463. (defun org-update-all-dblocks ()
  8464. "Update all dynamic blocks in the buffer.
  8465. This function can be used in a hook."
  8466. (interactive)
  8467. (when (derived-mode-p 'org-mode)
  8468. (org-map-dblocks 'org-update-dblock)))
  8469. ;;;; Completion
  8470. (declare-function org-export-backend-options "ox" (cl-x) t)
  8471. (defun org-get-export-keywords ()
  8472. "Return a list of all currently understood export keywords.
  8473. Export keywords include options, block names, attributes and
  8474. keywords relative to each registered export back-end."
  8475. (let (keywords)
  8476. (dolist (backend
  8477. (bound-and-true-p org-export-registered-backends)
  8478. (delq nil keywords))
  8479. ;; Back-end name (for keywords, like #+LATEX:)
  8480. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8481. (dolist (option-entry (org-export-backend-options backend))
  8482. ;; Back-end options.
  8483. (push (nth 1 option-entry) keywords)))))
  8484. (defconst org-options-keywords
  8485. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8486. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8487. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8488. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8489. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8490. (defcustom org-structure-template-alist
  8491. '(("a" . "export ascii")
  8492. ("c" . "center")
  8493. ("C" . "comment")
  8494. ("e" . "example")
  8495. ("E" . "export")
  8496. ("h" . "export html")
  8497. ("l" . "export latex")
  8498. ("q" . "quote")
  8499. ("s" . "src")
  8500. ("v" . "verse"))
  8501. "An alist of keys and block types.
  8502. `org-insert-structure-template' will display a menu with this
  8503. list of templates to choose from. The block type is inserted,
  8504. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8505. The menu keys are defined by the car of each entry in this alist.
  8506. If two entries have the keys \"a\" and \"aa\" respectively, the
  8507. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8508. latter will be inserted by typing \"aa\". If an entry with the
  8509. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8510. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8511. block can be inserted by pressing TAB after the string \"<KEY\"."
  8512. :group 'org-edit-structure
  8513. :type '(repeat
  8514. (cons (string :tag "Key")
  8515. (string :tag "Template")))
  8516. :package-version '(Org . "9.2"))
  8517. (defun org--check-org-structure-template-alist (&optional checklist)
  8518. "Check whether `org-structure-template-alist' is set up correctly.
  8519. In particular, check if the Org 9.2 format is used as opposed to
  8520. previous format."
  8521. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8522. (or (eval checklist)
  8523. org-structure-template-alist))))
  8524. (when elm
  8525. (org-display-warning
  8526. (format "
  8527. Please update the entries of `%s'.
  8528. In Org 9.2 the format was changed from something like
  8529. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8530. to something like
  8531. (\"s\" . \"src\")
  8532. Please refer to the documentation of `org-structure-template-alist'.
  8533. The following entries must be updated:
  8534. %s"
  8535. (or checklist 'org-structure-template-alist)
  8536. (pp-to-string elm))))))
  8537. (defun org--insert-structure-template-mks ()
  8538. "Present `org-structure-template-alist' with `org-mks'.
  8539. Menus are added if keys require more than one keystroke. Tabs
  8540. are added to single key entries when more than one stroke is
  8541. needed. Keys longer than two characters are reduced to two
  8542. characters."
  8543. (org--check-org-structure-template-alist)
  8544. (let* (case-fold-search
  8545. (templates (append org-structure-template-alist
  8546. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8547. (keys (mapcar #'car templates))
  8548. (start-letters
  8549. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8550. ;; Sort each element of `org-structure-template-alist' into
  8551. ;; sublists according to the first letter.
  8552. (superlist
  8553. (mapcar (lambda (letter)
  8554. (list letter
  8555. (cl-remove-if-not
  8556. (apply-partially #'string-match-p (concat "^" letter))
  8557. templates :key #'car)))
  8558. start-letters)))
  8559. (org-mks
  8560. (apply #'append
  8561. ;; Make an `org-mks' table. If only one element is
  8562. ;; present in a sublist, make it part of the top-menu,
  8563. ;; otherwise make a submenu according to the starting
  8564. ;; letter and populate it.
  8565. (mapcar (lambda (sublist)
  8566. (if (eq 1 (length (cadr sublist)))
  8567. (mapcar (lambda (elm)
  8568. (list (substring (car elm) 0 1)
  8569. (cdr elm) ""))
  8570. (cadr sublist))
  8571. ;; Create submenu.
  8572. (let* ((topkey (car sublist))
  8573. (elms (cadr sublist))
  8574. (keys (mapcar #'car elms))
  8575. (long (> (length elms) 3)))
  8576. (append
  8577. (list
  8578. ;; Make a description of the submenu.
  8579. (list topkey
  8580. (concat
  8581. (mapconcat #'cdr
  8582. (cl-subseq elms 0 (if long 3 (length elms)))
  8583. ", ")
  8584. (when long ", ..."))))
  8585. ;; List of entries in submenu.
  8586. (cl-mapcar #'list
  8587. (org--insert-structure-template-unique-keys keys)
  8588. (mapcar #'cdr elms)
  8589. (make-list (length elms) ""))))))
  8590. superlist))
  8591. "Select a key\n============"
  8592. "Key: ")))
  8593. (defun org--insert-structure-template-unique-keys (keys)
  8594. "Make a list of unique, two characters long elements from KEYS.
  8595. Elements of length one have a tab appended. Elements of length
  8596. two are kept as is. Longer elements are truncated to length two.
  8597. If an element cannot be made unique, an error is raised."
  8598. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8599. menu-keys)
  8600. (dolist (key ordered-keys)
  8601. (let ((potential-key
  8602. (cl-case (length key)
  8603. (1 (concat key "\t"))
  8604. (2 key)
  8605. (otherwise
  8606. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8607. (mapcar (apply-partially #'concat (substring key 0 1))
  8608. (split-string (substring key 1) "" t)))))))
  8609. (if (or (not potential-key) (assoc potential-key menu-keys))
  8610. (user-error "Could not make unique key for `%s'" key)
  8611. (push (cons potential-key key) menu-keys))))
  8612. (mapcar #'car
  8613. (cl-sort menu-keys #'<
  8614. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8615. (defun org-insert-structure-template (type)
  8616. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8617. Select a block from `org-structure-template-alist' then type
  8618. either RET, TAB or SPC to write the block type. With an active
  8619. region, wrap the region in the block. Otherwise, insert an empty
  8620. block."
  8621. (interactive
  8622. (list (pcase (org--insert-structure-template-mks)
  8623. (`("\t" . ,_) (read-string "Structure type: "))
  8624. (`(,_ ,choice . ,_) choice))))
  8625. (let* ((region? (use-region-p))
  8626. (region-start (and region? (region-beginning)))
  8627. (region-end (and region? (copy-marker (region-end))))
  8628. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8629. (verbatim? (string-match-p
  8630. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8631. type)))
  8632. (when region? (goto-char region-start))
  8633. (let ((column (current-indentation)))
  8634. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8635. (beginning-of-line)
  8636. (insert "\n"))
  8637. (save-excursion
  8638. (indent-to column)
  8639. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8640. (when region?
  8641. (when verbatim? (org-escape-code-in-region (point) region-end))
  8642. (goto-char region-end)
  8643. ;; Ignore empty lines at the end of the region.
  8644. (skip-chars-backward " \r\t\n")
  8645. (end-of-line))
  8646. (unless (bolp) (insert "\n"))
  8647. (indent-to column)
  8648. (insert (format "#+end_%s" (car (split-string type))))
  8649. (if (looking-at "[ \t]*$") (replace-match "")
  8650. (insert "\n"))
  8651. (when (and (eobp) (not (bolp))) (insert "\n")))
  8652. (if extended? (end-of-line)
  8653. (forward-line)
  8654. (skip-chars-forward " \t")))))
  8655. ;;;; TODO, DEADLINE, Comments
  8656. (defun org-toggle-comment ()
  8657. "Change the COMMENT state of an entry."
  8658. (interactive)
  8659. (save-excursion
  8660. (org-back-to-heading)
  8661. (let ((case-fold-search nil))
  8662. (looking-at org-complex-heading-regexp))
  8663. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8664. (skip-chars-forward " \t")
  8665. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8666. (if (org-in-commented-heading-p t)
  8667. (delete-region (point)
  8668. (progn (search-forward " " (line-end-position) 'move)
  8669. (skip-chars-forward " \t")
  8670. (point)))
  8671. (insert org-comment-string)
  8672. (unless (eolp) (insert " ")))))
  8673. (defvar org-last-todo-state-is-todo nil
  8674. "This is non-nil when the last TODO state change led to a TODO state.
  8675. If the last change removed the TODO tag or switched to DONE, then
  8676. this is nil.")
  8677. (defvar org-todo-setup-filter-hook nil
  8678. "Hook for functions that pre-filter todo specs.
  8679. Each function takes a todo spec and returns either nil or the spec
  8680. transformed into canonical form." )
  8681. (defvar org-todo-get-default-hook nil
  8682. "Hook for functions that get a default item for todo.
  8683. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8684. nil or a string to be used for the todo mark." )
  8685. (defvar org-agenda-headline-snapshot-before-repeat)
  8686. (defun org-current-effective-time ()
  8687. "Return current time adjusted for `org-extend-today-until' variable."
  8688. (let* ((ct (org-current-time))
  8689. (dct (decode-time ct))
  8690. (ct1
  8691. (cond
  8692. (org-use-last-clock-out-time-as-effective-time
  8693. (or (org-clock-get-last-clock-out-time) ct))
  8694. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8695. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8696. (t ct))))
  8697. ct1))
  8698. (defun org-todo-yesterday (&optional arg)
  8699. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8700. (interactive "P")
  8701. (if (eq major-mode 'org-agenda-mode)
  8702. (apply 'org-agenda-todo-yesterday arg)
  8703. (let* ((org-use-effective-time t)
  8704. (hour (nth 2 (decode-time (org-current-time))))
  8705. (org-extend-today-until (1+ hour)))
  8706. (org-todo arg))))
  8707. (defvar org-block-entry-blocking ""
  8708. "First entry preventing the TODO state change.")
  8709. (defun org-cancel-repeater ()
  8710. "Cancel a repeater by setting its numeric value to zero."
  8711. (interactive)
  8712. (save-excursion
  8713. (org-back-to-heading t)
  8714. (let ((bound1 (point))
  8715. (bound0 (save-excursion (outline-next-heading) (point))))
  8716. (when (and (re-search-forward
  8717. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8718. org-deadline-time-regexp "\\)\\|\\("
  8719. org-ts-regexp "\\)")
  8720. bound0 t)
  8721. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8722. bound1 t))
  8723. (replace-match "0" t nil nil 1)))))
  8724. (defvar org-state)
  8725. (defvar org-blocked-by-checkboxes)
  8726. (defun org-todo (&optional arg)
  8727. "Change the TODO state of an item.
  8728. The state of an item is given by a keyword at the start of the heading,
  8729. like
  8730. *** TODO Write paper
  8731. *** DONE Call mom
  8732. The different keywords are specified in the variable `org-todo-keywords'.
  8733. By default the available states are \"TODO\" and \"DONE\". So, for this
  8734. example: when the item starts with TODO, it is changed to DONE.
  8735. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8736. DONE are present, add TODO at the beginning of the heading.
  8737. You can set up single-character keys to fast-select the new state. See the
  8738. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8739. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8740. and take a
  8741. logging note.
  8742. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8743. next set of TODO \
  8744. keywords (nextset).
  8745. Another way to achieve this is `S-C-<right>'.
  8746. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8747. prefix, circumvent any state blocking.
  8748. With numeric prefix arg, switch to the Nth state.
  8749. With a numeric prefix arg of 0, inhibit note taking for the change.
  8750. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8751. When called through ELisp, arg is also interpreted in the following way:
  8752. `none' -> empty state
  8753. \"\" -> switch to empty state
  8754. `done' -> switch to DONE
  8755. `nextset' -> switch to the next set of keywords
  8756. `previousset' -> switch to the previous set of keywords
  8757. \"WAITING\" -> switch to the specified keyword, but only if it
  8758. really is a member of `org-todo-keywords'."
  8759. (interactive "P")
  8760. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8761. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8762. 'region-start-level 'region))
  8763. org-loop-over-headlines-in-active-region)
  8764. (org-map-entries
  8765. (lambda () (org-todo arg))
  8766. nil cl
  8767. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8768. (when (equal arg '(16)) (setq arg 'nextset))
  8769. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8770. (let ((org-blocker-hook org-blocker-hook)
  8771. commentp
  8772. case-fold-search)
  8773. (when (equal arg '(64))
  8774. (setq arg nil org-blocker-hook nil))
  8775. (when (and org-blocker-hook
  8776. (or org-inhibit-blocking
  8777. (org-entry-get nil "NOBLOCKING")))
  8778. (setq org-blocker-hook nil))
  8779. (save-excursion
  8780. (catch 'exit
  8781. (org-back-to-heading t)
  8782. (when (org-in-commented-heading-p t)
  8783. (org-toggle-comment)
  8784. (setq commentp t))
  8785. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8786. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8787. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8788. (let* ((match-data (match-data))
  8789. (startpos (copy-marker (line-beginning-position)))
  8790. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8791. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8792. (org-log-done org-log-done)
  8793. (org-log-repeat org-log-repeat)
  8794. (org-todo-log-states org-todo-log-states)
  8795. (org-inhibit-logging
  8796. (if (equal arg 0)
  8797. (progn (setq arg nil) 'note) org-inhibit-logging))
  8798. (this (match-string 1))
  8799. (hl-pos (match-beginning 0))
  8800. (head (org-get-todo-sequence-head this))
  8801. (ass (assoc head org-todo-kwd-alist))
  8802. (interpret (nth 1 ass))
  8803. (done-word (nth 3 ass))
  8804. (final-done-word (nth 4 ass))
  8805. (org-last-state (or this ""))
  8806. (completion-ignore-case t)
  8807. (member (member this org-todo-keywords-1))
  8808. (tail (cdr member))
  8809. (org-state (cond
  8810. ((eq arg 'right)
  8811. ;; Next state
  8812. (if this
  8813. (if tail (car tail) nil)
  8814. (car org-todo-keywords-1)))
  8815. ((eq arg 'left)
  8816. ;; Previous state
  8817. (unless (equal member org-todo-keywords-1)
  8818. (if this
  8819. (nth (- (length org-todo-keywords-1)
  8820. (length tail) 2)
  8821. org-todo-keywords-1)
  8822. (org-last org-todo-keywords-1))))
  8823. (arg
  8824. ;; User or caller requests a specific state.
  8825. (cond
  8826. ((equal arg "") nil)
  8827. ((eq arg 'none) nil)
  8828. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8829. ((eq arg 'nextset)
  8830. (or (car (cdr (member head org-todo-heads)))
  8831. (car org-todo-heads)))
  8832. ((eq arg 'previousset)
  8833. (let ((org-todo-heads (reverse org-todo-heads)))
  8834. (or (car (cdr (member head org-todo-heads)))
  8835. (car org-todo-heads))))
  8836. ((car (member arg org-todo-keywords-1)))
  8837. ((stringp arg)
  8838. (user-error "State `%s' not valid in this file" arg))
  8839. ((nth (1- (prefix-numeric-value arg))
  8840. org-todo-keywords-1))))
  8841. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8842. ;; Use fast selection.
  8843. (org-fast-todo-selection this))
  8844. ((null member) (or head (car org-todo-keywords-1)))
  8845. ((equal this final-done-word) nil) ;-> make empty
  8846. ((null tail) nil) ;-> first entry
  8847. ((memq interpret '(type priority))
  8848. (if (eq this-command last-command)
  8849. (car tail)
  8850. (if (> (length tail) 0)
  8851. (or done-word (car org-done-keywords))
  8852. nil)))
  8853. (t
  8854. (car tail))))
  8855. (org-state (or
  8856. (run-hook-with-args-until-success
  8857. 'org-todo-get-default-hook org-state org-last-state)
  8858. org-state))
  8859. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8860. (change-plist (list :type 'todo-state-change :from this :to org-state
  8861. :position startpos))
  8862. dolog now-done-p)
  8863. (when org-blocker-hook
  8864. (let (org-blocked-by-checkboxes block-reason)
  8865. (setq org-last-todo-state-is-todo
  8866. (not (member this org-done-keywords)))
  8867. (unless (save-excursion
  8868. (save-match-data
  8869. (org-with-wide-buffer
  8870. (run-hook-with-args-until-failure
  8871. 'org-blocker-hook change-plist))))
  8872. (setq block-reason (if org-blocked-by-checkboxes
  8873. "contained checkboxes"
  8874. (format "\"%s\"" org-block-entry-blocking)))
  8875. (if (called-interactively-p 'interactive)
  8876. (user-error "TODO state change from %s to %s blocked (by %s)"
  8877. this org-state block-reason)
  8878. ;; Fail silently.
  8879. (message "TODO state change from %s to %s blocked (by %s)"
  8880. this org-state block-reason)
  8881. (throw 'exit nil)))))
  8882. (store-match-data match-data)
  8883. (replace-match next t t)
  8884. (cond ((and org-state (equal this org-state))
  8885. (message "TODO state was already %s" (org-trim next)))
  8886. ((not (pos-visible-in-window-p hl-pos))
  8887. (message "TODO state changed to %s" (org-trim next))))
  8888. (unless head
  8889. (setq head (org-get-todo-sequence-head org-state)
  8890. ass (assoc head org-todo-kwd-alist)
  8891. interpret (nth 1 ass)
  8892. done-word (nth 3 ass)
  8893. final-done-word (nth 4 ass)))
  8894. (when (memq arg '(nextset previousset))
  8895. (message "Keyword-Set %d/%d: %s"
  8896. (- (length org-todo-sets) -1
  8897. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8898. (length org-todo-sets)
  8899. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8900. (setq org-last-todo-state-is-todo
  8901. (not (member org-state org-done-keywords)))
  8902. (setq now-done-p (and (member org-state org-done-keywords)
  8903. (not (member this org-done-keywords))))
  8904. (and logging (org-local-logging logging))
  8905. (when (or (and (or org-todo-log-states org-log-done)
  8906. (not (eq org-inhibit-logging t))
  8907. (not (memq arg '(nextset previousset))))
  8908. force-log)
  8909. ;; We need to look at recording a time and note.
  8910. (setq dolog (or (if force-log 'note)
  8911. (nth 1 (assoc org-state org-todo-log-states))
  8912. (nth 2 (assoc this org-todo-log-states))))
  8913. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8914. (setq dolog 'time))
  8915. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8916. (and org-state
  8917. (member org-state org-not-done-keywords)
  8918. (not (member this org-not-done-keywords))))
  8919. ;; This is now a todo state and was not one before
  8920. ;; If there was a CLOSED time stamp, get rid of it.
  8921. (org-add-planning-info nil nil 'closed))
  8922. (when (and now-done-p org-log-done)
  8923. ;; It is now done, and it was not done before.
  8924. (org-add-planning-info 'closed (org-current-effective-time))
  8925. (when (and (not dolog) (eq 'note org-log-done))
  8926. (org-add-log-setup 'done org-state this 'note)))
  8927. (when (and org-state dolog)
  8928. ;; This is a non-nil state, and we need to log it.
  8929. (org-add-log-setup 'state org-state this dolog)))
  8930. ;; Fixup tag positioning.
  8931. (org-todo-trigger-tag-changes org-state)
  8932. (when org-auto-align-tags (org-align-tags))
  8933. (when org-provide-todo-statistics
  8934. (org-update-parent-todo-statistics))
  8935. (when (bound-and-true-p org-clock-out-when-done)
  8936. (org-clock-out-if-current))
  8937. (run-hooks 'org-after-todo-state-change-hook)
  8938. (when (and arg (not (member org-state org-done-keywords)))
  8939. (setq head (org-get-todo-sequence-head org-state)))
  8940. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8941. ;; Do we need to trigger a repeat?
  8942. (when now-done-p
  8943. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8944. ;; This is for the agenda, take a snapshot of the headline.
  8945. (save-match-data
  8946. (setq org-agenda-headline-snapshot-before-repeat
  8947. (org-get-heading))))
  8948. (org-auto-repeat-maybe org-state))
  8949. ;; Fixup cursor location if close to the keyword.
  8950. (when (and (outline-on-heading-p)
  8951. (not (bolp))
  8952. (save-excursion (beginning-of-line 1)
  8953. (looking-at org-todo-line-regexp))
  8954. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8955. (goto-char (or (match-end 2) (match-end 1)))
  8956. (and (looking-at " ")
  8957. (not (looking-at " *:"))
  8958. (just-one-space)))
  8959. (when org-trigger-hook
  8960. (save-excursion
  8961. (run-hook-with-args 'org-trigger-hook change-plist)))
  8962. (when commentp (org-toggle-comment))))))))
  8963. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8964. "Block turning an entry into a TODO, using the hierarchy.
  8965. This checks whether the current task should be blocked from state
  8966. changes. Such blocking occurs when:
  8967. 1. The task has children which are not all in a completed state.
  8968. 2. A task has a parent with the property :ORDERED:, and there
  8969. are siblings prior to the current task with incomplete
  8970. status.
  8971. 3. The parent of the task is blocked because it has siblings that should
  8972. be done first, or is child of a block grandparent TODO entry."
  8973. (if (not org-enforce-todo-dependencies)
  8974. t ; if locally turned off don't block
  8975. (catch 'dont-block
  8976. ;; If this is not a todo state change, or if this entry is already DONE,
  8977. ;; do not block
  8978. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8979. (member (plist-get change-plist :from)
  8980. (cons 'done org-done-keywords))
  8981. (member (plist-get change-plist :to)
  8982. (cons 'todo org-not-done-keywords))
  8983. (not (plist-get change-plist :to)))
  8984. (throw 'dont-block t))
  8985. ;; If this task has children, and any are undone, it's blocked
  8986. (save-excursion
  8987. (org-back-to-heading t)
  8988. (let ((this-level (funcall outline-level)))
  8989. (outline-next-heading)
  8990. (let ((child-level (funcall outline-level)))
  8991. (while (and (not (eobp))
  8992. (> child-level this-level))
  8993. ;; this todo has children, check whether they are all
  8994. ;; completed
  8995. (when (and (not (org-entry-is-done-p))
  8996. (org-entry-is-todo-p))
  8997. (setq org-block-entry-blocking (org-get-heading))
  8998. (throw 'dont-block nil))
  8999. (outline-next-heading)
  9000. (setq child-level (funcall outline-level))))))
  9001. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  9002. ;; any previous siblings are undone, it's blocked
  9003. (save-excursion
  9004. (org-back-to-heading t)
  9005. (let* ((pos (point))
  9006. (parent-pos (and (org-up-heading-safe) (point)))
  9007. (case-fold-search nil))
  9008. (unless parent-pos (throw 'dont-block t)) ; no parent
  9009. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9010. (forward-line 1)
  9011. (re-search-forward org-not-done-heading-regexp pos t))
  9012. (setq org-block-entry-blocking (match-string 0))
  9013. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  9014. ;; Search further up the hierarchy, to see if an ancestor is blocked
  9015. (while t
  9016. (goto-char parent-pos)
  9017. (unless (looking-at org-not-done-heading-regexp)
  9018. (throw 'dont-block t)) ; do not block, parent is not a TODO
  9019. (setq pos (point))
  9020. (setq parent-pos (and (org-up-heading-safe) (point)))
  9021. (unless parent-pos (throw 'dont-block t)) ; no parent
  9022. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  9023. (forward-line 1)
  9024. (re-search-forward org-not-done-heading-regexp pos t)
  9025. (setq org-block-entry-blocking (org-get-heading)))
  9026. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  9027. (defcustom org-track-ordered-property-with-tag nil
  9028. "Should the ORDERED property also be shown as a tag?
  9029. The ORDERED property decides if an entry should require subtasks to be
  9030. completed in sequence. Since a property is not very visible, setting
  9031. this option means that toggling the ORDERED property with the command
  9032. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  9033. not relevant for the behavior, but it makes things more visible.
  9034. Note that toggling the tag with tags commands will not change the property
  9035. and therefore not influence behavior!
  9036. This can be t, meaning the tag ORDERED should be used. It can also be a
  9037. string to select a different tag for this task."
  9038. :group 'org-todo
  9039. :type '(choice
  9040. (const :tag "No tracking" nil)
  9041. (const :tag "Track with ORDERED tag" t)
  9042. (string :tag "Use other tag")))
  9043. (defun org-toggle-ordered-property ()
  9044. "Toggle the ORDERED property of the current entry.
  9045. For better visibility, you can track the value of this property with a tag.
  9046. See variable `org-track-ordered-property-with-tag'."
  9047. (interactive)
  9048. (let* ((t1 org-track-ordered-property-with-tag)
  9049. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9050. (save-excursion
  9051. (org-back-to-heading)
  9052. (if (org-entry-get nil "ORDERED")
  9053. (progn
  9054. (org-delete-property "ORDERED")
  9055. (and tag (org-toggle-tag tag 'off))
  9056. (message "Subtasks can be completed in arbitrary order"))
  9057. (org-entry-put nil "ORDERED" "t")
  9058. (and tag (org-toggle-tag tag 'on))
  9059. (message "Subtasks must be completed in sequence")))))
  9060. (defun org-block-todo-from-checkboxes (change-plist)
  9061. "Block turning an entry into a TODO, using checkboxes.
  9062. This checks whether the current task should be blocked from state
  9063. changes because there are unchecked boxes in this entry."
  9064. (if (not org-enforce-todo-checkbox-dependencies)
  9065. t ; if locally turned off don't block
  9066. (catch 'dont-block
  9067. ;; If this is not a todo state change, or if this entry is already DONE,
  9068. ;; do not block
  9069. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9070. (member (plist-get change-plist :from)
  9071. (cons 'done org-done-keywords))
  9072. (member (plist-get change-plist :to)
  9073. (cons 'todo org-not-done-keywords))
  9074. (not (plist-get change-plist :to)))
  9075. (throw 'dont-block t))
  9076. ;; If this task has checkboxes that are not checked, it's blocked
  9077. (save-excursion
  9078. (org-back-to-heading t)
  9079. (let ((beg (point)) end)
  9080. (outline-next-heading)
  9081. (setq end (point))
  9082. (goto-char beg)
  9083. (when (org-list-search-forward
  9084. (concat (org-item-beginning-re)
  9085. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9086. "\\[[- ]\\]")
  9087. end t)
  9088. (when (boundp 'org-blocked-by-checkboxes)
  9089. (setq org-blocked-by-checkboxes t))
  9090. (throw 'dont-block nil))))
  9091. t))) ; do not block
  9092. (defun org-entry-blocked-p ()
  9093. "Non-nil if entry at point is blocked."
  9094. (and (not (org-entry-get nil "NOBLOCKING"))
  9095. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9096. (not (run-hook-with-args-until-failure
  9097. 'org-blocker-hook
  9098. (list :type 'todo-state-change
  9099. :position (point)
  9100. :from 'todo
  9101. :to 'done)))))
  9102. (defun org-update-statistics-cookies (all)
  9103. "Update the statistics cookie, either from TODO or from checkboxes.
  9104. This should be called with the cursor in a line with a statistics
  9105. cookie. When called with a \\[universal-argument] prefix, update
  9106. all statistics cookies in the buffer."
  9107. (interactive "P")
  9108. (if all
  9109. (progn
  9110. (org-update-checkbox-count 'all)
  9111. (org-map-region 'org-update-parent-todo-statistics
  9112. (point-min) (point-max)))
  9113. (if (not (org-at-heading-p))
  9114. (org-update-checkbox-count)
  9115. (let ((pos (point-marker))
  9116. end l1 l2)
  9117. (ignore-errors (org-back-to-heading t))
  9118. (if (not (org-at-heading-p))
  9119. (org-update-checkbox-count)
  9120. (setq l1 (org-outline-level))
  9121. (setq end
  9122. (save-excursion
  9123. (outline-next-heading)
  9124. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9125. (point)))
  9126. (if (and (save-excursion
  9127. (re-search-forward
  9128. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9129. (not (save-excursion
  9130. (re-search-forward
  9131. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9132. (org-update-checkbox-count)
  9133. (if (and l2 (> l2 l1))
  9134. (progn
  9135. (goto-char end)
  9136. (org-update-parent-todo-statistics))
  9137. (goto-char pos)
  9138. (beginning-of-line 1)
  9139. (while (re-search-forward
  9140. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9141. (point-at-eol) t)
  9142. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9143. (goto-char pos)
  9144. (move-marker pos nil)))))
  9145. (defvar org-entry-property-inherited-from) ;; defined below
  9146. (defun org-update-parent-todo-statistics ()
  9147. "Update any statistics cookie in the parent of the current headline.
  9148. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9149. the entire subtree and this will travel up the hierarchy and update
  9150. statistics everywhere."
  9151. (let* ((prop (save-excursion
  9152. (org-up-heading-safe)
  9153. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9154. (recursive (or (not org-hierarchical-todo-statistics)
  9155. (and prop (string-match "\\<recursive\\>" prop))))
  9156. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9157. 0))
  9158. (first t)
  9159. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9160. level ltoggle l1 new ndel
  9161. (cnt-all 0) (cnt-done 0) is-percent kwd
  9162. checkbox-beg cookie-present)
  9163. (catch 'exit
  9164. (save-excursion
  9165. (beginning-of-line 1)
  9166. (setq ltoggle (funcall outline-level))
  9167. ;; Three situations are to consider:
  9168. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9169. ;; to the top-level ancestor on the headline;
  9170. ;; 2. If parent has "recursive" property, repeat up to the
  9171. ;; headline setting that property, taking inheritance into
  9172. ;; account;
  9173. ;; 3. Else, move up to direct parent and proceed only once.
  9174. (while (and (setq level (org-up-heading-safe))
  9175. (or recursive first)
  9176. (>= (point) lim))
  9177. (setq first nil cookie-present nil)
  9178. (unless (and level
  9179. (not (string-match
  9180. "\\<checkbox\\>"
  9181. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9182. "")))))
  9183. (throw 'exit nil))
  9184. (while (re-search-forward box-re (point-at-eol) t)
  9185. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9186. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9187. (save-match-data
  9188. (unless (outline-next-heading) (throw 'exit nil))
  9189. (while (and (looking-at org-complex-heading-regexp)
  9190. (> (setq l1 (length (match-string 1))) level))
  9191. (setq kwd (and (or recursive (= l1 ltoggle))
  9192. (match-string 2)))
  9193. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9194. (and (eq org-provide-todo-statistics t)
  9195. (or (member kwd org-done-keywords)))
  9196. (and (listp org-provide-todo-statistics)
  9197. (stringp (car org-provide-todo-statistics))
  9198. (or (member kwd org-provide-todo-statistics)
  9199. (member kwd org-done-keywords)))
  9200. (and (listp org-provide-todo-statistics)
  9201. (listp (car org-provide-todo-statistics))
  9202. (or (member kwd (car org-provide-todo-statistics))
  9203. (and (member kwd org-done-keywords)
  9204. (member kwd (cadr org-provide-todo-statistics))))))
  9205. (setq cnt-all (1+ cnt-all))
  9206. (and (eq org-provide-todo-statistics t)
  9207. kwd
  9208. (setq cnt-all (1+ cnt-all))))
  9209. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9210. (member kwd org-done-keywords))
  9211. (and (listp org-provide-todo-statistics)
  9212. (listp (car org-provide-todo-statistics))
  9213. (member kwd org-done-keywords)
  9214. (member kwd (cadr org-provide-todo-statistics)))
  9215. (and (listp org-provide-todo-statistics)
  9216. (stringp (car org-provide-todo-statistics))
  9217. (member kwd org-done-keywords)))
  9218. (setq cnt-done (1+ cnt-done)))
  9219. (outline-next-heading)))
  9220. (setq new
  9221. (if is-percent
  9222. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9223. (max 1 cnt-all)))
  9224. (format "[%d/%d]" cnt-done cnt-all))
  9225. ndel (- (match-end 0) checkbox-beg))
  9226. (goto-char checkbox-beg)
  9227. (insert new)
  9228. (delete-region (point) (+ (point) ndel))
  9229. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9230. (when cookie-present
  9231. (run-hook-with-args 'org-after-todo-statistics-hook
  9232. cnt-done (- cnt-all cnt-done))))))
  9233. (run-hooks 'org-todo-statistics-hook)))
  9234. (defvar org-after-todo-statistics-hook nil
  9235. "Hook that is called after a TODO statistics cookie has been updated.
  9236. Each function is called with two arguments: the number of not-done entries
  9237. and the number of done entries.
  9238. For example, the following function, when added to this hook, will switch
  9239. an entry to DONE when all children are done, and back to TODO when new
  9240. entries are set to a TODO status. Note that this hook is only called
  9241. when there is a statistics cookie in the headline!
  9242. (defun org-summary-todo (n-done n-not-done)
  9243. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9244. (let (org-log-done org-log-states) ; turn off logging
  9245. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9246. (defvar org-todo-statistics-hook nil
  9247. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9248. This hook runs even if there is no statistics cookie present, in which case
  9249. `org-after-todo-statistics-hook' would not run.")
  9250. (defun org-todo-trigger-tag-changes (state)
  9251. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9252. (let ((l org-todo-state-tags-triggers)
  9253. changes)
  9254. (when (or (not state) (equal state ""))
  9255. (setq changes (append changes (cdr (assoc "" l)))))
  9256. (when (and (stringp state) (> (length state) 0))
  9257. (setq changes (append changes (cdr (assoc state l)))))
  9258. (when (member state org-not-done-keywords)
  9259. (setq changes (append changes (cdr (assq 'todo l)))))
  9260. (when (member state org-done-keywords)
  9261. (setq changes (append changes (cdr (assq 'done l)))))
  9262. (dolist (c changes)
  9263. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9264. (defun org-local-logging (value)
  9265. "Get logging settings from a property VALUE."
  9266. ;; Directly set the variables, they are already local.
  9267. (setq org-log-done nil
  9268. org-log-repeat nil
  9269. org-todo-log-states nil)
  9270. (dolist (w (split-string value))
  9271. (let (a)
  9272. (cond
  9273. ((setq a (assoc w org-startup-options))
  9274. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9275. (set (nth 1 a) (nth 2 a))))
  9276. ((setq a (org-extract-log-state-settings w))
  9277. (and (member (car a) org-todo-keywords-1)
  9278. (push a org-todo-log-states)))))))
  9279. (defun org-get-todo-sequence-head (kwd)
  9280. "Return the head of the TODO sequence to which KWD belongs.
  9281. If KWD is not set, check if there is a text property remembering the
  9282. right sequence."
  9283. (let (p)
  9284. (cond
  9285. ((not kwd)
  9286. (or (get-text-property (point-at-bol) 'org-todo-head)
  9287. (progn
  9288. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9289. nil (point-at-eol)))
  9290. (get-text-property p 'org-todo-head))))
  9291. ((not (member kwd org-todo-keywords-1))
  9292. (car org-todo-keywords-1))
  9293. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9294. (defun org-fast-todo-selection (&optional current-state)
  9295. "Fast TODO keyword selection with single keys.
  9296. Returns the new TODO keyword, or nil if no state change should occur.
  9297. When CURRENT-STATE is given and selection letters are not unique globally,
  9298. prefer a state in the current sequence over on in another sequence."
  9299. (let* ((fulltable org-todo-key-alist)
  9300. (head (org-get-todo-sequence-head current-state))
  9301. (done-keywords org-done-keywords) ;; needed for the faces.
  9302. (maxlen (apply 'max (mapcar
  9303. (lambda (x)
  9304. (if (stringp (car x)) (string-width (car x)) 0))
  9305. fulltable)))
  9306. (expert (equal org-use-fast-todo-selection 'expert))
  9307. (prompt "")
  9308. (fwidth (+ maxlen 3 1 3))
  9309. (ncol (/ (- (window-width) 4) fwidth))
  9310. tg cnt e c tbl subtable
  9311. groups ingroup in-current-sequence)
  9312. (save-excursion
  9313. (save-window-excursion
  9314. (if expert
  9315. (set-buffer (get-buffer-create " *Org todo*"))
  9316. (delete-other-windows)
  9317. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9318. (org-switch-to-buffer-other-window " *Org todo*"))
  9319. (erase-buffer)
  9320. (setq-local org-done-keywords done-keywords)
  9321. (setq tbl fulltable cnt 0)
  9322. (while (setq e (pop tbl))
  9323. (cond
  9324. ((equal e '(:startgroup))
  9325. (push '() groups) (setq ingroup t)
  9326. (unless (= cnt 0)
  9327. (setq cnt 0)
  9328. (insert "\n"))
  9329. (setq prompt (concat prompt "{"))
  9330. (insert "{ "))
  9331. ((equal e '(:endgroup))
  9332. (setq ingroup nil cnt 0 in-current-sequence nil)
  9333. (setq prompt (concat prompt "}"))
  9334. (insert "}\n"))
  9335. ((equal e '(:newline))
  9336. (unless (= cnt 0)
  9337. (setq cnt 0)
  9338. (insert "\n")
  9339. (setq e (car tbl))
  9340. (while (equal (car tbl) '(:newline))
  9341. (insert "\n")
  9342. (setq tbl (cdr tbl)))))
  9343. (t
  9344. (setq tg (car e) c (cdr e))
  9345. (if (equal tg head) (setq in-current-sequence t))
  9346. (when ingroup (push tg (car groups)))
  9347. (when in-current-sequence (push e subtable))
  9348. (setq tg (org-add-props tg nil 'face
  9349. (org-get-todo-face tg)))
  9350. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9351. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9352. (insert "[" c "] " tg (make-string
  9353. (- fwidth 4 (length tg)) ?\ ))
  9354. (when (and (= (setq cnt (1+ cnt)) ncol)
  9355. ;; Avoid lines with just a closing delimiter.
  9356. (not (equal (car tbl) '(:endgroup))))
  9357. (insert "\n")
  9358. (when ingroup (insert " "))
  9359. (setq cnt 0)))))
  9360. (insert "\n")
  9361. (goto-char (point-min))
  9362. (unless expert (org-fit-window-to-buffer))
  9363. (message (concat "[a-z..]:Set [SPC]:clear"
  9364. (if expert (concat "\n" prompt) "")))
  9365. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9366. (setq subtable (nreverse subtable))
  9367. (cond
  9368. ((or (= c ?\C-g)
  9369. (and (= c ?q) (not (rassoc c fulltable))))
  9370. (setq quit-flag t))
  9371. ((= c ?\ ) nil)
  9372. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9373. tg (car e))
  9374. tg)
  9375. (t (setq quit-flag t)))))))
  9376. (defun org-entry-is-todo-p ()
  9377. (member (org-get-todo-state) org-not-done-keywords))
  9378. (defun org-entry-is-done-p ()
  9379. (member (org-get-todo-state) org-done-keywords))
  9380. (defun org-get-todo-state ()
  9381. "Return the TODO keyword of the current subtree."
  9382. (save-excursion
  9383. (org-back-to-heading t)
  9384. (and (let ((case-fold-search nil))
  9385. (looking-at org-todo-line-regexp))
  9386. (match-end 2)
  9387. (match-string 2))))
  9388. (defun org-at-date-range-p (&optional inactive-ok)
  9389. "Non-nil if point is inside a date range.
  9390. When optional argument INACTIVE-OK is non-nil, also consider
  9391. inactive time ranges.
  9392. When this function returns a non-nil value, match data is set
  9393. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9394. on INACTIVE-OK."
  9395. (interactive)
  9396. (save-excursion
  9397. (catch 'exit
  9398. (let ((pos (point)))
  9399. (skip-chars-backward "^[<\r\n")
  9400. (skip-chars-backward "<[")
  9401. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9402. (>= (match-end 0) pos)
  9403. (throw 'exit t))
  9404. (skip-chars-backward "^<[\r\n")
  9405. (skip-chars-backward "<[")
  9406. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9407. (>= (match-end 0) pos)
  9408. (throw 'exit t)))
  9409. nil)))
  9410. (defun org-get-repeat (&optional timestamp)
  9411. "Check if there is a time-stamp with repeater in this entry.
  9412. Return the repeater, as a string, or nil. Also return nil when
  9413. this function is called before first heading.
  9414. When optional argument TIMESTAMP is a string, extract the
  9415. repeater from there instead."
  9416. (save-match-data
  9417. (cond
  9418. (timestamp
  9419. (and (string-match org-repeat-re timestamp)
  9420. (match-string-no-properties 1 timestamp)))
  9421. ((org-before-first-heading-p) nil)
  9422. (t
  9423. (save-excursion
  9424. (org-back-to-heading t)
  9425. (let ((end (org-entry-end-position)))
  9426. (catch :repeat
  9427. (while (re-search-forward org-repeat-re end t)
  9428. (when (save-match-data (org-at-timestamp-p 'agenda))
  9429. (throw :repeat (match-string-no-properties 1)))))))))))
  9430. (defvar org-last-changed-timestamp)
  9431. (defvar org-last-inserted-timestamp)
  9432. (defvar org-log-post-message)
  9433. (defvar org-log-note-purpose)
  9434. (defvar org-log-note-how nil)
  9435. (defvar org-log-note-extra)
  9436. (defvar org-log-setup nil)
  9437. (defun org-auto-repeat-maybe (done-word)
  9438. "Check if the current headline contains a repeated time-stamp.
  9439. If yes, set TODO state back to what it was and change the base date
  9440. of repeating deadline/scheduled time stamps to new date.
  9441. This function is run automatically after each state change to a DONE state."
  9442. (let* ((repeat (org-get-repeat))
  9443. (aa (assoc org-last-state org-todo-kwd-alist))
  9444. (interpret (nth 1 aa))
  9445. (head (nth 2 aa))
  9446. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9447. (msg "Entry repeats: ")
  9448. (org-log-done nil)
  9449. (org-todo-log-states nil)
  9450. (end (copy-marker (org-entry-end-position))))
  9451. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9452. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9453. (let ((to-state
  9454. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9455. (and (stringp org-todo-repeat-to-state)
  9456. org-todo-repeat-to-state)
  9457. (and org-todo-repeat-to-state org-last-state))))
  9458. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9459. to-state)
  9460. ((eq interpret 'type) org-last-state)
  9461. (head)
  9462. (t 'none))))
  9463. (org-back-to-heading t)
  9464. (org-add-planning-info nil nil 'closed)
  9465. ;; When `org-log-repeat' is non-nil or entry contains
  9466. ;; a clock, set LAST_REPEAT property.
  9467. (when (or org-log-repeat
  9468. (catch :clock
  9469. (save-excursion
  9470. (while (re-search-forward org-clock-line-re end t)
  9471. (when (org-at-clock-log-p) (throw :clock t))))))
  9472. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9473. (org-time-stamp-format t t))))
  9474. (when org-log-repeat
  9475. (if org-log-setup
  9476. ;; We are already setup for some record.
  9477. (when (eq org-log-repeat 'note)
  9478. ;; Make sure we take a note, not only a time stamp.
  9479. (setq org-log-note-how 'note))
  9480. ;; Set up for taking a record.
  9481. (org-add-log-setup 'state
  9482. (or done-word (car org-done-keywords))
  9483. org-last-state
  9484. org-log-repeat)))
  9485. ;; Time-stamps without a repeater are usually skipped. However,
  9486. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9487. ;; longer relevant.
  9488. (save-excursion
  9489. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9490. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9491. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9492. ;; Update every time-stamp with a repeater in the entry.
  9493. (let ((planning-re (regexp-opt
  9494. (list org-scheduled-string org-deadline-string))))
  9495. (while (re-search-forward org-repeat-re end t)
  9496. (let* ((ts (match-string 0))
  9497. (type (if (not (org-at-planning-p)) "Plain:"
  9498. (save-excursion
  9499. (re-search-backward
  9500. planning-re (line-beginning-position) t)
  9501. (match-string 0)))))
  9502. (when (and (org-at-timestamp-p 'agenda)
  9503. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9504. (let ((n (string-to-number (match-string 2 ts)))
  9505. (what (match-string 3 ts)))
  9506. (when (equal what "w") (setq n (* n 7) what "d"))
  9507. (when (and (equal what "h")
  9508. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9509. ts)))
  9510. (user-error
  9511. "Cannot repeat in %d hour(s) because no hour has been set"
  9512. n))
  9513. ;; Preparation, see if we need to modify the start
  9514. ;; date for the change.
  9515. (when (match-end 1)
  9516. (let ((time (save-match-data (org-time-string-to-time ts)))
  9517. (repeater-type (match-string 1 ts)))
  9518. (cond
  9519. ((equal "." repeater-type)
  9520. ;; Shift starting date to today, or now if
  9521. ;; repeater is by hours.
  9522. (if (equal what "h")
  9523. (org-timestamp-change
  9524. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9525. (org-timestamp-change
  9526. (- (org-today) (time-to-days time)) 'day)))
  9527. ((equal "+" repeater-type)
  9528. (let ((nshiftmax 10)
  9529. (nshift 0))
  9530. (while (or (= nshift 0)
  9531. (not (time-less-p nil time)))
  9532. (when (= nshiftmax (cl-incf nshift))
  9533. (or (y-or-n-p
  9534. (format "%d repeater intervals were not \
  9535. enough to shift date past today. Continue? "
  9536. nshift))
  9537. (user-error "Abort")))
  9538. (org-timestamp-change n (cdr (assoc what whata)))
  9539. (org-in-regexp org-ts-regexp3)
  9540. (setq ts (match-string 1))
  9541. (setq time
  9542. (save-match-data
  9543. (org-time-string-to-time ts)))))
  9544. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9545. ;; Rematch, so that we have everything in place
  9546. ;; for the real shift.
  9547. (org-in-regexp org-ts-regexp3)
  9548. (setq ts (match-string 1))
  9549. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9550. ts)))))
  9551. (save-excursion
  9552. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9553. (setq msg
  9554. (concat msg type " " org-last-changed-timestamp " ")))))))
  9555. (run-hooks 'org-todo-repeat-hook)
  9556. (setq org-log-post-message msg)
  9557. (message msg))))
  9558. (defun org-show-todo-tree (arg)
  9559. "Make a compact tree which shows all headlines marked with TODO.
  9560. The tree will show the lines where the regexp matches, and all higher
  9561. headlines above the match.
  9562. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9563. With a numeric prefix N, construct a sparse tree for the Nth element
  9564. of `org-todo-keywords-1'."
  9565. (interactive "P")
  9566. (let ((case-fold-search nil)
  9567. (kwd-re
  9568. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9569. ((equal arg '(4))
  9570. (let ((kwd
  9571. (completing-read "Keyword (or KWD1|KWD2|...): "
  9572. (mapcar #'list org-todo-keywords-1))))
  9573. (concat "\\("
  9574. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9575. "\\)\\>")))
  9576. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9577. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9578. org-todo-keywords-1)))
  9579. (t (user-error "Invalid prefix argument: %s" arg)))))
  9580. (message "%d TODO entries found"
  9581. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9582. (defun org--deadline-or-schedule (arg type time)
  9583. "Insert DEADLINE or SCHEDULE information in current entry.
  9584. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9585. `org-schedule' for information about ARG and TIME arguments."
  9586. (let* ((deadline? (eq type 'deadline))
  9587. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9588. (log (if deadline? org-log-redeadline org-log-reschedule))
  9589. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9590. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9591. ;; Save repeater cookie from either TIME or current scheduled
  9592. ;; time stamp. We are going to insert it back at the end of
  9593. ;; the process.
  9594. (repeater (or (and (org-string-nw-p time)
  9595. ;; We use `org-repeat-re' because we need
  9596. ;; to tell the difference between a real
  9597. ;; repeater and a time delta, e.g. "+2d".
  9598. (string-match org-repeat-re time)
  9599. (match-string 1 time))
  9600. (and (org-string-nw-p old-date)
  9601. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9602. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9603. old-date)
  9604. (match-string 1 old-date)))))
  9605. (pcase arg
  9606. (`(4)
  9607. (if (not old-date)
  9608. (message (if deadline? "Entry had no deadline to remove"
  9609. "Entry was not scheduled"))
  9610. (when (and old-date log)
  9611. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9612. nil old-date log))
  9613. (org-remove-timestamp-with-keyword keyword)
  9614. (message (if deadline? "Entry no longer has a deadline."
  9615. "Entry is no longer scheduled."))))
  9616. (`(16)
  9617. (save-excursion
  9618. (org-back-to-heading t)
  9619. (let ((regexp (if deadline? org-deadline-time-regexp
  9620. org-scheduled-time-regexp)))
  9621. (if (not (re-search-forward regexp (line-end-position 2) t))
  9622. (user-error (if deadline? "No deadline information to update"
  9623. "No scheduled information to update"))
  9624. (let* ((rpl0 (match-string 1))
  9625. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9626. (msg (if deadline? "Warn starting from" "Delay until")))
  9627. (replace-match
  9628. (concat keyword
  9629. " <" rpl
  9630. (format " -%dd"
  9631. (abs (- (time-to-days
  9632. (save-match-data
  9633. (org-read-date
  9634. nil t nil msg old-date-time)))
  9635. (time-to-days old-date-time))))
  9636. ">") t t))))))
  9637. (_
  9638. (org-add-planning-info type time 'closed)
  9639. (when (and old-date
  9640. log
  9641. (not (equal old-date org-last-inserted-timestamp)))
  9642. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9643. org-last-inserted-timestamp
  9644. old-date
  9645. log))
  9646. (when repeater
  9647. (save-excursion
  9648. (org-back-to-heading t)
  9649. (when (re-search-forward
  9650. (concat keyword " " org-last-inserted-timestamp)
  9651. (line-end-position 2)
  9652. t)
  9653. (goto-char (1- (match-end 0)))
  9654. (insert " " repeater)
  9655. (setq org-last-inserted-timestamp
  9656. (concat (substring org-last-inserted-timestamp 0 -1)
  9657. " " repeater
  9658. (substring org-last-inserted-timestamp -1))))))
  9659. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9660. org-last-inserted-timestamp)))))
  9661. (defun org-deadline (arg &optional time)
  9662. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9663. When called interactively, this command pops up the Emacs calendar to let
  9664. the user select a date.
  9665. With one universal prefix argument, remove any deadline from the item.
  9666. With two universal prefix arguments, prompt for a warning delay.
  9667. With argument TIME, set the deadline at the corresponding date. TIME
  9668. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9669. (interactive "P")
  9670. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9671. (org-map-entries
  9672. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9673. nil
  9674. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9675. 'region-start-level
  9676. 'region)
  9677. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9678. (org--deadline-or-schedule arg 'deadline time)))
  9679. (defun org-schedule (arg &optional time)
  9680. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9681. When called interactively, this command pops up the Emacs calendar to let
  9682. the user select a date.
  9683. With one universal prefix argument, remove any scheduling date from the item.
  9684. With two universal prefix arguments, prompt for a delay cookie.
  9685. With argument TIME, scheduled at the corresponding date. TIME can
  9686. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9687. (interactive "P")
  9688. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9689. (org-map-entries
  9690. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9691. nil
  9692. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9693. 'region-start-level
  9694. 'region)
  9695. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9696. (org--deadline-or-schedule arg 'scheduled time)))
  9697. (defun org-get-scheduled-time (pom &optional inherit)
  9698. "Get the scheduled time as a time tuple, of a format suitable
  9699. for calling org-schedule with, or if there is no scheduling,
  9700. returns nil."
  9701. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9702. (when time
  9703. (org-time-string-to-time time))))
  9704. (defun org-get-deadline-time (pom &optional inherit)
  9705. "Get the deadline as a time tuple, of a format suitable for
  9706. calling org-deadline with, or if there is no scheduling, returns
  9707. nil."
  9708. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9709. (when time
  9710. (org-time-string-to-time time))))
  9711. (defun org-remove-timestamp-with-keyword (keyword)
  9712. "Remove all time stamps with KEYWORD in the current entry."
  9713. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9714. beg)
  9715. (save-excursion
  9716. (org-back-to-heading t)
  9717. (setq beg (point))
  9718. (outline-next-heading)
  9719. (while (re-search-backward re beg t)
  9720. (replace-match "")
  9721. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9722. (equal (char-before) ?\ ))
  9723. (backward-delete-char 1)
  9724. (when (string-match "^[ \t]*$" (buffer-substring
  9725. (point-at-bol) (point-at-eol)))
  9726. (delete-region (point-at-bol)
  9727. (min (point-max) (1+ (point-at-eol))))))))))
  9728. (defvar org-time-was-given) ; dynamically scoped parameter
  9729. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9730. (defun org-at-planning-p ()
  9731. "Non-nil when point is on a planning info line."
  9732. ;; This is as accurate and faster than `org-element-at-point' since
  9733. ;; planning info location is fixed in the section.
  9734. (or (let ((cached (org-element-at-point nil 'cached)))
  9735. (and cached
  9736. (eq 'planning (org-element-type cached))))
  9737. (org-with-wide-buffer
  9738. (beginning-of-line)
  9739. (and (looking-at-p org-planning-line-re)
  9740. (eq (point)
  9741. (ignore-errors
  9742. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9743. (org-back-to-heading t)
  9744. (org-with-limited-levels (org-back-to-heading t)))
  9745. (line-beginning-position 2)))))))
  9746. (defun org-add-planning-info (what &optional time &rest remove)
  9747. "Insert new timestamp with keyword in the planning line.
  9748. WHAT indicates what kind of time stamp to add. It is a symbol
  9749. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9750. the time to use. If none is given, the user is prompted for
  9751. a date. REMOVE indicates what kind of entries to remove. An old
  9752. WHAT entry will also be removed."
  9753. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9754. (when (and (memq what '(scheduled deadline))
  9755. (or (not time)
  9756. (and (stringp time)
  9757. (string-match "^[-+]+[0-9]" time))))
  9758. ;; Try to get a default date/time from existing timestamp
  9759. (save-excursion
  9760. (org-back-to-heading t)
  9761. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9762. (when (re-search-forward (if (eq what 'scheduled)
  9763. org-scheduled-time-regexp
  9764. org-deadline-time-regexp)
  9765. end t)
  9766. (setq ts (match-string 1)
  9767. default-time (org-time-string-to-time ts)
  9768. default-input (and ts (org-get-compact-tod ts)))))))
  9769. (when what
  9770. (setq time
  9771. (if (stringp time)
  9772. ;; This is a string (relative or absolute), set
  9773. ;; proper date.
  9774. (apply #'encode-time
  9775. (org-read-date-analyze
  9776. time default-time (decode-time default-time)))
  9777. ;; If necessary, get the time from the user
  9778. (or time (org-read-date nil 'to-time nil
  9779. (cl-case what
  9780. (deadline "DEADLINE")
  9781. (scheduled "SCHEDULED")
  9782. (otherwise nil))
  9783. default-time default-input)))))
  9784. (org-with-wide-buffer
  9785. (org-back-to-heading t)
  9786. (let ((planning? (save-excursion
  9787. (forward-line)
  9788. (looking-at-p org-planning-line-re))))
  9789. (cond
  9790. (planning?
  9791. (forward-line)
  9792. ;; Move to current indentation.
  9793. (skip-chars-forward " \t")
  9794. ;; Check if we have to remove something.
  9795. (dolist (type (if what (cons what remove) remove))
  9796. (save-excursion
  9797. (when (re-search-forward
  9798. (cl-case type
  9799. (closed org-closed-time-regexp)
  9800. (deadline org-deadline-time-regexp)
  9801. (scheduled org-scheduled-time-regexp)
  9802. (otherwise (error "Invalid planning type: %s" type)))
  9803. (line-end-position)
  9804. t)
  9805. ;; Delete until next keyword or end of line.
  9806. (delete-region
  9807. (match-beginning 0)
  9808. (if (re-search-forward org-keyword-time-not-clock-regexp
  9809. (line-end-position)
  9810. t)
  9811. (match-beginning 0)
  9812. (line-end-position))))))
  9813. ;; If there is nothing more to add and no more keyword is
  9814. ;; left, remove the line completely.
  9815. (if (and (looking-at-p "[ \t]*$") (not what))
  9816. (delete-region (line-end-position 0)
  9817. (line-end-position))
  9818. ;; If we removed last keyword, do not leave trailing white
  9819. ;; space at the end of line.
  9820. (let ((p (point)))
  9821. (save-excursion
  9822. (end-of-line)
  9823. (unless (= (skip-chars-backward " \t" p) 0)
  9824. (delete-region (point) (line-end-position)))))))
  9825. (what
  9826. (end-of-line)
  9827. (insert "\n")
  9828. (when org-adapt-indentation
  9829. (indent-to-column (1+ (org-outline-level)))))
  9830. (t nil)))
  9831. (when what
  9832. ;; Insert planning keyword.
  9833. (insert (cl-case what
  9834. (closed org-closed-string)
  9835. (deadline org-deadline-string)
  9836. (scheduled org-scheduled-string)
  9837. (otherwise (error "Invalid planning type: %s" what)))
  9838. " ")
  9839. ;; Insert associated timestamp.
  9840. (let ((ts (org-insert-time-stamp
  9841. time
  9842. (or org-time-was-given
  9843. (and (eq what 'closed) org-log-done-with-time))
  9844. (eq what 'closed)
  9845. nil nil (list org-end-time-was-given))))
  9846. (unless (eolp) (insert " "))
  9847. ts)))))
  9848. (defvar org-log-note-marker (make-marker)
  9849. "Marker pointing at the entry where the note is to be inserted.")
  9850. (defvar org-log-note-purpose nil)
  9851. (defvar org-log-note-state nil)
  9852. (defvar org-log-note-previous-state nil)
  9853. (defvar org-log-note-extra nil)
  9854. (defvar org-log-note-window-configuration nil)
  9855. (defvar org-log-note-return-to (make-marker))
  9856. (defvar org-log-note-effective-time nil
  9857. "Remembered current time.
  9858. So that dynamically scoped `org-extend-today-until' affects
  9859. timestamps in state change log.")
  9860. (defvar org-log-post-message nil
  9861. "Message to be displayed after a log note has been stored.
  9862. The auto-repeater uses this.")
  9863. (defun org-add-note ()
  9864. "Add a note to the current entry.
  9865. This is done in the same way as adding a state change note."
  9866. (interactive)
  9867. (org-add-log-setup 'note))
  9868. (defun org-log-beginning (&optional create)
  9869. "Return expected start of log notes in current entry.
  9870. When optional argument CREATE is non-nil, the function creates
  9871. a drawer to store notes, if necessary. Returned position ignores
  9872. narrowing."
  9873. (org-with-wide-buffer
  9874. (let ((drawer (org-log-into-drawer)))
  9875. (cond
  9876. (drawer
  9877. (org-end-of-meta-data)
  9878. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9879. (end (if (org-at-heading-p) (point)
  9880. (save-excursion (outline-next-heading) (point))))
  9881. (case-fold-search t))
  9882. (catch 'exit
  9883. ;; Try to find existing drawer.
  9884. (while (re-search-forward regexp end t)
  9885. (let ((element (org-element-at-point)))
  9886. (when (eq (org-element-type element) 'drawer)
  9887. (let ((cend (org-element-property :contents-end element)))
  9888. (when (and (not org-log-states-order-reversed) cend)
  9889. (goto-char cend)))
  9890. (throw 'exit nil))))
  9891. ;; No drawer found. Create one, if permitted.
  9892. (when create
  9893. (unless (bolp) (insert "\n"))
  9894. (let ((beg (point)))
  9895. (insert ":" drawer ":\n:END:\n")
  9896. (org-indent-region beg (point))
  9897. (org-flag-region (line-end-position -1)
  9898. (1- (point)) t 'outline))
  9899. (end-of-line -1)))))
  9900. (t
  9901. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9902. (skip-chars-forward " \t\n")
  9903. (beginning-of-line)
  9904. (unless org-log-states-order-reversed
  9905. (org-skip-over-state-notes)
  9906. (skip-chars-backward " \t\n")
  9907. (forward-line)))))
  9908. (if (bolp) (point) (line-beginning-position 2))))
  9909. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9910. "Set up the post command hook to take a note.
  9911. If this is about to TODO state change, the new state is expected in STATE.
  9912. HOW is an indicator what kind of note should be created.
  9913. EXTRA is additional text that will be inserted into the notes buffer."
  9914. (move-marker org-log-note-marker (point))
  9915. (setq org-log-note-purpose purpose
  9916. org-log-note-state state
  9917. org-log-note-previous-state prev-state
  9918. org-log-note-how how
  9919. org-log-note-extra extra
  9920. org-log-note-effective-time (org-current-effective-time)
  9921. org-log-setup t)
  9922. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9923. (defun org-skip-over-state-notes ()
  9924. "Skip past the list of State notes in an entry."
  9925. (when (ignore-errors (goto-char (org-in-item-p)))
  9926. (let* ((struct (org-list-struct))
  9927. (prevs (org-list-prevs-alist struct))
  9928. (regexp
  9929. (concat "[ \t]*- +"
  9930. (replace-regexp-in-string
  9931. " +" " +"
  9932. (org-replace-escapes
  9933. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9934. `(("%d" . ,org-ts-regexp-inactive)
  9935. ("%D" . ,org-ts-regexp)
  9936. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9937. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9938. ("%t" . ,org-ts-regexp-inactive)
  9939. ("%T" . ,org-ts-regexp)
  9940. ("%u" . ".*?")
  9941. ("%U" . ".*?")))))))
  9942. (while (looking-at-p regexp)
  9943. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9944. (org-list-get-item-end (point) struct)))))))
  9945. (defun org-add-log-note (&optional _purpose)
  9946. "Pop up a window for taking a note, and add this note later."
  9947. (remove-hook 'post-command-hook 'org-add-log-note)
  9948. (setq org-log-setup nil)
  9949. (setq org-log-note-window-configuration (current-window-configuration))
  9950. (delete-other-windows)
  9951. (move-marker org-log-note-return-to (point))
  9952. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9953. (goto-char org-log-note-marker)
  9954. (org-switch-to-buffer-other-window "*Org Note*")
  9955. (erase-buffer)
  9956. (if (memq org-log-note-how '(time state))
  9957. (org-store-log-note)
  9958. (let ((org-inhibit-startup t)) (org-mode))
  9959. (insert (format "# Insert note for %s.
  9960. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9961. (cl-case org-log-note-purpose
  9962. (clock-out "stopped clock")
  9963. (done "closed todo item")
  9964. (reschedule "rescheduling")
  9965. (delschedule "no longer scheduled")
  9966. (redeadline "changing deadline")
  9967. (deldeadline "removing deadline")
  9968. (refile "refiling")
  9969. (note "this entry")
  9970. (state
  9971. (format "state change from \"%s\" to \"%s\""
  9972. (or org-log-note-previous-state "")
  9973. (or org-log-note-state "")))
  9974. (t (error "This should not happen")))))
  9975. (when org-log-note-extra (insert org-log-note-extra))
  9976. (setq-local org-finish-function 'org-store-log-note)
  9977. (run-hooks 'org-log-buffer-setup-hook)))
  9978. (defvar org-note-abort nil) ; dynamically scoped
  9979. (defun org-store-log-note ()
  9980. "Finish taking a log note, and insert it to where it belongs."
  9981. (let ((txt (prog1 (buffer-string)
  9982. (kill-buffer)))
  9983. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9984. lines)
  9985. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9986. (setq txt (replace-match "" t t txt)))
  9987. (when (string-match "\\s-+\\'" txt)
  9988. (setq txt (replace-match "" t t txt)))
  9989. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9990. (when (org-string-nw-p note)
  9991. (setq note
  9992. (org-replace-escapes
  9993. note
  9994. (list (cons "%u" (user-login-name))
  9995. (cons "%U" user-full-name)
  9996. (cons "%t" (format-time-string
  9997. (org-time-stamp-format 'long 'inactive)
  9998. org-log-note-effective-time))
  9999. (cons "%T" (format-time-string
  10000. (org-time-stamp-format 'long nil)
  10001. org-log-note-effective-time))
  10002. (cons "%d" (format-time-string
  10003. (org-time-stamp-format nil 'inactive)
  10004. org-log-note-effective-time))
  10005. (cons "%D" (format-time-string
  10006. (org-time-stamp-format nil nil)
  10007. org-log-note-effective-time))
  10008. (cons "%s" (cond
  10009. ((not org-log-note-state) "")
  10010. ((string-match-p org-ts-regexp
  10011. org-log-note-state)
  10012. (format "\"[%s]\""
  10013. (substring org-log-note-state 1 -1)))
  10014. (t (format "\"%s\"" org-log-note-state))))
  10015. (cons "%S"
  10016. (cond
  10017. ((not org-log-note-previous-state) "")
  10018. ((string-match-p org-ts-regexp
  10019. org-log-note-previous-state)
  10020. (format "\"[%s]\""
  10021. (substring
  10022. org-log-note-previous-state 1 -1)))
  10023. (t (format "\"%s\""
  10024. org-log-note-previous-state)))))))
  10025. (when lines (setq note (concat note " \\\\")))
  10026. (push note lines))
  10027. (when (and lines (not org-note-abort))
  10028. (with-current-buffer (marker-buffer org-log-note-marker)
  10029. (org-with-wide-buffer
  10030. ;; Find location for the new note.
  10031. (goto-char org-log-note-marker)
  10032. (set-marker org-log-note-marker nil)
  10033. ;; Note associated to a clock is to be located right after
  10034. ;; the clock. Do not move point.
  10035. (unless (eq org-log-note-purpose 'clock-out)
  10036. (goto-char (org-log-beginning t)))
  10037. ;; Make sure point is at the beginning of an empty line.
  10038. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10039. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10040. ;; In an existing list, add a new item at the top level.
  10041. ;; Otherwise, indent line like a regular one.
  10042. (let ((itemp (org-in-item-p)))
  10043. (if itemp
  10044. (indent-line-to
  10045. (let ((struct (save-excursion
  10046. (goto-char itemp) (org-list-struct))))
  10047. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10048. (org-indent-line)))
  10049. (insert (org-list-bullet-string "-") (pop lines))
  10050. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10051. (dolist (line lines)
  10052. (insert "\n")
  10053. (indent-line-to ind)
  10054. (insert line)))
  10055. (message "Note stored")
  10056. (org-back-to-heading t)))))
  10057. ;; Don't add undo information when called from `org-agenda-todo'.
  10058. (set-window-configuration org-log-note-window-configuration)
  10059. (with-current-buffer (marker-buffer org-log-note-return-to)
  10060. (goto-char org-log-note-return-to))
  10061. (move-marker org-log-note-return-to nil)
  10062. (when org-log-post-message (message "%s" org-log-post-message)))
  10063. (defun org-remove-empty-drawer-at (pos)
  10064. "Remove an empty drawer at position POS.
  10065. POS may also be a marker."
  10066. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10067. (org-with-wide-buffer
  10068. (goto-char pos)
  10069. (let ((drawer (org-element-at-point)))
  10070. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10071. (not (org-element-property :contents-begin drawer)))
  10072. (delete-region (org-element-property :begin drawer)
  10073. (progn (goto-char (org-element-property :end drawer))
  10074. (skip-chars-backward " \r\t\n")
  10075. (forward-line)
  10076. (point))))))))
  10077. (defvar org-ts-type nil)
  10078. (defun org-sparse-tree (&optional arg type)
  10079. "Create a sparse tree, prompt for the details.
  10080. This command can create sparse trees. You first need to select the type
  10081. of match used to create the tree:
  10082. t Show all TODO entries.
  10083. T Show entries with a specific TODO keyword.
  10084. m Show entries selected by a tags/property match.
  10085. p Enter a property name and its value (both with completion on existing
  10086. names/values) and show entries with that property.
  10087. r Show entries matching a regular expression (`/' can be used as well).
  10088. b Show deadlines and scheduled items before a date.
  10089. a Show deadlines and scheduled items after a date.
  10090. d Show deadlines due within `org-deadline-warning-days'.
  10091. D Show deadlines and scheduled items between a date range."
  10092. (interactive "P")
  10093. (setq type (or type org-sparse-tree-default-date-type))
  10094. (setq org-ts-type type)
  10095. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10096. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10097. [c]ycle through date types: %s"
  10098. (cl-case type
  10099. (all "all timestamps")
  10100. (scheduled "only scheduled")
  10101. (deadline "only deadline")
  10102. (active "only active timestamps")
  10103. (inactive "only inactive timestamps")
  10104. (closed "with a closed time-stamp")
  10105. (otherwise "scheduled/deadline")))
  10106. (let ((answer (read-char-exclusive)))
  10107. (cl-case answer
  10108. (?c
  10109. (org-sparse-tree
  10110. arg
  10111. (cadr
  10112. (memq type '(nil all scheduled deadline active inactive closed)))))
  10113. (?d (call-interactively 'org-check-deadlines))
  10114. (?b (call-interactively 'org-check-before-date))
  10115. (?a (call-interactively 'org-check-after-date))
  10116. (?D (call-interactively 'org-check-dates-range))
  10117. (?t (call-interactively 'org-show-todo-tree))
  10118. (?T (org-show-todo-tree '(4)))
  10119. (?m (call-interactively 'org-match-sparse-tree))
  10120. ((?p ?P)
  10121. (let* ((kwd (completing-read
  10122. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10123. (value (completing-read
  10124. "Value: " (mapcar #'list (org-property-values kwd)))))
  10125. (unless (string-match "\\`{.*}\\'" value)
  10126. (setq value (concat "\"" value "\"")))
  10127. (org-match-sparse-tree arg (concat kwd "=" value))))
  10128. ((?r ?R ?/) (call-interactively 'org-occur))
  10129. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10130. (defvar-local org-occur-highlights nil
  10131. "List of overlays used for occur matches.")
  10132. (defvar-local org-occur-parameters nil
  10133. "Parameters of the active org-occur calls.
  10134. This is a list, each call to org-occur pushes as cons cell,
  10135. containing the regular expression and the callback, onto the list.
  10136. The list can contain several entries if `org-occur' has been called
  10137. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10138. will only contain one set of parameters. When the highlights are
  10139. removed (for example with `C-c C-c', or with the next edit (depending
  10140. on `org-remove-highlights-with-change'), this variable is emptied
  10141. as well.")
  10142. (defun org-occur (regexp &optional keep-previous callback)
  10143. "Make a compact tree showing all matches of REGEXP.
  10144. The tree will show the lines where the regexp matches, and any other context
  10145. defined in `org-show-context-detail', which see.
  10146. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10147. done by a previous call to `org-occur' will be kept, to allow stacking of
  10148. calls to this command.
  10149. Optional argument CALLBACK can be a function of no argument. In this case,
  10150. it is called with point at the end of the match, match data being set
  10151. accordingly. Current match is shown only if the return value is non-nil.
  10152. The function must neither move point nor alter narrowing."
  10153. (interactive "sRegexp: \nP")
  10154. (when (equal regexp "")
  10155. (user-error "Regexp cannot be empty"))
  10156. (unless keep-previous
  10157. (org-remove-occur-highlights nil nil t))
  10158. (push (cons regexp callback) org-occur-parameters)
  10159. (let ((cnt 0))
  10160. (save-excursion
  10161. (goto-char (point-min))
  10162. (when (or (not keep-previous) ; do not want to keep
  10163. (not org-occur-highlights)) ; no previous matches
  10164. ;; hide everything
  10165. (org-overview))
  10166. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10167. (isearch-no-upper-case-p regexp t)
  10168. org-occur-case-fold-search)))
  10169. (while (re-search-forward regexp nil t)
  10170. (when (or (not callback)
  10171. (save-match-data (funcall callback)))
  10172. (setq cnt (1+ cnt))
  10173. (when org-highlight-sparse-tree-matches
  10174. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10175. (org-show-context 'occur-tree)))))
  10176. (when org-remove-highlights-with-change
  10177. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10178. nil 'local))
  10179. (unless org-sparse-tree-open-archived-trees
  10180. (org-hide-archived-subtrees (point-min) (point-max)))
  10181. (run-hooks 'org-occur-hook)
  10182. (when (called-interactively-p 'interactive)
  10183. (message "%d match(es) for regexp %s" cnt regexp))
  10184. cnt))
  10185. (defun org-occur-next-match (&optional n _reset)
  10186. "Function for `next-error-function' to find sparse tree matches.
  10187. N is the number of matches to move, when negative move backwards.
  10188. This function always goes back to the starting point when no
  10189. match is found."
  10190. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10191. (search-func (if (< n 0)
  10192. 'previous-single-char-property-change
  10193. 'next-single-char-property-change))
  10194. (n (abs n))
  10195. (pos (point))
  10196. p1)
  10197. (catch 'exit
  10198. (while (setq p1 (funcall search-func (point) 'org-type))
  10199. (when (equal p1 limit)
  10200. (goto-char pos)
  10201. (user-error "No more matches"))
  10202. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10203. (setq n (1- n))
  10204. (when (= n 0)
  10205. (goto-char p1)
  10206. (throw 'exit (point))))
  10207. (goto-char p1))
  10208. (goto-char p1)
  10209. (user-error "No more matches"))))
  10210. (defun org-highlight-new-match (beg end)
  10211. "Highlight from BEG to END and mark the highlight is an occur headline."
  10212. (let ((ov (make-overlay beg end)))
  10213. (overlay-put ov 'face 'secondary-selection)
  10214. (overlay-put ov 'org-type 'org-occur)
  10215. (push ov org-occur-highlights)))
  10216. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10217. "Remove the occur highlights from the buffer.
  10218. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10219. from the `before-change-functions' in the current buffer."
  10220. (interactive)
  10221. (unless org-inhibit-highlight-removal
  10222. (mapc #'delete-overlay org-occur-highlights)
  10223. (setq org-occur-highlights nil)
  10224. (setq org-occur-parameters nil)
  10225. (unless noremove
  10226. (remove-hook 'before-change-functions
  10227. 'org-remove-occur-highlights 'local))))
  10228. ;;;; Priorities
  10229. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10230. "Regular expression matching the priority indicator.
  10231. A priority indicator can be e.g. [#A] or [#1].
  10232. This regular expression matches these groups:
  10233. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10234. 1 : the priority cookie, e.g. \"[#A]\"
  10235. 2 : the value of the priority cookie, e.g. \"A\".")
  10236. (defun org-priority-up ()
  10237. "Increase the priority of the current item."
  10238. (interactive)
  10239. (org-priority 'up))
  10240. (defun org-priority-down ()
  10241. "Decrease the priority of the current item."
  10242. (interactive)
  10243. (org-priority 'down))
  10244. (defun org-priority (&optional action show)
  10245. "Change the priority of an item.
  10246. When called interactively with a `\\[universal-argument]' prefix,
  10247. show the priority in the minibuffer instead of changing it.
  10248. When called programmatically, ACTION can be `set', `up', `down',
  10249. or a character."
  10250. (interactive "P")
  10251. (when show
  10252. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10253. ;; passed the SHOW argument should be removed.
  10254. (warn "`org-priority' called with deprecated SHOW argument"))
  10255. (if (equal action '(4))
  10256. (org-priority-show)
  10257. (unless org-priority-enable-commands
  10258. (user-error "Priority commands are disabled"))
  10259. (setq action (or action 'set))
  10260. (let ((nump (< org-priority-lowest 65))
  10261. current new news have remove)
  10262. (save-excursion
  10263. (org-back-to-heading t)
  10264. (when (looking-at org-priority-regexp)
  10265. (let ((ms (match-string 2)))
  10266. (setq current (org-priority-to-value ms)
  10267. have t)))
  10268. (cond
  10269. ((eq action 'remove)
  10270. (setq remove t new ?\ ))
  10271. ((or (eq action 'set)
  10272. (integerp action))
  10273. (if (not (eq action 'set))
  10274. (setq new action)
  10275. (setq
  10276. new
  10277. (if nump
  10278. (let ((msg (format "Priority %s-%s, SPC to remove: "
  10279. (number-to-string org-priority-highest)
  10280. (number-to-string org-priority-lowest))))
  10281. (if (< 9 org-priority-lowest)
  10282. (string-to-number (read-string msg))
  10283. (message msg)
  10284. (string-to-number (char-to-string (read-char-exclusive)))))
  10285. (progn (message "Priority %c-%c, SPC to remove: "
  10286. org-priority-highest org-priority-lowest)
  10287. (save-match-data
  10288. (setq new (read-char-exclusive)))))))
  10289. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10290. (= (upcase org-priority-lowest) org-priority-lowest))
  10291. (setq new (upcase new)))
  10292. (cond ((equal new ?\s) (setq remove t))
  10293. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10294. (user-error
  10295. (if nump
  10296. "Priority must be between `%s' and `%s'"
  10297. "Priority must be between `%c' and `%c'")
  10298. org-priority-highest org-priority-lowest))))
  10299. ((eq action 'up)
  10300. (setq new (if have
  10301. (1- current) ; normal cycling
  10302. ;; last priority was empty
  10303. (if (eq last-command this-command)
  10304. org-priority-lowest ; wrap around empty to lowest
  10305. ;; default
  10306. (if org-priority-start-cycle-with-default
  10307. org-priority-default
  10308. (1- org-priority-default))))))
  10309. ((eq action 'down)
  10310. (setq new (if have
  10311. (1+ current) ; normal cycling
  10312. ;; last priority was empty
  10313. (if (eq last-command this-command)
  10314. org-priority-highest ; wrap around empty to highest
  10315. ;; default
  10316. (if org-priority-start-cycle-with-default
  10317. org-priority-default
  10318. (1+ org-priority-default))))))
  10319. (t (user-error "Invalid action")))
  10320. (when (or (< (upcase new) org-priority-highest)
  10321. (> (upcase new) org-priority-lowest))
  10322. (if (and (memq action '(up down))
  10323. (not have) (not (eq last-command this-command)))
  10324. ;; `new' is from default priority
  10325. (error
  10326. "The default can not be set, see `org-priority-default' why")
  10327. ;; normal cycling: `new' is beyond highest/lowest priority
  10328. ;; and is wrapped around to the empty priority
  10329. (setq remove t)))
  10330. ;; Numerical priorities are limited to 64, beyond that number,
  10331. ;; assume the priority cookie is a character.
  10332. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10333. (if have
  10334. (if remove
  10335. (replace-match "" t t nil 1)
  10336. (replace-match news t t nil 2))
  10337. (if remove
  10338. (user-error "No priority cookie found in line")
  10339. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10340. (if (match-end 2)
  10341. (progn
  10342. (goto-char (match-end 2))
  10343. (insert " [#" news "]"))
  10344. (goto-char (match-beginning 3))
  10345. (insert "[#" news "] "))))
  10346. (org-align-tags))
  10347. (if remove
  10348. (message "Priority removed")
  10349. (message "Priority of current item set to %s" news)))))
  10350. (defalias 'org-show-priority 'org-priority-show)
  10351. (defun org-priority-show ()
  10352. "Show the priority of the current item.
  10353. This priority is composed of the main priority given with the [#A] cookies,
  10354. and by additional input from the age of a schedules or deadline entry."
  10355. (interactive)
  10356. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10357. (org-get-at-bol 'priority)
  10358. (save-excursion
  10359. (save-match-data
  10360. (beginning-of-line)
  10361. (and (looking-at org-heading-regexp)
  10362. (org-get-priority (match-string 0))))))))
  10363. (message "Priority is %d" (if pri pri -1000))))
  10364. (defun org-get-priority (s)
  10365. "Find priority cookie and return priority.
  10366. S is a string against which you can match `org-priority-regexp'.
  10367. If `org-priority-get-priority-function' is set to a custom
  10368. function, use it. Otherwise process S and output the priority
  10369. value, an integer."
  10370. (save-match-data
  10371. (if (functionp org-priority-get-priority-function)
  10372. (funcall org-priority-get-priority-function s)
  10373. (if (not (string-match org-priority-regexp s))
  10374. (* 1000 (- org-priority-lowest org-priority-default))
  10375. (* 1000 (- org-priority-lowest
  10376. (org-priority-to-value (match-string 2 s))))))))
  10377. ;;;; Tags
  10378. (defvar org-agenda-archives-mode)
  10379. (defvar org-map-continue-from nil
  10380. "Position from where mapping should continue.
  10381. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10382. (defvar org-scanner-tags nil
  10383. "The current tag list while the tags scanner is running.")
  10384. (defvar org-trust-scanner-tags nil
  10385. "Should `org-get-tags' use the tags for the scanner.
  10386. This is for internal dynamical scoping only.
  10387. When this is non-nil, the function `org-get-tags' will return the value
  10388. of `org-scanner-tags' instead of building the list by itself. This
  10389. can lead to large speed-ups when the tags scanner is used in a file with
  10390. many entries, and when the list of tags is retrieved, for example to
  10391. obtain a list of properties. Building the tags list for each entry in such
  10392. a file becomes an N^2 operation - but with this variable set, it scales
  10393. as N.")
  10394. (defvar org--matcher-tags-todo-only nil)
  10395. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10396. "Scan headline tags with inheritance and produce output ACTION.
  10397. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10398. or `agenda' to produce an entry list for an agenda view. It can also be
  10399. a Lisp form or a function that should be called at each matched headline, in
  10400. this case the return value is a list of all return values from these calls.
  10401. MATCHER is a function accepting three arguments, returning
  10402. a non-nil value whenever a given set of tags qualifies a headline
  10403. for inclusion. See `org-make-tags-matcher' for more information.
  10404. As a special case, it can also be set to t (respectively nil) in
  10405. order to match all (respectively none) headline.
  10406. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10407. included in the output.
  10408. START-LEVEL can be a string with asterisks, reducing the scope to
  10409. headlines matching this string."
  10410. (require 'org-agenda)
  10411. (let* ((re (concat "^"
  10412. (if start-level
  10413. ;; Get the correct level to match
  10414. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10415. org-outline-regexp)
  10416. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10417. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10418. (props (list 'face 'default
  10419. 'done-face 'org-agenda-done
  10420. 'undone-face 'default
  10421. 'mouse-face 'highlight
  10422. 'org-not-done-regexp org-not-done-regexp
  10423. 'org-todo-regexp org-todo-regexp
  10424. 'org-complex-heading-regexp org-complex-heading-regexp
  10425. 'help-echo
  10426. (format "mouse-2 or RET jump to Org file %S"
  10427. (abbreviate-file-name
  10428. (or (buffer-file-name (buffer-base-buffer))
  10429. (buffer-name (buffer-base-buffer)))))))
  10430. (org-map-continue-from nil)
  10431. lspos tags tags-list
  10432. (tags-alist (list (cons 0 org-file-tags)))
  10433. (llast 0) rtn rtn1 level category i txt
  10434. todo marker entry priority
  10435. ts-date ts-date-type ts-date-pair)
  10436. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10437. (setq action (list 'lambda nil action)))
  10438. (save-excursion
  10439. (goto-char (point-min))
  10440. (when (eq action 'sparse-tree)
  10441. (org-overview)
  10442. (org-remove-occur-highlights))
  10443. (if (org-element--cache-active-p)
  10444. (let ((fast-re (concat "^"
  10445. (if start-level
  10446. ;; Get the correct level to match
  10447. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10448. org-outline-regexp))))
  10449. (org-element-cache-map
  10450. (lambda (el)
  10451. (goto-char (org-element-property :begin el))
  10452. (setq todo (org-element-property :todo-keyword el)
  10453. level (org-element-property :level el)
  10454. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  10455. tags-list (org-get-tags el)
  10456. org-scanner-tags tags-list)
  10457. (when (eq action 'agenda)
  10458. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10459. ts-date (car ts-date-pair)
  10460. ts-date-type (cdr ts-date-pair)))
  10461. (catch :skip
  10462. (when (and
  10463. ;; eval matcher only when the todo condition is OK
  10464. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10465. (if (functionp matcher)
  10466. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10467. (funcall matcher todo tags-list level))
  10468. matcher))
  10469. ;; Call the skipper, but return t if it does not
  10470. ;; skip, so that the `and' form continues evaluating.
  10471. (progn
  10472. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  10473. t)
  10474. ;; Check if timestamps are deselecting this entry
  10475. (or (not todo-only)
  10476. (and (member todo org-todo-keywords-1)
  10477. (or (not org-agenda-tags-todo-honor-ignore-options)
  10478. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10479. ;; select this headline
  10480. (cond
  10481. ((eq action 'sparse-tree)
  10482. (and org-highlight-sparse-tree-matches
  10483. (org-get-heading) (match-end 0)
  10484. (org-highlight-new-match
  10485. (match-beginning 1) (match-end 1)))
  10486. (org-show-context 'tags-tree))
  10487. ((eq action 'agenda)
  10488. (let* ((effort (org-entry-get (point) org-effort-property))
  10489. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  10490. (setq txt (org-agenda-format-item
  10491. ""
  10492. ;; Add `effort' and `effort-minutes'
  10493. ;; properties for prefix format.
  10494. (org-add-props
  10495. (concat
  10496. (if (eq org-tags-match-list-sublevels 'indented)
  10497. (make-string (1- level) ?.) "")
  10498. (org-get-heading))
  10499. nil
  10500. 'effort effort
  10501. 'effort-minutes effort-minutes)
  10502. (make-string level ?\s)
  10503. category
  10504. tags-list)
  10505. priority (org-get-priority txt))
  10506. ;; Now add `effort' and `effort-minutes' to
  10507. ;; full agenda line.
  10508. (setq txt (org-add-props txt nil
  10509. 'effort effort
  10510. 'effort-minutes effort-minutes)))
  10511. (goto-char (org-element-property :begin el))
  10512. (setq marker (org-agenda-new-marker))
  10513. (org-add-props txt props
  10514. 'org-marker marker 'org-hd-marker marker 'org-category category
  10515. 'todo-state todo
  10516. 'ts-date ts-date
  10517. 'priority priority
  10518. 'type (concat "tagsmatch" ts-date-type))
  10519. (push txt rtn))
  10520. ((functionp action)
  10521. (setq org-map-continue-from nil)
  10522. (save-excursion
  10523. (setq rtn1 (funcall action))
  10524. (push rtn1 rtn)))
  10525. (t (user-error "Invalid action")))
  10526. ;; if we are to skip sublevels, jump to end of subtree
  10527. (unless org-tags-match-list-sublevels
  10528. (goto-char (1- (org-element-property :end el))))))
  10529. ;; Get the correct position from where to continue
  10530. (when org-map-continue-from
  10531. (goto-char org-map-continue-from))
  10532. ;; Return nil.
  10533. nil)
  10534. :next-re fast-re
  10535. :fail-re fast-re
  10536. :narrow t))
  10537. (while (let (case-fold-search)
  10538. (re-search-forward re nil t))
  10539. (setq org-map-continue-from nil)
  10540. (catch :skip
  10541. ;; Ignore closing parts of inline tasks.
  10542. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10543. (throw :skip t))
  10544. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10545. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10546. (goto-char (setq lspos (match-beginning 0)))
  10547. (setq level (org-reduced-level (org-outline-level))
  10548. category (org-get-category))
  10549. (when (eq action 'agenda)
  10550. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10551. ts-date (car ts-date-pair)
  10552. ts-date-type (cdr ts-date-pair)))
  10553. (setq i llast llast level)
  10554. ;; remove tag lists from same and sublevels
  10555. (while (>= i level)
  10556. (when (setq entry (assoc i tags-alist))
  10557. (setq tags-alist (delete entry tags-alist)))
  10558. (setq i (1- i)))
  10559. ;; add the next tags
  10560. (when tags
  10561. (setq tags (org-split-string tags ":")
  10562. tags-alist
  10563. (cons (cons level tags) tags-alist)))
  10564. ;; compile tags for current headline
  10565. (setq tags-list
  10566. (if org-use-tag-inheritance
  10567. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10568. tags)
  10569. org-scanner-tags tags-list)
  10570. (when org-use-tag-inheritance
  10571. (setcdr (car tags-alist)
  10572. (mapcar (lambda (x)
  10573. (setq x (copy-sequence x))
  10574. (org-add-prop-inherited x))
  10575. (cdar tags-alist))))
  10576. (when (and tags org-use-tag-inheritance
  10577. (or (not (eq t org-use-tag-inheritance))
  10578. org-tags-exclude-from-inheritance))
  10579. ;; Selective inheritance, remove uninherited ones.
  10580. (setcdr (car tags-alist)
  10581. (org-remove-uninherited-tags (cdar tags-alist))))
  10582. (when (and
  10583. ;; eval matcher only when the todo condition is OK
  10584. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10585. (if (functionp matcher)
  10586. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10587. (funcall matcher todo tags-list level))
  10588. matcher))
  10589. ;; Call the skipper, but return t if it does not
  10590. ;; skip, so that the `and' form continues evaluating.
  10591. (progn
  10592. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10593. t)
  10594. ;; Check if timestamps are deselecting this entry
  10595. (or (not todo-only)
  10596. (and (member todo org-todo-keywords-1)
  10597. (or (not org-agenda-tags-todo-honor-ignore-options)
  10598. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10599. ;; select this headline
  10600. (cond
  10601. ((eq action 'sparse-tree)
  10602. (and org-highlight-sparse-tree-matches
  10603. (org-get-heading) (match-end 0)
  10604. (org-highlight-new-match
  10605. (match-beginning 1) (match-end 1)))
  10606. (org-show-context 'tags-tree))
  10607. ((eq action 'agenda)
  10608. (setq txt (org-agenda-format-item
  10609. ""
  10610. (concat
  10611. (if (eq org-tags-match-list-sublevels 'indented)
  10612. (make-string (1- level) ?.) "")
  10613. (org-get-heading))
  10614. (make-string level ?\s)
  10615. category
  10616. tags-list)
  10617. priority (org-get-priority txt))
  10618. (goto-char lspos)
  10619. (setq marker (org-agenda-new-marker))
  10620. (org-add-props txt props
  10621. 'org-marker marker 'org-hd-marker marker 'org-category category
  10622. 'todo-state todo
  10623. 'ts-date ts-date
  10624. 'priority priority
  10625. 'type (concat "tagsmatch" ts-date-type))
  10626. (push txt rtn))
  10627. ((functionp action)
  10628. (setq org-map-continue-from nil)
  10629. (save-excursion
  10630. (setq rtn1 (funcall action))
  10631. (push rtn1 rtn)))
  10632. (t (user-error "Invalid action")))
  10633. ;; if we are to skip sublevels, jump to end of subtree
  10634. (unless org-tags-match-list-sublevels
  10635. (org-end-of-subtree t)
  10636. (backward-char 1))))
  10637. ;; Get the correct position from where to continue
  10638. (if org-map-continue-from
  10639. (goto-char org-map-continue-from)
  10640. (and (= (point) lspos) (end-of-line 1))))))
  10641. (when (and (eq action 'sparse-tree)
  10642. (not org-sparse-tree-open-archived-trees))
  10643. (org-hide-archived-subtrees (point-min) (point-max)))
  10644. (nreverse rtn)))
  10645. (defun org-remove-uninherited-tags (tags)
  10646. "Remove all tags that are not inherited from the list TAGS."
  10647. (cond
  10648. ((eq org-use-tag-inheritance t)
  10649. (if org-tags-exclude-from-inheritance
  10650. (org-delete-all org-tags-exclude-from-inheritance tags)
  10651. tags))
  10652. ((not org-use-tag-inheritance) nil)
  10653. ((stringp org-use-tag-inheritance)
  10654. (delq nil (mapcar
  10655. (lambda (x)
  10656. (if (and (string-match org-use-tag-inheritance x)
  10657. (not (member x org-tags-exclude-from-inheritance)))
  10658. x nil))
  10659. tags)))
  10660. ((listp org-use-tag-inheritance)
  10661. (delq nil (mapcar
  10662. (lambda (x)
  10663. (if (member x org-use-tag-inheritance) x nil))
  10664. tags)))))
  10665. (defun org-match-sparse-tree (&optional todo-only match)
  10666. "Create a sparse tree according to tags string MATCH.
  10667. MATCH is a string with match syntax. It can contain a selection
  10668. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10669. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10670. those. See the manual for details.
  10671. If optional argument TODO-ONLY is non-nil, only select lines that
  10672. are also TODO tasks."
  10673. (interactive "P")
  10674. (org-agenda-prepare-buffers (list (current-buffer)))
  10675. (let ((org--matcher-tags-todo-only todo-only))
  10676. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10677. org--matcher-tags-todo-only)))
  10678. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10679. (defvar org-cached-props nil)
  10680. (defun org-cached-entry-get (pom property)
  10681. (if (or (eq t org-use-property-inheritance)
  10682. (and (stringp org-use-property-inheritance)
  10683. (let ((case-fold-search t))
  10684. (string-match-p org-use-property-inheritance property)))
  10685. (and (listp org-use-property-inheritance)
  10686. (member-ignore-case property org-use-property-inheritance)))
  10687. ;; Caching is not possible, check it directly.
  10688. (org-entry-get pom property 'inherit)
  10689. ;; Get all properties, so we can do complicated checks easily.
  10690. (cdr (assoc-string property
  10691. (or org-cached-props
  10692. (setq org-cached-props (org-entry-properties pom)))
  10693. t))))
  10694. (defun org-global-tags-completion-table (&optional files)
  10695. "Return the list of all tags in all agenda buffer/files.
  10696. Optional FILES argument is a list of files which can be used
  10697. instead of the agenda files."
  10698. (save-excursion
  10699. (org-uniquify
  10700. (delq nil
  10701. (apply #'append
  10702. (mapcar
  10703. (lambda (file)
  10704. (set-buffer (find-file-noselect file))
  10705. (org--tag-add-to-alist
  10706. (org-get-buffer-tags)
  10707. (mapcar (lambda (x)
  10708. (and (stringp (car-safe x))
  10709. (list (car-safe x))))
  10710. org-current-tag-alist)))
  10711. (if (car-safe files) files
  10712. (org-agenda-files))))))))
  10713. (defun org-make-tags-matcher (match &optional only-local-tags)
  10714. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10715. Returns a cons of the selection string MATCH and a function
  10716. implementing the matcher.
  10717. The matcher is to be called at an Org entry, with point on the
  10718. headline, and returns non-nil if the entry matches the selection
  10719. string MATCH. It must be called with three arguments: the TODO
  10720. keyword at the entry (or nil if none), the list of all tags at
  10721. the entry including inherited ones and the reduced level of the
  10722. headline. Additionally, the category of the entry, if any, must
  10723. be specified as the text property `org-category' on the headline.
  10724. This function sets the variable `org--matcher-tags-todo-only' to
  10725. a non-nil value if the matcher restricts matching to TODO
  10726. entries, otherwise it is not touched.
  10727. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10728. table, only get buffer tags.
  10729. See also `org-scan-tags'."
  10730. (unless match
  10731. ;; Get a new match request, with completion against the global
  10732. ;; tags table and the local tags in current buffer.
  10733. (let ((org-last-tags-completion-table
  10734. (org--tag-add-to-alist
  10735. (org-get-buffer-tags)
  10736. (unless only-local-tags
  10737. (org-global-tags-completion-table)))))
  10738. (setq match
  10739. (completing-read
  10740. "Match: "
  10741. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10742. (let ((match0 match)
  10743. (re (concat
  10744. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10745. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10746. "\\([<>=]\\{1,2\\}\\)"
  10747. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10748. "\\|" org-tag-re "\\)"))
  10749. (start 0)
  10750. tagsmatch todomatch tagsmatcher todomatcher)
  10751. ;; Expand group tags.
  10752. (setq match (org-tags-expand match))
  10753. ;; Check if there is a TODO part of this match, which would be the
  10754. ;; part after a "/". To make sure that this slash is not part of
  10755. ;; a property value to be matched against, we also check that
  10756. ;; there is no / after that slash. First, find the last slash.
  10757. (let ((s 0))
  10758. (while (string-match "/+" match s)
  10759. (setq start (match-beginning 0))
  10760. (setq s (match-end 0))))
  10761. (if (and (string-match "/+" match start)
  10762. (not (string-match-p "\"" match start)))
  10763. ;; Match contains also a TODO-matching request.
  10764. (progn
  10765. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10766. (setq todomatch (substring match (match-end 0)))
  10767. (when (string-prefix-p "!" todomatch)
  10768. (setq org--matcher-tags-todo-only t)
  10769. (setq todomatch (substring todomatch 1)))
  10770. (when (string-match "\\`\\s-*\\'" todomatch)
  10771. (setq todomatch nil)))
  10772. ;; Only matching tags.
  10773. (setq tagsmatch match)
  10774. (setq todomatch nil))
  10775. ;; Make the tags matcher.
  10776. (when (org-string-nw-p tagsmatch)
  10777. (let ((orlist nil)
  10778. (orterms (org-split-string tagsmatch "|"))
  10779. term)
  10780. (while (setq term (pop orterms))
  10781. (while (and (equal (substring term -1) "\\") orterms)
  10782. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10783. (while (string-match re term)
  10784. (let* ((rest (substring term (match-end 0)))
  10785. (minus (and (match-end 1)
  10786. (equal (match-string 1 term) "-")))
  10787. (tag (save-match-data
  10788. (replace-regexp-in-string
  10789. "\\\\-" "-" (match-string 2 term))))
  10790. (regexp (eq (string-to-char tag) ?{))
  10791. (levelp (match-end 4))
  10792. (propp (match-end 5))
  10793. (mm
  10794. (cond
  10795. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10796. (levelp
  10797. `(,(org-op-to-function (match-string 3 term))
  10798. level
  10799. ,(string-to-number (match-string 4 term))))
  10800. (propp
  10801. (let* ((gv (pcase (upcase (match-string 5 term))
  10802. ("CATEGORY"
  10803. '(org-get-category (point)))
  10804. ("TODO" 'todo)
  10805. (p `(org-cached-entry-get nil ,p))))
  10806. (pv (match-string 7 term))
  10807. (regexp (eq (string-to-char pv) ?{))
  10808. (strp (eq (string-to-char pv) ?\"))
  10809. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10810. (po (org-op-to-function (match-string 6 term)
  10811. (if timep 'time strp))))
  10812. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10813. (when timep (setq pv (org-matcher-time pv)))
  10814. (cond ((and regexp (eq po '/=))
  10815. `(not (string-match ,pv (or ,gv ""))))
  10816. (regexp `(string-match ,pv (or ,gv "")))
  10817. (strp `(,po (or ,gv "") ,pv))
  10818. (t
  10819. `(,po
  10820. (string-to-number (or ,gv ""))
  10821. ,(string-to-number pv))))))
  10822. (t `(member ,tag tags-list)))))
  10823. (push (if minus `(not ,mm) mm) tagsmatcher)
  10824. (setq term rest)))
  10825. (push `(and ,@tagsmatcher) orlist)
  10826. (setq tagsmatcher nil))
  10827. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10828. ;; Make the TODO matcher.
  10829. (when (org-string-nw-p todomatch)
  10830. (let ((orlist nil))
  10831. (dolist (term (org-split-string todomatch "|"))
  10832. (while (string-match re term)
  10833. (let* ((minus (and (match-end 1)
  10834. (equal (match-string 1 term) "-")))
  10835. (kwd (match-string 2 term))
  10836. (regexp (eq (string-to-char kwd) ?{))
  10837. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10838. `(equal todo ,kwd))))
  10839. (push (if minus `(not ,mm) mm) todomatcher))
  10840. (setq term (substring term (match-end 0))))
  10841. (push (if (> (length todomatcher) 1)
  10842. (cons 'and todomatcher)
  10843. (car todomatcher))
  10844. orlist)
  10845. (setq todomatcher nil))
  10846. (setq todomatcher (cons 'or orlist))))
  10847. ;; Return the string and function of the matcher. If no
  10848. ;; tags-specific or todo-specific matcher exists, match
  10849. ;; everything.
  10850. (let ((matcher (if (and tagsmatcher todomatcher)
  10851. `(and ,tagsmatcher ,todomatcher)
  10852. (or tagsmatcher todomatcher t))))
  10853. (when org--matcher-tags-todo-only
  10854. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10855. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10856. (defun org--tags-expand-group (group tag-groups expanded)
  10857. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10858. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10859. an accumulator used in recursive calls."
  10860. (dolist (tag group)
  10861. (unless (member tag expanded)
  10862. (let ((group (assoc tag tag-groups)))
  10863. (push tag expanded)
  10864. (when group
  10865. (setq expanded
  10866. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10867. expanded)
  10868. (defun org-tags-expand (match &optional single-as-list)
  10869. "Expand group tags in MATCH.
  10870. This replaces every group tag in MATCH with a regexp tag search.
  10871. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10872. will be replaced like this:
  10873. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10874. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10875. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10876. Replacing by a regexp preserves the structure of the match.
  10877. E.g., this expansion
  10878. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10879. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10880. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10881. A group tag in MATCH can contain regular expressions of its own.
  10882. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10883. will be replaced like this:
  10884. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10885. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10886. assumed to be a single group tag, and the function will return
  10887. the list of tags in this group."
  10888. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10889. (let ((tag-groups
  10890. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10891. (cond
  10892. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10893. (org-group-tags
  10894. (let* ((case-fold-search t)
  10895. (tag-syntax org-mode-syntax-table)
  10896. (group-keys (mapcar #'car tag-groups))
  10897. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10898. (return-match match))
  10899. ;; Mark regexp-expressions in the match-expression so that we
  10900. ;; do not replace them later on.
  10901. (let ((s 0))
  10902. (while (string-match "{.+?}" return-match s)
  10903. (setq s (match-end 0))
  10904. (add-text-properties
  10905. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10906. ;; @ and _ are allowed as word-components in tags.
  10907. (modify-syntax-entry ?@ "w" tag-syntax)
  10908. (modify-syntax-entry ?_ "w" tag-syntax)
  10909. ;; For each tag token found in MATCH, compute a regexp and it
  10910. (with-syntax-table tag-syntax
  10911. (replace-regexp-in-string
  10912. key-regexp
  10913. (lambda (m)
  10914. (if (get-text-property (match-beginning 2) 'regexp m)
  10915. m ;regexp tag: ignore
  10916. (let* ((operator (match-string 1 m))
  10917. (tag-token (let ((tag (match-string 2 m)))
  10918. (list tag)))
  10919. regexp-tags regular-tags)
  10920. ;; Partition tags between regexp and regular tags.
  10921. ;; Remove curly bracket syntax from regexp tags.
  10922. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10923. (save-match-data
  10924. (if (string-match "{\\(.+?\\)}" tag)
  10925. (push (match-string 1 tag) regexp-tags)
  10926. (push tag regular-tags))))
  10927. ;; Replace tag token by the appropriate regexp.
  10928. ;; Regular tags need to be regexp-quoted, whereas
  10929. ;; regexp-tags are inserted as-is.
  10930. (let ((regular (regexp-opt regular-tags))
  10931. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10932. (concat operator
  10933. (cond
  10934. ((null regular-tags) (format "{%s}" regexp))
  10935. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10936. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10937. return-match
  10938. t t))))
  10939. (t match))))
  10940. (defun org-op-to-function (op &optional stringp)
  10941. "Turn an operator into the appropriate function."
  10942. (setq op
  10943. (cond
  10944. ((equal op "<" ) '(< org-string< org-time<))
  10945. ((equal op ">" ) '(> org-string> org-time>))
  10946. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10947. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10948. ((member op '("=" "==")) '(= string= org-time=))
  10949. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10950. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10951. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10952. (defvar org-tags-overlay (make-overlay 1 1))
  10953. (delete-overlay org-tags-overlay)
  10954. (defun org-add-prop-inherited (s)
  10955. (add-text-properties 0 (length s) '(inherited t) s)
  10956. s)
  10957. (defun org-toggle-tag (tag &optional onoff)
  10958. "Toggle the tag TAG for the current line.
  10959. If ONOFF is `on' or `off', don't toggle but set to this state."
  10960. (save-excursion
  10961. (org-back-to-heading t)
  10962. (let ((current
  10963. ;; Reverse the tags list so any new tag is appended to the
  10964. ;; current list of tags.
  10965. (nreverse (org-get-tags nil t)))
  10966. res)
  10967. (pcase onoff
  10968. (`off (setq current (delete tag current)))
  10969. ((or `on (guard (not (member tag current))))
  10970. (setq res t)
  10971. (cl-pushnew tag current :test #'equal))
  10972. (_ (setq current (delete tag current))))
  10973. (org-set-tags (nreverse current))
  10974. res)))
  10975. (defun org--align-tags-here (to-col)
  10976. "Align tags on the current headline to TO-COL.
  10977. Assume point is on a headline. Preserve point when aligning
  10978. tags."
  10979. (when (org-match-line org-tag-line-re)
  10980. (let* ((tags-start (match-beginning 1))
  10981. (blank-start (save-excursion
  10982. (goto-char tags-start)
  10983. (skip-chars-backward " \t")
  10984. (point)))
  10985. (new (max (if (>= to-col 0) to-col
  10986. (- (abs to-col) (string-width (match-string 1))))
  10987. ;; Introduce at least one space after the heading
  10988. ;; or the stars.
  10989. (save-excursion
  10990. (goto-char blank-start)
  10991. (1+ (current-column)))))
  10992. (current
  10993. (save-excursion (goto-char tags-start) (current-column)))
  10994. (origin (point-marker))
  10995. (column (current-column))
  10996. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10997. (when (/= new current)
  10998. (delete-region blank-start tags-start)
  10999. (goto-char blank-start)
  11000. (let ((indent-tabs-mode nil)) (indent-to new))
  11001. ;; Try to move back to original position. If point was in the
  11002. ;; blanks before the tags, ORIGIN marker is of no use because
  11003. ;; it now points to BLANK-START. Use COLUMN instead.
  11004. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  11005. (defun org-set-tags-command (&optional arg)
  11006. "Set the tags for the current visible entry.
  11007. When called with `\\[universal-argument]' prefix argument ARG, \
  11008. realign all tags
  11009. in the current buffer.
  11010. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11011. unconditionally do not
  11012. offer the fast tag selection interface.
  11013. If a region is active, set tags in the region according to the
  11014. setting of `org-loop-over-headlines-in-active-region'.
  11015. This function is for interactive use only;
  11016. in Lisp code use `org-set-tags' instead."
  11017. (interactive "P")
  11018. (let ((org-use-fast-tag-selection
  11019. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11020. (cond
  11021. ((equal '(4) arg) (org-align-tags t))
  11022. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11023. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  11024. (org-map-entries
  11025. #'org-set-tags-command
  11026. nil
  11027. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11028. 'region-start-level
  11029. 'region)
  11030. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11031. (t
  11032. (save-excursion
  11033. (org-back-to-heading)
  11034. (let* ((all-tags (org-get-tags))
  11035. (table (setq org-last-tags-completion-table
  11036. (org--tag-add-to-alist
  11037. (and org-complete-tags-always-offer-all-agenda-tags
  11038. (org-global-tags-completion-table
  11039. (org-agenda-files)))
  11040. (or org-current-tag-alist (org-get-buffer-tags)))))
  11041. (current-tags
  11042. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11043. all-tags))
  11044. (inherited-tags
  11045. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11046. all-tags))
  11047. (tags
  11048. (replace-regexp-in-string
  11049. ;; Ignore all forbidden characters in tags.
  11050. "[^[:alnum:]_@#%]+" ":"
  11051. (if (or (eq t org-use-fast-tag-selection)
  11052. (and org-use-fast-tag-selection
  11053. (delq nil (mapcar #'cdr table))))
  11054. (org-fast-tag-selection
  11055. current-tags
  11056. inherited-tags
  11057. table
  11058. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11059. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  11060. (crm-separator "[ \t]*:[ \t]*"))
  11061. (mapconcat #'identity
  11062. (completing-read-multiple
  11063. "Tags: "
  11064. org-last-tags-completion-table
  11065. nil nil (org-make-tag-string current-tags)
  11066. 'org-tags-history)
  11067. ":"))))))
  11068. (org-set-tags tags)))))
  11069. ;; `save-excursion' may not replace the point at the right
  11070. ;; position.
  11071. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  11072. (looking-at-p " "))
  11073. (forward-char))))
  11074. (defun org-align-tags (&optional all)
  11075. "Align tags in current entry.
  11076. When optional argument ALL is non-nil, align all tags in the
  11077. visible part of the buffer."
  11078. (let ((get-indent-column
  11079. (lambda ()
  11080. (let ((offset (if (bound-and-true-p org-indent-mode)
  11081. (* (1- org-indent-indentation-per-level)
  11082. (1- (org-current-level)))
  11083. 0)))
  11084. (+ org-tags-column
  11085. (if (> org-tags-column 0) (- offset) offset))))))
  11086. (if (and (not all) (org-at-heading-p))
  11087. (org--align-tags-here (funcall get-indent-column))
  11088. (save-excursion
  11089. (if all
  11090. (progn
  11091. (goto-char (point-min))
  11092. (while (re-search-forward org-tag-line-re nil t)
  11093. (org--align-tags-here (funcall get-indent-column))))
  11094. (org-back-to-heading t)
  11095. (org--align-tags-here (funcall get-indent-column)))))))
  11096. (defun org-set-tags (tags)
  11097. "Set the tags of the current entry to TAGS, replacing current tags.
  11098. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11099. If TAGS is nil or the empty string, all tags are removed.
  11100. This function assumes point is on a headline."
  11101. (org-with-wide-buffer
  11102. (let ((tags (pcase tags
  11103. ((pred listp) tags)
  11104. ((pred stringp) (split-string (org-trim tags) ":" t))
  11105. (_ (error "Invalid tag specification: %S" tags))))
  11106. (old-tags (org-get-tags nil t))
  11107. (tags-change? nil))
  11108. (when (functionp org-tags-sort-function)
  11109. (setq tags (sort tags org-tags-sort-function)))
  11110. (setq tags-change? (not (equal tags old-tags)))
  11111. (when tags-change?
  11112. ;; Delete previous tags and any trailing white space.
  11113. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11114. (line-end-position)))
  11115. (skip-chars-backward " \t")
  11116. (delete-region (point) (line-end-position))
  11117. ;; Deleting white spaces may break an otherwise empty headline.
  11118. ;; Re-introduce one space in this case.
  11119. (unless (org-at-heading-p) (insert " "))
  11120. (when tags
  11121. (save-excursion (insert " " (org-make-tag-string tags)))
  11122. ;; When text is being inserted on an invisible region
  11123. ;; boundary, it can be inadvertently sucked into
  11124. ;; invisibility.
  11125. (unless (org-invisible-p (line-beginning-position))
  11126. (org-flag-region (point) (line-end-position) nil 'outline))))
  11127. ;; Align tags, if any.
  11128. (when tags (org-align-tags))
  11129. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  11130. (defun org-change-tag-in-region (beg end tag off)
  11131. "Add or remove TAG for each entry in the region.
  11132. This works in the agenda, and also in an Org buffer."
  11133. (interactive
  11134. (list (region-beginning) (region-end)
  11135. (let ((org-last-tags-completion-table
  11136. (if (derived-mode-p 'org-mode)
  11137. (org--tag-add-to-alist
  11138. (org-get-buffer-tags)
  11139. (org-global-tags-completion-table))
  11140. (org-global-tags-completion-table))))
  11141. (completing-read
  11142. "Tag: " org-last-tags-completion-table nil nil nil
  11143. 'org-tags-history))
  11144. (progn
  11145. (message "[s]et or [r]emove? ")
  11146. (equal (read-char-exclusive) ?r))))
  11147. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11148. (let ((agendap (equal major-mode 'org-agenda-mode))
  11149. l1 l2 m buf pos newhead (cnt 0))
  11150. (goto-char end)
  11151. (setq l2 (1- (org-current-line)))
  11152. (goto-char beg)
  11153. (setq l1 (org-current-line))
  11154. (cl-loop for l from l1 to l2 do
  11155. (org-goto-line l)
  11156. (setq m (get-text-property (point) 'org-hd-marker))
  11157. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11158. (and agendap m))
  11159. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11160. pos (if agendap m (point)))
  11161. (with-current-buffer buf
  11162. (save-excursion
  11163. (save-restriction
  11164. (goto-char pos)
  11165. (setq cnt (1+ cnt))
  11166. (org-toggle-tag tag (if off 'off 'on))
  11167. (setq newhead (org-get-heading)))))
  11168. (and agendap (org-agenda-change-all-lines newhead m))))
  11169. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11170. (defun org-tags-completion-function (string _predicate &optional flag)
  11171. "Complete tag STRING.
  11172. FLAG specifies the type of completion operation to perform. This
  11173. function is passed as a collection function to `completing-read',
  11174. which see."
  11175. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11176. (confirm (lambda (x) (stringp (car x))))
  11177. (prefix ""))
  11178. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11179. (setq prefix (match-string 1 string))
  11180. (setq string (match-string 2 string)))
  11181. (pcase flag
  11182. (`t (all-completions string org-last-tags-completion-table confirm))
  11183. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11184. (`nil
  11185. (pcase (try-completion string org-last-tags-completion-table confirm)
  11186. ((and completion (pred stringp))
  11187. (concat prefix
  11188. completion
  11189. (if (and org-add-colon-after-tag-completion
  11190. (assoc completion org-last-tags-completion-table))
  11191. ":"
  11192. "")))
  11193. (completion completion)))
  11194. (_ nil))))
  11195. (defun org-fast-tag-insert (kwd tags face &optional end)
  11196. "Insert KWD, and the TAGS, the latter with face FACE.
  11197. Also insert END."
  11198. (insert (format "%-12s" (concat kwd ":"))
  11199. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11200. (or end "")))
  11201. (defun org-fast-tag-show-exit (flag)
  11202. (save-excursion
  11203. (org-goto-line 3)
  11204. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11205. (replace-match ""))
  11206. (when flag
  11207. (end-of-line 1)
  11208. (org-move-to-column (- (window-width) 19) t)
  11209. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11210. (defun org-set-current-tags-overlay (current prefix)
  11211. "Add an overlay to CURRENT tag with PREFIX."
  11212. (let ((s (org-make-tag-string current)))
  11213. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11214. (org-overlay-display org-tags-overlay (concat prefix s))))
  11215. (defvar org-last-tag-selection-key nil)
  11216. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11217. "Fast tag selection with single keys.
  11218. CURRENT is the current list of tags in the headline, INHERITED is the
  11219. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11220. possibly with grouping information. TODO-TABLE is a similar table with
  11221. TODO keywords, should these have keys assigned to them.
  11222. If the keys are nil, a-z are automatically assigned.
  11223. Returns the new tags string, or nil to not change the current settings."
  11224. (let* ((fulltable (append table todo-table))
  11225. (maxlen (if (null fulltable) 0
  11226. (apply #'max
  11227. (mapcar (lambda (x)
  11228. (if (stringp (car x)) (string-width (car x))
  11229. 0))
  11230. fulltable))))
  11231. (buf (current-buffer))
  11232. (expert (eq org-fast-tag-selection-single-key 'expert))
  11233. (tab-tags nil)
  11234. (fwidth (+ maxlen 3 1 3))
  11235. (ncol (/ (- (window-width) 4) fwidth))
  11236. (i-face 'org-done)
  11237. (c-face 'org-todo)
  11238. tg cnt e c char c1 c2 ntable tbl rtn
  11239. ov-start ov-end ov-prefix
  11240. (exit-after-next org-fast-tag-selection-single-key)
  11241. (done-keywords org-done-keywords)
  11242. groups ingroup intaggroup)
  11243. (save-excursion
  11244. (beginning-of-line)
  11245. (if (looking-at org-tag-line-re)
  11246. (setq ov-start (match-beginning 1)
  11247. ov-end (match-end 1)
  11248. ov-prefix "")
  11249. (setq ov-start (1- (point-at-eol))
  11250. ov-end (1+ ov-start))
  11251. (skip-chars-forward "^\n\r")
  11252. (setq ov-prefix
  11253. (concat
  11254. (buffer-substring (1- (point)) (point))
  11255. (if (> (current-column) org-tags-column)
  11256. " "
  11257. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11258. (move-overlay org-tags-overlay ov-start ov-end)
  11259. (save-excursion
  11260. (save-window-excursion
  11261. (if expert
  11262. (set-buffer (get-buffer-create " *Org tags*"))
  11263. (delete-other-windows)
  11264. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11265. (org-switch-to-buffer-other-window " *Org tags*"))
  11266. (erase-buffer)
  11267. (setq-local org-done-keywords done-keywords)
  11268. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11269. (org-fast-tag-insert "Current" current c-face "\n\n")
  11270. (org-fast-tag-show-exit exit-after-next)
  11271. (org-set-current-tags-overlay current ov-prefix)
  11272. (setq tbl fulltable char ?a cnt 0)
  11273. (while (setq e (pop tbl))
  11274. (cond
  11275. ((eq (car e) :startgroup)
  11276. (push '() groups) (setq ingroup t)
  11277. (unless (zerop cnt)
  11278. (setq cnt 0)
  11279. (insert "\n"))
  11280. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11281. ((eq (car e) :endgroup)
  11282. (setq ingroup nil cnt 0)
  11283. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11284. ((eq (car e) :startgrouptag)
  11285. (setq intaggroup t)
  11286. (unless (zerop cnt)
  11287. (setq cnt 0)
  11288. (insert "\n"))
  11289. (insert "[ "))
  11290. ((eq (car e) :endgrouptag)
  11291. (setq intaggroup nil cnt 0)
  11292. (insert "]\n"))
  11293. ((equal e '(:newline))
  11294. (unless (zerop cnt)
  11295. (setq cnt 0)
  11296. (insert "\n")
  11297. (setq e (car tbl))
  11298. (while (equal (car tbl) '(:newline))
  11299. (insert "\n")
  11300. (setq tbl (cdr tbl)))))
  11301. ((equal e '(:grouptags)) (insert " : "))
  11302. (t
  11303. (setq tg (copy-sequence (car e)) c2 nil)
  11304. (if (cdr e)
  11305. (setq c (cdr e))
  11306. ;; automatically assign a character.
  11307. (setq c1 (string-to-char
  11308. (downcase (substring
  11309. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11310. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11311. (while (or (rassoc char ntable) (rassoc char table))
  11312. (setq char (1+ char)))
  11313. (setq c2 c1))
  11314. (setq c (or c2 char)))
  11315. (when ingroup (push tg (car groups)))
  11316. (setq tg (org-add-props tg nil 'face
  11317. (cond
  11318. ((not (assoc tg table))
  11319. (org-get-todo-face tg))
  11320. ((member tg current) c-face)
  11321. ((member tg inherited) i-face))))
  11322. (when (equal (caar tbl) :grouptags)
  11323. (org-add-props tg nil 'face 'org-tag-group))
  11324. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11325. (insert "[" c "] " tg (make-string
  11326. (- fwidth 4 (length tg)) ?\ ))
  11327. (push (cons tg c) ntable)
  11328. (when (= (cl-incf cnt) ncol)
  11329. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11330. (insert "\n")
  11331. (when (or ingroup intaggroup) (insert " ")))
  11332. (setq cnt 0)))))
  11333. (setq ntable (nreverse ntable))
  11334. (insert "\n")
  11335. (goto-char (point-min))
  11336. (unless expert (org-fit-window-to-buffer))
  11337. (setq rtn
  11338. (catch 'exit
  11339. (while t
  11340. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11341. (if (not groups) "no " "")
  11342. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11343. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11344. (setq org-last-tag-selection-key c)
  11345. (cond
  11346. ((= c ?\r) (throw 'exit t))
  11347. ((= c ?!)
  11348. (setq groups (not groups))
  11349. (goto-char (point-min))
  11350. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11351. ((= c ?\C-c)
  11352. (if (not expert)
  11353. (org-fast-tag-show-exit
  11354. (setq exit-after-next (not exit-after-next)))
  11355. (setq expert nil)
  11356. (delete-other-windows)
  11357. (set-window-buffer (split-window-vertically) " *Org tags*")
  11358. (org-switch-to-buffer-other-window " *Org tags*")
  11359. (org-fit-window-to-buffer)))
  11360. ((or (= c ?\C-g)
  11361. (and (= c ?q) (not (rassoc c ntable))))
  11362. (delete-overlay org-tags-overlay)
  11363. (setq quit-flag t))
  11364. ((= c ?\ )
  11365. (setq current nil)
  11366. (when exit-after-next (setq exit-after-next 'now)))
  11367. ((= c ?\t)
  11368. (condition-case nil
  11369. (unless tab-tags
  11370. (setq tab-tags
  11371. (delq nil
  11372. (mapcar (lambda (x)
  11373. (let ((item (car-safe x)))
  11374. (and (stringp item)
  11375. (list item))))
  11376. (org--tag-add-to-alist
  11377. (with-current-buffer buf
  11378. (org-get-buffer-tags))
  11379. table))))))
  11380. (setq tg (completing-read "Tag: " tab-tags))
  11381. (when (string-match "\\S-" tg)
  11382. (cl-pushnew (list tg) tab-tags :test #'equal)
  11383. (if (member tg current)
  11384. (setq current (delete tg current))
  11385. (push tg current)))
  11386. (when exit-after-next (setq exit-after-next 'now)))
  11387. ((setq e (rassoc c todo-table) tg (car e))
  11388. (with-current-buffer buf
  11389. (save-excursion (org-todo tg)))
  11390. (when exit-after-next (setq exit-after-next 'now)))
  11391. ((setq e (rassoc c ntable) tg (car e))
  11392. (if (member tg current)
  11393. (setq current (delete tg current))
  11394. (cl-loop for g in groups do
  11395. (when (member tg g)
  11396. (dolist (x g) (setq current (delete x current)))))
  11397. (push tg current))
  11398. (when exit-after-next (setq exit-after-next 'now))))
  11399. ;; Create a sorted list
  11400. (setq current
  11401. (sort current
  11402. (lambda (a b)
  11403. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11404. (when (eq exit-after-next 'now) (throw 'exit t))
  11405. (goto-char (point-min))
  11406. (beginning-of-line 2)
  11407. (delete-region (point) (point-at-eol))
  11408. (org-fast-tag-insert "Current" current c-face)
  11409. (org-set-current-tags-overlay current ov-prefix)
  11410. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11411. (while (re-search-forward tag-re nil t)
  11412. (let ((tag (match-string 1)))
  11413. (add-text-properties
  11414. (match-beginning 1) (match-end 1)
  11415. (list 'face
  11416. (cond
  11417. ((member tag current) c-face)
  11418. ((member tag inherited) i-face)
  11419. (t (get-text-property (match-beginning 1) '
  11420. face))))))))
  11421. (goto-char (point-min)))))
  11422. (delete-overlay org-tags-overlay)
  11423. (if rtn
  11424. (mapconcat 'identity current ":")
  11425. nil)))))
  11426. (defun org-make-tag-string (tags)
  11427. "Return string associated to TAGS.
  11428. TAGS is a list of strings."
  11429. (if (null tags) ""
  11430. (format ":%s:" (mapconcat #'identity tags ":"))))
  11431. (defun org--get-local-tags ()
  11432. "Return list of tags for the current headline.
  11433. Assume point is at the beginning of the headline."
  11434. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  11435. (cached-tags (org-element-property :tags cached)))
  11436. (if cached
  11437. ;; If we do not wrap result into `cl-copy-list', reference would
  11438. ;; be returned and cache element might be modified directly.
  11439. (cl-copy-list cached-tags)
  11440. ;; Parse tags manually.
  11441. (and (looking-at org-tag-line-re)
  11442. (split-string (match-string-no-properties 2) ":" t)))))
  11443. (defun org-get-tags (&optional pos-or-element local)
  11444. "Get the list of tags specified in the current headline.
  11445. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  11446. POS.
  11447. According to `org-use-tag-inheritance', tags may be inherited
  11448. from parent headlines, and from the whole document, through
  11449. `org-file-tags'. In this case, the returned list of tags
  11450. contains tags in this order: file tags, tags inherited from
  11451. parent headlines, local tags. If a tag appears multiple times,
  11452. only the most local tag is returned.
  11453. However, when optional argument LOCAL is non-nil, only return
  11454. tags specified at the headline.
  11455. Inherited tags have the `inherited' text property."
  11456. (save-match-data
  11457. (if (and org-trust-scanner-tags
  11458. (or (not pos-or-element) (eq pos-or-element (point)))
  11459. (not local))
  11460. org-scanner-tags
  11461. (org-with-point-at (unless (org-element-type pos-or-element)
  11462. (or pos-or-element (point)))
  11463. (unless (and (not (org-element-type pos-or-element))
  11464. (org-before-first-heading-p))
  11465. (unless (org-element-type pos-or-element) (org-back-to-heading t))
  11466. (let ((ltags (if (org-element-type pos-or-element)
  11467. (org-element-property :tags (org-element-lineage pos-or-element '(headline) t))
  11468. (org--get-local-tags)))
  11469. itags)
  11470. (if (or local (not org-use-tag-inheritance)) ltags
  11471. (let ((cached (and (org-element--cache-active-p)
  11472. (if (org-element-type pos-or-element)
  11473. (org-element-lineage pos-or-element '(headline) t)
  11474. (org-element-at-point nil 'cached)))))
  11475. (if cached
  11476. (while (setq cached (org-element-property :parent cached))
  11477. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11478. ;; If we do not wrap result into `cl-copy-list', reference would
  11479. ;; be returned and cache element might be modified directly.
  11480. (cl-copy-list (org-element-property :tags cached)))
  11481. itags)))
  11482. (while (org-up-heading-safe)
  11483. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11484. (org--get-local-tags))
  11485. itags)))))
  11486. (setq itags (append org-file-tags itags))
  11487. (nreverse
  11488. (delete-dups
  11489. (nreverse (nconc (org-remove-uninherited-tags itags) ltags)))))))))))
  11490. (defun org-get-buffer-tags ()
  11491. "Get a table of all tags used in the buffer, for completion."
  11492. (org-with-point-at 1
  11493. (let (tags)
  11494. (while (re-search-forward org-tag-line-re nil t)
  11495. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11496. tags)))
  11497. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11498. ;;;; The mapping API
  11499. (defvar org-agenda-skip-comment-trees)
  11500. (defvar org-agenda-skip-function)
  11501. (defun org-map-entries (func &optional match scope &rest skip)
  11502. "Call FUNC at each headline selected by MATCH in SCOPE.
  11503. FUNC is a function or a Lisp form. The function will be called without
  11504. arguments, with the cursor positioned at the beginning of the headline.
  11505. The return values of all calls to the function will be collected and
  11506. returned as a list.
  11507. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  11508. does not need to preserve point. After evaluation, the cursor will be
  11509. moved to the end of the line (presumably of the headline of the
  11510. processed entry) and search continues from there. Under some
  11511. circumstances, this may not produce the wanted results. For example,
  11512. if you have removed (e.g. archived) the current (sub)tree it could
  11513. mean that the next entry will be skipped entirely. In such cases, you
  11514. can specify the position from where search should continue by making
  11515. FUNC set the variable `org-map-continue-from' to the desired buffer
  11516. position.
  11517. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11518. Only headlines that are matched by this query will be considered during
  11519. the iteration. When MATCH is nil or t, all headlines will be
  11520. visited by the iteration.
  11521. SCOPE determines the scope of this command. It can be any of:
  11522. nil The current buffer, respecting the restriction if any
  11523. tree The subtree started with the entry at point
  11524. region The entries within the active region, if any
  11525. region-start-level
  11526. The entries within the active region, but only those at
  11527. the same level than the first one.
  11528. file The current buffer, without restriction
  11529. file-with-archives
  11530. The current buffer, and any archives associated with it
  11531. agenda All agenda files
  11532. agenda-with-archives
  11533. All agenda files with any archive files associated with them
  11534. \(file1 file2 ...)
  11535. If this is a list, all files in the list will be scanned
  11536. The remaining args are treated as settings for the skipping facilities of
  11537. the scanner. The following items can be given here:
  11538. archive skip trees with the archive tag
  11539. comment skip trees with the COMMENT keyword
  11540. function or Emacs Lisp form:
  11541. will be used as value for `org-agenda-skip-function', so
  11542. whenever the function returns a position, FUNC will not be
  11543. called for that entry and search will continue from the
  11544. position returned
  11545. If your function needs to retrieve the tags including inherited tags
  11546. at the *current* entry, you can use the value of the variable
  11547. `org-scanner-tags' which will be much faster than getting the value
  11548. with `org-get-tags'. If your function gets properties with
  11549. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11550. to t around the call to `org-entry-properties' to get the same speedup.
  11551. Note that if your function moves around to retrieve tags and properties at
  11552. a *different* entry, you cannot use these techniques."
  11553. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11554. (not (org-region-active-p)))
  11555. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11556. (org-agenda-skip-archived-trees (memq 'archive skip))
  11557. (org-agenda-skip-comment-trees (memq 'comment skip))
  11558. (org-agenda-skip-function
  11559. (car (org-delete-all '(comment archive) skip)))
  11560. (org-tags-match-list-sublevels t)
  11561. (start-level (eq scope 'region-start-level))
  11562. matcher res
  11563. org-todo-keywords-for-agenda
  11564. org-done-keywords-for-agenda
  11565. org-todo-keyword-alist-for-agenda
  11566. org-tag-alist-for-agenda
  11567. org--matcher-tags-todo-only)
  11568. (cond
  11569. ((eq match t) (setq matcher t))
  11570. ((eq match nil) (setq matcher t))
  11571. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11572. (save-excursion
  11573. (save-restriction
  11574. (cond ((eq scope 'tree)
  11575. (org-back-to-heading t)
  11576. (org-narrow-to-subtree)
  11577. (setq scope nil))
  11578. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11579. (org-region-active-p))
  11580. ;; If needed, set start-level to a string like "2"
  11581. (when start-level
  11582. (save-excursion
  11583. (goto-char (region-beginning))
  11584. (unless (org-at-heading-p) (outline-next-heading))
  11585. (setq start-level (org-current-level))))
  11586. (narrow-to-region (region-beginning)
  11587. (save-excursion
  11588. (goto-char (region-end))
  11589. (unless (and (bolp) (org-at-heading-p))
  11590. (outline-next-heading))
  11591. (point)))
  11592. (setq scope nil)))
  11593. (if (not scope)
  11594. (progn
  11595. (org-agenda-prepare-buffers
  11596. (and buffer-file-name (list buffer-file-name)))
  11597. (setq res
  11598. (org-scan-tags
  11599. func matcher org--matcher-tags-todo-only start-level)))
  11600. ;; Get the right scope
  11601. (cond
  11602. ((and scope (listp scope) (symbolp (car scope)))
  11603. (setq scope (eval scope)))
  11604. ((eq scope 'agenda)
  11605. (setq scope (org-agenda-files t)))
  11606. ((eq scope 'agenda-with-archives)
  11607. (setq scope (org-agenda-files t))
  11608. (setq scope (org-add-archive-files scope)))
  11609. ((eq scope 'file)
  11610. (setq scope (and buffer-file-name (list buffer-file-name))))
  11611. ((eq scope 'file-with-archives)
  11612. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11613. (org-agenda-prepare-buffers scope)
  11614. (dolist (file scope)
  11615. (with-current-buffer (org-find-base-buffer-visiting file)
  11616. (org-with-wide-buffer
  11617. (goto-char (point-min))
  11618. (setq res
  11619. (append
  11620. res
  11621. (org-scan-tags
  11622. func matcher org--matcher-tags-todo-only)))))))))
  11623. res)))
  11624. ;;; Properties API
  11625. (defconst org-special-properties
  11626. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11627. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11628. "The special properties valid in Org mode.
  11629. These are properties that are not defined in the property drawer,
  11630. but in some other way.")
  11631. (defconst org-default-properties
  11632. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11633. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11634. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11635. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11636. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11637. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11638. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11639. "Some properties that are used by Org mode for various purposes.
  11640. Being in this list makes sure that they are offered for completion.")
  11641. (defun org--valid-property-p (property)
  11642. "Non-nil when string PROPERTY is a valid property name."
  11643. (not
  11644. (or (equal property "")
  11645. (string-match-p "\\s-" property))))
  11646. (defun org--update-property-plist (key val props)
  11647. "Associate KEY to VAL in alist PROPS.
  11648. Modifications are made by side-effect. Return new alist."
  11649. (let* ((appending (string= (substring key -1) "+"))
  11650. (key (if appending (substring key 0 -1) key))
  11651. (old (assoc-string key props t)))
  11652. (if (not old) (cons (cons key val) props)
  11653. (setcdr old (if appending (concat (cdr old) " " val) val))
  11654. props)))
  11655. (defun org-get-property-block (&optional beg force)
  11656. "Return the (beg . end) range of the body of the property drawer.
  11657. BEG is the beginning of the current subtree or the beginning of
  11658. the document if before the first headline. If it is not given,
  11659. it will be found. If the drawer does not exist, create it if
  11660. FORCE is non-nil, or return nil."
  11661. (org-with-wide-buffer
  11662. (let ((beg (cond (beg (goto-char beg))
  11663. ((or (not (featurep 'org-inlinetask))
  11664. (org-inlinetask-in-task-p))
  11665. (org-back-to-heading-or-point-min t) (point))
  11666. (t (org-with-limited-levels
  11667. (org-back-to-heading-or-point-min t))
  11668. (point)))))
  11669. ;; Move point to its position according to its positional rules.
  11670. (cond ((org-before-first-heading-p)
  11671. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11672. (t (forward-line)
  11673. (when (looking-at-p org-planning-line-re) (forward-line))))
  11674. (cond ((looking-at org-property-drawer-re)
  11675. (forward-line)
  11676. (cons (point) (progn (goto-char (match-end 0))
  11677. (line-beginning-position))))
  11678. (force
  11679. (goto-char beg)
  11680. (org-insert-property-drawer)
  11681. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11682. (line-beginning-position))))
  11683. (cons pos pos)))))))
  11684. (defun org-at-property-drawer-p ()
  11685. "Non-nil when point is at the first line of a property drawer."
  11686. (org-with-wide-buffer
  11687. (beginning-of-line)
  11688. (and (looking-at org-property-drawer-re)
  11689. (or (bobp)
  11690. (progn
  11691. (forward-line -1)
  11692. (cond ((org-at-heading-p))
  11693. ((looking-at org-planning-line-re)
  11694. (forward-line -1)
  11695. (org-at-heading-p))
  11696. ((looking-at org-comment-regexp)
  11697. (forward-line -1)
  11698. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11699. (forward-line -1))
  11700. (looking-at org-comment-regexp))
  11701. (t nil)))))))
  11702. (defun org-at-property-p ()
  11703. "Non-nil when point is inside a property drawer.
  11704. See `org-property-re' for match data, if applicable."
  11705. (save-excursion
  11706. (beginning-of-line)
  11707. (and (looking-at org-property-re)
  11708. (let ((property-drawer (save-match-data (org-get-property-block))))
  11709. (and property-drawer
  11710. (>= (point) (car property-drawer))
  11711. (< (point) (cdr property-drawer)))))))
  11712. (defun org-property-action ()
  11713. "Do an action on properties."
  11714. (interactive)
  11715. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11716. (let ((c (read-char-exclusive)))
  11717. (cl-case c
  11718. (?s (call-interactively #'org-set-property))
  11719. (?d (call-interactively #'org-delete-property))
  11720. (?D (call-interactively #'org-delete-property-globally))
  11721. (?c (call-interactively #'org-compute-property-at-point))
  11722. (otherwise (user-error "No such property action %c" c)))))
  11723. (defun org-inc-effort ()
  11724. "Increment the value of the effort property in the current entry."
  11725. (interactive)
  11726. (org-set-effort t))
  11727. (defvar org-clock-effort) ; Defined in org-clock.el.
  11728. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11729. (defun org-set-effort (&optional increment value)
  11730. "Set the effort property of the current entry.
  11731. If INCREMENT is non-nil, set the property to the next allowed
  11732. value. Otherwise, if optional argument VALUE is provided, use
  11733. it. Eventually, prompt for the new value if none of the previous
  11734. variables is set."
  11735. (interactive "P")
  11736. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11737. (current (org-entry-get nil org-effort-property))
  11738. (value
  11739. (cond
  11740. (increment
  11741. (unless allowed (user-error "Allowed effort values are not set"))
  11742. (or (cl-caadr (member (list current) allowed))
  11743. (user-error "Unknown value %S among allowed values" current)))
  11744. (value
  11745. (if (stringp value) value
  11746. (error "Invalid effort value: %S" value)))
  11747. (t
  11748. (let ((must-match
  11749. (and allowed
  11750. (not (get-text-property 0 'org-unrestricted
  11751. (caar allowed))))))
  11752. (completing-read "Effort: " allowed nil must-match))))))
  11753. ;; Test whether the value can be interpreted as a duration before
  11754. ;; inserting it in the buffer:
  11755. (org-duration-to-minutes value)
  11756. ;; Maybe update the effort value:
  11757. (unless (equal current value)
  11758. (org-entry-put nil org-effort-property value))
  11759. (org-refresh-property '((effort . identity)
  11760. (effort-minutes . org-duration-to-minutes))
  11761. value)
  11762. (when (equal (org-get-heading t t t t)
  11763. (bound-and-true-p org-clock-current-task))
  11764. (setq org-clock-effort value)
  11765. (org-clock-update-mode-line))
  11766. (message "%s is now %s" org-effort-property value)))
  11767. (defun org-entry-properties (&optional pom which)
  11768. "Get all properties of the current entry.
  11769. When POM is a buffer position, get all properties from the entry
  11770. there instead.
  11771. This includes the TODO keyword, the tags, time strings for
  11772. deadline, scheduled, and clocking, and any additional properties
  11773. defined in the entry.
  11774. If WHICH is nil or `all', get all properties. If WHICH is
  11775. `special' or `standard', only get that subclass. If WHICH is
  11776. a string, only get that property.
  11777. Return value is an alist. Keys are properties, as upcased
  11778. strings."
  11779. (org-with-point-at pom
  11780. (when (and (derived-mode-p 'org-mode)
  11781. (org-back-to-heading-or-point-min t))
  11782. (catch 'exit
  11783. (let* ((beg (point))
  11784. (specific (and (stringp which) (upcase which)))
  11785. (which (cond ((not specific) which)
  11786. ((member specific org-special-properties) 'special)
  11787. (t 'standard)))
  11788. props)
  11789. ;; Get the special properties, like TODO and TAGS.
  11790. (when (memq which '(nil all special))
  11791. (when (or (not specific) (string= specific "CLOCKSUM"))
  11792. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11793. (when clocksum
  11794. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11795. props)))
  11796. (when specific (throw 'exit props)))
  11797. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11798. (let ((clocksumt (get-text-property (point)
  11799. :org-clock-minutes-today)))
  11800. (when clocksumt
  11801. (push (cons "CLOCKSUM_T"
  11802. (org-duration-from-minutes clocksumt))
  11803. props)))
  11804. (when specific (throw 'exit props)))
  11805. (when (or (not specific) (string= specific "ITEM"))
  11806. (let ((case-fold-search nil))
  11807. (when (looking-at org-complex-heading-regexp)
  11808. (push (cons "ITEM"
  11809. (let ((title (match-string-no-properties 4)))
  11810. (if (org-string-nw-p title)
  11811. (org-remove-tabs title)
  11812. "")))
  11813. props)))
  11814. (when specific (throw 'exit props)))
  11815. (when (or (not specific) (string= specific "TODO"))
  11816. (let ((case-fold-search nil))
  11817. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11818. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11819. (when specific (throw 'exit props)))
  11820. (when (or (not specific) (string= specific "PRIORITY"))
  11821. (push (cons "PRIORITY"
  11822. (if (looking-at org-priority-regexp)
  11823. (match-string-no-properties 2)
  11824. (char-to-string org-priority-default)))
  11825. props)
  11826. (when specific (throw 'exit props)))
  11827. (when (or (not specific) (string= specific "FILE"))
  11828. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11829. props)
  11830. (when specific (throw 'exit props)))
  11831. (when (or (not specific) (string= specific "TAGS"))
  11832. (let ((tags (org-get-tags nil t)))
  11833. (when tags
  11834. (push (cons "TAGS" (org-make-tag-string tags))
  11835. props)))
  11836. (when specific (throw 'exit props)))
  11837. (when (or (not specific) (string= specific "ALLTAGS"))
  11838. (let ((tags (org-get-tags)))
  11839. (when tags
  11840. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11841. props)))
  11842. (when specific (throw 'exit props)))
  11843. (when (or (not specific) (string= specific "BLOCKED"))
  11844. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11845. (when specific (throw 'exit props)))
  11846. (when (or (not specific)
  11847. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11848. (forward-line)
  11849. (when (looking-at-p org-planning-line-re)
  11850. (end-of-line)
  11851. (let ((bol (line-beginning-position))
  11852. ;; Backward compatibility: time keywords used to
  11853. ;; be configurable (before 8.3). Make sure we
  11854. ;; get the correct keyword.
  11855. (key-assoc `(("CLOSED" . ,org-closed-string)
  11856. ("DEADLINE" . ,org-deadline-string)
  11857. ("SCHEDULED" . ,org-scheduled-string))))
  11858. (dolist (pair (if specific (list (assoc specific key-assoc))
  11859. key-assoc))
  11860. (save-excursion
  11861. (when (search-backward (cdr pair) bol t)
  11862. (goto-char (match-end 0))
  11863. (skip-chars-forward " \t")
  11864. (and (looking-at org-ts-regexp-both)
  11865. (push (cons (car pair)
  11866. (match-string-no-properties 0))
  11867. props)))))))
  11868. (when specific (throw 'exit props)))
  11869. (when (or (not specific)
  11870. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11871. (let ((find-ts
  11872. (lambda (end ts)
  11873. ;; Fix next time-stamp before END. TS is the
  11874. ;; list of time-stamps found so far.
  11875. (let ((ts ts)
  11876. (regexp (cond
  11877. ((string= specific "TIMESTAMP")
  11878. org-ts-regexp)
  11879. ((string= specific "TIMESTAMP_IA")
  11880. org-ts-regexp-inactive)
  11881. ((assoc "TIMESTAMP_IA" ts)
  11882. org-ts-regexp)
  11883. ((assoc "TIMESTAMP" ts)
  11884. org-ts-regexp-inactive)
  11885. (t org-ts-regexp-both))))
  11886. (catch 'next
  11887. (while (re-search-forward regexp end t)
  11888. (backward-char)
  11889. (let ((object (org-element-context)))
  11890. ;; Accept to match timestamps in node
  11891. ;; properties, too.
  11892. (when (memq (org-element-type object)
  11893. '(node-property timestamp))
  11894. (let ((type
  11895. (org-element-property :type object)))
  11896. (cond
  11897. ((and (memq type '(active active-range))
  11898. (not (equal specific "TIMESTAMP_IA")))
  11899. (unless (assoc "TIMESTAMP" ts)
  11900. (push (cons "TIMESTAMP"
  11901. (org-element-property
  11902. :raw-value object))
  11903. ts)
  11904. (when specific (throw 'exit ts))))
  11905. ((and (memq type '(inactive inactive-range))
  11906. (not (string= specific "TIMESTAMP")))
  11907. (unless (assoc "TIMESTAMP_IA" ts)
  11908. (push (cons "TIMESTAMP_IA"
  11909. (org-element-property
  11910. :raw-value object))
  11911. ts)
  11912. (when specific (throw 'exit ts))))))
  11913. ;; Both timestamp types are found,
  11914. ;; move to next part.
  11915. (when (= (length ts) 2) (throw 'next ts)))))
  11916. ts)))))
  11917. (goto-char beg)
  11918. ;; First look for timestamps within headline.
  11919. (let ((ts (funcall find-ts (line-end-position) nil)))
  11920. (if (= (length ts) 2) (setq props (nconc ts props))
  11921. ;; Then find timestamps in the section, skipping
  11922. ;; planning line.
  11923. (let ((end (save-excursion (outline-next-heading))))
  11924. (forward-line)
  11925. (when (looking-at-p org-planning-line-re) (forward-line))
  11926. (setq props (nconc (funcall find-ts end ts) props))))))))
  11927. ;; Get the standard properties, like :PROP:.
  11928. (when (memq which '(nil all standard))
  11929. ;; If we are looking after a specific property, delegate
  11930. ;; to `org-entry-get', which is faster. However, make an
  11931. ;; exception for "CATEGORY", since it can be also set
  11932. ;; through keywords (i.e. #+CATEGORY).
  11933. (if (and specific (not (equal specific "CATEGORY")))
  11934. (let ((value (org-entry-get beg specific nil t)))
  11935. (throw 'exit (and value (list (cons specific value)))))
  11936. (let ((range (org-get-property-block beg)))
  11937. (when range
  11938. (let ((end (cdr range)) seen-base)
  11939. (goto-char (car range))
  11940. ;; Unlike to `org--update-property-plist', we
  11941. ;; handle the case where base values is found
  11942. ;; after its extension. We also forbid standard
  11943. ;; properties to be named as special properties.
  11944. (while (re-search-forward org-property-re end t)
  11945. (let* ((key (upcase (match-string-no-properties 2)))
  11946. (extendp (string-match-p "\\+\\'" key))
  11947. (key-base (if extendp (substring key 0 -1) key))
  11948. (value (match-string-no-properties 3)))
  11949. (cond
  11950. ((member-ignore-case key-base org-special-properties))
  11951. (extendp
  11952. (setq props
  11953. (org--update-property-plist key value props)))
  11954. ((member key seen-base))
  11955. (t (push key seen-base)
  11956. (let ((p (assoc-string key props t)))
  11957. (if p (setcdr p (concat value " " (cdr p)))
  11958. (push (cons key value) props))))))))))))
  11959. (unless (assoc "CATEGORY" props)
  11960. (push (cons "CATEGORY" (org-get-category beg)) props)
  11961. (when (string= specific "CATEGORY") (throw 'exit props)))
  11962. ;; Return value.
  11963. props)))))
  11964. (defun org--property-local-values (property literal-nil &optional element)
  11965. "Return value for PROPERTY in current entry or ELEMENT.
  11966. Value is a list whose car is the base value for PROPERTY and cdr
  11967. a list of accumulated values. Return nil if neither is found in
  11968. the entry. Also return nil when PROPERTY is set to \"nil\",
  11969. unless LITERAL-NIL is non-nil."
  11970. (let ((element (or element
  11971. (and (org-element--cache-active-p)
  11972. (org-element-at-point nil 'cached)))))
  11973. (if element
  11974. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11975. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11976. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11977. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11978. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11979. (value (cons base-value extra-value)))
  11980. (and (not (equal value '(nil))) value))
  11981. (let ((range (org-get-property-block)))
  11982. (when range
  11983. (goto-char (car range))
  11984. (let* ((case-fold-search t)
  11985. (end (cdr range))
  11986. (value
  11987. ;; Base value.
  11988. (save-excursion
  11989. (let ((v (and (re-search-forward
  11990. (org-re-property property nil t) end t)
  11991. (match-string-no-properties 3))))
  11992. (list (if literal-nil v (org-not-nil v)))))))
  11993. ;; Find additional values.
  11994. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11995. (while (re-search-forward property+ end t)
  11996. (push (match-string-no-properties 3) value)))
  11997. ;; Return final values.
  11998. (and (not (equal value '(nil))) (nreverse value))))))))
  11999. (defun org--property-global-or-keyword-value (property literal-nil)
  12000. "Return value for PROPERTY as defined by global properties or by keyword.
  12001. Return value is a string. Return nil if property is not set
  12002. globally or by keyword. Also return nil when PROPERTY is set to
  12003. \"nil\", unless LITERAL-NIL is non-nil."
  12004. (let ((global
  12005. (cdr (or (assoc-string property org-keyword-properties t)
  12006. (assoc-string property org-global-properties t)
  12007. (assoc-string property org-global-properties-fixed t)))))
  12008. (if literal-nil global (org-not-nil global))))
  12009. (defun org-entry-get (pom property &optional inherit literal-nil)
  12010. "Get value of PROPERTY for entry or content at point-or-marker POM.
  12011. If INHERIT is non-nil and the entry does not have the property,
  12012. then also check higher levels of the hierarchy. If INHERIT is
  12013. the symbol `selective', use inheritance only if the setting in
  12014. `org-use-property-inheritance' selects PROPERTY for inheritance.
  12015. If the property is present but empty, the return value is the
  12016. empty string. If the property is not present at all, nil is
  12017. returned. In any other case, return the value as a string.
  12018. Search is case-insensitive.
  12019. If LITERAL-NIL is set, return the string value \"nil\" as
  12020. a string, do not interpret it as the list atom nil. This is used
  12021. for inheritance when a \"nil\" value can supersede a non-nil
  12022. value higher up the hierarchy."
  12023. (org-with-point-at pom
  12024. (cond
  12025. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12026. ;; We need a special property. Use `org-entry-properties' to
  12027. ;; retrieve it, but specify the wanted property.
  12028. (cdr (assoc-string property (org-entry-properties nil property))))
  12029. ((and inherit
  12030. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12031. (org-entry-get-with-inheritance property literal-nil))
  12032. (t
  12033. (let* ((local (org--property-local-values property literal-nil))
  12034. (value (and local (mapconcat #'identity (delq nil local) " "))))
  12035. (if literal-nil value (org-not-nil value)))))))
  12036. (defun org-property-or-variable-value (var &optional inherit)
  12037. "Check if there is a property fixing the value of VAR.
  12038. If yes, return this value. If not, return the current value of the variable."
  12039. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12040. (if (and prop (stringp prop) (string-match "\\S-" prop))
  12041. (read prop)
  12042. (symbol-value var))))
  12043. (defun org-entry-delete (pom property)
  12044. "Delete PROPERTY from entry at point-or-marker POM.
  12045. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  12046. non-nil when a property was removed."
  12047. (org-with-point-at pom
  12048. (pcase (org-get-property-block)
  12049. (`(,begin . ,origin)
  12050. (let* ((end (copy-marker origin))
  12051. (re (org-re-property
  12052. (concat (regexp-quote property) "\\+?") t t)))
  12053. (goto-char begin)
  12054. (while (re-search-forward re end t)
  12055. (delete-region (match-beginning 0) (line-beginning-position 2)))
  12056. ;; If drawer is empty, remove it altogether.
  12057. (when (= begin end)
  12058. (delete-region (line-beginning-position 0)
  12059. (line-beginning-position 2)))
  12060. ;; Return non-nil if some property was removed.
  12061. (prog1 (/= end origin) (set-marker end nil))))
  12062. (_ nil))))
  12063. ;; Multi-values properties are properties that contain multiple values
  12064. ;; These values are assumed to be single words, separated by whitespace.
  12065. (defun org-entry-add-to-multivalued-property (pom property value)
  12066. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12067. (let* ((old (org-entry-get pom property))
  12068. (values (and old (split-string old))))
  12069. (setq value (org-entry-protect-space value))
  12070. (unless (member value values)
  12071. (setq values (append values (list value)))
  12072. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12073. (defun org-entry-remove-from-multivalued-property (pom property value)
  12074. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12075. (let* ((old (org-entry-get pom property))
  12076. (values (and old (split-string old))))
  12077. (setq value (org-entry-protect-space value))
  12078. (when (member value values)
  12079. (setq values (delete value values))
  12080. (org-entry-put pom property (mapconcat #'identity values " ")))))
  12081. (defun org-entry-member-in-multivalued-property (pom property value)
  12082. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12083. (let* ((old (org-entry-get pom property))
  12084. (values (and old (split-string old))))
  12085. (setq value (org-entry-protect-space value))
  12086. (member value values)))
  12087. (defun org-entry-get-multivalued-property (pom property)
  12088. "Return a list of values in a multivalued property."
  12089. (let* ((value (org-entry-get pom property))
  12090. (values (and value (split-string value))))
  12091. (mapcar #'org-entry-restore-space values)))
  12092. (defun org-entry-put-multivalued-property (pom property &rest values)
  12093. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12094. VALUES should be a list of strings. Spaces will be protected."
  12095. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12096. (let* ((value (org-entry-get pom property))
  12097. (values (and value (split-string value))))
  12098. (mapcar #'org-entry-restore-space values)))
  12099. (defun org-entry-protect-space (s)
  12100. "Protect spaces and newline in string S."
  12101. (while (string-match " " s)
  12102. (setq s (replace-match "%20" t t s)))
  12103. (while (string-match "\n" s)
  12104. (setq s (replace-match "%0A" t t s)))
  12105. s)
  12106. (defun org-entry-restore-space (s)
  12107. "Restore spaces and newline in string S."
  12108. (while (string-match "%20" s)
  12109. (setq s (replace-match " " t t s)))
  12110. (while (string-match "%0A" s)
  12111. (setq s (replace-match "\n" t t s)))
  12112. s)
  12113. (defvar org-entry-property-inherited-from (make-marker)
  12114. "Marker pointing to the entry from where a property was inherited.
  12115. Each call to `org-entry-get-with-inheritance' will set this marker to the
  12116. location of the entry where the inheritance search matched. If there was
  12117. no match, the marker will point nowhere.
  12118. Note that also `org-entry-get' calls this function, if the INHERIT flag
  12119. is set.")
  12120. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  12121. "Get PROPERTY of entry or content at point, search higher levels if needed.
  12122. The search will stop at the first ancestor which has the property defined.
  12123. If the value found is \"nil\", return nil to show that the property
  12124. should be considered as undefined (this is the meaning of nil here).
  12125. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12126. (move-marker org-entry-property-inherited-from nil)
  12127. (org-with-wide-buffer
  12128. (let (value at-bob-no-heading)
  12129. (catch 'exit
  12130. (let ((element (or element
  12131. (and (org-element--cache-active-p)
  12132. (org-element-at-point nil 'cached)))))
  12133. (if element
  12134. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  12135. (while t
  12136. (let* ((v (org--property-local-values property literal-nil element))
  12137. (v (if (listp v) v (list v))))
  12138. (when v
  12139. (setq value
  12140. (concat (mapconcat #'identity (delq nil v) " ")
  12141. (and value " ")
  12142. value)))
  12143. (cond
  12144. ((car v)
  12145. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  12146. (throw 'exit nil))
  12147. ((org-element-property :parent element)
  12148. (setq element (org-element-property :parent element)))
  12149. (t
  12150. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12151. (cond ((not global))
  12152. (value (setq value (concat global " " value)))
  12153. (t (setq value global))))
  12154. (throw 'exit nil))))))
  12155. (while t
  12156. (let ((v (org--property-local-values property literal-nil)))
  12157. (when v
  12158. (setq value
  12159. (concat (mapconcat #'identity (delq nil v) " ")
  12160. (and value " ")
  12161. value)))
  12162. (cond
  12163. ((car v)
  12164. (org-back-to-heading-or-point-min t)
  12165. (move-marker org-entry-property-inherited-from (point))
  12166. (throw 'exit nil))
  12167. ((or (org-up-heading-safe)
  12168. (and (not (bobp))
  12169. (goto-char (point-min))
  12170. nil)
  12171. ;; `org-up-heading-safe' returned nil. We are at low
  12172. ;; level heading or bob. If there is headline
  12173. ;; there, do not try to fetch its properties.
  12174. (and (bobp)
  12175. (not at-bob-no-heading)
  12176. (not (org-at-heading-p))
  12177. (setq at-bob-no-heading t))))
  12178. (t
  12179. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12180. (cond ((not global))
  12181. (value (setq value (concat global " " value)))
  12182. (t (setq value global))))
  12183. (throw 'exit nil))))))))
  12184. (if literal-nil value (org-not-nil value)))))
  12185. (defvar org-property-changed-functions nil
  12186. "Hook called when the value of a property has changed.
  12187. Each hook function should accept two arguments, the name of the property
  12188. and the new value.")
  12189. (defun org-entry-put (pom property value)
  12190. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12191. If the value is nil, it is converted to the empty string. If it
  12192. is not a string, an error is raised. Also raise an error on
  12193. invalid property names.
  12194. PROPERTY can be any regular property (see
  12195. `org-special-properties'). It can also be \"TODO\",
  12196. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12197. For the last two properties, VALUE may have any of the special
  12198. values \"earlier\" and \"later\". The function then increases or
  12199. decreases scheduled or deadline date by one day."
  12200. (cond ((null value) (setq value ""))
  12201. ((not (stringp value)) (error "Properties values should be strings"))
  12202. ((not (org--valid-property-p property))
  12203. (user-error "Invalid property name: \"%s\"" property)))
  12204. (org-no-read-only
  12205. (org-with-point-at pom
  12206. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12207. (org-back-to-heading-or-point-min t)
  12208. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12209. (let ((beg (point)))
  12210. (cond
  12211. ((equal property "TODO")
  12212. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12213. ((not (member value org-todo-keywords-1))
  12214. (user-error "\"%s\" is not a valid TODO state" value)))
  12215. (org-todo value)
  12216. (org-align-tags))
  12217. ((equal property "PRIORITY")
  12218. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12219. (org-align-tags))
  12220. ((equal property "SCHEDULED")
  12221. (forward-line)
  12222. (if (and (looking-at-p org-planning-line-re)
  12223. (re-search-forward
  12224. org-scheduled-time-regexp (line-end-position) t))
  12225. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12226. ((string= value "later") (org-timestamp-change 1 'day))
  12227. ((string= value "") (org-schedule '(4)))
  12228. (t (org-schedule nil value)))
  12229. (if (member value '("earlier" "later" ""))
  12230. (call-interactively #'org-schedule)
  12231. (org-schedule nil value))))
  12232. ((equal property "DEADLINE")
  12233. (forward-line)
  12234. (if (and (looking-at-p org-planning-line-re)
  12235. (re-search-forward
  12236. org-deadline-time-regexp (line-end-position) t))
  12237. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12238. ((string= value "later") (org-timestamp-change 1 'day))
  12239. ((string= value "") (org-deadline '(4)))
  12240. (t (org-deadline nil value)))
  12241. (if (member value '("earlier" "later" ""))
  12242. (call-interactively #'org-deadline)
  12243. (org-deadline nil value))))
  12244. ((member property org-special-properties)
  12245. (error "The %s property cannot be set with `org-entry-put'" property))
  12246. (t
  12247. (let* ((range (org-get-property-block beg 'force))
  12248. (end (cdr range))
  12249. (case-fold-search t))
  12250. (goto-char (car range))
  12251. (if (re-search-forward (org-re-property property nil t) end t)
  12252. (progn (delete-region (match-beginning 0) (match-end 0))
  12253. (goto-char (match-beginning 0)))
  12254. (goto-char end)
  12255. (insert "\n")
  12256. (backward-char))
  12257. (insert ":" property ":")
  12258. (when value (insert " " value))
  12259. (org-indent-line)))))
  12260. (run-hook-with-args 'org-property-changed-functions property value))))
  12261. (defun org-buffer-property-keys (&optional specials defaults columns)
  12262. "Get all property keys in the current buffer.
  12263. When SPECIALS is non-nil, also list the special properties that
  12264. reflect things like tags and TODO state.
  12265. When DEFAULTS is non-nil, also include properties that has
  12266. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12267. DESCRIPTION, LOCATION, and LOGGING and others.
  12268. When COLUMNS in non-nil, also include property names given in
  12269. COLUMN formats in the current buffer."
  12270. (let ((case-fold-search t)
  12271. (props (append
  12272. (and specials org-special-properties)
  12273. (and defaults (cons org-effort-property org-default-properties))
  12274. ;; Get property names from #+PROPERTY keywords as well
  12275. (mapcar (lambda (s)
  12276. (nth 0 (split-string s)))
  12277. (cdar (org-collect-keywords '("PROPERTY")))))))
  12278. (org-with-wide-buffer
  12279. (goto-char (point-min))
  12280. (while (re-search-forward org-property-start-re nil t)
  12281. (catch :skip
  12282. (let ((range (org-get-property-block)))
  12283. (unless range (throw :skip nil))
  12284. (goto-char (car range))
  12285. (let ((begin (car range))
  12286. (end (cdr range)))
  12287. ;; Make sure that found property block is not located
  12288. ;; before current point, as it would generate an infloop.
  12289. ;; It can happen, for example, in the following
  12290. ;; situation:
  12291. ;;
  12292. ;; * Headline
  12293. ;; :PROPERTIES:
  12294. ;; ...
  12295. ;; :END:
  12296. ;; *************** Inlinetask
  12297. ;; #+BEGIN_EXAMPLE
  12298. ;; :PROPERTIES:
  12299. ;; #+END_EXAMPLE
  12300. ;;
  12301. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12302. (while (< (point) end)
  12303. (let ((p (progn (looking-at org-property-re)
  12304. (match-string-no-properties 2))))
  12305. ;; Only add true property name, not extension symbol.
  12306. (push (if (not (string-match-p "\\+\\'" p)) p
  12307. (substring p 0 -1))
  12308. props))
  12309. (forward-line))))
  12310. (outline-next-heading)))
  12311. (when columns
  12312. (goto-char (point-min))
  12313. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12314. (let ((element (org-element-at-point)))
  12315. (when (memq (org-element-type element) '(keyword node-property))
  12316. (let ((value (org-element-property :value element))
  12317. (start 0))
  12318. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12319. \\(?:{[^}]+}\\)?"
  12320. value start)
  12321. (setq start (match-end 0))
  12322. (let ((p (match-string-no-properties 1 value)))
  12323. (unless (member-ignore-case p org-special-properties)
  12324. (push p props))))))))))
  12325. (sort (delete-dups
  12326. (append props
  12327. ;; for each xxx_ALL property, make sure the bare
  12328. ;; xxx property is also included
  12329. (delq nil (mapcar (lambda (p)
  12330. (and (string-match-p "._ALL\\'" p)
  12331. (substring p 0 -4)))
  12332. props))))
  12333. (lambda (a b) (string< (upcase a) (upcase b))))))
  12334. (defun org-property-values (key)
  12335. "List all non-nil values of property KEY in current buffer."
  12336. (org-with-wide-buffer
  12337. (goto-char (point-min))
  12338. (let ((case-fold-search t)
  12339. (re (org-re-property key))
  12340. values)
  12341. (while (re-search-forward re nil t)
  12342. (push (org-entry-get (point) key) values))
  12343. (delete-dups values))))
  12344. (defun org-insert-property-drawer ()
  12345. "Insert a property drawer into the current entry.
  12346. Do nothing if the drawer already exists. The newly created
  12347. drawer is immediately hidden."
  12348. (org-with-wide-buffer
  12349. ;; Set point to the position where the drawer should be inserted.
  12350. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12351. (org-back-to-heading-or-point-min t)
  12352. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12353. (if (org-before-first-heading-p)
  12354. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12355. (progn
  12356. (forward-line)
  12357. (when (looking-at-p org-planning-line-re) (forward-line))))
  12358. (unless (looking-at-p org-property-drawer-re)
  12359. ;; Make sure we start editing a line from current entry, not from
  12360. ;; next one. It prevents extending text properties or overlays
  12361. ;; belonging to the latter.
  12362. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12363. (let ((begin (if (bobp) (point) (1+ (point))))
  12364. (inhibit-read-only t))
  12365. (unless (bobp) (insert "\n"))
  12366. (insert ":PROPERTIES:\n:END:")
  12367. (org-flag-region (line-end-position 0) (point) t 'outline)
  12368. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12369. (org-indent-region begin (point))))))
  12370. (defun org-insert-drawer (&optional arg drawer)
  12371. "Insert a drawer at point.
  12372. When optional argument ARG is non-nil, insert a property drawer.
  12373. Optional argument DRAWER, when non-nil, is a string representing
  12374. drawer's name. Otherwise, the user is prompted for a name.
  12375. If a region is active, insert the drawer around that region
  12376. instead.
  12377. Point is left between drawer's boundaries."
  12378. (interactive "P")
  12379. (let* ((drawer (if arg "PROPERTIES"
  12380. (or drawer (read-from-minibuffer "Drawer: ")))))
  12381. (cond
  12382. ;; With C-u, fall back on `org-insert-property-drawer'
  12383. (arg (org-insert-property-drawer))
  12384. ;; Check validity of suggested drawer's name.
  12385. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12386. (user-error "Invalid drawer name"))
  12387. ;; With an active region, insert a drawer at point.
  12388. ((not (org-region-active-p))
  12389. (progn
  12390. (unless (bolp) (insert "\n"))
  12391. (insert (format ":%s:\n\n:END:\n" drawer))
  12392. (forward-line -2)))
  12393. ;; Otherwise, insert the drawer at point
  12394. (t
  12395. (let ((rbeg (region-beginning))
  12396. (rend (copy-marker (region-end))))
  12397. (unwind-protect
  12398. (progn
  12399. (goto-char rbeg)
  12400. (beginning-of-line)
  12401. (when (save-excursion
  12402. (re-search-forward org-outline-regexp-bol rend t))
  12403. (user-error "Drawers cannot contain headlines"))
  12404. ;; Position point at the beginning of the first
  12405. ;; non-blank line in region. Insert drawer's opening
  12406. ;; there, then indent it.
  12407. (org-skip-whitespace)
  12408. (beginning-of-line)
  12409. (insert ":" drawer ":\n")
  12410. (forward-line -1)
  12411. (indent-for-tab-command)
  12412. ;; Move point to the beginning of the first blank line
  12413. ;; after the last non-blank line in region. Insert
  12414. ;; drawer's closing, then indent it.
  12415. (goto-char rend)
  12416. (skip-chars-backward " \r\t\n")
  12417. (insert "\n:END:")
  12418. (deactivate-mark t)
  12419. (indent-for-tab-command)
  12420. (unless (eolp) (insert "\n")))
  12421. ;; Clear marker, whatever the outcome of insertion is.
  12422. (set-marker rend nil)))))))
  12423. (defvar org-property-set-functions-alist nil
  12424. "Property set function alist.
  12425. Each entry should have the following format:
  12426. (PROPERTY . READ-FUNCTION)
  12427. The read function will be called with the same argument as
  12428. `org-completing-read'.")
  12429. (defun org-set-property-function (property)
  12430. "Get the function that should be used to set PROPERTY.
  12431. This is computed according to `org-property-set-functions-alist'."
  12432. (or (cdr (assoc property org-property-set-functions-alist))
  12433. 'org-completing-read))
  12434. (defun org-read-property-value (property &optional pom default)
  12435. "Read value for PROPERTY, as a string.
  12436. When optional argument POM is non-nil, completion uses additional
  12437. information, i.e., allowed or existing values at point or marker
  12438. POM.
  12439. Optional argument DEFAULT provides a default value for PROPERTY."
  12440. (let* ((completion-ignore-case t)
  12441. (allowed
  12442. (or (org-property-get-allowed-values nil property 'table)
  12443. (and pom (org-property-get-allowed-values pom property 'table))))
  12444. (current (org-entry-get nil property))
  12445. (prompt (format "%s value%s: "
  12446. property
  12447. (if (org-string-nw-p current)
  12448. (format " [%s]" current)
  12449. "")))
  12450. (set-function (org-set-property-function property)))
  12451. (org-trim
  12452. (if allowed
  12453. (funcall set-function
  12454. prompt allowed nil
  12455. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12456. default nil default)
  12457. (let ((all (mapcar #'list
  12458. (append (org-property-values property)
  12459. (and pom
  12460. (org-with-point-at pom
  12461. (org-property-values property)))))))
  12462. (funcall set-function prompt all nil nil "" nil current))))))
  12463. (defvar org-last-set-property nil)
  12464. (defvar org-last-set-property-value nil)
  12465. (defun org-read-property-name ()
  12466. "Read a property name."
  12467. (let ((completion-ignore-case t)
  12468. (default-prop (or (and (org-at-property-p)
  12469. (match-string-no-properties 2))
  12470. org-last-set-property)))
  12471. (org-completing-read
  12472. (concat "Property"
  12473. (if default-prop (concat " [" default-prop "]") "")
  12474. ": ")
  12475. (mapcar #'list (org-buffer-property-keys nil t t))
  12476. nil nil nil nil default-prop)))
  12477. (defun org-set-property-and-value (use-last)
  12478. "Allow to set [PROPERTY]: [value] direction from prompt.
  12479. When use-default, don't even ask, just use the last
  12480. \"[PROPERTY]: [value]\" string from the history."
  12481. (interactive "P")
  12482. (let* ((completion-ignore-case t)
  12483. (pv (or (and use-last org-last-set-property-value)
  12484. (org-completing-read
  12485. "Enter a \"[Property]: [value]\" pair: "
  12486. nil nil nil nil nil
  12487. org-last-set-property-value)))
  12488. prop val)
  12489. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12490. (setq prop (match-string 1 pv)
  12491. val (match-string 2 pv))
  12492. (org-set-property prop val))))
  12493. (defun org-set-property (property value)
  12494. "In the current entry, set PROPERTY to VALUE.
  12495. When called interactively, this will prompt for a property name, offering
  12496. completion on existing and default properties. And then it will prompt
  12497. for a value, offering completion either on allowed values (via an inherited
  12498. xxx_ALL property) or on existing values in other instances of this property
  12499. in the current file.
  12500. Throw an error when trying to set a property with an invalid name."
  12501. (interactive (list nil nil))
  12502. (let ((property (or property (org-read-property-name))))
  12503. ;; `org-entry-put' also makes the following check, but this one
  12504. ;; avoids polluting `org-last-set-property' and
  12505. ;; `org-last-set-property-value' needlessly.
  12506. (unless (org--valid-property-p property)
  12507. (user-error "Invalid property name: \"%s\"" property))
  12508. (let ((value (or value (org-read-property-value property)))
  12509. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12510. (setq org-last-set-property property)
  12511. (setq org-last-set-property-value (concat property ": " value))
  12512. ;; Possibly postprocess the inserted value:
  12513. (when fn (setq value (funcall fn value)))
  12514. (unless (equal (org-entry-get nil property) value)
  12515. (org-entry-put nil property value)))))
  12516. (defun org-find-property (property &optional value)
  12517. "Find first entry in buffer that sets PROPERTY.
  12518. When optional argument VALUE is non-nil, only consider an entry
  12519. if it contains PROPERTY set to this value. If PROPERTY should be
  12520. explicitly set to nil, use string \"nil\" for VALUE.
  12521. Return position where the entry begins, or nil if there is no
  12522. such entry. If narrowing is in effect, only search the visible
  12523. part of the buffer."
  12524. (save-excursion
  12525. (goto-char (point-min))
  12526. (let ((case-fold-search t)
  12527. (re (org-re-property property nil (not value) value)))
  12528. (catch 'exit
  12529. (while (re-search-forward re nil t)
  12530. (when (if value (org-at-property-p)
  12531. (org-entry-get (point) property nil t))
  12532. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12533. (point)))))))))
  12534. (defun org-delete-property (property)
  12535. "In the current entry, delete PROPERTY."
  12536. (interactive
  12537. (let* ((completion-ignore-case t)
  12538. (cat (org-entry-get (point) "CATEGORY"))
  12539. (props0 (org-entry-properties nil 'standard))
  12540. (props (if cat props0
  12541. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12542. (prop (if (< 1 (length props))
  12543. (completing-read "Property: " props nil t)
  12544. (caar props))))
  12545. (list prop)))
  12546. (if (not property)
  12547. (message "No property to delete in this entry")
  12548. (org-entry-delete nil property)
  12549. (message "Property \"%s\" deleted" property)))
  12550. (defun org-delete-property-globally (property)
  12551. "Remove PROPERTY globally, from all entries.
  12552. This function ignores narrowing, if any."
  12553. (interactive
  12554. (let* ((completion-ignore-case t)
  12555. (prop (completing-read
  12556. "Globally remove property: "
  12557. (mapcar #'list (org-buffer-property-keys)))))
  12558. (list prop)))
  12559. (org-with-wide-buffer
  12560. (goto-char (point-min))
  12561. (let ((count 0)
  12562. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12563. (while (re-search-forward re nil t)
  12564. (when (org-entry-delete (point) property) (cl-incf count)))
  12565. (message "Property \"%s\" removed from %d entries" property count))))
  12566. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12567. (defun org-compute-property-at-point ()
  12568. "Compute the property at point.
  12569. This looks for an enclosing column format, extracts the operator and
  12570. then applies it to the property in the column format's scope."
  12571. (interactive)
  12572. (unless (org-at-property-p)
  12573. (user-error "Not at a property"))
  12574. (let ((prop (match-string-no-properties 2)))
  12575. (org-columns-get-format-and-top-level)
  12576. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12577. (user-error "No operator defined for property %s" prop))
  12578. (org-columns-compute prop)))
  12579. (defvar org-property-allowed-value-functions nil
  12580. "Hook for functions supplying allowed values for a specific property.
  12581. The functions must take a single argument, the name of the property, and
  12582. return a flat list of allowed values. If \":ETC\" is one of
  12583. the values, this means that these values are intended as defaults for
  12584. completion, but that other values should be allowed too.
  12585. The functions must return nil if they are not responsible for this
  12586. property.")
  12587. (defun org-property-get-allowed-values (pom property &optional table)
  12588. "Get allowed values for the property PROPERTY.
  12589. When TABLE is non-nil, return an alist that can directly be used for
  12590. completion."
  12591. (let (vals)
  12592. (cond
  12593. ((equal property "TODO")
  12594. (setq vals (org-with-point-at pom
  12595. (append org-todo-keywords-1 '("")))))
  12596. ((equal property "PRIORITY")
  12597. (let ((n org-priority-lowest))
  12598. (while (>= n org-priority-highest)
  12599. (push (char-to-string n) vals)
  12600. (setq n (1- n)))))
  12601. ((equal property "CATEGORY"))
  12602. ((member property org-special-properties))
  12603. ((setq vals (run-hook-with-args-until-success
  12604. 'org-property-allowed-value-functions property)))
  12605. (t
  12606. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12607. (when (and vals (string-match "\\S-" vals))
  12608. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12609. (setq vals (mapcar (lambda (x)
  12610. (cond ((stringp x) x)
  12611. ((numberp x) (number-to-string x))
  12612. ((symbolp x) (symbol-name x))
  12613. (t "???")))
  12614. vals)))))
  12615. (when (member ":ETC" vals)
  12616. (setq vals (remove ":ETC" vals))
  12617. (org-add-props (car vals) '(org-unrestricted t)))
  12618. (if table (mapcar 'list vals) vals)))
  12619. (defun org-property-previous-allowed-value (&optional _previous)
  12620. "Switch to the next allowed value for this property."
  12621. (interactive)
  12622. (org-property-next-allowed-value t))
  12623. (defun org-property-next-allowed-value (&optional previous)
  12624. "Switch to the next allowed value for this property."
  12625. (interactive)
  12626. (unless (org-at-property-p)
  12627. (user-error "Not at a property"))
  12628. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12629. (key (match-string 2))
  12630. (value (match-string 3))
  12631. (allowed (or (org-property-get-allowed-values (point) key)
  12632. (and (member value '("[ ]" "[-]" "[X]"))
  12633. '("[ ]" "[X]"))))
  12634. (heading (save-match-data (nth 4 (org-heading-components))))
  12635. nval)
  12636. (unless allowed
  12637. (user-error "Allowed values for this property have not been defined"))
  12638. (when previous (setq allowed (reverse allowed)))
  12639. (when (member value allowed)
  12640. (setq nval (car (cdr (member value allowed)))))
  12641. (setq nval (or nval (car allowed)))
  12642. (when (equal nval value)
  12643. (user-error "Only one allowed value for this property"))
  12644. (org-at-property-p)
  12645. (replace-match (concat " :" key ": " nval) t t)
  12646. (org-indent-line)
  12647. (beginning-of-line 1)
  12648. (skip-chars-forward " \t")
  12649. (when (equal prop org-effort-property)
  12650. (org-refresh-property
  12651. '((effort . identity)
  12652. (effort-minutes . org-duration-to-minutes))
  12653. nval)
  12654. (when (string= org-clock-current-task heading)
  12655. (setq org-clock-effort nval)
  12656. (org-clock-update-mode-line)))
  12657. (run-hook-with-args 'org-property-changed-functions key nval)))
  12658. (defun org-find-olp (path &optional this-buffer)
  12659. "Return a marker pointing to the entry at outline path OLP.
  12660. If anything goes wrong, throw an error, and if you need to do
  12661. something based on this error, you can catch it with
  12662. `condition-case'.
  12663. If THIS-BUFFER is set, the outline path does not contain a file,
  12664. only headings."
  12665. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12666. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12667. (level 1)
  12668. (lmin 1)
  12669. (lmax 1)
  12670. end found flevel)
  12671. (unless buffer (error "File not found :%s" file))
  12672. (with-current-buffer buffer
  12673. (unless (derived-mode-p 'org-mode)
  12674. (error "Buffer %s needs to be in Org mode" buffer))
  12675. (org-with-wide-buffer
  12676. (goto-char (point-min))
  12677. (dolist (heading path)
  12678. (let ((re (format org-complex-heading-regexp-format
  12679. (regexp-quote heading)))
  12680. (cnt 0))
  12681. (while (re-search-forward re end t)
  12682. (setq level (- (match-end 1) (match-beginning 1)))
  12683. (when (and (>= level lmin) (<= level lmax))
  12684. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12685. (when (= cnt 0)
  12686. (error "Heading not found on level %d: %s" lmax heading))
  12687. (when (> cnt 1)
  12688. (error "Heading not unique on level %d: %s" lmax heading))
  12689. (goto-char found)
  12690. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12691. (setq end (save-excursion (org-end-of-subtree t t)))))
  12692. (when (org-at-heading-p)
  12693. (point-marker))))))
  12694. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12695. "Find node HEADING in BUFFER.
  12696. Return a marker to the heading if it was found, or nil if not.
  12697. If POS-ONLY is set, return just the position instead of a marker.
  12698. The heading text must match exact, but it may have a TODO keyword,
  12699. a priority cookie and tags in the standard locations."
  12700. (with-current-buffer (or buffer (current-buffer))
  12701. (org-with-wide-buffer
  12702. (goto-char (point-min))
  12703. (let (case-fold-search)
  12704. (when (re-search-forward
  12705. (format org-complex-heading-regexp-format
  12706. (regexp-quote heading)) nil t)
  12707. (if pos-only
  12708. (match-beginning 0)
  12709. (move-marker (make-marker) (match-beginning 0))))))))
  12710. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12711. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12712. When the target headline is found, return a marker to this location."
  12713. (let ((files (directory-files (or dir default-directory)
  12714. t "\\`[^.#].*\\.org\\'"))
  12715. visiting m buffer)
  12716. (catch 'found
  12717. (dolist (file files)
  12718. (message "trying %s" file)
  12719. (setq visiting (org-find-base-buffer-visiting file))
  12720. (setq buffer (or visiting (find-file-noselect file)))
  12721. (setq m (org-find-exact-headline-in-buffer
  12722. heading buffer))
  12723. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12724. (and m (throw 'found m))))))
  12725. (defun org-find-entry-with-id (ident)
  12726. "Locate the entry that contains the ID property with exact value IDENT.
  12727. IDENT can be a string, a symbol or a number, this function will search for
  12728. the string representation of it.
  12729. Return the position where this entry starts, or nil if there is no such entry."
  12730. (interactive "sID: ")
  12731. (let ((id (cond
  12732. ((stringp ident) ident)
  12733. ((symbolp ident) (symbol-name ident))
  12734. ((numberp ident) (number-to-string ident))
  12735. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12736. (org-with-wide-buffer (org-find-property "ID" id))))
  12737. ;;;; Timestamps
  12738. (defvar org-last-changed-timestamp nil)
  12739. (defvar org-last-inserted-timestamp nil
  12740. "The last time stamp inserted with `org-insert-time-stamp'.")
  12741. (defun org-time-stamp (arg &optional inactive)
  12742. "Prompt for a date/time and insert a time stamp.
  12743. If the user specifies a time like HH:MM or if this command is
  12744. called with at least one prefix argument, the time stamp contains
  12745. the date and the time. Otherwise, only the date is included.
  12746. All parts of a date not specified by the user are filled in from
  12747. the timestamp at point, if any, or the current date/time
  12748. otherwise.
  12749. If there is already a timestamp at the cursor, it is replaced.
  12750. With two universal prefix arguments, insert an active timestamp
  12751. with the current time without prompting the user.
  12752. When called from Lisp, the timestamp is inactive if INACTIVE is
  12753. non-nil."
  12754. (interactive "P")
  12755. (let* ((ts (cond
  12756. ((org-at-date-range-p t)
  12757. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12758. ((org-at-timestamp-p 'lax) (match-string 0))))
  12759. ;; Default time is either the timestamp at point or today.
  12760. ;; When entering a range, only the range start is considered.
  12761. (default-time (and ts (org-time-string-to-time ts)))
  12762. (default-input (and ts (org-get-compact-tod ts)))
  12763. (repeater (and ts
  12764. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12765. (match-string 0 ts)))
  12766. org-time-was-given
  12767. org-end-time-was-given
  12768. (time
  12769. (if (equal arg '(16)) (current-time)
  12770. ;; Preserve `this-command' and `last-command'.
  12771. (let ((this-command this-command)
  12772. (last-command last-command))
  12773. (org-read-date
  12774. arg 'totime nil nil default-time default-input
  12775. inactive)))))
  12776. (cond
  12777. ((and ts
  12778. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12779. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12780. (insert "--")
  12781. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12782. (ts
  12783. ;; Make sure we're on a timestamp. When in the middle of a date
  12784. ;; range, move arbitrarily to range end.
  12785. (unless (org-at-timestamp-p 'lax)
  12786. (skip-chars-forward "-")
  12787. (org-at-timestamp-p 'lax))
  12788. (replace-match "")
  12789. (setq org-last-changed-timestamp
  12790. (org-insert-time-stamp
  12791. time (or org-time-was-given arg)
  12792. inactive nil nil (list org-end-time-was-given)))
  12793. (when repeater
  12794. (backward-char)
  12795. (insert " " repeater)
  12796. (setq org-last-changed-timestamp
  12797. (concat (substring org-last-inserted-timestamp 0 -1)
  12798. " " repeater ">")))
  12799. (message "Timestamp updated"))
  12800. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12801. (t (org-insert-time-stamp
  12802. time (or org-time-was-given arg) inactive nil nil
  12803. (list org-end-time-was-given))))))
  12804. ;; FIXME: can we use this for something else, like computing time differences?
  12805. (defun org-get-compact-tod (s)
  12806. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12807. (let* ((t1 (match-string 1 s))
  12808. (h1 (string-to-number (match-string 2 s)))
  12809. (m1 (string-to-number (match-string 3 s)))
  12810. (t2 (and (match-end 4) (match-string 5 s)))
  12811. (h2 (and t2 (string-to-number (match-string 6 s))))
  12812. (m2 (and t2 (string-to-number (match-string 7 s))))
  12813. dh dm)
  12814. (if (not t2)
  12815. t1
  12816. (setq dh (- h2 h1) dm (- m2 m1))
  12817. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12818. (concat t1 "+" (number-to-string dh)
  12819. (and (/= 0 dm) (format ":%02d" dm)))))))
  12820. (defun org-time-stamp-inactive (&optional arg)
  12821. "Insert an inactive time stamp.
  12822. An inactive time stamp is enclosed in square brackets instead of
  12823. angle brackets. It is inactive in the sense that it does not
  12824. trigger agenda entries. So these are more for recording a
  12825. certain time/date.
  12826. If the user specifies a time like HH:MM or if this command is called with
  12827. at least one prefix argument, the time stamp contains the date and the time.
  12828. Otherwise, only the date is included.
  12829. When called with two universal prefix arguments, insert an inactive time stamp
  12830. with the current time without prompting the user."
  12831. (interactive "P")
  12832. (org-time-stamp arg 'inactive))
  12833. (defvar org-date-ovl (make-overlay 1 1))
  12834. (overlay-put org-date-ovl 'face 'org-date-selected)
  12835. (delete-overlay org-date-ovl)
  12836. (defvar org-ans1) ; dynamically scoped parameter
  12837. (defvar org-ans2) ; dynamically scoped parameter
  12838. (defvar org-plain-time-of-day-regexp) ; defined below
  12839. (defvar org-overriding-default-time nil) ; dynamically scoped
  12840. (defvar org-read-date-overlay nil)
  12841. (defvar org-read-date-history nil)
  12842. (defvar org-read-date-final-answer nil)
  12843. (defvar org-read-date-analyze-futurep nil)
  12844. (defvar org-read-date-analyze-forced-year nil)
  12845. (defvar org-read-date-inactive)
  12846. (defvar org-def)
  12847. (defvar org-defdecode)
  12848. (defvar org-with-time)
  12849. (defvar calendar-setup) ; Dynamically scoped.
  12850. (defun org-read-date (&optional with-time to-time from-string prompt
  12851. default-time default-input inactive)
  12852. "Read a date, possibly a time, and make things smooth for the user.
  12853. The prompt will suggest to enter an ISO date, but you can also enter anything
  12854. which will at least partially be understood by `parse-time-string'.
  12855. Unrecognized parts of the date will default to the current day, month, year,
  12856. hour and minute. If this command is called to replace a timestamp at point,
  12857. or to enter the second timestamp of a range, the default time is taken
  12858. from the existing stamp. Furthermore, the command prefers the future,
  12859. so if you are giving a date where the year is not given, and the day-month
  12860. combination is already past in the current year, it will assume you
  12861. mean next year. For details, see the manual. A few examples:
  12862. 3-2-5 --> 2003-02-05
  12863. feb 15 --> currentyear-02-15
  12864. 2/15 --> currentyear-02-15
  12865. sep 12 9 --> 2009-09-12
  12866. 12:45 --> today 12:45
  12867. 22 sept 0:34 --> currentyear-09-22 0:34
  12868. 12 --> currentyear-currentmonth-12
  12869. Fri --> nearest Friday after today
  12870. -Tue --> last Tuesday
  12871. etc.
  12872. Furthermore you can specify a relative date by giving, as the *first* thing
  12873. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12874. change in days weeks, months, years.
  12875. With a single plus or minus, the date is relative to today. With a double
  12876. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12877. +4d --> four days from today
  12878. +4 --> same as above
  12879. +2w --> two weeks from today
  12880. ++5 --> five days from default date
  12881. The function understands only English month and weekday abbreviations.
  12882. While prompting, a calendar is popped up - you can also select the
  12883. date with the mouse (button 1). The calendar shows a period of three
  12884. months. To scroll it to other months, use the keys `>' and `<'.
  12885. If you don't like the calendar, turn it off with
  12886. (setq org-read-date-popup-calendar nil)
  12887. With optional argument TO-TIME, the date will immediately be converted
  12888. to an internal time.
  12889. With an optional argument WITH-TIME, the prompt will suggest to
  12890. also insert a time. Note that when WITH-TIME is not set, you can
  12891. still enter a time, and this function will inform the calling routine
  12892. about this change. The calling routine may then choose to change the
  12893. format used to insert the time stamp into the buffer to include the time.
  12894. With optional argument FROM-STRING, read from this string instead from
  12895. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12896. the time/date that is used for everything that is not specified by the
  12897. user."
  12898. (require 'parse-time)
  12899. (let* ((org-with-time with-time)
  12900. (org-time-stamp-rounding-minutes
  12901. (if (equal org-with-time '(16))
  12902. '(0 0)
  12903. org-time-stamp-rounding-minutes))
  12904. (ct (org-current-time))
  12905. (org-def (or org-overriding-default-time default-time ct))
  12906. (org-defdecode (decode-time org-def))
  12907. (cur-frame (selected-frame))
  12908. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12909. (calendar-setup
  12910. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12911. (calendar-move-hook nil)
  12912. (calendar-view-diary-initially-flag nil)
  12913. (calendar-view-holidays-initially-flag nil)
  12914. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12915. ;; Rationalize `org-def' and `org-defdecode', if required.
  12916. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12917. (setf (nth 2 org-defdecode) -1)
  12918. (setf (nth 1 org-defdecode) 59)
  12919. (setq org-def (apply #'encode-time org-defdecode))
  12920. (setq org-defdecode (decode-time org-def)))
  12921. (let* ((timestr (format-time-string
  12922. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12923. org-def))
  12924. (prompt (concat (if prompt (concat prompt " ") "")
  12925. (format "Date+time [%s]: " timestr))))
  12926. (cond
  12927. (from-string (setq ans from-string))
  12928. (org-read-date-popup-calendar
  12929. (save-excursion
  12930. (save-window-excursion
  12931. (calendar)
  12932. (when (eq calendar-setup 'calendar-only)
  12933. (setq cal-frame
  12934. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12935. (select-frame cal-frame))
  12936. (org-eval-in-calendar '(setq cursor-type nil) t)
  12937. (unwind-protect
  12938. (progn
  12939. (calendar-forward-day (- (time-to-days org-def)
  12940. (calendar-absolute-from-gregorian
  12941. (calendar-current-date))))
  12942. (org-eval-in-calendar nil t)
  12943. (let* ((old-map (current-local-map))
  12944. (map (copy-keymap calendar-mode-map))
  12945. (minibuffer-local-map
  12946. (copy-keymap org-read-date-minibuffer-local-map)))
  12947. (org-defkey map (kbd "RET") 'org-calendar-select)
  12948. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12949. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12950. (unwind-protect
  12951. (progn
  12952. (use-local-map map)
  12953. (setq org-read-date-inactive inactive)
  12954. (add-hook 'post-command-hook 'org-read-date-display)
  12955. (setq org-ans0
  12956. (read-string prompt
  12957. default-input
  12958. 'org-read-date-history
  12959. nil))
  12960. ;; org-ans0: from prompt
  12961. ;; org-ans1: from mouse click
  12962. ;; org-ans2: from calendar motion
  12963. (setq ans
  12964. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12965. (remove-hook 'post-command-hook 'org-read-date-display)
  12966. (use-local-map old-map)
  12967. (when org-read-date-overlay
  12968. (delete-overlay org-read-date-overlay)
  12969. (setq org-read-date-overlay nil)))))
  12970. (bury-buffer "*Calendar*")
  12971. (when cal-frame
  12972. (delete-frame cal-frame)
  12973. (select-frame-set-input-focus cur-frame))))))
  12974. (t ; Naked prompt only
  12975. (unwind-protect
  12976. (setq ans (read-string prompt default-input
  12977. 'org-read-date-history timestr))
  12978. (when org-read-date-overlay
  12979. (delete-overlay org-read-date-overlay)
  12980. (setq org-read-date-overlay nil))))))
  12981. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12982. (when org-read-date-analyze-forced-year
  12983. (message "Year was forced into %s"
  12984. (if org-read-date-force-compatible-dates
  12985. "compatible range (1970-2037)"
  12986. "range representable on this machine"))
  12987. (ding))
  12988. (setq final (apply #'encode-time final))
  12989. (setq org-read-date-final-answer ans)
  12990. (if to-time
  12991. final
  12992. ;; This round-trip gets rid of 34th of August and stuff like that....
  12993. (setq final (decode-time final))
  12994. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12995. (format "%04d-%02d-%02d %02d:%02d"
  12996. (nth 5 final) (nth 4 final) (nth 3 final)
  12997. (nth 2 final) (nth 1 final))
  12998. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12999. (defun org-read-date-display ()
  13000. "Display the current date prompt interpretation in the minibuffer."
  13001. (when org-read-date-display-live
  13002. (when org-read-date-overlay
  13003. (delete-overlay org-read-date-overlay))
  13004. (when (minibufferp (current-buffer))
  13005. (save-excursion
  13006. (end-of-line 1)
  13007. (while (not (equal (buffer-substring
  13008. (max (point-min) (- (point) 4)) (point))
  13009. " "))
  13010. (insert " ")))
  13011. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  13012. " " (or org-ans1 org-ans2)))
  13013. (org-end-time-was-given nil)
  13014. (f (org-read-date-analyze ans org-def org-defdecode))
  13015. (fmts (if org-display-custom-times
  13016. org-time-stamp-custom-formats
  13017. org-time-stamp-formats))
  13018. (fmt (if (or org-with-time
  13019. (and (boundp 'org-time-was-given) org-time-was-given))
  13020. (cdr fmts)
  13021. (car fmts)))
  13022. (txt (format-time-string fmt (apply #'encode-time f)))
  13023. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  13024. (txt (concat "=> " txt)))
  13025. (when (and org-end-time-was-given
  13026. (string-match org-plain-time-of-day-regexp txt))
  13027. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13028. org-end-time-was-given
  13029. (substring txt (match-end 0)))))
  13030. (when org-read-date-analyze-futurep
  13031. (setq txt (concat txt " (=>F)")))
  13032. (setq org-read-date-overlay
  13033. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  13034. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13035. (defun org-read-date-analyze (ans def defdecode)
  13036. "Analyze the combined answer of the date prompt."
  13037. ;; FIXME: cleanup and comment
  13038. (let ((org-def def)
  13039. (org-defdecode defdecode)
  13040. (nowdecode (decode-time))
  13041. delta deltan deltaw deltadef year month day
  13042. hour minute second wday pm h2 m2 tl wday1
  13043. iso-year iso-weekday iso-week iso-date futurep kill-year)
  13044. (setq org-read-date-analyze-futurep nil
  13045. org-read-date-analyze-forced-year nil)
  13046. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13047. (setq ans "+0"))
  13048. (when (setq delta (org-read-date-get-relative ans nil org-def))
  13049. (setq ans (replace-match "" t t ans)
  13050. deltan (car delta)
  13051. deltaw (nth 1 delta)
  13052. deltadef (nth 2 delta)))
  13053. ;; Check if there is an iso week date in there. If yes, store the
  13054. ;; info and postpone interpreting it until the rest of the parsing
  13055. ;; is done.
  13056. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13057. (setq iso-year (when (match-end 1)
  13058. (org-small-year-to-year
  13059. (string-to-number (match-string 1 ans))))
  13060. iso-weekday (when (match-end 3)
  13061. (string-to-number (match-string 3 ans)))
  13062. iso-week (string-to-number (match-string 2 ans)))
  13063. (setq ans (replace-match "" t t ans)))
  13064. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13065. (when (string-match
  13066. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13067. (setq year (if (match-end 2)
  13068. (string-to-number (match-string 2 ans))
  13069. (progn (setq kill-year t)
  13070. (string-to-number (format-time-string "%Y"))))
  13071. month (string-to-number (match-string 3 ans))
  13072. day (string-to-number (match-string 4 ans)))
  13073. (setq year (org-small-year-to-year year))
  13074. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13075. t nil ans)))
  13076. ;; Help matching dotted european dates
  13077. (when (string-match
  13078. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13079. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13080. (setq kill-year t)
  13081. (string-to-number (format-time-string "%Y")))
  13082. day (string-to-number (match-string 1 ans))
  13083. month (string-to-number (match-string 2 ans))
  13084. ans (replace-match (format "%04d-%02d-%02d" year month day)
  13085. t nil ans)))
  13086. ;; Help matching american dates, like 5/30 or 5/30/7
  13087. (when (string-match
  13088. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13089. (setq year (if (match-end 4)
  13090. (string-to-number (match-string 4 ans))
  13091. (progn (setq kill-year t)
  13092. (string-to-number (format-time-string "%Y"))))
  13093. month (string-to-number (match-string 1 ans))
  13094. day (string-to-number (match-string 2 ans)))
  13095. (setq year (org-small-year-to-year year))
  13096. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13097. t nil ans)))
  13098. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13099. ;; If there is a time with am/pm, and *no* time without it, we convert
  13100. ;; so that matching will be successful.
  13101. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13102. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13103. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13104. (setq hour (string-to-number (match-string 1 ans))
  13105. minute (if (match-end 3)
  13106. (string-to-number (match-string 3 ans))
  13107. 0)
  13108. pm (equal ?p
  13109. (string-to-char (downcase (match-string 4 ans)))))
  13110. (if (and (= hour 12) (not pm))
  13111. (setq hour 0)
  13112. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13113. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13114. t t ans))))
  13115. ;; Help matching HHhMM times, similarly as for am/pm times.
  13116. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  13117. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13118. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  13119. (setq hour (if (match-end 1)
  13120. (string-to-number (match-string 1 ans))
  13121. 0)
  13122. minute (if (match-end 2)
  13123. (string-to-number (match-string 2 ans))
  13124. 0))
  13125. (setq ans (replace-match (format "%02d:%02d" hour minute)
  13126. t t ans))))
  13127. ;; Check if a time range is given as a duration
  13128. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13129. (setq hour (string-to-number (match-string 1 ans))
  13130. h2 (+ hour (string-to-number (match-string 3 ans)))
  13131. minute (string-to-number (match-string 2 ans))
  13132. m2 (+ minute (if (match-end 5) (string-to-number
  13133. (match-string 5 ans))0)))
  13134. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13135. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13136. t t ans)))
  13137. ;; Check if there is a time range
  13138. (when (boundp 'org-end-time-was-given)
  13139. (setq org-time-was-given nil)
  13140. (when (and (string-match org-plain-time-of-day-regexp ans)
  13141. (match-end 8))
  13142. (setq org-end-time-was-given (match-string 8 ans))
  13143. (setq ans (concat (substring ans 0 (match-beginning 7))
  13144. (substring ans (match-end 7))))))
  13145. (setq tl (parse-time-string ans)
  13146. day (or (nth 3 tl) (nth 3 org-defdecode))
  13147. month
  13148. (cond ((nth 4 tl))
  13149. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13150. ;; Day was specified. Make sure DAY+MONTH
  13151. ;; combination happens in the future.
  13152. ((nth 3 tl)
  13153. (setq futurep t)
  13154. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13155. (nth 4 nowdecode)))
  13156. (t (nth 4 org-defdecode)))
  13157. year
  13158. (cond ((and (not kill-year) (nth 5 tl)))
  13159. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13160. ;; Month was guessed in the future and is at least
  13161. ;; equal to NOWDECODE's. Fix year accordingly.
  13162. (futurep
  13163. (if (or (> month (nth 4 nowdecode))
  13164. (>= day (nth 3 nowdecode)))
  13165. (nth 5 nowdecode)
  13166. (1+ (nth 5 nowdecode))))
  13167. ;; Month was specified. Make sure MONTH+YEAR
  13168. ;; combination happens in the future.
  13169. ((nth 4 tl)
  13170. (setq futurep t)
  13171. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13172. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13173. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13174. (t (nth 5 nowdecode))))
  13175. (t (nth 5 org-defdecode)))
  13176. hour (or (nth 2 tl) (nth 2 org-defdecode))
  13177. minute (or (nth 1 tl) (nth 1 org-defdecode))
  13178. second (or (nth 0 tl) 0)
  13179. wday (nth 6 tl))
  13180. (when (and (eq org-read-date-prefer-future 'time)
  13181. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13182. (equal day (nth 3 nowdecode))
  13183. (equal month (nth 4 nowdecode))
  13184. (equal year (nth 5 nowdecode))
  13185. (nth 2 tl)
  13186. (or (< (nth 2 tl) (nth 2 nowdecode))
  13187. (and (= (nth 2 tl) (nth 2 nowdecode))
  13188. (nth 1 tl)
  13189. (< (nth 1 tl) (nth 1 nowdecode)))))
  13190. (setq day (1+ day)
  13191. futurep t))
  13192. ;; Special date definitions below
  13193. (cond
  13194. (iso-week
  13195. ;; There was an iso week
  13196. (require 'cal-iso)
  13197. (setq futurep nil)
  13198. (setq year (or iso-year year)
  13199. day (or iso-weekday wday 1)
  13200. wday nil ; to make sure that the trigger below does not match
  13201. iso-date (calendar-gregorian-from-absolute
  13202. (calendar-iso-to-absolute
  13203. (list iso-week day year))))
  13204. ; FIXME: Should we also push ISO weeks into the future?
  13205. ; (when (and org-read-date-prefer-future
  13206. ; (not iso-year)
  13207. ; (< (calendar-absolute-from-gregorian iso-date)
  13208. ; (time-to-days nil)))
  13209. ; (setq year (1+ year)
  13210. ; iso-date (calendar-gregorian-from-absolute
  13211. ; (calendar-iso-to-absolute
  13212. ; (list iso-week day year)))))
  13213. (setq month (car iso-date)
  13214. year (nth 2 iso-date)
  13215. day (nth 1 iso-date)))
  13216. (deltan
  13217. (setq futurep nil)
  13218. (unless deltadef
  13219. (let ((now (decode-time)))
  13220. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13221. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13222. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13223. ((equal deltaw "m") (setq month (+ month deltan)))
  13224. ((equal deltaw "y") (setq year (+ year deltan)))))
  13225. ((and wday (not (nth 3 tl)))
  13226. ;; Weekday was given, but no day, so pick that day in the week
  13227. ;; on or after the derived date.
  13228. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13229. (unless (equal wday wday1)
  13230. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13231. (when (and (boundp 'org-time-was-given)
  13232. (nth 2 tl))
  13233. (setq org-time-was-given t))
  13234. (when (< year 100) (setq year (+ 2000 year)))
  13235. ;; Check of the date is representable
  13236. (if org-read-date-force-compatible-dates
  13237. (progn
  13238. (when (< year 1970)
  13239. (setq year 1970 org-read-date-analyze-forced-year t))
  13240. (when (> year 2037)
  13241. (setq year 2037 org-read-date-analyze-forced-year t)))
  13242. (condition-case nil
  13243. (ignore (encode-time second minute hour day month year))
  13244. (error
  13245. (setq year (nth 5 org-defdecode))
  13246. (setq org-read-date-analyze-forced-year t))))
  13247. (setq org-read-date-analyze-futurep futurep)
  13248. (list second minute hour day month year)))
  13249. (defvar parse-time-weekdays)
  13250. (defun org-read-date-get-relative (s today default)
  13251. "Check string S for special relative date string.
  13252. TODAY and DEFAULT are internal times, for today and for a default.
  13253. Return shift list (N what def-flag)
  13254. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13255. N is the number of WHATs to shift.
  13256. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13257. the DEFAULT date rather than TODAY."
  13258. (require 'parse-time)
  13259. (when (and
  13260. (string-match
  13261. (concat
  13262. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13263. "\\([0-9]+\\)?"
  13264. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13265. "\\([ \t]\\|$\\)") s)
  13266. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13267. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13268. (string-to-char (substring (match-string 1 s) -1))
  13269. ?+))
  13270. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13271. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13272. (what (if (match-end 3) (match-string 3 s) "d"))
  13273. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13274. (date (if rel default today))
  13275. (wday (nth 6 (decode-time date)))
  13276. delta)
  13277. (if wday1
  13278. (progn
  13279. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13280. (when (= delta 0) (setq delta 7))
  13281. (when (= dir ?-)
  13282. (setq delta (- delta 7))
  13283. (when (= delta 0) (setq delta -7)))
  13284. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13285. (list delta "d" rel))
  13286. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13287. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13288. "Turn a user-specified date into the internal representation.
  13289. The internal representation needed by the calendar is (month day year).
  13290. This is a wrapper to handle the brain-dead convention in calendar that
  13291. user function argument order change dependent on argument order."
  13292. (pcase calendar-date-style
  13293. (`american (list arg1 arg2 arg3))
  13294. (`european (list arg2 arg1 arg3))
  13295. (`iso (list arg2 arg3 arg1))))
  13296. (defun org-eval-in-calendar (form &optional keepdate)
  13297. "Eval FORM in the calendar window and return to current window.
  13298. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13299. (let ((sf (selected-frame))
  13300. (sw (selected-window)))
  13301. (select-window (get-buffer-window "*Calendar*" t))
  13302. (eval form)
  13303. (when (and (not keepdate) (calendar-cursor-to-date))
  13304. (let* ((date (calendar-cursor-to-date))
  13305. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13306. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13307. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13308. (select-window sw)
  13309. (select-frame-set-input-focus sf)))
  13310. (defun org-calendar-select ()
  13311. "Return to `org-read-date' with the date currently selected.
  13312. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13313. (interactive)
  13314. (when (calendar-cursor-to-date)
  13315. (let* ((date (calendar-cursor-to-date))
  13316. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13317. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13318. (when (active-minibuffer-window) (exit-minibuffer))))
  13319. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13320. "Insert a date stamp for the date given by the internal TIME.
  13321. See `format-time-string' for the format of TIME.
  13322. WITH-HM means use the stamp format that includes the time of the day.
  13323. INACTIVE means use square brackets instead of angular ones, so that the
  13324. stamp will not contribute to the agenda.
  13325. PRE and POST are optional strings to be inserted before and after the
  13326. stamp.
  13327. The command returns the inserted time stamp."
  13328. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13329. stamp)
  13330. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13331. (insert-before-markers (or pre ""))
  13332. (when (listp extra)
  13333. (setq extra (car extra))
  13334. (if (and (stringp extra)
  13335. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13336. (setq extra (format "-%02d:%02d"
  13337. (string-to-number (match-string 1 extra))
  13338. (string-to-number (match-string 2 extra))))
  13339. (setq extra nil)))
  13340. (when extra
  13341. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13342. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13343. (insert-before-markers (or post ""))
  13344. (setq org-last-inserted-timestamp stamp)))
  13345. (defun org-toggle-time-stamp-overlays ()
  13346. "Toggle the use of custom time stamp formats."
  13347. (interactive)
  13348. (setq org-display-custom-times (not org-display-custom-times))
  13349. (unless org-display-custom-times
  13350. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13351. (while (setq p (next-single-property-change p 'display))
  13352. (when (and (get-text-property p 'display)
  13353. (eq (get-text-property p 'face) 'org-date))
  13354. (remove-text-properties
  13355. p (setq p (next-single-property-change p 'display))
  13356. '(display t))))
  13357. (set-buffer-modified-p bmp)))
  13358. (org-restart-font-lock)
  13359. (setq org-table-may-need-update t)
  13360. (if org-display-custom-times
  13361. (message "Time stamps are overlaid with custom format")
  13362. (message "Time stamp overlays removed")))
  13363. (defun org-display-custom-time (beg end)
  13364. "Overlay modified time stamp format over timestamp between BEG and END."
  13365. (let* ((ts (buffer-substring beg end))
  13366. t1 with-hm tf time str (off 0))
  13367. (save-match-data
  13368. (setq t1 (org-parse-time-string ts t))
  13369. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13370. (setq off (- (match-end 0) (match-beginning 0)))))
  13371. (setq end (- end off))
  13372. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13373. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13374. time (org-fix-decoded-time t1)
  13375. str (org-add-props
  13376. (format-time-string
  13377. (substring tf 1 -1) (apply 'encode-time time))
  13378. nil 'mouse-face 'highlight))
  13379. (put-text-property beg end 'display str)))
  13380. (defun org-fix-decoded-time (time)
  13381. "Set 0 instead of nil for the first 6 elements of time.
  13382. Don't touch the rest."
  13383. (let ((n 0))
  13384. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13385. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13386. "Difference between TIMESTAMP-STRING and now in days.
  13387. If SECONDS is non-nil, return the difference in seconds."
  13388. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13389. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13390. (funcall fdiff nil))))
  13391. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13392. "Is the time in TIMESTAMP-STRING close to the current date?"
  13393. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13394. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13395. (not (org-entry-is-done-p))))
  13396. (defun org-get-wdays (ts &optional delay zero-delay)
  13397. "Get the deadline lead time appropriate for timestring TS.
  13398. When DELAY is non-nil, get the delay time for scheduled items
  13399. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13400. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13401. don't try to find the delay cookie in the scheduled timestamp."
  13402. (let ((tv (if delay org-scheduled-delay-days
  13403. org-deadline-warning-days)))
  13404. (cond
  13405. ((or (and delay (< tv 0))
  13406. (and delay zero-delay (<= tv 0))
  13407. (and (not delay) (<= tv 0)))
  13408. ;; Enforce this value no matter what
  13409. (- tv))
  13410. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13411. ;; lead time is specified.
  13412. (floor (* (string-to-number (match-string 1 ts))
  13413. (cdr (assoc (match-string 2 ts)
  13414. '(("d" . 1) ("w" . 7)
  13415. ("m" . 30.4) ("y" . 365.25)
  13416. ("h" . 0.041667)))))))
  13417. ;; go for the default.
  13418. (t tv))))
  13419. (defun org-calendar-select-mouse (ev)
  13420. "Return to `org-read-date' with the date currently selected.
  13421. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13422. (interactive "e")
  13423. (mouse-set-point ev)
  13424. (when (calendar-cursor-to-date)
  13425. (let* ((date (calendar-cursor-to-date))
  13426. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13427. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13428. (when (active-minibuffer-window) (exit-minibuffer))))
  13429. (defun org-check-deadlines (ndays)
  13430. "Check if there are any deadlines due or past due.
  13431. A deadline is considered due if it happens within `org-deadline-warning-days'
  13432. days from today's date. If the deadline appears in an entry marked DONE,
  13433. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13434. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13435. are shown."
  13436. (interactive "P")
  13437. (let* ((org-warn-days
  13438. (cond
  13439. ((equal ndays '(4)) 100000)
  13440. (ndays (prefix-numeric-value ndays))
  13441. (t (abs org-deadline-warning-days))))
  13442. (case-fold-search nil)
  13443. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13444. (callback
  13445. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13446. (message "%d deadlines past-due or due within %d days"
  13447. (org-occur regexp nil callback)
  13448. org-warn-days)))
  13449. (defsubst org-re-timestamp (type)
  13450. "Return a regexp for timestamp TYPE.
  13451. Allowed values for TYPE are:
  13452. all: all timestamps
  13453. active: only active timestamps (<...>)
  13454. inactive: only inactive timestamps ([...])
  13455. scheduled: only scheduled timestamps
  13456. deadline: only deadline timestamps
  13457. closed: only closed time-stamps
  13458. When TYPE is nil, fall back on returning a regexp that matches
  13459. both scheduled and deadline timestamps."
  13460. (cl-case type
  13461. (all org-ts-regexp-both)
  13462. (active org-ts-regexp)
  13463. (inactive org-ts-regexp-inactive)
  13464. (scheduled org-scheduled-time-regexp)
  13465. (deadline org-deadline-time-regexp)
  13466. (closed org-closed-time-regexp)
  13467. (otherwise
  13468. (concat "\\<"
  13469. (regexp-opt (list org-deadline-string org-scheduled-string))
  13470. " *<\\([^>]+\\)>"))))
  13471. (defun org-check-before-date (d)
  13472. "Check if there are deadlines or scheduled entries before date D."
  13473. (interactive (list (org-read-date)))
  13474. (let* ((case-fold-search nil)
  13475. (regexp (org-re-timestamp org-ts-type))
  13476. (ts-type org-ts-type)
  13477. (callback
  13478. (lambda ()
  13479. (let ((match (match-string 1)))
  13480. (and (if (memq ts-type '(active inactive all))
  13481. (eq (org-element-type (save-excursion
  13482. (backward-char)
  13483. (org-element-context)))
  13484. 'timestamp)
  13485. (org-at-planning-p))
  13486. (time-less-p
  13487. (org-time-string-to-time match)
  13488. (org-time-string-to-time d)))))))
  13489. (message "%d entries before %s"
  13490. (org-occur regexp nil callback)
  13491. d)))
  13492. (defun org-check-after-date (d)
  13493. "Check if there are deadlines or scheduled entries after date D."
  13494. (interactive (list (org-read-date)))
  13495. (let* ((case-fold-search nil)
  13496. (regexp (org-re-timestamp org-ts-type))
  13497. (ts-type org-ts-type)
  13498. (callback
  13499. (lambda ()
  13500. (let ((match (match-string 1)))
  13501. (and (if (memq ts-type '(active inactive all))
  13502. (eq (org-element-type (save-excursion
  13503. (backward-char)
  13504. (org-element-context)))
  13505. 'timestamp)
  13506. (org-at-planning-p))
  13507. (not (time-less-p
  13508. (org-time-string-to-time match)
  13509. (org-time-string-to-time d))))))))
  13510. (message "%d entries after %s"
  13511. (org-occur regexp nil callback)
  13512. d)))
  13513. (defun org-check-dates-range (start-date end-date)
  13514. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13515. (interactive (list (org-read-date nil nil nil "Range starts")
  13516. (org-read-date nil nil nil "Range end")))
  13517. (let ((case-fold-search nil)
  13518. (regexp (org-re-timestamp org-ts-type))
  13519. (callback
  13520. (let ((type org-ts-type))
  13521. (lambda ()
  13522. (let ((match (match-string 1)))
  13523. (and
  13524. (if (memq type '(active inactive all))
  13525. (eq (org-element-type (save-excursion
  13526. (backward-char)
  13527. (org-element-context)))
  13528. 'timestamp)
  13529. (org-at-planning-p))
  13530. (not (time-less-p
  13531. (org-time-string-to-time match)
  13532. (org-time-string-to-time start-date)))
  13533. (time-less-p
  13534. (org-time-string-to-time match)
  13535. (org-time-string-to-time end-date))))))))
  13536. (message "%d entries between %s and %s"
  13537. (org-occur regexp nil callback) start-date end-date)))
  13538. (defun org-evaluate-time-range (&optional to-buffer)
  13539. "Evaluate a time range by computing the difference between start and end.
  13540. Normally the result is just printed in the echo area, but with prefix arg
  13541. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13542. If the time range is actually in a table, the result is inserted into the
  13543. next column.
  13544. For time difference computation, a year is assumed to be exactly 365
  13545. days in order to avoid rounding problems."
  13546. (interactive "P")
  13547. (or
  13548. (org-clock-update-time-maybe)
  13549. (save-excursion
  13550. (unless (org-at-date-range-p t)
  13551. (goto-char (point-at-bol))
  13552. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13553. (unless (org-at-date-range-p t)
  13554. (user-error "Not at a time-stamp range, and none found in current line")))
  13555. (let* ((ts1 (match-string 1))
  13556. (ts2 (match-string 2))
  13557. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13558. (match-end (match-end 0))
  13559. (time1 (org-time-string-to-time ts1))
  13560. (time2 (org-time-string-to-time ts2))
  13561. (diff (abs (float-time (time-subtract time2 time1))))
  13562. (negative (time-less-p time2 time1))
  13563. ;; (ys (floor (* 365 24 60 60)))
  13564. (ds (* 24 60 60))
  13565. (hs (* 60 60))
  13566. (fy "%dy %dd %02d:%02d")
  13567. (fy1 "%dy %dd")
  13568. (fd "%dd %02d:%02d")
  13569. (fd1 "%dd")
  13570. (fh "%02d:%02d")
  13571. y d h m align)
  13572. (if havetime
  13573. (setq ; y (floor diff ys) diff (mod diff ys)
  13574. y 0
  13575. d (floor diff ds) diff (mod diff ds)
  13576. h (floor diff hs) diff (mod diff hs)
  13577. m (floor diff 60))
  13578. (setq ; y (floor diff ys) diff (mod diff ys)
  13579. y 0
  13580. d (round diff ds)
  13581. h 0 m 0))
  13582. (if (not to-buffer)
  13583. (message "%s" (org-make-tdiff-string y d h m))
  13584. (if (org-at-table-p)
  13585. (progn
  13586. (goto-char match-end)
  13587. (setq align t)
  13588. (and (looking-at " *|") (goto-char (match-end 0))))
  13589. (goto-char match-end))
  13590. (when (looking-at
  13591. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13592. (replace-match ""))
  13593. (when negative (insert " -"))
  13594. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13595. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13596. (insert " " (format fh h m))))
  13597. (when align (org-table-align))
  13598. (message "Time difference inserted")))))
  13599. (defun org-make-tdiff-string (y d h m)
  13600. (let ((fmt "")
  13601. (l nil))
  13602. (when (> y 0)
  13603. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13604. (push y l))
  13605. (when (> d 0)
  13606. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13607. (push d l))
  13608. (when (> h 0)
  13609. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13610. (push h l))
  13611. (when (> m 0)
  13612. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13613. (push m l))
  13614. (apply 'format fmt (nreverse l))))
  13615. (defun org-time-string-to-time (s)
  13616. "Convert timestamp string S into internal time."
  13617. (apply #'encode-time (org-parse-time-string s)))
  13618. (defun org-time-string-to-seconds (s)
  13619. "Convert a timestamp string S into a number of seconds."
  13620. (float-time (org-time-string-to-time s)))
  13621. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13622. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13623. "Convert time stamp S to an absolute day number.
  13624. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13625. stamp, get the closest date to DAYNR. If PREFER is
  13626. `past' (respectively `future') return a date past (respectively
  13627. after) or equal to DAYNR.
  13628. POS is the location of time stamp S, as a buffer position in
  13629. BUFFER.
  13630. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13631. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13632. signaled."
  13633. (cond
  13634. ((string-match "\\`%%\\((.*)\\)" s)
  13635. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13636. ;; only able to match individual dates. If it fails, raise an
  13637. ;; error.
  13638. (if (and daynr
  13639. (org-diary-sexp-entry
  13640. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13641. daynr
  13642. (signal 'org-diary-sexp-no-match (list s))))
  13643. (daynr (org-closest-date s daynr prefer))
  13644. (t (time-to-days
  13645. (condition-case errdata
  13646. (org-time-string-to-time s)
  13647. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13648. s
  13649. (if (not (and buffer pos)) ""
  13650. (format-message " at %d in buffer `%s'" pos buffer))
  13651. (cdr errdata))))))))
  13652. (defun org-days-to-iso-week (days)
  13653. "Return the ISO week number."
  13654. (require 'cal-iso)
  13655. (car (calendar-iso-from-absolute days)))
  13656. (defun org-small-year-to-year (year)
  13657. "Convert 2-digit years into 4-digit years.
  13658. YEAR is expanded into one of the 30 next years, if possible, or
  13659. into a past one. Any year larger than 99 is returned unchanged."
  13660. (if (>= year 100) year
  13661. (let* ((current (string-to-number (format-time-string "%Y")))
  13662. (century (/ current 100))
  13663. (offset (- year (% current 100))))
  13664. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13665. ((> offset -70) (+ (* century 100) year))
  13666. (t (+ (* (1+ century) 100) year))))))
  13667. (defun org-time-from-absolute (d)
  13668. "Return the time corresponding to date D.
  13669. D may be an absolute day number, or a calendar-type list (month day year)."
  13670. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13671. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13672. (defvar org-agenda-current-date)
  13673. (defun org-calendar-holiday ()
  13674. "List of holidays, for Diary display in Org mode."
  13675. (require 'holidays)
  13676. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13677. (and hl (mapconcat #'identity hl "; "))))
  13678. (defun org-diary-sexp-entry (sexp entry d)
  13679. "Process a SEXP diary ENTRY for date D."
  13680. (require 'diary-lib)
  13681. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13682. ;; dynamically.
  13683. (let* ((sexp `(let ((entry ,entry)
  13684. (date ',d))
  13685. ,(car (read-from-string sexp))))
  13686. (result (if calendar-debug-sexp (eval sexp)
  13687. (condition-case nil
  13688. (eval sexp)
  13689. (error
  13690. (beep)
  13691. (message "Bad sexp at line %d in %s: %s"
  13692. (org-current-line)
  13693. (buffer-file-name) sexp)
  13694. (sleep-for 2))))))
  13695. (cond ((stringp result) (split-string result "; "))
  13696. ((and (consp result)
  13697. (not (consp (cdr result)))
  13698. (stringp (cdr result))) (cdr result))
  13699. ((and (consp result)
  13700. (stringp (car result))) result)
  13701. (result entry))))
  13702. (defun org-diary-to-ical-string (frombuf)
  13703. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13704. This uses the icalendar.el library."
  13705. (let* ((tmpdir temporary-file-directory)
  13706. (tmpfile (make-temp-name
  13707. (expand-file-name "orgics" tmpdir)))
  13708. buf rtn b e)
  13709. (with-current-buffer frombuf
  13710. (icalendar-export-region (point-min) (point-max) tmpfile)
  13711. (setq buf (find-buffer-visiting tmpfile))
  13712. (set-buffer buf)
  13713. (goto-char (point-min))
  13714. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13715. (setq b (match-beginning 0)))
  13716. (goto-char (point-max))
  13717. (when (re-search-backward "^END:VEVENT" nil t)
  13718. (setq e (match-end 0)))
  13719. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13720. (kill-buffer buf)
  13721. (delete-file tmpfile)
  13722. rtn))
  13723. (defun org-closest-date (start current prefer)
  13724. "Return closest date to CURRENT starting from START.
  13725. CURRENT and START are both time stamps.
  13726. When PREFER is `past', return a date that is either CURRENT or
  13727. past. When PREFER is `future', return a date that is either
  13728. CURRENT or future.
  13729. Only time stamps with a repeater are modified. Any other time
  13730. stamp stay unchanged. In any case, return value is an absolute
  13731. day number."
  13732. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13733. ;; No repeater. Do not shift time stamp.
  13734. (time-to-days (org-time-string-to-time start))
  13735. (let ((value (string-to-number (match-string 1 start)))
  13736. (type (match-string 2 start)))
  13737. (if (= 0 value)
  13738. ;; Repeater with a 0-value is considered as void.
  13739. (time-to-days (org-time-string-to-time start))
  13740. (let* ((base (org-date-to-gregorian start))
  13741. (target (org-date-to-gregorian current))
  13742. (sday (calendar-absolute-from-gregorian base))
  13743. (cday (calendar-absolute-from-gregorian target))
  13744. n1 n2)
  13745. ;; If START is already past CURRENT, just return START.
  13746. (if (<= cday sday) sday
  13747. ;; Compute closest date before (N1) and closest date past
  13748. ;; (N2) CURRENT.
  13749. (pcase type
  13750. ("h"
  13751. (let ((missing-hours
  13752. (mod (+ (- (* 24 (- cday sday))
  13753. (nth 2 (org-parse-time-string start)))
  13754. org-extend-today-until)
  13755. value)))
  13756. (setf n1 (if (= missing-hours 0) cday
  13757. (- cday (1+ (/ missing-hours 24)))))
  13758. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13759. ((or "d" "w")
  13760. (let ((value (if (equal type "w") (* 7 value) value)))
  13761. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13762. (setf n2 (+ n1 value))))
  13763. ("m"
  13764. (let* ((add-months
  13765. (lambda (d n)
  13766. ;; Add N months to gregorian date D, i.e.,
  13767. ;; a list (MONTH DAY YEAR). Return a valid
  13768. ;; gregorian date.
  13769. (let ((m (+ (nth 0 d) n)))
  13770. (list (mod m 12)
  13771. (nth 1 d)
  13772. (+ (/ m 12) (nth 2 d))))))
  13773. (months ; Complete months to TARGET.
  13774. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13775. (- (nth 0 target) (nth 0 base))
  13776. ;; If START's day is greater than
  13777. ;; TARGET's, remove incomplete month.
  13778. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13779. value)
  13780. value))
  13781. (before (funcall add-months base months)))
  13782. (setf n1 (calendar-absolute-from-gregorian before))
  13783. (setf n2
  13784. (calendar-absolute-from-gregorian
  13785. (funcall add-months before value)))))
  13786. (_
  13787. (let* ((d (nth 1 base))
  13788. (m (nth 0 base))
  13789. (y (nth 2 base))
  13790. (years ; Complete years to TARGET.
  13791. (* (/ (- (nth 2 target)
  13792. y
  13793. ;; If START's month and day are
  13794. ;; greater than TARGET's, remove
  13795. ;; incomplete year.
  13796. (if (or (> (nth 0 target) m)
  13797. (and (= (nth 0 target) m)
  13798. (> (nth 1 target) d)))
  13799. 0
  13800. 1))
  13801. value)
  13802. value))
  13803. (before (list m d (+ y years))))
  13804. (setf n1 (calendar-absolute-from-gregorian before))
  13805. (setf n2 (calendar-absolute-from-gregorian
  13806. (list m d (+ (nth 2 before) value)))))))
  13807. ;; Handle PREFER parameter, if any.
  13808. (cond
  13809. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13810. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13811. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13812. (defun org-date-to-gregorian (d)
  13813. "Turn any specification of date D into a Gregorian date for the calendar."
  13814. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13815. ((and (listp d) (= (length d) 3)) d)
  13816. ((stringp d)
  13817. (let ((d (org-parse-time-string d)))
  13818. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13819. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13820. (defun org-timestamp-up (&optional arg)
  13821. "Increase the date item at the cursor by one.
  13822. If the cursor is on the year, change the year. If it is on the month,
  13823. the day or the time, change that. If the cursor is on the enclosing
  13824. bracket, change the timestamp type.
  13825. With prefix ARG, change by that many units."
  13826. (interactive "p")
  13827. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13828. (defun org-timestamp-down (&optional arg)
  13829. "Decrease the date item at the cursor by one.
  13830. If the cursor is on the year, change the year. If it is on the month,
  13831. the day or the time, change that. If the cursor is on the enclosing
  13832. bracket, change the timestamp type.
  13833. With prefix ARG, change by that many units."
  13834. (interactive "p")
  13835. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13836. (defun org-timestamp-up-day (&optional arg)
  13837. "Increase the date in the time stamp by one day.
  13838. With prefix ARG, change that many days."
  13839. (interactive "p")
  13840. (if (and (not (org-at-timestamp-p 'lax))
  13841. (org-at-heading-p))
  13842. (org-todo 'up)
  13843. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13844. (defun org-timestamp-down-day (&optional arg)
  13845. "Decrease the date in the time stamp by one day.
  13846. With prefix ARG, change that many days."
  13847. (interactive "p")
  13848. (if (and (not (org-at-timestamp-p 'lax))
  13849. (org-at-heading-p))
  13850. (org-todo 'down)
  13851. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13852. (defun org-at-timestamp-p (&optional extended)
  13853. "Non-nil if point is inside a timestamp.
  13854. By default, the function only consider syntactically valid active
  13855. timestamps. However, the caller may have a broader definition
  13856. for timestamps. As a consequence, optional argument EXTENDED can
  13857. be set to the following values
  13858. `inactive'
  13859. Include also syntactically valid inactive timestamps.
  13860. `agenda'
  13861. Include timestamps allowed in Agenda, i.e., those in
  13862. properties drawers, planning lines and clock lines.
  13863. `lax'
  13864. Ignore context. The function matches any part of the
  13865. document looking like a timestamp. This includes comments,
  13866. example blocks...
  13867. For backward-compatibility with Org 9.0, every other non-nil
  13868. value is equivalent to `inactive'.
  13869. When at a timestamp, return the position of the point as a symbol
  13870. among `bracket', `after', `year', `month', `hour', `minute',
  13871. `day' or a number of character from the last know part of the
  13872. time stamp.
  13873. When matching, the match groups are the following:
  13874. group 1: year
  13875. group 2: month
  13876. group 3: day number
  13877. group 4: day name
  13878. group 5: hours, if any
  13879. group 6: minutes, if any"
  13880. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13881. (pos (point))
  13882. (match?
  13883. (let ((boundaries (org-in-regexp regexp)))
  13884. (save-match-data
  13885. (cond ((null boundaries) nil)
  13886. ((eq extended 'lax) t)
  13887. (t
  13888. (or (and (eq extended 'agenda)
  13889. (or (org-at-planning-p)
  13890. (org-at-property-p)
  13891. (and (bound-and-true-p
  13892. org-agenda-include-inactive-timestamps)
  13893. (org-at-clock-log-p))))
  13894. (eq 'timestamp
  13895. (save-excursion
  13896. (when (= pos (cdr boundaries)) (forward-char -1))
  13897. (org-element-type (org-element-context)))))))))))
  13898. (cond
  13899. ((not match?) nil)
  13900. ((= pos (match-beginning 0)) 'bracket)
  13901. ;; Distinguish location right before the closing bracket from
  13902. ;; right after it.
  13903. ((= pos (1- (match-end 0))) 'bracket)
  13904. ((= pos (match-end 0)) 'after)
  13905. ((org-pos-in-match-range pos 2) 'year)
  13906. ((org-pos-in-match-range pos 3) 'month)
  13907. ((org-pos-in-match-range pos 7) 'hour)
  13908. ((org-pos-in-match-range pos 8) 'minute)
  13909. ((or (org-pos-in-match-range pos 4)
  13910. (org-pos-in-match-range pos 5)) 'day)
  13911. ((and (> pos (or (match-end 8) (match-end 5)))
  13912. (< pos (match-end 0)))
  13913. (- pos (or (match-end 8) (match-end 5))))
  13914. (t 'day))))
  13915. (defun org-toggle-timestamp-type ()
  13916. "Toggle the type (<active> or [inactive]) of a time stamp."
  13917. (interactive)
  13918. (when (org-at-timestamp-p 'lax)
  13919. (let ((beg (match-beginning 0)) (end (match-end 0))
  13920. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13921. (save-excursion
  13922. (goto-char beg)
  13923. (while (re-search-forward "[][<>]" end t)
  13924. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13925. t t)))
  13926. (message "Timestamp is now %sactive"
  13927. (if (equal (char-after beg) ?<) "" "in")))))
  13928. (defun org-at-clock-log-p ()
  13929. "Non-nil if point is on a clock log line."
  13930. (and (org-match-line org-clock-line-re)
  13931. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13932. (defvar org-clock-history) ; defined in org-clock.el
  13933. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13934. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13935. "Change the date in the time stamp at point.
  13936. The date is changed by N times WHAT. WHAT can be `day', `month',
  13937. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13938. position in the timestamp determines what is changed.
  13939. When optional argument UPDOWN is non-nil, minutes are rounded
  13940. according to `org-time-stamp-rounding-minutes'.
  13941. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13942. \"--2d\"."
  13943. (let ((origin (point))
  13944. (timestamp? (org-at-timestamp-p 'lax))
  13945. origin-cat
  13946. with-hm inactive
  13947. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13948. extra rem
  13949. ts time time0 fixnext clrgx)
  13950. (unless timestamp? (user-error "Not at a timestamp"))
  13951. (if (and (not what) (eq timestamp? 'bracket))
  13952. (org-toggle-timestamp-type)
  13953. ;; Point isn't on brackets. Remember the part of the time-stamp
  13954. ;; the point was in. Indeed, size of time-stamps may change,
  13955. ;; but point must be kept in the same category nonetheless.
  13956. (setq origin-cat timestamp?)
  13957. (when (and (not what) (not (eq timestamp? 'day))
  13958. org-display-custom-times
  13959. (get-text-property (point) 'display)
  13960. (not (get-text-property (1- (point)) 'display)))
  13961. (setq timestamp? 'day))
  13962. (setq timestamp? (or what timestamp?)
  13963. inactive (= (char-after (match-beginning 0)) ?\[)
  13964. ts (match-string 0))
  13965. (replace-match "")
  13966. (when (string-match
  13967. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13968. ts)
  13969. (setq extra (match-string 1 ts))
  13970. (when suppress-tmp-delay
  13971. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13972. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13973. (setq with-hm t))
  13974. (setq time0 (org-parse-time-string ts))
  13975. (when (and updown
  13976. (eq timestamp? 'minute)
  13977. (not current-prefix-arg))
  13978. ;; This looks like s-up and s-down. Change by one rounding step.
  13979. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13980. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13981. (setcar (cdr time0) (+ (nth 1 time0)
  13982. (if (> n 0) (- rem) (- dm rem))))))
  13983. (setq time
  13984. (apply #'encode-time
  13985. (or (car time0) 0)
  13986. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13987. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13988. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13989. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13990. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13991. (nthcdr 6 time0)))
  13992. (when (and (memq timestamp? '(hour minute))
  13993. extra
  13994. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13995. (setq extra (org-modify-ts-extra
  13996. extra
  13997. (if (eq timestamp? 'hour) 2 5)
  13998. n dm)))
  13999. (when (integerp timestamp?)
  14000. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  14001. (when (eq what 'calendar)
  14002. (let ((cal-date (org-get-date-from-calendar)))
  14003. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  14004. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  14005. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  14006. (setcar time0 (or (car time0) 0))
  14007. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  14008. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  14009. (setq time (apply 'encode-time time0))))
  14010. ;; Insert the new time-stamp, and ensure point stays in the same
  14011. ;; category as before (i.e. not after the last position in that
  14012. ;; category).
  14013. (let ((pos (point)))
  14014. ;; Stay before inserted string. `save-excursion' is of no use.
  14015. (setq org-last-changed-timestamp
  14016. (org-insert-time-stamp time with-hm inactive nil nil extra))
  14017. (goto-char pos))
  14018. (save-match-data
  14019. (looking-at org-ts-regexp3)
  14020. (goto-char
  14021. (pcase origin-cat
  14022. ;; `day' category ends before `hour' if any, or at the end
  14023. ;; of the day name.
  14024. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14025. (`hour (min (match-end 7) origin))
  14026. (`minute (min (1- (match-end 8)) origin))
  14027. ((pred integerp) (min (1- (match-end 0)) origin))
  14028. ;; Point was right after the time-stamp. However, the
  14029. ;; time-stamp length might have changed, so refer to
  14030. ;; (match-end 0) instead.
  14031. (`after (match-end 0))
  14032. ;; `year' and `month' have both fixed size: point couldn't
  14033. ;; have moved into another part.
  14034. (_ origin))))
  14035. ;; Update clock if on a CLOCK line.
  14036. (org-clock-update-time-maybe)
  14037. ;; Maybe adjust the closest clock in `org-clock-history'
  14038. (when org-clock-adjust-closest
  14039. (if (not (and (org-at-clock-log-p)
  14040. (< 1 (length (delq nil (mapcar 'marker-position
  14041. org-clock-history))))))
  14042. (message "No clock to adjust")
  14043. (cond ((save-excursion ; fix previous clock?
  14044. (re-search-backward org-ts-regexp0 nil t)
  14045. (looking-back (concat org-clock-string " \\[")
  14046. (line-beginning-position)))
  14047. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14048. ((save-excursion ; fix next clock?
  14049. (re-search-backward org-ts-regexp0 nil t)
  14050. (looking-at (concat org-ts-regexp0 "\\] =>")))
  14051. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14052. (save-window-excursion
  14053. ;; Find closest clock to point, adjust the previous/next one in history
  14054. (let* ((p (save-excursion (org-back-to-heading t)))
  14055. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14056. (clfixnth
  14057. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14058. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14059. (if (not clfixpos)
  14060. (message "No clock to adjust")
  14061. (save-excursion
  14062. (org-goto-marker-or-bmk clfixpos)
  14063. (org-show-subtree)
  14064. (when (re-search-forward clrgx nil t)
  14065. (goto-char (match-beginning 1))
  14066. (let (org-clock-adjust-closest)
  14067. (org-timestamp-change n timestamp? updown))
  14068. (message "Clock adjusted in %s for heading: %s"
  14069. (file-name-nondirectory (buffer-file-name))
  14070. (org-get-heading t t)))))))))
  14071. ;; Try to recenter the calendar window, if any.
  14072. (when (and org-calendar-follow-timestamp-change
  14073. (get-buffer-window "*Calendar*" t)
  14074. (memq timestamp? '(day month year)))
  14075. (org-recenter-calendar (time-to-days time))))))
  14076. (defun org-modify-ts-extra (s pos n dm)
  14077. "Change the different parts of the lead-time and repeat fields in timestamp."
  14078. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14079. ng h m new rem)
  14080. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14081. (cond
  14082. ((or (org-pos-in-match-range pos 2)
  14083. (org-pos-in-match-range pos 3))
  14084. (setq m (string-to-number (match-string 3 s))
  14085. h (string-to-number (match-string 2 s)))
  14086. (if (org-pos-in-match-range pos 2)
  14087. (setq h (+ h n))
  14088. (setq n (* dm (with-no-warnings (cl-signum n))))
  14089. (unless (= 0 (setq rem (% m dm)))
  14090. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14091. (setq m (+ m n)))
  14092. (when (< m 0) (setq m (+ m 60) h (1- h)))
  14093. (when (> m 59) (setq m (- m 60) h (1+ h)))
  14094. (setq h (mod h 24))
  14095. (setq ng 1 new (format "-%02d:%02d" h m)))
  14096. ((org-pos-in-match-range pos 6)
  14097. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14098. ((org-pos-in-match-range pos 5)
  14099. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14100. ((org-pos-in-match-range pos 9)
  14101. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14102. ((org-pos-in-match-range pos 8)
  14103. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14104. (when ng
  14105. (setq s (concat
  14106. (substring s 0 (match-beginning ng))
  14107. new
  14108. (substring s (match-end ng))))))
  14109. s))
  14110. (defun org-recenter-calendar (d)
  14111. "If the calendar is visible, recenter it to date D."
  14112. (let ((cwin (get-buffer-window "*Calendar*" t)))
  14113. (when cwin
  14114. (let ((calendar-move-hook nil))
  14115. (with-selected-window cwin
  14116. (calendar-goto-date
  14117. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14118. (defun org-goto-calendar (&optional arg)
  14119. "Go to the Emacs calendar at the current date.
  14120. If there is a time stamp in the current line, go to that date.
  14121. A prefix ARG can be used to force the current date."
  14122. (interactive "P")
  14123. (let ((calendar-move-hook nil)
  14124. (calendar-view-holidays-initially-flag nil)
  14125. (calendar-view-diary-initially-flag nil)
  14126. diff)
  14127. (when (or (org-at-timestamp-p 'lax)
  14128. (org-match-line (concat ".*" org-ts-regexp)))
  14129. (let ((d1 (time-to-days nil))
  14130. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  14131. (setq diff (- d2 d1))))
  14132. (calendar)
  14133. (calendar-goto-today)
  14134. (when (and diff (not arg)) (calendar-forward-day diff))))
  14135. (defun org-get-date-from-calendar ()
  14136. "Return a list (month day year) of date at point in calendar."
  14137. (with-current-buffer "*Calendar*"
  14138. (save-match-data
  14139. (calendar-cursor-to-date))))
  14140. (defun org-date-from-calendar ()
  14141. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  14142. If there is already a time stamp at the cursor position, update it."
  14143. (interactive)
  14144. (if (org-at-timestamp-p 'lax)
  14145. (org-timestamp-change 0 'calendar)
  14146. (let ((cal-date (org-get-date-from-calendar)))
  14147. (org-insert-time-stamp
  14148. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  14149. (defcustom org-image-actual-width t
  14150. "When non-nil, use the actual width of images when inlining them.
  14151. When set to a number, use imagemagick (when available) to set the
  14152. image's width to this value.
  14153. When set to a number in a list, try to get the width from any
  14154. #+ATTR.* keyword if it matches a width specification like
  14155. #+ATTR_HTML: :width 300px
  14156. and fall back on that number if none is found.
  14157. When set to nil, try to get the width from an #+ATTR.* keyword
  14158. and fall back on the original width if none is found.
  14159. When set to any other non-nil value, always use the image width.
  14160. This requires Emacs >= 24.1, built with imagemagick support."
  14161. :group 'org-appearance
  14162. :version "24.4"
  14163. :package-version '(Org . "8.0")
  14164. :type '(choice
  14165. (const :tag "Use the image width" t)
  14166. (integer :tag "Use a number of pixels")
  14167. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  14168. (const :tag "Use #+ATTR* or don't resize" nil)))
  14169. (defcustom org-agenda-inhibit-startup nil
  14170. "Inhibit startup when preparing agenda buffers.
  14171. When this variable is t, the initialization of the Org agenda
  14172. buffers is inhibited: e.g. the visibility state is not set, the
  14173. tables are not re-aligned, etc."
  14174. :type 'boolean
  14175. :version "24.3"
  14176. :group 'org-agenda)
  14177. (defcustom org-agenda-ignore-properties nil
  14178. "Avoid updating text properties when building the agenda.
  14179. Properties are used to prepare buffers for effort estimates,
  14180. appointments, statistics and subtree-local categories.
  14181. If you don't use these in the agenda, you can add them to this
  14182. list and agenda building will be a bit faster.
  14183. The value is a list, with zero or more of the symbols `effort', `appt',
  14184. `stats' or `category'."
  14185. :type '(set :greedy t
  14186. (const effort)
  14187. (const appt)
  14188. (const stats)
  14189. (const category))
  14190. :version "26.1"
  14191. :package-version '(Org . "8.3")
  14192. :group 'org-agenda)
  14193. ;;;; Files
  14194. (defun org-save-all-org-buffers ()
  14195. "Save all Org buffers without user confirmation."
  14196. (interactive)
  14197. (message "Saving all Org buffers...")
  14198. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  14199. (when (featurep 'org-id) (org-id-locations-save))
  14200. (message "Saving all Org buffers... done"))
  14201. (defun org-revert-all-org-buffers ()
  14202. "Revert all Org buffers.
  14203. Prompt for confirmation when there are unsaved changes.
  14204. Be sure you know what you are doing before letting this function
  14205. overwrite your changes.
  14206. This function is useful in a setup where one tracks Org files
  14207. with a version control system, to revert on one machine after pulling
  14208. changes from another. I believe the procedure must be like this:
  14209. 1. \\[org-save-all-org-buffers]
  14210. 2. Pull changes from the other machine, resolve conflicts
  14211. 3. \\[org-revert-all-org-buffers]"
  14212. (interactive)
  14213. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14214. (user-error "Abort"))
  14215. (save-excursion
  14216. (save-window-excursion
  14217. (dolist (b (buffer-list))
  14218. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14219. (with-current-buffer b buffer-file-name))
  14220. (pop-to-buffer-same-window b)
  14221. (revert-buffer t 'no-confirm)))
  14222. (when (and (featurep 'org-id) org-id-track-globally)
  14223. (org-id-locations-load)))))
  14224. ;;;; Agenda files
  14225. ;;;###autoload
  14226. (defun org-switchb (&optional arg)
  14227. "Switch between Org buffers.
  14228. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14229. With `\\[universal-argument] \\[universal-argument]' \
  14230. prefix, restrict available buffers to agenda files."
  14231. (interactive "P")
  14232. (let ((blist (org-buffer-list
  14233. (cond ((equal arg '(4)) 'files)
  14234. ((equal arg '(16)) 'agenda)))))
  14235. (pop-to-buffer-same-window
  14236. (completing-read "Org buffer: "
  14237. (mapcar #'list (mapcar #'buffer-name blist))
  14238. nil t))))
  14239. (defun org-buffer-list (&optional predicate exclude-tmp)
  14240. "Return a list of Org buffers.
  14241. PREDICATE can be `export', `files' or `agenda'.
  14242. export restrict the list to Export buffers.
  14243. files restrict the list to buffers visiting Org files.
  14244. agenda restrict the list to buffers visiting agenda files.
  14245. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14246. (let* ((bfn nil)
  14247. (agenda-files (and (eq predicate 'agenda)
  14248. (mapcar 'file-truename (org-agenda-files t))))
  14249. (filter
  14250. (cond
  14251. ((eq predicate 'files)
  14252. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14253. ((eq predicate 'export)
  14254. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14255. ((eq predicate 'agenda)
  14256. (lambda (b)
  14257. (with-current-buffer b
  14258. (and (derived-mode-p 'org-mode)
  14259. (setq bfn (buffer-file-name b))
  14260. (member (file-truename bfn) agenda-files)))))
  14261. (t (lambda (b) (with-current-buffer b
  14262. (or (derived-mode-p 'org-mode)
  14263. (string-match "\\*Org .*Export"
  14264. (buffer-name b)))))))))
  14265. (delq nil
  14266. (mapcar
  14267. (lambda(b)
  14268. (if (and (funcall filter b)
  14269. (or (not exclude-tmp)
  14270. (not (string-match "tmp" (buffer-name b)))))
  14271. b
  14272. nil))
  14273. (buffer-list)))))
  14274. (defun org-agenda-files (&optional unrestricted archives)
  14275. "Get the list of agenda files.
  14276. Optional UNRESTRICTED means return the full list even if a restriction
  14277. is currently in place.
  14278. When ARCHIVES is t, include all archive files that are really being
  14279. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14280. `org-agenda-archives-mode' is t."
  14281. (let ((files
  14282. (cond
  14283. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14284. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14285. ((listp org-agenda-files) org-agenda-files)
  14286. (t (error "Invalid value of `org-agenda-files'")))))
  14287. (setq files (apply 'append
  14288. (mapcar (lambda (f)
  14289. (if (file-directory-p f)
  14290. (directory-files
  14291. f t org-agenda-file-regexp)
  14292. (list (expand-file-name f org-directory))))
  14293. files)))
  14294. (when org-agenda-skip-unavailable-files
  14295. (setq files (delq nil
  14296. (mapcar (lambda (file)
  14297. (and (file-readable-p file) file))
  14298. files))))
  14299. (when (or (eq archives t)
  14300. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14301. (setq files (org-add-archive-files files)))
  14302. files))
  14303. (defun org-agenda-file-p (&optional file)
  14304. "Return non-nil, if FILE is an agenda file.
  14305. If FILE is omitted, use the file associated with the current
  14306. buffer."
  14307. (let ((fname (or file (buffer-file-name))))
  14308. (and fname
  14309. (member (file-truename fname)
  14310. (mapcar #'file-truename (org-agenda-files t))))))
  14311. (defun org-edit-agenda-file-list ()
  14312. "Edit the list of agenda files.
  14313. Depending on setup, this either uses customize to edit the variable
  14314. `org-agenda-files', or it visits the file that is holding the list. In the
  14315. latter case, the buffer is set up in a way that saving it automatically kills
  14316. the buffer and restores the previous window configuration."
  14317. (interactive)
  14318. (if (stringp org-agenda-files)
  14319. (let ((cw (current-window-configuration)))
  14320. (find-file org-agenda-files)
  14321. (setq-local org-window-configuration cw)
  14322. (add-hook 'after-save-hook
  14323. (lambda ()
  14324. (set-window-configuration
  14325. (prog1 org-window-configuration
  14326. (kill-buffer (current-buffer))))
  14327. (org-install-agenda-files-menu)
  14328. (message "New agenda file list installed"))
  14329. nil 'local)
  14330. (message "%s" (substitute-command-keys
  14331. "Edit list and finish with \\[save-buffer]")))
  14332. (customize-variable 'org-agenda-files)))
  14333. (defun org-store-new-agenda-file-list (list)
  14334. "Set new value for the agenda file list and save it correctly."
  14335. (if (stringp org-agenda-files)
  14336. (let ((fe (org-read-agenda-file-list t)) b u)
  14337. (while (setq b (find-buffer-visiting org-agenda-files))
  14338. (kill-buffer b))
  14339. (with-temp-file org-agenda-files
  14340. (insert
  14341. (mapconcat
  14342. (lambda (f) ;; Keep un-expanded entries.
  14343. (if (setq u (assoc f fe))
  14344. (cdr u)
  14345. f))
  14346. list "\n")
  14347. "\n")))
  14348. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14349. (org-insert-mode-line-in-empty-file nil))
  14350. (setq org-agenda-files list)
  14351. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14352. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14353. "Read the list of agenda files from a file.
  14354. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14355. filenames, used by `org-store-new-agenda-file-list' to write back
  14356. un-expanded file names."
  14357. (when (file-directory-p org-agenda-files)
  14358. (error "`org-agenda-files' cannot be a single directory"))
  14359. (when (stringp org-agenda-files)
  14360. (with-temp-buffer
  14361. (insert-file-contents org-agenda-files)
  14362. (mapcar
  14363. (lambda (f)
  14364. (let ((e (expand-file-name (substitute-in-file-name f)
  14365. org-directory)))
  14366. (if pair-with-expansion
  14367. (cons e f)
  14368. e)))
  14369. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14370. ;;;###autoload
  14371. (defun org-cycle-agenda-files ()
  14372. "Cycle through the files in `org-agenda-files'.
  14373. If the current buffer visits an agenda file, find the next one in the list.
  14374. If the current buffer does not, find the first agenda file."
  14375. (interactive)
  14376. (let* ((fs (or (org-agenda-files t)
  14377. (user-error "No agenda files")))
  14378. (files (copy-sequence fs))
  14379. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14380. file)
  14381. (when tcf
  14382. (while (and (setq file (pop files))
  14383. (not (equal (file-truename file) tcf)))))
  14384. (find-file (car (or files fs)))
  14385. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14386. (defun org-agenda-file-to-front (&optional to-end)
  14387. "Move/add the current file to the top of the agenda file list.
  14388. If the file is not present in the list, it is added to the front. If it is
  14389. present, it is moved there. With optional argument TO-END, add/move to the
  14390. end of the list."
  14391. (interactive "P")
  14392. (let ((org-agenda-skip-unavailable-files nil)
  14393. (file-alist (mapcar (lambda (x)
  14394. (cons (file-truename x) x))
  14395. (org-agenda-files t)))
  14396. (ctf (file-truename
  14397. (or buffer-file-name
  14398. (user-error "Please save the current buffer to a file"))))
  14399. x had)
  14400. (setq x (assoc ctf file-alist) had x)
  14401. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14402. (if to-end
  14403. (setq file-alist (append (delq x file-alist) (list x)))
  14404. (setq file-alist (cons x (delq x file-alist))))
  14405. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14406. (org-install-agenda-files-menu)
  14407. (message "File %s to %s of agenda file list"
  14408. (if had "moved" "added") (if to-end "end" "front"))))
  14409. (defun org-remove-file (&optional file)
  14410. "Remove current file from the list of files in variable `org-agenda-files'.
  14411. These are the files which are being checked for agenda entries.
  14412. Optional argument FILE means use this file instead of the current."
  14413. (interactive)
  14414. (let* ((org-agenda-skip-unavailable-files nil)
  14415. (file (or file buffer-file-name
  14416. (user-error "Current buffer does not visit a file")))
  14417. (true-file (file-truename file))
  14418. (afile (abbreviate-file-name file))
  14419. (files (delq nil (mapcar
  14420. (lambda (x)
  14421. (unless (equal true-file
  14422. (file-truename x))
  14423. x))
  14424. (org-agenda-files t)))))
  14425. (if (not (= (length files) (length (org-agenda-files t))))
  14426. (progn
  14427. (org-store-new-agenda-file-list files)
  14428. (org-install-agenda-files-menu)
  14429. (message "Removed from Org Agenda list: %s" afile))
  14430. (message "File was not in list: %s (not removed)" afile))))
  14431. (defun org-file-menu-entry (file)
  14432. (vector file (list 'find-file file) t))
  14433. (defun org-check-agenda-file (file)
  14434. "Make sure FILE exists. If not, ask user what to do."
  14435. (unless (file-exists-p file)
  14436. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14437. (abbreviate-file-name file))
  14438. (let ((r (downcase (read-char-exclusive))))
  14439. (cond
  14440. ((equal r ?r)
  14441. (org-remove-file file)
  14442. (throw 'nextfile t))
  14443. (t (user-error "Abort"))))))
  14444. (defun org-get-agenda-file-buffer (file)
  14445. "Get an agenda buffer visiting FILE.
  14446. If the buffer needs to be created, add it to the list of buffers
  14447. which might be released later."
  14448. (let ((buf (org-find-base-buffer-visiting file)))
  14449. (if buf
  14450. buf ; just return it
  14451. ;; Make a new buffer and remember it
  14452. (setq buf (find-file-noselect file))
  14453. (when buf (push buf org-agenda-new-buffers))
  14454. buf)))
  14455. (defun org-release-buffers (blist)
  14456. "Release all buffers in list, asking the user for confirmation when needed.
  14457. When a buffer is unmodified, it is just killed. When modified, it is saved
  14458. \(if the user agrees) and then killed."
  14459. (let (file)
  14460. (dolist (buf blist)
  14461. (setq file (buffer-file-name buf))
  14462. (when (and (buffer-modified-p buf)
  14463. file
  14464. (y-or-n-p (format "Save file %s? " file)))
  14465. (with-current-buffer buf (save-buffer)))
  14466. (kill-buffer buf))))
  14467. (defun org-agenda-prepare-buffers (files)
  14468. "Create buffers for all agenda files, protect archived trees and comments."
  14469. (interactive)
  14470. (let ((inhibit-read-only t)
  14471. (org-inhibit-startup org-agenda-inhibit-startup)
  14472. pos)
  14473. (setq org-tag-alist-for-agenda nil
  14474. org-tag-groups-alist-for-agenda nil)
  14475. (save-excursion
  14476. (save-restriction
  14477. (dolist (file files)
  14478. (catch 'nextfile
  14479. (if (bufferp file)
  14480. (set-buffer file)
  14481. (org-check-agenda-file file)
  14482. (set-buffer (org-get-agenda-file-buffer file)))
  14483. (widen)
  14484. (org-set-regexps-and-options 'tags-only)
  14485. (setq pos (point))
  14486. (or (memq 'category org-agenda-ignore-properties)
  14487. (org-refresh-category-properties))
  14488. (or (memq 'stats org-agenda-ignore-properties)
  14489. (org-refresh-stats-properties))
  14490. (or (memq 'effort org-agenda-ignore-properties)
  14491. (unless (org-element--cache-active-p)
  14492. (org-refresh-effort-properties)))
  14493. (or (memq 'appt org-agenda-ignore-properties)
  14494. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14495. (setq org-todo-keywords-for-agenda
  14496. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14497. (setq org-done-keywords-for-agenda
  14498. (append org-done-keywords-for-agenda org-done-keywords))
  14499. (setq org-todo-keyword-alist-for-agenda
  14500. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14501. (setq org-tag-alist-for-agenda
  14502. (org--tag-add-to-alist
  14503. org-tag-alist-for-agenda
  14504. org-current-tag-alist))
  14505. ;; Merge current file's tag groups into global
  14506. ;; `org-tag-groups-alist-for-agenda'.
  14507. (when org-group-tags
  14508. (dolist (alist org-tag-groups-alist)
  14509. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14510. (if old
  14511. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14512. (push alist org-tag-groups-alist-for-agenda)))))
  14513. (goto-char pos)))))
  14514. (setq org-todo-keywords-for-agenda
  14515. (org-uniquify org-todo-keywords-for-agenda))
  14516. (setq org-todo-keyword-alist-for-agenda
  14517. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14518. ;;;; CDLaTeX minor mode
  14519. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14520. "Keymap for the minor `org-cdlatex-mode'.")
  14521. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14522. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14523. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14524. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14525. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14526. (defvar org-cdlatex-texmathp-advice-is-done nil
  14527. "Flag remembering if we have applied the advice to texmathp already.")
  14528. (define-minor-mode org-cdlatex-mode
  14529. "Toggle the minor `org-cdlatex-mode'.
  14530. This mode supports entering LaTeX environment and math in LaTeX fragments
  14531. in Org mode.
  14532. \\{org-cdlatex-mode-map}"
  14533. :lighter " OCDL"
  14534. (when org-cdlatex-mode
  14535. (require 'cdlatex)
  14536. (run-hooks 'cdlatex-mode-hook)
  14537. (cdlatex-compute-tables))
  14538. (unless org-cdlatex-texmathp-advice-is-done
  14539. (setq org-cdlatex-texmathp-advice-is-done t)
  14540. (defadvice texmathp (around org-math-always-on activate)
  14541. "Always return t in Org buffers.
  14542. This is because we want to insert math symbols without dollars even outside
  14543. the LaTeX math segments. If Org mode thinks that point is actually inside
  14544. an embedded LaTeX fragment, let `texmathp' do its job.
  14545. `\\[org-cdlatex-mode-map]'"
  14546. (interactive)
  14547. (let (p)
  14548. (cond
  14549. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14550. ((eq this-command 'cdlatex-math-symbol)
  14551. (setq ad-return-value t
  14552. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14553. (t
  14554. (let ((p (org-inside-LaTeX-fragment-p)))
  14555. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14556. (setq ad-return-value t
  14557. texmathp-why '("Org mode embedded math" . 0))
  14558. (when p ad-do-it)))))))))
  14559. (defun turn-on-org-cdlatex ()
  14560. "Unconditionally turn on `org-cdlatex-mode'."
  14561. (org-cdlatex-mode 1))
  14562. (defun org-try-cdlatex-tab ()
  14563. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14564. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14565. - inside a LaTeX fragment, or
  14566. - after the first word in a line, where an abbreviation expansion could
  14567. insert a LaTeX environment."
  14568. (when org-cdlatex-mode
  14569. (cond
  14570. ;; Before any word on the line: No expansion possible.
  14571. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14572. ;; Just after first word on the line: Expand it. Make sure it
  14573. ;; cannot happen on headlines, though.
  14574. ((save-excursion
  14575. (skip-chars-backward "a-zA-Z0-9*")
  14576. (skip-chars-backward " \t")
  14577. (and (bolp) (not (org-at-heading-p))))
  14578. (cdlatex-tab) t)
  14579. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14580. (defun org-cdlatex-underscore-caret (&optional _arg)
  14581. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14582. Revert to the normal definition outside of these fragments."
  14583. (interactive "P")
  14584. (if (org-inside-LaTeX-fragment-p)
  14585. (call-interactively 'cdlatex-sub-superscript)
  14586. (let (org-cdlatex-mode)
  14587. (call-interactively (key-binding (vector last-input-event))))))
  14588. (defun org-cdlatex-math-modify (&optional _arg)
  14589. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14590. Revert to the normal definition outside of these fragments."
  14591. (interactive "P")
  14592. (if (org-inside-LaTeX-fragment-p)
  14593. (call-interactively 'cdlatex-math-modify)
  14594. (let (org-cdlatex-mode)
  14595. (call-interactively (key-binding (vector last-input-event))))))
  14596. (defun org-cdlatex-environment-indent (&optional environment item)
  14597. "Execute `cdlatex-environment' and indent the inserted environment.
  14598. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14599. The inserted environment is indented to current indentation
  14600. unless point is at the beginning of the line, in which the
  14601. environment remains unintended."
  14602. (interactive)
  14603. ;; cdlatex-environment always return nil. Therefore, capture output
  14604. ;; first and determine if an environment was selected.
  14605. (let* ((beg (point-marker))
  14606. (end (copy-marker (point) t))
  14607. (inserted (progn
  14608. (ignore-errors (cdlatex-environment environment item))
  14609. (< beg end)))
  14610. ;; Figure out how many lines to move forward after the
  14611. ;; environment has been inserted.
  14612. (lines (when inserted
  14613. (save-excursion
  14614. (- (cl-loop while (< beg (point))
  14615. with x = 0
  14616. do (forward-line -1)
  14617. (cl-incf x)
  14618. finally return x)
  14619. (if (progn (goto-char beg)
  14620. (and (progn (skip-chars-forward " \t") (eolp))
  14621. (progn (skip-chars-backward " \t") (bolp))))
  14622. 1 0)))))
  14623. (env (org-trim (delete-and-extract-region beg end))))
  14624. (when inserted
  14625. ;; Get indentation of next line unless at column 0.
  14626. (let ((ind (if (bolp) 0
  14627. (save-excursion
  14628. (org-return t)
  14629. (prog1 (current-indentation)
  14630. (when (progn (skip-chars-forward " \t") (eolp))
  14631. (delete-region beg (point)))))))
  14632. (bol (progn (skip-chars-backward " \t") (bolp))))
  14633. ;; Insert a newline before environment unless at column zero
  14634. ;; to "escape" the current line. Insert a newline if
  14635. ;; something is one the same line as \end{ENVIRONMENT}.
  14636. (insert
  14637. (concat (unless bol "\n") env
  14638. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14639. (unless (zerop ind)
  14640. (save-excursion
  14641. (goto-char beg)
  14642. (while (< (point) end)
  14643. (unless (eolp) (indent-line-to ind))
  14644. (forward-line))))
  14645. (goto-char beg)
  14646. (forward-line lines)
  14647. (indent-line-to ind)))
  14648. (set-marker beg nil)
  14649. (set-marker end nil)))
  14650. ;;;; LaTeX fragments
  14651. (defun org-inside-LaTeX-fragment-p ()
  14652. "Test if point is inside a LaTeX fragment.
  14653. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14654. sequence appearing also before point.
  14655. Even though the matchers for math are configurable, this function assumes
  14656. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14657. delimiters are skipped when they have been removed by customization.
  14658. The return value is nil, or a cons cell with the delimiter and the
  14659. position of this delimiter.
  14660. This function does a reasonably good job, but can locally be fooled by
  14661. for example currency specifications. For example it will assume being in
  14662. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14663. fragments that are properly closed, but during editing, we have to live
  14664. with the uncertainty caused by missing closing delimiters. This function
  14665. looks only before point, not after."
  14666. (catch 'exit
  14667. (let ((pos (point))
  14668. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14669. (lim (progn
  14670. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14671. 'move)
  14672. (point)))
  14673. dd-on str (start 0) m re)
  14674. (goto-char pos)
  14675. (when dodollar
  14676. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14677. re (nth 1 (assoc "$" org-latex-regexps)))
  14678. (while (string-match re str start)
  14679. (cond
  14680. ((= (match-end 0) (length str))
  14681. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14682. ((= (match-end 0) (- (length str) 5))
  14683. (throw 'exit nil))
  14684. (t (setq start (match-end 0))))))
  14685. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14686. (goto-char pos)
  14687. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14688. (and (match-beginning 2) (throw 'exit nil))
  14689. ;; count $$
  14690. (while (re-search-backward "\\$\\$" lim t)
  14691. (setq dd-on (not dd-on)))
  14692. (goto-char pos)
  14693. (when dd-on (cons "$$" m))))))
  14694. (defun org-inside-latex-macro-p ()
  14695. "Is point inside a LaTeX macro or its arguments?"
  14696. (save-match-data
  14697. (org-in-regexp
  14698. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14699. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14700. "Build an overlay between BEG and END using IMAGE file.
  14701. Argument IMAGETYPE is the extension of the displayed image,
  14702. as a string. It defaults to \"png\"."
  14703. (let ((ov (make-overlay beg end))
  14704. (imagetype (or (intern imagetype) 'png)))
  14705. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14706. (overlay-put ov 'evaporate t)
  14707. (overlay-put ov
  14708. 'modification-hooks
  14709. (list (lambda (o _flag _beg _end &optional _l)
  14710. (delete-overlay o))))
  14711. (overlay-put ov
  14712. 'display
  14713. (list 'image :type imagetype :file image :ascent 'center))))
  14714. (defun org-clear-latex-preview (&optional beg end)
  14715. "Remove all overlays with LaTeX fragment images in current buffer.
  14716. When optional arguments BEG and END are non-nil, remove all
  14717. overlays between them instead. Return a non-nil value when some
  14718. overlays were removed, nil otherwise."
  14719. (let ((overlays
  14720. (cl-remove-if-not
  14721. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14722. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14723. (mapc #'delete-overlay overlays)
  14724. overlays))
  14725. (defun org--latex-preview-region (beg end)
  14726. "Preview LaTeX fragments between BEG and END.
  14727. BEG and END are buffer positions."
  14728. (let ((file (buffer-file-name (buffer-base-buffer))))
  14729. (save-excursion
  14730. (org-format-latex
  14731. (concat org-preview-latex-image-directory "org-ltximg")
  14732. beg end
  14733. ;; Emacs cannot overlay images from remote hosts. Create it in
  14734. ;; `temporary-file-directory' instead.
  14735. (if (or (not file) (file-remote-p file))
  14736. temporary-file-directory
  14737. default-directory)
  14738. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14739. (defun org-latex-preview (&optional arg)
  14740. "Toggle preview of the LaTeX fragment at point.
  14741. If the cursor is on a LaTeX fragment, create the image and
  14742. overlay it over the source code, if there is none. Remove it
  14743. otherwise. If there is no fragment at point, display images for
  14744. all fragments in the current section.
  14745. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14746. for all fragments
  14747. in the current section.
  14748. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14749. argument ARG, display image for all
  14750. fragments in the buffer.
  14751. With a `\\[universal-argument] \\[universal-argument] \
  14752. \\[universal-argument]' prefix argument ARG, clear image for all
  14753. fragments in the buffer."
  14754. (interactive "P")
  14755. (cond
  14756. ((not (display-graphic-p)) nil)
  14757. ;; Clear whole buffer.
  14758. ((equal arg '(64))
  14759. (org-clear-latex-preview (point-min) (point-max))
  14760. (message "LaTeX previews removed from buffer"))
  14761. ;; Preview whole buffer.
  14762. ((equal arg '(16))
  14763. (message "Creating LaTeX previews in buffer...")
  14764. (org--latex-preview-region (point-min) (point-max))
  14765. (message "Creating LaTeX previews in buffer... done."))
  14766. ;; Clear current section.
  14767. ((equal arg '(4))
  14768. (org-clear-latex-preview
  14769. (if (org-before-first-heading-p) (point-min)
  14770. (save-excursion
  14771. (org-with-limited-levels (org-back-to-heading t) (point))))
  14772. (org-with-limited-levels (org-entry-end-position))))
  14773. ;; Toggle preview on LaTeX code at point.
  14774. ((let ((datum (org-element-context)))
  14775. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14776. (let ((beg (org-element-property :begin datum))
  14777. (end (org-element-property :end datum)))
  14778. (if (org-clear-latex-preview beg end)
  14779. (message "LaTeX preview removed")
  14780. (message "Creating LaTeX preview...")
  14781. (org--latex-preview-region beg end)
  14782. (message "Creating LaTeX preview... done."))
  14783. t))))
  14784. ;; Preview current section.
  14785. (t
  14786. (let ((beg (if (org-before-first-heading-p) (point-min)
  14787. (save-excursion
  14788. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14789. (end (org-with-limited-levels (org-entry-end-position))))
  14790. (message "Creating LaTeX previews in section...")
  14791. (org--latex-preview-region beg end)
  14792. (message "Creating LaTeX previews in section... done.")))))
  14793. (defun org-format-latex
  14794. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14795. "Replace LaTeX fragments with links to an image.
  14796. The function takes care of creating the replacement image.
  14797. Only consider fragments between BEG and END when those are
  14798. provided.
  14799. When optional argument OVERLAYS is non-nil, display the image on
  14800. top of the fragment instead of replacing it.
  14801. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14802. Some of the options can be changed using the variable
  14803. `org-format-latex-options', which see."
  14804. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14805. (unless (eq processing-type 'verbatim)
  14806. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14807. (cnt 0)
  14808. checkdir-flag)
  14809. (goto-char (or beg (point-min)))
  14810. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14811. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14812. (overlay-recenter (or end (point-max))))
  14813. (while (re-search-forward math-regexp end t)
  14814. (unless (and overlays
  14815. (eq (get-char-property (point) 'org-overlay-type)
  14816. 'org-latex-overlay))
  14817. (let* ((context (org-element-context))
  14818. (type (org-element-type context)))
  14819. (when (memq type '(latex-environment latex-fragment))
  14820. (let ((block-type (eq type 'latex-environment))
  14821. (value (org-element-property :value context))
  14822. (beg (org-element-property :begin context))
  14823. (end (save-excursion
  14824. (goto-char (org-element-property :end context))
  14825. (skip-chars-backward " \r\t\n")
  14826. (point))))
  14827. (cond
  14828. ((eq processing-type 'mathjax)
  14829. ;; Prepare for MathJax processing.
  14830. (if (not (string-match "\\`\\$\\$?" value))
  14831. (goto-char end)
  14832. (delete-region beg end)
  14833. (if (string= (match-string 0 value) "$$")
  14834. (insert "\\[" (substring value 2 -2) "\\]")
  14835. (insert "\\(" (substring value 1 -1) "\\)"))))
  14836. ((eq processing-type 'html)
  14837. (goto-char beg)
  14838. (delete-region beg end)
  14839. (insert (org-format-latex-as-html value)))
  14840. ((assq processing-type org-preview-latex-process-alist)
  14841. ;; Process to an image.
  14842. (cl-incf cnt)
  14843. (goto-char beg)
  14844. (let* ((processing-info
  14845. (cdr (assq processing-type org-preview-latex-process-alist)))
  14846. (face (face-at-point))
  14847. ;; Get the colors from the face at point.
  14848. (fg
  14849. (let ((color (plist-get org-format-latex-options
  14850. :foreground)))
  14851. (if forbuffer
  14852. (cond
  14853. ((eq color 'auto)
  14854. (face-attribute face :foreground nil 'default))
  14855. ((eq color 'default)
  14856. (face-attribute 'default :foreground nil))
  14857. (t color))
  14858. color)))
  14859. (bg
  14860. (let ((color (plist-get org-format-latex-options
  14861. :background)))
  14862. (if forbuffer
  14863. (cond
  14864. ((eq color 'auto)
  14865. (face-attribute face :background nil 'default))
  14866. ((eq color 'default)
  14867. (face-attribute 'default :background nil))
  14868. (t color))
  14869. color)))
  14870. (hash (sha1 (prin1-to-string
  14871. (list org-format-latex-header
  14872. org-latex-default-packages-alist
  14873. org-latex-packages-alist
  14874. org-format-latex-options
  14875. forbuffer value fg bg))))
  14876. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14877. (absprefix (expand-file-name prefix dir))
  14878. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14879. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14880. (sep (and block-type "\n\n"))
  14881. (link (concat sep "[[file:" linkfile "]]" sep))
  14882. (options
  14883. (org-combine-plists
  14884. org-format-latex-options
  14885. `(:foreground ,fg :background ,bg))))
  14886. (when msg (message msg cnt))
  14887. (unless checkdir-flag ; Ensure the directory exists.
  14888. (setq checkdir-flag t)
  14889. (let ((todir (file-name-directory absprefix)))
  14890. (unless (file-directory-p todir)
  14891. (make-directory todir t))))
  14892. (unless (file-exists-p movefile)
  14893. (org-create-formula-image
  14894. value movefile options forbuffer processing-type))
  14895. (if overlays
  14896. (progn
  14897. (dolist (o (overlays-in beg end))
  14898. (when (eq (overlay-get o 'org-overlay-type)
  14899. 'org-latex-overlay)
  14900. (delete-overlay o)))
  14901. (org--make-preview-overlay beg end movefile imagetype)
  14902. (goto-char end))
  14903. (delete-region beg end)
  14904. (insert
  14905. (org-add-props link
  14906. (list 'org-latex-src
  14907. (replace-regexp-in-string "\"" "" value)
  14908. 'org-latex-src-embed-type
  14909. (if block-type 'paragraph 'character)))))))
  14910. ((eq processing-type 'mathml)
  14911. ;; Process to MathML.
  14912. (unless (org-format-latex-mathml-available-p)
  14913. (user-error "LaTeX to MathML converter not configured"))
  14914. (cl-incf cnt)
  14915. (when msg (message msg cnt))
  14916. (goto-char beg)
  14917. (delete-region beg end)
  14918. (insert (org-format-latex-as-mathml
  14919. value block-type prefix dir)))
  14920. (t
  14921. (error "Unknown conversion process %s for LaTeX fragments"
  14922. processing-type)))))))))))
  14923. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14924. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14925. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14926. successful, return the portion between \"<math...> </math>\"
  14927. elements otherwise return nil. When MATHML-FILE is specified,
  14928. write the results in to that file. When invoked as an
  14929. interactive command, prompt for LATEX-FRAG, with initial value
  14930. set to the current active region and echo the results for user
  14931. inspection."
  14932. (interactive (list (let ((frag (when (org-region-active-p)
  14933. (buffer-substring-no-properties
  14934. (region-beginning) (region-end)))))
  14935. (read-string "LaTeX Fragment: " frag nil frag))))
  14936. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14937. (let* ((tmp-in-file
  14938. (let ((file (file-relative-name
  14939. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14940. (write-region latex-frag nil file)
  14941. file))
  14942. (tmp-out-file (file-relative-name
  14943. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14944. (cmd (format-spec
  14945. org-latex-to-mathml-convert-command
  14946. `((?j . ,(and org-latex-to-mathml-jar-file
  14947. (shell-quote-argument
  14948. (expand-file-name
  14949. org-latex-to-mathml-jar-file))))
  14950. (?I . ,(shell-quote-argument tmp-in-file))
  14951. (?i . ,latex-frag)
  14952. (?o . ,(shell-quote-argument tmp-out-file)))))
  14953. mathml shell-command-output)
  14954. (when (called-interactively-p 'any)
  14955. (unless (org-format-latex-mathml-available-p)
  14956. (user-error "LaTeX to MathML converter not configured")))
  14957. (message "Running %s" cmd)
  14958. (setq shell-command-output (shell-command-to-string cmd))
  14959. (setq mathml
  14960. (when (file-readable-p tmp-out-file)
  14961. (with-current-buffer (find-file-noselect tmp-out-file t)
  14962. (goto-char (point-min))
  14963. (when (re-search-forward
  14964. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14965. (regexp-quote
  14966. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14967. nil t)
  14968. (prog1 (match-string 0) (kill-buffer))))))
  14969. (cond
  14970. (mathml
  14971. (setq mathml
  14972. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14973. (when mathml-file
  14974. (write-region mathml nil mathml-file))
  14975. (when (called-interactively-p 'any)
  14976. (message mathml)))
  14977. ((warn "LaTeX to MathML conversion failed")
  14978. (message shell-command-output)))
  14979. (delete-file tmp-in-file)
  14980. (when (file-exists-p tmp-out-file)
  14981. (delete-file tmp-out-file))
  14982. mathml))
  14983. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14984. prefix &optional dir)
  14985. "Use `org-create-math-formula' but check local cache first."
  14986. (let* ((absprefix (expand-file-name prefix dir))
  14987. (print-length nil) (print-level nil)
  14988. (formula-id (concat
  14989. "formula-"
  14990. (sha1
  14991. (prin1-to-string
  14992. (list latex-frag
  14993. org-latex-to-mathml-convert-command)))))
  14994. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14995. (formula-cache-dir (file-name-directory formula-cache)))
  14996. (unless (file-directory-p formula-cache-dir)
  14997. (make-directory formula-cache-dir t))
  14998. (unless (file-exists-p formula-cache)
  14999. (org-create-math-formula latex-frag formula-cache))
  15000. (if (file-exists-p formula-cache)
  15001. ;; Successful conversion. Return the link to MathML file.
  15002. (org-add-props
  15003. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  15004. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  15005. 'org-latex-src-embed-type (if latex-frag-type
  15006. 'paragraph 'character)))
  15007. ;; Failed conversion. Return the LaTeX fragment verbatim
  15008. latex-frag)))
  15009. (defun org-format-latex-as-html (latex-fragment)
  15010. "Convert LATEX-FRAGMENT to HTML.
  15011. This uses `org-latex-to-html-convert-command', which see."
  15012. (let ((cmd (format-spec org-latex-to-html-convert-command
  15013. `((?i . ,latex-fragment)))))
  15014. (message "Running %s" cmd)
  15015. (shell-command-to-string cmd)))
  15016. (defun org--get-display-dpi ()
  15017. "Get the DPI of the display.
  15018. The function assumes that the display has the same pixel width in
  15019. the horizontal and vertical directions."
  15020. (if (display-graphic-p)
  15021. (round (/ (display-pixel-height)
  15022. (/ (display-mm-height) 25.4)))
  15023. (error "Attempt to calculate the dpi of a non-graphic display")))
  15024. (defun org-create-formula-image
  15025. (string tofile options buffer &optional processing-type)
  15026. "Create an image from LaTeX source using external processes.
  15027. The LaTeX STRING is saved to a temporary LaTeX file, then
  15028. converted to an image file by process PROCESSING-TYPE defined in
  15029. `org-preview-latex-process-alist'. A nil value defaults to
  15030. `org-preview-latex-default-process'.
  15031. The generated image file is eventually moved to TOFILE.
  15032. The OPTIONS argument controls the size, foreground color and
  15033. background color of the generated image.
  15034. When BUFFER non-nil, this function is used for LaTeX previewing.
  15035. Otherwise, it is used to deal with LaTeX snippets showed in
  15036. a HTML file."
  15037. (let* ((processing-type (or processing-type
  15038. org-preview-latex-default-process))
  15039. (processing-info
  15040. (cdr (assq processing-type org-preview-latex-process-alist)))
  15041. (programs (plist-get processing-info :programs))
  15042. (error-message (or (plist-get processing-info :message) ""))
  15043. (image-input-type (plist-get processing-info :image-input-type))
  15044. (image-output-type (plist-get processing-info :image-output-type))
  15045. (post-clean (or (plist-get processing-info :post-clean)
  15046. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15047. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15048. (latex-header
  15049. (or (plist-get processing-info :latex-header)
  15050. (org-latex-make-preamble
  15051. (org-export-get-environment (org-export-get-backend 'latex))
  15052. org-format-latex-header
  15053. 'snippet)))
  15054. (latex-compiler (plist-get processing-info :latex-compiler))
  15055. (tmpdir temporary-file-directory)
  15056. (texfilebase (make-temp-name
  15057. (expand-file-name "orgtex" tmpdir)))
  15058. (texfile (concat texfilebase ".tex"))
  15059. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  15060. '(1.0 . 1.0)))
  15061. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  15062. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  15063. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  15064. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  15065. "Black"))
  15066. (bg (or (plist-get options (if buffer :background :html-background))
  15067. "Transparent"))
  15068. (image-converter
  15069. (or (and (string= bg "Transparent")
  15070. (plist-get processing-info :transparent-image-converter))
  15071. (plist-get processing-info :image-converter)))
  15072. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  15073. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  15074. (dolist (program programs)
  15075. (org-check-external-command program error-message))
  15076. (if (eq fg 'default)
  15077. (setq fg (org-latex-color :foreground))
  15078. (setq fg (org-latex-color-format fg)))
  15079. (setq bg (cond
  15080. ((eq bg 'default) (org-latex-color :background))
  15081. ((string= bg "Transparent") nil)
  15082. (t (org-latex-color-format bg))))
  15083. ;; Remove TeX \par at end of snippet to avoid trailing space.
  15084. (if (string-suffix-p string "\n")
  15085. (aset string (1- (length string)) ?%)
  15086. (setq string (concat string "%")))
  15087. (with-temp-file texfile
  15088. (insert latex-header)
  15089. (insert "\n\\begin{document}\n"
  15090. "\\definecolor{fg}{rgb}{" fg "}%\n"
  15091. (if bg
  15092. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  15093. "\n\\pagecolor{bg}%\n")
  15094. "")
  15095. "\n{\\color{fg}\n"
  15096. string
  15097. "\n}\n"
  15098. "\n\\end{document}\n"))
  15099. (let* ((err-msg (format "Please adjust `%s' part of \
  15100. `org-preview-latex-process-alist'."
  15101. processing-type))
  15102. (image-input-file
  15103. (org-compile-file
  15104. texfile latex-compiler image-input-type err-msg log-buf))
  15105. (image-output-file
  15106. (org-compile-file
  15107. image-input-file image-converter image-output-type err-msg log-buf
  15108. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  15109. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  15110. (copy-file image-output-file tofile 'replace)
  15111. (dolist (e post-clean)
  15112. (when (file-exists-p (concat texfilebase e))
  15113. (delete-file (concat texfilebase e))))
  15114. image-output-file)))
  15115. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  15116. "Fill a LaTeX header template TPL.
  15117. In the template, the following place holders will be recognized:
  15118. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  15119. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  15120. [PACKAGES] \\usepackage statements for PKG
  15121. [NO-PACKAGES] do not include PKG
  15122. [EXTRA] the string EXTRA
  15123. [NO-EXTRA] do not include EXTRA
  15124. For backward compatibility, if both the positive and the negative place
  15125. holder is missing, the positive one (without the \"NO-\") will be
  15126. assumed to be present at the end of the template.
  15127. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  15128. EXTRA is a string.
  15129. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  15130. (let (rpl (end ""))
  15131. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  15132. (setq rpl (if (or (match-end 1) (not def-pkg))
  15133. "" (org-latex-packages-to-string def-pkg snippets-p t))
  15134. tpl (replace-match rpl t t tpl))
  15135. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  15136. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  15137. (setq rpl (if (or (match-end 1) (not pkg))
  15138. "" (org-latex-packages-to-string pkg snippets-p t))
  15139. tpl (replace-match rpl t t tpl))
  15140. (when pkg (setq end
  15141. (concat end "\n"
  15142. (org-latex-packages-to-string pkg snippets-p)))))
  15143. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  15144. (setq rpl (if (or (match-end 1) (not extra))
  15145. "" (concat extra "\n"))
  15146. tpl (replace-match rpl t t tpl))
  15147. (when (and extra (string-match "\\S-" extra))
  15148. (setq end (concat end "\n" extra))))
  15149. (if (string-match "\\S-" end)
  15150. (concat tpl "\n" end)
  15151. tpl)))
  15152. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  15153. "Turn an alist of packages into a string with the \\usepackage macros."
  15154. (setq pkg (mapconcat (lambda(p)
  15155. (cond
  15156. ((stringp p) p)
  15157. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  15158. (format "%% Package %s omitted" (cadr p)))
  15159. ((equal "" (car p))
  15160. (format "\\usepackage{%s}" (cadr p)))
  15161. (t
  15162. (format "\\usepackage[%s]{%s}"
  15163. (car p) (cadr p)))))
  15164. pkg
  15165. "\n"))
  15166. (if newline (concat pkg "\n") pkg))
  15167. (defun org-dvipng-color (attr)
  15168. "Return a RGB color specification for dvipng."
  15169. (org-dvipng-color-format (face-attribute 'default attr nil)))
  15170. (defun org-dvipng-color-format (color-name)
  15171. "Convert COLOR-NAME to a RGB color value for dvipng."
  15172. (apply #'format "rgb %s %s %s"
  15173. (mapcar 'org-normalize-color
  15174. (color-values color-name))))
  15175. (defun org-latex-color (attr)
  15176. "Return a RGB color for the LaTeX color package."
  15177. (org-latex-color-format (face-attribute 'default attr nil)))
  15178. (defun org-latex-color-format (color-name)
  15179. "Convert COLOR-NAME to a RGB color value."
  15180. (apply #'format "%s,%s,%s"
  15181. (mapcar 'org-normalize-color
  15182. (color-values color-name))))
  15183. (defun org-normalize-color (value)
  15184. "Return string to be used as color value for an RGB component."
  15185. (format "%g" (/ value 65535.0)))
  15186. ;; Image display
  15187. (defvar-local org-inline-image-overlays nil)
  15188. (defun org-toggle-inline-images (&optional include-linked)
  15189. "Toggle the display of inline images.
  15190. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15191. (interactive "P")
  15192. (if org-inline-image-overlays
  15193. (progn
  15194. (org-remove-inline-images)
  15195. (when (called-interactively-p 'interactive)
  15196. (message "Inline image display turned off")))
  15197. (org-display-inline-images include-linked)
  15198. (when (called-interactively-p 'interactive)
  15199. (message (if org-inline-image-overlays
  15200. (format "%d images displayed inline"
  15201. (length org-inline-image-overlays))
  15202. "No images to display inline")))))
  15203. (defun org-redisplay-inline-images ()
  15204. "Assure display of inline images and refresh them."
  15205. (interactive)
  15206. (org-toggle-inline-images)
  15207. (unless org-inline-image-overlays
  15208. (org-toggle-inline-images)))
  15209. ;; For without-x builds.
  15210. (declare-function image-refresh "image" (spec &optional frame))
  15211. (defcustom org-display-remote-inline-images 'skip
  15212. "How to display remote inline images.
  15213. Possible values of this option are:
  15214. skip Don't display remote images.
  15215. download Always download and display remote images.
  15216. cache Display remote images, and open them in separate buffers
  15217. for caching. Silently update the image buffer when a file
  15218. change is detected."
  15219. :group 'org-appearance
  15220. :package-version '(Org . "9.4")
  15221. :type '(choice
  15222. (const :tag "Ignore remote images" skip)
  15223. (const :tag "Always display remote images" download)
  15224. (const :tag "Display and silently update remote images" cache))
  15225. :safe #'symbolp)
  15226. (defun org--create-inline-image (file width)
  15227. "Create image located at FILE, or return nil.
  15228. WIDTH is the width of the image. The image may not be created
  15229. according to the value of `org-display-remote-inline-images'."
  15230. (let* ((remote? (file-remote-p file))
  15231. (file-or-data
  15232. (pcase org-display-remote-inline-images
  15233. ((guard (not remote?)) file)
  15234. (`download (with-temp-buffer
  15235. (set-buffer-multibyte nil)
  15236. (insert-file-contents-literally file)
  15237. (buffer-string)))
  15238. (`cache (let ((revert-without-query '(".")))
  15239. (with-current-buffer (find-file-noselect file)
  15240. (buffer-string))))
  15241. (`skip nil)
  15242. (other
  15243. (message "Invalid value of `org-display-remote-inline-images': %S"
  15244. other)
  15245. nil))))
  15246. (when file-or-data
  15247. (create-image file-or-data
  15248. (and (image-type-available-p 'imagemagick)
  15249. width
  15250. 'imagemagick)
  15251. remote?
  15252. :width width :scale 1))))
  15253. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15254. "Display inline images.
  15255. An inline image is a link which follows either of these
  15256. conventions:
  15257. 1. Its path is a file with an extension matching return value
  15258. from `image-file-name-regexp' and it has no contents.
  15259. 2. Its description consists in a single link of the previous
  15260. type. In this case, that link must be a well-formed plain
  15261. or angle link, i.e., it must have an explicit \"file\" type.
  15262. Equip each image with the key-map `image-map'.
  15263. When optional argument INCLUDE-LINKED is non-nil, also links with
  15264. a text description part will be inlined. This can be nice for
  15265. a quick look at those images, but it does not reflect what
  15266. exported files will look like.
  15267. When optional argument REFRESH is non-nil, refresh existing
  15268. images between BEG and END. This will create new image displays
  15269. only if necessary.
  15270. BEG and END define the considered part. They default to the
  15271. buffer boundaries with possible narrowing."
  15272. (interactive "P")
  15273. (when (display-graphic-p)
  15274. (unless refresh
  15275. (org-remove-inline-images)
  15276. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15277. (let ((end (or end (point-max))))
  15278. (org-with-point-at (or beg (point-min))
  15279. (let* ((case-fold-search t)
  15280. (file-extension-re (image-file-name-regexp))
  15281. (link-abbrevs (mapcar #'car
  15282. (append org-link-abbrev-alist-local
  15283. org-link-abbrev-alist)))
  15284. ;; Check absolute, relative file names and explicit
  15285. ;; "file:" links. Also check link abbreviations since
  15286. ;; some might expand to "file" links.
  15287. (file-types-re
  15288. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15289. (if (not link-abbrevs) ""
  15290. (concat "\\|" (regexp-opt link-abbrevs))))))
  15291. (while (re-search-forward file-types-re end t)
  15292. (let* ((link (org-element-lineage
  15293. (save-match-data (org-element-context))
  15294. '(link) t))
  15295. (linktype (org-element-property :type link))
  15296. (inner-start (match-beginning 1))
  15297. (path
  15298. (cond
  15299. ;; No link at point; no inline image.
  15300. ((not link) nil)
  15301. ;; File link without a description. Also handle
  15302. ;; INCLUDE-LINKED here since it should have
  15303. ;; precedence over the next case. I.e., if link
  15304. ;; contains filenames in both the path and the
  15305. ;; description, prioritize the path only when
  15306. ;; INCLUDE-LINKED is non-nil.
  15307. ((or (not (org-element-property :contents-begin link))
  15308. include-linked)
  15309. (and (or (equal "file" linktype)
  15310. (equal "attachment" linktype))
  15311. (org-element-property :path link)))
  15312. ;; Link with a description. Check if description
  15313. ;; is a filename. Even if Org doesn't have syntax
  15314. ;; for those -- clickable image -- constructs, fake
  15315. ;; them, as in `org-export-insert-image-links'.
  15316. ((not inner-start) nil)
  15317. (t
  15318. (org-with-point-at inner-start
  15319. (and (looking-at
  15320. (if (char-equal ?< (char-after inner-start))
  15321. org-link-angle-re
  15322. org-link-plain-re))
  15323. ;; File name must fill the whole
  15324. ;; description.
  15325. (= (org-element-property :contents-end link)
  15326. (match-end 0))
  15327. (match-string 2)))))))
  15328. (when (and path (string-match-p file-extension-re path))
  15329. (let ((file (if (equal "attachment" linktype)
  15330. (progn
  15331. (require 'org-attach)
  15332. (ignore-errors (org-attach-expand path)))
  15333. (expand-file-name path))))
  15334. (when (and file (file-exists-p file))
  15335. (let ((width (org-display-inline-image--width link))
  15336. (old (get-char-property-and-overlay
  15337. (org-element-property :begin link)
  15338. 'org-image-overlay)))
  15339. (if (and (car-safe old) refresh)
  15340. (image-refresh (overlay-get (cdr old) 'display))
  15341. (let ((image (org--create-inline-image file width)))
  15342. (when image
  15343. (let ((ov (make-overlay
  15344. (org-element-property :begin link)
  15345. (progn
  15346. (goto-char
  15347. (org-element-property :end link))
  15348. (skip-chars-backward " \t")
  15349. (point)))))
  15350. (overlay-put ov 'display image)
  15351. (overlay-put ov 'face 'default)
  15352. (overlay-put ov 'org-image-overlay t)
  15353. (overlay-put
  15354. ov 'modification-hooks
  15355. (list 'org-display-inline-remove-overlay))
  15356. (when (boundp 'image-map)
  15357. (overlay-put ov 'keymap image-map))
  15358. (push ov org-inline-image-overlays))))))))))))))))
  15359. (defvar visual-fill-column-width) ; Silence compiler warning
  15360. (defun org-display-inline-image--width (link)
  15361. "Determine the display width of the image LINK, in pixels.
  15362. - When `org-image-actual-width' is t, the image's pixel width is used.
  15363. - When `org-image-actual-width' is a number, that value will is used.
  15364. - When `org-image-actual-width' is nil or a list, the first :width attribute
  15365. set (if it exists) is used to set the image width. A width of X% is
  15366. divided by 100.
  15367. If no :width attribute is given and `org-image-actual-width' is a list with
  15368. a number as the car, then that number is used as the default value.
  15369. If the value is a float between 0 and 2, it interpreted as that proportion
  15370. of the text width in the buffer."
  15371. ;; Apply `org-image-actual-width' specifications.
  15372. (cond
  15373. ((eq org-image-actual-width t) nil)
  15374. ((listp org-image-actual-width)
  15375. (let* ((case-fold-search t)
  15376. (par (org-element-lineage link '(paragraph)))
  15377. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  15378. (par-end (org-element-property :post-affiliated par))
  15379. ;; Try to find an attribute providing a :width.
  15380. (attr-width
  15381. (when (and par (org-with-point-at
  15382. (org-element-property :begin par)
  15383. (re-search-forward attr-re par-end t)))
  15384. (match-string 1)))
  15385. (attr-width-val
  15386. (cond
  15387. ((null attr-width) nil)
  15388. ((string-match-p "\\`[0-9.]+%" attr-width)
  15389. (/ (string-to-number attr-width) 100.0))
  15390. (t (string-to-number attr-width))))
  15391. ;; Fallback to `org-image-actual-width' if no explicit width is given.
  15392. (width (or attr-width-val (car org-image-actual-width))))
  15393. (if (and (floatp width) (<= 0.0 width 2.0))
  15394. ;; A float in [0,2] should be interpereted as this portion of
  15395. ;; the text width in the window. This works well with cases like
  15396. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  15397. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  15398. ;; bound as cases such as 1.2\linewidth are feasible.
  15399. (round (* width
  15400. (window-pixel-width)
  15401. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  15402. (or visual-fill-column-width auto-fill-function))
  15403. (when auto-fill-function fill-column)
  15404. (- (window-text-width) (or display-line-numbers-width 0)))
  15405. (float (window-total-width)))))
  15406. width)))
  15407. ((numberp org-image-actual-width)
  15408. org-image-actual-width)
  15409. (t nil)))
  15410. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15411. "Remove inline-display overlay if a corresponding region is modified."
  15412. (let ((inhibit-modification-hooks t))
  15413. (when (and ov after)
  15414. (delete ov org-inline-image-overlays)
  15415. (delete-overlay ov))))
  15416. (defun org-remove-inline-images ()
  15417. "Remove inline display of images."
  15418. (interactive)
  15419. (mapc #'delete-overlay org-inline-image-overlays)
  15420. (setq org-inline-image-overlays nil))
  15421. (defvar org-self-insert-command-undo-counter 0)
  15422. (defvar org-speed-command nil)
  15423. (defun org-self-insert-command (N)
  15424. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15425. If the cursor is in a table looking at whitespace, the whitespace is
  15426. overwritten, and the table is not marked as requiring realignment."
  15427. (interactive "p")
  15428. (org-check-before-invisible-edit 'insert)
  15429. (cond
  15430. ((and org-use-speed-commands
  15431. (let ((kv (this-command-keys-vector)))
  15432. (setq org-speed-command
  15433. (run-hook-with-args-until-success
  15434. 'org-speed-command-hook
  15435. (make-string 1 (aref kv (1- (length kv))))))))
  15436. (cond
  15437. ((commandp org-speed-command)
  15438. (setq this-command org-speed-command)
  15439. (call-interactively org-speed-command))
  15440. ((functionp org-speed-command)
  15441. (funcall org-speed-command))
  15442. ((and org-speed-command (listp org-speed-command))
  15443. (eval org-speed-command))
  15444. (t (let (org-use-speed-commands)
  15445. (call-interactively 'org-self-insert-command)))))
  15446. ((and
  15447. (= N 1)
  15448. (not (org-region-active-p))
  15449. (org-at-table-p)
  15450. (progn
  15451. ;; Check if we blank the field, and if that triggers align.
  15452. (and (featurep 'org-table)
  15453. org-table-auto-blank-field
  15454. (memq last-command
  15455. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15456. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15457. ;; Got extra space, this field does not determine
  15458. ;; column width.
  15459. (let (org-table-may-need-update) (org-table-blank-field))
  15460. ;; No extra space, this field may determine column
  15461. ;; width.
  15462. (org-table-blank-field)))
  15463. t)
  15464. (looking-at "[^|\n]* |"))
  15465. ;; There is room for insertion without re-aligning the table.
  15466. (self-insert-command N)
  15467. (org-table-with-shrunk-field
  15468. (save-excursion
  15469. (skip-chars-forward "^|")
  15470. ;; Do not delete last space, which is
  15471. ;; `org-table-separator-space', but the regular space before
  15472. ;; it.
  15473. (delete-region (- (point) 2) (1- (point))))))
  15474. (t
  15475. (setq org-table-may-need-update t)
  15476. (self-insert-command N)
  15477. (org-fix-tags-on-the-fly)
  15478. (when org-self-insert-cluster-for-undo
  15479. (if (not (eq last-command 'org-self-insert-command))
  15480. (setq org-self-insert-command-undo-counter 1)
  15481. (if (>= org-self-insert-command-undo-counter 20)
  15482. (setq org-self-insert-command-undo-counter 1)
  15483. (and (> org-self-insert-command-undo-counter 0)
  15484. buffer-undo-list (listp buffer-undo-list)
  15485. (not (cadr buffer-undo-list)) ; remove nil entry
  15486. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15487. (setq org-self-insert-command-undo-counter
  15488. (1+ org-self-insert-command-undo-counter))))))))
  15489. (defun org-check-before-invisible-edit (kind)
  15490. "Check if editing kind KIND would be dangerous with invisible text around.
  15491. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15492. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15493. (when (and org-catch-invisible-edits
  15494. (or (not (boundp 'visible-mode)) (not visible-mode))
  15495. (or (get-char-property (point) 'invisible)
  15496. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15497. ;; OK, we need to take a closer look. Do not consider
  15498. ;; invisibility obtained through text properties (e.g., link
  15499. ;; fontification), as it cannot be toggled.
  15500. (let* ((invisible-at-point
  15501. (pcase (get-char-property-and-overlay (point) 'invisible)
  15502. (`(,_ . ,(and (pred overlayp) o)) o)))
  15503. ;; Assume that point cannot land in the middle of an
  15504. ;; overlay, or between two overlays.
  15505. (invisible-before-point
  15506. (and (not invisible-at-point)
  15507. (not (bobp))
  15508. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15509. (`(,_ . ,(and (pred overlayp) o)) o))))
  15510. (border-and-ok-direction
  15511. (or
  15512. ;; Check if we are acting predictably before invisible
  15513. ;; text.
  15514. (and invisible-at-point
  15515. (memq kind '(insert delete-backward)))
  15516. ;; Check if we are acting predictably after invisible text
  15517. ;; This works not well, and I have turned it off. It seems
  15518. ;; better to always show and stop after invisible text.
  15519. ;; (and (not invisible-at-point) invisible-before-point
  15520. ;; (memq kind '(insert delete)))
  15521. )))
  15522. (when (or invisible-at-point invisible-before-point)
  15523. (when (eq org-catch-invisible-edits 'error)
  15524. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15525. (if (and org-custom-properties-overlays
  15526. (y-or-n-p "Display invisible properties in this buffer? "))
  15527. (org-toggle-custom-properties-visibility)
  15528. ;; Make the area visible
  15529. (save-excursion
  15530. (when invisible-before-point
  15531. (goto-char
  15532. (previous-single-char-property-change (point) 'invisible)))
  15533. ;; Remove whatever overlay is currently making yet-to-be
  15534. ;; edited text invisible. Also remove nested invisibility
  15535. ;; related overlays.
  15536. (delete-overlay (or invisible-at-point invisible-before-point))
  15537. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15538. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15539. (`(,_ . ,(and (pred overlayp) o))
  15540. (delete-overlay o)
  15541. t)))))
  15542. (cond
  15543. ((eq org-catch-invisible-edits 'show)
  15544. ;; That's it, we do the edit after showing
  15545. (message
  15546. "Unfolding invisible region around point before editing")
  15547. (sit-for 1))
  15548. ((and (eq org-catch-invisible-edits 'smart)
  15549. border-and-ok-direction)
  15550. (message "Unfolding invisible region around point before editing"))
  15551. (t
  15552. ;; Don't do the edit, make the user repeat it in full visibility
  15553. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15554. (defun org-fix-tags-on-the-fly ()
  15555. "Align tags in headline at point.
  15556. Unlike `org-align-tags', this function does nothing if point is
  15557. either not currently on a tagged headline or on a tag."
  15558. (when (and (org-match-line org-tag-line-re)
  15559. (< (point) (match-beginning 1)))
  15560. (org-align-tags)))
  15561. (defun org-delete-backward-char (N)
  15562. "Like `delete-backward-char', insert whitespace at field end in tables.
  15563. When deleting backwards, in tables this function will insert whitespace in
  15564. front of the next \"|\" separator, to keep the table aligned. The table will
  15565. still be marked for re-alignment if the field did fill the entire column,
  15566. because, in this case the deletion might narrow the column."
  15567. (interactive "p")
  15568. (save-match-data
  15569. (org-check-before-invisible-edit 'delete-backward)
  15570. (if (and (= N 1)
  15571. (not overwrite-mode)
  15572. (not (org-region-active-p))
  15573. (not (eq (char-before) ?|))
  15574. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15575. (looking-at-p ".*?|")
  15576. (org-at-table-p))
  15577. (progn (forward-char -1) (org-delete-char 1))
  15578. (backward-delete-char N)
  15579. (org-fix-tags-on-the-fly))))
  15580. (defun org-delete-char (N)
  15581. "Like `delete-char', but insert whitespace at field end in tables.
  15582. When deleting characters, in tables this function will insert whitespace in
  15583. front of the next \"|\" separator, to keep the table aligned. The table will
  15584. still be marked for re-alignment if the field did fill the entire column,
  15585. because, in this case the deletion might narrow the column."
  15586. (interactive "p")
  15587. (save-match-data
  15588. (org-check-before-invisible-edit 'delete)
  15589. (cond
  15590. ((or (/= N 1)
  15591. (eq (char-after) ?|)
  15592. (save-excursion (skip-chars-backward " \t") (bolp))
  15593. (not (org-at-table-p)))
  15594. (delete-char N)
  15595. (org-fix-tags-on-the-fly))
  15596. ((looking-at ".\\(.*?\\)|")
  15597. (let* ((update? org-table-may-need-update)
  15598. (noalign (looking-at-p ".*? |")))
  15599. (delete-char 1)
  15600. (org-table-with-shrunk-field
  15601. (save-excursion
  15602. ;; Last space is `org-table-separator-space', so insert
  15603. ;; a regular one before it instead.
  15604. (goto-char (- (match-end 0) 2))
  15605. (insert " ")))
  15606. ;; If there were two spaces at the end, this field does not
  15607. ;; determine the width of the column.
  15608. (when noalign (setq org-table-may-need-update update?))))
  15609. (t
  15610. (delete-char N)))))
  15611. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15612. (put 'org-self-insert-command 'delete-selection
  15613. (lambda ()
  15614. (not (run-hook-with-args-until-success
  15615. 'self-insert-uses-region-functions))))
  15616. (put 'orgtbl-self-insert-command 'delete-selection
  15617. (lambda ()
  15618. (not (run-hook-with-args-until-success
  15619. 'self-insert-uses-region-functions))))
  15620. (put 'org-delete-char 'delete-selection 'supersede)
  15621. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15622. (put 'org-yank 'delete-selection 'yank)
  15623. (put 'org-return 'delete-selection t)
  15624. ;; Make `flyspell-mode' delay after some commands
  15625. (put 'org-self-insert-command 'flyspell-delayed t)
  15626. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15627. (put 'org-delete-char 'flyspell-delayed t)
  15628. (put 'org-delete-backward-char 'flyspell-delayed t)
  15629. ;; Make pabbrev-mode expand after Org mode commands
  15630. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15631. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15632. (defun org-transpose-words ()
  15633. "Transpose words for Org.
  15634. This uses the `org-mode-transpose-word-syntax-table' syntax
  15635. table, which interprets characters in `org-emphasis-alist' as
  15636. word constituents."
  15637. (interactive)
  15638. (with-syntax-table org-mode-transpose-word-syntax-table
  15639. (call-interactively 'transpose-words)))
  15640. (defvar org-ctrl-c-ctrl-c-hook nil
  15641. "Hook for functions attaching themselves to `C-c C-c'.
  15642. This can be used to add additional functionality to the `C-c C-c'
  15643. key which executes context-dependent commands. This hook is run
  15644. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15645. run after the last test.
  15646. Each function will be called with no arguments. The function
  15647. must check if the context is appropriate for it to act. If yes,
  15648. it should do its thing and then return a non-nil value. If the
  15649. context is wrong, just do nothing and return nil.")
  15650. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15651. "Hook for functions attaching themselves to `C-c C-c'.
  15652. This can be used to add additional functionality to the `C-c C-c'
  15653. key which executes context-dependent commands. This hook is run
  15654. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15655. before the first test.
  15656. Each function will be called with no arguments. The function
  15657. must check if the context is appropriate for it to act. If yes,
  15658. it should do its thing and then return a non-nil value. If the
  15659. context is wrong, just do nothing and return nil.")
  15660. (defvar org-tab-first-hook nil
  15661. "Hook for functions to attach themselves to TAB.
  15662. See `org-ctrl-c-ctrl-c-hook' for more information.
  15663. This hook runs as the first action when TAB is pressed, even before
  15664. `org-cycle' messes around with the `outline-regexp' to cater for
  15665. inline tasks and plain list item folding.
  15666. If any function in this hook returns t, any other actions that
  15667. would have been caused by TAB (such as table field motion or visibility
  15668. cycling) will not occur.")
  15669. (defvar org-tab-after-check-for-table-hook nil
  15670. "Hook for functions to attach themselves to TAB.
  15671. See `org-ctrl-c-ctrl-c-hook' for more information.
  15672. This hook runs after it has been established that the cursor is not in a
  15673. table, but before checking if the cursor is in a headline or if global cycling
  15674. should be done.
  15675. If any function in this hook returns t, not other actions like visibility
  15676. cycling will be done.")
  15677. (defvar org-tab-after-check-for-cycling-hook nil
  15678. "Hook for functions to attach themselves to TAB.
  15679. See `org-ctrl-c-ctrl-c-hook' for more information.
  15680. This hook runs after it has been established that not table field motion and
  15681. not visibility should be done because of current context. This is probably
  15682. the place where a package like yasnippets can hook in.")
  15683. (defvar org-tab-before-tab-emulation-hook nil
  15684. "Hook for functions to attach themselves to TAB.
  15685. See `org-ctrl-c-ctrl-c-hook' for more information.
  15686. This hook runs after every other options for TAB have been exhausted, but
  15687. before indentation and \t insertion takes place.")
  15688. (defvar org-metaleft-hook nil
  15689. "Hook for functions attaching themselves to `M-left'.
  15690. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15691. (defvar org-metaright-hook nil
  15692. "Hook for functions attaching themselves to `M-right'.
  15693. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15694. (defvar org-metaup-hook nil
  15695. "Hook for functions attaching themselves to `M-up'.
  15696. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15697. (defvar org-metadown-hook nil
  15698. "Hook for functions attaching themselves to `M-down'.
  15699. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15700. (defvar org-shiftmetaleft-hook nil
  15701. "Hook for functions attaching themselves to `M-S-left'.
  15702. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15703. (defvar org-shiftmetaright-hook nil
  15704. "Hook for functions attaching themselves to `M-S-right'.
  15705. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15706. (defvar org-shiftmetaup-hook nil
  15707. "Hook for functions attaching themselves to `M-S-up'.
  15708. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15709. (defvar org-shiftmetadown-hook nil
  15710. "Hook for functions attaching themselves to `M-S-down'.
  15711. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15712. (defvar org-metareturn-hook nil
  15713. "Hook for functions attaching themselves to `M-RET'.
  15714. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15715. (defvar org-shiftup-hook nil
  15716. "Hook for functions attaching themselves to `S-up'.
  15717. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15718. (defvar org-shiftup-final-hook nil
  15719. "Hook for functions attaching themselves to `S-up'.
  15720. This one runs after all other options except shift-select have been excluded.
  15721. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15722. (defvar org-shiftdown-hook nil
  15723. "Hook for functions attaching themselves to `S-down'.
  15724. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15725. (defvar org-shiftdown-final-hook nil
  15726. "Hook for functions attaching themselves to `S-down'.
  15727. This one runs after all other options except shift-select have been excluded.
  15728. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15729. (defvar org-shiftleft-hook nil
  15730. "Hook for functions attaching themselves to `S-left'.
  15731. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15732. (defvar org-shiftleft-final-hook nil
  15733. "Hook for functions attaching themselves to `S-left'.
  15734. This one runs after all other options except shift-select have been excluded.
  15735. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15736. (defvar org-shiftright-hook nil
  15737. "Hook for functions attaching themselves to `S-right'.
  15738. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15739. (defvar org-shiftright-final-hook nil
  15740. "Hook for functions attaching themselves to `S-right'.
  15741. This one runs after all other options except shift-select have been excluded.
  15742. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15743. (defun org-modifier-cursor-error ()
  15744. "Throw an error, a modified cursor command was applied in wrong context."
  15745. (user-error "This command is active in special context like tables, headlines or items"))
  15746. (defun org-shiftselect-error ()
  15747. "Throw an error because Shift-Cursor command was applied in wrong context."
  15748. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15749. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15750. (user-error "This command works only in special context like headlines or timestamps")))
  15751. (defun org-call-for-shift-select (cmd)
  15752. (let ((this-command-keys-shift-translated t))
  15753. (call-interactively cmd)))
  15754. (defun org-shifttab (&optional arg)
  15755. "Global visibility cycling or move to previous table field.
  15756. Call `org-table-previous-field' within a table.
  15757. When ARG is nil, cycle globally through visibility states.
  15758. When ARG is a numeric prefix, show contents of this level."
  15759. (interactive "P")
  15760. (cond
  15761. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15762. ((integerp arg)
  15763. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15764. (message "Content view to level: %d" arg)
  15765. (org-content (prefix-numeric-value arg2))
  15766. (org-cycle-show-empty-lines t)
  15767. (setq org-cycle-global-status 'overview)
  15768. (run-hook-with-args 'org-cycle-hook 'overview)))
  15769. (t (call-interactively 'org-global-cycle))))
  15770. (defun org-shiftmetaleft ()
  15771. "Promote subtree or delete table column.
  15772. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15773. `org-table-delete-column', depending on context. See the
  15774. individual commands for more information."
  15775. (interactive)
  15776. (cond
  15777. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15778. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15779. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15780. ((if (not (org-region-active-p)) (org-at-item-p)
  15781. (save-excursion (goto-char (region-beginning))
  15782. (org-at-item-p)))
  15783. (call-interactively 'org-outdent-item-tree))
  15784. (t (org-modifier-cursor-error))))
  15785. (defun org-shiftmetaright ()
  15786. "Demote subtree or insert table column.
  15787. Calls `org-demote-subtree', `org-indent-item-tree', or
  15788. `org-table-insert-column', depending on context. See the
  15789. individual commands for more information."
  15790. (interactive)
  15791. (cond
  15792. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15793. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15794. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15795. ((if (not (org-region-active-p)) (org-at-item-p)
  15796. (save-excursion (goto-char (region-beginning))
  15797. (org-at-item-p)))
  15798. (call-interactively 'org-indent-item-tree))
  15799. (t (org-modifier-cursor-error))))
  15800. (defun org-shiftmetaup (&optional _arg)
  15801. "Drag the line at point up.
  15802. In a table, kill the current row.
  15803. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15804. but also adjust the previous clocked item in the clock history.
  15805. Everywhere else, drag the line at point up."
  15806. (interactive "P")
  15807. (cond
  15808. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15809. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15810. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15811. (call-interactively 'org-timestamp-up)))
  15812. (t (call-interactively 'org-drag-line-backward))))
  15813. (defun org-shiftmetadown (&optional _arg)
  15814. "Drag the line at point down.
  15815. In a table, insert an empty row at the current line.
  15816. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15817. but also adjust the previous clocked item in the clock history.
  15818. Everywhere else, drag the line at point down."
  15819. (interactive "P")
  15820. (cond
  15821. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15822. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15823. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15824. (call-interactively 'org-timestamp-down)))
  15825. (t (call-interactively 'org-drag-line-forward))))
  15826. (defsubst org-hidden-tree-error ()
  15827. (user-error
  15828. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15829. (defun org-metaleft (&optional _arg)
  15830. "Promote heading, list item at point or move table column left.
  15831. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15832. depending on context. With no specific context, calls the Emacs
  15833. default `backward-word'. See the individual commands for more
  15834. information.
  15835. This function runs the hook `org-metaleft-hook' as a first step,
  15836. and returns at first non-nil value."
  15837. (interactive "P")
  15838. (cond
  15839. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15840. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15841. ((org-with-limited-levels
  15842. (or (org-at-heading-p)
  15843. (and (org-region-active-p)
  15844. (save-excursion
  15845. (goto-char (region-beginning))
  15846. (org-at-heading-p)))))
  15847. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15848. (call-interactively 'org-do-promote))
  15849. ;; At an inline task.
  15850. ((org-at-heading-p)
  15851. (call-interactively 'org-inlinetask-promote))
  15852. ((or (org-at-item-p)
  15853. (and (org-region-active-p)
  15854. (save-excursion
  15855. (goto-char (region-beginning))
  15856. (org-at-item-p))))
  15857. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15858. (call-interactively 'org-outdent-item))
  15859. (t (call-interactively 'backward-word))))
  15860. (defun org-metaright (&optional _arg)
  15861. "Demote heading, list item at point or move table column right.
  15862. In front of a drawer or a block keyword, indent it correctly.
  15863. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15864. `org-indent-drawer' or `org-indent-block' depending on context.
  15865. With no specific context, calls the Emacs default `forward-word'.
  15866. See the individual commands for more information.
  15867. This function runs the hook `org-metaright-hook' as a first step,
  15868. and returns at first non-nil value."
  15869. (interactive "P")
  15870. (cond
  15871. ((run-hook-with-args-until-success 'org-metaright-hook))
  15872. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15873. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15874. ((org-at-block-p) (call-interactively 'org-indent-block))
  15875. ((org-with-limited-levels
  15876. (or (org-at-heading-p)
  15877. (and (org-region-active-p)
  15878. (save-excursion
  15879. (goto-char (region-beginning))
  15880. (org-at-heading-p)))))
  15881. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15882. (call-interactively 'org-do-demote))
  15883. ;; At an inline task.
  15884. ((org-at-heading-p)
  15885. (call-interactively 'org-inlinetask-demote))
  15886. ((or (org-at-item-p)
  15887. (and (org-region-active-p)
  15888. (save-excursion
  15889. (goto-char (region-beginning))
  15890. (org-at-item-p))))
  15891. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15892. (call-interactively 'org-indent-item))
  15893. (t (call-interactively 'forward-word))))
  15894. (defun org-check-for-hidden (what)
  15895. "Check if there are hidden headlines/items in the current visual line.
  15896. WHAT can be either `headlines' or `items'. If the current line is
  15897. an outline or item heading and it has a folded subtree below it,
  15898. this function returns t, nil otherwise."
  15899. (let ((re (cond
  15900. ((eq what 'headlines) org-outline-regexp-bol)
  15901. ((eq what 'items) (org-item-beginning-re))
  15902. (t (error "This should not happen"))))
  15903. beg end)
  15904. (save-excursion
  15905. (catch 'exit
  15906. (unless (org-region-active-p)
  15907. (setq beg (point-at-bol))
  15908. (beginning-of-line 2)
  15909. (while (and (not (eobp)) ;; this is like `next-line'
  15910. (get-char-property (1- (point)) 'invisible))
  15911. (beginning-of-line 2))
  15912. (setq end (point))
  15913. (goto-char beg)
  15914. (goto-char (point-at-eol))
  15915. (setq end (max end (point)))
  15916. (while (re-search-forward re end t)
  15917. (when (get-char-property (match-beginning 0) 'invisible)
  15918. (throw 'exit t))))
  15919. nil))))
  15920. (defun org-metaup (&optional _arg)
  15921. "Move subtree up or move table row up.
  15922. Calls `org-move-subtree-up' or `org-table-move-row' or
  15923. `org-move-item-up', depending on context. See the individual commands
  15924. for more information."
  15925. (interactive "P")
  15926. (cond
  15927. ((run-hook-with-args-until-success 'org-metaup-hook))
  15928. ((org-region-active-p)
  15929. (let* ((a (save-excursion
  15930. (goto-char (min (region-beginning) (region-end)))
  15931. (line-beginning-position)))
  15932. (b (save-excursion
  15933. (goto-char (max (region-beginning) (region-end)))
  15934. (if (bolp) (1- (point)) (line-end-position))))
  15935. (c (save-excursion
  15936. (goto-char a)
  15937. (move-beginning-of-line 0)
  15938. (point)))
  15939. (d (save-excursion
  15940. (goto-char a)
  15941. (move-end-of-line 0)
  15942. (point))))
  15943. (transpose-regions a b c d)
  15944. (goto-char c)))
  15945. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15946. ((and (featurep 'org-inlinetask)
  15947. (org-inlinetask-in-task-p))
  15948. (org-drag-element-backward))
  15949. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15950. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15951. (t (org-drag-element-backward))))
  15952. (defun org-metadown (&optional _arg)
  15953. "Move subtree down or move table row down.
  15954. Calls `org-move-subtree-down' or `org-table-move-row' or
  15955. `org-move-item-down', depending on context. See the individual
  15956. commands for more information."
  15957. (interactive "P")
  15958. (cond
  15959. ((run-hook-with-args-until-success 'org-metadown-hook))
  15960. ((org-region-active-p)
  15961. (let* ((a (save-excursion
  15962. (goto-char (min (region-beginning) (region-end)))
  15963. (line-beginning-position)))
  15964. (b (save-excursion
  15965. (goto-char (max (region-beginning) (region-end)))
  15966. (if (bolp) (1- (point)) (line-end-position))))
  15967. (c (save-excursion
  15968. (goto-char b)
  15969. (move-beginning-of-line (if (bolp) 1 2))
  15970. (point)))
  15971. (d (save-excursion
  15972. (goto-char b)
  15973. (move-end-of-line (if (bolp) 1 2))
  15974. (point))))
  15975. (transpose-regions a b c d)
  15976. (goto-char d)))
  15977. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15978. ((and (featurep 'org-inlinetask)
  15979. (org-inlinetask-in-task-p))
  15980. (org-drag-element-forward))
  15981. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15982. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15983. (t (org-drag-element-forward))))
  15984. (defun org-shiftup (&optional arg)
  15985. "Act on current element according to context.
  15986. Call `org-timestamp-up' or `org-priority-up', or
  15987. `org-previous-item', or `org-table-move-cell-up'. See the
  15988. individual commands for more information."
  15989. (interactive "P")
  15990. (cond
  15991. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15992. ((and org-support-shift-select (org-region-active-p))
  15993. (org-call-for-shift-select 'previous-line))
  15994. ((org-at-timestamp-p 'lax)
  15995. (call-interactively (if org-edit-timestamp-down-means-later
  15996. 'org-timestamp-down 'org-timestamp-up)))
  15997. ((and (not (eq org-support-shift-select 'always))
  15998. org-priority-enable-commands
  15999. (org-at-heading-p))
  16000. (call-interactively 'org-priority-up))
  16001. ((and (not org-support-shift-select) (org-at-item-p))
  16002. (call-interactively 'org-previous-item))
  16003. ((org-clocktable-try-shift 'up arg))
  16004. ((and (not (eq org-support-shift-select 'always))
  16005. (org-at-table-p))
  16006. (org-table-move-cell-up))
  16007. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  16008. (org-support-shift-select
  16009. (org-call-for-shift-select 'previous-line))
  16010. (t (org-shiftselect-error))))
  16011. (defun org-shiftdown (&optional arg)
  16012. "Act on current element according to context.
  16013. Call `org-timestamp-down' or `org-priority-down', or
  16014. `org-next-item', or `org-table-move-cell-down'. See the
  16015. individual commands for more information."
  16016. (interactive "P")
  16017. (cond
  16018. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  16019. ((and org-support-shift-select (org-region-active-p))
  16020. (org-call-for-shift-select 'next-line))
  16021. ((org-at-timestamp-p 'lax)
  16022. (call-interactively (if org-edit-timestamp-down-means-later
  16023. 'org-timestamp-up 'org-timestamp-down)))
  16024. ((and (not (eq org-support-shift-select 'always))
  16025. org-priority-enable-commands
  16026. (org-at-heading-p))
  16027. (call-interactively 'org-priority-down))
  16028. ((and (not org-support-shift-select) (org-at-item-p))
  16029. (call-interactively 'org-next-item))
  16030. ((org-clocktable-try-shift 'down arg))
  16031. ((and (not (eq org-support-shift-select 'always))
  16032. (org-at-table-p))
  16033. (org-table-move-cell-down))
  16034. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  16035. (org-support-shift-select
  16036. (org-call-for-shift-select 'next-line))
  16037. (t (org-shiftselect-error))))
  16038. (defun org-shiftright (&optional arg)
  16039. "Act on the current element according to context.
  16040. This does one of the following:
  16041. - switch a timestamp at point one day into the future
  16042. - on a headline, switch to the next TODO keyword
  16043. - on an item, switch entire list to the next bullet type
  16044. - on a property line, switch to the next allowed value
  16045. - on a clocktable definition line, move time block into the future
  16046. - in a table, move a single cell right"
  16047. (interactive "P")
  16048. (cond
  16049. ((run-hook-with-args-until-success 'org-shiftright-hook))
  16050. ((and org-support-shift-select (org-region-active-p))
  16051. (org-call-for-shift-select 'forward-char))
  16052. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  16053. ((and (not (eq org-support-shift-select 'always))
  16054. (org-at-heading-p))
  16055. (let ((org-inhibit-logging
  16056. (not org-treat-S-cursor-todo-selection-as-state-change))
  16057. (org-inhibit-blocking
  16058. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16059. (org-call-with-arg 'org-todo 'right)))
  16060. ((or (and org-support-shift-select
  16061. (not (eq org-support-shift-select 'always))
  16062. (org-at-item-bullet-p))
  16063. (and (not org-support-shift-select) (org-at-item-p)))
  16064. (org-call-with-arg 'org-cycle-list-bullet nil))
  16065. ((and (not (eq org-support-shift-select 'always))
  16066. (org-at-property-p))
  16067. (call-interactively 'org-property-next-allowed-value))
  16068. ((org-clocktable-try-shift 'right arg))
  16069. ((and (not (eq org-support-shift-select 'always))
  16070. (org-at-table-p))
  16071. (org-table-move-cell-right))
  16072. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  16073. (org-support-shift-select
  16074. (org-call-for-shift-select 'forward-char))
  16075. (t (org-shiftselect-error))))
  16076. (defun org-shiftleft (&optional arg)
  16077. "Act on current element according to context.
  16078. This does one of the following:
  16079. - switch a timestamp at point one day into the past
  16080. - on a headline, switch to the previous TODO keyword.
  16081. - on an item, switch entire list to the previous bullet type
  16082. - on a property line, switch to the previous allowed value
  16083. - on a clocktable definition line, move time block into the past
  16084. - in a table, move a single cell left"
  16085. (interactive "P")
  16086. (cond
  16087. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  16088. ((and org-support-shift-select (org-region-active-p))
  16089. (org-call-for-shift-select 'backward-char))
  16090. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  16091. ((and (not (eq org-support-shift-select 'always))
  16092. (org-at-heading-p))
  16093. (let ((org-inhibit-logging
  16094. (not org-treat-S-cursor-todo-selection-as-state-change))
  16095. (org-inhibit-blocking
  16096. (not org-treat-S-cursor-todo-selection-as-state-change)))
  16097. (org-call-with-arg 'org-todo 'left)))
  16098. ((or (and org-support-shift-select
  16099. (not (eq org-support-shift-select 'always))
  16100. (org-at-item-bullet-p))
  16101. (and (not org-support-shift-select) (org-at-item-p)))
  16102. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  16103. ((and (not (eq org-support-shift-select 'always))
  16104. (org-at-property-p))
  16105. (call-interactively 'org-property-previous-allowed-value))
  16106. ((org-clocktable-try-shift 'left arg))
  16107. ((and (not (eq org-support-shift-select 'always))
  16108. (org-at-table-p))
  16109. (org-table-move-cell-left))
  16110. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  16111. (org-support-shift-select
  16112. (org-call-for-shift-select 'backward-char))
  16113. (t (org-shiftselect-error))))
  16114. (defun org-shiftcontrolright ()
  16115. "Switch to next TODO set."
  16116. (interactive)
  16117. (cond
  16118. ((and org-support-shift-select (org-region-active-p))
  16119. (org-call-for-shift-select 'forward-word))
  16120. ((and (not (eq org-support-shift-select 'always))
  16121. (org-at-heading-p))
  16122. (org-call-with-arg 'org-todo 'nextset))
  16123. (org-support-shift-select
  16124. (org-call-for-shift-select 'forward-word))
  16125. (t (org-shiftselect-error))))
  16126. (defun org-shiftcontrolleft ()
  16127. "Switch to previous TODO set."
  16128. (interactive)
  16129. (cond
  16130. ((and org-support-shift-select (org-region-active-p))
  16131. (org-call-for-shift-select 'backward-word))
  16132. ((and (not (eq org-support-shift-select 'always))
  16133. (org-at-heading-p))
  16134. (org-call-with-arg 'org-todo 'previousset))
  16135. (org-support-shift-select
  16136. (org-call-for-shift-select 'backward-word))
  16137. (t (org-shiftselect-error))))
  16138. (defun org-shiftcontrolup (&optional n)
  16139. "Change timestamps synchronously up in CLOCK log lines.
  16140. Optional argument N tells to change by that many units."
  16141. (interactive "P")
  16142. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16143. (let (org-support-shift-select)
  16144. (org-clock-timestamps-up n))
  16145. (user-error "Not at a clock log")))
  16146. (defun org-shiftcontroldown (&optional n)
  16147. "Change timestamps synchronously down in CLOCK log lines.
  16148. Optional argument N tells to change by that many units."
  16149. (interactive "P")
  16150. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  16151. (let (org-support-shift-select)
  16152. (org-clock-timestamps-down n))
  16153. (user-error "Not at a clock log")))
  16154. (defun org-increase-number-at-point (&optional inc)
  16155. "Increment the number at point.
  16156. With an optional prefix numeric argument INC, increment using
  16157. this numeric value."
  16158. (interactive "p")
  16159. (if (not (number-at-point))
  16160. (user-error "Not on a number")
  16161. (unless inc (setq inc 1))
  16162. (let ((pos (point))
  16163. (beg (skip-chars-backward "-+^/*0-9eE."))
  16164. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  16165. (setq nap (buffer-substring-no-properties
  16166. (+ pos beg) (+ pos beg end)))
  16167. (delete-region (+ pos beg) (+ pos beg end))
  16168. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  16169. (when (org-at-table-p)
  16170. (org-table-align)
  16171. (org-table-end-of-field 1))))
  16172. (defun org-decrease-number-at-point (&optional inc)
  16173. "Decrement the number at point.
  16174. With an optional prefix numeric argument INC, decrement using
  16175. this numeric value."
  16176. (interactive "p")
  16177. (org-increase-number-at-point (- (or inc 1))))
  16178. (defun org-ctrl-c-ret ()
  16179. "Call `org-table-hline-and-move' or `org-insert-heading'."
  16180. (interactive)
  16181. (cond
  16182. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  16183. (t (call-interactively 'org-insert-heading))))
  16184. (defun org-copy-visible (beg end)
  16185. "Copy the visible parts of the region."
  16186. (interactive "r")
  16187. (let ((result ""))
  16188. (while (/= beg end)
  16189. (when (get-char-property beg 'invisible)
  16190. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16191. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16192. (setq result (concat result (buffer-substring beg next)))
  16193. (setq beg next)))
  16194. (setq deactivate-mark t)
  16195. (kill-new result)
  16196. (message "Visible strings have been copied to the kill ring.")))
  16197. (defun org-copy-special ()
  16198. "Copy region in table or copy current subtree.
  16199. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16200. context. See the individual commands for more information."
  16201. (interactive)
  16202. (call-interactively
  16203. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16204. (defun org-cut-special ()
  16205. "Cut region in table or cut current subtree.
  16206. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16207. context. See the individual commands for more information."
  16208. (interactive)
  16209. (call-interactively
  16210. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16211. (defun org-paste-special (arg)
  16212. "Paste rectangular region into table, or past subtree relative to level.
  16213. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16214. See the individual commands for more information."
  16215. (interactive "P")
  16216. (if (org-at-table-p)
  16217. (org-table-paste-rectangle)
  16218. (org-paste-subtree arg)))
  16219. (defun org-edit-special (&optional arg)
  16220. "Call a special editor for the element at point.
  16221. When at a table, call the formula editor with `org-table-edit-formulas'.
  16222. When in a source code block, call `org-edit-src-code'.
  16223. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16224. When in an export block, call `org-edit-export-block'.
  16225. When in a LaTeX environment, call `org-edit-latex-environment'.
  16226. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  16227. When at a footnote reference, call `org-edit-footnote-reference'.
  16228. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16229. When at an active timestamp, call `org-time-stamp'.
  16230. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16231. On a link, call `ffap' to visit the link at point.
  16232. Otherwise, return a user error."
  16233. (interactive "P")
  16234. (let ((element (org-element-at-point)))
  16235. (barf-if-buffer-read-only)
  16236. (pcase (org-element-type element)
  16237. (`src-block
  16238. (if (not arg) (org-edit-src-code)
  16239. (let* ((info (org-babel-get-src-block-info))
  16240. (lang (nth 0 info))
  16241. (params (nth 2 info))
  16242. (session (cdr (assq :session params))))
  16243. (if (not session) (org-edit-src-code)
  16244. ;; At a source block with a session and function called
  16245. ;; with an ARG: switch to the buffer related to the
  16246. ;; inferior process.
  16247. (switch-to-buffer
  16248. (funcall (intern (concat "org-babel-prep-session:" lang))
  16249. session params))))))
  16250. (`keyword
  16251. (unless (member (org-element-property :key element)
  16252. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  16253. (user-error "No special environment to edit here"))
  16254. (let ((value (org-element-property :value element)))
  16255. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16256. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16257. (or (match-string 1 value)
  16258. (match-string 0 value)))))
  16259. (when (org-url-p file)
  16260. (user-error "Files located with a URL cannot be edited"))
  16261. (org-link-open-from-string
  16262. (format "[[%s]]" (expand-file-name file))))))
  16263. (`table
  16264. (if (eq (org-element-property :type element) 'table.el)
  16265. (org-edit-table.el)
  16266. (call-interactively 'org-table-edit-formulas)))
  16267. ;; Only Org tables contain `table-row' type elements.
  16268. (`table-row (call-interactively 'org-table-edit-formulas))
  16269. (`example-block (org-edit-src-code))
  16270. (`export-block (org-edit-export-block))
  16271. (`fixed-width (org-edit-fixed-width-region))
  16272. (`latex-environment (org-edit-latex-environment))
  16273. (`planning
  16274. (let ((proplist (cadr element)))
  16275. (mapc #'call-interactively
  16276. (remq nil
  16277. (list
  16278. (when (plist-get proplist :deadline) #'org-deadline)
  16279. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16280. (_
  16281. ;; No notable element at point. Though, we may be at a link or
  16282. ;; a footnote reference, which are objects. Thus, scan deeper.
  16283. (let ((context (org-element-context element)))
  16284. (pcase (org-element-type context)
  16285. (`footnote-reference (org-edit-footnote-reference))
  16286. (`inline-src-block (org-edit-inline-src-code))
  16287. (`latex-fragment (org-edit-latex-fragment))
  16288. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16289. (call-interactively #'org-time-stamp-inactive)
  16290. (call-interactively #'org-time-stamp)))
  16291. (`link (call-interactively #'ffap))
  16292. (_ (user-error "No special environment to edit here"))))))))
  16293. (defun org-ctrl-c-ctrl-c (&optional arg)
  16294. "Set tags in headline, or update according to changed information at point.
  16295. This command does many different things, depending on context:
  16296. - If column view is active, in agenda or org buffers, quit it.
  16297. - If there are highlights, remove them.
  16298. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16299. this is what we do.
  16300. - If the cursor is on a statistics cookie, update it.
  16301. - If the cursor is in a headline, in an agenda or an org buffer,
  16302. prompt for tags and insert them into the current line, aligned
  16303. to `org-tags-column'. When called with prefix arg, realign all
  16304. tags in the current buffer.
  16305. - If the cursor is in one of the special #+KEYWORD lines, this
  16306. triggers scanning the buffer for these lines and updating the
  16307. information.
  16308. - If the cursor is inside a table, realign the table. This command
  16309. works even if the automatic table editor has been turned off.
  16310. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16311. the entire table.
  16312. - If the cursor is at a footnote reference or definition, jump to
  16313. the corresponding definition or references, respectively.
  16314. - If the cursor is a the beginning of a dynamic block, update it.
  16315. - If the current buffer is a capture buffer, close note and file it.
  16316. - If the cursor is on a <<<target>>>, update radio targets and
  16317. corresponding links in this buffer.
  16318. - If the cursor is on a numbered item in a plain list, renumber the
  16319. ordered list.
  16320. - If the cursor is on a checkbox, toggle it.
  16321. - If the cursor is on a code block, evaluate it. The variable
  16322. `org-confirm-babel-evaluate' can be used to control prompting
  16323. before code block evaluation, by default every code block
  16324. evaluation requires confirmation. Code block evaluation can be
  16325. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16326. (interactive "P")
  16327. (cond
  16328. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16329. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16330. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16331. (org-remove-occur-highlights)
  16332. (message "Temporary highlights/overlays removed from current buffer"))
  16333. ((and (local-variable-p 'org-finish-function)
  16334. (fboundp org-finish-function))
  16335. (funcall org-finish-function))
  16336. ((org-babel-hash-at-point))
  16337. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16338. (t
  16339. (let* ((context
  16340. (org-element-lineage
  16341. (org-element-context)
  16342. ;; Limit to supported contexts.
  16343. '(babel-call clock dynamic-block footnote-definition
  16344. footnote-reference inline-babel-call inline-src-block
  16345. inlinetask item keyword node-property paragraph
  16346. plain-list planning property-drawer radio-target
  16347. src-block statistics-cookie table table-cell table-row
  16348. timestamp)
  16349. t))
  16350. (radio-list-p (org-at-radio-list-p))
  16351. (type (org-element-type context)))
  16352. ;; For convenience: at the first line of a paragraph on the same
  16353. ;; line as an item, apply function on that item instead.
  16354. (when (eq type 'paragraph)
  16355. (let ((parent (org-element-property :parent context)))
  16356. (when (and (eq (org-element-type parent) 'item)
  16357. (= (line-beginning-position)
  16358. (org-element-property :begin parent)))
  16359. (setq context parent)
  16360. (setq type 'item))))
  16361. ;; Act according to type of element or object at point.
  16362. ;;
  16363. ;; Do nothing on a blank line, except if it is contained in
  16364. ;; a source block. Hence, we first check if point is in such
  16365. ;; a block and then if it is at a blank line.
  16366. (pcase type
  16367. ((or `inline-src-block `src-block)
  16368. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16369. (org-babel-eval-wipe-error-buffer)
  16370. (org-babel-execute-src-block
  16371. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16372. ((guard (org-match-line "[ \t]*$"))
  16373. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16374. (user-error
  16375. (substitute-command-keys
  16376. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16377. ((or `babel-call `inline-babel-call)
  16378. (let ((info (org-babel-lob-get-info context)))
  16379. (when info (org-babel-execute-src-block nil info))))
  16380. (`clock (org-clock-update-time-maybe))
  16381. (`dynamic-block
  16382. (save-excursion
  16383. (goto-char (org-element-property :post-affiliated context))
  16384. (org-update-dblock)))
  16385. (`footnote-definition
  16386. (goto-char (org-element-property :post-affiliated context))
  16387. (call-interactively 'org-footnote-action))
  16388. (`footnote-reference (call-interactively #'org-footnote-action))
  16389. ((or `headline `inlinetask)
  16390. (save-excursion (goto-char (org-element-property :begin context))
  16391. (call-interactively #'org-set-tags-command)))
  16392. (`item
  16393. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16394. ;; unconditionally, whereas `C-u' will toggle its presence.
  16395. ;; Without a universal argument, if the item has a checkbox,
  16396. ;; toggle it. Otherwise repair the list.
  16397. (if (or radio-list-p
  16398. (and (boundp org-list-checkbox-radio-mode)
  16399. org-list-checkbox-radio-mode))
  16400. (org-toggle-radio-button arg)
  16401. (let* ((box (org-element-property :checkbox context))
  16402. (struct (org-element-property :structure context))
  16403. (old-struct (copy-tree struct))
  16404. (parents (org-list-parents-alist struct))
  16405. (prevs (org-list-prevs-alist struct))
  16406. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16407. (org-list-set-checkbox
  16408. (org-element-property :begin context) struct
  16409. (cond ((equal arg '(16)) "[-]")
  16410. ((and (not box) (equal arg '(4))) "[ ]")
  16411. ((or (not box) (equal arg '(4))) nil)
  16412. ((eq box 'on) "[ ]")
  16413. (t "[X]")))
  16414. ;; Mimic `org-list-write-struct' but with grabbing a return
  16415. ;; value from `org-list-struct-fix-box'.
  16416. (org-list-struct-fix-ind struct parents 2)
  16417. (org-list-struct-fix-item-end struct)
  16418. (org-list-struct-fix-bul struct prevs)
  16419. (org-list-struct-fix-ind struct parents)
  16420. (let ((block-item
  16421. (org-list-struct-fix-box struct parents prevs orderedp)))
  16422. (if (and box (equal struct old-struct))
  16423. (if (equal arg '(16))
  16424. (message "Checkboxes already reset")
  16425. (user-error "Cannot toggle this checkbox: %s"
  16426. (if (eq box 'on)
  16427. "all subitems checked"
  16428. "unchecked subitems")))
  16429. (org-list-struct-apply-struct struct old-struct)
  16430. (org-update-checkbox-count-maybe))
  16431. (when block-item
  16432. (message "Checkboxes were removed due to empty box at line %d"
  16433. (org-current-line block-item)))))))
  16434. (`plain-list
  16435. ;; At a plain list, with a double C-u argument, set
  16436. ;; checkboxes of each item to "[-]", whereas a single one
  16437. ;; will toggle their presence according to the state of the
  16438. ;; first item in the list. Without an argument, repair the
  16439. ;; list.
  16440. (if (or radio-list-p
  16441. (and (boundp org-list-checkbox-radio-mode)
  16442. org-list-checkbox-radio-mode))
  16443. (org-toggle-radio-button arg)
  16444. (let* ((begin (org-element-property :contents-begin context))
  16445. (struct (org-element-property :structure context))
  16446. (old-struct (copy-tree struct))
  16447. (first-box (save-excursion
  16448. (goto-char begin)
  16449. (looking-at org-list-full-item-re)
  16450. (match-string-no-properties 3)))
  16451. (new-box (cond ((equal arg '(16)) "[-]")
  16452. ((equal arg '(4)) (unless first-box "[ ]"))
  16453. ((equal first-box "[X]") "[ ]")
  16454. (t "[X]"))))
  16455. (cond
  16456. (arg
  16457. (dolist (pos
  16458. (org-list-get-all-items
  16459. begin struct (org-list-prevs-alist struct)))
  16460. (org-list-set-checkbox pos struct new-box)))
  16461. ((and first-box (eq (point) begin))
  16462. ;; For convenience, when point is at bol on the first
  16463. ;; item of the list and no argument is provided, simply
  16464. ;; toggle checkbox of that item, if any.
  16465. (org-list-set-checkbox begin struct new-box)))
  16466. (when (equal
  16467. (org-list-write-struct
  16468. struct (org-list-parents-alist struct) old-struct)
  16469. old-struct)
  16470. (message "Cannot update this checkbox"))
  16471. (org-update-checkbox-count-maybe))))
  16472. (`keyword
  16473. (let ((org-inhibit-startup-visibility-stuff t)
  16474. (org-startup-align-all-tables nil))
  16475. (when (boundp 'org-table-coordinate-overlays)
  16476. (mapc #'delete-overlay org-table-coordinate-overlays)
  16477. (setq org-table-coordinate-overlays nil))
  16478. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16479. (message "Local setup has been refreshed"))
  16480. ((or `property-drawer `node-property)
  16481. (call-interactively #'org-property-action))
  16482. (`radio-target
  16483. (call-interactively #'org-update-radio-target-regexp))
  16484. (`statistics-cookie
  16485. (call-interactively #'org-update-statistics-cookies))
  16486. ((or `table `table-cell `table-row)
  16487. ;; At a table, generate a plot if on the #+plot line,
  16488. ;; recalculate every field and align it otherwise. Also
  16489. ;; send the table if necessary.
  16490. (cond
  16491. ((and (org-match-line "[ \t]*#\\+plot:")
  16492. (< (point) (org-element-property :post-affiliated context)))
  16493. (org-plot/gnuplot))
  16494. ;; If the table has a `table.el' type, just give up.
  16495. ((eq (org-element-property :type context) 'table.el)
  16496. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16497. Use `\\[org-edit-special]' to edit table.el tables")))
  16498. ;; At a table row or cell, maybe recalculate line but always
  16499. ;; align table.
  16500. ((or (eq type 'table)
  16501. ;; Check if point is at a TBLFM line.
  16502. (and (eq type 'table-row)
  16503. (= (point) (org-element-property :end context))))
  16504. (save-excursion
  16505. (if (org-at-TBLFM-p)
  16506. (progn (require 'org-table)
  16507. (org-table-calc-current-TBLFM))
  16508. (goto-char (org-element-property :contents-begin context))
  16509. (org-call-with-arg 'org-table-recalculate (or arg t))
  16510. (orgtbl-send-table 'maybe))))
  16511. (t
  16512. (org-table-maybe-eval-formula)
  16513. (cond (arg (call-interactively #'org-table-recalculate))
  16514. ((org-table-maybe-recalculate-line))
  16515. (t (org-table-align))))))
  16516. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16517. (org-timestamp-change 0 'day))
  16518. ((and `nil (guard (org-at-heading-p)))
  16519. ;; When point is on an unsupported object type, we can miss
  16520. ;; the fact that it also is at a heading. Handle it here.
  16521. (call-interactively #'org-set-tags-command))
  16522. ((guard
  16523. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16524. (_
  16525. (user-error
  16526. (substitute-command-keys
  16527. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16528. (defun org-mode-restart ()
  16529. "Restart `org-mode'."
  16530. (interactive)
  16531. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16532. (funcall major-mode)
  16533. (hack-local-variables)
  16534. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16535. (org-indent-mode -1))
  16536. (org-reset-file-cache))
  16537. (message "%s restarted" major-mode))
  16538. (defun org-flag-above-first-heading (&optional arg)
  16539. "Hide from bob up to the first heading.
  16540. Move point to the beginning of first heading or end of buffer."
  16541. (goto-char (point-min))
  16542. (unless (org-at-heading-p)
  16543. (outline-next-heading))
  16544. (unless (bobp)
  16545. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16546. (defun org-show-branches-buffer ()
  16547. "Show all branches in the buffer."
  16548. (org-flag-above-first-heading)
  16549. (outline-hide-sublevels 1)
  16550. (unless (eobp)
  16551. (outline-show-branches)
  16552. (while (outline-get-next-sibling)
  16553. (outline-show-branches)))
  16554. (goto-char (point-min)))
  16555. (defun org-kill-note-or-show-branches ()
  16556. "Abort storing current note, or show just branches."
  16557. (interactive)
  16558. (cond (org-finish-function
  16559. (let ((org-note-abort t)) (funcall org-finish-function)))
  16560. ((org-before-first-heading-p)
  16561. (org-show-branches-buffer)
  16562. (org-hide-archived-subtrees (point-min) (point-max)))
  16563. (t
  16564. (let ((beg (progn (org-back-to-heading) (point)))
  16565. (end (save-excursion (org-end-of-subtree t t) (point))))
  16566. (outline-hide-subtree)
  16567. (outline-show-branches)
  16568. (org-hide-archived-subtrees beg end)))))
  16569. (defun org-delete-indentation (&optional arg)
  16570. "Join current line to previous and fix whitespace at join.
  16571. If previous line is a headline add to headline title. Otherwise
  16572. the function calls `delete-indentation'.
  16573. I.e. with a non-nil optional argument, join the line with the
  16574. following one. If there is a region then join the lines in that
  16575. region."
  16576. (interactive "*P")
  16577. (if (save-excursion
  16578. (beginning-of-line (if arg 1 0))
  16579. (let ((case-fold-search nil))
  16580. (looking-at org-complex-heading-regexp)))
  16581. ;; At headline.
  16582. (let ((tags-column (when (match-beginning 5)
  16583. (save-excursion (goto-char (match-beginning 5))
  16584. (current-column))))
  16585. (string (concat " " (progn (when arg (forward-line 1))
  16586. (org-trim (delete-and-extract-region
  16587. (line-beginning-position)
  16588. (line-end-position)))))))
  16589. (unless (bobp) (delete-region (point) (1- (point))))
  16590. (goto-char (or (match-end 4)
  16591. (match-beginning 5)
  16592. (match-end 0)))
  16593. (skip-chars-backward " \t")
  16594. (save-excursion (insert string))
  16595. ;; Adjust alignment of tags.
  16596. (cond
  16597. ((not tags-column)) ;no tags
  16598. (org-auto-align-tags (org-align-tags))
  16599. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16600. (let ((current-prefix-arg arg))
  16601. (call-interactively #'delete-indentation))))
  16602. (defun org-open-line (n)
  16603. "Insert a new row in tables, call `open-line' elsewhere.
  16604. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16605. As a special case, when a document starts with a table, allow to
  16606. call `open-line' on the very first character."
  16607. (interactive "*p")
  16608. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16609. (org-table-insert-row)
  16610. (open-line n)))
  16611. (defun org--newline (indent arg interactive)
  16612. "Call `newline-and-indent' or just `newline'.
  16613. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16614. indent unconditionally; otherwise, call `newline' with ARG and
  16615. INTERACTIVE, which can trigger indentation if
  16616. `electric-indent-mode' is enabled."
  16617. (if indent
  16618. (org-newline-and-indent arg)
  16619. (newline arg interactive)))
  16620. (defun org-return (&optional indent arg interactive)
  16621. "Goto next table row or insert a newline.
  16622. Calls `org-table-next-row' or `newline', depending on context.
  16623. When optional INDENT argument is non-nil, call
  16624. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16625. and INTERACTIVE.
  16626. When `org-return-follows-link' is non-nil and point is on
  16627. a timestamp or a link, call `org-open-at-point'. However, it
  16628. will not happen if point is in a table or on a \"dead\"
  16629. object (e.g., within a comment). In these case, you need to use
  16630. `org-open-at-point' directly."
  16631. (interactive "i\nP\np")
  16632. (let* ((context (if org-return-follows-link (org-element-context)
  16633. (org-element-at-point)))
  16634. (element-type (org-element-type context)))
  16635. (cond
  16636. ;; In a table, call `org-table-next-row'. However, before first
  16637. ;; column or after last one, split the table.
  16638. ((or (and (eq 'table element-type)
  16639. (not (eq 'table.el (org-element-property :type context)))
  16640. (>= (point) (org-element-property :contents-begin context))
  16641. (< (point) (org-element-property :contents-end context)))
  16642. (org-element-lineage context '(table-row table-cell) t))
  16643. (if (or (looking-at-p "[ \t]*$")
  16644. (save-excursion (skip-chars-backward " \t") (bolp)))
  16645. (insert "\n")
  16646. (org-table-justify-field-maybe)
  16647. (call-interactively #'org-table-next-row)))
  16648. ;; On a link or a timestamp, call `org-open-at-point' if
  16649. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16650. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16651. ((and org-return-follows-link
  16652. (or (and (eq 'link element-type)
  16653. ;; Ensure point is not on the white spaces after
  16654. ;; the link.
  16655. (let ((origin (point)))
  16656. (org-with-point-at (org-element-property :end context)
  16657. (skip-chars-backward " \t")
  16658. (> (point) origin))))
  16659. (org-in-regexp org-ts-regexp-both nil t)
  16660. (org-in-regexp org-tsr-regexp-both nil t)
  16661. (org-in-regexp org-link-any-re nil t)))
  16662. (call-interactively #'org-open-at-point))
  16663. ;; Insert newline in heading, but preserve tags.
  16664. ((and (not (bolp))
  16665. (let ((case-fold-search nil))
  16666. (org-match-line org-complex-heading-regexp)))
  16667. ;; At headline. Split line. However, if point is on keyword,
  16668. ;; priority cookie or tags, do not break any of them: add
  16669. ;; a newline after the headline instead.
  16670. (let ((tags-column (and (match-beginning 5)
  16671. (save-excursion (goto-char (match-beginning 5))
  16672. (current-column))))
  16673. (string
  16674. (when (and (match-end 4) (org-point-in-group (point) 4))
  16675. (delete-and-extract-region (point) (match-end 4)))))
  16676. ;; Adjust tag alignment.
  16677. (cond
  16678. ((not (and tags-column string)))
  16679. (org-auto-align-tags (org-align-tags))
  16680. (t (org--align-tags-here tags-column))) ;preserve tags column
  16681. (end-of-line)
  16682. (org-show-entry)
  16683. (org--newline indent arg interactive)
  16684. (when string (save-excursion (insert (org-trim string))))))
  16685. ;; In a list, make sure indenting keeps trailing text within.
  16686. ((and (not (eolp))
  16687. (org-element-lineage context '(item)))
  16688. (let ((trailing-data
  16689. (delete-and-extract-region (point) (line-end-position))))
  16690. (org--newline indent arg interactive)
  16691. (save-excursion (insert trailing-data))))
  16692. (t
  16693. ;; Do not auto-fill when point is in an Org property drawer.
  16694. (let ((auto-fill-function (and (not (org-at-property-p))
  16695. auto-fill-function)))
  16696. (org--newline indent arg interactive))))))
  16697. (defun org-return-and-maybe-indent ()
  16698. "Goto next table row, or insert a newline, maybe indented.
  16699. Call `org-table-next-row' or `org-return', depending on context.
  16700. See the individual commands for more information.
  16701. When inserting a newline, if `org-adapt-indentation' is t:
  16702. indent the line if `electric-indent-mode' is disabled, don't
  16703. indent it if it is enabled."
  16704. (interactive)
  16705. (org-return (not electric-indent-mode)))
  16706. (defun org-ctrl-c-tab (&optional arg)
  16707. "Toggle columns width in a table, or show children.
  16708. Call `org-table-toggle-column-width' if point is in a table.
  16709. Otherwise provide a compact view of the children. ARG is the
  16710. level to hide."
  16711. (interactive "p")
  16712. (cond
  16713. ((org-at-table-p)
  16714. (call-interactively #'org-table-toggle-column-width))
  16715. ((org-before-first-heading-p)
  16716. (save-excursion
  16717. (org-flag-above-first-heading)
  16718. (outline-hide-sublevels (or arg 1))))
  16719. (t
  16720. (outline-hide-subtree)
  16721. (org-show-children arg))))
  16722. (defun org-ctrl-c-star ()
  16723. "Compute table, or change heading status of lines.
  16724. Calls `org-table-recalculate' or `org-toggle-heading',
  16725. depending on context."
  16726. (interactive)
  16727. (cond
  16728. ((org-at-table-p)
  16729. (call-interactively 'org-table-recalculate))
  16730. (t
  16731. ;; Convert all lines in region to list items
  16732. (call-interactively 'org-toggle-heading))))
  16733. (defun org-ctrl-c-minus ()
  16734. "Insert separator line in table or modify bullet status of line.
  16735. Also turns a plain line or a region of lines into list items.
  16736. Calls `org-table-insert-hline', `org-toggle-item', or
  16737. `org-cycle-list-bullet', depending on context."
  16738. (interactive)
  16739. (cond
  16740. ((org-at-table-p)
  16741. (call-interactively 'org-table-insert-hline))
  16742. ((org-region-active-p)
  16743. (call-interactively 'org-toggle-item))
  16744. ((org-in-item-p)
  16745. (call-interactively 'org-cycle-list-bullet))
  16746. (t
  16747. (call-interactively 'org-toggle-item))))
  16748. (defun org-toggle-heading (&optional nstars)
  16749. "Convert headings to normal text, or items or text to headings.
  16750. If there is no active region, only convert the current line.
  16751. With a `\\[universal-argument]' prefix, convert the whole list at
  16752. point into heading.
  16753. In a region:
  16754. - If the first non blank line is a headline, remove the stars
  16755. from all headlines in the region.
  16756. - If it is a normal line, turn each and every normal line (i.e.,
  16757. not an heading or an item) in the region into headings. If you
  16758. want to convert only the first line of this region, use one
  16759. universal prefix argument.
  16760. - If it is a plain list item, turn all plain list items into headings.
  16761. When converting a line into a heading, the number of stars is chosen
  16762. such that the lines become children of the current entry. However,
  16763. when a numeric prefix argument is given, its value determines the
  16764. number of stars to add."
  16765. (interactive "P")
  16766. (let ((skip-blanks
  16767. ;; Return beginning of first non-blank line, starting from
  16768. ;; line at POS.
  16769. (lambda (pos)
  16770. (save-excursion
  16771. (goto-char pos)
  16772. (while (org-at-comment-p) (forward-line))
  16773. (skip-chars-forward " \r\t\n")
  16774. (point-at-bol))))
  16775. beg end toggled)
  16776. ;; Determine boundaries of changes. If a universal prefix has
  16777. ;; been given, put the list in a region. If region ends at a bol,
  16778. ;; do not consider the last line to be in the region.
  16779. (when (and current-prefix-arg (org-at-item-p))
  16780. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16781. (org-mark-element))
  16782. (if (org-region-active-p)
  16783. (setq beg (funcall skip-blanks (region-beginning))
  16784. end (copy-marker (save-excursion
  16785. (goto-char (region-end))
  16786. (if (bolp) (point) (point-at-eol)))))
  16787. (setq beg (funcall skip-blanks (point-at-bol))
  16788. end (copy-marker (point-at-eol))))
  16789. ;; Ensure inline tasks don't count as headings.
  16790. (org-with-limited-levels
  16791. (save-excursion
  16792. (goto-char beg)
  16793. (cond
  16794. ;; Case 1. Started at an heading: de-star headings.
  16795. ((org-at-heading-p)
  16796. (while (< (point) end)
  16797. (when (org-at-heading-p t)
  16798. (looking-at org-outline-regexp) (replace-match "")
  16799. (setq toggled t))
  16800. (forward-line)))
  16801. ;; Case 2. Started at an item: change items into headlines.
  16802. ;; One star will be added by `org-list-to-subtree'.
  16803. ((org-at-item-p)
  16804. (while (< (point) end)
  16805. (when (org-at-item-p)
  16806. ;; Pay attention to cases when region ends before list.
  16807. (let* ((struct (org-list-struct))
  16808. (list-end
  16809. (min (org-list-get-bottom-point struct) (1+ end))))
  16810. (save-restriction
  16811. (narrow-to-region (point) list-end)
  16812. (insert (org-list-to-subtree
  16813. (org-list-to-lisp t)
  16814. (pcase (org-current-level)
  16815. (`nil 1)
  16816. (l (1+ (org-reduced-level l)))))
  16817. "\n")))
  16818. (setq toggled t))
  16819. (forward-line)))
  16820. ;; Case 3. Started at normal text: make every line an heading,
  16821. ;; skipping headlines and items.
  16822. (t (let* ((stars
  16823. (make-string
  16824. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16825. (add-stars
  16826. (cond (nstars "") ; stars from prefix only
  16827. ((equal stars "") "*") ; before first heading
  16828. (org-odd-levels-only "**") ; inside heading, odd
  16829. (t "*"))) ; inside heading, oddeven
  16830. (rpl (concat stars add-stars " "))
  16831. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16832. (while (< (point) (if (equal nstars '(4)) lend end))
  16833. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16834. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16835. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16836. (forward-line)))))))
  16837. (unless toggled (message "Cannot toggle heading from here"))))
  16838. (defun org-meta-return (&optional arg)
  16839. "Insert a new heading or wrap a region in a table.
  16840. Calls `org-insert-heading', `org-insert-item' or
  16841. `org-table-wrap-region', depending on context. When called with
  16842. an argument, unconditionally call `org-insert-heading'."
  16843. (interactive "P")
  16844. (org-check-before-invisible-edit 'insert)
  16845. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16846. (call-interactively (cond (arg #'org-insert-heading)
  16847. ((org-at-table-p) #'org-table-wrap-region)
  16848. ((org-in-item-p) #'org-insert-item)
  16849. (t #'org-insert-heading)))))
  16850. ;;; Menu entries
  16851. (defsubst org-in-subtree-not-table-p ()
  16852. "Are we in a subtree and not in a table?"
  16853. (and (not (org-before-first-heading-p))
  16854. (not (org-at-table-p))))
  16855. ;; Define the Org mode menus
  16856. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16857. `("Org"
  16858. ("Show/Hide"
  16859. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16860. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16861. ["Sparse Tree..." org-sparse-tree t]
  16862. ["Reveal Context" org-reveal t]
  16863. ["Show All" org-show-all t]
  16864. "--"
  16865. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16866. "--"
  16867. ["New Heading" org-insert-heading t]
  16868. ("Navigate Headings"
  16869. ["Up" outline-up-heading t]
  16870. ["Next" outline-next-visible-heading t]
  16871. ["Previous" outline-previous-visible-heading t]
  16872. ["Next Same Level" outline-forward-same-level t]
  16873. ["Previous Same Level" outline-backward-same-level t]
  16874. "--"
  16875. ["Jump" org-goto t])
  16876. ("Edit Structure"
  16877. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16878. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16879. "--"
  16880. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16881. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16882. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16883. "--"
  16884. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16885. "--"
  16886. ["Copy visible text" org-copy-visible t]
  16887. "--"
  16888. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16889. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16890. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16891. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16892. "--"
  16893. ["Sort Region/Children" org-sort t]
  16894. "--"
  16895. ["Convert to odd levels" org-convert-to-odd-levels t]
  16896. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16897. ("Editing"
  16898. ["Emphasis..." org-emphasize t]
  16899. ["Add block structure" org-insert-structure-template t]
  16900. ["Edit Source Example" org-edit-special t]
  16901. "--"
  16902. ["Footnote new/jump" org-footnote-action t]
  16903. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16904. ("Archive"
  16905. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16906. "--"
  16907. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16908. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16909. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16910. "--"
  16911. ("Hyperlinks"
  16912. ["Store Link (Global)" org-store-link t]
  16913. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16914. ["Insert Link" org-insert-link t]
  16915. ["Follow Link" org-open-at-point t]
  16916. "--"
  16917. ["Next link" org-next-link t]
  16918. ["Previous link" org-previous-link t]
  16919. "--"
  16920. ["Descriptive Links"
  16921. org-toggle-link-display
  16922. :style radio
  16923. :selected org-descriptive-links
  16924. ]
  16925. ["Literal Links"
  16926. org-toggle-link-display
  16927. :style radio
  16928. :selected (not org-descriptive-links)])
  16929. "--"
  16930. ("TODO Lists"
  16931. ["TODO/DONE/-" org-todo t]
  16932. ("Select keyword"
  16933. ["Next keyword" org-shiftright (org-at-heading-p)]
  16934. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16935. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16936. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16937. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16938. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16939. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16940. "--"
  16941. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16942. :selected org-enforce-todo-dependencies :style toggle :active t]
  16943. "Settings for tree at point"
  16944. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16945. :selected (org-entry-get nil "ORDERED")
  16946. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16947. ["Do Children parallel" org-toggle-ordered-property :style radio
  16948. :selected (not (org-entry-get nil "ORDERED"))
  16949. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16950. "--"
  16951. ["Set Priority" org-priority t]
  16952. ["Priority Up" org-shiftup t]
  16953. ["Priority Down" org-shiftdown t]
  16954. "--"
  16955. ["Get news from all feeds" org-feed-update-all t]
  16956. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16957. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16958. ("TAGS and Properties"
  16959. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16960. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16961. "--"
  16962. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16963. ["Column view of properties" org-columns t]
  16964. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16965. ("Dates and Scheduling"
  16966. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16967. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16968. ("Change Date"
  16969. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16970. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16971. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16972. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16973. ["Compute Time Range" org-evaluate-time-range t]
  16974. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16975. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16976. "--"
  16977. ["Custom time format" org-toggle-time-stamp-overlays
  16978. :style radio :selected org-display-custom-times]
  16979. "--"
  16980. ["Goto Calendar" org-goto-calendar t]
  16981. ["Date from Calendar" org-date-from-calendar t]
  16982. "--"
  16983. ["Start/Restart Timer" org-timer-start t]
  16984. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16985. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16986. ["Insert Timer String" org-timer t]
  16987. ["Insert Timer Item" org-timer-item t])
  16988. ("Logging work"
  16989. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16990. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16991. ["Clock out" org-clock-out t]
  16992. ["Clock cancel" org-clock-cancel t]
  16993. "--"
  16994. ["Mark as default task" org-clock-mark-default-task t]
  16995. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16996. ["Goto running clock" org-clock-goto t]
  16997. "--"
  16998. ["Display times" org-clock-display t]
  16999. ["Create clock table" org-clock-report t]
  17000. "--"
  17001. ["Record DONE time"
  17002. (progn (setq org-log-done (not org-log-done))
  17003. (message "Switching to %s will %s record a timestamp"
  17004. (car org-done-keywords)
  17005. (if org-log-done "automatically" "not")))
  17006. :style toggle :selected org-log-done])
  17007. "--"
  17008. ["Agenda Command..." org-agenda t]
  17009. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  17010. ("File List for Agenda")
  17011. ("Special views current file"
  17012. ["TODO Tree" org-show-todo-tree t]
  17013. ["Check Deadlines" org-check-deadlines t]
  17014. ["Tags/Property tree" org-match-sparse-tree t])
  17015. "--"
  17016. ["Export/Publish..." org-export-dispatch t]
  17017. ("LaTeX"
  17018. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  17019. :style toggle :selected org-cdlatex-mode]
  17020. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  17021. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  17022. ["Modify math symbol" org-cdlatex-math-modify
  17023. (org-inside-LaTeX-fragment-p)]
  17024. ["Insert citation" org-reftex-citation t])
  17025. "--"
  17026. ("Documentation"
  17027. ["Show Version" org-version t]
  17028. ["Info Documentation" org-info t]
  17029. ["Browse Org News" org-browse-news t])
  17030. ("Customize"
  17031. ["Browse Org Group" org-customize t]
  17032. "--"
  17033. ["Expand This Menu" org-create-customize-menu t])
  17034. ["Send bug report" org-submit-bug-report t]
  17035. "--"
  17036. ("Refresh/Reload"
  17037. ["Refresh setup current buffer" org-mode-restart t]
  17038. ["Reload Org (after update)" org-reload t]
  17039. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  17040. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  17041. '("Table"
  17042. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  17043. ["Next Field" org-cycle (org-at-table-p)]
  17044. ["Previous Field" org-shifttab (org-at-table-p)]
  17045. ["Next Row" org-return (org-at-table-p)]
  17046. "--"
  17047. ["Blank Field" org-table-blank-field (org-at-table-p)]
  17048. ["Edit Field" org-table-edit-field (org-at-table-p)]
  17049. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  17050. "--"
  17051. ("Column"
  17052. ["Move Column Left" org-metaleft (org-at-table-p)]
  17053. ["Move Column Right" org-metaright (org-at-table-p)]
  17054. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  17055. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  17056. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  17057. ("Row"
  17058. ["Move Row Up" org-metaup (org-at-table-p)]
  17059. ["Move Row Down" org-metadown (org-at-table-p)]
  17060. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  17061. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  17062. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  17063. "--"
  17064. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  17065. ("Rectangle"
  17066. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  17067. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  17068. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  17069. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  17070. "--"
  17071. ("Calculate"
  17072. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  17073. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  17074. ["Edit Formulas" org-edit-special (org-at-table-p)]
  17075. "--"
  17076. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  17077. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  17078. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  17079. "--"
  17080. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  17081. "--"
  17082. ["Sum Column/Rectangle" org-table-sum
  17083. (or (org-at-table-p) (org-region-active-p))]
  17084. ["Which Column?" org-table-current-column (org-at-table-p)])
  17085. ["Debug Formulas"
  17086. org-table-toggle-formula-debugger
  17087. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  17088. ["Show Col/Row Numbers"
  17089. org-table-toggle-coordinate-overlays
  17090. :style toggle
  17091. :selected (bound-and-true-p org-table-overlay-coordinates)]
  17092. "--"
  17093. ["Create" org-table-create (not (org-at-table-p))]
  17094. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  17095. ["Import from File" org-table-import (not (org-at-table-p))]
  17096. ["Export to File" org-table-export (org-at-table-p)]
  17097. "--"
  17098. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  17099. "--"
  17100. ("Plot"
  17101. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  17102. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  17103. (defun org-info (&optional node)
  17104. "Read documentation for Org in the info system.
  17105. With optional NODE, go directly to that node."
  17106. (interactive)
  17107. (info (format "(org)%s" (or node ""))))
  17108. (defun org-browse-news ()
  17109. "Browse the news for the latest major release."
  17110. (interactive)
  17111. (browse-url "https://orgmode.org/Changes.html"))
  17112. ;;;###autoload
  17113. (defun org-submit-bug-report ()
  17114. "Submit a bug report on Org via mail.
  17115. Don't hesitate to report any problems or inaccurate documentation.
  17116. If you don't have setup sending mail from (X)Emacs, please copy the
  17117. output buffer into your mail program, as it gives us important
  17118. information about your Org version and configuration."
  17119. (interactive)
  17120. (require 'reporter)
  17121. (defvar reporter-prompt-for-summary-p)
  17122. (org-load-modules-maybe)
  17123. (org-require-autoloaded-modules)
  17124. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  17125. (reporter-submit-bug-report
  17126. "emacs-orgmode@gnu.org"
  17127. (org-version nil 'full)
  17128. (let (list)
  17129. (save-window-excursion
  17130. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  17131. (delete-other-windows)
  17132. (erase-buffer)
  17133. (insert "You are about to submit a bug report to the Org mailing list.
  17134. If your report is about Org installation, please read this section:
  17135. https://orgmode.org/org.html#Installation
  17136. Please read https://orgmode.org/org.html#Feedback on how to make
  17137. a good report, it will help Org contributors fixing your problem.
  17138. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  17139. if the issue you are about to raise has already been dealt with.
  17140. We also would like to add your full Org and Outline configuration
  17141. to the bug report. It will help us debugging the issue.
  17142. *HOWEVER*, some variables you have customized may contain private
  17143. information. The names of customers, colleagues, or friends, might
  17144. appear in the form of file names, tags, todo states or search strings.
  17145. If you answer \"yes\" to the prompt, you might want to check and remove
  17146. such private information before sending the email.")
  17147. (add-text-properties (point-min) (point-max) '(face org-warning))
  17148. (when (yes-or-no-p "Include your Org configuration ")
  17149. (mapatoms
  17150. (lambda (v)
  17151. (and (boundp v)
  17152. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  17153. (or (and (symbol-value v)
  17154. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  17155. (and
  17156. (get v 'custom-type) (get v 'standard-value)
  17157. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  17158. (push v list)))))
  17159. (kill-buffer (get-buffer "*Warn about privacy*"))
  17160. list))
  17161. nil nil
  17162. "Remember to cover the basics, that is, what you expected to happen and
  17163. what in fact did happen. You don't know how to make a good report? See
  17164. https://orgmode.org/manual/Feedback.html#Feedback
  17165. Your bug report will be posted to the Org mailing list.
  17166. ------------------------------------------------------------------------")
  17167. (save-excursion
  17168. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  17169. (replace-match "\\1[BUG] \\3 [\\2]")))))
  17170. (defun org-install-agenda-files-menu ()
  17171. "Install agenda file menu."
  17172. (let ((bl (buffer-list)))
  17173. (save-excursion
  17174. (while bl
  17175. (set-buffer (pop bl))
  17176. (when (derived-mode-p 'org-mode) (setq bl nil)))
  17177. (when (derived-mode-p 'org-mode)
  17178. (easy-menu-change
  17179. '("Org") "File List for Agenda"
  17180. (append
  17181. (list
  17182. ["Edit File List" (org-edit-agenda-file-list) t]
  17183. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  17184. ["Remove Current File from List" org-remove-file t]
  17185. ["Cycle through agenda files" org-cycle-agenda-files t]
  17186. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17187. "--")
  17188. (mapcar 'org-file-menu-entry
  17189. ;; Prevent initialization from failing.
  17190. (ignore-errors (org-agenda-files t)))))))))
  17191. ;;;; Documentation
  17192. (defun org-require-autoloaded-modules ()
  17193. (interactive)
  17194. (mapc #'require
  17195. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17196. org-table org-timer)))
  17197. ;;;###autoload
  17198. (defun org-reload (&optional uncompiled)
  17199. "Reload all Org Lisp files.
  17200. With prefix arg UNCOMPILED, load the uncompiled versions."
  17201. (interactive "P")
  17202. (require 'loadhist)
  17203. (let* ((org-dir (org-find-library-dir "org"))
  17204. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17205. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17206. (remove-re (format "\\`%s\\'"
  17207. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17208. (feats (delete-dups
  17209. (mapcar 'file-name-sans-extension
  17210. (mapcar 'file-name-nondirectory
  17211. (delq nil
  17212. (mapcar 'feature-file
  17213. features))))))
  17214. (lfeat (append
  17215. (sort
  17216. (setq feats
  17217. (delq nil (mapcar
  17218. (lambda (f)
  17219. (if (and (string-match feature-re f)
  17220. (not (string-match remove-re f)))
  17221. f nil))
  17222. feats)))
  17223. 'string-lessp)
  17224. (list "org-version" "org")))
  17225. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17226. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17227. load-uncore load-misses)
  17228. (setq load-misses
  17229. (delq 't
  17230. (mapcar (lambda (f)
  17231. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17232. (and (string= org-dir contrib-dir)
  17233. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17234. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17235. (push f load-uncore)
  17236. 't)
  17237. f))
  17238. lfeat)))
  17239. (when load-uncore
  17240. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17241. (if (> (length load-uncore) 1) "s were" " was")
  17242. (reverse load-uncore)))
  17243. (if load-misses
  17244. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17245. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17246. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17247. ;;;###autoload
  17248. (defun org-customize ()
  17249. "Call the customize function with org as argument."
  17250. (interactive)
  17251. (org-load-modules-maybe)
  17252. (org-require-autoloaded-modules)
  17253. (customize-browse 'org))
  17254. (defun org-create-customize-menu ()
  17255. "Create a full customization menu for Org mode, insert it into the menu."
  17256. (interactive)
  17257. (org-load-modules-maybe)
  17258. (org-require-autoloaded-modules)
  17259. (easy-menu-change
  17260. '("Org") "Customize"
  17261. `(["Browse Org group" org-customize t]
  17262. "--"
  17263. ,(customize-menu-create 'org)
  17264. ["Set" Custom-set t]
  17265. ["Save" Custom-save t]
  17266. ["Reset to Current" Custom-reset-current t]
  17267. ["Reset to Saved" Custom-reset-saved t]
  17268. ["Reset to Standard Settings" Custom-reset-standard t]))
  17269. (message "\"Org\"-menu now contains full customization menu"))
  17270. ;;;; Miscellaneous stuff
  17271. ;;; Generally useful functions
  17272. (defun org-in-clocktable-p ()
  17273. "Check if the cursor is in a clocktable."
  17274. (let ((pos (point)) start)
  17275. (save-excursion
  17276. (end-of-line 1)
  17277. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17278. (setq start (match-beginning 0))
  17279. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17280. (>= (match-end 0) pos)
  17281. start))))
  17282. (defun org-in-verbatim-emphasis ()
  17283. (save-match-data
  17284. (and (org-in-regexp org-verbatim-re 2)
  17285. (>= (point) (match-beginning 3))
  17286. (<= (point) (match-end 4)))))
  17287. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17288. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17289. (if (and marker (marker-buffer marker)
  17290. (buffer-live-p (marker-buffer marker)))
  17291. (progn
  17292. (pop-to-buffer-same-window (marker-buffer marker))
  17293. (when (or (> marker (point-max)) (< marker (point-min)))
  17294. (widen))
  17295. (goto-char marker)
  17296. (org-show-context 'org-goto))
  17297. (if bookmark
  17298. (bookmark-jump bookmark)
  17299. (error "Cannot find location"))))
  17300. (defun org-quote-csv-field (s)
  17301. "Quote field for inclusion in CSV material."
  17302. (if (string-match "[\",]" s)
  17303. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17304. s))
  17305. (defun org-force-self-insert (N)
  17306. "Needed to enforce self-insert under remapping."
  17307. (interactive "p")
  17308. (self-insert-command N))
  17309. (defun org-quote-vert (s)
  17310. "Replace \"|\" with \"\\vert\"."
  17311. (while (string-match "|" s)
  17312. (setq s (replace-match "\\vert" t t s)))
  17313. s)
  17314. (defun org-uuidgen-p (s)
  17315. "Is S an ID created by UUIDGEN?"
  17316. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17317. (defun org-in-src-block-p (&optional inside)
  17318. "Whether point is in a code source block.
  17319. When INSIDE is non-nil, don't consider we are within a source
  17320. block when point is at #+BEGIN_SRC or #+END_SRC."
  17321. (let ((case-fold-search t))
  17322. (or (and (eq (get-char-property (point) 'src-block) t))
  17323. (and (not inside)
  17324. (save-match-data
  17325. (save-excursion
  17326. (beginning-of-line)
  17327. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17328. (defun org-context ()
  17329. "Return a list of contexts of the current cursor position.
  17330. If several contexts apply, all are returned.
  17331. Each context entry is a list with a symbol naming the context, and
  17332. two positions indicating start and end of the context. Possible
  17333. contexts are:
  17334. :headline anywhere in a headline
  17335. :headline-stars on the leading stars in a headline
  17336. :todo-keyword on a TODO keyword (including DONE) in a headline
  17337. :tags on the TAGS in a headline
  17338. :priority on the priority cookie in a headline
  17339. :item on the first line of a plain list item
  17340. :item-bullet on the bullet/number of a plain list item
  17341. :checkbox on the checkbox in a plain list item
  17342. :table in an Org table
  17343. :table-special on a special filed in a table
  17344. :table-table in a table.el table
  17345. :clocktable in a clocktable
  17346. :src-block in a source block
  17347. :link on a hyperlink
  17348. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17349. :latex-fragment on a LaTeX fragment
  17350. :latex-preview on a LaTeX fragment with overlaid preview image
  17351. This function expects the position to be visible because it uses font-lock
  17352. faces as a help to recognize the following contexts: :table-special, :link,
  17353. and :keyword."
  17354. (let* ((f (get-text-property (point) 'face))
  17355. (faces (if (listp f) f (list f)))
  17356. (case-fold-search t)
  17357. (p (point)) clist o)
  17358. ;; First the large context
  17359. (cond
  17360. ((org-at-heading-p t)
  17361. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17362. (when (progn
  17363. (beginning-of-line 1)
  17364. (looking-at org-todo-line-tags-regexp))
  17365. (push (org-point-in-group p 1 :headline-stars) clist)
  17366. (push (org-point-in-group p 2 :todo-keyword) clist)
  17367. (push (org-point-in-group p 4 :tags) clist))
  17368. (goto-char p)
  17369. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17370. (when (looking-at "\\[#[A-Z0-9]\\]")
  17371. (push (org-point-in-group p 0 :priority) clist)))
  17372. ((org-at-item-p)
  17373. (push (org-point-in-group p 2 :item-bullet) clist)
  17374. (push (list :item (point-at-bol)
  17375. (save-excursion (org-end-of-item) (point)))
  17376. clist)
  17377. (and (org-at-item-checkbox-p)
  17378. (push (org-point-in-group p 0 :checkbox) clist)))
  17379. ((org-at-table-p)
  17380. (push (list :table (org-table-begin) (org-table-end)) clist)
  17381. (when (memq 'org-formula faces)
  17382. (push (list :table-special
  17383. (previous-single-property-change p 'face)
  17384. (next-single-property-change p 'face))
  17385. clist)))
  17386. ((org-at-table-p 'any)
  17387. (push (list :table-table) clist)))
  17388. (goto-char p)
  17389. (let ((case-fold-search t))
  17390. ;; New the "medium" contexts: clocktables, source blocks
  17391. (cond ((org-in-clocktable-p)
  17392. (push (list :clocktable
  17393. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17394. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17395. (match-beginning 1))
  17396. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17397. (match-end 0)))
  17398. clist))
  17399. ((org-in-src-block-p)
  17400. (push (list :src-block
  17401. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17402. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17403. (match-beginning 1))
  17404. (and (search-forward "#+END_SRC" nil t)
  17405. (match-beginning 0)))
  17406. clist))))
  17407. (goto-char p)
  17408. ;; Now the small context
  17409. (cond
  17410. ((org-at-timestamp-p)
  17411. (push (org-point-in-group p 0 :timestamp) clist))
  17412. ((memq 'org-link faces)
  17413. (push (list :link
  17414. (previous-single-property-change p 'face)
  17415. (next-single-property-change p 'face))
  17416. clist))
  17417. ((memq 'org-special-keyword faces)
  17418. (push (list :keyword
  17419. (previous-single-property-change p 'face)
  17420. (next-single-property-change p 'face))
  17421. clist))
  17422. ((setq o (cl-some
  17423. (lambda (o)
  17424. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17425. o))
  17426. (overlays-at (point))))
  17427. (push (list :latex-fragment
  17428. (overlay-start o) (overlay-end o))
  17429. clist)
  17430. (push (list :latex-preview
  17431. (overlay-start o) (overlay-end o))
  17432. clist))
  17433. ((org-inside-LaTeX-fragment-p)
  17434. ;; FIXME: positions wrong.
  17435. (push (list :latex-fragment (point) (point)) clist)))
  17436. (setq clist (nreverse (delq nil clist)))
  17437. clist))
  17438. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17439. "Non-nil when point is between matches of START-RE and END-RE.
  17440. Also return a non-nil value when point is on one of the matches.
  17441. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17442. buffer positions. Default values are the positions of headlines
  17443. surrounding the point.
  17444. The functions returns a cons cell whose car (resp. cdr) is the
  17445. position before START-RE (resp. after END-RE)."
  17446. (save-match-data
  17447. (let ((pos (point))
  17448. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17449. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17450. beg end)
  17451. (save-excursion
  17452. ;; Point is on a block when on START-RE or if START-RE can be
  17453. ;; found before it...
  17454. (and (or (org-in-regexp start-re)
  17455. (re-search-backward start-re limit-up t))
  17456. (setq beg (match-beginning 0))
  17457. ;; ... and END-RE after it...
  17458. (goto-char (match-end 0))
  17459. (re-search-forward end-re limit-down t)
  17460. (> (setq end (match-end 0)) pos)
  17461. ;; ... without another START-RE in-between.
  17462. (goto-char (match-beginning 0))
  17463. (not (re-search-backward start-re (1+ beg) t))
  17464. ;; Return value.
  17465. (cons beg end))))))
  17466. (defun org-in-block-p (names)
  17467. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17468. NAMES is a list of strings containing names of blocks.
  17469. Return first block name matched, or nil. Beware that in case of
  17470. nested blocks, the returned name may not belong to the closest
  17471. block from point."
  17472. (save-match-data
  17473. (catch 'exit
  17474. (let ((case-fold-search t)
  17475. (lim-up (save-excursion (outline-previous-heading)))
  17476. (lim-down (save-excursion (outline-next-heading))))
  17477. (dolist (name names)
  17478. (let ((n (regexp-quote name)))
  17479. (when (org-between-regexps-p
  17480. (concat "^[ \t]*#\\+begin_" n)
  17481. (concat "^[ \t]*#\\+end_" n)
  17482. lim-up lim-down)
  17483. (throw 'exit n)))))
  17484. nil)))
  17485. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17486. "Call `multi-occur' with buffers for all agenda files."
  17487. (interactive "sOrg-files matching: ")
  17488. (let* ((files (org-agenda-files))
  17489. (tnames (mapcar #'file-truename files))
  17490. (extra org-agenda-text-search-extra-files))
  17491. (when (eq (car extra) 'agenda-archives)
  17492. (setq extra (cdr extra))
  17493. (setq files (org-add-archive-files files)))
  17494. (dolist (f extra)
  17495. (unless (member (file-truename f) tnames)
  17496. (unless (member f files) (setq files (append files (list f))))
  17497. (setq tnames (append tnames (list (file-truename f))))))
  17498. (multi-occur
  17499. (mapcar (lambda (x)
  17500. (with-current-buffer
  17501. ;; FIXME: Why not just (find-file-noselect x)?
  17502. ;; Is it to avoid the "revert buffer" prompt?
  17503. (or (get-file-buffer x) (find-file-noselect x))
  17504. (widen)
  17505. (current-buffer)))
  17506. files)
  17507. regexp)))
  17508. (add-hook 'occur-mode-find-occurrence-hook
  17509. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17510. (defun org-occur-link-in-agenda-files ()
  17511. "Create a link and search for it in the agendas.
  17512. The link is not stored in `org-stored-links', it is just created
  17513. for the search purpose."
  17514. (interactive)
  17515. (let ((link (condition-case nil
  17516. (org-store-link nil)
  17517. (error "Unable to create a link to here"))))
  17518. (org-occur-in-agenda-files (regexp-quote link))))
  17519. (defun org-back-over-empty-lines ()
  17520. "Move backwards over whitespace, to the beginning of the first empty line.
  17521. Returns the number of empty lines passed."
  17522. (let ((pos (point)))
  17523. (if (cdr (assq 'heading org-blank-before-new-entry))
  17524. (skip-chars-backward " \t\n\r")
  17525. (unless (eobp)
  17526. (forward-line -1)))
  17527. (beginning-of-line 2)
  17528. (goto-char (min (point) pos))
  17529. (count-lines (point) pos)))
  17530. ;;; TODO: Only called once, from ox-odt which should probably use
  17531. ;;; org-export-inline-image-p or something.
  17532. (defun org-file-image-p (file)
  17533. "Return non-nil if FILE is an image."
  17534. (save-match-data
  17535. (string-match (image-file-name-regexp) file)))
  17536. (defun org-get-cursor-date (&optional with-time)
  17537. "Return the date at cursor in as a time.
  17538. This works in the calendar and in the agenda, anywhere else it just
  17539. returns the current time.
  17540. If WITH-TIME is non-nil, returns the time of the event at point (in
  17541. the agenda) or the current time of the day; otherwise returns the
  17542. earliest time on the cursor date that Org treats as that date
  17543. (bearing in mind `org-extend-today-until')."
  17544. (let (date day defd tp hod mod)
  17545. (when with-time
  17546. (setq tp (get-text-property (point) 'time))
  17547. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17548. (setq hod (string-to-number (match-string 1 tp))
  17549. mod (string-to-number (match-string 2 tp))))
  17550. (or tp (let ((now (decode-time)))
  17551. (setq hod (nth 2 now)
  17552. mod (nth 1 now)))))
  17553. (cond
  17554. ((eq major-mode 'calendar-mode)
  17555. (setq date (calendar-cursor-to-date)
  17556. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17557. (nth 1 date) (nth 0 date) (nth 2 date))))
  17558. ((eq major-mode 'org-agenda-mode)
  17559. (setq day (get-text-property (point) 'day))
  17560. (when day
  17561. (setq date (calendar-gregorian-from-absolute day)
  17562. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17563. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17564. (or defd (current-time))))
  17565. (defun org-mark-subtree (&optional up)
  17566. "Mark the current subtree.
  17567. This puts point at the start of the current subtree, and mark at
  17568. the end. If a numeric prefix UP is given, move up into the
  17569. hierarchy of headlines by UP levels before marking the subtree."
  17570. (interactive "P")
  17571. (org-with-limited-levels
  17572. (cond ((org-at-heading-p) (beginning-of-line))
  17573. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17574. (t (outline-previous-visible-heading 1))))
  17575. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17576. (if (called-interactively-p 'any)
  17577. (call-interactively 'org-mark-element)
  17578. (org-mark-element)))
  17579. ;;; Indentation
  17580. (defvar org-element-greater-elements)
  17581. (defun org--get-expected-indentation (element contentsp)
  17582. "Expected indentation column for current line, according to ELEMENT.
  17583. ELEMENT is an element containing point. CONTENTSP is non-nil
  17584. when indentation is to be computed according to contents of
  17585. ELEMENT."
  17586. (let ((type (org-element-type element))
  17587. (start (org-element-property :begin element))
  17588. (post-affiliated (org-element-property :post-affiliated element)))
  17589. (org-with-wide-buffer
  17590. (cond
  17591. (contentsp
  17592. (cl-case type
  17593. ((diary-sexp footnote-definition) 0)
  17594. (section
  17595. (org--get-expected-indentation
  17596. (org-element-property :parent element)
  17597. t))
  17598. ((headline inlinetask nil)
  17599. (if (not org-adapt-indentation) 0
  17600. (let ((level (org-current-level)))
  17601. (if level (1+ level) 0))))
  17602. ((item plain-list) (org-list-item-body-column post-affiliated))
  17603. (t
  17604. (goto-char start)
  17605. (current-indentation))))
  17606. ((memq type '(headline inlinetask nil))
  17607. (if (org-match-line "[ \t]*$")
  17608. (org--get-expected-indentation element t)
  17609. 0))
  17610. ((memq type '(diary-sexp footnote-definition)) 0)
  17611. ;; First paragraph of a footnote definition or an item.
  17612. ;; Indent like parent.
  17613. ((< (line-beginning-position) start)
  17614. (org--get-expected-indentation
  17615. (org-element-property :parent element) t))
  17616. ;; At first line: indent according to previous sibling, if any,
  17617. ;; ignoring footnote definitions and inline tasks, or parent's
  17618. ;; contents.
  17619. ((and ( = (line-beginning-position) start)
  17620. (eq org-adapt-indentation t))
  17621. (catch 'exit
  17622. (while t
  17623. (if (= (point-min) start) (throw 'exit 0)
  17624. (goto-char (1- start))
  17625. (let* ((previous (org-element-at-point))
  17626. (parent previous))
  17627. (while (and parent (<= (org-element-property :end parent) start))
  17628. (setq previous parent
  17629. parent (org-element-property :parent parent)))
  17630. (cond
  17631. ((not previous) (throw 'exit 0))
  17632. ((> (org-element-property :end previous) start)
  17633. (throw 'exit (org--get-expected-indentation previous t)))
  17634. ((memq (org-element-type previous)
  17635. '(footnote-definition inlinetask))
  17636. (setq start (org-element-property :begin previous)))
  17637. (t (goto-char (org-element-property :begin previous))
  17638. (throw 'exit
  17639. (if (bolp) (current-indentation)
  17640. ;; At first paragraph in an item or
  17641. ;; a footnote definition.
  17642. (org--get-expected-indentation
  17643. (org-element-property :parent previous) t))))))))))
  17644. ;; Otherwise, move to the first non-blank line above.
  17645. (t
  17646. (beginning-of-line)
  17647. (let ((pos (point)))
  17648. (skip-chars-backward " \r\t\n")
  17649. (cond
  17650. ;; Two blank lines end a footnote definition or a plain
  17651. ;; list. When we indent an empty line after them, the
  17652. ;; containing list or footnote definition is over, so it
  17653. ;; qualifies as a previous sibling. Therefore, we indent
  17654. ;; like its first line.
  17655. ((and (memq type '(footnote-definition plain-list))
  17656. (> (count-lines (point) pos) 2))
  17657. (goto-char start)
  17658. (current-indentation))
  17659. ;; Line above is the first one of a paragraph at the
  17660. ;; beginning of an item or a footnote definition. Indent
  17661. ;; like parent.
  17662. ((< (line-beginning-position) start)
  17663. (org--get-expected-indentation
  17664. (org-element-property :parent element) t))
  17665. ;; Line above is the beginning of an element, i.e., point
  17666. ;; was originally on the blank lines between element's start
  17667. ;; and contents.
  17668. ((= (line-beginning-position) post-affiliated)
  17669. (org--get-expected-indentation element t))
  17670. ;; POS is after contents in a greater element. Indent like
  17671. ;; the beginning of the element.
  17672. ((and (memq type org-element-greater-elements)
  17673. (let ((cend (org-element-property :contents-end element)))
  17674. (and cend (<= cend pos))))
  17675. ;; As a special case, if point is at the end of a footnote
  17676. ;; definition or an item, indent like the very last element
  17677. ;; within. If that last element is an item, indent like
  17678. ;; its contents.
  17679. (if (memq type '(footnote-definition item plain-list))
  17680. (let ((last (org-element-at-point)))
  17681. (goto-char pos)
  17682. (org--get-expected-indentation
  17683. last (eq (org-element-type last) 'item)))
  17684. (goto-char start)
  17685. (current-indentation)))
  17686. ;; In any other case, indent like the current line.
  17687. (t (current-indentation)))))
  17688. ;; Finally, no indentation is needed, fall back to 0.
  17689. (t (current-indentation))))))
  17690. (defun org--align-node-property ()
  17691. "Align node property at point.
  17692. Alignment is done according to `org-property-format', which see."
  17693. (when (save-excursion
  17694. (beginning-of-line)
  17695. (looking-at org-property-re))
  17696. (combine-change-calls (match-beginning 0) (match-end 0)
  17697. (let ((newtext (concat (match-string 4)
  17698. (org-trim
  17699. (format org-property-format (match-string 1) (match-string 3))))))
  17700. (setf (buffer-substring (match-beginning 0) (match-end 0)) newtext)))))
  17701. (defun org-indent-line ()
  17702. "Indent line depending on context.
  17703. Indentation is done according to the following rules:
  17704. - Footnote definitions, diary sexps, headlines and inline tasks
  17705. have to start at column 0.
  17706. - On the very first line of an element, consider, in order, the
  17707. next rules until one matches:
  17708. 1. If there's a sibling element before, ignoring footnote
  17709. definitions and inline tasks, indent like its first line.
  17710. 2. If element has a parent, indent like its contents. More
  17711. precisely, if parent is an item, indent after the bullet.
  17712. Else, indent like parent's first line.
  17713. 3. Otherwise, indent relatively to current level, if
  17714. `org-adapt-indentation' is t, or to left margin.
  17715. - On a blank line at the end of an element, indent according to
  17716. the type of the element. More precisely
  17717. 1. If element is a plain list, an item, or a footnote
  17718. definition, indent like the very last element within.
  17719. 2. If element is a paragraph, indent like its last non blank
  17720. line.
  17721. 3. Otherwise, indent like its very first line.
  17722. - In the code part of a source block, use language major mode
  17723. to indent current line if `org-src-tab-acts-natively' is
  17724. non-nil. If it is nil, do nothing.
  17725. - Otherwise, indent like the first non-blank line above.
  17726. The function doesn't indent an item as it could break the whole
  17727. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17728. `\\[org-shiftmetaright]'.
  17729. Also align node properties according to `org-property-format'."
  17730. (interactive)
  17731. (unless (or (org-at-heading-p)
  17732. (and (eq org-adapt-indentation 'headline-data)
  17733. (not (or (org-at-clock-log-p)
  17734. (org-at-planning-p)))
  17735. (save-excursion
  17736. (beginning-of-line 1)
  17737. (skip-chars-backward "\n")
  17738. (or (org-at-heading-p)
  17739. (looking-back ":END:.*" (point-at-bol))))))
  17740. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  17741. (type (org-element-type element)))
  17742. (cond ((and (memq type '(plain-list item))
  17743. (= (line-beginning-position)
  17744. (org-element-property :post-affiliated element)))
  17745. nil)
  17746. ((and (eq type 'latex-environment)
  17747. (>= (point) (org-element-property :post-affiliated element))
  17748. (< (point)
  17749. (org-with-point-at (org-element-property :end element)
  17750. (skip-chars-backward " \t\n")
  17751. (line-beginning-position 2))))
  17752. nil)
  17753. ((and (eq type 'src-block)
  17754. org-src-tab-acts-natively
  17755. (> (line-beginning-position)
  17756. (org-element-property :post-affiliated element))
  17757. (< (line-beginning-position)
  17758. (org-with-point-at (org-element-property :end element)
  17759. (skip-chars-backward " \t\n")
  17760. (line-beginning-position))))
  17761. ;; At the beginning of a blank line, do some preindentation. This
  17762. ;; signals org-src--edit-element to preserve the indentation on exit
  17763. (when (and (looking-at-p "^[[:space:]]*$")
  17764. (not org-src-preserve-indentation))
  17765. (let ((element (org-element-at-point))
  17766. block-content-ind some-ind)
  17767. (org-with-point-at (org-element-property :begin element)
  17768. (setq block-content-ind (+ (current-indentation)
  17769. org-edit-src-content-indentation))
  17770. (forward-line)
  17771. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17772. (backward-char)
  17773. (setq some-ind (if (looking-at-p "#\\+end_src")
  17774. block-content-ind (current-indentation))))
  17775. (indent-line-to (min block-content-ind some-ind))))
  17776. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17777. (t
  17778. (let ((column (org--get-expected-indentation element nil)))
  17779. ;; Preserve current column.
  17780. (if (<= (current-column) (current-indentation))
  17781. (indent-line-to column)
  17782. (save-excursion (indent-line-to column))))
  17783. ;; Align node property. Also preserve current column.
  17784. (when (eq type 'node-property)
  17785. (let ((column (current-column)))
  17786. (org--align-node-property)
  17787. (org-move-to-column column))))))))
  17788. (defun org-indent-region (start end)
  17789. "Indent each non-blank line in the region.
  17790. Called from a program, START and END specify the region to
  17791. indent. The function will not indent contents of example blocks,
  17792. verse blocks and export blocks as leading white spaces are
  17793. assumed to be significant there."
  17794. (interactive "r")
  17795. (save-excursion
  17796. (goto-char start)
  17797. (skip-chars-forward " \r\t\n")
  17798. (unless (eobp) (beginning-of-line))
  17799. (let ((indent-to
  17800. (lambda (ind pos)
  17801. ;; Set IND as indentation for all lines between point and
  17802. ;; POS. Blank lines are ignored. Leave point after POS
  17803. ;; once done.
  17804. (let ((limit (copy-marker pos)))
  17805. (while (< (point) limit)
  17806. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17807. (forward-line))
  17808. (set-marker limit nil))))
  17809. (end (copy-marker end)))
  17810. (while (< (point) end)
  17811. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17812. (let* ((element (org-element-at-point-no-context))
  17813. (type (org-element-type element))
  17814. (element-end (copy-marker (org-element-property :end element)))
  17815. (ind (org--get-expected-indentation element nil)))
  17816. (cond
  17817. ;; Element indented as a single block. Example blocks
  17818. ;; preserving indentation are a special case since the
  17819. ;; "contents" must not be indented whereas the block
  17820. ;; boundaries can.
  17821. ((or (memq type '(export-block latex-environment))
  17822. (and (eq type 'example-block)
  17823. (not
  17824. (or org-src-preserve-indentation
  17825. (org-element-property :preserve-indent element)))))
  17826. (let ((offset (- ind (current-indentation))))
  17827. (unless (zerop offset)
  17828. (indent-rigidly (org-element-property :begin element)
  17829. (org-element-property :end element)
  17830. offset)))
  17831. (goto-char element-end))
  17832. ;; Elements indented line wise. Be sure to exclude
  17833. ;; example blocks (preserving indentation) and source
  17834. ;; blocks from this category as they are treated
  17835. ;; specially later.
  17836. ((or (memq type '(paragraph table table-row))
  17837. (not (or (org-element-property :contents-begin element)
  17838. (memq type '(example-block src-block)))))
  17839. (when (eq type 'node-property)
  17840. (org--align-node-property)
  17841. (beginning-of-line))
  17842. (funcall indent-to ind (min element-end end)))
  17843. ;; Elements consisting of three parts: before the
  17844. ;; contents, the contents, and after the contents. The
  17845. ;; contents are treated specially, according to the
  17846. ;; element type, or not indented at all. Other parts are
  17847. ;; indented as a single block.
  17848. (t
  17849. (let* ((post (copy-marker
  17850. (org-element-property :post-affiliated element)))
  17851. (cbeg
  17852. (copy-marker
  17853. (cond
  17854. ((not (org-element-property :contents-begin element))
  17855. ;; Fake contents for source blocks.
  17856. (org-with-wide-buffer
  17857. (goto-char post)
  17858. (line-beginning-position 2)))
  17859. ((memq type '(footnote-definition item plain-list))
  17860. ;; Contents in these elements could start on
  17861. ;; the same line as the beginning of the
  17862. ;; element. Make sure we start indenting
  17863. ;; from the second line.
  17864. (org-with-wide-buffer
  17865. (goto-char post)
  17866. (end-of-line)
  17867. (skip-chars-forward " \r\t\n")
  17868. (if (eobp) (point) (line-beginning-position))))
  17869. (t (org-element-property :contents-begin element)))))
  17870. (cend (copy-marker
  17871. (or (org-element-property :contents-end element)
  17872. ;; Fake contents for source blocks.
  17873. (org-with-wide-buffer
  17874. (goto-char element-end)
  17875. (skip-chars-backward " \r\t\n")
  17876. (line-beginning-position)))
  17877. t)))
  17878. ;; Do not change items indentation individually as it
  17879. ;; might break the list as a whole. On the other
  17880. ;; hand, when at a plain list, indent it as a whole.
  17881. (cond ((eq type 'plain-list)
  17882. (let ((offset (- ind (current-indentation))))
  17883. (unless (zerop offset)
  17884. (indent-rigidly (org-element-property :begin element)
  17885. (org-element-property :end element)
  17886. offset))
  17887. (goto-char cbeg)))
  17888. ((eq type 'item) (goto-char cbeg))
  17889. (t (funcall indent-to ind (min cbeg end))))
  17890. (when (< (point) end)
  17891. (cl-case type
  17892. ((example-block verse-block))
  17893. (src-block
  17894. ;; In a source block, indent source code
  17895. ;; according to language major mode, but only if
  17896. ;; `org-src-tab-acts-natively' is non-nil.
  17897. (when (and (< (point) end) org-src-tab-acts-natively)
  17898. (ignore-errors
  17899. (org-babel-do-in-edit-buffer
  17900. (indent-region (point-min) (point-max))))))
  17901. (t (org-indent-region (point) (min cend end))))
  17902. (goto-char (min cend end))
  17903. (when (< (point) end)
  17904. (funcall indent-to ind (min element-end end))))
  17905. (set-marker post nil)
  17906. (set-marker cbeg nil)
  17907. (set-marker cend nil))))
  17908. (set-marker element-end nil))))
  17909. (set-marker end nil))))
  17910. (defun org-indent-drawer ()
  17911. "Indent the drawer at point."
  17912. (interactive)
  17913. (unless (save-excursion
  17914. (beginning-of-line)
  17915. (looking-at-p org-drawer-regexp))
  17916. (user-error "Not at a drawer"))
  17917. (let ((element (org-element-at-point-no-context)))
  17918. (unless (memq (org-element-type element) '(drawer property-drawer))
  17919. (user-error "Not at a drawer"))
  17920. (org-with-wide-buffer
  17921. (org-indent-region (org-element-property :begin element)
  17922. (org-element-property :end element))))
  17923. (message "Drawer at point indented"))
  17924. (defun org-indent-block ()
  17925. "Indent the block at point."
  17926. (interactive)
  17927. (unless (save-excursion
  17928. (beginning-of-line)
  17929. (let ((case-fold-search t))
  17930. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17931. (user-error "Not at a block"))
  17932. (let ((element (org-element-at-point-no-context)))
  17933. (unless (memq (org-element-type element)
  17934. '(comment-block center-block dynamic-block example-block
  17935. export-block quote-block special-block
  17936. src-block verse-block))
  17937. (user-error "Not at a block"))
  17938. (org-with-wide-buffer
  17939. (org-indent-region (org-element-property :begin element)
  17940. (org-element-property :end element))))
  17941. (message "Block at point indented"))
  17942. ;;; Filling
  17943. ;; We use our own fill-paragraph and auto-fill functions.
  17944. ;; `org-fill-paragraph' relies on adaptive filling and context
  17945. ;; checking. Appropriate `fill-prefix' is computed with
  17946. ;; `org-adaptive-fill-function'.
  17947. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17948. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17949. ;; `org-adaptive-fill-function' value. Internally,
  17950. ;; `org-comment-line-break-function' breaks the line.
  17951. ;; `org-setup-filling' installs filling and auto-filling related
  17952. ;; variables during `org-mode' initialization.
  17953. (defun org-setup-filling ()
  17954. (require 'org-element)
  17955. ;; Prevent auto-fill from inserting unwanted new items.
  17956. (when (boundp 'fill-nobreak-predicate)
  17957. (setq-local
  17958. fill-nobreak-predicate
  17959. (org-uniquify
  17960. (append fill-nobreak-predicate
  17961. '(org-fill-line-break-nobreak-p
  17962. org-fill-n-macro-as-item-nobreak-p
  17963. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17964. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17965. (setq-local paragraph-start paragraph-ending)
  17966. (setq-local paragraph-separate paragraph-ending))
  17967. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17968. (setq-local auto-fill-inhibit-regexp nil)
  17969. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17970. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17971. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17972. (defun org-fill-line-break-nobreak-p ()
  17973. "Non-nil when a new line at point would create an Org line break."
  17974. (save-excursion
  17975. (skip-chars-backward " \t")
  17976. (skip-chars-backward "\\\\")
  17977. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17978. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17979. "Non-nil when a new line at point would split a timestamp."
  17980. (and (org-at-timestamp-p 'lax)
  17981. (not (looking-at org-ts-regexp-both))))
  17982. (defun org-fill-n-macro-as-item-nobreak-p ()
  17983. "Non-nil when a new line at point would create a new list."
  17984. ;; During export, a "n" macro followed by a dot or a closing
  17985. ;; parenthesis can end up being parsed as a new list item.
  17986. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17987. (defun org-adaptive-fill-function ()
  17988. "Compute a fill prefix for the current line.
  17989. Return fill prefix, as a string, or nil if current line isn't
  17990. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17991. matches in paragraphs or comments, use it."
  17992. (org-with-wide-buffer
  17993. (unless (org-at-heading-p)
  17994. (let* ((p (line-beginning-position))
  17995. (element (save-excursion
  17996. (beginning-of-line)
  17997. (org-element-at-point)))
  17998. (type (org-element-type element))
  17999. (post-affiliated (org-element-property :post-affiliated element)))
  18000. (unless (< p post-affiliated)
  18001. (cl-case type
  18002. (comment
  18003. (save-excursion
  18004. (beginning-of-line)
  18005. (looking-at "[ \t]*")
  18006. (concat (match-string 0) "# ")))
  18007. (footnote-definition "")
  18008. ((item plain-list)
  18009. (make-string (org-list-item-body-column post-affiliated) ?\s))
  18010. (paragraph
  18011. ;; Fill prefix is usually the same as the current line,
  18012. ;; unless the paragraph is at the beginning of an item.
  18013. (let ((parent (org-element-property :parent element)))
  18014. (save-excursion
  18015. (beginning-of-line)
  18016. (cond ((eq (org-element-type parent) 'item)
  18017. (make-string (org-list-item-body-column
  18018. (org-element-property :begin parent))
  18019. ?\s))
  18020. ((and adaptive-fill-regexp
  18021. ;; Locally disable
  18022. ;; `adaptive-fill-function' to let
  18023. ;; `fill-context-prefix' handle
  18024. ;; `adaptive-fill-regexp' variable.
  18025. (let (adaptive-fill-function)
  18026. (fill-context-prefix
  18027. post-affiliated
  18028. (org-element-property :end element)))))
  18029. ((looking-at "[ \t]+") (match-string 0))
  18030. (t "")))))
  18031. (comment-block
  18032. ;; Only fill contents if P is within block boundaries.
  18033. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  18034. (forward-line)
  18035. (point)))
  18036. (cend (save-excursion
  18037. (goto-char (org-element-property :end element))
  18038. (skip-chars-backward " \r\t\n")
  18039. (line-beginning-position))))
  18040. (when (and (>= p cbeg) (< p cend))
  18041. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  18042. (match-string 0)
  18043. ""))))))))))
  18044. (defun org-fill-element (&optional justify)
  18045. "Fill element at point, when applicable.
  18046. This function only applies to comment blocks, comments, example
  18047. blocks and paragraphs. Also, as a special case, re-align table
  18048. when point is at one.
  18049. If JUSTIFY is non-nil (interactively, with prefix argument),
  18050. justify as well. If `sentence-end-double-space' is non-nil, then
  18051. period followed by one space does not end a sentence, so don't
  18052. break a line there. The variable `fill-column' controls the
  18053. width for filling.
  18054. For convenience, when point is at a plain list, an item or
  18055. a footnote definition, try to fill the first paragraph within."
  18056. (with-syntax-table org-mode-transpose-word-syntax-table
  18057. ;; Move to end of line in order to get the first paragraph within
  18058. ;; a plain list or a footnote definition.
  18059. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  18060. ;; First check if point is in a blank line at the beginning of
  18061. ;; the buffer. In that case, ignore filling.
  18062. (cl-case (org-element-type element)
  18063. ;; Use major mode filling function is source blocks.
  18064. (src-block (org-babel-do-in-edit-buffer
  18065. (push-mark (point-min))
  18066. (goto-char (point-max))
  18067. (setq mark-active t)
  18068. (funcall-interactively #'fill-paragraph justify 'region)))
  18069. ;; Align Org tables, leave table.el tables as-is.
  18070. (table-row (org-table-align) t)
  18071. (table
  18072. (when (eq (org-element-property :type element) 'org)
  18073. (save-excursion
  18074. (goto-char (org-element-property :post-affiliated element))
  18075. (org-table-align)))
  18076. t)
  18077. (paragraph
  18078. ;; Paragraphs may contain `line-break' type objects.
  18079. (let ((beg (max (point-min)
  18080. (org-element-property :contents-begin element)))
  18081. (end (min (point-max)
  18082. (org-element-property :contents-end element))))
  18083. ;; Do nothing if point is at an affiliated keyword.
  18084. (if (< (line-end-position) beg) t
  18085. ;; Fill paragraph, taking line breaks into account.
  18086. (save-excursion
  18087. (goto-char beg)
  18088. (let ((cuts (list beg)))
  18089. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  18090. (when (eq 'line-break
  18091. (org-element-type
  18092. (save-excursion (backward-char)
  18093. (org-element-context))))
  18094. (push (point) cuts)))
  18095. (dolist (c (delq end cuts))
  18096. (fill-region-as-paragraph c end justify)
  18097. (setq end c))))
  18098. t)))
  18099. ;; Contents of `comment-block' type elements should be
  18100. ;; filled as plain text, but only if point is within block
  18101. ;; markers.
  18102. (comment-block
  18103. (let* ((case-fold-search t)
  18104. (beg (save-excursion
  18105. (goto-char (org-element-property :begin element))
  18106. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  18107. (forward-line)
  18108. (point)))
  18109. (end (save-excursion
  18110. (goto-char (org-element-property :end element))
  18111. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  18112. (line-beginning-position))))
  18113. (if (or (< (point) beg) (> (point) end)) t
  18114. (fill-region-as-paragraph
  18115. (save-excursion (end-of-line)
  18116. (re-search-backward "^[ \t]*$" beg 'move)
  18117. (line-beginning-position))
  18118. (save-excursion (beginning-of-line)
  18119. (re-search-forward "^[ \t]*$" end 'move)
  18120. (line-beginning-position))
  18121. justify))))
  18122. ;; Fill comments.
  18123. (comment
  18124. (let ((begin (org-element-property :post-affiliated element))
  18125. (end (org-element-property :end element)))
  18126. (when (and (>= (point) begin) (<= (point) end))
  18127. (let ((begin (save-excursion
  18128. (end-of-line)
  18129. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  18130. (progn (forward-line) (point))
  18131. begin)))
  18132. (end (save-excursion
  18133. (end-of-line)
  18134. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  18135. (1- (line-beginning-position))
  18136. (skip-chars-backward " \r\t\n")
  18137. (line-end-position)))))
  18138. ;; Do not fill comments when at a blank line.
  18139. (when (> end begin)
  18140. (let ((fill-prefix
  18141. (save-excursion
  18142. (beginning-of-line)
  18143. (looking-at "[ \t]*#")
  18144. (let ((comment-prefix (match-string 0)))
  18145. (goto-char (match-end 0))
  18146. (if (looking-at adaptive-fill-regexp)
  18147. (concat comment-prefix (match-string 0))
  18148. (concat comment-prefix " "))))))
  18149. (save-excursion
  18150. (fill-region-as-paragraph begin end justify))))))
  18151. t))
  18152. ;; Ignore every other element.
  18153. (otherwise t)))))
  18154. (defun org-fill-paragraph (&optional justify region)
  18155. "Fill element at point, when applicable.
  18156. This function only applies to comment blocks, comments, example
  18157. blocks and paragraphs. Also, as a special case, re-align table
  18158. when point is at one.
  18159. For convenience, when point is at a plain list, an item or
  18160. a footnote definition, try to fill the first paragraph within.
  18161. If JUSTIFY is non-nil (interactively, with prefix argument),
  18162. justify as well. If `sentence-end-double-space' is non-nil, then
  18163. period followed by one space does not end a sentence, so don't
  18164. break a line there. The variable `fill-column' controls the
  18165. width for filling.
  18166. The REGION argument is non-nil if called interactively; in that
  18167. case, if Transient Mark mode is enabled and the mark is active,
  18168. fill each of the elements in the active region, instead of just
  18169. filling the current element."
  18170. (interactive (progn
  18171. (barf-if-buffer-read-only)
  18172. (list (when current-prefix-arg 'full) t)))
  18173. (let ((hash (and (not (buffer-modified-p))
  18174. (org-buffer-hash))))
  18175. (cond
  18176. ((and region transient-mark-mode mark-active
  18177. (not (eq (region-beginning) (region-end))))
  18178. (let ((origin (point-marker))
  18179. (start (region-beginning)))
  18180. (unwind-protect
  18181. (progn
  18182. (goto-char (region-end))
  18183. (skip-chars-backward " \t\n")
  18184. (while (> (point) start)
  18185. (org-fill-element justify)
  18186. (org-backward-paragraph)))
  18187. (goto-char origin)
  18188. (set-marker origin nil))))
  18189. (t
  18190. (save-excursion
  18191. (when (org-match-line "[ \t]*$")
  18192. (skip-chars-forward " \t\n"))
  18193. (org-fill-element justify))))
  18194. ;; If we didn't change anything in the buffer (and the buffer was
  18195. ;; previously unmodified), then flip the modification status back
  18196. ;; to "unchanged".
  18197. (when (and hash (equal hash (org-buffer-hash)))
  18198. (set-buffer-modified-p nil))
  18199. ;; Return non-nil.
  18200. t))
  18201. (defun org-auto-fill-function ()
  18202. "Auto-fill function."
  18203. ;; Check if auto-filling is meaningful.
  18204. (let ((fc (current-fill-column)))
  18205. (when (and fc (> (current-column) fc))
  18206. (let* ((fill-prefix (org-adaptive-fill-function))
  18207. ;; Enforce empty fill prefix, if required. Otherwise, it
  18208. ;; will be computed again.
  18209. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18210. (when fill-prefix (do-auto-fill))))))
  18211. (defun org-comment-line-break-function (&optional soft)
  18212. "Break line at point and indent, continuing comment if within one.
  18213. The inserted newline is marked hard if variable
  18214. `use-hard-newlines' is true, unless optional argument SOFT is
  18215. non-nil."
  18216. (if soft (insert-and-inherit ?\n) (newline 1))
  18217. (save-excursion (forward-char -1) (delete-horizontal-space))
  18218. (delete-horizontal-space)
  18219. (indent-to-left-margin)
  18220. (insert-before-markers-and-inherit fill-prefix))
  18221. ;;; Fixed Width Areas
  18222. (defun org-toggle-fixed-width ()
  18223. "Toggle fixed-width markup.
  18224. Add or remove fixed-width markup on current line, whenever it
  18225. makes sense. Return an error otherwise.
  18226. If a region is active and if it contains only fixed-width areas
  18227. or blank lines, remove all fixed-width markup in it. If the
  18228. region contains anything else, convert all non-fixed-width lines
  18229. to fixed-width ones.
  18230. Blank lines at the end of the region are ignored unless the
  18231. region only contains such lines."
  18232. (interactive)
  18233. (if (not (org-region-active-p))
  18234. ;; No region:
  18235. ;;
  18236. ;; Remove fixed width marker only in a fixed-with element.
  18237. ;;
  18238. ;; Add fixed width maker in paragraphs, in blank lines after
  18239. ;; elements or at the beginning of a headline or an inlinetask,
  18240. ;; and before any one-line elements (e.g., a clock).
  18241. (progn
  18242. (beginning-of-line)
  18243. (let* ((element (org-element-at-point))
  18244. (type (org-element-type element)))
  18245. (cond
  18246. ((and (eq type 'fixed-width)
  18247. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18248. (replace-match
  18249. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18250. ((and (memq type '(babel-call clock comment diary-sexp headline
  18251. horizontal-rule keyword paragraph
  18252. planning))
  18253. (<= (org-element-property :post-affiliated element) (point)))
  18254. (skip-chars-forward " \t")
  18255. (insert ": "))
  18256. ((and (looking-at-p "[ \t]*$")
  18257. (or (eq type 'inlinetask)
  18258. (save-excursion
  18259. (skip-chars-forward " \r\t\n")
  18260. (<= (org-element-property :end element) (point)))))
  18261. (delete-region (point) (line-end-position))
  18262. (org-indent-line)
  18263. (insert ": "))
  18264. (t (user-error "Cannot insert a fixed-width line here")))))
  18265. ;; Region active.
  18266. (let* ((begin (save-excursion
  18267. (goto-char (region-beginning))
  18268. (line-beginning-position)))
  18269. (end (copy-marker
  18270. (save-excursion
  18271. (goto-char (region-end))
  18272. (unless (eolp) (beginning-of-line))
  18273. (if (save-excursion (re-search-backward "\\S-" begin t))
  18274. (progn (skip-chars-backward " \r\t\n") (point))
  18275. (point)))))
  18276. (all-fixed-width-p
  18277. (catch 'not-all-p
  18278. (save-excursion
  18279. (goto-char begin)
  18280. (skip-chars-forward " \r\t\n")
  18281. (when (eobp) (throw 'not-all-p nil))
  18282. (while (< (point) end)
  18283. (let ((element (org-element-at-point)))
  18284. (if (eq (org-element-type element) 'fixed-width)
  18285. (goto-char (org-element-property :end element))
  18286. (throw 'not-all-p nil))))
  18287. t))))
  18288. (if all-fixed-width-p
  18289. (save-excursion
  18290. (goto-char begin)
  18291. (while (< (point) end)
  18292. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18293. (replace-match
  18294. "" nil nil nil
  18295. (if (= (line-end-position) (match-end 0)) 0 1)))
  18296. (forward-line)))
  18297. (let ((min-ind (point-max)))
  18298. ;; Find minimum indentation across all lines.
  18299. (save-excursion
  18300. (goto-char begin)
  18301. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18302. (setq min-ind 0)
  18303. (catch 'zerop
  18304. (while (< (point) end)
  18305. (unless (looking-at-p "[ \t]*$")
  18306. (let ((ind (current-indentation)))
  18307. (setq min-ind (min min-ind ind))
  18308. (when (zerop ind) (throw 'zerop t))))
  18309. (forward-line)))))
  18310. ;; Loop over all lines and add fixed-width markup everywhere
  18311. ;; but in fixed-width lines.
  18312. (save-excursion
  18313. (goto-char begin)
  18314. (while (< (point) end)
  18315. (cond
  18316. ((org-at-heading-p)
  18317. (insert ": ")
  18318. (forward-line)
  18319. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18320. (insert ":")
  18321. (forward-line)))
  18322. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18323. (let* ((element (org-element-at-point))
  18324. (element-end (org-element-property :end element)))
  18325. (if (eq (org-element-type element) 'fixed-width)
  18326. (progn (goto-char element-end)
  18327. (skip-chars-backward " \r\t\n")
  18328. (forward-line))
  18329. (let ((limit (min end element-end)))
  18330. (while (< (point) limit)
  18331. (org-move-to-column min-ind t)
  18332. (insert ": ")
  18333. (forward-line))))))
  18334. (t
  18335. (org-move-to-column min-ind t)
  18336. (insert ": ")
  18337. (forward-line)))))))
  18338. (set-marker end nil))))
  18339. ;;; Blocks
  18340. (defun org-block-map (function &optional start end)
  18341. "Call FUNCTION at the head of all source blocks in the current buffer.
  18342. Optional arguments START and END can be used to limit the range."
  18343. (let ((start (or start (point-min)))
  18344. (end (or end (point-max))))
  18345. (save-excursion
  18346. (goto-char start)
  18347. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18348. (save-excursion
  18349. (save-match-data
  18350. (goto-char (match-beginning 0))
  18351. (funcall function)))))))
  18352. (defun org-next-block (arg &optional backward block-regexp)
  18353. "Jump to the next block.
  18354. With a prefix argument ARG, jump forward ARG many blocks.
  18355. When BACKWARD is non-nil, jump to the previous block.
  18356. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18357. Match data is set according to this regexp when the function
  18358. returns.
  18359. Return point at beginning of the opening line of found block.
  18360. Throw an error if no block is found."
  18361. (interactive "p")
  18362. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18363. (case-fold-search t)
  18364. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18365. (count (or arg 1))
  18366. (origin (point))
  18367. last-element)
  18368. (if backward (beginning-of-line) (end-of-line))
  18369. (while (and (> count 0) (funcall search-fn re nil t))
  18370. (let ((element (save-excursion
  18371. (goto-char (match-beginning 0))
  18372. (save-match-data (org-element-at-point)))))
  18373. (when (and (memq (org-element-type element)
  18374. '(center-block comment-block dynamic-block
  18375. example-block export-block quote-block
  18376. special-block src-block verse-block))
  18377. (<= (match-beginning 0)
  18378. (org-element-property :post-affiliated element)))
  18379. (setq last-element element)
  18380. (cl-decf count))))
  18381. (if (= count 0)
  18382. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18383. (save-match-data (org-show-context)))
  18384. (goto-char origin)
  18385. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18386. (defun org-previous-block (arg &optional block-regexp)
  18387. "Jump to the previous block.
  18388. With a prefix argument ARG, jump backward ARG many source blocks.
  18389. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18390. (interactive "p")
  18391. (org-next-block arg t block-regexp))
  18392. ;;; Comments
  18393. ;; Org comments syntax is quite complex. It requires the entire line
  18394. ;; to be just a comment. Also, even with the right syntax at the
  18395. ;; beginning of line, some elements (e.g., verse-block or
  18396. ;; example-block) don't accept comments. Usual Emacs comment commands
  18397. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18398. ;; Org still relies on 'comment-dwim', but cannot trust
  18399. ;; 'comment-only-p'. So, 'comment-region-function' and
  18400. ;; 'uncomment-region-function' both point
  18401. ;; to 'org-comment-or-uncomment-region'. Eventually,
  18402. ;; 'org-insert-comment' takes care of insertion of comments at the
  18403. ;; beginning of line.
  18404. ;; 'org-setup-comments-handling' install comments related variables
  18405. ;; during 'org-mode' initialization.
  18406. (defun org-setup-comments-handling ()
  18407. (interactive)
  18408. (setq-local comment-use-syntax nil)
  18409. (setq-local comment-start "# ")
  18410. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18411. (setq-local comment-insert-comment-function 'org-insert-comment)
  18412. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18413. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18414. (defun org-insert-comment ()
  18415. "Insert an empty comment above current line.
  18416. If the line is empty, insert comment at its beginning. When
  18417. point is within a source block, comment according to the related
  18418. major mode."
  18419. (if (let ((element (org-element-at-point)))
  18420. (and (eq (org-element-type element) 'src-block)
  18421. (< (save-excursion
  18422. (goto-char (org-element-property :post-affiliated element))
  18423. (line-end-position))
  18424. (point))
  18425. (> (save-excursion
  18426. (goto-char (org-element-property :end element))
  18427. (skip-chars-backward " \r\t\n")
  18428. (line-beginning-position))
  18429. (point))))
  18430. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18431. (beginning-of-line)
  18432. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18433. (open-line 1))
  18434. (org-indent-line)
  18435. (insert "# ")))
  18436. (defvar comment-empty-lines) ; From newcomment.el.
  18437. (defun org-comment-or-uncomment-region (beg end &rest _)
  18438. "Comment or uncomment each non-blank line in the region.
  18439. Uncomment each non-blank line between BEG and END if it only
  18440. contains commented lines. Otherwise, comment them. If region is
  18441. strictly within a source block, use appropriate comment syntax."
  18442. (if (let ((element (org-element-at-point)))
  18443. (and (eq (org-element-type element) 'src-block)
  18444. (< (save-excursion
  18445. (goto-char (org-element-property :post-affiliated element))
  18446. (line-end-position))
  18447. beg)
  18448. (>= (save-excursion
  18449. (goto-char (org-element-property :end element))
  18450. (skip-chars-backward " \r\t\n")
  18451. (line-beginning-position))
  18452. end)))
  18453. ;; Translate region boundaries for the Org buffer to the source
  18454. ;; buffer.
  18455. (let ((offset (- end beg)))
  18456. (save-excursion
  18457. (goto-char beg)
  18458. (org-babel-do-in-edit-buffer
  18459. (comment-or-uncomment-region (point) (+ offset (point))))))
  18460. (save-restriction
  18461. ;; Restrict region
  18462. (narrow-to-region (save-excursion (goto-char beg)
  18463. (skip-chars-forward " \r\t\n" end)
  18464. (line-beginning-position))
  18465. (save-excursion (goto-char end)
  18466. (skip-chars-backward " \r\t\n" beg)
  18467. (line-end-position)))
  18468. (let ((uncommentp
  18469. ;; UNCOMMENTP is non-nil when every non blank line between
  18470. ;; BEG and END is a comment.
  18471. (save-excursion
  18472. (goto-char (point-min))
  18473. (while (and (not (eobp))
  18474. (let ((element (org-element-at-point)))
  18475. (and (eq (org-element-type element) 'comment)
  18476. (goto-char (min (point-max)
  18477. (org-element-property
  18478. :end element)))))))
  18479. (eobp))))
  18480. (if uncommentp
  18481. ;; Only blank lines and comments in region: uncomment it.
  18482. (save-excursion
  18483. (goto-char (point-min))
  18484. (while (not (eobp))
  18485. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18486. (replace-match "" nil nil nil 1))
  18487. (forward-line)))
  18488. ;; Comment each line in region.
  18489. (let ((min-indent (point-max)))
  18490. ;; First find the minimum indentation across all lines.
  18491. (save-excursion
  18492. (goto-char (point-min))
  18493. (while (and (not (eobp)) (not (zerop min-indent)))
  18494. (unless (looking-at "[ \t]*$")
  18495. (setq min-indent (min min-indent (current-indentation))))
  18496. (forward-line)))
  18497. ;; Then loop over all lines.
  18498. (save-excursion
  18499. (goto-char (point-min))
  18500. (while (not (eobp))
  18501. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18502. ;; Don't get fooled by invisible text (e.g. link path)
  18503. ;; when moving to column MIN-INDENT.
  18504. (let ((buffer-invisibility-spec nil))
  18505. (org-move-to-column min-indent t))
  18506. (insert comment-start))
  18507. (forward-line)))))))))
  18508. (defun org-comment-dwim (_arg)
  18509. "Call the comment command you mean.
  18510. Call `org-toggle-comment' if on a heading, otherwise call
  18511. `comment-dwim', within a source edit buffer if needed."
  18512. (interactive "*P")
  18513. (cond ((org-at-heading-p)
  18514. (call-interactively #'org-toggle-comment))
  18515. ((org-in-src-block-p)
  18516. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18517. (t (call-interactively #'comment-dwim))))
  18518. ;;; Timestamps API
  18519. ;; This section contains tools to operate on, or create, timestamp
  18520. ;; objects, as returned by, e.g. `org-element-context'.
  18521. (defun org-timestamp-from-string (s)
  18522. "Convert Org timestamp S, as a string, into a timestamp object.
  18523. Return nil if S is not a valid timestamp string."
  18524. (when (org-string-nw-p s)
  18525. (with-temp-buffer
  18526. (save-excursion (insert s))
  18527. (org-element-timestamp-parser))))
  18528. (defun org-timestamp-from-time (time &optional with-time inactive)
  18529. "Convert a time value into a timestamp object.
  18530. TIME is an Emacs internal time representation, as returned, e.g.,
  18531. by `current-time'.
  18532. When optional argument WITH-TIME is non-nil, return a timestamp
  18533. object with a time part, i.e., with hours and minutes.
  18534. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18535. return an active timestamp."
  18536. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18537. (org-element-create 'timestamp
  18538. (list :type (if inactive 'inactive 'active)
  18539. :year-start year
  18540. :month-start month
  18541. :day-start day
  18542. :hour-start (and with-time hour)
  18543. :minute-start (and with-time minute)))))
  18544. (defun org-timestamp-to-time (timestamp &optional end)
  18545. "Convert TIMESTAMP object into an Emacs internal time value.
  18546. Use end of date range or time range when END is non-nil.
  18547. Otherwise, use its start."
  18548. (apply #'encode-time 0
  18549. (mapcar
  18550. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18551. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18552. '(:minute-start :hour-start :day-start :month-start
  18553. :year-start)))))
  18554. (defun org-timestamp-has-time-p (timestamp)
  18555. "Non-nil when TIMESTAMP has a time specified."
  18556. (org-element-property :hour-start timestamp))
  18557. (defun org-timestamp-format (timestamp format &optional end utc)
  18558. "Format a TIMESTAMP object into a string.
  18559. FORMAT is a format specifier to be passed to
  18560. `format-time-string'.
  18561. When optional argument END is non-nil, use end of date-range or
  18562. time-range, if possible.
  18563. When optional argument UTC is non-nil, time is be expressed as
  18564. Universal Time."
  18565. (format-time-string format (org-timestamp-to-time timestamp end)
  18566. (and utc t)))
  18567. (defun org-timestamp-split-range (timestamp &optional end)
  18568. "Extract a TIMESTAMP object from a date or time range.
  18569. END, when non-nil, means extract the end of the range.
  18570. Otherwise, extract its start.
  18571. Return a new timestamp object."
  18572. (let ((type (org-element-property :type timestamp)))
  18573. (if (memq type '(active inactive diary)) timestamp
  18574. (let ((split-ts (org-element-copy timestamp)))
  18575. ;; Set new type.
  18576. (org-element-put-property
  18577. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18578. ;; Copy start properties over end properties if END is
  18579. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18580. (let ((p-alist '((:minute-start . :minute-end)
  18581. (:hour-start . :hour-end)
  18582. (:day-start . :day-end)
  18583. (:month-start . :month-end)
  18584. (:year-start . :year-end))))
  18585. (dolist (p-cell p-alist)
  18586. (org-element-put-property
  18587. split-ts
  18588. (funcall (if end #'car #'cdr) p-cell)
  18589. (org-element-property
  18590. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18591. ;; Eventually refresh `:raw-value'.
  18592. (org-element-put-property split-ts :raw-value nil)
  18593. (org-element-put-property
  18594. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18595. (defun org-timestamp-translate (timestamp &optional boundary)
  18596. "Translate TIMESTAMP object to custom format.
  18597. Format string is defined in `org-time-stamp-custom-formats',
  18598. which see.
  18599. When optional argument BOUNDARY is non-nil, it is either the
  18600. symbol `start' or `end'. In this case, only translate the
  18601. starting or ending part of TIMESTAMP if it is a date or time
  18602. range. Otherwise, translate both parts.
  18603. Return timestamp as-is if `org-display-custom-times' is nil or if
  18604. it has a `diary' type."
  18605. (let ((type (org-element-property :type timestamp)))
  18606. (if (or (not org-display-custom-times) (eq type 'diary))
  18607. (org-element-interpret-data timestamp)
  18608. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18609. org-time-stamp-custom-formats)))
  18610. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18611. (concat (org-timestamp-format timestamp fmt)
  18612. "--"
  18613. (org-timestamp-format timestamp fmt t))
  18614. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18615. ;;; Other stuff
  18616. (defvar reftex-docstruct-symbol)
  18617. (defvar org--rds)
  18618. (defun org-reftex-citation ()
  18619. "Use `reftex-citation' to insert a citation into the buffer.
  18620. This looks for a line like
  18621. #+BIBLIOGRAPHY: foo plain option:-d
  18622. and derives from it that foo.bib is the bibliography file relevant
  18623. for this document. It then installs the necessary environment for RefTeX
  18624. to work in this buffer and calls `reftex-citation' to insert a citation
  18625. into the buffer.
  18626. Export of such citations to both LaTeX and HTML is handled by the contributed
  18627. package ox-bibtex by Taru Karttunen."
  18628. (interactive)
  18629. (let ((reftex-docstruct-symbol 'org--rds)
  18630. org--rds bib)
  18631. (org-with-wide-buffer
  18632. (let ((case-fold-search t)
  18633. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18634. (if (not (save-excursion
  18635. (or (re-search-forward re nil t)
  18636. (re-search-backward re nil t))))
  18637. (user-error "No bibliography defined in file")
  18638. (setq bib (concat (match-string 1) ".bib")
  18639. org--rds (list (list 'bib bib))))))
  18640. (call-interactively 'reftex-citation)))
  18641. ;;;; Functions extending outline functionality
  18642. (defun org-beginning-of-line (&optional n)
  18643. "Go to the beginning of the current visible line.
  18644. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18645. symbol `reversed', on the first attempt move to where the
  18646. headline text starts, and only move to beginning of line when the
  18647. cursor is already before the start of the text of the headline.
  18648. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18649. start of the text on the second attempt.
  18650. With argument N not nil or 1, move forward N - 1 lines first."
  18651. (interactive "^p")
  18652. (let ((origin (point))
  18653. (special (pcase org-special-ctrl-a/e
  18654. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18655. deactivate-mark)
  18656. ;; First move to a visible line.
  18657. (if (bound-and-true-p visual-line-mode)
  18658. (beginning-of-visual-line n)
  18659. (move-beginning-of-line n)
  18660. ;; `move-beginning-of-line' may leave point after invisible
  18661. ;; characters if line starts with such of these (e.g., with
  18662. ;; a link at column 0). Really move to the beginning of the
  18663. ;; current visible line.
  18664. (beginning-of-line))
  18665. (cond
  18666. ;; No special behavior. Point is already at the beginning of
  18667. ;; a line, logical or visual.
  18668. ((not special))
  18669. ;; `beginning-of-visual-line' left point before logical beginning
  18670. ;; of line: point is at the beginning of a visual line. Bail
  18671. ;; out.
  18672. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18673. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18674. ;; At a headline, special position is before the title, but
  18675. ;; after any TODO keyword or priority cookie.
  18676. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18677. (line-end-position)))
  18678. (bol (point)))
  18679. (if (eq special 'reversed)
  18680. (when (and (= origin bol) (eq last-command this-command))
  18681. (goto-char refpos))
  18682. (when (or (> origin refpos) (= origin bol))
  18683. (goto-char refpos)))))
  18684. ((and (looking-at org-list-full-item-re)
  18685. (memq (org-element-type (save-match-data (org-element-at-point)))
  18686. '(item plain-list)))
  18687. ;; Set special position at first white space character after
  18688. ;; bullet, and check-box, if any.
  18689. (let ((after-bullet
  18690. (let ((box (match-end 3)))
  18691. (cond ((not box) (match-end 1))
  18692. ((eq (char-after box) ?\s) (1+ box))
  18693. (t box)))))
  18694. (if (eq special 'reversed)
  18695. (when (and (= (point) origin) (eq last-command this-command))
  18696. (goto-char after-bullet))
  18697. (when (or (> origin after-bullet) (= (point) origin))
  18698. (goto-char after-bullet)))))
  18699. ;; No special context. Point is already at beginning of line.
  18700. (t nil))))
  18701. (defun org-end-of-line (&optional n)
  18702. "Go to the end of the line, but before ellipsis, if any.
  18703. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18704. symbol `reversed', ignore tags on the first attempt, and only
  18705. move to after the tags when the cursor is already beyond the end
  18706. of the headline.
  18707. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18708. on the second attempt.
  18709. With argument N not nil or 1, move forward N - 1 lines first."
  18710. (interactive "^p")
  18711. (let ((origin (point))
  18712. (special (pcase org-special-ctrl-a/e
  18713. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18714. deactivate-mark)
  18715. ;; First move to a visible line.
  18716. (if (bound-and-true-p visual-line-mode)
  18717. (beginning-of-visual-line n)
  18718. (move-beginning-of-line n))
  18719. (cond
  18720. ;; At a headline, with tags.
  18721. ((and special
  18722. (save-excursion
  18723. (beginning-of-line)
  18724. (let ((case-fold-search nil))
  18725. (looking-at org-complex-heading-regexp)))
  18726. (match-end 5))
  18727. (let ((tags (save-excursion
  18728. (goto-char (match-beginning 5))
  18729. (skip-chars-backward " \t")
  18730. (point)))
  18731. (visual-end (and (bound-and-true-p visual-line-mode)
  18732. (save-excursion
  18733. (end-of-visual-line)
  18734. (point)))))
  18735. ;; If `end-of-visual-line' brings us before end of line or
  18736. ;; even tags, i.e., the headline spans over multiple visual
  18737. ;; lines, move there.
  18738. (cond ((and visual-end
  18739. (< visual-end tags)
  18740. (<= origin visual-end))
  18741. (goto-char visual-end))
  18742. ((eq special 'reversed)
  18743. (if (and (= origin (line-end-position))
  18744. (eq this-command last-command))
  18745. (goto-char tags)
  18746. (end-of-line)))
  18747. (t
  18748. (if (or (< origin tags) (= origin (line-end-position)))
  18749. (goto-char tags)
  18750. (end-of-line))))))
  18751. ((bound-and-true-p visual-line-mode)
  18752. (let ((bol (line-beginning-position)))
  18753. (end-of-visual-line)
  18754. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18755. ;; end of a line, backtrack and use `end-of-line' instead.
  18756. (when (/= bol (line-beginning-position))
  18757. (goto-char bol)
  18758. (end-of-line))))
  18759. (t (end-of-line)))))
  18760. (defun org-backward-sentence (&optional _arg)
  18761. "Go to beginning of sentence, or beginning of table field.
  18762. This will call `backward-sentence' or `org-table-beginning-of-field',
  18763. depending on context."
  18764. (interactive)
  18765. (let* ((element (org-element-at-point))
  18766. (contents-begin (org-element-property :contents-begin element))
  18767. (table (org-element-lineage element '(table) t)))
  18768. (if (and table
  18769. (> (point) contents-begin)
  18770. (<= (point) (org-element-property :contents-end table)))
  18771. (call-interactively #'org-table-beginning-of-field)
  18772. (save-restriction
  18773. (when (and contents-begin
  18774. (< (point-min) contents-begin)
  18775. (> (point) contents-begin))
  18776. (narrow-to-region contents-begin
  18777. (org-element-property :contents-end element)))
  18778. (call-interactively #'backward-sentence)))))
  18779. (defun org-forward-sentence (&optional _arg)
  18780. "Go to end of sentence, or end of table field.
  18781. This will call `forward-sentence' or `org-table-end-of-field',
  18782. depending on context."
  18783. (interactive)
  18784. (if (and (org-at-heading-p)
  18785. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18786. (save-restriction
  18787. (narrow-to-region (line-beginning-position) (line-end-position))
  18788. (call-interactively #'forward-sentence))
  18789. (let* ((element (org-element-at-point))
  18790. (contents-end (org-element-property :contents-end element))
  18791. (table (org-element-lineage element '(table) t)))
  18792. (if (and table
  18793. (>= (point) (org-element-property :contents-begin table))
  18794. (< (point) contents-end))
  18795. (call-interactively #'org-table-end-of-field)
  18796. (save-restriction
  18797. (when (and contents-end
  18798. (> (point-max) contents-end)
  18799. ;; Skip blank lines between elements.
  18800. (< (org-element-property :end element)
  18801. (save-excursion (goto-char contents-end)
  18802. (skip-chars-forward " \r\t\n"))))
  18803. (narrow-to-region (org-element-property :contents-begin element)
  18804. contents-end))
  18805. ;; End of heading is considered as the end of a sentence.
  18806. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18807. (call-interactively #'forward-sentence)))))))
  18808. (defun org-kill-line (&optional _arg)
  18809. "Kill line, to tags or end of line."
  18810. (interactive)
  18811. (cond
  18812. ((or (not org-special-ctrl-k)
  18813. (bolp)
  18814. (not (org-at-heading-p)))
  18815. (when (and (get-char-property (line-end-position) 'invisible)
  18816. org-ctrl-k-protect-subtree
  18817. (or (eq org-ctrl-k-protect-subtree 'error)
  18818. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18819. (user-error
  18820. (substitute-command-keys
  18821. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18822. (call-interactively
  18823. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18824. ((org-match-line org-tag-line-re)
  18825. (let ((end (save-excursion
  18826. (goto-char (match-beginning 1))
  18827. (skip-chars-backward " \t")
  18828. (point))))
  18829. (if (<= end (point)) ;on tags part
  18830. (kill-region (point) (line-end-position))
  18831. (kill-region (point) end)))
  18832. ;; Only align tags when we are still on a heading:
  18833. (if (org-at-heading-p) (org-align-tags)))
  18834. (t (kill-region (point) (line-end-position)))))
  18835. (defun org-yank (&optional arg)
  18836. "Yank. If the kill is a subtree, treat it specially.
  18837. This command will look at the current kill and check if is a single
  18838. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18839. cursor is at the beginning of a line or after the stars of a currently
  18840. empty headline, then the yank is handled specially. How exactly depends
  18841. on the value of the following variables.
  18842. `org-yank-folded-subtrees'
  18843. By default, this variable is non-nil, which results in
  18844. subtree(s) being folded after insertion, except if doing so
  18845. would swallow text after the yanked text.
  18846. `org-yank-adjusted-subtrees'
  18847. When non-nil (the default value is nil), the subtree will be
  18848. promoted or demoted in order to fit into the local outline tree
  18849. structure, which means that the level will be adjusted so that it
  18850. becomes the smaller one of the two *visible* surrounding headings.
  18851. Any prefix to this command will cause `yank' to be called directly with
  18852. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18853. will just
  18854. plainly yank the text as it is.
  18855. \[1] The test checks if the first non-white line is a heading
  18856. and if there are no other headings with fewer stars."
  18857. (interactive "P")
  18858. (org-yank-generic 'yank arg))
  18859. (defun org-yank-generic (command arg)
  18860. "Perform some yank-like command.
  18861. This function implements the behavior described in the `org-yank'
  18862. documentation. However, it has been generalized to work for any
  18863. interactive command with similar behavior."
  18864. ;; pretend to be command COMMAND
  18865. (setq this-command command)
  18866. (if arg
  18867. (call-interactively command)
  18868. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18869. (and (org-kill-is-subtree-p)
  18870. (or (bolp)
  18871. (and (looking-at "[ \t]*$")
  18872. (string-match
  18873. "\\`\\*+\\'"
  18874. (buffer-substring (point-at-bol) (point)))))))
  18875. swallowp)
  18876. (cond
  18877. ((and subtreep org-yank-folded-subtrees)
  18878. (let ((beg (point))
  18879. end)
  18880. (if (and subtreep org-yank-adjusted-subtrees)
  18881. (org-paste-subtree nil nil 'for-yank)
  18882. (call-interactively command))
  18883. (setq end (point))
  18884. (goto-char beg)
  18885. (when (and (bolp) subtreep
  18886. (not (setq swallowp
  18887. (org-yank-folding-would-swallow-text beg end))))
  18888. (org-with-limited-levels
  18889. (or (looking-at org-outline-regexp)
  18890. (re-search-forward org-outline-regexp-bol end t))
  18891. (while (and (< (point) end) (looking-at org-outline-regexp))
  18892. (org-flag-subtree t)
  18893. (org-cycle-show-empty-lines 'folded)
  18894. (condition-case nil
  18895. (outline-forward-same-level 1)
  18896. (error (goto-char end))))))
  18897. (when swallowp
  18898. (message
  18899. "Inserted text not folded because that would swallow text"))
  18900. (goto-char end)
  18901. (skip-chars-forward " \t\n\r")
  18902. (beginning-of-line 1)
  18903. (push-mark beg 'nomsg)))
  18904. ((and subtreep org-yank-adjusted-subtrees)
  18905. (let ((beg (point-at-bol)))
  18906. (org-paste-subtree nil nil 'for-yank)
  18907. (push-mark beg 'nomsg)))
  18908. (t
  18909. (call-interactively command))))))
  18910. (defun org-yank-folding-would-swallow-text (beg end)
  18911. "Would `hide-subtree' at BEG swallow any text after END?"
  18912. (let (level)
  18913. (org-with-limited-levels
  18914. (save-excursion
  18915. (goto-char beg)
  18916. (when (or (looking-at org-outline-regexp)
  18917. (re-search-forward org-outline-regexp-bol end t))
  18918. (setq level (org-outline-level)))
  18919. (goto-char end)
  18920. (skip-chars-forward " \t\r\n\v\f")
  18921. (not (or (eobp)
  18922. (and (bolp) (looking-at-p org-outline-regexp)
  18923. (<= (org-outline-level) level))))))))
  18924. (defun org-back-to-heading (&optional invisible-ok)
  18925. "Go back to beginning of heading."
  18926. (beginning-of-line)
  18927. (or (org-at-heading-p (not invisible-ok))
  18928. (let (found)
  18929. (save-excursion
  18930. ;; At inlinetask end. Move to bol, so that the following
  18931. ;; search goes to the beginning of the inlinetask.
  18932. (when (and (featurep 'org-inlinetask)
  18933. (fboundp 'org-inlinetask-end-p)
  18934. (org-inlinetask-end-p))
  18935. (goto-char (line-beginning-position)))
  18936. (while (not found)
  18937. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18938. nil t)
  18939. (user-error "Before first headline at position %d in buffer %s"
  18940. (point) (current-buffer)))
  18941. ;; Skip inlinetask end.
  18942. (if (and (featurep 'org-inlinetask)
  18943. (fboundp 'org-inlinetask-end-p)
  18944. (org-inlinetask-end-p))
  18945. (org-inlinetask-goto-beginning)
  18946. (setq found (and (or invisible-ok (not (org-invisible-p)))
  18947. (point))))))
  18948. (goto-char found)
  18949. found)))
  18950. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18951. "Go back to heading or first point in buffer.
  18952. If point is before first heading go to first point in buffer
  18953. instead of back to heading."
  18954. (if (org-before-first-heading-p)
  18955. (goto-char (point-min))
  18956. (org-back-to-heading invisible-ok)))
  18957. (defun org-before-first-heading-p ()
  18958. "Before first heading?"
  18959. (org-with-limited-levels
  18960. (save-excursion
  18961. (end-of-line)
  18962. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18963. (defun org-at-heading-p (&optional _)
  18964. "Non-nil when on a headline."
  18965. (outline-on-heading-p t))
  18966. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18967. "Non-nil if point is under a commented heading.
  18968. This function also checks ancestors of the current headline,
  18969. unless optional argument NO-INHERITANCE is non-nil.
  18970. Optional argument ELEMENT contains element at point."
  18971. (save-match-data
  18972. (let ((el (or element (org-element-at-point nil 'cached))))
  18973. (if el
  18974. (catch :found
  18975. (setq el (org-element-lineage el '(headline) 'include-self))
  18976. (if no-inheritance
  18977. (org-element-property :commentedp el)
  18978. (while el
  18979. (when (org-element-property :commentedp el)
  18980. (throw :found t))
  18981. (setq el (org-element-property :parent el)))))
  18982. (cond
  18983. ((org-before-first-heading-p) nil)
  18984. ((let ((headline (nth 4 (org-heading-components))))
  18985. (and headline
  18986. (let ((case-fold-search nil))
  18987. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18988. headline)))))
  18989. (no-inheritance nil)
  18990. (t
  18991. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p)))))))))
  18992. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18993. "Non-nil if point is under an archived heading.
  18994. This function also checks ancestors of the current headline,
  18995. unless optional argument NO-INHERITANCE is non-nil.
  18996. Optional argument ELEMENT contains element at point."
  18997. (cond
  18998. ((and (not element) (org-before-first-heading-p)) nil)
  18999. ((if element
  19000. (org-element-property :archivedp element)
  19001. (let ((tags (org-get-tags element 'local)))
  19002. (and tags
  19003. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  19004. (no-inheritance nil)
  19005. (t
  19006. (if (org-element--cache-active-p)
  19007. (cl-some (lambda (el) (org-element-property :archivedp el))
  19008. (org-element-lineage (or element (org-element-at-point)) nil t))
  19009. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  19010. (defun org-at-comment-p nil
  19011. "Return t if cursor is in a commented line."
  19012. (save-excursion
  19013. (save-match-data
  19014. (beginning-of-line)
  19015. (looking-at org-comment-regexp))))
  19016. (defun org-at-keyword-p nil
  19017. "Return t if cursor is at a keyword-line."
  19018. (save-excursion
  19019. (move-beginning-of-line 1)
  19020. (looking-at org-keyword-regexp)))
  19021. (defun org-at-drawer-p nil
  19022. "Return t if cursor is at a drawer keyword."
  19023. (save-excursion
  19024. (move-beginning-of-line 1)
  19025. (looking-at org-drawer-regexp)))
  19026. (defun org-at-block-p nil
  19027. "Return t if cursor is at a block keyword."
  19028. (save-excursion
  19029. (move-beginning-of-line 1)
  19030. (looking-at org-block-regexp)))
  19031. (defun org-point-at-end-of-empty-headline ()
  19032. "If point is at the end of an empty headline, return t, else nil.
  19033. If the heading only contains a TODO keyword, it is still considered
  19034. empty."
  19035. (let ((case-fold-search nil))
  19036. (and (looking-at "[ \t]*$")
  19037. org-todo-line-regexp
  19038. (save-excursion
  19039. (beginning-of-line)
  19040. (looking-at org-todo-line-regexp)
  19041. (string= (match-string 3) "")))))
  19042. (defun org-at-heading-or-item-p ()
  19043. (or (org-at-heading-p) (org-at-item-p)))
  19044. (defun org-up-heading-all (arg)
  19045. "Move to the heading line of which the present line is a subheading.
  19046. This function considers both visible and invisible heading lines.
  19047. With argument, move up ARG levels."
  19048. (outline-up-heading arg t))
  19049. (defvar-local org--up-heading-cache nil
  19050. "Buffer-local `org-up-heading-safe' cache.")
  19051. (defvar-local org--up-heading-cache-tick nil
  19052. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  19053. (defun org-up-heading-safe ()
  19054. "Move to the heading line of which the present line is a subheading.
  19055. This version will not throw an error. It will return the level of the
  19056. headline found, or nil if no higher level is found.
  19057. Also, this function will be a lot faster than `outline-up-heading',
  19058. because it relies on stars being the outline starters. This can really
  19059. make a significant difference in outlines with very many siblings."
  19060. (let ((element (and (org-element--cache-active-p)
  19061. (org-element-at-point nil t))))
  19062. (if element
  19063. (let* ((current-heading (org-element-lineage element '(headline) 'with-self))
  19064. (parent (org-element-lineage current-heading '(headline))))
  19065. (if (and parent
  19066. (<= (point-min) (org-element-property :begin parent)))
  19067. (progn
  19068. (goto-char (org-element-property :begin parent))
  19069. (org-element-property :level parent))
  19070. (when (and current-heading
  19071. (<= (point-min) (org-element-property :begin current-heading)))
  19072. (goto-char (org-element-property :begin current-heading))
  19073. nil)))
  19074. (when (ignore-errors (org-back-to-heading t))
  19075. (let (level-cache)
  19076. (unless org--up-heading-cache
  19077. (setq org--up-heading-cache (make-hash-table)))
  19078. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  19079. (setq level-cache (gethash (point) org--up-heading-cache)))
  19080. (when (<= (point-min) (car level-cache) (point-max))
  19081. ;; Parent is inside accessible part of the buffer.
  19082. (progn (goto-char (car level-cache))
  19083. (cdr level-cache)))
  19084. ;; Buffer modified. Invalidate cache.
  19085. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  19086. (setq-local org--up-heading-cache-tick
  19087. (buffer-chars-modified-tick))
  19088. (clrhash org--up-heading-cache))
  19089. (let* ((level-up (1- (funcall outline-level)))
  19090. (pos (point))
  19091. (result (and (> level-up 0)
  19092. (re-search-backward
  19093. (format "^\\*\\{1,%d\\} " level-up) nil t)
  19094. (funcall outline-level))))
  19095. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  19096. result)))))))
  19097. (defun org-up-heading-or-point-min ()
  19098. "Move to the heading line of which the present is a subheading, or point-min.
  19099. This version is needed to make point-min behave like a virtual
  19100. heading of level 0 for property-inheritance. It will return the
  19101. level of the headline found (down to 0) or nil if already at a
  19102. point before the first headline or at point-min."
  19103. (when (ignore-errors (org-back-to-heading t))
  19104. (if (< 1 (funcall outline-level))
  19105. (or (org-up-heading-safe)
  19106. ;; The first heading may not be level 1 heading.
  19107. (goto-char (point-min)))
  19108. (unless (= (point) (point-min)) (goto-char (point-min))))))
  19109. (defun org-first-sibling-p ()
  19110. "Is this heading the first child of its parents?"
  19111. (interactive)
  19112. (let ((re org-outline-regexp-bol)
  19113. level l)
  19114. (unless (org-at-heading-p t)
  19115. (user-error "Not at a heading"))
  19116. (setq level (funcall outline-level))
  19117. (save-excursion
  19118. (if (not (re-search-backward re nil t))
  19119. t
  19120. (setq l (funcall outline-level))
  19121. (< l level)))))
  19122. (defun org-goto-sibling (&optional previous)
  19123. "Goto the next sibling, even if it is invisible.
  19124. When PREVIOUS is set, go to the previous sibling instead. Returns t
  19125. when a sibling was found. When none is found, return nil and don't
  19126. move point."
  19127. (let ((fun (if previous 're-search-backward 're-search-forward))
  19128. (pos (point))
  19129. (re org-outline-regexp-bol)
  19130. level l)
  19131. (when (ignore-errors (org-back-to-heading t))
  19132. (setq level (funcall outline-level))
  19133. (catch 'exit
  19134. (or previous (forward-char 1))
  19135. (while (funcall fun re nil t)
  19136. (setq l (funcall outline-level))
  19137. (when (< l level) (goto-char pos) (throw 'exit nil))
  19138. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  19139. (goto-char pos)
  19140. nil))))
  19141. (defun org-show-siblings ()
  19142. "Show all siblings of the current headline."
  19143. (save-excursion
  19144. (while (org-goto-sibling) (org-flag-heading nil)))
  19145. (save-excursion
  19146. (while (org-goto-sibling 'previous)
  19147. (org-flag-heading nil))))
  19148. (defun org-goto-first-child (&optional element)
  19149. "Goto the first child, even if it is invisible.
  19150. Return t when a child was found. Otherwise don't move point and
  19151. return nil."
  19152. (if (org-element--cache-active-p)
  19153. (let ((heading (org-element-lineage
  19154. (or element (org-element-at-point))
  19155. '(headline inlinetask org-data)
  19156. t)))
  19157. (when heading
  19158. (unless (or (eq 'inlinetask (org-element-type heading))
  19159. (not (org-element-property :contents-begin heading)))
  19160. (let ((pos (point)))
  19161. (goto-char (org-element-property :contents-begin heading))
  19162. (if (re-search-forward
  19163. org-outline-regexp-bol
  19164. (org-element-property :end heading)
  19165. t)
  19166. (progn (goto-char (match-beginning 0)) t)
  19167. (goto-char pos) nil)))))
  19168. (let (level (pos (point)) (re org-outline-regexp-bol))
  19169. (when (org-back-to-heading-or-point-min t)
  19170. (setq level (org-outline-level))
  19171. (forward-char 1)
  19172. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  19173. (progn (goto-char (match-beginning 0)) t)
  19174. (goto-char pos) nil)))))
  19175. (defun org-show-hidden-entry ()
  19176. "Show an entry where even the heading is hidden."
  19177. (save-excursion
  19178. (org-show-entry)))
  19179. (defun org-flag-heading (flag &optional entry)
  19180. "Flag the current heading. FLAG non-nil means make invisible.
  19181. When ENTRY is non-nil, show the entire entry."
  19182. (save-excursion
  19183. (org-back-to-heading t)
  19184. ;; Check if we should show the entire entry
  19185. (if (not entry)
  19186. (org-flag-region
  19187. (line-end-position 0) (line-end-position) flag 'outline)
  19188. (org-show-entry)
  19189. (save-excursion
  19190. (and (outline-next-heading)
  19191. (org-flag-heading nil))))))
  19192. (defun org-get-next-sibling ()
  19193. "Move to next heading of the same level, and return point.
  19194. If there is no such heading, return nil.
  19195. This is like outline-next-sibling, but invisible headings are ok."
  19196. (let ((level (funcall outline-level)))
  19197. (outline-next-heading)
  19198. (while (and (not (eobp)) (> (funcall outline-level) level))
  19199. (outline-next-heading))
  19200. (unless (or (eobp) (< (funcall outline-level) level))
  19201. (point))))
  19202. (defun org-get-previous-sibling ()
  19203. "Move to previous heading of the same level, and return point.
  19204. If there is no such heading, return nil."
  19205. (let ((opoint (point))
  19206. (level (funcall outline-level)))
  19207. (outline-previous-heading)
  19208. (when (and (/= (point) opoint) (outline-on-heading-p t))
  19209. (while (and (> (funcall outline-level) level)
  19210. (not (bobp)))
  19211. (outline-previous-heading))
  19212. (unless (< (funcall outline-level) level)
  19213. (point)))))
  19214. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  19215. "Goto to the end of a subtree at point or for ELEMENT heading."
  19216. ;; This contains an exact copy of the original function, but it uses
  19217. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  19218. ;; trees and before first headline. And is uses an invisible-ok argument.
  19219. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  19220. ;; Furthermore, when used inside Org, finding the end of a large subtree
  19221. ;; with many children and grandchildren etc, this can be much faster
  19222. ;; than the outline version.
  19223. (org-back-to-heading-or-point-min invisible-ok)
  19224. (unless (and (org-element--cache-active-p)
  19225. (let ((cached (or element (org-element-at-point nil t))))
  19226. (and cached
  19227. (eq 'headline (org-element-type cached))
  19228. (goto-char (org-element-property
  19229. :end cached)))))
  19230. (let ((first t)
  19231. (level (funcall outline-level)))
  19232. (cond ((= level 0)
  19233. (goto-char (point-max)))
  19234. ((and (derived-mode-p 'org-mode) (< level 1000))
  19235. ;; A true heading (not a plain list item), in Org
  19236. ;; This means we can easily find the end by looking
  19237. ;; only for the right number of stars. Using a regexp to do
  19238. ;; this is so much faster than using a Lisp loop.
  19239. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  19240. (forward-char 1)
  19241. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  19242. (t
  19243. ;; something else, do it the slow way
  19244. (while (and (not (eobp))
  19245. (or first (> (funcall outline-level) level)))
  19246. (setq first nil)
  19247. (outline-next-heading))))))
  19248. (unless to-heading
  19249. (when (memq (preceding-char) '(?\n ?\^M))
  19250. ;; Go to end of line before heading
  19251. (forward-char -1)
  19252. (when (memq (preceding-char) '(?\n ?\^M))
  19253. ;; leave blank line before heading
  19254. (forward-char -1))))
  19255. (point))
  19256. (defun org-end-of-meta-data (&optional full)
  19257. "Skip planning line and properties drawer in current entry.
  19258. When optional argument FULL is t, also skip planning information,
  19259. clocking lines and any kind of drawer.
  19260. When FULL is non-nil but not t, skip planning information,
  19261. properties, clocking lines and logbook drawers."
  19262. (org-back-to-heading t)
  19263. (forward-line)
  19264. ;; Skip planning information.
  19265. (when (looking-at-p org-planning-line-re) (forward-line))
  19266. ;; Skip property drawer.
  19267. (when (looking-at org-property-drawer-re)
  19268. (goto-char (match-end 0))
  19269. (forward-line))
  19270. ;; When FULL is not nil, skip more.
  19271. (when (and full (not (org-at-heading-p)))
  19272. (catch 'exit
  19273. (let ((end (save-excursion (outline-next-heading) (point)))
  19274. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  19275. (while (not (eobp))
  19276. (cond ;; Skip clock lines.
  19277. ((looking-at-p re) (forward-line))
  19278. ;; Skip logbook drawer.
  19279. ((looking-at-p org-logbook-drawer-re)
  19280. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19281. (forward-line)
  19282. (throw 'exit t)))
  19283. ;; When FULL is t, skip regular drawer too.
  19284. ((and (eq full t) (looking-at-p org-drawer-regexp))
  19285. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19286. (forward-line)
  19287. (throw 'exit t)))
  19288. (t (throw 'exit t))))))))
  19289. (defun org--line-fully-invisible-p ()
  19290. "Return non-nil if the current line is fully invisible."
  19291. (let ((line-beg (line-beginning-position))
  19292. (line-pos (1- (line-end-position)))
  19293. (is-invisible t))
  19294. (while (and (< line-beg line-pos) is-invisible)
  19295. (setq is-invisible (org-invisible-p line-pos))
  19296. (setq line-pos (1- line-pos)))
  19297. is-invisible))
  19298. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  19299. "Move forward to the ARG'th subheading at same level as this one.
  19300. Stop at the first and last subheadings of a superior heading.
  19301. Normally this only looks at visible headings, but when INVISIBLE-OK is
  19302. non-nil it will also look at invisible ones."
  19303. (interactive "p")
  19304. (let ((backward? (and arg (< arg 0))))
  19305. (if (org-before-first-heading-p)
  19306. (if backward? (goto-char (point-min)) (outline-next-heading))
  19307. (org-back-to-heading invisible-ok)
  19308. (unless backward? (end-of-line)) ;do not match current headline
  19309. (let ((level (- (match-end 0) (match-beginning 0) 1))
  19310. (f (if backward? #'re-search-backward #'re-search-forward))
  19311. (count (if arg (abs arg) 1))
  19312. (result (point)))
  19313. (while (and (> count 0)
  19314. (funcall f org-outline-regexp-bol nil 'move))
  19315. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  19316. (cond ((< l level) (setq count 0))
  19317. ((and (= l level)
  19318. (or invisible-ok
  19319. ;; FIXME: See commit a700fadd72 and the
  19320. ;; related discussion on why using
  19321. ;; `org--line-fully-invisible-p' is needed
  19322. ;; here, which is to serve the needs of an
  19323. ;; external package. If the change is
  19324. ;; wrong regarding Org itself, it should
  19325. ;; be removed.
  19326. (not (org--line-fully-invisible-p))))
  19327. (cl-decf count)
  19328. (when (= l level) (setq result (point)))))))
  19329. (goto-char result))
  19330. (beginning-of-line))))
  19331. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19332. "Move backward to the ARG'th subheading at same level as this one.
  19333. Stop at the first and last subheadings of a superior heading."
  19334. (interactive "p")
  19335. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19336. (defun org-next-visible-heading (arg)
  19337. "Move to the next visible heading line.
  19338. With ARG, repeats or can move backward if negative."
  19339. (interactive "p")
  19340. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  19341. (if (< arg 0)
  19342. (beginning-of-line)
  19343. (end-of-line))
  19344. (while (and (< arg 0) (re-search-backward regexp nil :move))
  19345. (unless (bobp)
  19346. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19347. (`(outline . ,o)
  19348. (goto-char (overlay-start o))
  19349. (re-search-backward regexp nil :move))
  19350. (_ nil))))
  19351. (cl-incf arg))
  19352. (while (and (> arg 0) (re-search-forward regexp nil t))
  19353. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19354. (`(outline . ,o)
  19355. (goto-char (overlay-end o))
  19356. (re-search-forward regexp nil :move))
  19357. (_
  19358. (end-of-line)
  19359. nil))) ;leave the loop
  19360. (cl-decf arg))
  19361. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  19362. (defun org-previous-visible-heading (arg)
  19363. "Move to the previous visible heading.
  19364. With ARG, repeats or can move forward if negative."
  19365. (interactive "p")
  19366. (org-next-visible-heading (- arg)))
  19367. (defun org-forward-paragraph (&optional arg)
  19368. "Move forward by a paragraph, or equivalent, unit.
  19369. With argument ARG, do it ARG times;
  19370. a negative argument ARG = -N means move backward N paragraphs.
  19371. The function moves point between two structural
  19372. elements (paragraphs, tables, lists, etc.).
  19373. It also provides the following special moves for convenience:
  19374. - on a table or a property drawer, move to its beginning;
  19375. - on comment, example, export, source and verse blocks, stop
  19376. at blank lines;
  19377. - skip consecutive clocks, diary S-exps, and keywords."
  19378. (interactive "^p")
  19379. (unless arg (setq arg 1))
  19380. (if (< arg 0) (org-backward-paragraph (- arg))
  19381. (while (and (> arg 0) (not (eobp)))
  19382. (org--forward-paragraph-once)
  19383. (cl-decf arg))
  19384. ;; Return moves left.
  19385. arg))
  19386. (defun org-backward-paragraph (&optional arg)
  19387. "Move backward by a paragraph, or equivalent, unit.
  19388. With argument ARG, do it ARG times;
  19389. a negative argument ARG = -N means move forward N paragraphs.
  19390. The function moves point between two structural
  19391. elements (paragraphs, tables, lists, etc.).
  19392. It also provides the following special moves for convenience:
  19393. - on a table or a property drawer, move to its beginning;
  19394. - on comment, example, export, source and verse blocks, stop
  19395. at blank lines;
  19396. - skip consecutive clocks, diary S-exps, and keywords."
  19397. (interactive "^p")
  19398. (unless arg (setq arg 1))
  19399. (if (< arg 0) (org-forward-paragraph (- arg))
  19400. (while (and (> arg 0) (not (bobp)))
  19401. (org--backward-paragraph-once)
  19402. (cl-decf arg))
  19403. ;; Return moves left.
  19404. arg))
  19405. (defun org--paragraph-at-point ()
  19406. "Return paragraph, or equivalent, element at point.
  19407. Paragraph element at point is the element at point, with the
  19408. following special cases:
  19409. - treat table rows (resp. node properties) as the table
  19410. \(resp. property drawer) containing them.
  19411. - treat plain lists with an item every line as a whole.
  19412. - treat consecutive keywords, clocks, and diary-sexps as a single
  19413. block.
  19414. Function may return a real element, or a pseudo-element with type
  19415. `pseudo-paragraph'."
  19416. (let* ((e (org-element-at-point))
  19417. (type (org-element-type e))
  19418. ;; If we need to fake a new pseudo-element, triplet is
  19419. ;;
  19420. ;; (BEG END PARENT)
  19421. ;;
  19422. ;; where BEG and END are element boundaries, and PARENT the
  19423. ;; element containing it, or nil.
  19424. (triplet
  19425. (cond
  19426. ((memq type '(table property-drawer))
  19427. (list (org-element-property :begin e)
  19428. (org-element-property :end e)
  19429. (org-element-property :parent e)))
  19430. ((memq type '(node-property table-row))
  19431. (let ((e (org-element-property :parent e)))
  19432. (list (org-element-property :begin e)
  19433. (org-element-property :end e)
  19434. (org-element-property :parent e))))
  19435. ((memq type '(clock diary-sexp keyword))
  19436. (let* ((regexp (pcase type
  19437. (`clock org-clock-line-re)
  19438. (`diary-sexp "%%(")
  19439. (_ org-keyword-regexp)))
  19440. (end (if (< 0 (org-element-property :post-blank e))
  19441. (org-element-property :end e)
  19442. (org-with-wide-buffer
  19443. (forward-line)
  19444. (while (looking-at regexp) (forward-line))
  19445. (skip-chars-forward " \t\n")
  19446. (line-beginning-position))))
  19447. (begin (org-with-point-at (org-element-property :begin e)
  19448. (while (and (not (bobp)) (looking-at regexp))
  19449. (forward-line -1))
  19450. ;; We may have gotten one line too far.
  19451. (if (looking-at regexp)
  19452. (point)
  19453. (line-beginning-position 2)))))
  19454. (list begin end (org-element-property :parent e))))
  19455. ;; Find the full plain list containing point, the check it
  19456. ;; contains exactly one line per item.
  19457. ((let ((l (org-element-lineage e '(plain-list) t)))
  19458. (while (memq (org-element-type (org-element-property :parent l))
  19459. '(item plain-list))
  19460. (setq l (org-element-property :parent l)))
  19461. (and l
  19462. (org-with-point-at (org-element-property :post-affiliated l)
  19463. (forward-line (length (org-element-property :structure l)))
  19464. (= (point) (org-element-property :contents-end l)))
  19465. ;; Return value.
  19466. (list (org-element-property :begin l)
  19467. (org-element-property :end l)
  19468. (org-element-property :parent l)))))
  19469. (t nil)))) ;no triplet: return element
  19470. (pcase triplet
  19471. (`(,b ,e ,p)
  19472. (org-element-create
  19473. 'pseudo-paragraph
  19474. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  19475. (_ e))))
  19476. (defun org--forward-paragraph-once ()
  19477. "Move forward to end of paragraph or equivalent, once.
  19478. See `org-forward-paragraph'."
  19479. (interactive)
  19480. (save-restriction
  19481. (widen)
  19482. (skip-chars-forward " \t\n")
  19483. (cond
  19484. ((eobp) nil)
  19485. ;; When inside a folded part, move out of it.
  19486. ((pcase (get-char-property-and-overlay (point) 'invisible)
  19487. (`(,(or `outline `org-hide-block) . ,o)
  19488. (goto-char (overlay-end o))
  19489. (forward-line)
  19490. t)
  19491. (_ nil)))
  19492. (t
  19493. (let* ((element (org--paragraph-at-point))
  19494. (type (org-element-type element))
  19495. (contents-begin (org-element-property :contents-begin element))
  19496. (end (org-element-property :end element))
  19497. (post-affiliated (org-element-property :post-affiliated element)))
  19498. (cond
  19499. ((eq type 'plain-list)
  19500. (forward-char)
  19501. (org--forward-paragraph-once))
  19502. ;; If the element is folded, skip it altogether.
  19503. ((pcase (org-with-point-at post-affiliated
  19504. (get-char-property-and-overlay (line-end-position)
  19505. 'invisible))
  19506. (`(,(or `outline `org-hide-block) . ,o)
  19507. (goto-char (overlay-end o))
  19508. (forward-line)
  19509. t)
  19510. (_ nil)))
  19511. ;; At a greater element, move inside.
  19512. ((and contents-begin
  19513. (> contents-begin (point))
  19514. (not (eq type 'paragraph)))
  19515. (goto-char contents-begin)
  19516. ;; Items and footnote definitions contents may not start at
  19517. ;; the beginning of the line. In this case, skip until the
  19518. ;; next paragraph.
  19519. (cond
  19520. ((not (bolp)) (org--forward-paragraph-once))
  19521. ((org-previous-line-empty-p) (forward-line -1))
  19522. (t nil)))
  19523. ;; Move between empty lines in some blocks.
  19524. ((memq type '(comment-block example-block export-block src-block
  19525. verse-block))
  19526. (let ((contents-start
  19527. (org-with-point-at post-affiliated
  19528. (line-beginning-position 2))))
  19529. (if (< (point) contents-start)
  19530. (goto-char contents-start)
  19531. (let ((contents-end
  19532. (org-with-point-at end
  19533. (skip-chars-backward " \t\n")
  19534. (line-beginning-position))))
  19535. (cond
  19536. ((>= (point) contents-end)
  19537. (goto-char end)
  19538. (skip-chars-backward " \t\n")
  19539. (forward-line))
  19540. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19541. (forward-line -1))
  19542. (t nil))))))
  19543. (t
  19544. ;; Move to element's end.
  19545. (goto-char end)
  19546. (skip-chars-backward " \t\n")
  19547. (forward-line))))))))
  19548. (defun org--backward-paragraph-once ()
  19549. "Move backward to start of paragraph or equivalent, once.
  19550. See `org-backward-paragraph'."
  19551. (interactive)
  19552. (save-restriction
  19553. (widen)
  19554. (cond
  19555. ((bobp) nil)
  19556. ;; Blank lines at the beginning of the buffer.
  19557. ((and (org-match-line "^[ \t]*$")
  19558. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19559. (goto-char (point-min)))
  19560. ;; When inside a folded part, move out of it.
  19561. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19562. (`(,(or `outline `org-hide-block) . ,o)
  19563. (goto-char (1- (overlay-start o)))
  19564. (org--backward-paragraph-once)
  19565. t)
  19566. (_ nil)))
  19567. (t
  19568. (let* ((element (org--paragraph-at-point))
  19569. (type (org-element-type element))
  19570. (begin (org-element-property :begin element))
  19571. (post-affiliated (org-element-property :post-affiliated element))
  19572. (contents-end (org-element-property :contents-end element))
  19573. (end (org-element-property :end element))
  19574. (parent (org-element-property :parent element))
  19575. (reach
  19576. ;; Move to the visible empty line above position P, or
  19577. ;; to position P. Return t.
  19578. (lambda (p)
  19579. (goto-char p)
  19580. (when (and (org-previous-line-empty-p)
  19581. (let ((end (line-end-position 0)))
  19582. (or (= end (point-min))
  19583. (not (org-invisible-p (1- end))))))
  19584. (forward-line -1))
  19585. t)))
  19586. (cond
  19587. ;; Already at the beginning of an element.
  19588. ((= begin (point))
  19589. (cond
  19590. ;; There is a blank line above. Move there.
  19591. ((and (org-previous-line-empty-p)
  19592. (let ((lep (line-end-position 0)))
  19593. ;; When the first headline start at point 2, don't choke while
  19594. ;; checking with `org-invisible-p'.
  19595. (or (= lep 1)
  19596. (not (org-invisible-p (1- (line-end-position 0)))))))
  19597. (forward-line -1))
  19598. ;; At the beginning of the first element within a greater
  19599. ;; element. Move to the beginning of the greater element.
  19600. ((and parent
  19601. (not (eq 'section (org-element-type parent)))
  19602. (= begin (org-element-property :contents-begin parent)))
  19603. (funcall reach (org-element-property :begin parent)))
  19604. ;; Since we have to move anyway, find the beginning
  19605. ;; position of the element above.
  19606. (t
  19607. (forward-char -1)
  19608. (org--backward-paragraph-once))))
  19609. ;; Skip paragraphs at the very beginning of footnote
  19610. ;; definitions or items.
  19611. ((and (eq type 'paragraph)
  19612. (org-with-point-at begin (not (bolp))))
  19613. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19614. ;; If the element is folded, skip it altogether.
  19615. ((org-with-point-at post-affiliated
  19616. (org-invisible-p (line-end-position) t))
  19617. (funcall reach begin))
  19618. ;; At the end of a greater element, move inside.
  19619. ((and contents-end
  19620. (<= contents-end (point))
  19621. (not (eq type 'paragraph)))
  19622. (cond
  19623. ((memq type '(footnote-definition plain-list))
  19624. (skip-chars-backward " \t\n")
  19625. (org--backward-paragraph-once))
  19626. ((= contents-end (point))
  19627. (forward-char -1)
  19628. (org--backward-paragraph-once))
  19629. (t
  19630. (goto-char contents-end))))
  19631. ;; Move between empty lines in some blocks.
  19632. ((and (memq type '(comment-block example-block export-block src-block
  19633. verse-block))
  19634. (let ((contents-start
  19635. (org-with-point-at post-affiliated
  19636. (line-beginning-position 2))))
  19637. (when (> (point) contents-start)
  19638. (let ((contents-end
  19639. (org-with-point-at end
  19640. (skip-chars-backward " \t\n")
  19641. (line-beginning-position))))
  19642. (if (> (point) contents-end)
  19643. (progn (goto-char contents-end) t)
  19644. (skip-chars-backward " \t\n" begin)
  19645. (re-search-backward "^[ \t]*\n" contents-start :move)
  19646. t))))))
  19647. ;; Move to element's start.
  19648. (t
  19649. (funcall reach begin))))))))
  19650. (defun org-forward-element ()
  19651. "Move forward by one element.
  19652. Move to the next element at the same level, when possible."
  19653. (interactive)
  19654. (cond ((eobp) (user-error "Cannot move further down"))
  19655. ((org-with-limited-levels (org-at-heading-p))
  19656. (let ((origin (point)))
  19657. (goto-char (org-end-of-subtree nil t))
  19658. (unless (org-with-limited-levels (org-at-heading-p))
  19659. (goto-char origin)
  19660. (user-error "Cannot move further down"))))
  19661. (t
  19662. (let* ((elem (org-element-at-point))
  19663. (end (org-element-property :end elem))
  19664. (parent (org-element-property :parent elem)))
  19665. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19666. (goto-char (org-element-property :end parent)))
  19667. ((integer-or-marker-p end) (goto-char end))
  19668. (t (message "No element at point")))))))
  19669. (defun org-backward-element ()
  19670. "Move backward by one element.
  19671. Move to the previous element at the same level, when possible."
  19672. (interactive)
  19673. (cond ((bobp) (user-error "Cannot move further up"))
  19674. ((org-with-limited-levels (org-at-heading-p))
  19675. ;; At a headline, move to the previous one, if any, or stay
  19676. ;; here.
  19677. (let ((origin (point)))
  19678. (org-with-limited-levels (org-backward-heading-same-level 1))
  19679. ;; When current headline has no sibling above, move to its
  19680. ;; parent.
  19681. (when (= (point) origin)
  19682. (or (org-with-limited-levels (org-up-heading-safe))
  19683. (progn (goto-char origin)
  19684. (user-error "Cannot move further up"))))))
  19685. (t
  19686. (let* ((elem (org-element-at-point))
  19687. (beg (org-element-property :begin elem)))
  19688. (cond
  19689. ;; Move to beginning of current element if point isn't
  19690. ;; there already.
  19691. ((null beg) (message "No element at point"))
  19692. ((/= (point) beg) (goto-char beg))
  19693. (t (goto-char beg)
  19694. (skip-chars-backward " \r\t\n")
  19695. (unless (bobp)
  19696. (let ((prev (org-element-at-point)))
  19697. (goto-char (org-element-property :begin prev))
  19698. (while (and (setq prev (org-element-property :parent prev))
  19699. (<= (org-element-property :end prev) beg))
  19700. (goto-char (org-element-property :begin prev)))))))))))
  19701. (defun org-up-element ()
  19702. "Move to upper element."
  19703. (interactive)
  19704. (if (org-with-limited-levels (org-at-heading-p))
  19705. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19706. (let* ((elem (org-element-at-point))
  19707. (parent (org-element-property :parent elem)))
  19708. (if (and parent
  19709. (not (memq (org-element-type parent) '(section org-data))))
  19710. (goto-char (org-element-property :begin parent))
  19711. (if (org-with-limited-levels (org-before-first-heading-p))
  19712. (user-error "No surrounding element")
  19713. (org-with-limited-levels (org-back-to-heading)))))))
  19714. (defun org-down-element ()
  19715. "Move to inner element."
  19716. (interactive)
  19717. (let ((element (org-element-at-point)))
  19718. (cond
  19719. ((memq (org-element-type element) '(plain-list table))
  19720. (goto-char (org-element-property :contents-begin element))
  19721. (forward-char))
  19722. ((memq (org-element-type element) org-element-greater-elements)
  19723. ;; If contents are hidden, first disclose them.
  19724. (when (org-invisible-p (line-end-position)) (org-cycle))
  19725. (goto-char (or (org-element-property :contents-begin element)
  19726. (user-error "No content for this element"))))
  19727. (t (user-error "No inner element")))))
  19728. (defun org-drag-element-backward ()
  19729. "Move backward element at point."
  19730. (interactive)
  19731. (let ((elem (or (org-element-at-point)
  19732. (user-error "No element at point"))))
  19733. (if (eq (org-element-type elem) 'headline)
  19734. ;; Preserve point when moving a whole tree, even if point was
  19735. ;; on blank lines below the headline.
  19736. (let ((offset (skip-chars-backward " \t\n")))
  19737. (unwind-protect (org-move-subtree-up)
  19738. (forward-char (- offset))))
  19739. (let ((prev-elem
  19740. (save-excursion
  19741. (goto-char (org-element-property :begin elem))
  19742. (skip-chars-backward " \r\t\n")
  19743. (unless (bobp)
  19744. (let* ((beg (org-element-property :begin elem))
  19745. (prev (org-element-at-point))
  19746. (up prev))
  19747. (while (and (setq up (org-element-property :parent up))
  19748. (<= (org-element-property :end up) beg))
  19749. (setq prev up))
  19750. prev)))))
  19751. ;; Error out if no previous element or previous element is
  19752. ;; a parent of the current one.
  19753. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19754. (user-error "Cannot drag element backward")
  19755. (let ((pos (point)))
  19756. (org-element-swap-A-B prev-elem elem)
  19757. (goto-char (+ (org-element-property :begin prev-elem)
  19758. (- pos (org-element-property :begin elem))))))))))
  19759. (defun org-drag-element-forward ()
  19760. "Move forward element at point."
  19761. (interactive)
  19762. (let* ((pos (point))
  19763. (elem (or (org-element-at-point)
  19764. (user-error "No element at point"))))
  19765. (when (= (point-max) (org-element-property :end elem))
  19766. (user-error "Cannot drag element forward"))
  19767. (goto-char (org-element-property :end elem))
  19768. (let ((next-elem (org-element-at-point)))
  19769. (when (or (org-element-nested-p elem next-elem)
  19770. (and (eq (org-element-type next-elem) 'headline)
  19771. (not (eq (org-element-type elem) 'headline))))
  19772. (goto-char pos)
  19773. (user-error "Cannot drag element forward"))
  19774. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19775. ;; body's length (without final blanks) and by the length of
  19776. ;; blanks between ELEM and NEXT-ELEM.
  19777. (let ((size-next (- (save-excursion
  19778. (goto-char (org-element-property :end next-elem))
  19779. (skip-chars-backward " \r\t\n")
  19780. (forward-line)
  19781. ;; Small correction if buffer doesn't end
  19782. ;; with a newline character.
  19783. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19784. (org-element-property :begin next-elem)))
  19785. (size-blank (- (org-element-property :end elem)
  19786. (save-excursion
  19787. (goto-char (org-element-property :end elem))
  19788. (skip-chars-backward " \r\t\n")
  19789. (forward-line)
  19790. (point)))))
  19791. (org-element-swap-A-B elem next-elem)
  19792. (goto-char (+ pos size-next size-blank))))))
  19793. (defun org-drag-line-forward (arg)
  19794. "Drag the line at point ARG lines forward."
  19795. (interactive "p")
  19796. (dotimes (_ (abs arg))
  19797. (let ((c (current-column)))
  19798. (if (< 0 arg)
  19799. (progn
  19800. (beginning-of-line 2)
  19801. (transpose-lines 1)
  19802. (beginning-of-line 0))
  19803. (transpose-lines 1)
  19804. (beginning-of-line -1))
  19805. (org-move-to-column c))))
  19806. (defun org-drag-line-backward (arg)
  19807. "Drag the line at point ARG lines backward."
  19808. (interactive "p")
  19809. (org-drag-line-forward (- arg)))
  19810. (defun org-mark-element ()
  19811. "Put point at beginning of this element, mark at end.
  19812. Interactively, if this command is repeated or (in Transient Mark
  19813. mode) if the mark is active, it marks the next element after the
  19814. ones already marked."
  19815. (interactive)
  19816. (let (deactivate-mark)
  19817. (if (and (called-interactively-p 'any)
  19818. (or (and (eq last-command this-command) (mark t))
  19819. (and transient-mark-mode mark-active)))
  19820. (set-mark
  19821. (save-excursion
  19822. (goto-char (mark))
  19823. (goto-char (org-element-property :end (org-element-at-point)))
  19824. (point)))
  19825. (let ((element (org-element-at-point)))
  19826. (end-of-line)
  19827. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19828. (goto-char (org-element-property :begin element))))))
  19829. (defun org-narrow-to-element ()
  19830. "Narrow buffer to current element."
  19831. (interactive)
  19832. (let ((elem (org-element-at-point)))
  19833. (cond
  19834. ((eq (car elem) 'headline)
  19835. (narrow-to-region
  19836. (org-element-property :begin elem)
  19837. (org-element-property :end elem)))
  19838. ((memq (car elem) org-element-greater-elements)
  19839. (narrow-to-region
  19840. (org-element-property :contents-begin elem)
  19841. (org-element-property :contents-end elem)))
  19842. (t
  19843. (narrow-to-region
  19844. (org-element-property :begin elem)
  19845. (org-element-property :end elem))))))
  19846. (defun org-transpose-element ()
  19847. "Transpose current and previous elements, keeping blank lines between.
  19848. Point is moved after both elements."
  19849. (interactive)
  19850. (org-skip-whitespace)
  19851. (let ((end (org-element-property :end (org-element-at-point))))
  19852. (org-drag-element-backward)
  19853. (goto-char end)))
  19854. (defun org-unindent-buffer ()
  19855. "Un-indent the visible part of the buffer.
  19856. Relative indentation (between items, inside blocks, etc.) isn't
  19857. modified."
  19858. (interactive)
  19859. (unless (eq major-mode 'org-mode)
  19860. (user-error "Cannot un-indent a buffer not in Org mode"))
  19861. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19862. (unindent-tree
  19863. (lambda (contents)
  19864. (dolist (element (reverse contents))
  19865. (if (memq (org-element-type element) '(headline section))
  19866. (funcall unindent-tree (org-element-contents element))
  19867. (save-excursion
  19868. (save-restriction
  19869. (narrow-to-region
  19870. (org-element-property :begin element)
  19871. (org-element-property :end element))
  19872. (org-do-remove-indentation))))))))
  19873. (funcall unindent-tree (org-element-contents parse-tree))))
  19874. (defun org-make-options-regexp (kwds &optional extra)
  19875. "Make a regular expression for keyword lines.
  19876. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19877. when non-nil, is a regexp matching keywords names."
  19878. (concat "^[ \t]*#\\+\\("
  19879. (regexp-opt kwds)
  19880. (and extra (concat (and kwds "\\|") extra))
  19881. "\\):[ \t]*\\(.*\\)"))
  19882. ;;; Conveniently switch to Info nodes
  19883. (defun org-info-find-node (&optional nodename)
  19884. "Find Info documentation NODENAME or Org documentation according context.
  19885. Started from `gnus-info-find-node'."
  19886. (interactive)
  19887. (Info-goto-node
  19888. (or nodename
  19889. (let ((default-org-info-node "(org) Top"))
  19890. (cond
  19891. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19892. ((eq 'org-mode major-mode)
  19893. (let* ((context (org-element-at-point))
  19894. (element-info-nodes ; compare to `org-element-all-elements'.
  19895. `((babel-call . "(org) Evaluating Code Blocks")
  19896. (center-block . "(org) Paragraphs")
  19897. (clock . ,default-org-info-node)
  19898. (comment . "(org) Comment Lines")
  19899. (comment-block . "(org) Comment Lines")
  19900. (diary-sexp . ,default-org-info-node)
  19901. (drawer . "(org) Drawers")
  19902. (dynamic-block . "(org) Dynamic Blocks")
  19903. (example-block . "(org) Literal Examples")
  19904. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19905. (fixed-width . ,default-org-info-node)
  19906. (footnote-definition . "(org) Creating Footnotes")
  19907. (headline . "(org) Document Structure")
  19908. (horizontal-rule . "(org) Built-in Table Editor")
  19909. (inlinetask . ,default-org-info-node)
  19910. (item . "(org) Plain Lists")
  19911. (keyword . "(org) Per-file keywords")
  19912. (latex-environment . "(org) LaTeX Export")
  19913. (node-property . "(org) Properties and Columns")
  19914. (paragraph . "(org) Paragraphs")
  19915. (plain-list . "(org) Plain Lists")
  19916. (planning . "(org) Deadlines and Scheduling")
  19917. (property-drawer . "(org) Properties and Columns")
  19918. (quote-block . "(org) Paragraphs")
  19919. (section . ,default-org-info-node)
  19920. (special-block . ,default-org-info-node)
  19921. (src-block . "(org) Working with Source Code")
  19922. (table . "(org) Tables")
  19923. (table-row . "(org) Tables")
  19924. (verse-block . "(org) Paragraphs"))))
  19925. (or (cdr (assoc (car context) element-info-nodes))
  19926. default-org-info-node)))
  19927. (t default-org-info-node))))))
  19928. ;;; Finish up
  19929. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19930. (lambda () (add-hook 'change-major-mode-hook
  19931. 'org-show-all 'append 'local)))
  19932. (provide 'org)
  19933. (run-hooks 'org-load-hook)
  19934. ;;; org.el ends here