org-clock.el 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. ;;; org-clock.el --- The time clocking code for Org-mode
  2. ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 6.02b
  7. ;;
  8. ;; This file is part of GNU Emacs.
  9. ;;
  10. ;; GNU Emacs is free software; you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation; either version 3, or (at your option)
  13. ;; any later version.
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  20. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  21. ;; Boston, MA 02110-1301, USA.
  22. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  23. ;;
  24. ;;; Commentary:
  25. ;; This file contains the time clocking code for Org-mode
  26. (require 'org)
  27. (eval-when-compile
  28. (require 'cl)
  29. (require 'calendar))
  30. (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
  31. (defgroup org-clock nil
  32. "Options concerning clocking working time in Org-mode."
  33. :tag "Org Clock"
  34. :group 'org-progress)
  35. (defcustom org-clock-into-drawer 2
  36. "Should clocking info be wrapped into a drawer?
  37. When t, clocking info will always be inserted into a :CLOCK: drawer.
  38. If necessary, the drawer will be created.
  39. When nil, the drawer will not be created, but used when present.
  40. When an integer and the number of clocking entries in an item
  41. reaches or exceeds this number, a drawer will be created."
  42. :group 'org-todo
  43. :group 'org-clock
  44. :type '(choice
  45. (const :tag "Always" t)
  46. (const :tag "Only when drawer exists" nil)
  47. (integer :tag "When at least N clock entries")))
  48. (defcustom org-clock-out-when-done t
  49. "When t, the clock will be stopped when the relevant entry is marked DONE.
  50. Nil means, clock will keep running until stopped explicitly with
  51. `C-c C-x C-o', or until the clock is started in a different item."
  52. :group 'org-clock
  53. :type 'boolean)
  54. (defcustom org-clock-out-remove-zero-time-clocks nil
  55. "Non-nil means, remove the clock line when the resulting time is zero."
  56. :group 'org-clock
  57. :type 'boolean)
  58. (defcustom org-clock-in-switch-to-state nil
  59. "Set task to a special todo state while clocking it.
  60. The value should be the state to which the entry should be switched."
  61. :group 'org-clock
  62. :group 'org-todo
  63. :type '(choice
  64. (const :tag "Don't force a state" nil)
  65. (string :tag "State")))
  66. (defcustom org-clock-history-length 5
  67. "Number of clock tasks to remember in history."
  68. :group 'org-clock
  69. :type 'integer)
  70. (defcustom org-clock-heading-function nil
  71. "When non-nil, should be a function to create `org-clock-heading'.
  72. This is the string shown in the mode line when a clock is running.
  73. The function is called with point at the beginning of the headline."
  74. :group 'org-clock
  75. :type 'function)
  76. ;;; The clock for measuring work time.
  77. (defvar org-mode-line-string "")
  78. (put 'org-mode-line-string 'risky-local-variable t)
  79. (defvar org-mode-line-timer nil)
  80. (defvar org-clock-heading "")
  81. (defvar org-clock-start-time "")
  82. (defvar org-clock-history nil
  83. "List of marker pointing to recent clocked tasks.")
  84. (defvar org-clock-default-task (make-marker)
  85. "Marker pointing to the default task that should clock time.
  86. The clock can be made to switch to this task after clocking out
  87. of a different task.")
  88. (defvar org-clock-interrupted-task (make-marker)
  89. "Marker pointing to the task that has been interrupted by the current clock.")
  90. (defun org-clock-history-push (&optional pos buffer)
  91. "Push a marker to the clock history."
  92. (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
  93. (while (setq n (member m org-clock-history))
  94. (move-marker (car n) nil))
  95. (setq org-clock-history
  96. (delq nil
  97. (mapcar (lambda (x) (if (marker-buffer x) x nil))
  98. org-clock-history)))
  99. (when (>= (setq l (length org-clock-history)) org-clock-history-length)
  100. (setq org-clock-history
  101. (nreverse
  102. (nthcdr (- l org-clock-history-length -1)
  103. (nreverse org-clock-history)))))
  104. (push m org-clock-history)))
  105. (defun org-clock-select-task (&optional prompt)
  106. "Select a task that recently was associated with clocking."
  107. (interactive)
  108. (let (sel-list rpl file task (i 0) s)
  109. (save-window-excursion
  110. (org-switch-to-buffer-other-window
  111. (get-buffer-create "*Clock Task Select*"))
  112. (erase-buffer)
  113. (when (marker-buffer org-clock-default-task)
  114. (insert (org-add-props "Default Task\n" nil 'face 'bold))
  115. (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
  116. (push s sel-list))
  117. (when (marker-buffer org-clock-interrupted-task)
  118. (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
  119. (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
  120. (push s sel-list))
  121. (when (marker-buffer org-clock-marker)
  122. (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
  123. (setq s (org-clock-insert-selection-line ?c org-clock-marker))
  124. (push s sel-list))
  125. (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
  126. (mapc
  127. (lambda (m)
  128. (when (marker-buffer m)
  129. (setq i (1+ i)
  130. s (org-clock-insert-selection-line
  131. (string-to-char (number-to-string i)) m))
  132. (push s sel-list)))
  133. org-clock-history)
  134. (shrink-window-if-larger-than-buffer)
  135. (message (or prompt "Select task for clocking:"))
  136. (setq rpl (read-char-exclusive))
  137. (cond
  138. ((eq rpl ?q) nil)
  139. ((eq rpl ?x) nil)
  140. ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
  141. (t (error "Invalid task choice %c" rpl))))))
  142. (defun org-clock-insert-selection-line (i marker)
  143. (when (marker-buffer marker)
  144. (let (file cat task)
  145. (with-current-buffer (org-base-buffer (marker-buffer marker))
  146. (save-excursion
  147. (save-restriction
  148. (widen)
  149. (goto-char marker)
  150. (setq file (buffer-file-name (marker-buffer marker))
  151. cat (or (org-get-category)
  152. (progn (org-refresh-category-properties)
  153. (org-get-category)))
  154. task (org-get-heading 'notags)))))
  155. (when (and cat task)
  156. (insert (format "[%c] %-15s %s\n" i cat task))
  157. (cons i marker)))))
  158. (defun org-update-mode-line ()
  159. (let* ((delta (- (time-to-seconds (current-time))
  160. (time-to-seconds org-clock-start-time)))
  161. (h (floor delta 3600))
  162. (m (floor (- delta (* 3600 h)) 60)))
  163. (setq org-mode-line-string
  164. (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
  165. 'help-echo "Org-mode clock is running"))
  166. (force-mode-line-update)))
  167. (defvar org-clock-mode-line-entry nil
  168. "Information for the modeline about the running clock.")
  169. (defun org-clock-in (&optional select)
  170. "Start the clock on the current item.
  171. If necessary, clock-out of the currently active clock.
  172. With prefix arg SELECT, offer a list of recently clocked ta sks to
  173. clock into. When SELECT is `C-u C-u', clock into the current task and mark
  174. is as the default task, a special task that will always be offered in
  175. the clocking selection, associated with the letter `d'."
  176. (interactive "P")
  177. (let ((interrupting (marker-buffer org-clock-marker))
  178. ts selected-task target-pos)
  179. (when (equal select '(4))
  180. (setq selected-task (org-clock-select-task "Clock-in on task: "))
  181. (if selected-task
  182. (setq selected-task (copy-marker selected-task))
  183. (error "Abort")))
  184. (when interrupting
  185. ;; We are interrupting the clocking of a differnt task.
  186. ;; Save a marker to this task, so that we can go back.
  187. (move-marker org-clock-interrupted-task
  188. (marker-position org-clock-marker)
  189. (marker-buffer org-clock-marker))
  190. (org-clock-out t))
  191. (when (equal select '(16))
  192. ;; Mark as default clocking task
  193. (save-excursion
  194. (org-back-to-heading t)
  195. (move-marker org-clock-default-task (point))))
  196. (setq target-pos (point)) ;; we want to clock in at this location
  197. (save-excursion
  198. (when (and selected-task (marker-buffer selected-task))
  199. ;; There is a selected task, move to the correct buffer
  200. ;; and set the new target position.
  201. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  202. (setq target-pos (marker-position selected-task))
  203. (move-marker selected-task nil))
  204. (save-excursion
  205. (save-restriction
  206. (widen)
  207. (goto-char target-pos)
  208. (org-back-to-heading t)
  209. (or interrupting (move-marker org-clock-interrupted-task nil))
  210. (org-clock-history-push)
  211. (when (and org-clock-in-switch-to-state
  212. (not (looking-at (concat outline-regexp "[ \t]*"
  213. org-clock-in-switch-to-state
  214. "\\>"))))
  215. (org-todo org-clock-in-switch-to-state))
  216. (if (and org-clock-heading-function
  217. (functionp org-clock-heading-function))
  218. (setq org-clock-heading (funcall org-clock-heading-function))
  219. (if (looking-at org-complex-heading-regexp)
  220. (setq org-clock-heading (match-string 4))
  221. (setq org-clock-heading "???")))
  222. (setq org-clock-heading (propertize org-clock-heading 'face nil))
  223. (org-clock-find-position)
  224. (insert "\n") (backward-char 1)
  225. (indent-relative)
  226. (insert org-clock-string " ")
  227. (setq org-clock-start-time (current-time))
  228. (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
  229. (move-marker org-clock-marker (point) (buffer-base-buffer))
  230. (or global-mode-string (setq global-mode-string '("")))
  231. (or (memq 'org-mode-line-string global-mode-string)
  232. (setq global-mode-string
  233. (append global-mode-string '(org-mode-line-string))))
  234. (org-update-mode-line)
  235. (setq org-mode-line-timer
  236. (run-with-timer 60 60 'org-update-mode-line))
  237. (message "Clock started at %s" ts))))))
  238. (defun org-clock-find-position ()
  239. "Find the location where the next clock line should be inserted."
  240. (org-back-to-heading t)
  241. (catch 'exit
  242. (let ((beg (save-excursion
  243. (beginning-of-line 2)
  244. (or (bolp) (newline))
  245. (point)))
  246. (end (progn (outline-next-heading) (point)))
  247. (re (concat "^[ \t]*" org-clock-string))
  248. (cnt 0)
  249. first last)
  250. (goto-char beg)
  251. (when (eobp) (newline) (setq end (max (point) end)))
  252. (when (re-search-forward "^[ \t]*:CLOCK:" end t)
  253. ;; we seem to have a CLOCK drawer, so go there.
  254. (beginning-of-line 2)
  255. (throw 'exit t))
  256. ;; Lets count the CLOCK lines
  257. (goto-char beg)
  258. (while (re-search-forward re end t)
  259. (setq first (or first (match-beginning 0))
  260. last (match-beginning 0)
  261. cnt (1+ cnt)))
  262. (when (and (integerp org-clock-into-drawer)
  263. (>= (1+ cnt) org-clock-into-drawer))
  264. ;; Wrap current entries into a new drawer
  265. (goto-char last)
  266. (beginning-of-line 2)
  267. (insert ":END:\n")
  268. (beginning-of-line 0)
  269. (org-indent-line-function)
  270. (goto-char first)
  271. (insert ":CLOCK:\n")
  272. (beginning-of-line 0)
  273. (org-indent-line-function)
  274. (org-flag-drawer t)
  275. (beginning-of-line 2)
  276. (throw 'exit nil))
  277. (goto-char beg)
  278. (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  279. (not (equal (match-string 1) org-clock-string)))
  280. ;; Planning info, skip to after it
  281. (beginning-of-line 2)
  282. (or (bolp) (newline)))
  283. (when (eq t org-clock-into-drawer)
  284. (insert ":CLOCK:\n:END:\n")
  285. (beginning-of-line -1)
  286. (org-indent-line-function)
  287. (org-flag-drawer t)
  288. (beginning-of-line 2)
  289. (org-indent-line-function)))))
  290. (defun org-clock-out (&optional fail-quietly)
  291. "Stop the currently running clock.
  292. If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
  293. (interactive)
  294. (catch 'exit
  295. (if (not (marker-buffer org-clock-marker))
  296. (if fail-quietly (throw 'exit t) (error "No active clock")))
  297. (let (ts te s h m remove)
  298. (save-excursion
  299. (set-buffer (marker-buffer org-clock-marker))
  300. (save-restriction
  301. (widen)
  302. (goto-char org-clock-marker)
  303. (beginning-of-line 1)
  304. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  305. (equal (match-string 1) org-clock-string))
  306. (setq ts (match-string 2))
  307. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  308. (goto-char (match-end 0))
  309. (delete-region (point) (point-at-eol))
  310. (insert "--")
  311. (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
  312. (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
  313. (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
  314. h (floor (/ s 3600))
  315. s (- s (* 3600 h))
  316. m (floor (/ s 60))
  317. s (- s (* 60 s)))
  318. (insert " => " (format "%2d:%02d" h m))
  319. (when (setq remove (and org-clock-out-remove-zero-time-clocks
  320. (= (+ h m) 0)))
  321. (beginning-of-line 1)
  322. (delete-region (point) (point-at-eol))
  323. (and (looking-at "\n") (> (point-max) (1+ (point)))
  324. (delete-char 1)))
  325. (move-marker org-clock-marker nil)
  326. (when org-log-note-clock-out
  327. (org-add-log-setup 'clock-out))
  328. (when org-mode-line-timer
  329. (cancel-timer org-mode-line-timer)
  330. (setq org-mode-line-timer nil))
  331. (setq global-mode-string
  332. (delq 'org-mode-line-string global-mode-string))
  333. (force-mode-line-update)
  334. (message "Clock stopped at %s after HH:MM = %d:%02d%s" te h m
  335. (if remove " => LINE REMOVED" "")))))))
  336. (defun org-clock-cancel ()
  337. "Cancel the running clock be removing the start timestamp."
  338. (interactive)
  339. (if (not (marker-buffer org-clock-marker))
  340. (error "No active clock"))
  341. (save-excursion
  342. (set-buffer (marker-buffer org-clock-marker))
  343. (goto-char org-clock-marker)
  344. (delete-region (1- (point-at-bol)) (point-at-eol)))
  345. (setq global-mode-string
  346. (delq 'org-mode-line-string global-mode-string))
  347. (force-mode-line-update)
  348. (message "Clock canceled"))
  349. (defun org-clock-goto (&optional select)
  350. "Go to the currently clocked-in entry.
  351. With prefix arg SELECT, offer recently clocked tasks."
  352. (interactive "P")
  353. (let ((m (if select
  354. (org-clock-select-task "Select task to go to: ")
  355. org-clock-marker)))
  356. (if (not (marker-buffer m))
  357. (if select
  358. (error "No task selected")
  359. (error "No active clock")))
  360. (switch-to-buffer (marker-buffer m))
  361. (if (or (< m (point-min)) (> m (point-max))) (widen))
  362. (goto-char m)
  363. (org-show-entry)
  364. (org-back-to-heading)
  365. (org-cycle-hide-drawers 'children)
  366. (recenter)))
  367. (defvar org-clock-file-total-minutes nil
  368. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  369. (make-variable-buffer-local 'org-clock-file-total-minutes)
  370. (defun org-clock-sum (&optional tstart tend)
  371. "Sum the times for each subtree.
  372. Puts the resulting times in minutes as a text property on each headline."
  373. (interactive)
  374. (let* ((bmp (buffer-modified-p))
  375. (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  376. org-clock-string
  377. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  378. (lmax 30)
  379. (ltimes (make-vector lmax 0))
  380. (t1 0)
  381. (level 0)
  382. ts te dt
  383. time)
  384. (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
  385. (save-excursion
  386. (goto-char (point-max))
  387. (while (re-search-backward re nil t)
  388. (cond
  389. ((match-end 2)
  390. ;; Two time stamps
  391. (setq ts (match-string 2)
  392. te (match-string 3)
  393. ts (time-to-seconds
  394. (apply 'encode-time (org-parse-time-string ts)))
  395. te (time-to-seconds
  396. (apply 'encode-time (org-parse-time-string te)))
  397. ts (if tstart (max ts tstart) ts)
  398. te (if tend (min te tend) te)
  399. dt (- te ts)
  400. t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
  401. ((match-end 4)
  402. ;; A naket time
  403. (setq t1 (+ t1 (string-to-number (match-string 5))
  404. (* 60 (string-to-number (match-string 4))))))
  405. (t ;; A headline
  406. (setq level (- (match-end 1) (match-beginning 1)))
  407. (when (or (> t1 0) (> (aref ltimes level) 0))
  408. (loop for l from 0 to level do
  409. (aset ltimes l (+ (aref ltimes l) t1)))
  410. (setq t1 0 time (aref ltimes level))
  411. (loop for l from level to (1- lmax) do
  412. (aset ltimes l 0))
  413. (goto-char (match-beginning 0))
  414. (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
  415. (setq org-clock-file-total-minutes (aref ltimes 0)))
  416. (set-buffer-modified-p bmp)))
  417. (defun org-clock-display (&optional total-only)
  418. "Show subtree times in the entire buffer.
  419. If TOTAL-ONLY is non-nil, only show the total time for the entire file
  420. in the echo area."
  421. (interactive)
  422. (org-remove-clock-overlays)
  423. (let (time h m p)
  424. (org-clock-sum)
  425. (unless total-only
  426. (save-excursion
  427. (goto-char (point-min))
  428. (while (or (and (equal (setq p (point)) (point-min))
  429. (get-text-property p :org-clock-minutes))
  430. (setq p (next-single-property-change
  431. (point) :org-clock-minutes)))
  432. (goto-char p)
  433. (when (setq time (get-text-property p :org-clock-minutes))
  434. (org-put-clock-overlay time (funcall outline-level))))
  435. (setq h (/ org-clock-file-total-minutes 60)
  436. m (- org-clock-file-total-minutes (* 60 h)))
  437. ;; Arrange to remove the overlays upon next change.
  438. (when org-remove-highlights-with-change
  439. (org-add-hook 'before-change-functions 'org-remove-clock-overlays
  440. nil 'local))))
  441. (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
  442. (defvar org-clock-overlays nil)
  443. (make-variable-buffer-local 'org-clock-overlays)
  444. (defun org-put-clock-overlay (time &optional level)
  445. "Put an overlays on the current line, displaying TIME.
  446. If LEVEL is given, prefix time with a corresponding number of stars.
  447. This creates a new overlay and stores it in `org-clock-overlays', so that it
  448. will be easy to remove."
  449. (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
  450. (l (if level (org-get-valid-level level 0) 0))
  451. (off 0)
  452. ov tx)
  453. (org-move-to-column c)
  454. (unless (eolp) (skip-chars-backward "^ \t"))
  455. (skip-chars-backward " \t")
  456. (setq ov (org-make-overlay (1- (point)) (point-at-eol))
  457. tx (concat (buffer-substring (1- (point)) (point))
  458. (make-string (+ off (max 0 (- c (current-column)))) ?.)
  459. (org-add-props (format "%s %2d:%02d%s"
  460. (make-string l ?*) h m
  461. (make-string (- 16 l) ?\ ))
  462. '(face secondary-selection))
  463. ""))
  464. (if (not (featurep 'xemacs))
  465. (org-overlay-put ov 'display tx)
  466. (org-overlay-put ov 'invisible t)
  467. (org-overlay-put ov 'end-glyph (make-glyph tx)))
  468. (push ov org-clock-overlays)))
  469. (defun org-remove-clock-overlays (&optional beg end noremove)
  470. "Remove the occur highlights from the buffer.
  471. BEG and END are ignored. If NOREMOVE is nil, remove this function
  472. from the `before-change-functions' in the current buffer."
  473. (interactive)
  474. (unless org-inhibit-highlight-removal
  475. (mapc 'org-delete-overlay org-clock-overlays)
  476. (setq org-clock-overlays nil)
  477. (unless noremove
  478. (remove-hook 'before-change-functions
  479. 'org-remove-clock-overlays 'local))))
  480. (defvar state) ;; dynamically scoped into this function
  481. (defun org-clock-out-if-current ()
  482. "Clock out if the current entry contains the running clock.
  483. This is used to stop the clock after a TODO entry is marked DONE,
  484. and is only done if the variable `org-clock-out-when-done' is not nil."
  485. (when (and org-clock-out-when-done
  486. (member state org-done-keywords)
  487. (equal (marker-buffer org-clock-marker) (current-buffer))
  488. (< (point) org-clock-marker)
  489. (> (save-excursion (outline-next-heading) (point))
  490. org-clock-marker))
  491. ;; Clock out, but don't accept a logging message for this.
  492. (let ((org-log-note-clock-out nil))
  493. (org-clock-out))))
  494. (add-hook 'org-after-todo-state-change-hook
  495. 'org-clock-out-if-current)
  496. ;;;###autoload
  497. (defun org-get-clocktable (&rest props)
  498. "Get a formatted clocktable with parameters according to PROPS.
  499. The table is created in a temporary buffer, fully formatted and
  500. fontified, and then returned."
  501. ;; Set the defaults
  502. (setq props (plist-put props :name "clocktable"))
  503. (unless (plist-member props :maxlevel)
  504. (setq props (plist-put props :maxlevel 2)))
  505. (unless (plist-member props :scope)
  506. (setq props (plist-put props :scope 'agenda)))
  507. (with-temp-buffer
  508. (org-mode)
  509. (org-create-dblock props)
  510. (org-update-dblock)
  511. (font-lock-fontify-buffer)
  512. (forward-line 2)
  513. (buffer-substring (point) (progn
  514. (re-search-forward "^#\\+END" nil t)
  515. (point-at-bol)))))
  516. (defun org-clock-report (&optional arg)
  517. "Create a table containing a report about clocked time.
  518. If the cursor is inside an existing clocktable block, then the table
  519. will be updated. If not, a new clocktable will be inserted.
  520. When called with a prefix argument, move to the first clock table in the
  521. buffer and update it."
  522. (interactive "P")
  523. (org-remove-clock-overlays)
  524. (when arg
  525. (org-find-dblock "clocktable")
  526. (org-show-entry))
  527. (if (org-in-clocktable-p)
  528. (goto-char (org-in-clocktable-p))
  529. (org-create-dblock (list :name "clocktable"
  530. :maxlevel 2 :scope 'file)))
  531. (org-update-dblock))
  532. (defun org-in-clocktable-p ()
  533. "Check if the cursor is in a clocktable."
  534. (let ((pos (point)) start)
  535. (save-excursion
  536. (end-of-line 1)
  537. (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
  538. (setq start (match-beginning 0))
  539. (re-search-forward "^#\\+END:.*" nil t)
  540. (>= (match-end 0) pos)
  541. start))))
  542. (defun org-clock-special-range (key &optional time as-strings)
  543. "Return two times bordering a special time range.
  544. Key is a symbol specifying the range and can be one of `today', `yesterday',
  545. `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
  546. A week starts Monday 0:00 and ends Sunday 24:00.
  547. The range is determined relative to TIME. TIME defaults to the current time.
  548. The return value is a cons cell with two internal times like the ones
  549. returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
  550. the returned times will be formatted strings."
  551. (if (integerp key) (setq key (intern (number-to-string key))))
  552. (let* ((tm (decode-time (or time (current-time))))
  553. (s 0) (m (nth 1 tm)) (h (nth 2 tm))
  554. (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
  555. (dow (nth 6 tm))
  556. (skey (symbol-name key))
  557. (shift 0)
  558. s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
  559. (cond
  560. ((string-match "^[0-9]+$" skey)
  561. (setq y (string-to-number skey) m 1 d 1 key 'year))
  562. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  563. (setq y (string-to-number (match-string 1 skey))
  564. month (string-to-number (match-string 2 skey))
  565. d 1 key 'month))
  566. ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
  567. (require 'cal-iso)
  568. (setq y (string-to-number (match-string 1 skey))
  569. w (string-to-number (match-string 2 skey)))
  570. (setq date (calendar-gregorian-from-absolute
  571. (calendar-absolute-from-iso (list w 1 y))))
  572. (setq d (nth 1 date) month (car date) y (nth 2 date)
  573. key 'week))
  574. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  575. (setq y (string-to-number (match-string 1 skey))
  576. month (string-to-number (match-string 2 skey))
  577. d (string-to-number (match-string 3 skey))
  578. key 'day))
  579. ((string-match "\\([-+][0-9]+\\)$" skey)
  580. (setq shift (string-to-number (match-string 1 skey))
  581. key (intern (substring skey 0 (match-beginning 1))))))
  582. (unless shift
  583. (cond ((eq key 'yesterday) (setq key 'today shift -1))
  584. ((eq key 'lastweek) (setq key 'week shift -1))
  585. ((eq key 'lastmonth) (setq key 'month shift -1))
  586. ((eq key 'lastyear) (setq key 'year shift -1))))
  587. (cond
  588. ((memq key '(day today))
  589. (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
  590. ((memq key '(week thisweek))
  591. (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
  592. m 0 h 0 d (- d diff) d1 (+ 7 d)))
  593. ((memq key '(month thismonth))
  594. (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
  595. ((memq key '(year thisyear))
  596. (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
  597. (t (error "No such time block %s" key)))
  598. (setq ts (encode-time s m h d month y)
  599. te (encode-time (or s1 s) (or m1 m) (or h1 h)
  600. (or d1 d) (or month1 month) (or y1 y)))
  601. (setq fm (cdr org-time-stamp-formats))
  602. (cond
  603. ((memq key '(day today))
  604. (setq txt (format-time-string "%A, %B %d, %Y" ts)))
  605. ((memq key '(week thisweek))
  606. (setq txt (format-time-string "week %G-W%V" ts)))
  607. ((memq key '(month thismonth))
  608. (setq txt (format-time-string "%B %Y" ts)))
  609. ((memq key '(year thisyear))
  610. (setq txt (format-time-string "the year %Y" ts))))
  611. (if as-strings
  612. (list (format-time-string fm ts) (format-time-string fm te) txt)
  613. (list ts te txt))))
  614. (defun org-clocktable-shift (dir n)
  615. "Try to shift the :block date of the clocktable at point.
  616. Point must be in the #+BEGIN: line of a clocktable, or this function
  617. will throw an error.
  618. DIR is a direction, a symbol `left', `right', `up', or `down'.
  619. Both `left' and `down' shift the block toward the past, `up' and `right'
  620. push it toward the future.
  621. N is the number of shift steps to take. The size of the step depends on
  622. the currently selected interval size."
  623. (setq n (prefix-numeric-value n))
  624. (and (memq dir '(left down)) (setq n (- n)))
  625. (save-excursion
  626. (goto-char (point-at-bol))
  627. (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
  628. (error "Line needs a :block definition before this command works")
  629. (let* ((b (match-beginning 1)) (e (match-end 1))
  630. (s (match-string 1))
  631. block shift ins y mw d date wp m)
  632. (cond
  633. ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
  634. (setq block (match-string 1 s)
  635. shift (if (match-end 2)
  636. (string-to-number (match-string 2 s))
  637. 0))
  638. (setq shift (+ shift n))
  639. (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
  640. ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
  641. ;; 1 1 2 3 3 4 4 5 6 6 5 2
  642. (setq y (string-to-number (match-string 1 s))
  643. wp (and (match-end 3) (match-string 3 s))
  644. mw (and (match-end 4) (string-to-number (match-string 4 s)))
  645. d (and (match-end 6) (string-to-number (match-string 6 s))))
  646. (cond
  647. (d (setq ins (format-time-string
  648. "%Y-%m-%d"
  649. (encode-time 0 0 0 (+ d n) m y))))
  650. ((and wp mw (> (length wp) 0))
  651. (require 'cal-iso)
  652. (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
  653. (setq ins (format-time-string
  654. "%G-W%V"
  655. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  656. (mw
  657. (setq ins (format-time-string
  658. "%Y-%m"
  659. (encode-time 0 0 0 1 (+ mw n) y))))
  660. (y
  661. (setq ins (number-to-string (+ y n))))))
  662. (t (error "Cannot shift clocktable block")))
  663. (when ins
  664. (goto-char b)
  665. (insert ins)
  666. (delete-region (point) (+ (point) (- e b)))
  667. (beginning-of-line 1)
  668. (org-update-dblock)
  669. t)))))
  670. (defun org-dblock-write:clocktable (params)
  671. "Write the standard clocktable."
  672. (catch 'exit
  673. (let* ((hlchars '((1 . "*") (2 . "/")))
  674. (ins (make-marker))
  675. (total-time nil)
  676. (scope (plist-get params :scope))
  677. (tostring (plist-get params :tostring))
  678. (multifile (plist-get params :multifile))
  679. (header (plist-get params :header))
  680. (maxlevel (or (plist-get params :maxlevel) 3))
  681. (step (plist-get params :step))
  682. (emph (plist-get params :emphasize))
  683. (ts (plist-get params :tstart))
  684. (te (plist-get params :tend))
  685. (block (plist-get params :block))
  686. (link (plist-get params :link))
  687. ipos time p level hlc hdl
  688. cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list)
  689. (setq org-clock-file-total-minutes nil)
  690. (when step
  691. (unless (or block (and ts te))
  692. (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
  693. (org-clocktable-steps params)
  694. (throw 'exit nil))
  695. (when block
  696. (setq cc (org-clock-special-range block nil t)
  697. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  698. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  699. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  700. (when (and ts (listp ts))
  701. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  702. (when (and te (listp te))
  703. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  704. ;; Now the times are strings we can parse.
  705. (if ts (setq ts (time-to-seconds
  706. (apply 'encode-time (org-parse-time-string ts)))))
  707. (if te (setq te (time-to-seconds
  708. (apply 'encode-time (org-parse-time-string te)))))
  709. (move-marker ins (point))
  710. (setq ipos (point))
  711. ;; Get the right scope
  712. (setq pos (point))
  713. (cond
  714. ((and scope (listp scope) (symbolp (car scope)))
  715. (setq scope (eval scope)))
  716. ((eq scope 'agenda)
  717. (setq scope (org-agenda-files t)))
  718. ((eq scope 'agenda-with-archives)
  719. (setq scope (org-agenda-files t))
  720. (setq scope (org-add-archive-files scope)))
  721. ((eq scope 'file-with-archives)
  722. (setq scope (org-add-archive-files (list (buffer-file-name)))
  723. rm-file-column t)))
  724. (setq scope-is-list (and scope (listp scope)))
  725. (save-restriction
  726. (cond
  727. ((not scope))
  728. ((eq scope 'file) (widen))
  729. ((eq scope 'subtree) (org-narrow-to-subtree))
  730. ((eq scope 'tree)
  731. (while (org-up-heading-safe))
  732. (org-narrow-to-subtree))
  733. ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
  734. (symbol-name scope)))
  735. (setq level (string-to-number (match-string 1 (symbol-name scope))))
  736. (catch 'exit
  737. (while (org-up-heading-safe)
  738. (looking-at outline-regexp)
  739. (if (<= (org-reduced-level (funcall outline-level)) level)
  740. (throw 'exit nil))))
  741. (org-narrow-to-subtree))
  742. (scope-is-list
  743. (let* ((files scope)
  744. (scope 'agenda)
  745. (p1 (copy-sequence params))
  746. file)
  747. (setq p1 (plist-put p1 :tostring t))
  748. (setq p1 (plist-put p1 :multifile t))
  749. (setq p1 (plist-put p1 :scope 'file))
  750. (org-prepare-agenda-buffers files)
  751. (while (setq file (pop files))
  752. (with-current-buffer (find-buffer-visiting file)
  753. (setq tbl1 (org-dblock-write:clocktable p1))
  754. (when tbl1
  755. (push (org-clocktable-add-file
  756. file
  757. (concat "| |*File time*|*"
  758. (org-minutes-to-hh:mm-string
  759. org-clock-file-total-minutes)
  760. "*|\n"
  761. tbl1)) tbl)
  762. (setq total-time (+ (or total-time 0)
  763. org-clock-file-total-minutes))))))))
  764. (goto-char pos)
  765. (unless scope-is-list
  766. (org-clock-sum ts te)
  767. (goto-char (point-min))
  768. (while (setq p (next-single-property-change (point) :org-clock-minutes))
  769. (goto-char p)
  770. (when (setq time (get-text-property p :org-clock-minutes))
  771. (save-excursion
  772. (beginning-of-line 1)
  773. (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
  774. (setq level (org-reduced-level
  775. (- (match-end 1) (match-beginning 1))))
  776. (<= level maxlevel))
  777. (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
  778. hdl (if (not link)
  779. (match-string 2)
  780. (org-make-link-string
  781. (format "file:%s::%s"
  782. (buffer-file-name)
  783. (save-match-data
  784. (org-make-org-heading-search-string
  785. (match-string 2))))
  786. (match-string 2))))
  787. (if (and (not multifile) (= level 1)) (push "|-" tbl))
  788. (push (concat
  789. "| " (int-to-string level) "|" hlc hdl hlc " |"
  790. (make-string (1- level) ?|)
  791. hlc (org-minutes-to-hh:mm-string time) hlc
  792. " |") tbl))))))
  793. (setq tbl (nreverse tbl))
  794. (if tostring
  795. (if tbl (mapconcat 'identity tbl "\n") nil)
  796. (goto-char ins)
  797. (insert-before-markers
  798. (or header
  799. (concat
  800. "Clock summary at ["
  801. (substring
  802. (format-time-string (cdr org-time-stamp-formats))
  803. 1 -1)
  804. "]"
  805. (if block (concat ", for " range-text ".") "")
  806. "\n\n"))
  807. (if scope-is-list "|File" "")
  808. "|L|Headline|Time|\n")
  809. (setq total-time (or total-time org-clock-file-total-minutes))
  810. (insert-before-markers
  811. "|-\n|"
  812. (if scope-is-list "|" "")
  813. "|"
  814. "*Total time*| *"
  815. (org-minutes-to-hh:mm-string (or total-time 0))
  816. "*|\n|-\n")
  817. (setq tbl (delq nil tbl))
  818. (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
  819. (equal (substring (car tbl) 0 2) "|-"))
  820. (pop tbl))
  821. (insert-before-markers (mapconcat
  822. 'identity (delq nil tbl)
  823. (if scope-is-list "\n|-\n" "\n")))
  824. (backward-delete-char 1)
  825. (goto-char ipos)
  826. (skip-chars-forward "^|")
  827. (org-table-align)
  828. (when rm-file-column
  829. (forward-char 1)
  830. (org-table-delete-column)))))))
  831. (defun org-clocktable-steps (params)
  832. (let* ((p1 (copy-sequence params))
  833. (ts (plist-get p1 :tstart))
  834. (te (plist-get p1 :tend))
  835. (step0 (plist-get p1 :step))
  836. (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
  837. (block (plist-get p1 :block))
  838. cc range-text)
  839. (when block
  840. (setq cc (org-clock-special-range block nil t)
  841. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  842. (if ts (setq ts (time-to-seconds
  843. (apply 'encode-time (org-parse-time-string ts)))))
  844. (if te (setq te (time-to-seconds
  845. (apply 'encode-time (org-parse-time-string te)))))
  846. (setq p1 (plist-put p1 :header ""))
  847. (setq p1 (plist-put p1 :step nil))
  848. (setq p1 (plist-put p1 :block nil))
  849. (while (< ts te)
  850. (or (bolp) (insert "\n"))
  851. (setq p1 (plist-put p1 :tstart (format-time-string
  852. (car org-time-stamp-formats)
  853. (seconds-to-time ts))))
  854. (setq p1 (plist-put p1 :tend (format-time-string
  855. (car org-time-stamp-formats)
  856. (seconds-to-time (setq ts (+ ts step))))))
  857. (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
  858. (plist-get p1 :tstart) "\n")
  859. (org-dblock-write:clocktable p1)
  860. (re-search-forward "#\\+END:")
  861. (end-of-line 0))))
  862. (defun org-clocktable-add-file (file table)
  863. (if table
  864. (let ((lines (org-split-string table "\n"))
  865. (ff (file-name-nondirectory file)))
  866. (mapconcat 'identity
  867. (mapcar (lambda (x)
  868. (if (string-match org-table-dataline-regexp x)
  869. (concat "|" ff x)
  870. x))
  871. lines)
  872. "\n"))))
  873. (provide 'org-clock)
  874. ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
  875. ;;; org-clock.el ends here