org-clock.el 33 KB

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