org-clock.el 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  1. ;;; org-clock.el --- The time clocking code for Org-mode
  2. ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
  3. ;; Free Software Foundation, Inc.
  4. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  5. ;; Keywords: outlines, hypermedia, calendar, wp
  6. ;; Homepage: http://orgmode.org
  7. ;; Version: 7.02trans
  8. ;;
  9. ;; This file is part of GNU Emacs.
  10. ;;
  11. ;; GNU Emacs is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation, either version 3 of the License, or
  14. ;; (at your option) any later version.
  15. ;; GNU Emacs is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  21. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  22. ;;
  23. ;;; Commentary:
  24. ;; This file contains the time clocking code for Org-mode
  25. (require 'org)
  26. ;;; Code:
  27. (eval-when-compile
  28. (require 'cl))
  29. (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
  30. (declare-function notifications-notify "notifications" (&rest params))
  31. (defvar org-time-stamp-formats)
  32. (defgroup org-clock nil
  33. "Options concerning clocking working time in Org-mode."
  34. :tag "Org Clock"
  35. :group 'org-progress)
  36. (defcustom org-clock-into-drawer org-log-into-drawer
  37. "Should clocking info be wrapped into a drawer?
  38. When t, clocking info will always be inserted into a :LOGBOOK: drawer.
  39. If necessary, the drawer will be created.
  40. When nil, the drawer will not be created, but used when present.
  41. When an integer and the number of clocking entries in an item
  42. reaches or exceeds this number, a drawer will be created.
  43. When a string, it names the drawer to be used.
  44. The default for this variable is the value of `org-log-into-drawer',
  45. which see."
  46. :group 'org-todo
  47. :group 'org-clock
  48. :type '(choice
  49. (const :tag "Always" t)
  50. (const :tag "Only when drawer exists" nil)
  51. (integer :tag "When at least N clock entries")
  52. (const :tag "Into LOGBOOK drawer" "LOGBOOK")
  53. (string :tag "Into Drawer named...")))
  54. (defcustom org-clock-out-when-done t
  55. "When non-nil, clock will be stopped when the clocked entry is marked DONE.
  56. DONE here means any DONE-like state.
  57. A nil value means clock will keep running until stopped explicitly with
  58. `C-c C-x C-o', or until the clock is started in a different item.
  59. Instead of t, this can also be a list of TODO states that should trigger
  60. clocking out."
  61. :group 'org-clock
  62. :type '(choice
  63. (const :tag "No" nil)
  64. (const :tag "Yes, when done" t)
  65. (repeat :tag "State list"
  66. (string :tag "TODO keyword"))))
  67. (defcustom org-clock-out-remove-zero-time-clocks nil
  68. "Non-nil means remove the clock line when the resulting time is zero."
  69. :group 'org-clock
  70. :type 'boolean)
  71. (defcustom org-clock-in-switch-to-state nil
  72. "Set task to a special todo state while clocking it.
  73. The value should be the state to which the entry should be
  74. switched. If the value is a function, it must take one
  75. parameter (the current TODO state of the item) and return the
  76. state to switch it to."
  77. :group 'org-clock
  78. :group 'org-todo
  79. :type '(choice
  80. (const :tag "Don't force a state" nil)
  81. (string :tag "State")
  82. (symbol :tag "Function")))
  83. (defcustom org-clock-out-switch-to-state nil
  84. "Set task to a special todo state after clocking out.
  85. The value should be the state to which the entry should be
  86. switched. If the value is a function, it must take one
  87. parameter (the current TODO state of the item) and return the
  88. state to switch it to."
  89. :group 'org-clock
  90. :group 'org-todo
  91. :type '(choice
  92. (const :tag "Don't force a state" nil)
  93. (string :tag "State")
  94. (symbol :tag "Function")))
  95. (defcustom org-clock-history-length 5
  96. "Number of clock tasks to remember in history."
  97. :group 'org-clock
  98. :type 'integer)
  99. (defcustom org-clock-goto-may-find-recent-task t
  100. "Non-nil means `org-clock-goto' can go to recent task if no active clock."
  101. :group 'org-clock
  102. :type 'boolean)
  103. (defcustom org-clock-heading-function nil
  104. "When non-nil, should be a function to create `org-clock-heading'.
  105. This is the string shown in the mode line when a clock is running.
  106. The function is called with point at the beginning of the headline."
  107. :group 'org-clock
  108. :type 'function)
  109. (defcustom org-clock-string-limit 0
  110. "Maximum length of clock strings in the modeline. 0 means no limit."
  111. :group 'org-clock
  112. :type 'integer)
  113. (defcustom org-clock-in-resume nil
  114. "If non-nil, resume clock when clocking into task with open clock.
  115. When clocking into a task with a clock entry which has not been closed,
  116. the clock can be resumed from that point."
  117. :group 'org-clock
  118. :type 'boolean)
  119. (defcustom org-clock-persist nil
  120. "When non-nil, save the running clock when Emacs is closed.
  121. The clock is resumed when Emacs restarts.
  122. When this is t, both the running clock, and the entire clock
  123. history are saved. When this is the symbol `clock', only the
  124. running clock is saved.
  125. When Emacs restarts with saved clock information, the file containing the
  126. running clock as well as all files mentioned in the clock history will
  127. be visited.
  128. All this depends on running `org-clock-persistence-insinuate' in .emacs"
  129. :group 'org-clock
  130. :type '(choice
  131. (const :tag "Just the running clock" clock)
  132. (const :tag "Just the history" history)
  133. (const :tag "Clock and history" t)
  134. (const :tag "No persistence" nil)))
  135. (defcustom org-clock-persist-file (convert-standard-filename
  136. "~/.emacs.d/org-clock-save.el")
  137. "File to save clock data to."
  138. :group 'org-clock
  139. :type 'string)
  140. (defcustom org-clock-persist-query-save nil
  141. "When non-nil, ask before saving the current clock on exit."
  142. :group 'org-clock
  143. :type 'boolean)
  144. (defcustom org-clock-persist-query-resume t
  145. "When non-nil, ask before resuming any stored clock during load."
  146. :group 'org-clock
  147. :type 'boolean)
  148. (defcustom org-clock-sound nil
  149. "Sound that will used for notifications.
  150. Possible values:
  151. nil no sound played.
  152. t standard Emacs beep
  153. file name play this sound file. If not possible, fall back to beep"
  154. :group 'org-clock
  155. :type '(choice
  156. (const :tag "No sound" nil)
  157. (const :tag "Standard beep" t)
  158. (file :tag "Play sound file")))
  159. (defcustom org-clock-modeline-total 'auto
  160. "Default setting for the time included for the modeline clock.
  161. This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
  162. Allowed values are:
  163. current Only the time in the current instance of the clock
  164. today All time clocked into this task today
  165. repeat All time clocked into this task since last repeat
  166. all All time ever recorded for this task
  167. auto Automatically, either `all', or `repeat' for repeating tasks"
  168. :group 'org-clock
  169. :type '(choice
  170. (const :tag "Current clock" current)
  171. (const :tag "Today's task time" today)
  172. (const :tag "Since last repeat" repeat)
  173. (const :tag "All task time" all)
  174. (const :tag "Automatically, `all' or since `repeat'" auto)))
  175. (defcustom org-task-overrun-text nil
  176. "The extra modeline text that should indicate that the clock is overrun.
  177. The can be nil to indicate that instead of adding text, the clock time
  178. should get a different face (`org-mode-line-clock-overrun').
  179. When this is a string, it is prepended to the clock string as an indication,
  180. also using the face `org-mode-line-clock-overrun'."
  181. :group 'org-clock
  182. :type '(choice
  183. (const :tag "Just mark the time string" nil)
  184. (string :tag "Text to prepend")))
  185. (defcustom org-show-notification-handler nil
  186. "Function or program to send notification with.
  187. The function or program will be called with the notification
  188. string as argument."
  189. :group 'org-clock
  190. :type '(choice
  191. (string :tag "Program")
  192. (function :tag "Function")))
  193. (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
  194. "Default properties for new clocktables."
  195. :group 'org-clock
  196. :type 'plist)
  197. (defcustom org-clock-idle-time nil
  198. "When non-nil, resolve open clocks if the user is idle more than X minutes."
  199. :group 'org-clock
  200. :type '(choice
  201. (const :tag "Never" nil)
  202. (integer :tag "After N minutes")))
  203. (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
  204. "When to automatically resolve open clocks found in Org buffers."
  205. :group 'org-clock
  206. :type '(choice
  207. (const :tag "Never" nil)
  208. (const :tag "Always" t)
  209. (const :tag "When no clock is running" when-no-clock-is-running)))
  210. (defcustom org-clock-report-include-clocking-task nil
  211. "When non-nil, include the current clocking task time in clock reports."
  212. :group 'org-clock
  213. :type 'boolean)
  214. (defcustom org-clock-resolve-expert nil
  215. "Non-nil means do not show the splash buffer with the clock resolver."
  216. :group 'org-clock
  217. :type 'boolean)
  218. (defvar org-clock-in-prepare-hook nil
  219. "Hook run when preparing the clock.
  220. This hook is run before anything happens to the task that
  221. you want to clock in. For example, you can use this hook
  222. to add an effort property.")
  223. (defvar org-clock-in-hook nil
  224. "Hook run when starting the clock.")
  225. (defvar org-clock-out-hook nil
  226. "Hook run when stopping the current clock.")
  227. (defvar org-clock-cancel-hook nil
  228. "Hook run when cancelling the current clock.")
  229. (defvar org-clock-goto-hook nil
  230. "Hook run when selecting the currently clocked-in entry.")
  231. (defvar org-clock-has-been-used nil
  232. "Has the clock been used during the current Emacs session?")
  233. ;;; The clock for measuring work time.
  234. (defvar org-mode-line-string "")
  235. (put 'org-mode-line-string 'risky-local-variable t)
  236. (defvar org-clock-mode-line-timer nil)
  237. (defvar org-clock-idle-timer nil)
  238. (defvar org-clock-heading) ; defined in org.el
  239. (defvar org-clock-heading-for-remember "")
  240. (defvar org-clock-start-time "")
  241. (defvar org-clock-leftover-time nil
  242. "If non-nil, user cancelled a clock; this is when leftover time started.")
  243. (defvar org-clock-effort ""
  244. "Effort estimate of the currently clocking task.")
  245. (defvar org-clock-total-time nil
  246. "Holds total time, spent previously on currently clocked item.
  247. This does not include the time in the currently running clock.")
  248. (defvar org-clock-history nil
  249. "List of marker pointing to recent clocked tasks.")
  250. (defvar org-clock-default-task (make-marker)
  251. "Marker pointing to the default task that should clock time.
  252. The clock can be made to switch to this task after clocking out
  253. of a different task.")
  254. (defvar org-clock-interrupted-task (make-marker)
  255. "Marker pointing to the task that has been interrupted by the current clock.")
  256. (defvar org-clock-mode-line-map (make-sparse-keymap))
  257. (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
  258. (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
  259. (defun org-clock-menu ()
  260. (interactive)
  261. (popup-menu
  262. '("Clock"
  263. ["Clock out" org-clock-out t]
  264. ["Change effort estimate" org-clock-modify-effort-estimate t]
  265. ["Go to clock entry" org-clock-goto t]
  266. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
  267. (defun org-clock-history-push (&optional pos buffer)
  268. "Push a marker to the clock history."
  269. (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
  270. (let ((m (move-marker (make-marker)
  271. (or pos (point)) (org-base-buffer
  272. (or buffer (current-buffer)))))
  273. n l)
  274. (while (setq n (member m org-clock-history))
  275. (move-marker (car n) nil))
  276. (setq org-clock-history
  277. (delq nil
  278. (mapcar (lambda (x) (if (marker-buffer x) x nil))
  279. org-clock-history)))
  280. (when (>= (setq l (length org-clock-history)) org-clock-history-length)
  281. (setq org-clock-history
  282. (nreverse
  283. (nthcdr (- l org-clock-history-length -1)
  284. (nreverse org-clock-history)))))
  285. (push m org-clock-history)))
  286. (defun org-clock-save-markers-for-cut-and-paste (beg end)
  287. "Save relative positions of markers in region."
  288. (org-check-and-save-marker org-clock-marker beg end)
  289. (org-check-and-save-marker org-clock-hd-marker beg end)
  290. (org-check-and-save-marker org-clock-default-task beg end)
  291. (org-check-and-save-marker org-clock-interrupted-task beg end)
  292. (mapc (lambda (m) (org-check-and-save-marker m beg end))
  293. org-clock-history))
  294. (defun org-clocking-buffer ()
  295. "Return the clocking buffer if we are currently clocking a task or nil."
  296. (marker-buffer org-clock-marker))
  297. (defun org-clocking-p ()
  298. "Return t when clocking a task."
  299. (not (equal (org-clocking-buffer) nil)))
  300. (defun org-clock-select-task (&optional prompt)
  301. "Select a task that recently was associated with clocking."
  302. (interactive)
  303. (let (sel-list rpl (i 0) s)
  304. (save-window-excursion
  305. (org-switch-to-buffer-other-window
  306. (get-buffer-create "*Clock Task Select*"))
  307. (erase-buffer)
  308. (when (marker-buffer org-clock-default-task)
  309. (insert (org-add-props "Default Task\n" nil 'face 'bold))
  310. (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
  311. (push s sel-list))
  312. (when (marker-buffer org-clock-interrupted-task)
  313. (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
  314. (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
  315. (push s sel-list))
  316. (when (org-clocking-p)
  317. (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
  318. (setq s (org-clock-insert-selection-line ?c org-clock-marker))
  319. (push s sel-list))
  320. (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
  321. (mapc
  322. (lambda (m)
  323. (when (marker-buffer m)
  324. (setq i (1+ i)
  325. s (org-clock-insert-selection-line
  326. (if (< i 10)
  327. (+ i ?0)
  328. (+ i (- ?A 10))) m))
  329. (if (fboundp 'int-to-char) (setf (car s) (int-to-char (car s))))
  330. (push s sel-list)))
  331. org-clock-history)
  332. (org-fit-window-to-buffer)
  333. (message (or prompt "Select task for clocking:"))
  334. (setq rpl (read-char-exclusive))
  335. (cond
  336. ((eq rpl ?q) nil)
  337. ((eq rpl ?x) nil)
  338. ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
  339. (t (error "Invalid task choice %c" rpl))))))
  340. (defun org-clock-insert-selection-line (i marker)
  341. "Insert a line for the clock selection menu.
  342. And return a cons cell with the selection character integer and the marker
  343. pointing to it."
  344. (when (marker-buffer marker)
  345. (let (file cat task heading prefix)
  346. (with-current-buffer (org-base-buffer (marker-buffer marker))
  347. (save-excursion
  348. (save-restriction
  349. (widen)
  350. (ignore-errors
  351. (goto-char marker)
  352. (setq file (buffer-file-name (marker-buffer marker))
  353. cat (or (org-get-category)
  354. (progn (org-refresh-category-properties)
  355. (org-get-category)))
  356. heading (org-get-heading 'notags)
  357. prefix (save-excursion
  358. (org-back-to-heading t)
  359. (looking-at "\\*+ ")
  360. (match-string 0))
  361. task (substring
  362. (org-fontify-like-in-org-mode
  363. (concat prefix heading)
  364. org-odd-levels-only)
  365. (length prefix)))))))
  366. (when (and cat task)
  367. (insert (format "[%c] %-15s %s\n" i cat task))
  368. (cons i marker)))))
  369. (defvar org-task-overrun nil
  370. "Internal flag indicating if the clock has overrun the planned time.")
  371. (defvar org-clock-update-period 60
  372. "Number of seconds between mode line clock string updates.")
  373. (defun org-clock-get-clock-string ()
  374. "Form a clock-string, that will be shown in the mode line.
  375. If an effort estimate was defined for the current item, use
  376. 01:30/01:50 format (clocked/estimated).
  377. If not, show simply the clocked time like 01:50."
  378. (let* ((clocked-time (org-clock-get-clocked-time))
  379. (h (floor clocked-time 60))
  380. (m (- clocked-time (* 60 h))))
  381. (if org-clock-effort
  382. (let* ((effort-in-minutes
  383. (org-hh:mm-string-to-minutes org-clock-effort))
  384. (effort-h (floor effort-in-minutes 60))
  385. (effort-m (- effort-in-minutes (* effort-h 60)))
  386. (work-done-str
  387. (org-propertize
  388. (format org-time-clocksum-format h m)
  389. 'face (if (and org-task-overrun (not org-task-overrun-text))
  390. 'org-mode-line-clock-overrun 'org-mode-line-clock)))
  391. (effort-str (format org-time-clocksum-format effort-h effort-m))
  392. (clockstr (org-propertize
  393. (concat "[%s/" effort-str
  394. "] (" (replace-regexp-in-string "%" "%%" org-clock-heading) ")")
  395. 'face 'org-mode-line-clock)))
  396. (format clockstr work-done-str))
  397. (org-propertize (format
  398. (concat "[" org-time-clocksum-format " (%s)]")
  399. h m org-clock-heading)
  400. 'face 'org-mode-line-clock))))
  401. (defun org-clock-update-mode-line ()
  402. (if org-clock-effort
  403. (org-clock-notify-once-if-expired)
  404. (setq org-task-overrun nil))
  405. (setq org-mode-line-string
  406. (org-propertize
  407. (let ((clock-string (org-clock-get-clock-string))
  408. (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
  409. (if (and (> org-clock-string-limit 0)
  410. (> (length clock-string) org-clock-string-limit))
  411. (org-propertize
  412. (substring clock-string 0 org-clock-string-limit)
  413. 'help-echo (concat help-text ": " org-clock-heading))
  414. (org-propertize clock-string 'help-echo help-text)))
  415. 'local-map org-clock-mode-line-map
  416. 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
  417. ))
  418. (if (and org-task-overrun org-task-overrun-text)
  419. (setq org-mode-line-string
  420. (concat (org-propertize
  421. org-task-overrun-text
  422. 'face 'org-mode-line-clock-overrun) org-mode-line-string)))
  423. (force-mode-line-update))
  424. (defun org-clock-get-clocked-time ()
  425. "Get the clocked time for the current item in minutes.
  426. The time returned includes the time spent on this task in
  427. previous clocking intervals."
  428. (let ((currently-clocked-time
  429. (floor (- (org-float-time)
  430. (org-float-time org-clock-start-time)) 60)))
  431. (+ currently-clocked-time (or org-clock-total-time 0))))
  432. (defun org-clock-modify-effort-estimate (&optional value)
  433. "Add to or set the effort estimate of the item currently being clocked.
  434. VALUE can be a number of minutes, or a string with format hh:mm or mm.
  435. When the string starts with a + or a - sign, the current value of the effort
  436. property will be changed by that amount.
  437. This will update the \"Effort\" property of currently clocked item, and
  438. the mode line."
  439. (interactive)
  440. (when (org-clock-is-active)
  441. (let ((current org-clock-effort) sign)
  442. (unless value
  443. ;; Prompt user for a value or a change
  444. (setq value
  445. (read-string
  446. (format "Set effort (hh:mm or mm%s): "
  447. (if current
  448. (format ", prefix + to add to %s" org-clock-effort)
  449. "")))))
  450. (when (stringp value)
  451. ;; A string. See if it is a delta
  452. (setq sign (string-to-char value))
  453. (if (member sign '(?- ?+))
  454. (setq current (org-hh:mm-string-to-minutes current)
  455. value (substring value 1))
  456. (setq current 0))
  457. (setq value (org-hh:mm-string-to-minutes value))
  458. (if (equal ?- sign)
  459. (setq value (- current value))
  460. (if (equal ?+ sign) (setq value (+ current value)))))
  461. (setq value (max 0 value)
  462. org-clock-effort (org-minutes-to-hh:mm-string value))
  463. (org-entry-put org-clock-marker "Effort" org-clock-effort)
  464. (org-clock-update-mode-line)
  465. (message "Effort is now %s" org-clock-effort))))
  466. (defvar org-clock-notification-was-shown nil
  467. "Shows if we have shown notification already.")
  468. (defun org-clock-notify-once-if-expired ()
  469. "Show notification if we spent more time than we estimated before.
  470. Notification is shown only once."
  471. (when (org-clocking-p)
  472. (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
  473. (clocked-time (org-clock-get-clocked-time)))
  474. (if (setq org-task-overrun
  475. (if (or (null effort-in-minutes) (zerop effort-in-minutes))
  476. nil
  477. (>= clocked-time effort-in-minutes)))
  478. (unless org-clock-notification-was-shown
  479. (setq org-clock-notification-was-shown t)
  480. (org-notify
  481. (format "Task '%s' should be finished by now. (%s)"
  482. org-clock-heading org-clock-effort) t))
  483. (setq org-clock-notification-was-shown nil)))))
  484. (defun org-notify (notification &optional play-sound)
  485. "Send a NOTIFICATION and maybe PLAY-SOUND."
  486. (org-show-notification notification)
  487. (if play-sound (org-clock-play-sound)))
  488. (defun org-show-notification (notification)
  489. "Show notification.
  490. Use `org-show-notification-handler' if defined,
  491. use libnotify if available, or fall back on a message."
  492. (cond ((functionp org-show-notification-handler)
  493. (funcall org-show-notification-handler notification))
  494. ((stringp org-show-notification-handler)
  495. (start-process "emacs-timer-notification" nil
  496. org-show-notification-handler notification))
  497. ((featurep 'notifications)
  498. (require 'notifications)
  499. (notifications-notify
  500. :title "Org-mode message"
  501. :body notification
  502. ;; FIXME how to link to the Org icon?
  503. ;; :app-icon "~/.emacs.d/icons/mail.png"
  504. :urgency 'low))
  505. ((org-program-exists "notify-send")
  506. (start-process "emacs-timer-notification" nil
  507. "notify-send" notification))
  508. ;; Maybe the handler will send a message, so only use message as
  509. ;; a fall back option
  510. (t (message "%s" notification))))
  511. (defun org-clock-play-sound ()
  512. "Play sound as configured by `org-clock-sound'.
  513. Use alsa's aplay tool if available."
  514. (cond
  515. ((not org-clock-sound))
  516. ((eq org-clock-sound t) (beep t) (beep t))
  517. ((stringp org-clock-sound)
  518. (let ((file (expand-file-name org-clock-sound)))
  519. (if (file-exists-p file)
  520. (if (org-program-exists "aplay")
  521. (start-process "org-clock-play-notification" nil
  522. "aplay" file)
  523. (condition-case nil
  524. (play-sound-file file)
  525. (error (beep t) (beep t)))))))))
  526. (defun org-program-exists (program-name)
  527. "Checks whenever we can locate program and launch it."
  528. (if (eq system-type 'gnu/linux)
  529. (= 0 (call-process "which" nil nil nil program-name))))
  530. (defvar org-clock-mode-line-entry nil
  531. "Information for the modeline about the running clock.")
  532. (defun org-find-open-clocks (file)
  533. "Search through the given file and find all open clocks."
  534. (let ((buf (or (get-file-buffer file)
  535. (find-file-noselect file)))
  536. clocks)
  537. (with-current-buffer buf
  538. (save-excursion
  539. (goto-char (point-min))
  540. (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t)
  541. (push (cons (copy-marker (match-end 1) t)
  542. (org-time-string-to-time (match-string 1))) clocks))))
  543. clocks))
  544. (defsubst org-is-active-clock (clock)
  545. "Return t if CLOCK is the currently active clock."
  546. (and (org-clock-is-active)
  547. (= org-clock-marker (car clock))))
  548. (defmacro org-with-clock-position (clock &rest forms)
  549. "Evaluate FORMS with CLOCK as the current active clock."
  550. `(with-current-buffer (marker-buffer (car ,clock))
  551. (save-excursion
  552. (save-restriction
  553. (widen)
  554. (goto-char (car ,clock))
  555. (beginning-of-line)
  556. ,@forms))))
  557. (put 'org-with-clock-position 'lisp-indent-function 1)
  558. (defmacro org-with-clock (clock &rest forms)
  559. "Evaluate FORMS with CLOCK as the current active clock.
  560. This macro also protects the current active clock from being altered."
  561. `(org-with-clock-position ,clock
  562. (let ((org-clock-start-time (cdr ,clock))
  563. (org-clock-total-time)
  564. (org-clock-history)
  565. (org-clock-effort)
  566. (org-clock-marker (car ,clock))
  567. (org-clock-hd-marker (save-excursion
  568. (outline-back-to-heading t)
  569. (point-marker))))
  570. ,@forms)))
  571. (put 'org-with-clock 'lisp-indent-function 1)
  572. (defsubst org-clock-clock-in (clock &optional resume start-time)
  573. "Clock in to the clock located by CLOCK.
  574. If necessary, clock-out of the currently active clock."
  575. (org-with-clock-position clock
  576. (let ((org-clock-in-resume (or resume org-clock-in-resume)))
  577. (org-clock-in nil start-time))))
  578. (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
  579. "Clock out of the clock located by CLOCK."
  580. (let ((temp (copy-marker (car clock)
  581. (marker-insertion-type (car clock)))))
  582. (if (org-is-active-clock clock)
  583. (org-clock-out fail-quietly at-time)
  584. (org-with-clock clock
  585. (org-clock-out fail-quietly at-time)))
  586. (setcar clock temp)))
  587. (defsubst org-clock-clock-cancel (clock)
  588. "Cancel the clock located by CLOCK."
  589. (let ((temp (copy-marker (car clock)
  590. (marker-insertion-type (car clock)))))
  591. (if (org-is-active-clock clock)
  592. (org-clock-cancel)
  593. (org-with-clock clock
  594. (org-clock-cancel)))
  595. (setcar clock temp)))
  596. (defvar org-clock-clocking-in nil)
  597. (defvar org-clock-resolving-clocks nil)
  598. (defvar org-clock-resolving-clocks-due-to-idleness nil)
  599. (defun org-clock-resolve-clock (clock resolve-to clock-out-time
  600. &optional close-p restart-p fail-quietly)
  601. "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
  602. `CLOCK' is a cons cell of the form (MARKER START-TIME)."
  603. (let ((org-clock-resolving-clocks t))
  604. (cond
  605. ((null resolve-to)
  606. (org-clock-clock-cancel clock)
  607. (if (and restart-p (not org-clock-clocking-in))
  608. (org-clock-clock-in clock)))
  609. ((eq resolve-to 'now)
  610. (if restart-p
  611. (error "RESTART-P is not valid here"))
  612. (if (or close-p org-clock-clocking-in)
  613. (org-clock-clock-out clock fail-quietly)
  614. (unless (org-is-active-clock clock)
  615. (org-clock-clock-in clock t))))
  616. ((not (time-less-p resolve-to (current-time)))
  617. (error "RESOLVE-TO must refer to a time in the past"))
  618. (t
  619. (if restart-p
  620. (error "RESTART-P is not valid here"))
  621. (org-clock-clock-out clock fail-quietly (or clock-out-time
  622. resolve-to))
  623. (unless org-clock-clocking-in
  624. (if close-p
  625. (setq org-clock-leftover-time (and (null clock-out-time)
  626. resolve-to))
  627. (org-clock-clock-in clock nil (and clock-out-time
  628. resolve-to))))))))
  629. (defun org-clock-jump-to-current-clock (&optional effective-clock)
  630. (interactive)
  631. (let ((clock (or effective-clock (cons org-clock-marker
  632. org-clock-start-time))))
  633. (unless (marker-buffer (car clock))
  634. (error "No clock is currently running"))
  635. (org-with-clock clock (org-clock-goto))
  636. (with-current-buffer (marker-buffer (car clock))
  637. (goto-char (car clock))
  638. (if org-clock-into-drawer
  639. (let ((logbook
  640. (if (stringp org-clock-into-drawer)
  641. (concat ":" org-clock-into-drawer ":")
  642. ":LOGBOOK:")))
  643. (ignore-errors
  644. (outline-flag-region
  645. (save-excursion
  646. (outline-back-to-heading t)
  647. (search-forward logbook)
  648. (goto-char (match-beginning 0)))
  649. (save-excursion
  650. (outline-back-to-heading t)
  651. (search-forward logbook)
  652. (search-forward ":END:")
  653. (goto-char (match-end 0)))
  654. nil)))))))
  655. (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
  656. "Resolve an open org-mode clock.
  657. An open clock was found, with `dangling' possibly being non-nil.
  658. If this function was invoked with a prefix argument, non-dangling
  659. open clocks are ignored. The given clock requires some sort of
  660. user intervention to resolve it, either because a clock was left
  661. dangling or due to an idle timeout. The clock resolution can
  662. either be:
  663. (a) deleted, the user doesn't care about the clock
  664. (b) restarted from the current time (if no other clock is open)
  665. (c) closed, giving the clock X minutes
  666. (d) closed and then restarted
  667. (e) resumed, as if the user had never left
  668. The format of clock is (CONS MARKER START-TIME), where MARKER
  669. identifies the buffer and position the clock is open at (and
  670. thus, the heading it's under), and START-TIME is when the clock
  671. was started."
  672. (assert clock)
  673. (let* ((ch
  674. (save-window-excursion
  675. (save-excursion
  676. (unless org-clock-resolving-clocks-due-to-idleness
  677. (org-clock-jump-to-current-clock clock))
  678. (unless org-clock-resolve-expert
  679. (with-output-to-temp-buffer "*Org Clock*"
  680. (princ "Select a Clock Resolution Command:
  681. i/q/C-g Ignore this question; the same as keeping all the idle time.
  682. k/K Keep X minutes of the idle time (default is all). If this
  683. amount is less than the default, you will be clocked out
  684. that many minutes after the time that idling began, and then
  685. clocked back in at the present time.
  686. g/G Indicate that you \"got back\" X minutes ago. This is quite
  687. different from 'k': it clocks you out from the beginning of
  688. the idle period and clock you back in X minutes ago.
  689. s/S Subtract the idle time from the current clock. This is the
  690. same as keeping 0 minutes.
  691. C Cancel the open timer altogether. It will be as though you
  692. never clocked in.
  693. j/J Jump to the current clock, to make manual adjustments.
  694. For all these options, using uppercase makes your final state
  695. to be CLOCKED OUT.")))
  696. (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
  697. (let (char-pressed)
  698. (when (featurep 'xemacs)
  699. (message (concat (funcall prompt-fn clock)
  700. " [jkKgGsScCiq]? "))
  701. (setq char-pressed (read-char-exclusive)))
  702. (while (or (null char-pressed)
  703. (and (not (memq char-pressed
  704. '(?k ?K ?g ?G ?s ?S ?C
  705. ?j ?J ?i ?q)))
  706. (or (ding) t)))
  707. (setq char-pressed
  708. (read-char (concat (funcall prompt-fn clock)
  709. " [jkKgGSscCiq]? ")
  710. nil 45)))
  711. (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
  712. (default
  713. (floor (/ (org-float-time
  714. (time-subtract (current-time) last-valid)) 60)))
  715. (keep
  716. (and (memq ch '(?k ?K))
  717. (read-number "Keep how many minutes? " default)))
  718. (gotback
  719. (and (memq ch '(?g ?G))
  720. (read-number "Got back how many minutes ago? " default)))
  721. (subtractp (memq ch '(?s ?S)))
  722. (barely-started-p (< (- (org-float-time last-valid)
  723. (org-float-time (cdr clock))) 45))
  724. (start-over (and subtractp barely-started-p)))
  725. (cond
  726. ((memq ch '(?j ?J))
  727. (if (eq ch ?J)
  728. (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
  729. (org-clock-jump-to-current-clock clock))
  730. ((or (null ch)
  731. (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
  732. (message ""))
  733. (t
  734. (org-clock-resolve-clock
  735. clock (cond
  736. ((or (eq ch ?C)
  737. ;; If the time on the clock was less than a minute before
  738. ;; the user went away, and they've ask to subtract all the
  739. ;; time...
  740. start-over)
  741. nil)
  742. ((or subtractp
  743. (and gotback (= gotback 0)))
  744. last-valid)
  745. ((or (and keep (= keep default))
  746. (and gotback (= gotback default)))
  747. 'now)
  748. (keep
  749. (time-add last-valid (seconds-to-time (* 60 keep))))
  750. (gotback
  751. (time-subtract (current-time)
  752. (seconds-to-time (* 60 gotback))))
  753. (t
  754. (error "Unexpected, please report this as a bug")))
  755. (and gotback last-valid)
  756. (memq ch '(?K ?G ?S))
  757. (and start-over
  758. (not (memq ch '(?K ?G ?S ?C))))
  759. fail-quietly)))))
  760. (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
  761. "Resolve all currently open org-mode clocks.
  762. If `only-dangling-p' is non-nil, only ask to resolve dangling
  763. \(i.e., not currently open and valid) clocks."
  764. (interactive "P")
  765. (unless org-clock-resolving-clocks
  766. (let ((org-clock-resolving-clocks t))
  767. (dolist (file (org-files-list))
  768. (let ((clocks (org-find-open-clocks file)))
  769. (dolist (clock clocks)
  770. (let ((dangling (or (not (org-clock-is-active))
  771. (/= (car clock) org-clock-marker))))
  772. (if (or (not only-dangling-p) dangling)
  773. (org-clock-resolve
  774. clock
  775. (or prompt-fn
  776. (function
  777. (lambda (clock)
  778. (format
  779. "Dangling clock started %d mins ago"
  780. (floor
  781. (/ (- (org-float-time (current-time))
  782. (org-float-time (cdr clock))) 60))))))
  783. (or last-valid
  784. (cdr clock)))))))))))
  785. (defun org-emacs-idle-seconds ()
  786. "Return the current Emacs idle time in seconds, or nil if not idle."
  787. (let ((idle-time (current-idle-time)))
  788. (if idle-time
  789. (org-float-time idle-time)
  790. 0)))
  791. (defun org-mac-idle-seconds ()
  792. "Return the current Mac idle time in seconds."
  793. (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
  794. (defun org-x11-idle-seconds ()
  795. "Return the current X11 idle time in seconds."
  796. (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
  797. (defun org-user-idle-seconds ()
  798. "Return the number of seconds the user has been idle for.
  799. This routine returns a floating point number."
  800. (cond
  801. ((eq system-type 'darwin)
  802. (org-mac-idle-seconds))
  803. ((eq window-system 'x)
  804. (org-x11-idle-seconds))
  805. (t
  806. (org-emacs-idle-seconds))))
  807. (defvar org-clock-user-idle-seconds)
  808. (defun org-resolve-clocks-if-idle ()
  809. "Resolve all currently open org-mode clocks.
  810. This is performed after `org-clock-idle-time' minutes, to check
  811. if the user really wants to stay clocked in after being idle for
  812. so long."
  813. (when (and org-clock-idle-time (not org-clock-resolving-clocks)
  814. org-clock-marker)
  815. (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
  816. (org-clock-user-idle-start
  817. (time-subtract (current-time)
  818. (seconds-to-time org-clock-user-idle-seconds)))
  819. (org-clock-resolving-clocks-due-to-idleness t))
  820. (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
  821. (org-clock-resolve
  822. (cons org-clock-marker
  823. org-clock-start-time)
  824. (function
  825. (lambda (clock)
  826. (format "Clocked in & idle for %.1f mins"
  827. (/ (org-float-time
  828. (time-subtract (current-time)
  829. org-clock-user-idle-start))
  830. 60.0))))
  831. org-clock-user-idle-start)))))
  832. (defun org-clock-in (&optional select start-time)
  833. "Start the clock on the current item.
  834. If necessary, clock-out of the currently active clock.
  835. With a prefix argument SELECT (\\[universal-argument]), offer a list of \
  836. recently clocked tasks to
  837. clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
  838. clock into the current task and mark
  839. is as the default task, a special task that will always be offered in
  840. the clocking selection, associated with the letter `d'."
  841. (interactive "P")
  842. (setq org-clock-notification-was-shown nil)
  843. (catch 'abort
  844. (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
  845. (org-clocking-p)))
  846. ts selected-task target-pos (msg-extra "")
  847. (leftover (and (not org-clock-resolving-clocks)
  848. org-clock-leftover-time)))
  849. (when (and org-clock-auto-clock-resolution
  850. (or (not interrupting)
  851. (eq t org-clock-auto-clock-resolution))
  852. (not org-clock-clocking-in)
  853. (not org-clock-resolving-clocks))
  854. (setq org-clock-leftover-time nil)
  855. (let ((org-clock-clocking-in t))
  856. (org-resolve-clocks))) ; check if any clocks are dangling
  857. (when (equal select '(4))
  858. (setq selected-task (org-clock-select-task "Clock-in on task: "))
  859. (if selected-task
  860. (setq selected-task (copy-marker selected-task))
  861. (error "Abort")))
  862. (when interrupting
  863. ;; We are interrupting the clocking of a different task.
  864. ;; Save a marker to this task, so that we can go back.
  865. ;; First check if we are trying to clock into the same task!
  866. (when (save-excursion
  867. (unless selected-task
  868. (org-back-to-heading t))
  869. (and (equal (marker-buffer org-clock-hd-marker)
  870. (if selected-task
  871. (marker-buffer selected-task)
  872. (current-buffer)))
  873. (= (marker-position org-clock-hd-marker)
  874. (if selected-task
  875. (marker-position selected-task)
  876. (point)))))
  877. (message "Clock continues in \"%s\"" org-clock-heading)
  878. (throw 'abort nil))
  879. (move-marker org-clock-interrupted-task
  880. (marker-position org-clock-marker)
  881. (marker-buffer org-clock-marker))
  882. (let ((org-clock-clocking-in t))
  883. (org-clock-out t)))
  884. (when (equal select '(16))
  885. ;; Mark as default clocking task
  886. (org-clock-mark-default-task))
  887. ;; Clock in at which position?
  888. (setq target-pos
  889. (if (and (eobp) (not (org-on-heading-p)))
  890. (point-at-bol 0)
  891. (point)))
  892. (run-hooks 'org-clock-in-prepare-hook)
  893. (save-excursion
  894. (when (and selected-task (marker-buffer selected-task))
  895. ;; There is a selected task, move to the correct buffer
  896. ;; and set the new target position.
  897. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  898. (setq target-pos (marker-position selected-task))
  899. (move-marker selected-task nil))
  900. (save-excursion
  901. (save-restriction
  902. (widen)
  903. (goto-char target-pos)
  904. (org-back-to-heading t)
  905. (or interrupting (move-marker org-clock-interrupted-task nil))
  906. (org-clock-history-push)
  907. (org-clock-set-current)
  908. (cond ((functionp org-clock-in-switch-to-state)
  909. (looking-at org-complex-heading-regexp)
  910. (let ((newstate (funcall org-clock-in-switch-to-state
  911. (match-string 2))))
  912. (if newstate (org-todo newstate))))
  913. ((and org-clock-in-switch-to-state
  914. (not (looking-at (concat outline-regexp "[ \t]*"
  915. org-clock-in-switch-to-state
  916. "\\>"))))
  917. (org-todo org-clock-in-switch-to-state)))
  918. (setq org-clock-heading-for-remember
  919. (and (looking-at org-complex-heading-regexp)
  920. (match-end 4)
  921. (org-trim (buffer-substring (match-end 1)
  922. (match-end 4)))))
  923. (setq org-clock-heading
  924. (cond ((and org-clock-heading-function
  925. (functionp org-clock-heading-function))
  926. (funcall org-clock-heading-function))
  927. ((looking-at org-complex-heading-regexp)
  928. (replace-regexp-in-string
  929. "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
  930. (match-string 4)))
  931. (t "???")))
  932. (setq org-clock-heading (org-propertize org-clock-heading
  933. 'face nil))
  934. (org-clock-find-position org-clock-in-resume)
  935. (cond
  936. ((and org-clock-in-resume
  937. (looking-at
  938. (concat "^[ \t]* " org-clock-string
  939. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  940. " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  941. (message "Matched %s" (match-string 1))
  942. (setq ts (concat "[" (match-string 1) "]"))
  943. (goto-char (match-end 1))
  944. (setq org-clock-start-time
  945. (apply 'encode-time
  946. (org-parse-time-string (match-string 1))))
  947. (setq org-clock-effort (org-get-effort))
  948. (setq org-clock-total-time (org-clock-sum-current-item
  949. (org-clock-get-sum-start))))
  950. ((eq org-clock-in-resume 'auto-restart)
  951. ;; called from org-clock-load during startup,
  952. ;; do not interrupt, but warn!
  953. (message "Cannot restart clock because task does not contain unfinished clock")
  954. (ding)
  955. (sit-for 2)
  956. (throw 'abort nil))
  957. (t
  958. (insert-before-markers "\n")
  959. (backward-char 1)
  960. (org-indent-line-function)
  961. (when (and (save-excursion
  962. (end-of-line 0)
  963. (org-in-item-p)))
  964. (beginning-of-line 1)
  965. (org-indent-line-to (- (org-get-indentation) 2)))
  966. (insert org-clock-string " ")
  967. (setq org-clock-effort (org-get-effort))
  968. (setq org-clock-total-time (org-clock-sum-current-item
  969. (org-clock-get-sum-start)))
  970. (setq org-clock-start-time
  971. (or (and leftover
  972. (y-or-n-p
  973. (format
  974. "You stopped another clock %d mins ago; start this one from then? "
  975. (/ (- (org-float-time (current-time))
  976. (org-float-time leftover)) 60)))
  977. leftover)
  978. start-time
  979. (current-time)))
  980. (setq ts (org-insert-time-stamp org-clock-start-time
  981. 'with-hm 'inactive))))
  982. (move-marker org-clock-marker (point) (buffer-base-buffer))
  983. (move-marker org-clock-hd-marker
  984. (save-excursion (org-back-to-heading t) (point))
  985. (buffer-base-buffer))
  986. (setq org-clock-has-been-used t)
  987. (or global-mode-string (setq global-mode-string '("")))
  988. (or (memq 'org-mode-line-string global-mode-string)
  989. (setq global-mode-string
  990. (append global-mode-string '(org-mode-line-string))))
  991. (org-clock-update-mode-line)
  992. (when org-clock-mode-line-timer
  993. (cancel-timer org-clock-mode-line-timer)
  994. (setq org-clock-mode-line-timer nil))
  995. (setq org-clock-mode-line-timer
  996. (run-with-timer org-clock-update-period
  997. org-clock-update-period
  998. 'org-clock-update-mode-line))
  999. (when org-clock-idle-timer
  1000. (cancel-timer org-clock-idle-timer)
  1001. (setq org-clock-idle-timer nil))
  1002. (setq org-clock-idle-timer
  1003. (run-with-timer 60 60 'org-resolve-clocks-if-idle))
  1004. (message "Clock starts at %s - %s" ts msg-extra)
  1005. (run-hooks 'org-clock-in-hook)))))))
  1006. (defvar org-clock-current-task nil
  1007. "Task currently clocked in.")
  1008. (defun org-clock-set-current ()
  1009. "Set `org-clock-current-task' to the task currently clocked in."
  1010. (setq org-clock-current-task (nth 4 (org-heading-components))))
  1011. (defun org-clock-delete-current ()
  1012. "Reset `org-clock-current-task' to nil."
  1013. (setq org-clock-current-task nil))
  1014. (defun org-clock-mark-default-task ()
  1015. "Mark current task as default task."
  1016. (interactive)
  1017. (save-excursion
  1018. (org-back-to-heading t)
  1019. (move-marker org-clock-default-task (point))))
  1020. (defvar msg-extra)
  1021. (defun org-clock-get-sum-start ()
  1022. "Return the time from which clock times should be counted.
  1023. This is for the currently running clock as it is displayed
  1024. in the mode line. This function looks at the properties
  1025. LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
  1026. corresponding variable `org-clock-modeline-total' and then
  1027. decides which time to use."
  1028. (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
  1029. (symbol-name org-clock-modeline-total)))
  1030. (lr (org-entry-get nil "LAST_REPEAT")))
  1031. (cond
  1032. ((equal cmt "current")
  1033. (setq msg-extra "showing time in current clock instance")
  1034. (current-time))
  1035. ((equal cmt "today")
  1036. (setq msg-extra "showing today's task time.")
  1037. (let* ((dt (decode-time (current-time))))
  1038. (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
  1039. (if org-extend-today-until
  1040. (setf (nth 2 dt) org-extend-today-until))
  1041. (apply 'encode-time dt)))
  1042. ((or (equal cmt "all")
  1043. (and (or (not cmt) (equal cmt "auto"))
  1044. (not lr)))
  1045. (setq msg-extra "showing entire task time.")
  1046. nil)
  1047. ((or (equal cmt "repeat")
  1048. (and (or (not cmt) (equal cmt "auto"))
  1049. lr))
  1050. (setq msg-extra "showing task time since last repeat.")
  1051. (if (not lr)
  1052. nil
  1053. (org-time-string-to-time lr)))
  1054. (t nil))))
  1055. (defun org-clock-find-position (find-unclosed)
  1056. "Find the location where the next clock line should be inserted.
  1057. When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
  1058. line and position cursor in that line."
  1059. (org-back-to-heading t)
  1060. (catch 'exit
  1061. (let ((beg (save-excursion
  1062. (beginning-of-line 2)
  1063. (or (bolp) (newline))
  1064. (point)))
  1065. (end (progn (outline-next-heading) (point)))
  1066. (re (concat "^[ \t]*" org-clock-string))
  1067. (cnt 0)
  1068. (drawer (if (stringp org-clock-into-drawer)
  1069. org-clock-into-drawer "LOGBOOK"))
  1070. first last ind-last)
  1071. (goto-char beg)
  1072. (when (and find-unclosed
  1073. (re-search-forward
  1074. (concat "^[ \t]* " org-clock-string
  1075. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1076. " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
  1077. end t))
  1078. (beginning-of-line 1)
  1079. (throw 'exit t))
  1080. (when (eobp) (newline) (setq end (max (point) end)))
  1081. (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
  1082. ;; we seem to have a CLOCK drawer, so go there.
  1083. (beginning-of-line 2)
  1084. (or org-log-states-order-reversed
  1085. (and (re-search-forward org-property-end-re nil t)
  1086. (goto-char (match-beginning 0))))
  1087. (throw 'exit t))
  1088. ;; Lets count the CLOCK lines
  1089. (goto-char beg)
  1090. (while (re-search-forward re end t)
  1091. (setq first (or first (match-beginning 0))
  1092. last (match-beginning 0)
  1093. cnt (1+ cnt)))
  1094. (when (and (integerp org-clock-into-drawer)
  1095. last
  1096. (>= (1+ cnt) org-clock-into-drawer))
  1097. ;; Wrap current entries into a new drawer
  1098. (goto-char last)
  1099. (setq ind-last (org-get-indentation))
  1100. (beginning-of-line 2)
  1101. (if (and (>= (org-get-indentation) ind-last)
  1102. (org-at-item-p))
  1103. (org-end-of-item))
  1104. (insert ":END:\n")
  1105. (beginning-of-line 0)
  1106. (org-indent-line-to ind-last)
  1107. (goto-char first)
  1108. (insert ":" drawer ":\n")
  1109. (beginning-of-line 0)
  1110. (org-indent-line-function)
  1111. (org-flag-drawer t)
  1112. (beginning-of-line 2)
  1113. (or org-log-states-order-reversed
  1114. (and (re-search-forward org-property-end-re nil t)
  1115. (goto-char (match-beginning 0))))
  1116. (throw 'exit nil))
  1117. (goto-char beg)
  1118. (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1119. (not (equal (match-string 1) org-clock-string)))
  1120. ;; Planning info, skip to after it
  1121. (beginning-of-line 2)
  1122. (or (bolp) (newline)))
  1123. (when (or (eq org-clock-into-drawer t)
  1124. (stringp org-clock-into-drawer)
  1125. (and (integerp org-clock-into-drawer)
  1126. (< org-clock-into-drawer 2)))
  1127. (insert ":" drawer ":\n:END:\n")
  1128. (beginning-of-line -1)
  1129. (org-indent-line-function)
  1130. (org-flag-drawer t)
  1131. (beginning-of-line 2)
  1132. (org-indent-line-function)
  1133. (beginning-of-line)
  1134. (or org-log-states-order-reversed
  1135. (and (re-search-forward org-property-end-re nil t)
  1136. (goto-char (match-beginning 0))))))))
  1137. (defun org-clock-out (&optional fail-quietly at-time)
  1138. "Stop the currently running clock.
  1139. If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
  1140. (interactive)
  1141. (catch 'exit
  1142. (when (not (org-clocking-p))
  1143. (setq global-mode-string
  1144. (delq 'org-mode-line-string global-mode-string))
  1145. (force-mode-line-update)
  1146. (if fail-quietly (throw 'exit t) (error "No active clock")))
  1147. (let (ts te s h m remove)
  1148. (save-excursion ; Do not replace this with `with-current-buffer'.
  1149. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1150. (save-restriction
  1151. (widen)
  1152. (goto-char org-clock-marker)
  1153. (beginning-of-line 1)
  1154. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1155. (equal (match-string 1) org-clock-string))
  1156. (setq ts (match-string 2))
  1157. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  1158. (goto-char (match-end 0))
  1159. (delete-region (point) (point-at-eol))
  1160. (insert "--")
  1161. (setq te (org-insert-time-stamp (or at-time (current-time))
  1162. 'with-hm 'inactive))
  1163. (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
  1164. (org-float-time (apply 'encode-time (org-parse-time-string ts))))
  1165. h (floor (/ s 3600))
  1166. s (- s (* 3600 h))
  1167. m (floor (/ s 60))
  1168. s (- s (* 60 s)))
  1169. (insert " => " (format "%2d:%02d" h m))
  1170. (when (setq remove (and org-clock-out-remove-zero-time-clocks
  1171. (= (+ h m) 0)))
  1172. (beginning-of-line 1)
  1173. (delete-region (point) (point-at-eol))
  1174. (and (looking-at "\n") (> (point-max) (1+ (point)))
  1175. (delete-char 1)))
  1176. (move-marker org-clock-marker nil)
  1177. (move-marker org-clock-hd-marker nil)
  1178. (when org-log-note-clock-out
  1179. (org-add-log-setup 'clock-out nil nil nil nil
  1180. (concat "# Task: " (org-get-heading t) "\n\n")))
  1181. (when org-clock-mode-line-timer
  1182. (cancel-timer org-clock-mode-line-timer)
  1183. (setq org-clock-mode-line-timer nil))
  1184. (when org-clock-idle-timer
  1185. (cancel-timer org-clock-idle-timer)
  1186. (setq org-clock-idle-timer nil))
  1187. (setq global-mode-string
  1188. (delq 'org-mode-line-string global-mode-string))
  1189. (when org-clock-out-switch-to-state
  1190. (save-excursion
  1191. (org-back-to-heading t)
  1192. (let ((org-inhibit-logging t)
  1193. (org-clock-out-when-done nil))
  1194. (cond
  1195. ((functionp org-clock-out-switch-to-state)
  1196. (looking-at org-complex-heading-regexp)
  1197. (let ((newstate (funcall org-clock-out-switch-to-state
  1198. (match-string 2))))
  1199. (if newstate (org-todo newstate))))
  1200. ((and org-clock-out-switch-to-state
  1201. (not (looking-at (concat outline-regexp "[ \t]*"
  1202. org-clock-out-switch-to-state
  1203. "\\>"))))
  1204. (org-todo org-clock-out-switch-to-state))))))
  1205. (force-mode-line-update)
  1206. (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
  1207. (if remove " => LINE REMOVED" ""))
  1208. (run-hooks 'org-clock-out-hook)
  1209. (org-clock-delete-current))))))
  1210. (defun org-clock-cancel ()
  1211. "Cancel the running clock by removing the start timestamp."
  1212. (interactive)
  1213. (when (not (org-clocking-p))
  1214. (setq global-mode-string
  1215. (delq 'org-mode-line-string global-mode-string))
  1216. (force-mode-line-update)
  1217. (error "No active clock"))
  1218. (save-excursion ; Do not replace this with `with-current-buffer'.
  1219. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1220. (goto-char org-clock-marker)
  1221. (delete-region (1- (point-at-bol)) (point-at-eol))
  1222. ;; Just in case, remove any empty LOGBOOK left over
  1223. (org-remove-empty-drawer-at "LOGBOOK" (point)))
  1224. (move-marker org-clock-marker nil)
  1225. (move-marker org-clock-hd-marker nil)
  1226. (setq global-mode-string
  1227. (delq 'org-mode-line-string global-mode-string))
  1228. (force-mode-line-update)
  1229. (message "Clock canceled")
  1230. (run-hooks 'org-clock-cancel-hook))
  1231. (defun org-clock-goto (&optional select)
  1232. "Go to the currently clocked-in entry, or to the most recently clocked one.
  1233. With prefix arg SELECT, offer recently clocked tasks for selection."
  1234. (interactive "@P")
  1235. (let* ((recent nil)
  1236. (m (cond
  1237. (select
  1238. (or (org-clock-select-task "Select task to go to: ")
  1239. (error "No task selected")))
  1240. ((org-clocking-p) org-clock-marker)
  1241. ((and org-clock-goto-may-find-recent-task
  1242. (car org-clock-history)
  1243. (marker-buffer (car org-clock-history)))
  1244. (setq recent t)
  1245. (car org-clock-history))
  1246. (t (error "No active or recent clock task")))))
  1247. (switch-to-buffer (marker-buffer m))
  1248. (if (or (< m (point-min)) (> m (point-max))) (widen))
  1249. (goto-char m)
  1250. (org-show-entry)
  1251. (org-back-to-heading t)
  1252. (org-cycle-hide-drawers 'children)
  1253. (recenter)
  1254. (org-reveal)
  1255. (if recent
  1256. (message "No running clock, this is the most recently clocked task"))
  1257. (run-hooks 'org-clock-goto-hook)))
  1258. (defvar org-clock-file-total-minutes nil
  1259. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  1260. (make-variable-buffer-local 'org-clock-file-total-minutes)
  1261. (defun org-clock-sum (&optional tstart tend headline-filter)
  1262. "Sum the times for each subtree.
  1263. Puts the resulting times in minutes as a text property on each headline.
  1264. TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
  1265. zero-arg function that, if specified, is called for each headline in the time
  1266. range with point at the headline. Headlines for which HEADLINE-FILTER returns
  1267. nil are excluded from the clock summation."
  1268. (interactive)
  1269. (let* ((bmp (buffer-modified-p))
  1270. (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  1271. org-clock-string
  1272. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  1273. (lmax 30)
  1274. (ltimes (make-vector lmax 0))
  1275. (t1 0)
  1276. (level 0)
  1277. ts te dt
  1278. time)
  1279. (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
  1280. (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
  1281. (if (consp tstart) (setq tstart (org-float-time tstart)))
  1282. (if (consp tend) (setq tend (org-float-time tend)))
  1283. (remove-text-properties (point-min) (point-max)
  1284. '(:org-clock-minutes t
  1285. :org-clock-force-headline-inclusion t))
  1286. (save-excursion
  1287. (goto-char (point-max))
  1288. (while (re-search-backward re nil t)
  1289. (cond
  1290. ((match-end 2)
  1291. ;; Two time stamps
  1292. (setq ts (match-string 2)
  1293. te (match-string 3)
  1294. ts (org-float-time
  1295. (apply 'encode-time (org-parse-time-string ts)))
  1296. te (org-float-time
  1297. (apply 'encode-time (org-parse-time-string te)))
  1298. ts (if tstart (max ts tstart) ts)
  1299. te (if tend (min te tend) te)
  1300. dt (- te ts)
  1301. t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
  1302. ((match-end 4)
  1303. ;; A naked time
  1304. (setq t1 (+ t1 (string-to-number (match-string 5))
  1305. (* 60 (string-to-number (match-string 4))))))
  1306. (t ;; A headline
  1307. ;; Add the currently clocking item time to the total
  1308. (when (and org-clock-report-include-clocking-task
  1309. (equal (org-clocking-buffer) (current-buffer))
  1310. (equal (marker-position org-clock-hd-marker) (point))
  1311. tstart
  1312. tend
  1313. (>= (org-float-time org-clock-start-time) tstart)
  1314. (<= (org-float-time org-clock-start-time) tend))
  1315. (let ((time (floor (- (org-float-time)
  1316. (org-float-time org-clock-start-time)) 60)))
  1317. (setq t1 (+ t1 time))))
  1318. (let* ((headline-forced
  1319. (get-text-property (point)
  1320. :org-clock-force-headline-inclusion))
  1321. (headline-included
  1322. (or (null headline-filter)
  1323. (save-excursion
  1324. (save-match-data (funcall headline-filter))))))
  1325. (setq level (- (match-end 1) (match-beginning 1)))
  1326. (when (or (> t1 0) (> (aref ltimes level) 0))
  1327. (when (or headline-included headline-forced)
  1328. (if headline-included
  1329. (loop for l from 0 to level do
  1330. (aset ltimes l (+ (aref ltimes l) t1))))
  1331. (setq time (aref ltimes level))
  1332. (goto-char (match-beginning 0))
  1333. (put-text-property (point) (point-at-eol) :org-clock-minutes time)
  1334. (if headline-filter
  1335. (save-excursion
  1336. (save-match-data
  1337. (while
  1338. (> (funcall outline-level) 1)
  1339. (outline-up-heading 1 t)
  1340. (put-text-property
  1341. (point) (point-at-eol)
  1342. :org-clock-force-headline-inclusion t))))))
  1343. (setq t1 0)
  1344. (loop for l from level to (1- lmax) do
  1345. (aset ltimes l 0)))))))
  1346. (setq org-clock-file-total-minutes (aref ltimes 0)))
  1347. (set-buffer-modified-p bmp)))
  1348. (defun org-clock-sum-current-item (&optional tstart)
  1349. "Return time, clocked on current item in total."
  1350. (save-excursion
  1351. (save-restriction
  1352. (org-narrow-to-subtree)
  1353. (org-clock-sum tstart)
  1354. org-clock-file-total-minutes)))
  1355. (defun org-clock-display (&optional total-only)
  1356. "Show subtree times in the entire buffer.
  1357. If TOTAL-ONLY is non-nil, only show the total time for the entire file
  1358. in the echo area."
  1359. (interactive)
  1360. (org-clock-remove-overlays)
  1361. (let (time h m p)
  1362. (org-clock-sum)
  1363. (unless total-only
  1364. (save-excursion
  1365. (goto-char (point-min))
  1366. (while (or (and (equal (setq p (point)) (point-min))
  1367. (get-text-property p :org-clock-minutes))
  1368. (setq p (next-single-property-change
  1369. (point) :org-clock-minutes)))
  1370. (goto-char p)
  1371. (when (setq time (get-text-property p :org-clock-minutes))
  1372. (org-clock-put-overlay time (funcall outline-level))))
  1373. (setq h (/ org-clock-file-total-minutes 60)
  1374. m (- org-clock-file-total-minutes (* 60 h)))
  1375. ;; Arrange to remove the overlays upon next change.
  1376. (when org-remove-highlights-with-change
  1377. (org-add-hook 'before-change-functions 'org-clock-remove-overlays
  1378. nil 'local))))
  1379. (if org-time-clocksum-use-fractional
  1380. (message (concat "Total file time: " org-time-clocksum-fractional-format
  1381. " (%d hours and %d minutes)")
  1382. (/ (+ (* h 60.0) m) 60.0) h m)
  1383. (message (concat "Total file time: " org-time-clocksum-format
  1384. " (%d hours and %d minutes)") h m h m))))
  1385. (defvar org-clock-overlays nil)
  1386. (make-variable-buffer-local 'org-clock-overlays)
  1387. (defun org-clock-put-overlay (time &optional level)
  1388. "Put an overlays on the current line, displaying TIME.
  1389. If LEVEL is given, prefix time with a corresponding number of stars.
  1390. This creates a new overlay and stores it in `org-clock-overlays', so that it
  1391. will be easy to remove."
  1392. (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
  1393. (l (if level (org-get-valid-level level 0) 0))
  1394. (fmt (concat "%s " (if org-time-clocksum-use-fractional
  1395. org-time-clocksum-fractional-format
  1396. org-time-clocksum-format) "%s"))
  1397. (off 0)
  1398. ov tx)
  1399. (org-move-to-column c)
  1400. (unless (eolp) (skip-chars-backward "^ \t"))
  1401. (skip-chars-backward " \t")
  1402. (setq ov (make-overlay (1- (point)) (point-at-eol))
  1403. tx (concat (buffer-substring (1- (point)) (point))
  1404. (make-string (+ off (max 0 (- c (current-column)))) ?.)
  1405. (org-add-props (if org-time-clocksum-use-fractional
  1406. (format fmt
  1407. (make-string l ?*)
  1408. (/ (+ (* h 60.0) m) 60.0)
  1409. (make-string (- 16 l) ?\ ))
  1410. (format fmt
  1411. (make-string l ?*) h m
  1412. (make-string (- 16 l) ?\ )))
  1413. (list 'face 'org-clock-overlay))
  1414. ""))
  1415. (if (not (featurep 'xemacs))
  1416. (overlay-put ov 'display tx)
  1417. (overlay-put ov 'invisible t)
  1418. (overlay-put ov 'end-glyph (make-glyph tx)))
  1419. (push ov org-clock-overlays)))
  1420. (defun org-clock-remove-overlays (&optional beg end noremove)
  1421. "Remove the occur highlights from the buffer.
  1422. BEG and END are ignored. If NOREMOVE is nil, remove this function
  1423. from the `before-change-functions' in the current buffer."
  1424. (interactive)
  1425. (unless org-inhibit-highlight-removal
  1426. (mapc 'delete-overlay org-clock-overlays)
  1427. (setq org-clock-overlays nil)
  1428. (unless noremove
  1429. (remove-hook 'before-change-functions
  1430. 'org-clock-remove-overlays 'local))))
  1431. (defvar state) ;; dynamically scoped into this function
  1432. (defun org-clock-out-if-current ()
  1433. "Clock out if the current entry contains the running clock.
  1434. This is used to stop the clock after a TODO entry is marked DONE,
  1435. and is only done if the variable `org-clock-out-when-done' is not nil."
  1436. (when (and org-clock-out-when-done
  1437. (or (and (eq t org-clock-out-when-done)
  1438. (member state org-done-keywords))
  1439. (and (listp org-clock-out-when-done)
  1440. (member state org-clock-out-when-done)))
  1441. (equal (or (buffer-base-buffer (org-clocking-buffer))
  1442. (org-clocking-buffer))
  1443. (or (buffer-base-buffer (current-buffer))
  1444. (current-buffer)))
  1445. (< (point) org-clock-marker)
  1446. (> (save-excursion (outline-next-heading) (point))
  1447. org-clock-marker))
  1448. ;; Clock out, but don't accept a logging message for this.
  1449. (let ((org-log-note-clock-out nil)
  1450. (org-clock-out-switch-to-state nil))
  1451. (org-clock-out))))
  1452. (add-hook 'org-after-todo-state-change-hook
  1453. 'org-clock-out-if-current)
  1454. ;;;###autoload
  1455. (defun org-get-clocktable (&rest props)
  1456. "Get a formatted clocktable with parameters according to PROPS.
  1457. The table is created in a temporary buffer, fully formatted and
  1458. fontified, and then returned."
  1459. ;; Set the defaults
  1460. (setq props (plist-put props :name "clocktable"))
  1461. (unless (plist-member props :maxlevel)
  1462. (setq props (plist-put props :maxlevel 2)))
  1463. (unless (plist-member props :scope)
  1464. (setq props (plist-put props :scope 'agenda)))
  1465. (with-temp-buffer
  1466. (org-mode)
  1467. (org-create-dblock props)
  1468. (org-update-dblock)
  1469. (font-lock-fontify-buffer)
  1470. (forward-line 2)
  1471. (buffer-substring (point) (progn
  1472. (re-search-forward "^#\\+END" nil t)
  1473. (point-at-bol)))))
  1474. (defun org-clock-report (&optional arg)
  1475. "Create a table containing a report about clocked time.
  1476. If the cursor is inside an existing clocktable block, then the table
  1477. will be updated. If not, a new clocktable will be inserted.
  1478. When called with a prefix argument, move to the first clock table in the
  1479. buffer and update it."
  1480. (interactive "P")
  1481. (org-clock-remove-overlays)
  1482. (when arg
  1483. (org-find-dblock "clocktable")
  1484. (org-show-entry))
  1485. (if (org-in-clocktable-p)
  1486. (goto-char (org-in-clocktable-p))
  1487. (org-create-dblock (append (list :name "clocktable")
  1488. org-clock-clocktable-default-properties)))
  1489. (org-update-dblock))
  1490. (defun org-in-clocktable-p ()
  1491. "Check if the cursor is in a clocktable."
  1492. (let ((pos (point)) start)
  1493. (save-excursion
  1494. (end-of-line 1)
  1495. (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
  1496. (setq start (match-beginning 0))
  1497. (re-search-forward "^#\\+END:.*" nil t)
  1498. (>= (match-end 0) pos)
  1499. start))))
  1500. (defun org-clock-special-range (key &optional time as-strings)
  1501. "Return two times bordering a special time range.
  1502. Key is a symbol specifying the range and can be one of `today', `yesterday',
  1503. `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
  1504. A week starts Monday 0:00 and ends Sunday 24:00.
  1505. The range is determined relative to TIME. TIME defaults to the current time.
  1506. The return value is a cons cell with two internal times like the ones
  1507. returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
  1508. the returned times will be formatted strings."
  1509. (if (integerp key) (setq key (intern (number-to-string key))))
  1510. (let* ((tm (decode-time (or time (current-time))))
  1511. (s 0) (m (nth 1 tm)) (h (nth 2 tm))
  1512. (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
  1513. (dow (nth 6 tm))
  1514. (skey (symbol-name key))
  1515. (shift 0)
  1516. s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
  1517. (cond
  1518. ((string-match "^[0-9]+$" skey)
  1519. (setq y (string-to-number skey) m 1 d 1 key 'year))
  1520. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  1521. (setq y (string-to-number (match-string 1 skey))
  1522. month (string-to-number (match-string 2 skey))
  1523. d 1 key 'month))
  1524. ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
  1525. (require 'cal-iso)
  1526. (setq y (string-to-number (match-string 1 skey))
  1527. w (string-to-number (match-string 2 skey)))
  1528. (setq date (calendar-gregorian-from-absolute
  1529. (calendar-absolute-from-iso (list w 1 y))))
  1530. (setq d (nth 1 date) month (car date) y (nth 2 date)
  1531. dow 1
  1532. key 'week))
  1533. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  1534. (setq y (string-to-number (match-string 1 skey))
  1535. month (string-to-number (match-string 2 skey))
  1536. d (string-to-number (match-string 3 skey))
  1537. key 'day))
  1538. ((string-match "\\([-+][0-9]+\\)$" skey)
  1539. (setq shift (string-to-number (match-string 1 skey))
  1540. key (intern (substring skey 0 (match-beginning 1))))))
  1541. (when (= shift 0)
  1542. (cond ((eq key 'yesterday) (setq key 'today shift -1))
  1543. ((eq key 'lastweek) (setq key 'week shift -1))
  1544. ((eq key 'lastmonth) (setq key 'month shift -1))
  1545. ((eq key 'lastyear) (setq key 'year shift -1))))
  1546. (cond
  1547. ((memq key '(day today))
  1548. (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
  1549. ((memq key '(week thisweek))
  1550. (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
  1551. m 0 h 0 d (- d diff) d1 (+ 7 d)))
  1552. ((memq key '(month thismonth))
  1553. (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
  1554. ((memq key '(year thisyear))
  1555. (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
  1556. (t (error "No such time block %s" key)))
  1557. (setq ts (encode-time s m h d month y)
  1558. te (encode-time (or s1 s) (or m1 m) (or h1 h)
  1559. (or d1 d) (or month1 month) (or y1 y)))
  1560. (setq fm (cdr org-time-stamp-formats))
  1561. (cond
  1562. ((memq key '(day today))
  1563. (setq txt (format-time-string "%A, %B %d, %Y" ts)))
  1564. ((memq key '(week thisweek))
  1565. (setq txt (format-time-string "week %G-W%V" ts)))
  1566. ((memq key '(month thismonth))
  1567. (setq txt (format-time-string "%B %Y" ts)))
  1568. ((memq key '(year thisyear))
  1569. (setq txt (format-time-string "the year %Y" ts))))
  1570. (if as-strings
  1571. (list (format-time-string fm ts) (format-time-string fm te) txt)
  1572. (list ts te txt))))
  1573. (defun org-clocktable-shift (dir n)
  1574. "Try to shift the :block date of the clocktable at point.
  1575. Point must be in the #+BEGIN: line of a clocktable, or this function
  1576. will throw an error.
  1577. DIR is a direction, a symbol `left', `right', `up', or `down'.
  1578. Both `left' and `down' shift the block toward the past, `up' and `right'
  1579. push it toward the future.
  1580. N is the number of shift steps to take. The size of the step depends on
  1581. the currently selected interval size."
  1582. (setq n (prefix-numeric-value n))
  1583. (and (memq dir '(left down)) (setq n (- n)))
  1584. (save-excursion
  1585. (goto-char (point-at-bol))
  1586. (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
  1587. (error "Line needs a :block definition before this command works")
  1588. (let* ((b (match-beginning 1)) (e (match-end 1))
  1589. (s (match-string 1))
  1590. block shift ins y mw d date wp m)
  1591. (cond
  1592. ((equal s "yesterday") (setq s "today-1"))
  1593. ((equal s "lastweek") (setq s "thisweek-1"))
  1594. ((equal s "lastmonth") (setq s "thismonth-1"))
  1595. ((equal s "lastyear") (setq s "thisyear-1")))
  1596. (cond
  1597. ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
  1598. (setq block (match-string 1 s)
  1599. shift (if (match-end 2)
  1600. (string-to-number (match-string 2 s))
  1601. 0))
  1602. (setq shift (+ shift n))
  1603. (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
  1604. ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
  1605. ;; 1 1 2 3 3 4 4 5 6 6 5 2
  1606. (setq y (string-to-number (match-string 1 s))
  1607. wp (and (match-end 3) (match-string 3 s))
  1608. mw (and (match-end 4) (string-to-number (match-string 4 s)))
  1609. d (and (match-end 6) (string-to-number (match-string 6 s))))
  1610. (cond
  1611. (d (setq ins (format-time-string
  1612. "%Y-%m-%d"
  1613. (encode-time 0 0 0 (+ d n) m y))))
  1614. ((and wp mw (> (length wp) 0))
  1615. (require 'cal-iso)
  1616. (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
  1617. (setq ins (format-time-string
  1618. "%G-W%V"
  1619. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  1620. (mw
  1621. (setq ins (format-time-string
  1622. "%Y-%m"
  1623. (encode-time 0 0 0 1 (+ mw n) y))))
  1624. (y
  1625. (setq ins (number-to-string (+ y n))))))
  1626. (t (error "Cannot shift clocktable block")))
  1627. (when ins
  1628. (goto-char b)
  1629. (insert ins)
  1630. (delete-region (point) (+ (point) (- e b)))
  1631. (beginning-of-line 1)
  1632. (org-update-dblock)
  1633. t)))))
  1634. (defun org-dblock-write:clocktable (params)
  1635. "Write the standard clocktable."
  1636. (catch 'exit
  1637. (let* ((hlchars '((1 . "*") (2 . "/")))
  1638. (ins (make-marker))
  1639. (total-time nil)
  1640. (scope (plist-get params :scope))
  1641. (tostring (plist-get params :tostring))
  1642. (multifile (plist-get params :multifile))
  1643. (header (plist-get params :header))
  1644. (maxlevel (or (plist-get params :maxlevel) 3))
  1645. (step (plist-get params :step))
  1646. (emph (plist-get params :emphasize))
  1647. (timestamp (plist-get params :timestamp))
  1648. (ts (plist-get params :tstart))
  1649. (te (plist-get params :tend))
  1650. (block (plist-get params :block))
  1651. (link (plist-get params :link))
  1652. (tags (plist-get params :tags))
  1653. (matcher (if tags (cdr (org-make-tags-matcher tags))))
  1654. ipos time p level hlc hdl tsp props content recalc formula pcol
  1655. cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
  1656. (setq org-clock-file-total-minutes nil)
  1657. (when step
  1658. (unless (or block (and ts te))
  1659. (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
  1660. (org-clocktable-steps params)
  1661. (throw 'exit nil))
  1662. (when block
  1663. (setq cc (org-clock-special-range block nil t)
  1664. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  1665. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  1666. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  1667. (when (and ts (listp ts))
  1668. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  1669. (when (and te (listp te))
  1670. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  1671. ;; Now the times are strings we can parse.
  1672. (if ts (setq ts (org-float-time
  1673. (apply 'encode-time (org-parse-time-string ts)))))
  1674. (if te (setq te (org-float-time
  1675. (apply 'encode-time (org-parse-time-string te)))))
  1676. (move-marker ins (point))
  1677. (setq ipos (point))
  1678. ;; Get the right scope
  1679. (setq pos (point))
  1680. (cond
  1681. ((and scope (listp scope) (symbolp (car scope)))
  1682. (setq scope (eval scope)))
  1683. ((eq scope 'agenda)
  1684. (setq scope (org-agenda-files t)))
  1685. ((eq scope 'agenda-with-archives)
  1686. (setq scope (org-agenda-files t))
  1687. (setq scope (org-add-archive-files scope)))
  1688. ((eq scope 'file-with-archives)
  1689. (setq scope (org-add-archive-files (list (buffer-file-name)))
  1690. rm-file-column t)))
  1691. (setq scope-is-list (and scope (listp scope)))
  1692. (save-restriction
  1693. (cond
  1694. ((not scope))
  1695. ((eq scope 'file) (widen))
  1696. ((eq scope 'subtree) (org-narrow-to-subtree))
  1697. ((eq scope 'tree)
  1698. (while (org-up-heading-safe))
  1699. (org-narrow-to-subtree))
  1700. ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
  1701. (symbol-name scope)))
  1702. (setq level (string-to-number (match-string 1 (symbol-name scope))))
  1703. (catch 'exit
  1704. (while (org-up-heading-safe)
  1705. (looking-at outline-regexp)
  1706. (if (<= (org-reduced-level (funcall outline-level)) level)
  1707. (throw 'exit nil))))
  1708. (org-narrow-to-subtree))
  1709. (scope-is-list
  1710. (let* ((files scope)
  1711. (scope 'agenda)
  1712. (p1 (copy-sequence params))
  1713. file)
  1714. (setq p1 (plist-put p1 :tostring t))
  1715. (setq p1 (plist-put p1 :multifile t))
  1716. (setq p1 (plist-put p1 :scope 'file))
  1717. (org-prepare-agenda-buffers files)
  1718. (while (setq file (pop files))
  1719. (with-current-buffer (find-buffer-visiting file)
  1720. (setq org-clock-file-total-minutes 0)
  1721. (setq tbl1 (org-dblock-write:clocktable p1))
  1722. (when tbl1
  1723. (push (org-clocktable-add-file
  1724. file
  1725. (concat "| |*File time*|*"
  1726. (org-minutes-to-hh:mm-string
  1727. org-clock-file-total-minutes)
  1728. "*|\n"
  1729. tbl1)) tbl)
  1730. (setq total-time (+ (or total-time 0)
  1731. org-clock-file-total-minutes))))))))
  1732. (goto-char pos)
  1733. (unless scope-is-list
  1734. (org-clock-sum ts te
  1735. (unless (null matcher)
  1736. (lambda ()
  1737. (let ((tags-list
  1738. (org-split-string
  1739. (or (org-entry-get (point) "ALLTAGS") "")
  1740. ":")))
  1741. (eval matcher)))))
  1742. (goto-char (point-min))
  1743. (setq st t)
  1744. (while (or (and (bobp) (prog1 st (setq st nil))
  1745. (get-text-property (point) :org-clock-minutes)
  1746. (setq p (point-min)))
  1747. (setq p (next-single-property-change (point) :org-clock-minutes)))
  1748. (goto-char p)
  1749. (when (setq time (get-text-property p :org-clock-minutes))
  1750. (save-excursion
  1751. (beginning-of-line 1)
  1752. (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  1753. (setq level (org-reduced-level
  1754. (- (match-end 1) (match-beginning 1))))
  1755. (<= level maxlevel))
  1756. (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
  1757. hdl (if (not link)
  1758. (match-string 2)
  1759. (org-make-link-string
  1760. (format "file:%s::%s"
  1761. (buffer-file-name)
  1762. (save-match-data
  1763. (org-make-org-heading-search-string
  1764. (match-string 2))))
  1765. (match-string 2)))
  1766. tsp (when timestamp
  1767. (setq props (org-entry-properties (point)))
  1768. (or (cdr (assoc "SCHEDULED" props))
  1769. (cdr (assoc "TIMESTAMP" props))
  1770. (cdr (assoc "DEADLINE" props))
  1771. (cdr (assoc "TIMESTAMP_IA" props)))))
  1772. (if (and (not multifile) (= level 1)) (push "|-" tbl))
  1773. (push (concat
  1774. "| " (int-to-string level) "|"
  1775. (if timestamp (concat tsp "|") "")
  1776. hlc hdl hlc " |"
  1777. (make-string (1- level) ?|)
  1778. hlc (org-minutes-to-hh:mm-string time) hlc
  1779. " |") tbl))))))
  1780. (setq tbl (nreverse tbl))
  1781. (if tostring
  1782. (if tbl (mapconcat 'identity tbl "\n") nil)
  1783. (goto-char ins)
  1784. (insert-before-markers
  1785. (or header
  1786. (concat
  1787. "Clock summary at ["
  1788. (substring
  1789. (format-time-string (cdr org-time-stamp-formats))
  1790. 1 -1)
  1791. "]"
  1792. (if block (concat ", for " range-text ".") "")
  1793. "\n\n"))
  1794. (if scope-is-list "|File" "")
  1795. "|L|" (if timestamp "Timestamp|" "") "Headline|Time|\n")
  1796. (setq total-time (or total-time org-clock-file-total-minutes))
  1797. (insert-before-markers
  1798. "|-\n|"
  1799. (if scope-is-list "|" "")
  1800. (if timestamp "|Timestamp|" "|")
  1801. "*Total time*| *"
  1802. (org-minutes-to-hh:mm-string (or total-time 0))
  1803. "*|\n|-\n")
  1804. (setq tbl (delq nil tbl))
  1805. (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
  1806. (equal (substring (car tbl) 0 2) "|-"))
  1807. (pop tbl))
  1808. (insert-before-markers (mapconcat
  1809. 'identity (delq nil tbl)
  1810. (if scope-is-list "\n|-\n" "\n")))
  1811. (backward-delete-char 1)
  1812. (if (setq formula (plist-get params :formula))
  1813. (cond
  1814. ((eq formula '%)
  1815. (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
  1816. (insert
  1817. (format
  1818. "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
  1819. pcol
  1820. 2
  1821. (+ 3 (if scope-is-list 1 0))
  1822. (+ (if scope-is-list 1 0) 3)
  1823. (1- pcol)))
  1824. (setq recalc t))
  1825. ((stringp formula)
  1826. (insert "\n#+TBLFM: " formula)
  1827. (setq recalc t))
  1828. (t (error "invalid formula in clocktable")))
  1829. ;; Should we rescue an old formula?
  1830. (when (stringp (setq content (plist-get params :content)))
  1831. (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
  1832. (setq recalc t)
  1833. (insert "\n" (match-string 1 (plist-get params :content)))
  1834. (beginning-of-line 0))))
  1835. (goto-char ipos)
  1836. (skip-chars-forward "^|")
  1837. (org-table-align)
  1838. (when recalc
  1839. (if (eq formula '%)
  1840. (save-excursion (org-table-goto-column pcol nil 'force)
  1841. (insert "%")))
  1842. (org-table-recalculate 'all))
  1843. (when rm-file-column
  1844. (forward-char 1)
  1845. (org-table-delete-column))
  1846. total-time)))))
  1847. (defun org-clocktable-steps (params)
  1848. (let* ((p1 (copy-sequence params))
  1849. (ts (plist-get p1 :tstart))
  1850. (te (plist-get p1 :tend))
  1851. (step0 (plist-get p1 :step))
  1852. (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
  1853. (stepskip0 (plist-get p1 :stepskip0))
  1854. (block (plist-get p1 :block))
  1855. cc range-text step-time)
  1856. (when block
  1857. (setq cc (org-clock-special-range block nil t)
  1858. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  1859. (cond
  1860. ((numberp ts)
  1861. ;; If ts is a number, it's an absolute day number from org-agenda.
  1862. (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
  1863. (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
  1864. (ts
  1865. (setq ts (org-float-time
  1866. (apply 'encode-time (org-parse-time-string ts))))))
  1867. (cond
  1868. ((numberp te)
  1869. ;; Likewise for te.
  1870. (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
  1871. (setq te (org-float-time (encode-time 0 0 0 day month year)))))
  1872. (te
  1873. (setq te (org-float-time
  1874. (apply 'encode-time (org-parse-time-string te))))))
  1875. (setq p1 (plist-put p1 :header ""))
  1876. (setq p1 (plist-put p1 :step nil))
  1877. (setq p1 (plist-put p1 :block nil))
  1878. (while (< ts te)
  1879. (or (bolp) (insert "\n"))
  1880. (setq p1 (plist-put p1 :tstart (format-time-string
  1881. (org-time-stamp-format nil t)
  1882. (seconds-to-time ts))))
  1883. (setq p1 (plist-put p1 :tend (format-time-string
  1884. (org-time-stamp-format nil t)
  1885. (seconds-to-time (setq ts (+ ts step))))))
  1886. (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
  1887. (plist-get p1 :tstart) "\n")
  1888. (setq step-time (org-dblock-write:clocktable p1))
  1889. (re-search-forward "#\\+END:")
  1890. (when (and (equal step-time 0) stepskip0)
  1891. ;; Remove the empty table
  1892. (delete-region (point-at-bol)
  1893. (save-excursion
  1894. (re-search-backward "^\\(Daily\\|Weekly\\) report" nil t)
  1895. (point))))
  1896. (end-of-line 0))))
  1897. (defun org-clocktable-add-file (file table)
  1898. (if table
  1899. (let ((lines (org-split-string table "\n"))
  1900. (ff (file-name-nondirectory file)))
  1901. (mapconcat 'identity
  1902. (mapcar (lambda (x)
  1903. (if (string-match org-table-dataline-regexp x)
  1904. (concat "|" ff x)
  1905. x))
  1906. lines)
  1907. "\n"))))
  1908. (defun org-clock-time% (total &rest strings)
  1909. "Compute a time fraction in percent.
  1910. TOTAL s a time string like 10:21 specifying the total times.
  1911. STRINGS is a list of strings that should be checked for a time.
  1912. The first string that does have a time will be used.
  1913. This function is made for clock tables."
  1914. (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
  1915. tot s)
  1916. (save-match-data
  1917. (catch 'exit
  1918. (if (not (string-match re total))
  1919. (throw 'exit 0.)
  1920. (setq tot (+ (string-to-number (match-string 2 total))
  1921. (* 60 (string-to-number (match-string 1 total)))))
  1922. (if (= tot 0.) (throw 'exit 0.)))
  1923. (while (setq s (pop strings))
  1924. (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  1925. (throw 'exit
  1926. (/ (* 100.0 (+ (string-to-number (match-string 2 s))
  1927. (* 60 (string-to-number (match-string 1 s)))))
  1928. tot))))
  1929. 0))))
  1930. (defvar org-clock-loaded nil
  1931. "Was the clock file loaded?")
  1932. (defun org-clock-save ()
  1933. "Persist various clock-related data to disk.
  1934. The details of what will be saved are regulated by the variable
  1935. `org-clock-persist'."
  1936. (when (and org-clock-persist
  1937. (or org-clock-loaded
  1938. org-clock-has-been-used
  1939. (not (file-exists-p org-clock-persist-file))))
  1940. (let (b)
  1941. (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
  1942. (progn
  1943. (delete-region (point-min) (point-max))
  1944. ;;Store clock
  1945. (insert (format ";; org-persist.el - %s at %s\n"
  1946. system-name (format-time-string
  1947. (cdr org-time-stamp-formats))))
  1948. (if (and (memq org-clock-persist '(t clock))
  1949. (setq b (org-clocking-buffer))
  1950. (setq b (or (buffer-base-buffer b) b))
  1951. (buffer-live-p b)
  1952. (buffer-file-name b)
  1953. (or (not org-clock-persist-query-save)
  1954. (y-or-n-p (concat "Save current clock ("
  1955. (substring-no-properties org-clock-heading)
  1956. ") "))))
  1957. (insert "(setq resume-clock '(\""
  1958. (buffer-file-name (org-clocking-buffer))
  1959. "\" . " (int-to-string (marker-position org-clock-marker))
  1960. "))\n"))
  1961. ;; Store clocked task history. Tasks are stored reversed to make
  1962. ;; reading simpler
  1963. (when (and (memq org-clock-persist '(t history))
  1964. org-clock-history)
  1965. (insert
  1966. "(setq stored-clock-history '("
  1967. (mapconcat
  1968. (lambda (m)
  1969. (when (and (setq b (marker-buffer m))
  1970. (setq b (or (buffer-base-buffer b) b))
  1971. (buffer-live-p b)
  1972. (buffer-file-name b))
  1973. (concat "(\"" (buffer-file-name b)
  1974. "\" . " (int-to-string (marker-position m))
  1975. ")")))
  1976. (reverse org-clock-history) " ") "))\n"))
  1977. (save-buffer)
  1978. (kill-buffer (current-buffer)))))))
  1979. (defun org-clock-load ()
  1980. "Load clock-related data from disk, maybe resuming a stored clock."
  1981. (when (and org-clock-persist (not org-clock-loaded))
  1982. (let ((filename (expand-file-name org-clock-persist-file))
  1983. (org-clock-in-resume 'auto-restart)
  1984. resume-clock stored-clock-history)
  1985. (if (not (file-readable-p filename))
  1986. (message "Not restoring clock data; %s not found"
  1987. org-clock-persist-file)
  1988. (message "%s" "Restoring clock data")
  1989. (setq org-clock-loaded t)
  1990. (load-file filename)
  1991. ;; load history
  1992. (when stored-clock-history
  1993. (save-window-excursion
  1994. (mapc (lambda (task)
  1995. (if (file-exists-p (car task))
  1996. (org-clock-history-push (cdr task)
  1997. (find-file (car task)))))
  1998. stored-clock-history)))
  1999. ;; resume clock
  2000. (when (and resume-clock org-clock-persist
  2001. (file-exists-p (car resume-clock))
  2002. (or (not org-clock-persist-query-resume)
  2003. (y-or-n-p
  2004. (concat
  2005. "Resume clock ("
  2006. (with-current-buffer (find-file (car resume-clock))
  2007. (save-excursion
  2008. (goto-char (cdr resume-clock))
  2009. (org-back-to-heading t)
  2010. (and (looking-at org-complex-heading-regexp)
  2011. (match-string 4))))
  2012. ") "))))
  2013. (when (file-exists-p (car resume-clock))
  2014. (with-current-buffer (find-file (car resume-clock))
  2015. (goto-char (cdr resume-clock))
  2016. (let ((org-clock-auto-clock-resolution nil))
  2017. (org-clock-in)
  2018. (if (org-invisible-p)
  2019. (org-show-context))))))))))
  2020. ;;;###autoload
  2021. (defun org-clock-persistence-insinuate ()
  2022. "Set up hooks for clock persistence."
  2023. (add-hook 'org-mode-hook 'org-clock-load)
  2024. (add-hook 'kill-emacs-hook 'org-clock-save))
  2025. ;; Suggested bindings
  2026. (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
  2027. (provide 'org-clock)
  2028. ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
  2029. ;;; org-clock.el ends here