org-clock.el 33 KB

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