org-clock.el 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106
  1. ;;; org-clock.el --- The time clocking code for Org mode -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2004-2020 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: https://orgmode.org
  6. ;;
  7. ;; This file is part of GNU Emacs.
  8. ;;
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  20. ;;
  21. ;;; Commentary:
  22. ;; This file contains the time clocking code for Org mode
  23. ;;; Code:
  24. (require 'cl-lib)
  25. (require 'org)
  26. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  27. (declare-function notifications-notify "notifications" (&rest params))
  28. (declare-function org-element-property "org-element" (property element))
  29. (declare-function org-element-type "org-element" (element))
  30. (declare-function org-link-display-format "ol" (s))
  31. (declare-function org-link-heading-search-string "ol" (&optional string))
  32. (declare-function org-link-make-string "ol" (link &optional description))
  33. (declare-function org-table-goto-line "org-table" (n))
  34. (declare-function org-dynamic-block-define "org" (type func))
  35. (declare-function w32-notification-notify "w32fns.c" (&rest params))
  36. (declare-function w32-notification-close "w32fns.c" (&rest params))
  37. (defvar org-frame-title-format-backup nil)
  38. (defvar org-state)
  39. (defvar org-link-bracket-re)
  40. (defvar org-time-stamp-formats)
  41. (defgroup org-clock nil
  42. "Options concerning clocking working time in Org mode."
  43. :tag "Org Clock"
  44. :group 'org-progress)
  45. (defcustom org-clock-into-drawer t
  46. "Non-nil when clocking info should be wrapped into a drawer.
  47. When non-nil, clocking info will be inserted into the same drawer
  48. as log notes (see variable `org-log-into-drawer'), if it exists,
  49. or \"LOGBOOK\" otherwise. If necessary, the drawer will be
  50. created.
  51. When an integer, the drawer is created only when the number of
  52. clocking entries in an item reaches or exceeds this value.
  53. When a string, it becomes the name of the drawer, ignoring the
  54. log notes drawer altogether.
  55. Do not check directly this variable in a Lisp program. Call
  56. function `org-clock-into-drawer' instead."
  57. :group 'org-todo
  58. :group 'org-clock
  59. :version "26.1"
  60. :package-version '(Org . "8.3")
  61. :type '(choice
  62. (const :tag "Always" t)
  63. (const :tag "Only when drawer exists" nil)
  64. (integer :tag "When at least N clock entries")
  65. (const :tag "Into LOGBOOK drawer" "LOGBOOK")
  66. (string :tag "Into Drawer named...")))
  67. (defun org-clock-into-drawer ()
  68. "Value of `org-clock-into-drawer'. but let properties overrule.
  69. If the current entry has or inherits a CLOCK_INTO_DRAWER
  70. property, it will be used instead of the default value.
  71. Return value is either a string, an integer, or nil."
  72. (let ((p (org-entry-get nil "CLOCK_INTO_DRAWER" 'inherit t)))
  73. (cond ((equal p "nil") nil)
  74. ((equal p "t") (or (org-log-into-drawer) "LOGBOOK"))
  75. ((org-string-nw-p p)
  76. (if (string-match-p "\\`[0-9]+\\'" p) (string-to-number p) p))
  77. ((org-string-nw-p org-clock-into-drawer))
  78. ((integerp org-clock-into-drawer) org-clock-into-drawer)
  79. ((not org-clock-into-drawer) nil)
  80. ((org-log-into-drawer))
  81. (t "LOGBOOK"))))
  82. (defcustom org-clock-out-when-done t
  83. "When non-nil, clock will be stopped when the clocked entry is marked DONE.
  84. \\<org-mode-map>\
  85. DONE here means any DONE-like state.
  86. A nil value means clock will keep running until stopped explicitly with
  87. `\\[org-clock-out]', or until the clock is started in a different item.
  88. Instead of t, this can also be a list of TODO states that should trigger
  89. clocking out."
  90. :group 'org-clock
  91. :type '(choice
  92. (const :tag "No" nil)
  93. (const :tag "Yes, when done" t)
  94. (repeat :tag "State list"
  95. (string :tag "TODO keyword"))))
  96. (defcustom org-clock-rounding-minutes 0
  97. "Rounding minutes when clocking in or out.
  98. The default value is 0 so that no rounding is done.
  99. When set to a non-integer value, use the car of
  100. `org-time-stamp-rounding-minutes', like for setting a time-stamp.
  101. E.g. if `org-clock-rounding-minutes' is set to 5, time is 14:47
  102. and you clock in: then the clock starts at 14:45. If you clock
  103. out within the next 5 minutes, the clock line will be removed;
  104. if you clock out 8 minutes after your clocked in, the clock
  105. out time will be 14:50."
  106. :group 'org-clock
  107. :version "24.4"
  108. :package-version '(Org . "8.0")
  109. :type '(choice
  110. (integer :tag "Minutes (0 for no rounding)")
  111. (symbol :tag "Use `org-time-stamp-rounding-minutes'" 'same-as-time-stamp)))
  112. (defcustom org-clock-out-remove-zero-time-clocks nil
  113. "Non-nil means remove the clock line when the resulting time is zero."
  114. :group 'org-clock
  115. :type 'boolean)
  116. (defcustom org-clock-in-switch-to-state nil
  117. "Set task to a special todo state while clocking it.
  118. The value should be the state to which the entry should be
  119. switched. If the value is a function, it must take one
  120. parameter (the current TODO state of the item) and return the
  121. state to switch it to."
  122. :group 'org-clock
  123. :group 'org-todo
  124. :type '(choice
  125. (const :tag "Don't force a state" nil)
  126. (string :tag "State")
  127. (symbol :tag "Function")))
  128. (defcustom org-clock-out-switch-to-state nil
  129. "Set task to a special todo state after clocking out.
  130. The value should be the state to which the entry should be
  131. switched. If the value is a function, it must take one
  132. parameter (the current TODO state of the item) and return the
  133. state to switch it to."
  134. :group 'org-clock
  135. :group 'org-todo
  136. :type '(choice
  137. (const :tag "Don't force a state" nil)
  138. (string :tag "State")
  139. (symbol :tag "Function")))
  140. (defcustom org-clock-history-length 5
  141. "Number of clock tasks to remember in history.
  142. Clocking in using history works best if this is at most 35, in
  143. which case all digits and capital letters are used up by the
  144. *Clock Task Select* buffer."
  145. :group 'org-clock
  146. :type 'integer)
  147. (defcustom org-clock-goto-may-find-recent-task t
  148. "Non-nil means `org-clock-goto' can go to recent task if no active clock."
  149. :group 'org-clock
  150. :type 'boolean)
  151. (defcustom org-clock-heading-function nil
  152. "When non-nil, should be a function to create `org-clock-heading'.
  153. This is the string shown in the mode line when a clock is running.
  154. The function is called with point at the beginning of the headline."
  155. :group 'org-clock
  156. :type '(choice (const nil) (function)))
  157. (defcustom org-clock-string-limit 0
  158. "Maximum length of clock strings in the mode line. 0 means no limit."
  159. :group 'org-clock
  160. :type 'integer)
  161. (defcustom org-clock-in-resume nil
  162. "If non-nil, resume clock when clocking into task with open clock.
  163. When clocking into a task with a clock entry which has not been closed,
  164. the clock can be resumed from that point."
  165. :group 'org-clock
  166. :type 'boolean)
  167. (defcustom org-clock-persist nil
  168. "When non-nil, save the running clock when Emacs is closed.
  169. The clock is resumed when Emacs restarts.
  170. When this is t, both the running clock, and the entire clock
  171. history are saved. When this is the symbol `clock', only the
  172. running clock is saved. When this is the symbol `history', only
  173. the clock history is saved.
  174. When Emacs restarts with saved clock information, the file containing
  175. the running clock as well as all files mentioned in the clock history
  176. will be visited.
  177. All this depends on running `org-clock-persistence-insinuate' in your
  178. Emacs initialization file."
  179. :group 'org-clock
  180. :type '(choice
  181. (const :tag "Just the running clock" clock)
  182. (const :tag "Just the history" history)
  183. (const :tag "Clock and history" t)
  184. (const :tag "No persistence" nil)))
  185. (defcustom org-clock-persist-file (convert-standard-filename
  186. (concat user-emacs-directory "org-clock-save.el"))
  187. "File to save clock data to."
  188. :group 'org-clock
  189. :type 'string)
  190. (defcustom org-clock-persist-query-save nil
  191. "When non-nil, ask before saving the current clock on exit."
  192. :group 'org-clock
  193. :type 'boolean)
  194. (defcustom org-clock-persist-query-resume t
  195. "When non-nil, ask before resuming any stored clock during load."
  196. :group 'org-clock
  197. :type 'boolean)
  198. (defcustom org-clock-sound nil
  199. "Sound to use for notifications.
  200. Possible values are:
  201. nil No sound played
  202. t Standard Emacs beep
  203. file name Play this sound file, fall back to beep"
  204. :group 'org-clock
  205. :type '(choice
  206. (const :tag "No sound" nil)
  207. (const :tag "Standard beep" t)
  208. (file :tag "Play sound file")))
  209. (defcustom org-clock-mode-line-total 'auto
  210. "Default setting for the time included for the mode line clock.
  211. This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
  212. Allowed values are:
  213. current Only the time in the current instance of the clock
  214. today All time clocked into this task today
  215. repeat All time clocked into this task since last repeat
  216. all All time ever recorded for this task
  217. auto Automatically, either `all', or `repeat' for repeating tasks"
  218. :group 'org-clock
  219. :type '(choice
  220. (const :tag "Current clock" current)
  221. (const :tag "Today's task time" today)
  222. (const :tag "Since last repeat" repeat)
  223. (const :tag "All task time" all)
  224. (const :tag "Automatically, `all' or since `repeat'" auto)))
  225. (defvaralias 'org-task-overrun-text 'org-clock-task-overrun-text)
  226. (defcustom org-clock-task-overrun-text nil
  227. "Extra mode line text to indicate that the clock is overrun.
  228. The can be nil to indicate that instead of adding text, the clock time
  229. should get a different face (`org-mode-line-clock-overrun').
  230. When this is a string, it is prepended to the clock string as an indication,
  231. also using the face `org-mode-line-clock-overrun'."
  232. :group 'org-clock
  233. :version "24.1"
  234. :type '(choice
  235. (const :tag "Just mark the time string" nil)
  236. (string :tag "Text to prepend")))
  237. (defcustom org-show-notification-timeout 3
  238. "Number of seconds to wait before closing Org notifications.
  239. This is applied to notifications sent with `notifications-notify'
  240. and `w32-notification-notify' only, not other mechanisms possibly
  241. set through `org-show-notification-handler'."
  242. :group 'org-clock
  243. :package-version '(Org . "9.4")
  244. :type 'integer)
  245. (defcustom org-show-notification-handler nil
  246. "Function or program to send notification with.
  247. The function or program will be called with the notification
  248. string as argument."
  249. :group 'org-clock
  250. :type '(choice
  251. (const nil)
  252. (string :tag "Program")
  253. (function :tag "Function")))
  254. (defgroup org-clocktable nil
  255. "Options concerning the clock table in Org mode."
  256. :tag "Org Clock Table"
  257. :group 'org-clock)
  258. (defcustom org-clocktable-defaults
  259. (list
  260. :maxlevel 2
  261. :lang (or (bound-and-true-p org-export-default-language) "en")
  262. :scope 'file
  263. :block nil
  264. :wstart 1
  265. :mstart 1
  266. :tstart nil
  267. :tend nil
  268. :step nil
  269. :stepskip0 nil
  270. :fileskip0 nil
  271. :tags nil
  272. :match nil
  273. :emphasize nil
  274. :link nil
  275. :narrow '40!
  276. :indent t
  277. :hidefiles nil
  278. :formula nil
  279. :timestamp nil
  280. :level nil
  281. :tcolumns nil
  282. :formatter nil)
  283. "Default properties for clock tables."
  284. :group 'org-clock
  285. :version "24.1"
  286. :type 'plist)
  287. (defcustom org-clock-clocktable-formatter 'org-clocktable-write-default
  288. "Function to turn clocking data into a table.
  289. For more information, see `org-clocktable-write-default'."
  290. :group 'org-clocktable
  291. :version "24.1"
  292. :type 'function)
  293. ;; FIXME: translate es and nl last string "Clock summary at"
  294. (defcustom org-clock-clocktable-language-setup
  295. '(("en" "File" "L" "Timestamp" "Headline" "Time" "ALL" "Total time" "File time" "Clock summary at")
  296. ("es" "Archivo" "N" "Fecha y hora" "Tarea" "Tiempo" "TODO" "Tiempo total" "Tiempo archivo" "Clock summary at")
  297. ("fr" "Fichier" "N" "Horodatage" "En-tête" "Durée" "TOUT" "Durée totale" "Durée fichier" "Horodatage sommaire à")
  298. ("nl" "Bestand" "N" "Tijdstip" "Hoofding" "Duur" "ALLES" "Totale duur" "Bestandstijd" "Clock summary at")
  299. ("de" "Datei" "E" "Zeitstempel" "Kopfzeile" "Dauer" "GESAMT"
  300. "Gesamtdauer" "Dateizeit" "Erstellt am"))
  301. "Terms used in clocktable, translated to different languages."
  302. :group 'org-clocktable
  303. :version "24.1"
  304. :type 'alist)
  305. (defcustom org-clock-clocktable-default-properties '(:maxlevel 2)
  306. "Default properties for new clocktables.
  307. These will be inserted into the BEGIN line, to make it easy for users to
  308. play with them."
  309. :group 'org-clocktable
  310. :package-version '(Org . "9.2")
  311. :type 'plist)
  312. (defcustom org-clock-idle-time nil
  313. "When non-nil, resolve open clocks if the user is idle more than X minutes."
  314. :group 'org-clock
  315. :type '(choice
  316. (const :tag "Never" nil)
  317. (integer :tag "After N minutes")))
  318. (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
  319. "When to automatically resolve open clocks found in Org buffers."
  320. :group 'org-clock
  321. :type '(choice
  322. (const :tag "Never" nil)
  323. (const :tag "Always" t)
  324. (const :tag "When no clock is running" when-no-clock-is-running)))
  325. (defcustom org-clock-report-include-clocking-task nil
  326. "When non-nil, include the current clocking task time in clock reports."
  327. :group 'org-clock
  328. :version "24.1"
  329. :type 'boolean)
  330. (defcustom org-clock-resolve-expert nil
  331. "Non-nil means do not show the splash buffer with the clock resolver."
  332. :group 'org-clock
  333. :version "24.1"
  334. :type 'boolean)
  335. (defcustom org-clock-continuously nil
  336. "Non-nil means to start clocking from the last clock-out time, if any."
  337. :type 'boolean
  338. :version "24.1"
  339. :group 'org-clock)
  340. (defcustom org-clock-total-time-cell-format "*%s*"
  341. "Format string for the total time cells."
  342. :group 'org-clock
  343. :version "24.1"
  344. :type 'string)
  345. (defcustom org-clock-file-time-cell-format "*%s*"
  346. "Format string for the file time cells."
  347. :group 'org-clock
  348. :version "24.1"
  349. :type 'string)
  350. (defcustom org-clock-clocked-in-display 'mode-line
  351. "When clocked in for a task, Org can display the current
  352. task and accumulated time in the mode line and/or frame title.
  353. Allowed values are:
  354. both displays in both mode line and frame title
  355. mode-line displays only in mode line (default)
  356. frame-title displays only in frame title
  357. nil current clock is not displayed"
  358. :group 'org-clock
  359. :type '(choice
  360. (const :tag "Mode line" mode-line)
  361. (const :tag "Frame title" frame-title)
  362. (const :tag "Both" both)
  363. (const :tag "None" nil)))
  364. (defcustom org-clock-frame-title-format '(t org-mode-line-string)
  365. "The value for `frame-title-format' when clocking in.
  366. When `org-clock-clocked-in-display' is set to `frame-title'
  367. or `both', clocking in will replace `frame-title-format' with
  368. this value. Clocking out will restore `frame-title-format'.
  369. `org-frame-title-string' is a format string using the same
  370. specifications than `frame-title-format', which see."
  371. :version "24.1"
  372. :group 'org-clock
  373. :type 'sexp)
  374. (defcustom org-clock-x11idle-program-name "x11idle"
  375. "Name of the program which prints X11 idle time in milliseconds.
  376. You can find x11idle.c in the contrib/scripts directory of the
  377. Org git distribution. Or, you can do:
  378. sudo apt-get install xprintidle
  379. if you are using Debian."
  380. :group 'org-clock
  381. :version "24.4"
  382. :package-version '(Org . "8.0")
  383. :type 'string)
  384. (defcustom org-clock-goto-before-context 2
  385. "Number of lines of context to display before currently clocked-in entry.
  386. This applies when using `org-clock-goto'."
  387. :group 'org-clock
  388. :type 'integer)
  389. (defcustom org-clock-display-default-range 'thisyear
  390. "Default range when displaying clocks with `org-clock-display'.
  391. Valid values are: `today', `yesterday', `thisweek', `lastweek',
  392. `thismonth', `lastmonth', `thisyear', `lastyear' and `untilnow'."
  393. :group 'org-clock
  394. :type '(choice (const today)
  395. (const yesterday)
  396. (const thisweek)
  397. (const lastweek)
  398. (const thismonth)
  399. (const lastmonth)
  400. (const thisyear)
  401. (const lastyear)
  402. (const untilnow)
  403. (const :tag "Select range interactively" interactive))
  404. :safe #'symbolp)
  405. (defcustom org-clock-auto-clockout-timer nil
  406. "Timer for auto clocking out when Emacs is idle.
  407. When set to a number, auto clock out the currently clocked in
  408. task after this number of seconds of idle time.
  409. This is only effective when `org-clock-auto-clockout-insinuate'
  410. is added to the user configuration."
  411. :group 'org-clock
  412. :package-version '(Org . "9.4")
  413. :type '(choice
  414. (integer :tag "Clock out after Emacs is idle for X seconds")
  415. (const :tag "Never auto clock out" nil)))
  416. (defvar org-clock-in-prepare-hook nil
  417. "Hook run when preparing the clock.
  418. This hook is run before anything happens to the task that
  419. you want to clock in. For example, you can use this hook
  420. to add an effort property.")
  421. (defvar org-clock-in-hook nil
  422. "Hook run when starting the clock.")
  423. (defvar org-clock-out-hook nil
  424. "Hook run when stopping the current clock.")
  425. (defvar org-clock-cancel-hook nil
  426. "Hook run when canceling the current clock.")
  427. (defvar org-clock-goto-hook nil
  428. "Hook run when selecting the currently clocked-in entry.")
  429. (defvar org-clock-has-been-used nil
  430. "Has the clock been used during the current Emacs session?")
  431. (defvar org-clock-stored-history nil
  432. "Clock history, populated by `org-clock-load'")
  433. (defvar org-clock-stored-resume-clock nil
  434. "Clock to resume, saved by `org-clock-load'")
  435. ;;; The clock for measuring work time.
  436. (defvar org-mode-line-string "")
  437. (put 'org-mode-line-string 'risky-local-variable t)
  438. (defvar org-clock-mode-line-timer nil)
  439. (defvar org-clock-idle-timer nil)
  440. (defvar org-clock-heading) ; defined in org.el
  441. (defvar org-clock-start-time "")
  442. (defvar org-clock-leftover-time nil
  443. "If non-nil, user canceled a clock; this is when leftover time started.")
  444. (defvar org-clock-effort ""
  445. "Effort estimate of the currently clocking task.")
  446. (defvar org-clock-total-time nil
  447. "Holds total time, spent previously on currently clocked item.
  448. This does not include the time in the currently running clock.")
  449. (defvar org-clock-history nil
  450. "List of marker pointing to recent clocked tasks.")
  451. (defvar org-clock-default-task (make-marker)
  452. "Marker pointing to the default task that should clock time.
  453. The clock can be made to switch to this task after clocking out
  454. of a different task.")
  455. (defvar org-clock-interrupted-task (make-marker)
  456. "Marker pointing to the task that has been interrupted by the current clock.")
  457. (defvar org-clock-mode-line-map (make-sparse-keymap))
  458. (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
  459. (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
  460. (defun org-clock--translate (s language)
  461. "Translate string S into using string LANGUAGE.
  462. Assume S in the English term to translate. Return S as-is if it
  463. cannot be translated."
  464. (or (nth (pcase s
  465. ("File" 1) ("L" 2) ("Timestamp" 3) ("Headline" 4) ("Time" 5)
  466. ("ALL" 6) ("Total time" 7) ("File time" 8) ("Clock summary at" 9))
  467. (assoc-string language org-clock-clocktable-language-setup t))
  468. s))
  469. (defun org-clock--mode-line-heading ()
  470. "Return currently clocked heading, formatted for mode line."
  471. (cond ((functionp org-clock-heading-function)
  472. (funcall org-clock-heading-function))
  473. ((org-before-first-heading-p) "???")
  474. (t (org-link-display-format
  475. (org-no-properties (org-get-heading t t t t))))))
  476. (defun org-clock-menu ()
  477. (interactive)
  478. (popup-menu
  479. '("Clock"
  480. ["Clock out" org-clock-out t]
  481. ["Change effort estimate" org-clock-modify-effort-estimate t]
  482. ["Go to clock entry" org-clock-goto t]
  483. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
  484. (defun org-clock-history-push (&optional pos buffer)
  485. "Push a marker to the clock history."
  486. (setq org-clock-history-length (max 1 org-clock-history-length))
  487. (let ((m (move-marker (make-marker)
  488. (or pos (point)) (org-base-buffer
  489. (or buffer (current-buffer)))))
  490. n l)
  491. (while (setq n (member m org-clock-history))
  492. (move-marker (car n) nil))
  493. (setq org-clock-history
  494. (delq nil
  495. (mapcar (lambda (x) (if (marker-buffer x) x nil))
  496. org-clock-history)))
  497. (when (>= (setq l (length org-clock-history)) org-clock-history-length)
  498. (setq org-clock-history
  499. (nreverse
  500. (nthcdr (- l org-clock-history-length -1)
  501. (nreverse org-clock-history)))))
  502. (push m org-clock-history)))
  503. (defun org-clock-save-markers-for-cut-and-paste (beg end)
  504. "Save relative positions of markers in region."
  505. (org-check-and-save-marker org-clock-marker beg end)
  506. (org-check-and-save-marker org-clock-hd-marker beg end)
  507. (org-check-and-save-marker org-clock-default-task beg end)
  508. (org-check-and-save-marker org-clock-interrupted-task beg end)
  509. (dolist (m org-clock-history)
  510. (org-check-and-save-marker m beg end)))
  511. (defun org-clock-drawer-name ()
  512. "Return clock drawer's name for current entry, or nil."
  513. (let ((drawer (org-clock-into-drawer)))
  514. (cond ((integerp drawer)
  515. (let ((log-drawer (org-log-into-drawer)))
  516. (if (stringp log-drawer) log-drawer "LOGBOOK")))
  517. ((stringp drawer) drawer)
  518. (t nil))))
  519. (defun org-clocking-buffer ()
  520. "Return the clocking buffer if we are currently clocking a task or nil."
  521. (marker-buffer org-clock-marker))
  522. (defun org-clocking-p ()
  523. "Return t when clocking a task."
  524. (not (equal (org-clocking-buffer) nil)))
  525. (defvar org-clock-before-select-task-hook nil
  526. "Hook called in task selection just before prompting the user.")
  527. (defun org-clock-select-task (&optional prompt)
  528. "Select a task that was recently associated with clocking.
  529. Return marker position of the selected task. Raise an error if
  530. there is no recent clock to choose from."
  531. (let (och chl sel-list rpl (i 0) s)
  532. ;; Remove successive dups from the clock history to consider
  533. (dolist (c org-clock-history)
  534. (unless (equal c (car och)) (push c och)))
  535. (setq och (reverse och) chl (length och))
  536. (if (zerop chl)
  537. (user-error "No recent clock")
  538. (save-window-excursion
  539. (org-switch-to-buffer-other-window
  540. (get-buffer-create "*Clock Task Select*"))
  541. (erase-buffer)
  542. (when (marker-buffer org-clock-default-task)
  543. (insert (org-add-props "Default Task\n" nil 'face 'bold))
  544. (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
  545. (push s sel-list))
  546. (when (marker-buffer org-clock-interrupted-task)
  547. (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
  548. (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
  549. (push s sel-list))
  550. (when (org-clocking-p)
  551. (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
  552. (setq s (org-clock-insert-selection-line ?c org-clock-marker))
  553. (push s sel-list))
  554. (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
  555. (dolist (m och)
  556. (when (marker-buffer m)
  557. (setq i (1+ i)
  558. s (org-clock-insert-selection-line
  559. (if (< i 10)
  560. (+ i ?0)
  561. (+ i (- ?A 10))) m))
  562. (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
  563. (push s sel-list)))
  564. (run-hooks 'org-clock-before-select-task-hook)
  565. (goto-char (point-min))
  566. ;; Set min-height relatively to circumvent a possible but in
  567. ;; `fit-window-to-buffer'
  568. (fit-window-to-buffer nil nil (if (< chl 10) chl (+ 5 chl)))
  569. (message (or prompt "Select task for clocking:"))
  570. (setq cursor-type nil rpl (read-char-exclusive))
  571. (kill-buffer)
  572. (cond
  573. ((eq rpl ?q) nil)
  574. ((eq rpl ?x) nil)
  575. ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
  576. (t (user-error "Invalid task choice %c" rpl)))))))
  577. (defun org-clock-insert-selection-line (i marker)
  578. "Insert a line for the clock selection menu.
  579. And return a cons cell with the selection character integer and the marker
  580. pointing to it."
  581. (when (marker-buffer marker)
  582. (let (cat task heading prefix)
  583. (with-current-buffer (org-base-buffer (marker-buffer marker))
  584. (org-with-wide-buffer
  585. (ignore-errors
  586. (goto-char marker)
  587. (setq cat (org-get-category)
  588. heading (org-get-heading 'notags)
  589. prefix (save-excursion
  590. (org-back-to-heading t)
  591. (looking-at org-outline-regexp)
  592. (match-string 0))
  593. task (substring
  594. (org-fontify-like-in-org-mode
  595. (concat prefix heading)
  596. org-odd-levels-only)
  597. (length prefix))))))
  598. (when (and cat task)
  599. (insert (format "[%c] %-12s %s\n" i cat task))
  600. (cons i marker)))))
  601. (defvar org-clock-task-overrun nil
  602. "Internal flag indicating if the clock has overrun the planned time.")
  603. (defvar org-clock-update-period 60
  604. "Number of seconds between mode line clock string updates.")
  605. (defun org-clock-get-clock-string ()
  606. "Form a clock-string, that will be shown in the mode line.
  607. If an effort estimate was defined for the current item, use
  608. 01:30/01:50 format (clocked/estimated).
  609. If not, show simply the clocked time like 01:50."
  610. (let ((clocked-time (org-clock-get-clocked-time)))
  611. (if org-clock-effort
  612. (let* ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
  613. (work-done-str
  614. (propertize (org-duration-from-minutes clocked-time)
  615. 'face
  616. (if (and org-clock-task-overrun
  617. (not org-clock-task-overrun-text))
  618. 'org-mode-line-clock-overrun
  619. 'org-mode-line-clock)))
  620. (effort-str (org-duration-from-minutes effort-in-minutes)))
  621. (format (propertize " [%s/%s] (%s)" 'face 'org-mode-line-clock)
  622. work-done-str effort-str org-clock-heading))
  623. (format (propertize " [%s] (%s)" 'face 'org-mode-line-clock)
  624. (org-duration-from-minutes clocked-time)
  625. org-clock-heading))))
  626. (defun org-clock-get-last-clock-out-time ()
  627. "Get the last clock-out time for the current subtree."
  628. (save-excursion
  629. (let ((end (save-excursion (org-end-of-subtree))))
  630. (when (re-search-forward (concat org-clock-string
  631. ".*\\]--\\(\\[[^]]+\\]\\)")
  632. end t)
  633. (org-time-string-to-time (match-string 1))))))
  634. (defun org-clock-update-mode-line (&optional refresh)
  635. "Update mode line with clock information.
  636. When optional argument is non-nil, refresh cached heading."
  637. (if org-clock-effort
  638. (org-clock-notify-once-if-expired)
  639. (setq org-clock-task-overrun nil))
  640. (when refresh (setq org-clock-heading (org-clock--mode-line-heading)))
  641. (setq org-mode-line-string
  642. (propertize
  643. (let ((clock-string (org-clock-get-clock-string))
  644. (help-text "Org mode clock is running.\nmouse-1 shows a \
  645. menu\nmouse-2 will jump to task"))
  646. (if (and (> org-clock-string-limit 0)
  647. (> (length clock-string) org-clock-string-limit))
  648. (propertize
  649. (substring clock-string 0 org-clock-string-limit)
  650. 'help-echo (concat help-text ": " org-clock-heading))
  651. (propertize clock-string 'help-echo help-text)))
  652. 'local-map org-clock-mode-line-map
  653. 'mouse-face 'mode-line-highlight))
  654. (if (and org-clock-task-overrun org-clock-task-overrun-text)
  655. (setq org-mode-line-string
  656. (concat (propertize
  657. org-clock-task-overrun-text
  658. 'face 'org-mode-line-clock-overrun)
  659. org-mode-line-string)))
  660. (force-mode-line-update))
  661. (defun org-clock-get-clocked-time ()
  662. "Get the clocked time for the current item in minutes.
  663. The time returned includes the time spent on this task in
  664. previous clocking intervals."
  665. (let ((currently-clocked-time
  666. (floor (org-time-convert-to-integer
  667. (org-time-since org-clock-start-time))
  668. 60)))
  669. (+ currently-clocked-time (or org-clock-total-time 0))))
  670. (defun org-clock-modify-effort-estimate (&optional value)
  671. "Add to or set the effort estimate of the item currently being clocked.
  672. VALUE can be a number of minutes, or a string with format hh:mm or mm.
  673. When the string starts with a + or a - sign, the current value of the effort
  674. property will be changed by that amount. If the effort value is expressed
  675. as an unit defined in `org-duration-units' (e.g. \"3h\"), the modified
  676. value will be converted to a hh:mm duration.
  677. This command will update the \"Effort\" property of the currently
  678. clocked item, and the value displayed in the mode line."
  679. (interactive)
  680. (if (org-clock-is-active)
  681. (let ((current org-clock-effort) sign)
  682. (unless value
  683. ;; Prompt user for a value or a change
  684. (setq value
  685. (read-string
  686. (format "Set effort (hh:mm or mm%s): "
  687. (if current
  688. (format ", prefix + to add to %s" org-clock-effort)
  689. "")))))
  690. (when (stringp value)
  691. ;; A string. See if it is a delta
  692. (setq sign (string-to-char value))
  693. (if (member sign '(?- ?+))
  694. (setq current (org-duration-to-minutes current)
  695. value (substring value 1))
  696. (setq current 0))
  697. (setq value (org-duration-to-minutes value))
  698. (if (equal ?- sign)
  699. (setq value (- current value))
  700. (if (equal ?+ sign) (setq value (+ current value)))))
  701. (setq value (max 0 value)
  702. org-clock-effort (org-duration-from-minutes value))
  703. (org-entry-put org-clock-marker "Effort" org-clock-effort)
  704. (org-clock-update-mode-line)
  705. (message "Effort is now %s" org-clock-effort))
  706. (message "Clock is not currently active")))
  707. (defvar org-clock-notification-was-shown nil
  708. "Shows if we have shown notification already.")
  709. (defun org-clock-notify-once-if-expired ()
  710. "Show notification if we spent more time than we estimated before.
  711. Notification is shown only once."
  712. (when (org-clocking-p)
  713. (let ((effort-in-minutes (org-duration-to-minutes org-clock-effort))
  714. (clocked-time (org-clock-get-clocked-time)))
  715. (if (setq org-clock-task-overrun
  716. (if (or (null effort-in-minutes) (zerop effort-in-minutes))
  717. nil
  718. (>= clocked-time effort-in-minutes)))
  719. (unless org-clock-notification-was-shown
  720. (setq org-clock-notification-was-shown t)
  721. (org-notify
  722. (format-message "Task `%s' should be finished by now. (%s)"
  723. org-clock-heading org-clock-effort)
  724. org-clock-sound))
  725. (setq org-clock-notification-was-shown nil)))))
  726. (defun org-notify (notification &optional play-sound)
  727. "Send a NOTIFICATION and maybe PLAY-SOUND.
  728. If PLAY-SOUND is non-nil, it overrides `org-clock-sound'."
  729. (org-show-notification notification)
  730. (if play-sound (org-clock-play-sound play-sound)))
  731. (defun org-show-notification (notification)
  732. "Show notification.
  733. Use `org-show-notification-handler' if defined,
  734. use libnotify if available, or fall back on a message."
  735. (ignore-errors (require 'notifications))
  736. (cond ((functionp org-show-notification-handler)
  737. (funcall org-show-notification-handler notification))
  738. ((stringp org-show-notification-handler)
  739. (start-process "emacs-timer-notification" nil
  740. org-show-notification-handler notification))
  741. ((fboundp 'w32-notification-notify)
  742. (let ((id (w32-notification-notify
  743. :title "Org mode message"
  744. :body notification
  745. :urgency 'low)))
  746. (run-with-timer
  747. org-show-notification-timeout
  748. nil
  749. (lambda () (w32-notification-close id)))))
  750. ((fboundp 'notifications-notify)
  751. (notifications-notify
  752. :title "Org mode message"
  753. :body notification
  754. :timeout (* org-show-notification-timeout 1000)
  755. ;; FIXME how to link to the Org icon?
  756. ;; :app-icon "~/.emacs.d/icons/mail.png"
  757. :urgency 'low))
  758. ((executable-find "notify-send")
  759. (start-process "emacs-timer-notification" nil
  760. "notify-send" notification))
  761. ;; Maybe the handler will send a message, so only use message as
  762. ;; a fall back option
  763. (t (message "%s" notification))))
  764. (defun org-clock-play-sound (&optional clock-sound)
  765. "Play sound as configured by `org-clock-sound'.
  766. Use alsa's aplay tool if available.
  767. If CLOCK-SOUND is non-nil, it overrides `org-clock-sound'."
  768. (let ((org-clock-sound (or clock-sound org-clock-sound)))
  769. (cond
  770. ((not org-clock-sound))
  771. ((eq org-clock-sound t) (beep t) (beep t))
  772. ((stringp org-clock-sound)
  773. (let ((file (expand-file-name org-clock-sound)))
  774. (if (file-exists-p file)
  775. (if (executable-find "aplay")
  776. (start-process "org-clock-play-notification" nil
  777. "aplay" file)
  778. (condition-case nil
  779. (play-sound-file file)
  780. (error (beep t) (beep t))))))))))
  781. (defvar org-clock-mode-line-entry nil
  782. "Information for the mode line about the running clock.")
  783. (defun org-find-open-clocks (file)
  784. "Search through the given file and find all open clocks."
  785. (let ((buf (or (get-file-buffer file)
  786. (find-file-noselect file)))
  787. (org-clock-re (concat org-clock-string " \\(\\[.*?\\]\\)$"))
  788. clocks)
  789. (with-current-buffer buf
  790. (save-excursion
  791. (goto-char (point-min))
  792. (while (re-search-forward org-clock-re nil t)
  793. (push (cons (copy-marker (match-end 1) t)
  794. (org-time-string-to-time (match-string 1)))
  795. clocks))))
  796. clocks))
  797. (defsubst org-is-active-clock (clock)
  798. "Return t if CLOCK is the currently active clock."
  799. (and (org-clock-is-active)
  800. (= org-clock-marker (car clock))))
  801. (defmacro org-with-clock-position (clock &rest forms)
  802. "Evaluate FORMS with CLOCK as the current active clock."
  803. `(with-current-buffer (marker-buffer (car ,clock))
  804. (org-with-wide-buffer
  805. (goto-char (car ,clock))
  806. (beginning-of-line)
  807. ,@forms)))
  808. (def-edebug-spec org-with-clock-position (form body))
  809. (put 'org-with-clock-position 'lisp-indent-function 1)
  810. (defmacro org-with-clock (clock &rest forms)
  811. "Evaluate FORMS with CLOCK as the current active clock.
  812. This macro also protects the current active clock from being altered."
  813. `(org-with-clock-position ,clock
  814. (let ((org-clock-start-time (cdr ,clock))
  815. (org-clock-total-time)
  816. (org-clock-history)
  817. (org-clock-effort)
  818. (org-clock-marker (car ,clock))
  819. (org-clock-hd-marker (save-excursion
  820. (org-back-to-heading t)
  821. (point-marker))))
  822. ,@forms)))
  823. (def-edebug-spec org-with-clock (form body))
  824. (put 'org-with-clock 'lisp-indent-function 1)
  825. (defsubst org-clock-clock-in (clock &optional resume start-time)
  826. "Clock in to the clock located by CLOCK.
  827. If necessary, clock-out of the currently active clock."
  828. (org-with-clock-position clock
  829. (let ((org-clock-in-resume (or resume org-clock-in-resume)))
  830. (org-clock-in nil start-time))))
  831. (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
  832. "Clock out of the clock located by CLOCK."
  833. (let ((temp (copy-marker (car clock)
  834. (marker-insertion-type (car clock)))))
  835. (if (org-is-active-clock clock)
  836. (org-clock-out nil fail-quietly at-time)
  837. (org-with-clock clock
  838. (org-clock-out nil fail-quietly at-time)))
  839. (setcar clock temp)))
  840. (defsubst org-clock-clock-cancel (clock)
  841. "Cancel the clock located by CLOCK."
  842. (let ((temp (copy-marker (car clock)
  843. (marker-insertion-type (car clock)))))
  844. (if (org-is-active-clock clock)
  845. (org-clock-cancel)
  846. (org-with-clock clock
  847. (org-clock-cancel)))
  848. (setcar clock temp)))
  849. (defvar org-clock-clocking-in nil)
  850. (defvar org-clock-resolving-clocks nil)
  851. (defvar org-clock-resolving-clocks-due-to-idleness nil)
  852. (defun org-clock-resolve-clock
  853. (clock resolve-to clock-out-time close restart fail-quietly)
  854. "Resolve CLOCK given the time RESOLVE-TO, and the present.
  855. CLOCK is a cons cell of the form (MARKER START-TIME)."
  856. (let ((org-clock-resolving-clocks t)
  857. ;; If the clocked entry contained only a clock and possibly
  858. ;; the associated drawer, and we either cancel it or clock it
  859. ;; out, `org-clock-out-remove-zero-time-clocks' may clear all
  860. ;; contents, and leave point on the /next/ headline. We store
  861. ;; the current entry location to be able to get back here when
  862. ;; we need to clock in again the previously clocked task.
  863. (heading (org-with-point-at (car clock)
  864. (org-back-to-heading t)
  865. (point-marker))))
  866. (pcase resolve-to
  867. (`nil
  868. (org-clock-clock-cancel clock)
  869. (when (and restart (not org-clock-clocking-in))
  870. (org-with-point-at heading (org-clock-in))))
  871. (`now
  872. (cond
  873. (restart (error "RESTART is not valid here"))
  874. ((or close org-clock-clocking-in)
  875. (org-clock-clock-out clock fail-quietly))
  876. ((org-is-active-clock clock) nil)
  877. (t (org-clock-clock-in clock t))))
  878. ((pred (org-time-less-p nil))
  879. (error "RESOLVE-TO must refer to a time in the past"))
  880. (_
  881. (when restart (error "RESTART is not valid here"))
  882. (org-clock-clock-out clock fail-quietly (or clock-out-time resolve-to))
  883. (cond
  884. (org-clock-clocking-in nil)
  885. (close
  886. (setq org-clock-leftover-time (and (null clock-out-time) resolve-to)))
  887. (t
  888. (org-with-point-at heading
  889. (org-clock-in nil (and clock-out-time resolve-to)))))))))
  890. (defun org-clock-jump-to-current-clock (&optional effective-clock)
  891. "When an Org clock is running, jump to it."
  892. (let ((drawer (org-clock-into-drawer))
  893. (clock (or effective-clock (cons org-clock-marker
  894. org-clock-start-time))))
  895. (unless (marker-buffer (car clock))
  896. (user-error "No Org clock is currently running"))
  897. (org-with-clock clock (org-clock-goto))
  898. (with-current-buffer (marker-buffer (car clock))
  899. (goto-char (car clock))
  900. (when drawer
  901. (org-with-wide-buffer
  902. (let ((drawer-re (format "^[ \t]*:%s:[ \t]*$"
  903. (regexp-quote (if (stringp drawer) drawer "LOGBOOK"))))
  904. (beg (save-excursion (org-back-to-heading t) (point))))
  905. (catch 'exit
  906. (while (re-search-backward drawer-re beg t)
  907. (let ((element (org-element-at-point)))
  908. (when (eq (org-element-type element) 'drawer)
  909. (when (> (org-element-property :end element) (car clock))
  910. (org-hide-drawer-toggle 'off nil element))
  911. (throw 'exit nil)))))))))))
  912. (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
  913. "Resolve an open Org clock.
  914. An open clock was found, with `dangling' possibly being non-nil.
  915. If this function was invoked with a prefix argument, non-dangling
  916. open clocks are ignored. The given clock requires some sort of
  917. user intervention to resolve it, either because a clock was left
  918. dangling or due to an idle timeout. The clock resolution can
  919. either be:
  920. (a) deleted, the user doesn't care about the clock
  921. (b) restarted from the current time (if no other clock is open)
  922. (c) closed, giving the clock X minutes
  923. (d) closed and then restarted
  924. (e) resumed, as if the user had never left
  925. The format of clock is (CONS MARKER START-TIME), where MARKER
  926. identifies the buffer and position the clock is open at (and
  927. thus, the heading it's under), and START-TIME is when the clock
  928. was started."
  929. (cl-assert clock)
  930. (let* ((ch
  931. (save-window-excursion
  932. (save-excursion
  933. (unless org-clock-resolving-clocks-due-to-idleness
  934. (org-clock-jump-to-current-clock clock))
  935. (unless org-clock-resolve-expert
  936. (with-output-to-temp-buffer "*Org Clock*"
  937. (princ (format-message "Select a Clock Resolution Command:
  938. i/q Ignore this question; the same as keeping all the idle time.
  939. k/K Keep X minutes of the idle time (default is all). If this
  940. amount is less than the default, you will be clocked out
  941. that many minutes after the time that idling began, and then
  942. clocked back in at the present time.
  943. t/T Like `k', but will ask you to specify a time (when you got
  944. distracted away), instead of a number of minutes.
  945. g/G Indicate that you \"got back\" X minutes ago. This is quite
  946. different from `k': it clocks you out from the beginning of
  947. the idle period and clock you back in X minutes ago.
  948. s/S Subtract the idle time from the current clock. This is the
  949. same as keeping 0 minutes.
  950. C Cancel the open timer altogether. It will be as though you
  951. never clocked in.
  952. j/J Jump to the current clock, to make manual adjustments.
  953. For all these options, using uppercase makes your final state
  954. to be CLOCKED OUT."))))
  955. (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
  956. (let (char-pressed)
  957. (while (or (null char-pressed)
  958. (and (not (memq char-pressed
  959. '(?k ?K ?g ?G ?s ?S ?C
  960. ?j ?J ?i ?q ?t ?T)))
  961. (or (ding) t)))
  962. (setq char-pressed
  963. (read-char (concat (funcall prompt-fn clock)
  964. " [jkKtTgGSscCiq]? ")
  965. nil 45)))
  966. (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
  967. (default
  968. (floor (org-time-convert-to-integer (org-time-since last-valid))
  969. 60))
  970. (keep
  971. (or (and (memq ch '(?k ?K))
  972. (read-number "Keep how many minutes? " default))
  973. (and (memq ch '(?t ?T))
  974. (floor
  975. (/ (float-time
  976. (org-time-subtract (org-read-date t t) last-valid))
  977. 60)))))
  978. (gotback
  979. (and (memq ch '(?g ?G))
  980. (read-number "Got back how many minutes ago? " default)))
  981. (subtractp (memq ch '(?s ?S)))
  982. (barely-started-p (org-time-less-p
  983. (org-time-subtract last-valid (cdr clock))
  984. 45))
  985. (start-over (and subtractp barely-started-p)))
  986. (cond
  987. ((memq ch '(?j ?J))
  988. (if (eq ch ?J)
  989. (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
  990. (org-clock-jump-to-current-clock clock))
  991. ((or (null ch)
  992. (not (memq ch '(?k ?K ?g ?G ?s ?S ?C ?t ?T))))
  993. (message ""))
  994. (t
  995. (org-clock-resolve-clock
  996. clock (cond
  997. ((or (eq ch ?C)
  998. ;; If the time on the clock was less than a minute before
  999. ;; the user went away, and they've ask to subtract all the
  1000. ;; time...
  1001. start-over)
  1002. nil)
  1003. ((or subtractp
  1004. (and gotback (= gotback 0)))
  1005. last-valid)
  1006. ((or (and keep (= keep default))
  1007. (and gotback (= gotback default)))
  1008. 'now)
  1009. (keep
  1010. (org-time-add last-valid (* 60 keep)))
  1011. (gotback
  1012. (org-time-since (* 60 gotback)))
  1013. (t
  1014. (error "Unexpected, please report this as a bug")))
  1015. (and gotback last-valid)
  1016. (memq ch '(?K ?G ?S ?T))
  1017. (and start-over
  1018. (not (memq ch '(?K ?G ?S ?C))))
  1019. fail-quietly)))))
  1020. ;;;###autoload
  1021. (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
  1022. "Resolve all currently open Org clocks.
  1023. If `only-dangling-p' is non-nil, only ask to resolve dangling
  1024. \(i.e., not currently open and valid) clocks."
  1025. (interactive "P")
  1026. (unless org-clock-resolving-clocks
  1027. (let ((org-clock-resolving-clocks t))
  1028. (dolist (file (org-files-list))
  1029. (let ((clocks (org-find-open-clocks file)))
  1030. (dolist (clock clocks)
  1031. (let ((dangling (or (not (org-clock-is-active))
  1032. (/= (car clock) org-clock-marker))))
  1033. (if (or (not only-dangling-p) dangling)
  1034. (org-clock-resolve
  1035. clock
  1036. (or prompt-fn
  1037. (function
  1038. (lambda (clock)
  1039. (format
  1040. "Dangling clock started %d mins ago"
  1041. (floor (org-time-convert-to-integer
  1042. (org-time-since (cdr clock)))
  1043. 60)))))
  1044. (or last-valid
  1045. (cdr clock)))))))))))
  1046. (defun org-emacs-idle-seconds ()
  1047. "Return the current Emacs idle time in seconds, or nil if not idle."
  1048. (let ((idle-time (current-idle-time)))
  1049. (if idle-time
  1050. (float-time idle-time)
  1051. 0)))
  1052. (defun org-mac-idle-seconds ()
  1053. "Return the current Mac idle time in seconds."
  1054. (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
  1055. (defvar org-x11idle-exists-p
  1056. ;; Check that x11idle exists
  1057. (and (eq window-system 'x)
  1058. (eq 0 (call-process-shell-command
  1059. (format "command -v %s" org-clock-x11idle-program-name)))
  1060. ;; Check that x11idle can retrieve the idle time
  1061. ;; FIXME: Why "..-shell-command" rather than just `call-process'?
  1062. (eq 0 (call-process-shell-command org-clock-x11idle-program-name))))
  1063. (defun org-x11-idle-seconds ()
  1064. "Return the current X11 idle time in seconds."
  1065. (/ (string-to-number (shell-command-to-string org-clock-x11idle-program-name)) 1000))
  1066. (defun org-user-idle-seconds ()
  1067. "Return the number of seconds the user has been idle for.
  1068. This routine returns a floating point number."
  1069. (cond
  1070. ((eq system-type 'darwin)
  1071. (org-mac-idle-seconds))
  1072. ((and (eq window-system 'x) org-x11idle-exists-p)
  1073. (org-x11-idle-seconds))
  1074. (t
  1075. (org-emacs-idle-seconds))))
  1076. (defvar org-clock-user-idle-seconds)
  1077. (defun org-resolve-clocks-if-idle ()
  1078. "Resolve all currently open Org clocks.
  1079. This is performed after `org-clock-idle-time' minutes, to check
  1080. if the user really wants to stay clocked in after being idle for
  1081. so long."
  1082. (when (and org-clock-idle-time (not org-clock-resolving-clocks)
  1083. org-clock-marker (marker-buffer org-clock-marker))
  1084. (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
  1085. (org-clock-user-idle-start
  1086. (org-time-since org-clock-user-idle-seconds))
  1087. (org-clock-resolving-clocks-due-to-idleness t))
  1088. (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
  1089. (org-clock-resolve
  1090. (cons org-clock-marker
  1091. org-clock-start-time)
  1092. (lambda (_)
  1093. (format "Clocked in & idle for %.1f mins"
  1094. (/ (float-time
  1095. (time-since org-clock-user-idle-start))
  1096. 60)))
  1097. org-clock-user-idle-start)))))
  1098. (defvar org-clock-current-task nil "Task currently clocked in.")
  1099. (defvar org-clock-out-time nil) ; store the time of the last clock-out
  1100. (defvar org--msg-extra)
  1101. ;;;###autoload
  1102. (defun org-clock-in (&optional select start-time)
  1103. "Start the clock on the current item.
  1104. If necessary, clock-out of the currently active clock.
  1105. With a `\\[universal-argument]' prefix argument SELECT, offer a list of \
  1106. recently clocked
  1107. tasks to clock into.
  1108. When SELECT is `\\[universal-argument] \ \\[universal-argument]', \
  1109. clock into the current task and mark it as
  1110. the default task, a special task that will always be offered in the
  1111. clocking selection, associated with the letter `d'.
  1112. When SELECT is `\\[universal-argument] \\[universal-argument] \
  1113. \\[universal-argument]', clock in by using the last clock-out
  1114. time as the start time. See `org-clock-continuously' to make this
  1115. the default behavior."
  1116. (interactive "P")
  1117. (setq org-clock-notification-was-shown nil)
  1118. (org-refresh-effort-properties)
  1119. (catch 'abort
  1120. (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
  1121. (org-clocking-p)))
  1122. ts selected-task target-pos (org--msg-extra "")
  1123. (leftover (and (not org-clock-resolving-clocks)
  1124. org-clock-leftover-time)))
  1125. (when (and org-clock-auto-clock-resolution
  1126. (or (not interrupting)
  1127. (eq t org-clock-auto-clock-resolution))
  1128. (not org-clock-clocking-in)
  1129. (not org-clock-resolving-clocks))
  1130. (setq org-clock-leftover-time nil)
  1131. (let ((org-clock-clocking-in t))
  1132. (org-resolve-clocks))) ; check if any clocks are dangling
  1133. (when (equal select '(64))
  1134. ;; Set start-time to `org-clock-out-time'
  1135. (let ((org-clock-continuously t))
  1136. (org-clock-in nil org-clock-out-time)
  1137. (throw 'abort nil)))
  1138. (when (equal select '(4))
  1139. (pcase (org-clock-select-task "Clock-in on task: ")
  1140. (`nil (error "Abort"))
  1141. (task (setq selected-task (copy-marker task)))))
  1142. (when (equal select '(16))
  1143. ;; Mark as default clocking task
  1144. (org-clock-mark-default-task))
  1145. (when interrupting
  1146. ;; We are interrupting the clocking of a different task. Save
  1147. ;; a marker to this task, so that we can go back. First check
  1148. ;; if we are trying to clock into the same task!
  1149. (when (or selected-task (derived-mode-p 'org-mode))
  1150. (org-with-point-at selected-task
  1151. (unless selected-task (org-back-to-heading t))
  1152. (when (and (eq (marker-buffer org-clock-hd-marker)
  1153. (org-base-buffer (current-buffer)))
  1154. (= (point) (marker-position org-clock-hd-marker))
  1155. (equal org-clock-current-task (org-get-heading t t t t)))
  1156. (message "Clock continues in %S" org-clock-heading)
  1157. (throw 'abort nil))))
  1158. (move-marker org-clock-interrupted-task
  1159. (marker-position org-clock-marker)
  1160. (marker-buffer org-clock-marker))
  1161. (let ((org-clock-clocking-in t))
  1162. (org-clock-out nil t)))
  1163. ;; Clock in at which position?
  1164. (setq target-pos
  1165. (if (and (eobp) (not (org-at-heading-p)))
  1166. (point-at-bol 0)
  1167. (point)))
  1168. (save-excursion
  1169. (when (and selected-task (marker-buffer selected-task))
  1170. ;; There is a selected task, move to the correct buffer
  1171. ;; and set the new target position.
  1172. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  1173. (setq target-pos (marker-position selected-task))
  1174. (move-marker selected-task nil))
  1175. (org-with-wide-buffer
  1176. (goto-char target-pos)
  1177. (org-back-to-heading t)
  1178. (or interrupting (move-marker org-clock-interrupted-task nil))
  1179. (run-hooks 'org-clock-in-prepare-hook)
  1180. (org-clock-history-push)
  1181. (setq org-clock-current-task (org-get-heading t t t t))
  1182. (cond ((functionp org-clock-in-switch-to-state)
  1183. (let ((case-fold-search nil))
  1184. (looking-at org-complex-heading-regexp))
  1185. (let ((newstate (funcall org-clock-in-switch-to-state
  1186. (match-string 2))))
  1187. (when newstate (org-todo newstate))))
  1188. ((and org-clock-in-switch-to-state
  1189. (not (looking-at (concat org-outline-regexp "[ \t]*"
  1190. org-clock-in-switch-to-state
  1191. "\\>"))))
  1192. (org-todo org-clock-in-switch-to-state)))
  1193. (setq org-clock-heading (org-clock--mode-line-heading))
  1194. (org-clock-find-position org-clock-in-resume)
  1195. (cond
  1196. ((and org-clock-in-resume
  1197. (looking-at
  1198. (concat "^[ \t]*" org-clock-string
  1199. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1200. " *\\sw+.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  1201. (message "Matched %s" (match-string 1))
  1202. (setq ts (concat "[" (match-string 1) "]"))
  1203. (goto-char (match-end 1))
  1204. (setq org-clock-start-time
  1205. (org-time-string-to-time (match-string 1)))
  1206. (setq org-clock-effort (org-entry-get (point) org-effort-property))
  1207. (setq org-clock-total-time (org-clock-sum-current-item
  1208. (org-clock-get-sum-start))))
  1209. ((eq org-clock-in-resume 'auto-restart)
  1210. ;; called from org-clock-load during startup,
  1211. ;; do not interrupt, but warn!
  1212. (message "Cannot restart clock because task does not contain unfinished clock")
  1213. (ding)
  1214. (sit-for 2)
  1215. (throw 'abort nil))
  1216. (t
  1217. (insert-before-markers "\n")
  1218. (backward-char 1)
  1219. (when (and (save-excursion
  1220. (end-of-line 0)
  1221. (org-in-item-p)))
  1222. (beginning-of-line 1)
  1223. (indent-line-to (- (current-indentation) 2)))
  1224. (insert org-clock-string " ")
  1225. (setq org-clock-effort (org-entry-get (point) org-effort-property))
  1226. (setq org-clock-total-time (org-clock-sum-current-item
  1227. (org-clock-get-sum-start)))
  1228. (setq org-clock-start-time
  1229. (or (and org-clock-continuously org-clock-out-time)
  1230. (and leftover
  1231. (y-or-n-p
  1232. (format
  1233. "You stopped another clock %d mins ago; start this one from then? "
  1234. (/ (org-time-convert-to-integer
  1235. (org-time-subtract
  1236. (org-current-time org-clock-rounding-minutes t)
  1237. leftover))
  1238. 60)))
  1239. leftover)
  1240. start-time
  1241. (org-current-time org-clock-rounding-minutes t)))
  1242. (setq ts (org-insert-time-stamp org-clock-start-time
  1243. 'with-hm 'inactive))
  1244. (org-indent-line)))
  1245. (move-marker org-clock-marker (point) (buffer-base-buffer))
  1246. (move-marker org-clock-hd-marker
  1247. (save-excursion (org-back-to-heading t) (point))
  1248. (buffer-base-buffer))
  1249. (setq org-clock-has-been-used t)
  1250. ;; add to mode line
  1251. (when (or (eq org-clock-clocked-in-display 'mode-line)
  1252. (eq org-clock-clocked-in-display 'both))
  1253. (or global-mode-string (setq global-mode-string '("")))
  1254. (or (memq 'org-mode-line-string global-mode-string)
  1255. (setq global-mode-string
  1256. (append global-mode-string '(org-mode-line-string)))))
  1257. ;; add to frame title
  1258. (when (or (eq org-clock-clocked-in-display 'frame-title)
  1259. (eq org-clock-clocked-in-display 'both))
  1260. (setq org-frame-title-format-backup frame-title-format)
  1261. (setq frame-title-format org-clock-frame-title-format))
  1262. (org-clock-update-mode-line)
  1263. (when org-clock-mode-line-timer
  1264. (cancel-timer org-clock-mode-line-timer)
  1265. (setq org-clock-mode-line-timer nil))
  1266. (when org-clock-clocked-in-display
  1267. (setq org-clock-mode-line-timer
  1268. (run-with-timer org-clock-update-period
  1269. org-clock-update-period
  1270. 'org-clock-update-mode-line)))
  1271. (when org-clock-idle-timer
  1272. (cancel-timer org-clock-idle-timer)
  1273. (setq org-clock-idle-timer nil))
  1274. (setq org-clock-idle-timer
  1275. (run-with-timer 60 60 'org-resolve-clocks-if-idle))
  1276. (message "Clock starts at %s - %s" ts org--msg-extra)
  1277. (run-hooks 'org-clock-in-hook))))))
  1278. (defun org-clock-auto-clockout ()
  1279. "Clock out the currently clocked in task if Emacs is idle.
  1280. See `org-clock-auto-clockout-timer' to set the idle time span.
  1281. This is only effective when `org-clock-auto-clockout-insinuate'
  1282. is present in the user configuration."
  1283. (when (and (numberp org-clock-auto-clockout-timer)
  1284. org-clock-current-task)
  1285. (run-with-idle-timer
  1286. org-clock-auto-clockout-timer nil #'org-clock-out)))
  1287. ;;;###autoload
  1288. (defun org-clock-toggle-auto-clockout ()
  1289. (interactive)
  1290. (if (memq 'org-clock-auto-clockout org-clock-in-hook)
  1291. (progn (remove-hook 'org-clock-in-hook #'org-clock-auto-clockout)
  1292. (message "Auto clock-out after idle time turned off"))
  1293. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t)
  1294. (message "Auto clock-out after idle time turned on")))
  1295. ;;;###autoload
  1296. (defun org-clock-in-last (&optional arg)
  1297. "Clock in the last closed clocked item.
  1298. When already clocking in, send a warning.
  1299. With a universal prefix argument, select the task you want to
  1300. clock in from the last clocked in tasks.
  1301. With two universal prefix arguments, start clocking using the
  1302. last clock-out time, if any.
  1303. With three universal prefix arguments, interactively prompt
  1304. for a todo state to switch to, overriding the existing value
  1305. `org-clock-in-switch-to-state'."
  1306. (interactive "P")
  1307. (if (equal arg '(4)) (org-clock-in arg)
  1308. (let ((start-time (if (or org-clock-continuously (equal arg '(16)))
  1309. (or org-clock-out-time
  1310. (org-current-time org-clock-rounding-minutes t))
  1311. (org-current-time org-clock-rounding-minutes t))))
  1312. (if (null org-clock-history)
  1313. (message "No last clock")
  1314. (let ((org-clock-in-switch-to-state
  1315. (if (and (not org-clock-current-task) (equal arg '(64)))
  1316. (completing-read "Switch to state: "
  1317. (and org-clock-history
  1318. (with-current-buffer
  1319. (marker-buffer (car org-clock-history))
  1320. org-todo-keywords-1)))
  1321. org-clock-in-switch-to-state))
  1322. (already-clocking org-clock-current-task))
  1323. (org-clock-clock-in (list (car org-clock-history)) nil start-time)
  1324. (or already-clocking
  1325. ;; Don't display a message if we are already clocking in
  1326. (message "Clocking back: %s (in %s)"
  1327. org-clock-current-task
  1328. (buffer-name (marker-buffer org-clock-marker)))))))))
  1329. (defun org-clock-mark-default-task ()
  1330. "Mark current task as default task."
  1331. (interactive)
  1332. (save-excursion
  1333. (org-back-to-heading t)
  1334. (move-marker org-clock-default-task (point))))
  1335. (defun org-clock-get-sum-start ()
  1336. "Return the time from which clock times should be counted.
  1337. This is for the currently running clock as it is displayed in the
  1338. mode line. This function looks at the properties LAST_REPEAT and
  1339. in particular CLOCK_MODELINE_TOTAL and the corresponding variable
  1340. `org-clock-mode-line-total' and then decides which time to use.
  1341. The time is always returned as UTC."
  1342. (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL" 'selective)
  1343. (symbol-name org-clock-mode-line-total)))
  1344. (lr (org-entry-get nil "LAST_REPEAT")))
  1345. (cond
  1346. ((equal cmt "current")
  1347. (setq org--msg-extra "showing time in current clock instance")
  1348. (current-time))
  1349. ((equal cmt "today")
  1350. (setq org--msg-extra "showing today's task time.")
  1351. (let* ((dt (decode-time))
  1352. (hour (nth 2 dt))
  1353. (day (nth 3 dt)))
  1354. (if (< hour org-extend-today-until) (setf (nth 3 dt) (1- day)))
  1355. (setf (nth 2 dt) org-extend-today-until)
  1356. (apply #'encode-time 0 0 (nthcdr 2 dt))))
  1357. ((or (equal cmt "all")
  1358. (and (or (not cmt) (equal cmt "auto"))
  1359. (not lr)))
  1360. (setq org--msg-extra "showing entire task time.")
  1361. nil)
  1362. ((or (equal cmt "repeat")
  1363. (and (or (not cmt) (equal cmt "auto"))
  1364. lr))
  1365. (setq org--msg-extra "showing task time since last repeat.")
  1366. (and lr (org-time-string-to-time lr)))
  1367. (t nil))))
  1368. (defun org-clock-find-position (find-unclosed)
  1369. "Find the location where the next clock line should be inserted.
  1370. When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
  1371. line and position cursor in that line."
  1372. (org-back-to-heading t)
  1373. (catch 'exit
  1374. (let* ((beg (line-beginning-position))
  1375. (end (save-excursion (outline-next-heading) (point)))
  1376. (org-clock-into-drawer (org-clock-into-drawer))
  1377. (drawer (org-clock-drawer-name)))
  1378. ;; Look for a running clock if FIND-UNCLOSED in non-nil.
  1379. (when find-unclosed
  1380. (let ((open-clock-re
  1381. (concat "^[ \t]*"
  1382. org-clock-string
  1383. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1384. " *\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  1385. (while (re-search-forward open-clock-re end t)
  1386. (let ((element (org-element-at-point)))
  1387. (when (and (eq (org-element-type element) 'clock)
  1388. (eq (org-element-property :status element) 'running))
  1389. (beginning-of-line)
  1390. (throw 'exit t))))))
  1391. ;; Look for an existing clock drawer.
  1392. (when drawer
  1393. (goto-char beg)
  1394. (let ((drawer-re (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$")))
  1395. (while (re-search-forward drawer-re end t)
  1396. (let ((element (org-element-at-point)))
  1397. (when (eq (org-element-type element) 'drawer)
  1398. (let ((cend (org-element-property :contents-end element)))
  1399. (if (and (not org-log-states-order-reversed) cend)
  1400. (goto-char cend)
  1401. (forward-line))
  1402. (throw 'exit t)))))))
  1403. (goto-char beg)
  1404. (let ((clock-re (concat "^[ \t]*" org-clock-string))
  1405. (count 0)
  1406. positions)
  1407. ;; Count the CLOCK lines and store their positions.
  1408. (save-excursion
  1409. (while (re-search-forward clock-re end t)
  1410. (let ((element (org-element-at-point)))
  1411. (when (eq (org-element-type element) 'clock)
  1412. (setq positions (cons (line-beginning-position) positions)
  1413. count (1+ count))))))
  1414. (cond
  1415. ((null positions)
  1416. ;; Skip planning line and property drawer, if any.
  1417. (org-end-of-meta-data)
  1418. (unless (bolp) (insert "\n"))
  1419. ;; Create a new drawer if necessary.
  1420. (when (and org-clock-into-drawer
  1421. (or (not (wholenump org-clock-into-drawer))
  1422. (< org-clock-into-drawer 2)))
  1423. (let ((beg (point)))
  1424. (insert ":" drawer ":\n:END:\n")
  1425. (org-indent-region beg (point))
  1426. (org-flag-region
  1427. (line-end-position -1) (1- (point)) t 'org-hide-drawer)
  1428. (forward-line -1))))
  1429. ;; When a clock drawer needs to be created because of the
  1430. ;; number of clock items or simply if it is missing, collect
  1431. ;; all clocks in the section and wrap them within the drawer.
  1432. ((if (wholenump org-clock-into-drawer)
  1433. (>= (1+ count) org-clock-into-drawer)
  1434. drawer)
  1435. ;; Skip planning line and property drawer, if any.
  1436. (org-end-of-meta-data)
  1437. (let ((beg (point)))
  1438. (insert
  1439. (mapconcat
  1440. (lambda (p)
  1441. (save-excursion
  1442. (goto-char p)
  1443. (org-trim (delete-and-extract-region
  1444. (save-excursion (skip-chars-backward " \r\t\n")
  1445. (line-beginning-position 2))
  1446. (line-beginning-position 2)))))
  1447. positions "\n")
  1448. "\n:END:\n")
  1449. (let ((end (point-marker)))
  1450. (goto-char beg)
  1451. (save-excursion (insert ":" drawer ":\n"))
  1452. (org-flag-region (line-end-position) (1- end) t 'org-hide-drawer)
  1453. (org-indent-region (point) end)
  1454. (forward-line)
  1455. (unless org-log-states-order-reversed
  1456. (goto-char end)
  1457. (beginning-of-line -1))
  1458. (set-marker end nil))))
  1459. (org-log-states-order-reversed (goto-char (car (last positions))))
  1460. (t (goto-char (car positions))))))))
  1461. (defun org-clock-restore-frame-title-format ()
  1462. "Restore `frame-title-format' from `org-frame-title-format-backup'.
  1463. `frame-title-format' is restored if `org-frame-title-format-backup' is not nil
  1464. and current `frame-title-format' is equal to `org-clock-frame-title-format'."
  1465. (when (and org-frame-title-format-backup
  1466. (equal frame-title-format org-clock-frame-title-format))
  1467. (setq frame-title-format org-frame-title-format-backup)))
  1468. ;;;###autoload
  1469. (defun org-clock-out (&optional switch-to-state fail-quietly at-time)
  1470. "Stop the currently running clock.
  1471. Throw an error if there is no running clock and FAIL-QUIETLY is nil.
  1472. With a universal prefix, prompt for a state to switch the clocked out task
  1473. to, overriding the existing value of `org-clock-out-switch-to-state'."
  1474. (interactive "P")
  1475. (catch 'exit
  1476. (when (not (org-clocking-p))
  1477. (setq global-mode-string
  1478. (delq 'org-mode-line-string global-mode-string))
  1479. (org-clock-restore-frame-title-format)
  1480. (force-mode-line-update)
  1481. (if fail-quietly (throw 'exit t) (user-error "No active clock")))
  1482. (let ((org-clock-out-switch-to-state
  1483. (if switch-to-state
  1484. (completing-read "Switch to state: "
  1485. (with-current-buffer
  1486. (marker-buffer org-clock-marker)
  1487. org-todo-keywords-1)
  1488. nil t "DONE")
  1489. org-clock-out-switch-to-state))
  1490. (now (org-current-time org-clock-rounding-minutes))
  1491. ts te s h m remove)
  1492. (setq org-clock-out-time now)
  1493. (save-excursion ; Do not replace this with `with-current-buffer'.
  1494. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1495. (save-restriction
  1496. (widen)
  1497. (goto-char org-clock-marker)
  1498. (beginning-of-line 1)
  1499. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1500. (equal (match-string 1) org-clock-string))
  1501. (setq ts (match-string 2))
  1502. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  1503. (goto-char (match-end 0))
  1504. (delete-region (point) (point-at-eol))
  1505. (insert "--")
  1506. (setq te (org-insert-time-stamp (or at-time now) 'with-hm 'inactive))
  1507. (setq s (org-time-convert-to-integer
  1508. (time-subtract
  1509. (org-time-string-to-time te)
  1510. (org-time-string-to-time ts)))
  1511. h (floor s 3600)
  1512. m (floor (mod s 3600) 60))
  1513. (insert " => " (format "%2d:%02d" h m))
  1514. (move-marker org-clock-marker nil)
  1515. (move-marker org-clock-hd-marker nil)
  1516. ;; Possibly remove zero time clocks. However, do not add
  1517. ;; a note associated to the CLOCK line in this case.
  1518. (cond ((and org-clock-out-remove-zero-time-clocks
  1519. (= 0 h m))
  1520. (setq remove t)
  1521. (delete-region (line-beginning-position)
  1522. (line-beginning-position 2)))
  1523. (org-log-note-clock-out
  1524. (org-add-log-setup
  1525. 'clock-out nil nil nil
  1526. (concat "# Task: " (org-get-heading t) "\n\n"))))
  1527. (when org-clock-mode-line-timer
  1528. (cancel-timer org-clock-mode-line-timer)
  1529. (setq org-clock-mode-line-timer nil))
  1530. (when org-clock-idle-timer
  1531. (cancel-timer org-clock-idle-timer)
  1532. (setq org-clock-idle-timer nil))
  1533. (setq global-mode-string
  1534. (delq 'org-mode-line-string global-mode-string))
  1535. (org-clock-restore-frame-title-format)
  1536. (when org-clock-out-switch-to-state
  1537. (save-excursion
  1538. (org-back-to-heading t)
  1539. (let ((org-clock-out-when-done nil))
  1540. (cond
  1541. ((functionp org-clock-out-switch-to-state)
  1542. (let ((case-fold-search nil))
  1543. (looking-at org-complex-heading-regexp))
  1544. (let ((newstate (funcall org-clock-out-switch-to-state
  1545. (match-string 2))))
  1546. (when newstate (org-todo newstate))))
  1547. ((and org-clock-out-switch-to-state
  1548. (not (looking-at (concat org-outline-regexp "[ \t]*"
  1549. org-clock-out-switch-to-state
  1550. "\\>"))))
  1551. (org-todo org-clock-out-switch-to-state))))))
  1552. (force-mode-line-update)
  1553. (message (if remove
  1554. "Clock stopped at %s after %s => LINE REMOVED"
  1555. "Clock stopped at %s after %s")
  1556. te (org-duration-from-minutes (+ (* 60 h) m)))
  1557. (run-hooks 'org-clock-out-hook)
  1558. (unless (org-clocking-p)
  1559. (setq org-clock-current-task nil)))))))
  1560. (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
  1561. (defun org-clock-remove-empty-clock-drawer ()
  1562. "Remove empty clock drawers in current subtree."
  1563. (save-excursion
  1564. (org-back-to-heading t)
  1565. (org-map-tree
  1566. (lambda ()
  1567. (let ((drawer (org-clock-drawer-name))
  1568. (case-fold-search t))
  1569. (when drawer
  1570. (let ((re (format "^[ \t]*:%s:[ \t]*$" (regexp-quote drawer)))
  1571. (end (save-excursion (outline-next-heading))))
  1572. (while (re-search-forward re end t)
  1573. (org-remove-empty-drawer-at (point))))))))))
  1574. (defun org-clock-timestamps-up (&optional n)
  1575. "Increase CLOCK timestamps at cursor.
  1576. Optional argument N tells to change by that many units."
  1577. (interactive "P")
  1578. (org-clock-timestamps-change 'up n))
  1579. (defun org-clock-timestamps-down (&optional n)
  1580. "Increase CLOCK timestamps at cursor.
  1581. Optional argument N tells to change by that many units."
  1582. (interactive "P")
  1583. (org-clock-timestamps-change 'down n))
  1584. (defun org-clock-timestamps-change (updown &optional n)
  1585. "Change CLOCK timestamps synchronously at cursor.
  1586. UPDOWN tells whether to change `up' or `down'.
  1587. Optional argument N tells to change by that many units."
  1588. (let ((tschange (if (eq updown 'up) 'org-timestamp-up
  1589. 'org-timestamp-down))
  1590. (timestamp? (org-at-timestamp-p 'lax))
  1591. ts1 begts1 ts2 begts2 updatets1 tdiff)
  1592. (when timestamp?
  1593. (save-excursion
  1594. (move-beginning-of-line 1)
  1595. (re-search-forward org-ts-regexp3 nil t)
  1596. (setq ts1 (match-string 0) begts1 (match-beginning 0))
  1597. (when (re-search-forward org-ts-regexp3 nil t)
  1598. (setq ts2 (match-string 0) begts2 (match-beginning 0))))
  1599. ;; Are we on the second timestamp?
  1600. (if (<= begts2 (point)) (setq updatets1 t))
  1601. (if (not ts2)
  1602. ;; fall back on org-timestamp-up if there is only one
  1603. (funcall tschange n)
  1604. (funcall tschange n)
  1605. (let ((ts (if updatets1 ts2 ts1))
  1606. (begts (if updatets1 begts1 begts2)))
  1607. (setq tdiff
  1608. (time-subtract
  1609. (org-time-string-to-time org-last-changed-timestamp)
  1610. (org-time-string-to-time ts)))
  1611. (save-excursion
  1612. (goto-char begts)
  1613. (org-timestamp-change
  1614. (round (/ (float-time tdiff)
  1615. (pcase timestamp?
  1616. (`minute 60)
  1617. (`hour 3600)
  1618. (`day (* 24 3600))
  1619. (`month (* 24 3600 31))
  1620. (`year (* 24 3600 365.2)))))
  1621. timestamp? 'updown)))))))
  1622. ;;;###autoload
  1623. (defun org-clock-cancel ()
  1624. "Cancel the running clock by removing the start timestamp."
  1625. (interactive)
  1626. (when (not (org-clocking-p))
  1627. (setq global-mode-string
  1628. (delq 'org-mode-line-string global-mode-string))
  1629. (org-clock-restore-frame-title-format)
  1630. (force-mode-line-update)
  1631. (user-error "No active clock"))
  1632. (save-excursion ; Do not replace this with `with-current-buffer'.
  1633. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1634. (goto-char org-clock-marker)
  1635. (if (looking-back (concat "^[ \t]*" org-clock-string ".*")
  1636. (line-beginning-position))
  1637. (progn (delete-region (1- (point-at-bol)) (point-at-eol))
  1638. (org-remove-empty-drawer-at (point)))
  1639. (message "Clock gone, cancel the timer anyway")
  1640. (sit-for 2)))
  1641. (move-marker org-clock-marker nil)
  1642. (move-marker org-clock-hd-marker nil)
  1643. (setq org-clock-current-task nil)
  1644. (setq global-mode-string
  1645. (delq 'org-mode-line-string global-mode-string))
  1646. (org-clock-restore-frame-title-format)
  1647. (force-mode-line-update)
  1648. (message "Clock canceled")
  1649. (run-hooks 'org-clock-cancel-hook))
  1650. ;;;###autoload
  1651. (defun org-clock-goto (&optional select)
  1652. "Go to the currently clocked-in entry, or to the most recently clocked one.
  1653. With prefix arg SELECT, offer recently clocked tasks for selection."
  1654. (interactive "@P")
  1655. (let* ((recent nil)
  1656. (m (cond
  1657. (select
  1658. (or (org-clock-select-task "Select task to go to: ")
  1659. (user-error "No task selected")))
  1660. ((org-clocking-p) org-clock-marker)
  1661. ((and org-clock-goto-may-find-recent-task
  1662. (car org-clock-history)
  1663. (marker-buffer (car org-clock-history)))
  1664. (setq recent t)
  1665. (car org-clock-history))
  1666. (t (user-error "No active or recent clock task")))))
  1667. (pop-to-buffer-same-window (marker-buffer m))
  1668. (if (or (< m (point-min)) (> m (point-max))) (widen))
  1669. (goto-char m)
  1670. (org-show-entry)
  1671. (org-back-to-heading t)
  1672. (recenter org-clock-goto-before-context)
  1673. (org-reveal)
  1674. (if recent
  1675. (message "No running clock, this is the most recently clocked task"))
  1676. (run-hooks 'org-clock-goto-hook)))
  1677. (defvar-local org-clock-file-total-minutes nil
  1678. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  1679. ;;;###autoload
  1680. (defun org-clock-sum-today (&optional headline-filter)
  1681. "Sum the times for each subtree for today."
  1682. (let ((range (org-clock-special-range 'today)))
  1683. (org-clock-sum (car range) (cadr range)
  1684. headline-filter :org-clock-minutes-today)))
  1685. (defun org-clock-sum-custom (&optional headline-filter range propname)
  1686. "Sum the times for each subtree for today."
  1687. (let ((r (or (and (symbolp range) (org-clock-special-range range))
  1688. (org-clock-special-range
  1689. (intern (completing-read
  1690. "Range: "
  1691. '("today" "yesterday" "thisweek" "lastweek"
  1692. "thismonth" "lastmonth" "thisyear" "lastyear"
  1693. "interactive")
  1694. nil t))))))
  1695. (org-clock-sum (car r) (cadr r)
  1696. headline-filter (or propname :org-clock-minutes-custom))))
  1697. ;;;###autoload
  1698. (defun org-clock-sum (&optional tstart tend headline-filter propname)
  1699. "Sum the times for each subtree.
  1700. Puts the resulting times in minutes as a text property on each headline.
  1701. TSTART and TEND can mark a time range to be considered.
  1702. HEADLINE-FILTER is a zero-arg function that, if specified, is called for
  1703. each headline in the time range with point at the headline. Headlines for
  1704. which HEADLINE-FILTER returns nil are excluded from the clock summation.
  1705. PROPNAME lets you set a custom text property instead of :org-clock-minutes."
  1706. (with-silent-modifications
  1707. (let* ((re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  1708. org-clock-string
  1709. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  1710. (lmax 30)
  1711. (ltimes (make-vector lmax 0))
  1712. (level 0)
  1713. (tstart (cond ((stringp tstart) (org-time-string-to-seconds tstart))
  1714. ((consp tstart) (float-time tstart))
  1715. (t tstart)))
  1716. (tend (cond ((stringp tend) (org-time-string-to-seconds tend))
  1717. ((consp tend) (float-time tend))
  1718. (t tend)))
  1719. (t1 0)
  1720. time)
  1721. (remove-text-properties (point-min) (point-max)
  1722. `(,(or propname :org-clock-minutes) t
  1723. :org-clock-force-headline-inclusion t))
  1724. (save-excursion
  1725. (goto-char (point-max))
  1726. (while (re-search-backward re nil t)
  1727. (cond
  1728. ((match-end 2)
  1729. ;; Two time stamps.
  1730. (let* ((ts (float-time
  1731. (apply #'encode-time
  1732. (save-match-data
  1733. (org-parse-time-string (match-string 2))))))
  1734. (te (float-time
  1735. (apply #'encode-time
  1736. (org-parse-time-string (match-string 3)))))
  1737. (dt (- (if tend (min te tend) te)
  1738. (if tstart (max ts tstart) ts))))
  1739. (when (> dt 0) (cl-incf t1 (floor dt 60)))))
  1740. ((match-end 4)
  1741. ;; A naked time.
  1742. (setq t1 (+ t1 (string-to-number (match-string 5))
  1743. (* 60 (string-to-number (match-string 4))))))
  1744. (t ;A headline
  1745. ;; Add the currently clocking item time to the total.
  1746. (when (and org-clock-report-include-clocking-task
  1747. (eq (org-clocking-buffer) (current-buffer))
  1748. (eq (marker-position org-clock-hd-marker) (point))
  1749. tstart
  1750. tend
  1751. (>= (float-time org-clock-start-time) tstart)
  1752. (<= (float-time org-clock-start-time) tend))
  1753. (let ((time (floor (org-time-convert-to-integer
  1754. (org-time-since org-clock-start-time))
  1755. 60)))
  1756. (setq t1 (+ t1 time))))
  1757. (let* ((headline-forced
  1758. (get-text-property (point)
  1759. :org-clock-force-headline-inclusion))
  1760. (headline-included
  1761. (or (null headline-filter)
  1762. (save-excursion
  1763. (save-match-data (funcall headline-filter))))))
  1764. (setq level (- (match-end 1) (match-beginning 1)))
  1765. (when (>= level lmax)
  1766. (setq ltimes (vconcat ltimes (make-vector lmax 0)) lmax (* 2 lmax)))
  1767. (when (or (> t1 0) (> (aref ltimes level) 0))
  1768. (when (or headline-included headline-forced)
  1769. (if headline-included
  1770. (cl-loop for l from 0 to level do
  1771. (aset ltimes l (+ (aref ltimes l) t1))))
  1772. (setq time (aref ltimes level))
  1773. (goto-char (match-beginning 0))
  1774. (put-text-property (point) (point-at-eol)
  1775. (or propname :org-clock-minutes) time)
  1776. (when headline-filter
  1777. (save-excursion
  1778. (save-match-data
  1779. (while (org-up-heading-safe)
  1780. (put-text-property
  1781. (point) (line-end-position)
  1782. :org-clock-force-headline-inclusion t))))))
  1783. (setq t1 0)
  1784. (cl-loop for l from level to (1- lmax) do
  1785. (aset ltimes l 0)))))))
  1786. (setq org-clock-file-total-minutes (aref ltimes 0))))))
  1787. (defun org-clock-sum-current-item (&optional tstart)
  1788. "Return time, clocked on current item in total."
  1789. (save-excursion
  1790. (save-restriction
  1791. (org-narrow-to-subtree)
  1792. (org-clock-sum tstart)
  1793. org-clock-file-total-minutes)))
  1794. ;;;###autoload
  1795. (defun org-clock-display (&optional arg)
  1796. "Show subtree times in the entire buffer.
  1797. By default, show the total time for the range defined in
  1798. `org-clock-display-default-range'. With `\\[universal-argument]' \
  1799. prefix, show
  1800. the total time for today instead.
  1801. With `\\[universal-argument] \\[universal-argument]' prefix, \
  1802. use a custom range, entered at prompt.
  1803. With `\\[universal-argument] \ \\[universal-argument] \
  1804. \\[universal-argument]' prefix, display the total time in the
  1805. echo area.
  1806. Use `\\[org-clock-remove-overlays]' to remove the subtree times."
  1807. (interactive "P")
  1808. (org-clock-remove-overlays)
  1809. (let* ((todayp (equal arg '(4)))
  1810. (customp (member arg '((16) today yesterday
  1811. thisweek lastweek thismonth
  1812. lastmonth thisyear lastyear
  1813. untilnow interactive)))
  1814. (prop (cond ((not arg) :org-clock-minutes-default)
  1815. (todayp :org-clock-minutes-today)
  1816. (customp :org-clock-minutes-custom)
  1817. (t :org-clock-minutes))))
  1818. (cond ((not arg) (org-clock-sum-custom
  1819. nil org-clock-display-default-range prop))
  1820. (todayp (org-clock-sum-today))
  1821. (customp (org-clock-sum-custom nil arg))
  1822. (t (org-clock-sum)))
  1823. (unless (equal arg '(64))
  1824. (save-excursion
  1825. (goto-char (point-min))
  1826. (let ((p nil))
  1827. (while (or (and (equal (setq p (point)) (point-min))
  1828. (get-text-property p prop))
  1829. (setq p (next-single-property-change (point) prop)))
  1830. (goto-char p)
  1831. (let ((time (get-text-property p prop)))
  1832. (when time (org-clock-put-overlay time)))))
  1833. ;; Arrange to remove the overlays upon next change.
  1834. (when org-remove-highlights-with-change
  1835. (add-hook 'before-change-functions 'org-clock-remove-overlays
  1836. nil 'local))))
  1837. (let* ((h (/ org-clock-file-total-minutes 60))
  1838. (m (- org-clock-file-total-minutes (* 60 h))))
  1839. (message (cond
  1840. (todayp
  1841. "Total file time for today: %s (%d hours and %d minutes)")
  1842. (customp
  1843. "Total file time (custom): %s (%d hours and %d minutes)")
  1844. (t
  1845. "Total file time: %s (%d hours and %d minutes)"))
  1846. (org-duration-from-minutes org-clock-file-total-minutes)
  1847. h m))))
  1848. (defvar-local org-clock-overlays nil)
  1849. (defun org-clock-put-overlay (time)
  1850. "Put an overlay on the headline at point, displaying TIME.
  1851. Create a new overlay and store it in `org-clock-overlays', so
  1852. that it will be easy to remove. This function assumes point is
  1853. on a headline."
  1854. (org-match-line org-complex-heading-regexp)
  1855. (goto-char (match-beginning 4))
  1856. (let* ((headline (match-string 4))
  1857. (text (concat headline
  1858. (org-add-props
  1859. (make-string
  1860. (max (- (- 60 (current-column))
  1861. (org-string-width headline)
  1862. (length (org-get-at-bol 'line-prefix)))
  1863. 0)
  1864. ?\·)
  1865. '(face shadow))
  1866. (org-add-props
  1867. (format " %9s " (org-duration-from-minutes time))
  1868. '(face org-clock-overlay))))
  1869. (o (make-overlay (point) (line-end-position))))
  1870. (org-overlay-display o text)
  1871. (push o org-clock-overlays)))
  1872. ;;;###autoload
  1873. (defun org-clock-remove-overlays (&optional _beg _end noremove)
  1874. "Remove the occur highlights from the buffer.
  1875. If NOREMOVE is nil, remove this function from the
  1876. `before-change-functions' in the current buffer."
  1877. (interactive)
  1878. (unless org-inhibit-highlight-removal
  1879. (mapc #'delete-overlay org-clock-overlays)
  1880. (setq org-clock-overlays nil)
  1881. (unless noremove
  1882. (remove-hook 'before-change-functions
  1883. 'org-clock-remove-overlays 'local))))
  1884. ;;;###autoload
  1885. (defun org-clock-out-if-current ()
  1886. "Clock out if the current entry contains the running clock.
  1887. This is used to stop the clock after a TODO entry is marked DONE,
  1888. and is only done if the variable `org-clock-out-when-done' is not nil."
  1889. (when (and (org-clocking-p)
  1890. org-clock-out-when-done
  1891. (marker-buffer org-clock-marker)
  1892. (or (and (eq t org-clock-out-when-done)
  1893. (member org-state org-done-keywords))
  1894. (and (listp org-clock-out-when-done)
  1895. (member org-state org-clock-out-when-done)))
  1896. (equal (or (buffer-base-buffer (org-clocking-buffer))
  1897. (org-clocking-buffer))
  1898. (or (buffer-base-buffer (current-buffer))
  1899. (current-buffer)))
  1900. (< (point) org-clock-marker)
  1901. (> (org-with-wide-buffer (org-entry-end-position))
  1902. org-clock-marker))
  1903. ;; Clock out, but don't accept a logging message for this.
  1904. (let ((org-log-note-clock-out nil)
  1905. (org-clock-out-switch-to-state nil))
  1906. (org-clock-out))))
  1907. ;;;###autoload
  1908. (defun org-clock-get-clocktable (&rest props)
  1909. "Get a formatted clocktable with parameters according to PROPS.
  1910. The table is created in a temporary buffer, fully formatted and
  1911. fontified, and then returned."
  1912. ;; Set the defaults
  1913. (setq props (plist-put props :name "clocktable"))
  1914. (unless (plist-member props :maxlevel)
  1915. (setq props (plist-put props :maxlevel 2)))
  1916. (unless (plist-member props :scope)
  1917. (setq props (plist-put props :scope 'agenda)))
  1918. (with-temp-buffer
  1919. (org-mode)
  1920. (org-create-dblock props)
  1921. (org-update-dblock)
  1922. (org-font-lock-ensure)
  1923. (forward-line 2)
  1924. (buffer-substring (point) (progn
  1925. (re-search-forward "^[ \t]*#\\+END" nil t)
  1926. (point-at-bol)))))
  1927. ;;;###autoload
  1928. (defun org-clock-report (&optional arg)
  1929. "Update or create a table containing a report about clocked time.
  1930. If point is inside an existing clocktable block, update it.
  1931. Otherwise, insert a new one.
  1932. The new table inherits its properties from the variable
  1933. `org-clock-clocktable-default-properties'. The scope of the
  1934. clocktable, when not specified in the previous variable, is
  1935. `subtree' when the function is called from within a subtree, and
  1936. `file' elsewhere.
  1937. When called with a prefix argument, move to the first clock table
  1938. in the buffer and update it."
  1939. (interactive "P")
  1940. (org-clock-remove-overlays)
  1941. (when arg
  1942. (org-find-dblock "clocktable")
  1943. (org-show-entry))
  1944. (pcase (org-in-clocktable-p)
  1945. (`nil
  1946. (org-create-dblock
  1947. (org-combine-plists
  1948. (list :scope (if (org-before-first-heading-p) 'file 'subtree))
  1949. org-clock-clocktable-default-properties
  1950. '(:name "clocktable"))))
  1951. (start (goto-char start)))
  1952. (org-update-dblock))
  1953. ;;;###autoload
  1954. (eval-after-load 'org
  1955. '(progn
  1956. (org-dynamic-block-define "clocktable" #'org-clock-report)))
  1957. (defun org-day-of-week (day month year)
  1958. "Return the day of the week as an integer."
  1959. (nth 6
  1960. (decode-time
  1961. (date-to-time
  1962. (format "%d-%02d-%02dT00:00:00" year month day)))))
  1963. (defun org-quarter-to-date (quarter year)
  1964. "Get the date (week day year) of the first day of a given quarter."
  1965. (let (startday)
  1966. (cond
  1967. ((= quarter 1)
  1968. (setq startday (org-day-of-week 1 1 year))
  1969. (cond
  1970. ((= startday 0)
  1971. (list 52 7 (- year 1)))
  1972. ((= startday 6)
  1973. (list 52 6 (- year 1)))
  1974. ((<= startday 4)
  1975. (list 1 startday year))
  1976. ((> startday 4)
  1977. (list 53 startday (- year 1)))
  1978. )
  1979. )
  1980. ((= quarter 2)
  1981. (setq startday (org-day-of-week 1 4 year))
  1982. (cond
  1983. ((= startday 0)
  1984. (list 13 startday year))
  1985. ((< startday 4)
  1986. (list 14 startday year))
  1987. ((>= startday 4)
  1988. (list 13 startday year))
  1989. )
  1990. )
  1991. ((= quarter 3)
  1992. (setq startday (org-day-of-week 1 7 year))
  1993. (cond
  1994. ((= startday 0)
  1995. (list 26 startday year))
  1996. ((< startday 4)
  1997. (list 27 startday year))
  1998. ((>= startday 4)
  1999. (list 26 startday year))
  2000. )
  2001. )
  2002. ((= quarter 4)
  2003. (setq startday (org-day-of-week 1 10 year))
  2004. (cond
  2005. ((= startday 0)
  2006. (list 39 startday year))
  2007. ((<= startday 4)
  2008. (list 40 startday year))
  2009. ((> startday 4)
  2010. (list 39 startday year)))))))
  2011. (defun org-clock-special-range (key &optional time as-strings wstart mstart)
  2012. "Return two times bordering a special time range.
  2013. KEY is a symbol specifying the range and can be one of `today',
  2014. `yesterday', `thisweek', `lastweek', `thismonth', `lastmonth',
  2015. `thisyear', `lastyear' or `untilnow'. If set to `interactive',
  2016. user is prompted for range boundaries. It can be a string or an
  2017. integer.
  2018. By default, a week starts Monday 0:00 and ends Sunday 24:00. The
  2019. range is determined relative to TIME, which defaults to current
  2020. time.
  2021. The return value is a list containing two internal times, one for
  2022. the beginning of the range and one for its end, like the ones
  2023. returned by `current-time' or `encode-time' and a string used to
  2024. display information. If AS-STRINGS is non-nil, the returned
  2025. times will be formatted strings. Note that the first element is
  2026. always nil when KEY is `untilnow'.
  2027. If WSTART is non-nil, use this number to specify the starting day
  2028. of a week (monday is 1). If MSTART is non-nil, use this number
  2029. to specify the starting day of a month (1 is the first day of the
  2030. month). If you can combine both, the month starting day will
  2031. have priority."
  2032. (let* ((tm (decode-time time))
  2033. (m (nth 1 tm))
  2034. (h (nth 2 tm))
  2035. (d (nth 3 tm))
  2036. (month (nth 4 tm))
  2037. (y (nth 5 tm))
  2038. (dow (nth 6 tm))
  2039. (skey (format "%s" key))
  2040. (shift 0)
  2041. (q (cond ((>= month 10) 4)
  2042. ((>= month 7) 3)
  2043. ((>= month 4) 2)
  2044. (t 1)))
  2045. m1 h1 d1 month1 y1 shiftedy shiftedm shiftedq)
  2046. (cond
  2047. ((string-match "\\`[0-9]+\\'" skey)
  2048. (setq y (string-to-number skey) month 1 d 1 key 'year))
  2049. ((string-match "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)\\'" skey)
  2050. (setq y (string-to-number (match-string 1 skey))
  2051. month (string-to-number (match-string 2 skey))
  2052. d 1
  2053. key 'month))
  2054. ((string-match "\\`\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)\\'" skey)
  2055. (require 'cal-iso)
  2056. (let ((date (calendar-gregorian-from-absolute
  2057. (calendar-iso-to-absolute
  2058. (list (string-to-number (match-string 2 skey))
  2059. 1
  2060. (string-to-number (match-string 1 skey)))))))
  2061. (setq d (nth 1 date)
  2062. month (car date)
  2063. y (nth 2 date)
  2064. dow 1
  2065. key 'week)))
  2066. ((string-match "\\`\\([0-9]+\\)-[qQ]\\([1-4]\\)\\'" skey)
  2067. (require 'cal-iso)
  2068. (setq q (string-to-number (match-string 2 skey)))
  2069. (let ((date (calendar-gregorian-from-absolute
  2070. (calendar-iso-to-absolute
  2071. (org-quarter-to-date
  2072. q (string-to-number (match-string 1 skey)))))))
  2073. (setq d (nth 1 date)
  2074. month (car date)
  2075. y (nth 2 date)
  2076. dow 1
  2077. key 'quarter)))
  2078. ((string-match
  2079. "\\`\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)\\'"
  2080. skey)
  2081. (setq y (string-to-number (match-string 1 skey))
  2082. month (string-to-number (match-string 2 skey))
  2083. d (string-to-number (match-string 3 skey))
  2084. key 'day))
  2085. ((string-match "\\([-+][0-9]+\\)\\'" skey)
  2086. (setq shift (string-to-number (match-string 1 skey))
  2087. key (intern (substring skey 0 (match-beginning 1))))
  2088. (when (and (memq key '(quarter thisq)) (> shift 0))
  2089. (error "Looking forward with quarters isn't implemented"))))
  2090. (when (= shift 0)
  2091. (pcase key
  2092. (`yesterday (setq key 'today shift -1))
  2093. (`lastweek (setq key 'week shift -1))
  2094. (`lastmonth (setq key 'month shift -1))
  2095. (`lastyear (setq key 'year shift -1))
  2096. (`lastq (setq key 'quarter shift -1))))
  2097. ;; Prepare start and end times depending on KEY's type.
  2098. (pcase key
  2099. ((or `day `today) (setq m 0
  2100. h org-extend-today-until
  2101. h1 (+ 24 org-extend-today-until)
  2102. d (+ d shift)))
  2103. ((or `week `thisweek)
  2104. (let* ((ws (or wstart 1))
  2105. (diff (+ (* -7 shift) (if (= dow 0) (- 7 ws) (- dow ws)))))
  2106. (setq m 0 h org-extend-today-until d (- d diff) d1 (+ 7 d))))
  2107. ((or `month `thismonth)
  2108. (setq h org-extend-today-until m 0 d (or mstart 1)
  2109. month (+ month shift) month1 (1+ month)))
  2110. ((or `quarter `thisq)
  2111. ;; Compute if this shift remains in this year. If not, compute
  2112. ;; how many years and quarters we have to shift (via floor*) and
  2113. ;; compute the shifted years, months and quarters.
  2114. (cond
  2115. ((< (+ (- q 1) shift) 0) ; Shift not in this year.
  2116. (let* ((interval (* -1 (+ (- q 1) shift)))
  2117. ;; Set tmp to ((years to shift) (quarters to shift)).
  2118. (tmp (cl-floor interval 4)))
  2119. ;; Due to the use of floor, 0 quarters actually means 4.
  2120. (if (= 0 (nth 1 tmp))
  2121. (setq shiftedy (- y (nth 0 tmp))
  2122. shiftedm 1
  2123. shiftedq 1)
  2124. (setq shiftedy (- y (+ 1 (nth 0 tmp)))
  2125. shiftedm (- 13 (* 3 (nth 1 tmp)))
  2126. shiftedq (- 5 (nth 1 tmp)))))
  2127. (setq m 0 h org-extend-today-until d 1
  2128. month shiftedm month1 (+ 3 shiftedm) y shiftedy))
  2129. ((> (+ q shift) 0) ; Shift is within this year.
  2130. (setq shiftedq (+ q shift))
  2131. (setq shiftedy y)
  2132. (let ((qshift (* 3 (1- (+ q shift)))))
  2133. (setq m 0 h org-extend-today-until d 1
  2134. month (+ 1 qshift) month1 (+ 4 qshift))))))
  2135. ((or `year `thisyear)
  2136. (setq m 0 h org-extend-today-until d 1 month 1 y (+ y shift) y1 (1+ y)))
  2137. ((or `interactive `untilnow)) ; Special cases, ignore them.
  2138. (_ (user-error "No such time block %s" key)))
  2139. ;; Format start and end times according to AS-STRINGS.
  2140. (let* ((start (pcase key
  2141. (`interactive (org-read-date nil t nil "Range start? "))
  2142. (`untilnow nil)
  2143. (_ (encode-time 0 m h d month y))))
  2144. (end (pcase key
  2145. (`interactive (org-read-date nil t nil "Range end? "))
  2146. (`untilnow (current-time))
  2147. (_ (encode-time 0
  2148. (or m1 m)
  2149. (or h1 h)
  2150. (or d1 d)
  2151. (or month1 month)
  2152. (or y1 y)))))
  2153. (text
  2154. (pcase key
  2155. ((or `day `today) (format-time-string "%A, %B %d, %Y" start))
  2156. ((or `week `thisweek) (format-time-string "week %G-W%V" start))
  2157. ((or `month `thismonth) (format-time-string "%B %Y" start))
  2158. ((or `year `thisyear) (format-time-string "the year %Y" start))
  2159. ((or `quarter `thisq)
  2160. (concat (org-count-quarter shiftedq)
  2161. " quarter of " (number-to-string shiftedy)))
  2162. (`interactive "(Range interactively set)")
  2163. (`untilnow "now"))))
  2164. (if (not as-strings) (list start end text)
  2165. (let ((f (cdr org-time-stamp-formats)))
  2166. (list (and start (format-time-string f start))
  2167. (format-time-string f end)
  2168. text))))))
  2169. (defun org-count-quarter (n)
  2170. (cond
  2171. ((= n 1) "1st")
  2172. ((= n 2) "2nd")
  2173. ((= n 3) "3rd")
  2174. ((= n 4) "4th")))
  2175. ;;;###autoload
  2176. (defun org-clocktable-shift (dir n)
  2177. "Try to shift the :block date of the clocktable at point.
  2178. Point must be in the #+BEGIN: line of a clocktable, or this function
  2179. will throw an error.
  2180. DIR is a direction, a symbol `left', `right', `up', or `down'.
  2181. Both `left' and `down' shift the block toward the past, `up' and `right'
  2182. push it toward the future.
  2183. N is the number of shift steps to take. The size of the step depends on
  2184. the currently selected interval size."
  2185. (setq n (prefix-numeric-value n))
  2186. (and (memq dir '(left down)) (setq n (- n)))
  2187. (save-excursion
  2188. (goto-char (point-at-bol))
  2189. (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
  2190. (user-error "Line needs a :block definition before this command works")
  2191. (let* ((b (match-beginning 1)) (e (match-end 1))
  2192. (s (match-string 1))
  2193. block shift ins y mw d date wp m)
  2194. (cond
  2195. ((equal s "yesterday") (setq s "today-1"))
  2196. ((equal s "lastweek") (setq s "thisweek-1"))
  2197. ((equal s "lastmonth") (setq s "thismonth-1"))
  2198. ((equal s "lastyear") (setq s "thisyear-1"))
  2199. ((equal s "lastq") (setq s "thisq-1")))
  2200. (cond
  2201. ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
  2202. (setq block (match-string 1 s)
  2203. shift (if (match-end 2)
  2204. (string-to-number (match-string 2 s))
  2205. 0))
  2206. (setq shift (+ shift n))
  2207. (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
  2208. ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
  2209. ;; 1 1 2 3 3 4 4 5 6 6 5 2
  2210. (setq y (string-to-number (match-string 1 s))
  2211. wp (and (match-end 3) (match-string 3 s))
  2212. mw (and (match-end 4) (string-to-number (match-string 4 s)))
  2213. d (and (match-end 6) (string-to-number (match-string 6 s))))
  2214. (cond
  2215. (d (setq ins (format-time-string
  2216. "%Y-%m-%d"
  2217. (encode-time 0 0 0 (+ d n) m y))))
  2218. ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
  2219. (require 'cal-iso)
  2220. (setq date (calendar-gregorian-from-absolute
  2221. (calendar-iso-to-absolute (list (+ mw n) 1 y))))
  2222. (setq ins (format-time-string
  2223. "%G-W%V"
  2224. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  2225. ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
  2226. (require 'cal-iso)
  2227. ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
  2228. (if (> (+ mw n) 4)
  2229. (setq mw 0
  2230. y (+ 1 y))
  2231. ())
  2232. ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
  2233. (if (= (+ mw n) 0)
  2234. (setq mw 5
  2235. y (- y 1))
  2236. ())
  2237. (setq date (calendar-gregorian-from-absolute
  2238. (calendar-iso-to-absolute (org-quarter-to-date (+ mw n) y))))
  2239. (setq ins (format-time-string
  2240. (concat (number-to-string y) "-Q" (number-to-string (+ mw n)))
  2241. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  2242. (mw
  2243. (setq ins (format-time-string
  2244. "%Y-%m"
  2245. (encode-time 0 0 0 1 (+ mw n) y))))
  2246. (y
  2247. (setq ins (number-to-string (+ y n))))))
  2248. (t (user-error "Cannot shift clocktable block")))
  2249. (when ins
  2250. (goto-char b)
  2251. (insert ins)
  2252. (delete-region (point) (+ (point) (- e b)))
  2253. (beginning-of-line 1)
  2254. (org-update-dblock)
  2255. t)))))
  2256. ;;;###autoload
  2257. (defun org-dblock-write:clocktable (params)
  2258. "Write the standard clocktable."
  2259. (setq params (org-combine-plists org-clocktable-defaults params))
  2260. (catch 'exit
  2261. (let* ((scope (plist-get params :scope))
  2262. (files (pcase scope
  2263. (`agenda
  2264. (org-agenda-files t))
  2265. (`agenda-with-archives
  2266. (org-add-archive-files (org-agenda-files t)))
  2267. (`file-with-archives
  2268. (and buffer-file-name
  2269. (org-add-archive-files (list buffer-file-name))))
  2270. ((or `nil `file `subtree `tree
  2271. (and (pred symbolp)
  2272. (guard (string-match "\\`tree\\([0-9]+\\)\\'"
  2273. (symbol-name scope)))))
  2274. (or (buffer-file-name (buffer-base-buffer))
  2275. (current-buffer)))
  2276. ((pred functionp) (funcall scope))
  2277. ((pred consp) scope)
  2278. (_ (user-error "Unknown scope: %S" scope))))
  2279. (block (plist-get params :block))
  2280. (ts (plist-get params :tstart))
  2281. (te (plist-get params :tend))
  2282. (ws (plist-get params :wstart))
  2283. (ms (plist-get params :mstart))
  2284. (step (plist-get params :step))
  2285. (hide-files (plist-get params :hidefiles))
  2286. (formatter (or (plist-get params :formatter)
  2287. org-clock-clocktable-formatter
  2288. 'org-clocktable-write-default))
  2289. cc)
  2290. ;; Check if we need to do steps
  2291. (when block
  2292. ;; Get the range text for the header
  2293. (setq cc (org-clock-special-range block nil t ws ms)
  2294. ts (car cc)
  2295. te (nth 1 cc)))
  2296. (when step
  2297. ;; Write many tables, in steps
  2298. (unless (or block (and ts te))
  2299. (user-error "Clocktable `:step' can only be used with `:block' or `:tstart, :end'"))
  2300. (org-clocktable-steps params)
  2301. (throw 'exit nil))
  2302. (org-agenda-prepare-buffers (if (consp files) files (list files)))
  2303. (let ((origin (point))
  2304. (tables
  2305. (if (consp files)
  2306. (mapcar (lambda (file)
  2307. (with-current-buffer (find-buffer-visiting file)
  2308. (save-excursion
  2309. (save-restriction
  2310. (org-clock-get-table-data file params)))))
  2311. files)
  2312. ;; Get the right restriction for the scope.
  2313. (save-restriction
  2314. (cond
  2315. ((not scope)) ;use the restriction as it is now
  2316. ((eq scope 'file) (widen))
  2317. ((eq scope 'subtree) (org-narrow-to-subtree))
  2318. ((eq scope 'tree)
  2319. (while (org-up-heading-safe))
  2320. (org-narrow-to-subtree))
  2321. ((and (symbolp scope)
  2322. (string-match "\\`tree\\([0-9]+\\)\\'"
  2323. (symbol-name scope)))
  2324. (let ((level (string-to-number
  2325. (match-string 1 (symbol-name scope)))))
  2326. (catch 'exit
  2327. (while (org-up-heading-safe)
  2328. (looking-at org-outline-regexp)
  2329. (when (<= (org-reduced-level (funcall outline-level))
  2330. level)
  2331. (throw 'exit nil))))
  2332. (org-narrow-to-subtree))))
  2333. (list (org-clock-get-table-data nil params)))))
  2334. (multifile
  2335. ;; Even though `file-with-archives' can consist of
  2336. ;; multiple files, we consider this is one extended file
  2337. ;; instead.
  2338. (and (not hide-files)
  2339. (consp files)
  2340. (not (eq scope 'file-with-archives)))))
  2341. (funcall formatter
  2342. origin
  2343. tables
  2344. (org-combine-plists params `(:multifile ,multifile)))))))
  2345. (defun org-clocktable-write-default (ipos tables params)
  2346. "Write out a clock table at position IPOS in the current buffer.
  2347. TABLES is a list of tables with clocking data as produced by
  2348. `org-clock-get-table-data'. PARAMS is the parameter property list obtained
  2349. from the dynamic block definition."
  2350. ;; This function looks quite complicated, mainly because there are a
  2351. ;; lot of options which can add or remove columns. I have massively
  2352. ;; commented this function, the I hope it is understandable. If
  2353. ;; someone wants to write their own special formatter, this maybe
  2354. ;; much easier because there can be a fixed format with a
  2355. ;; well-defined number of columns...
  2356. (let* ((lang (or (plist-get params :lang) "en"))
  2357. (multifile (plist-get params :multifile))
  2358. (block (plist-get params :block))
  2359. (sort (plist-get params :sort))
  2360. (header (plist-get params :header))
  2361. (link (plist-get params :link))
  2362. (maxlevel (or (plist-get params :maxlevel) 3))
  2363. (emph (plist-get params :emphasize))
  2364. (compact? (plist-get params :compact))
  2365. (narrow (or (plist-get params :narrow) (and compact? '40!)))
  2366. (level? (and (not compact?) (plist-get params :level)))
  2367. (timestamp (plist-get params :timestamp))
  2368. (tags (plist-get params :tags))
  2369. (properties (plist-get params :properties))
  2370. (time-columns
  2371. (if (or compact? (< maxlevel 2)) 1
  2372. ;; Deepest headline level is a hard limit for the number
  2373. ;; of time columns.
  2374. (let ((levels
  2375. (cl-mapcan
  2376. (lambda (table)
  2377. (pcase table
  2378. (`(,_ ,(and (pred wholenump) (pred (/= 0))) ,entries)
  2379. (mapcar #'car entries))))
  2380. tables)))
  2381. (min maxlevel
  2382. (or (plist-get params :tcolumns) 100)
  2383. (if (null levels) 1 (apply #'max levels))))))
  2384. (indent (or compact? (plist-get params :indent)))
  2385. (formula (plist-get params :formula))
  2386. (case-fold-search t)
  2387. (total-time (apply #'+ (mapcar #'cadr tables)))
  2388. recalc narrow-cut-p)
  2389. (when (and narrow (integerp narrow) link)
  2390. ;; We cannot have both integer narrow and link.
  2391. (message "Using hard narrowing in clocktable to allow for links")
  2392. (setq narrow (intern (format "%d!" narrow))))
  2393. (pcase narrow
  2394. ((or `nil (pred integerp)) nil) ;nothing to do
  2395. ((and (pred symbolp)
  2396. (guard (string-match-p "\\`[0-9]+!\\'" (symbol-name narrow))))
  2397. (setq narrow-cut-p t)
  2398. (setq narrow (string-to-number (symbol-name narrow))))
  2399. (_ (user-error "Invalid value %s of :narrow property in clock table" narrow)))
  2400. ;; Now we need to output this table stuff.
  2401. (goto-char ipos)
  2402. ;; Insert the text *before* the actual table.
  2403. (insert-before-markers
  2404. (or header
  2405. ;; Format the standard header.
  2406. (format "#+CAPTION: %s %s%s\n"
  2407. (org-clock--translate "Clock summary at" lang)
  2408. (format-time-string (org-time-stamp-format t t))
  2409. (if block
  2410. (let ((range-text
  2411. (nth 2 (org-clock-special-range
  2412. block nil t
  2413. (plist-get params :wstart)
  2414. (plist-get params :mstart)))))
  2415. (format ", for %s." range-text))
  2416. ""))))
  2417. ;; Insert the narrowing line
  2418. (when (and narrow (integerp narrow) (not narrow-cut-p))
  2419. (insert-before-markers
  2420. "|" ;table line starter
  2421. (if multifile "|" "") ;file column, maybe
  2422. (if level? "|" "") ;level column, maybe
  2423. (if timestamp "|" "") ;timestamp column, maybe
  2424. (if tags "|" "") ;tags columns, maybe
  2425. (if properties ;properties columns, maybe
  2426. (make-string (length properties) ?|)
  2427. "")
  2428. (format "<%d>| |\n" narrow))) ;headline and time columns
  2429. ;; Insert the table header line
  2430. (insert-before-markers
  2431. "|" ;table line starter
  2432. (if multifile ;file column, maybe
  2433. (concat (org-clock--translate "File" lang) "|")
  2434. "")
  2435. (if level? ;level column, maybe
  2436. (concat (org-clock--translate "L" lang) "|")
  2437. "")
  2438. (if timestamp ;timestamp column, maybe
  2439. (concat (org-clock--translate "Timestamp" lang) "|")
  2440. "")
  2441. (if tags "Tags |" "") ;tags columns, maybe
  2442. (if properties ;properties columns, maybe
  2443. (concat (mapconcat #'identity properties "|") "|")
  2444. "")
  2445. (concat (org-clock--translate "Headline" lang)"|")
  2446. (concat (org-clock--translate "Time" lang) "|")
  2447. (make-string (max 0 (1- time-columns)) ?|) ;other time columns
  2448. (if (eq formula '%) "%|\n" "\n"))
  2449. ;; Insert the total time in the table
  2450. (insert-before-markers
  2451. "|-\n" ;a hline
  2452. "|" ;table line starter
  2453. (if multifile (format "| %s " (org-clock--translate "ALL" lang)) "")
  2454. ;file column, maybe
  2455. (if level? "|" "") ;level column, maybe
  2456. (if timestamp "|" "") ;timestamp column, maybe
  2457. (if tags "|" "") ;timestamp column, maybe
  2458. (make-string (length properties) ?|) ;properties columns, maybe
  2459. (concat (format org-clock-total-time-cell-format
  2460. (org-clock--translate "Total time" lang))
  2461. "| ")
  2462. (format org-clock-total-time-cell-format
  2463. (org-duration-from-minutes (or total-time 0))) ;time
  2464. "|"
  2465. (make-string (max 0 (1- time-columns)) ?|)
  2466. (cond ((not (eq formula '%)) "")
  2467. ((or (not total-time) (= total-time 0)) "0.0|")
  2468. (t "100.0|"))
  2469. "\n")
  2470. ;; Now iterate over the tables and insert the data but only if any
  2471. ;; time has been collected.
  2472. (when (and total-time (> total-time 0))
  2473. (pcase-dolist (`(,file-name ,file-time ,entries) tables)
  2474. (when (or (and file-time (> file-time 0))
  2475. (not (plist-get params :fileskip0)))
  2476. (insert-before-markers "|-\n") ;hline at new file
  2477. ;; First the file time, if we have multiple files.
  2478. (when multifile
  2479. ;; Summarize the time collected from this file.
  2480. (insert-before-markers
  2481. (format (concat "| %s %s | %s%s%s"
  2482. (format org-clock-file-time-cell-format
  2483. (org-clock--translate "File time" lang))
  2484. " | *%s*|\n")
  2485. (file-name-nondirectory file-name)
  2486. (if level? "| " "") ;level column, maybe
  2487. (if timestamp "| " "") ;timestamp column, maybe
  2488. (if tags "| " "") ;tags column, maybe
  2489. (if properties ;properties columns, maybe
  2490. (make-string (length properties) ?|)
  2491. "")
  2492. (org-duration-from-minutes file-time)))) ;time
  2493. ;; Get the list of node entries and iterate over it
  2494. (when (> maxlevel 0)
  2495. (pcase-dolist (`(,level ,headline ,tgs ,ts ,time ,props) entries)
  2496. (when narrow-cut-p
  2497. (setq headline
  2498. (if (and (string-match
  2499. (format "\\`%s\\'" org-link-bracket-re)
  2500. headline)
  2501. (match-end 2))
  2502. (format "[[%s][%s]]"
  2503. (match-string 1 headline)
  2504. (org-shorten-string (match-string 2 headline)
  2505. narrow))
  2506. (org-shorten-string headline narrow))))
  2507. (cl-flet ((format-field (f) (format (cond ((not emph) "%s |")
  2508. ((= level 1) "*%s* |")
  2509. ((= level 2) "/%s/ |")
  2510. (t "%s |"))
  2511. f)))
  2512. (insert-before-markers
  2513. "|" ;start the table line
  2514. (if multifile "|" "") ;free space for file name column?
  2515. (if level? (format "%d|" level) "") ;level, maybe
  2516. (if timestamp (concat ts "|") "") ;timestamp, maybe
  2517. (if tags (concat (mapconcat #'identity tgs ", ") "|") "") ;tags, maybe
  2518. (if properties ;properties columns, maybe
  2519. (concat (mapconcat (lambda (p) (or (cdr (assoc p props)) ""))
  2520. properties
  2521. "|")
  2522. "|")
  2523. "")
  2524. (if indent ;indentation
  2525. (org-clocktable-indent-string level)
  2526. "")
  2527. (format-field headline)
  2528. ;; Empty fields for higher levels.
  2529. (make-string (max 0 (1- (min time-columns level))) ?|)
  2530. (format-field (org-duration-from-minutes time))
  2531. (make-string (max 0 (- time-columns level)) ?|)
  2532. (if (eq formula '%)
  2533. (format "%.1f |" (* 100 (/ time (float total-time))))
  2534. "")
  2535. "\n")))))))
  2536. (delete-char -1)
  2537. (cond
  2538. ;; Possibly rescue old formula?
  2539. ((or (not formula) (eq formula '%))
  2540. (let ((contents (org-string-nw-p (plist-get params :content))))
  2541. (when (and contents (string-match "^\\([ \t]*#\\+tblfm:.*\\)" contents))
  2542. (setq recalc t)
  2543. (insert "\n" (match-string 1 contents))
  2544. (beginning-of-line 0))))
  2545. ;; Insert specified formula line.
  2546. ((stringp formula)
  2547. (insert "\n#+TBLFM: " formula)
  2548. (setq recalc t))
  2549. (t
  2550. (user-error "Invalid :formula parameter in clocktable")))
  2551. ;; Back to beginning, align the table, recalculate if necessary.
  2552. (goto-char ipos)
  2553. (skip-chars-forward "^|")
  2554. (org-table-align)
  2555. (when org-hide-emphasis-markers
  2556. ;; We need to align a second time.
  2557. (org-table-align))
  2558. (when sort
  2559. (save-excursion
  2560. (org-table-goto-line 3)
  2561. (org-table-goto-column (car sort))
  2562. (org-table-sort-lines nil (cdr sort))))
  2563. (when recalc (org-table-recalculate 'all))
  2564. total-time))
  2565. (defun org-clocktable-indent-string (level)
  2566. "Return indentation string according to LEVEL.
  2567. LEVEL is an integer. Indent by two spaces per level above 1."
  2568. (if (= level 1) ""
  2569. (concat "\\_" (make-string (* 2 (1- level)) ?\s))))
  2570. (defun org-clocktable-steps (params)
  2571. "Create one or more clock tables, according to PARAMS.
  2572. Step through the range specifications in plist PARAMS to make
  2573. a number of clock tables."
  2574. (let* ((ignore-empty-tables (plist-get params :stepskip0))
  2575. (step (plist-get params :step))
  2576. (step-header
  2577. (pcase step
  2578. (`day "Daily report: ")
  2579. (`week "Weekly report starting on: ")
  2580. (`semimonth "Semimonthly report starting on: ")
  2581. (`month "Monthly report starting on: ")
  2582. (`year "Annual report starting on: ")
  2583. (_ (user-error "Unknown `:step' specification: %S" step))))
  2584. (week-start (or (plist-get params :wstart) 1))
  2585. (month-start (or (plist-get params :mstart) 1))
  2586. (range
  2587. (pcase (plist-get params :block)
  2588. (`nil nil)
  2589. (range
  2590. (org-clock-special-range range nil t week-start month-start))))
  2591. ;; For both START and END, any number is an absolute day
  2592. ;; number from Agenda. Otherwise, consider value to be an Org
  2593. ;; timestamp string. The `:block' property has precedence
  2594. ;; over `:tstart' and `:tend'.
  2595. (start
  2596. (pcase (if range (car range) (plist-get params :tstart))
  2597. ((and (pred numberp) n)
  2598. (pcase-let ((`(,m ,d ,y) (calendar-gregorian-from-absolute n)))
  2599. (apply #'encode-time (list 0 0 org-extend-today-until d m y))))
  2600. (timestamp
  2601. (seconds-to-time
  2602. (org-matcher-time (or timestamp
  2603. ;; The year Org was born.
  2604. "<2003-01-01 Thu 00:00>"))))))
  2605. (end
  2606. (pcase (if range (nth 1 range) (plist-get params :tend))
  2607. ((and (pred numberp) n)
  2608. (pcase-let ((`(,m ,d ,y) (calendar-gregorian-from-absolute n)))
  2609. (apply #'encode-time (list 0 0 org-extend-today-until d m y))))
  2610. (timestamp (seconds-to-time (org-matcher-time timestamp))))))
  2611. (while (time-less-p start end)
  2612. (unless (bolp) (insert "\n"))
  2613. ;; Insert header before each clock table.
  2614. (insert "\n"
  2615. step-header
  2616. (format-time-string (org-time-stamp-format nil t) start)
  2617. "\n")
  2618. ;; Compute NEXT, which is the end of the current clock table,
  2619. ;; according to step.
  2620. (let* ((next
  2621. (apply #'encode-time
  2622. (pcase-let
  2623. ((`(,_ ,_ ,_ ,d ,m ,y ,dow . ,_) (decode-time start)))
  2624. (pcase step
  2625. (`day (list 0 0 org-extend-today-until (1+ d) m y))
  2626. (`week
  2627. (let ((offset (if (= dow week-start) 7
  2628. (mod (- week-start dow) 7))))
  2629. (list 0 0 org-extend-today-until (+ d offset) m y)))
  2630. (`semimonth (list 0 0 0
  2631. (if (< d 16) 16 1)
  2632. (if (< d 16) m (1+ m)) y))
  2633. (`month (list 0 0 0 month-start (1+ m) y))
  2634. (`year (list 0 0 org-extend-today-until 1 1 (1+ y)))))))
  2635. (table-begin (line-beginning-position 0))
  2636. (step-time
  2637. ;; Write clock table between START and NEXT.
  2638. (org-dblock-write:clocktable
  2639. (org-combine-plists
  2640. params (list :header ""
  2641. :step nil
  2642. :block nil
  2643. :tstart (format-time-string
  2644. (org-time-stamp-format t t)
  2645. start)
  2646. :tend (format-time-string
  2647. (org-time-stamp-format t t)
  2648. ;; Never include clocks past END.
  2649. (if (time-less-p end next) end next)))))))
  2650. (let ((case-fold-search t)) (re-search-forward "^[ \t]*#\\+END:"))
  2651. ;; Remove the table if it is empty and `:stepskip0' is
  2652. ;; non-nil.
  2653. (when (and ignore-empty-tables (equal step-time 0))
  2654. (delete-region (line-beginning-position) table-begin))
  2655. (setq start next))
  2656. (end-of-line 0))))
  2657. (defun org-clock-get-table-data (file params)
  2658. "Get the clocktable data for file FILE, with parameters PARAMS.
  2659. FILE is only for identification - this function assumes that
  2660. the correct buffer is current, and that the wanted restriction is
  2661. in place.
  2662. The return value will be a list with the file name and the total
  2663. file time (in minutes) as 1st and 2nd elements. The third element
  2664. of this list will be a list of headline entries. Each entry has the
  2665. following structure:
  2666. (LEVEL HEADLINE TAGS TIMESTAMP TIME PROPERTIES)
  2667. LEVEL: The level of the headline, as an integer. This will be
  2668. the reduced level, so 1,2,3,... even if only odd levels
  2669. are being used.
  2670. HEADLINE: The text of the headline. Depending on PARAMS, this may
  2671. already be formatted like a link.
  2672. TAGS: The list of tags of the headline.
  2673. TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
  2674. entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
  2675. in this sequence.
  2676. TIME: The sum of all time spend in this tree, in minutes. This time
  2677. will of cause be restricted to the time block and tags match
  2678. specified in PARAMS.
  2679. PROPERTIES: The list properties specified in the `:properties' parameter
  2680. along with their value, as an alist following the pattern
  2681. (NAME . VALUE)."
  2682. (let* ((maxlevel (or (plist-get params :maxlevel) 3))
  2683. (timestamp (plist-get params :timestamp))
  2684. (ts (plist-get params :tstart))
  2685. (te (plist-get params :tend))
  2686. (ws (plist-get params :wstart))
  2687. (ms (plist-get params :mstart))
  2688. (block (plist-get params :block))
  2689. (link (plist-get params :link))
  2690. (tags (plist-get params :tags))
  2691. (match (plist-get params :match))
  2692. (properties (plist-get params :properties))
  2693. (inherit-property-p (plist-get params :inherit-props))
  2694. (matcher (and match (cdr (org-make-tags-matcher match))))
  2695. cc st p tbl)
  2696. (setq org-clock-file-total-minutes nil)
  2697. (when block
  2698. (setq cc (org-clock-special-range block nil t ws ms)
  2699. ts (car cc)
  2700. te (nth 1 cc)))
  2701. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  2702. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  2703. (when (and ts (listp ts))
  2704. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  2705. (when (and te (listp te))
  2706. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  2707. ;; Now the times are strings we can parse.
  2708. (if ts (setq ts (org-matcher-time ts)))
  2709. (if te (setq te (org-matcher-time te)))
  2710. (save-excursion
  2711. (org-clock-sum ts te
  2712. (when matcher
  2713. `(lambda ()
  2714. (let* ((todo (org-get-todo-state))
  2715. (tags-list (org-get-tags))
  2716. (org-scanner-tags tags-list)
  2717. (org-trust-scanner-tags t))
  2718. (funcall ,matcher todo tags-list nil)))))
  2719. (goto-char (point-min))
  2720. (setq st t)
  2721. (while (or (and (bobp) (prog1 st (setq st nil))
  2722. (get-text-property (point) :org-clock-minutes)
  2723. (setq p (point-min)))
  2724. (setq p (next-single-property-change
  2725. (point) :org-clock-minutes)))
  2726. (goto-char p)
  2727. (let ((time (get-text-property p :org-clock-minutes)))
  2728. (when (and time (> time 0) (org-at-heading-p))
  2729. (let ((level (org-reduced-level (org-current-level))))
  2730. (when (<= level maxlevel)
  2731. (let* ((headline (org-get-heading t t t t))
  2732. (hdl
  2733. (if (not link) headline
  2734. (let ((search
  2735. (org-link-heading-search-string headline)))
  2736. (org-link-make-string
  2737. (if (not (buffer-file-name)) search
  2738. (format "file:%s::%s" (buffer-file-name) search))
  2739. ;; Prune statistics cookies. Replace
  2740. ;; links with their description, or
  2741. ;; a plain link if there is none.
  2742. (org-trim
  2743. (org-link-display-format
  2744. (replace-regexp-in-string
  2745. "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]" ""
  2746. headline)))))))
  2747. (tgs (and tags (org-get-tags)))
  2748. (tsp
  2749. (and timestamp
  2750. (cl-some (lambda (p) (org-entry-get (point) p))
  2751. '("SCHEDULED" "DEADLINE" "TIMESTAMP"
  2752. "TIMESTAMP_IA"))))
  2753. (props
  2754. (and properties
  2755. (delq nil
  2756. (mapcar
  2757. (lambda (p)
  2758. (let ((v (org-entry-get
  2759. (point) p inherit-property-p)))
  2760. (and v (cons p v))))
  2761. properties)))))
  2762. (push (list level hdl tgs tsp time props) tbl)))))))
  2763. (list file org-clock-file-total-minutes (nreverse tbl)))))
  2764. ;; Saving and loading the clock
  2765. (defvar org-clock-loaded nil
  2766. "Was the clock file loaded?")
  2767. ;;;###autoload
  2768. (defun org-clock-update-time-maybe ()
  2769. "If this is a CLOCK line, update it and return t.
  2770. Otherwise, return nil."
  2771. (interactive)
  2772. (save-excursion
  2773. (beginning-of-line 1)
  2774. (skip-chars-forward " \t")
  2775. (when (looking-at org-clock-string)
  2776. (let ((re (concat "[ \t]*" org-clock-string
  2777. " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
  2778. "\\([ \t]*=>.*\\)?\\)?"))
  2779. ts te h m s neg)
  2780. (cond
  2781. ((not (looking-at re))
  2782. nil)
  2783. ((not (match-end 2))
  2784. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  2785. (> org-clock-marker (point))
  2786. (<= org-clock-marker (point-at-eol)))
  2787. ;; The clock is running here
  2788. (setq org-clock-start-time
  2789. (org-time-string-to-time (match-string 1)))
  2790. (org-clock-update-mode-line)))
  2791. (t
  2792. (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
  2793. (end-of-line 1)
  2794. (setq ts (match-string 1)
  2795. te (match-string 3))
  2796. (setq s (- (float-time
  2797. (apply #'encode-time (org-parse-time-string te)))
  2798. (float-time
  2799. (apply #'encode-time (org-parse-time-string ts))))
  2800. neg (< s 0)
  2801. s (abs s)
  2802. h (floor (/ s 3600))
  2803. s (- s (* 3600 h))
  2804. m (floor (/ s 60))
  2805. s (- s (* 60 s)))
  2806. (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
  2807. t))))))
  2808. (defun org-clock-save ()
  2809. "Persist various clock-related data to disk.
  2810. The details of what will be saved are regulated by the variable
  2811. `org-clock-persist'."
  2812. (when (and org-clock-persist
  2813. (or org-clock-loaded
  2814. org-clock-has-been-used
  2815. (not (file-exists-p org-clock-persist-file))))
  2816. (with-temp-file org-clock-persist-file
  2817. (insert (format ";; %s - %s at %s\n"
  2818. (file-name-nondirectory org-clock-persist-file)
  2819. (system-name)
  2820. (format-time-string (org-time-stamp-format t))))
  2821. ;; Store clock to be resumed.
  2822. (when (and (memq org-clock-persist '(t clock))
  2823. (let ((b (org-base-buffer (org-clocking-buffer))))
  2824. (and (buffer-live-p b)
  2825. (buffer-file-name b)
  2826. (or (not org-clock-persist-query-save)
  2827. (y-or-n-p (format "Save current clock (%s) "
  2828. org-clock-heading))))))
  2829. (insert
  2830. (format "(setq org-clock-stored-resume-clock '(%S . %d))\n"
  2831. (buffer-file-name (org-base-buffer (org-clocking-buffer)))
  2832. (marker-position org-clock-marker))))
  2833. ;; Store clocked task history. Tasks are stored reversed to
  2834. ;; make reading simpler.
  2835. (when (and (memq org-clock-persist '(t history))
  2836. org-clock-history)
  2837. (insert
  2838. (format "(setq org-clock-stored-history '(%s))\n"
  2839. (mapconcat
  2840. (lambda (m)
  2841. (let ((b (org-base-buffer (marker-buffer m))))
  2842. (when (and (buffer-live-p b)
  2843. (buffer-file-name b))
  2844. (format "(%S . %d)"
  2845. (buffer-file-name b)
  2846. (marker-position m)))))
  2847. (reverse org-clock-history)
  2848. " ")))))))
  2849. (defun org-clock-load ()
  2850. "Load clock-related data from disk, maybe resuming a stored clock."
  2851. (when (and org-clock-persist (not org-clock-loaded))
  2852. (if (not (file-readable-p org-clock-persist-file))
  2853. (message "Not restoring clock data; %S not found" org-clock-persist-file)
  2854. (message "Restoring clock data")
  2855. ;; Load history.
  2856. (load-file org-clock-persist-file)
  2857. (setq org-clock-loaded t)
  2858. (pcase-dolist (`(,(and file (pred file-exists-p)) . ,position)
  2859. org-clock-stored-history)
  2860. (org-clock-history-push position (find-file-noselect file)))
  2861. ;; Resume clock.
  2862. (pcase org-clock-stored-resume-clock
  2863. (`(,(and file (pred file-exists-p)) . ,position)
  2864. (with-current-buffer (find-file-noselect file)
  2865. (when (or (not org-clock-persist-query-resume)
  2866. (y-or-n-p (format "Resume clock (%s) "
  2867. (save-excursion
  2868. (goto-char position)
  2869. (org-get-heading t t)))))
  2870. (goto-char position)
  2871. (let ((org-clock-in-resume 'auto-restart)
  2872. (org-clock-auto-clock-resolution nil))
  2873. (org-clock-in)
  2874. (when (org-invisible-p) (org-show-context))))))
  2875. (_ nil)))))
  2876. ;; Suggested bindings
  2877. (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
  2878. (provide 'org-clock)
  2879. ;; Local variables:
  2880. ;; generated-autoload-file: "org-loaddefs.el"
  2881. ;; coding: utf-8
  2882. ;; End:
  2883. ;;; org-clock.el ends here