org-clock.el 36 KB

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