org-clock.el 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. ;;; org-clock.el --- The time clocking code for Org-mode
  2. ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
  3. ;; Free Software Foundation, Inc.
  4. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  5. ;; Keywords: outlines, hypermedia, calendar, wp
  6. ;; Homepage: http://orgmode.org
  7. ;; Version: 6.26
  8. ;;
  9. ;; This file is part of GNU Emacs.
  10. ;;
  11. ;; GNU Emacs is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation, either version 3 of the License, or
  14. ;; (at your option) any later version.
  15. ;; GNU Emacs is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  21. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  22. ;;
  23. ;;; Commentary:
  24. ;; This file contains the time clocking code for Org-mode
  25. (require 'org)
  26. (eval-when-compile
  27. (require 'cl)
  28. (require 'calendar))
  29. (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
  30. (defvar org-time-stamp-formats)
  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 org-log-into-drawer
  36. "Should clocking info be wrapped into a drawer?
  37. When t, clocking info will always be inserted into a :LOGBOOK: 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. When a string, it names the drawer to be used.
  43. The default for this variable is the value of `org-log-into-drawer',
  44. which see."
  45. :group 'org-todo
  46. :group 'org-clock
  47. :type '(choice
  48. (const :tag "Always" t)
  49. (const :tag "Only when drawer exists" nil)
  50. (integer :tag "When at least N clock entries")
  51. (const :tag "Into LOGBOOK drawer" "LOGBOOK")
  52. (string :tag "Into Drawer named...")))
  53. (defcustom org-clock-out-when-done t
  54. "When non-nil, clock will be stopped when the clocked entry is marked DONE.
  55. A nil value means, clock will keep running until stopped explicitly with
  56. `C-c C-x C-o', or until the clock is started in a different item."
  57. :group 'org-clock
  58. :type 'boolean)
  59. (defcustom org-clock-out-remove-zero-time-clocks nil
  60. "Non-nil means, remove the clock line when the resulting time is zero."
  61. :group 'org-clock
  62. :type 'boolean)
  63. (defcustom org-clock-in-switch-to-state nil
  64. "Set task to a special todo state while clocking it.
  65. The value should be the state to which the entry should be
  66. switched. If the value is a function, it must take one
  67. parameter (the current TODO state of the item) and return the
  68. state to switch it to."
  69. :group 'org-clock
  70. :group 'org-todo
  71. :type '(choice
  72. (const :tag "Don't force a state" nil)
  73. (string :tag "State")
  74. (symbol :tag "Function")))
  75. (defcustom org-clock-history-length 5
  76. "Number of clock tasks to remember in history."
  77. :group 'org-clock
  78. :type 'integer)
  79. (defcustom org-clock-heading-function nil
  80. "When non-nil, should be a function to create `org-clock-heading'.
  81. This is the string shown in the mode line when a clock is running.
  82. The function is called with point at the beginning of the headline."
  83. :group 'org-clock
  84. :type 'function)
  85. (defcustom org-clock-string-limit 0
  86. "Maximum length of clock strings in the modeline. 0 means no limit."
  87. :group 'org-clock
  88. :type 'integer)
  89. (defcustom org-clock-in-resume nil
  90. "If non-nil, resume clock when clocking into task with open clock.
  91. When clocking into a task with a clock entry which has not been closed,
  92. the clock can be resumed from that point."
  93. :group 'org-clock
  94. :type 'boolean)
  95. (defcustom org-clock-persist nil
  96. "When non-nil, save the running clock when emacs is closed.
  97. The clock is resumed when emacs restarts.
  98. When this is t, both the running clock, and the entire clock
  99. history are saved. When this is the symbol `clock', only the
  100. running clock is saved.
  101. When Emacs restarts with saved clock information, the file containing the
  102. running clock as well as all files mentioned in the clock history will
  103. be visited.
  104. All this depends on running `org-clock-persistence-insinuate' in .emacs"
  105. :group 'org-clock
  106. :type '(choice
  107. (const :tag "Just the running clock" clock)
  108. (const :tag "Clock and history" t)
  109. (const :tag "No persistence" nil)))
  110. (defcustom org-clock-persist-file (convert-standard-filename
  111. "~/.emacs.d/org-clock-save.el")
  112. "File to save clock data to."
  113. :group 'org-clock
  114. :type 'string)
  115. (defcustom org-clock-persist-query-save nil
  116. "When non-nil, ask before saving the current clock on exit."
  117. :group 'org-clock
  118. :type 'boolean)
  119. (defcustom org-clock-persist-query-resume t
  120. "When non-nil, ask before resuming any stored clock during load."
  121. :group 'org-clock
  122. :type 'boolean)
  123. ;;; The clock for measuring work time.
  124. (defvar org-mode-line-string "")
  125. (put 'org-mode-line-string 'risky-local-variable t)
  126. (defvar org-clock-mode-line-timer nil)
  127. (defvar org-clock-heading "")
  128. (defvar org-clock-heading-for-remember "")
  129. (defvar org-clock-start-time "")
  130. (defvar org-clock-history nil
  131. "List of marker pointing to recent clocked tasks.")
  132. (defvar org-clock-default-task (make-marker)
  133. "Marker pointing to the default task that should clock time.
  134. The clock can be made to switch to this task after clocking out
  135. of a different task.")
  136. (defvar org-clock-interrupted-task (make-marker)
  137. "Marker pointing to the task that has been interrupted by the current clock.")
  138. (defvar org-clock-mode-line-map (make-sparse-keymap))
  139. (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
  140. (defun org-clock-history-push (&optional pos buffer)
  141. "Push a marker to the clock history."
  142. (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
  143. (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
  144. (while (setq n (member m org-clock-history))
  145. (move-marker (car n) nil))
  146. (setq org-clock-history
  147. (delq nil
  148. (mapcar (lambda (x) (if (marker-buffer x) x nil))
  149. org-clock-history)))
  150. (when (>= (setq l (length org-clock-history)) org-clock-history-length)
  151. (setq org-clock-history
  152. (nreverse
  153. (nthcdr (- l org-clock-history-length -1)
  154. (nreverse org-clock-history)))))
  155. (push m org-clock-history)))
  156. (defun org-clock-save-markers-for-cut-and-paste (beg end)
  157. "Save relative positions of markers in region."
  158. (org-check-and-save-marker org-clock-marker beg end)
  159. (org-check-and-save-marker org-clock-default-task beg end)
  160. (org-check-and-save-marker org-clock-interrupted-task beg end)
  161. (mapc (lambda (m) (org-check-and-save-marker m beg end))
  162. org-clock-history))
  163. (defun org-clock-select-task (&optional prompt)
  164. "Select a task that recently was associated with clocking."
  165. (interactive)
  166. (let (sel-list rpl (i 0) s)
  167. (save-window-excursion
  168. (org-switch-to-buffer-other-window
  169. (get-buffer-create "*Clock Task Select*"))
  170. (erase-buffer)
  171. (when (marker-buffer org-clock-default-task)
  172. (insert (org-add-props "Default Task\n" nil 'face 'bold))
  173. (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
  174. (push s sel-list))
  175. (when (marker-buffer org-clock-interrupted-task)
  176. (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
  177. (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
  178. (push s sel-list))
  179. (when (marker-buffer org-clock-marker)
  180. (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
  181. (setq s (org-clock-insert-selection-line ?c org-clock-marker))
  182. (push s sel-list))
  183. (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
  184. (mapc
  185. (lambda (m)
  186. (when (marker-buffer m)
  187. (setq i (1+ i)
  188. s (org-clock-insert-selection-line
  189. (if (< i 10)
  190. (+ i ?0)
  191. (+ i (- ?A 10))) m))
  192. (push s sel-list)))
  193. org-clock-history)
  194. (org-fit-window-to-buffer)
  195. (message (or prompt "Select task for clocking:"))
  196. (setq rpl (read-char-exclusive))
  197. (cond
  198. ((eq rpl ?q) nil)
  199. ((eq rpl ?x) nil)
  200. ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
  201. (t (error "Invalid task choice %c" rpl))))))
  202. (defun org-clock-insert-selection-line (i marker)
  203. (when (marker-buffer marker)
  204. (let (file cat task)
  205. (with-current-buffer (org-base-buffer (marker-buffer marker))
  206. (save-excursion
  207. (save-restriction
  208. (widen)
  209. (goto-char marker)
  210. (setq file (buffer-file-name (marker-buffer marker))
  211. cat (or (org-get-category)
  212. (progn (org-refresh-category-properties)
  213. (org-get-category)))
  214. task (org-get-heading 'notags)))))
  215. (when (and cat task)
  216. (insert (format "[%c] %-15s %s\n" i cat task))
  217. (cons i marker)))))
  218. (defun org-clock-update-mode-line ()
  219. (let* ((delta (- (time-to-seconds (current-time))
  220. (time-to-seconds org-clock-start-time)))
  221. (h (floor delta 3600))
  222. (m (floor (- delta (* 3600 h)) 60)))
  223. (setq org-mode-line-string
  224. (org-propertize
  225. (let ((clock-string (format (concat "-[" org-time-clocksum-format " (%s)]")
  226. h m org-clock-heading))
  227. (help-text "Org-mode clock is running. Mouse-2 to go there."))
  228. (if (and (> org-clock-string-limit 0)
  229. (> (length clock-string) org-clock-string-limit))
  230. (org-propertize (substring clock-string 0 org-clock-string-limit)
  231. 'help-echo (concat help-text ": " org-clock-heading))
  232. (org-propertize clock-string 'help-echo help-text)))
  233. 'local-map org-clock-mode-line-map
  234. 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)))
  235. (force-mode-line-update)))
  236. (defvar org-clock-mode-line-entry nil
  237. "Information for the modeline about the running clock.")
  238. (defun org-clock-in (&optional select)
  239. "Start the clock on the current item.
  240. If necessary, clock-out of the currently active clock.
  241. With prefix arg SELECT, offer a list of recently clocked tasks to
  242. clock into. When SELECT is `C-u C-u', clock into the current task and mark
  243. is as the default task, a special task that will always be offered in
  244. the clocking selection, associated with the letter `d'."
  245. (interactive "P")
  246. (catch 'abort
  247. (let ((interrupting (marker-buffer org-clock-marker))
  248. ts selected-task target-pos)
  249. (when (equal select '(4))
  250. (setq selected-task (org-clock-select-task "Clock-in on task: "))
  251. (if selected-task
  252. (setq selected-task (copy-marker selected-task))
  253. (error "Abort")))
  254. (when interrupting
  255. ;; We are interrupting the clocking of a different task.
  256. ;; Save a marker to this task, so that we can go back.
  257. (move-marker org-clock-interrupted-task
  258. (marker-position org-clock-marker)
  259. (marker-buffer org-clock-marker))
  260. (org-clock-out t))
  261. (when (equal select '(16))
  262. ;; Mark as default clocking task
  263. (save-excursion
  264. (org-back-to-heading t)
  265. (move-marker org-clock-default-task (point))))
  266. (setq target-pos (point)) ;; we want to clock in at this location
  267. (save-excursion
  268. (when (and selected-task (marker-buffer selected-task))
  269. ;; There is a selected task, move to the correct buffer
  270. ;; and set the new target position.
  271. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  272. (setq target-pos (marker-position selected-task))
  273. (move-marker selected-task nil))
  274. (save-excursion
  275. (save-restriction
  276. (widen)
  277. (goto-char target-pos)
  278. (org-back-to-heading t)
  279. (or interrupting (move-marker org-clock-interrupted-task nil))
  280. (org-clock-history-push)
  281. (cond ((functionp org-clock-in-switch-to-state)
  282. (looking-at org-complex-heading-regexp)
  283. (let ((newstate (funcall org-clock-in-switch-to-state
  284. (match-string 2))))
  285. (if newstate (org-todo newstate))))
  286. ((and org-clock-in-switch-to-state
  287. (not (looking-at (concat outline-regexp "[ \t]*"
  288. org-clock-in-switch-to-state
  289. "\\>"))))
  290. (org-todo org-clock-in-switch-to-state)))
  291. (setq org-clock-heading-for-remember
  292. (and (looking-at org-complex-heading-regexp)
  293. (match-end 4)
  294. (org-trim (buffer-substring (match-end 1)
  295. (match-end 4)))))
  296. (setq org-clock-heading
  297. (cond ((and org-clock-heading-function
  298. (functionp org-clock-heading-function))
  299. (funcall org-clock-heading-function))
  300. ((looking-at org-complex-heading-regexp)
  301. (match-string 4))
  302. (t "???")))
  303. (setq org-clock-heading (org-propertize org-clock-heading
  304. 'face nil))
  305. (org-clock-find-position org-clock-in-resume)
  306. (cond
  307. ((and org-clock-in-resume
  308. (looking-at
  309. (concat "^[ \t]* " org-clock-string
  310. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  311. " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  312. (message "Matched %s" (match-string 1))
  313. (setq ts (concat "[" (match-string 1) "]"))
  314. (goto-char (match-end 1))
  315. (setq org-clock-start-time
  316. (apply 'encode-time
  317. (org-parse-time-string (match-string 1)))))
  318. ((eq org-clock-in-resume 'auto-restart)
  319. ;; called from org-clock-load during startup,
  320. ;; do not interrupt, but warn!
  321. (message "Cannot restart clock because task does not contain unfinished clock")
  322. (ding)
  323. (sit-for 2)
  324. (throw 'abort nil))
  325. (t
  326. (insert-before-markers "\n")
  327. (backward-char 1)
  328. (org-indent-line-function)
  329. (when (and (save-excursion
  330. (end-of-line 0)
  331. (org-in-item-p)))
  332. (beginning-of-line 1)
  333. (org-indent-line-to (- (org-get-indentation) 2)))
  334. (insert org-clock-string " ")
  335. (setq org-clock-start-time (current-time))
  336. (setq ts (org-insert-time-stamp org-clock-start-time 'with-hm 'inactive))))
  337. (move-marker org-clock-marker (point) (buffer-base-buffer))
  338. (or global-mode-string (setq global-mode-string '("")))
  339. (or (memq 'org-mode-line-string global-mode-string)
  340. (setq global-mode-string
  341. (append global-mode-string '(org-mode-line-string))))
  342. (org-clock-update-mode-line)
  343. (setq org-clock-mode-line-timer
  344. (run-with-timer 60 60 'org-clock-update-mode-line))
  345. (message "Clock started at %s" ts)))))
  346. (org-clock-goto nil)))
  347. (defun org-clock-find-position (find-unclosed)
  348. "Find the location where the next clock line should be inserted.
  349. When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
  350. line and position cursor in that line."
  351. (org-back-to-heading t)
  352. (catch 'exit
  353. (let ((beg (save-excursion
  354. (beginning-of-line 2)
  355. (or (bolp) (newline))
  356. (point)))
  357. (end (progn (outline-next-heading) (point)))
  358. (re (concat "^[ \t]*" org-clock-string))
  359. (cnt 0)
  360. (drawer (if (stringp org-clock-into-drawer)
  361. org-clock-into-drawer "LOGBOOK"))
  362. first last ind-last)
  363. (goto-char beg)
  364. (when (and find-unclosed
  365. (re-search-forward
  366. (concat "^[ \t]* " org-clock-string
  367. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  368. " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
  369. end t))
  370. (beginning-of-line 1)
  371. (throw 'exit t))
  372. (when (eobp) (newline) (setq end (max (point) end)))
  373. (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
  374. ;; we seem to have a CLOCK drawer, so go there.
  375. (beginning-of-line 2)
  376. (or org-log-states-order-reversed
  377. (and (re-search-forward org-property-end-re nil t)
  378. (goto-char (match-beginning 0))))
  379. (throw 'exit t))
  380. ;; Lets count the CLOCK lines
  381. (goto-char beg)
  382. (while (re-search-forward re end t)
  383. (setq first (or first (match-beginning 0))
  384. last (match-beginning 0)
  385. cnt (1+ cnt)))
  386. (when (and (integerp org-clock-into-drawer)
  387. last
  388. (>= (1+ cnt) org-clock-into-drawer))
  389. ;; Wrap current entries into a new drawer
  390. (goto-char last)
  391. (setq ind-last (org-get-indentation))
  392. (beginning-of-line 2)
  393. (if (and (>= (org-get-indentation) ind-last)
  394. (org-at-item-p))
  395. (org-end-of-item))
  396. (insert ":END:\n")
  397. (beginning-of-line 0)
  398. (org-indent-line-to ind-last)
  399. (goto-char first)
  400. (insert ":" drawer ":\n")
  401. (beginning-of-line 0)
  402. (org-indent-line-function)
  403. (org-flag-drawer t)
  404. (beginning-of-line 2)
  405. (or org-log-states-order-reversed
  406. (and (re-search-forward org-property-end-re nil t)
  407. (goto-char (match-beginning 0))))
  408. (throw 'exit nil))
  409. (goto-char beg)
  410. (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  411. (not (equal (match-string 1) org-clock-string)))
  412. ;; Planning info, skip to after it
  413. (beginning-of-line 2)
  414. (or (bolp) (newline)))
  415. (when (or (eq org-clock-into-drawer t)
  416. (stringp org-clock-into-drawer)
  417. (and (integerp org-clock-into-drawer)
  418. (< org-clock-into-drawer 2)))
  419. (insert ":" drawer ":\n:END:\n")
  420. (beginning-of-line -1)
  421. (org-indent-line-function)
  422. (org-flag-drawer t)
  423. (beginning-of-line 2)
  424. (org-indent-line-function)
  425. (beginning-of-line)
  426. (or org-log-states-order-reversed
  427. (and (re-search-forward org-property-end-re nil t)
  428. (goto-char (match-beginning 0))))))))
  429. (defun org-clock-out (&optional fail-quietly)
  430. "Stop the currently running clock.
  431. If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
  432. (interactive)
  433. (catch 'exit
  434. (if (not (marker-buffer org-clock-marker))
  435. (if fail-quietly (throw 'exit t) (error "No active clock")))
  436. (let (ts te s h m remove)
  437. (save-excursion
  438. (set-buffer (marker-buffer org-clock-marker))
  439. (save-restriction
  440. (widen)
  441. (goto-char org-clock-marker)
  442. (beginning-of-line 1)
  443. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  444. (equal (match-string 1) org-clock-string))
  445. (setq ts (match-string 2))
  446. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  447. (goto-char (match-end 0))
  448. (delete-region (point) (point-at-eol))
  449. (insert "--")
  450. (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
  451. (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
  452. (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
  453. h (floor (/ s 3600))
  454. s (- s (* 3600 h))
  455. m (floor (/ s 60))
  456. s (- s (* 60 s)))
  457. (insert " => " (format "%2d:%02d" h m))
  458. (when (setq remove (and org-clock-out-remove-zero-time-clocks
  459. (= (+ h m) 0)))
  460. (beginning-of-line 1)
  461. (delete-region (point) (point-at-eol))
  462. (and (looking-at "\n") (> (point-max) (1+ (point)))
  463. (delete-char 1)))
  464. (move-marker org-clock-marker nil)
  465. (when org-log-note-clock-out
  466. (org-add-log-setup 'clock-out nil nil nil nil
  467. (concat "# Task: " (org-get-heading t) "\n\n")))
  468. (when org-clock-mode-line-timer
  469. (cancel-timer org-clock-mode-line-timer)
  470. (setq org-clock-mode-line-timer nil))
  471. (setq global-mode-string
  472. (delq 'org-mode-line-string global-mode-string))
  473. (force-mode-line-update)
  474. (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
  475. (if remove " => LINE REMOVED" "")))))))
  476. (defun org-clock-cancel ()
  477. "Cancel the running clock be removing the start timestamp."
  478. (interactive)
  479. (if (not (marker-buffer org-clock-marker))
  480. (error "No active clock"))
  481. (save-excursion
  482. (set-buffer (marker-buffer org-clock-marker))
  483. (goto-char org-clock-marker)
  484. (delete-region (1- (point-at-bol)) (point-at-eol)))
  485. (setq global-mode-string
  486. (delq 'org-mode-line-string global-mode-string))
  487. (force-mode-line-update)
  488. (message "Clock canceled"))
  489. (defun org-clock-goto (&optional select)
  490. "Go to the currently clocked-in entry.
  491. With prefix arg SELECT, offer recently clocked tasks."
  492. (interactive "P")
  493. (let ((m (if select
  494. (org-clock-select-task "Select task to go to: ")
  495. org-clock-marker)))
  496. (if (not (marker-buffer m))
  497. (if select
  498. (error "No task selected")
  499. (error "No active clock")))
  500. (switch-to-buffer (marker-buffer m))
  501. (if (or (< m (point-min)) (> m (point-max))) (widen))
  502. (goto-char m)
  503. (org-show-entry)
  504. (org-back-to-heading)
  505. (org-cycle-hide-drawers 'children)
  506. (recenter)))
  507. (defvar org-clock-file-total-minutes nil
  508. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  509. (make-variable-buffer-local 'org-clock-file-total-minutes)
  510. (defun org-clock-sum (&optional tstart tend)
  511. "Sum the times for each subtree.
  512. Puts the resulting times in minutes as a text property on each headline."
  513. (interactive)
  514. (let* ((bmp (buffer-modified-p))
  515. (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  516. org-clock-string
  517. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  518. (lmax 30)
  519. (ltimes (make-vector lmax 0))
  520. (t1 0)
  521. (level 0)
  522. ts te dt
  523. time)
  524. (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
  525. (save-excursion
  526. (goto-char (point-max))
  527. (while (re-search-backward re nil t)
  528. (cond
  529. ((match-end 2)
  530. ;; Two time stamps
  531. (setq ts (match-string 2)
  532. te (match-string 3)
  533. ts (time-to-seconds
  534. (apply 'encode-time (org-parse-time-string ts)))
  535. te (time-to-seconds
  536. (apply 'encode-time (org-parse-time-string te)))
  537. ts (if tstart (max ts tstart) ts)
  538. te (if tend (min te tend) te)
  539. dt (- te ts)
  540. t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
  541. ((match-end 4)
  542. ;; A naked time
  543. (setq t1 (+ t1 (string-to-number (match-string 5))
  544. (* 60 (string-to-number (match-string 4))))))
  545. (t ;; A headline
  546. (setq level (- (match-end 1) (match-beginning 1)))
  547. (when (or (> t1 0) (> (aref ltimes level) 0))
  548. (loop for l from 0 to level do
  549. (aset ltimes l (+ (aref ltimes l) t1)))
  550. (setq t1 0 time (aref ltimes level))
  551. (loop for l from level to (1- lmax) do
  552. (aset ltimes l 0))
  553. (goto-char (match-beginning 0))
  554. (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
  555. (setq org-clock-file-total-minutes (aref ltimes 0)))
  556. (set-buffer-modified-p bmp)))
  557. (defun org-clock-display (&optional total-only)
  558. "Show subtree times in the entire buffer.
  559. If TOTAL-ONLY is non-nil, only show the total time for the entire file
  560. in the echo area."
  561. (interactive)
  562. (org-clock-remove-overlays)
  563. (let (time h m p)
  564. (org-clock-sum)
  565. (unless total-only
  566. (save-excursion
  567. (goto-char (point-min))
  568. (while (or (and (equal (setq p (point)) (point-min))
  569. (get-text-property p :org-clock-minutes))
  570. (setq p (next-single-property-change
  571. (point) :org-clock-minutes)))
  572. (goto-char p)
  573. (when (setq time (get-text-property p :org-clock-minutes))
  574. (org-clock-put-overlay time (funcall outline-level))))
  575. (setq h (/ org-clock-file-total-minutes 60)
  576. m (- org-clock-file-total-minutes (* 60 h)))
  577. ;; Arrange to remove the overlays upon next change.
  578. (when org-remove-highlights-with-change
  579. (org-add-hook 'before-change-functions 'org-clock-remove-overlays
  580. nil 'local))))
  581. (message (concat "Total file time: " org-time-clocksum-format " (%d hours and %d minutes)") h m h m)))
  582. (defvar org-clock-overlays nil)
  583. (make-variable-buffer-local 'org-clock-overlays)
  584. (defun org-clock-put-overlay (time &optional level)
  585. "Put an overlays on the current line, displaying TIME.
  586. If LEVEL is given, prefix time with a corresponding number of stars.
  587. This creates a new overlay and stores it in `org-clock-overlays', so that it
  588. will be easy to remove."
  589. (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
  590. (l (if level (org-get-valid-level level 0) 0))
  591. (fmt (concat "%s " org-time-clocksum-format "%s"))
  592. (off 0)
  593. ov tx)
  594. (org-move-to-column c)
  595. (unless (eolp) (skip-chars-backward "^ \t"))
  596. (skip-chars-backward " \t")
  597. (setq ov (org-make-overlay (1- (point)) (point-at-eol))
  598. tx (concat (buffer-substring (1- (point)) (point))
  599. (make-string (+ off (max 0 (- c (current-column)))) ?.)
  600. (org-add-props (format fmt
  601. (make-string l ?*) h m
  602. (make-string (- 16 l) ?\ ))
  603. (list 'face 'org-clock-overlay))
  604. ""))
  605. (if (not (featurep 'xemacs))
  606. (org-overlay-put ov 'display tx)
  607. (org-overlay-put ov 'invisible t)
  608. (org-overlay-put ov 'end-glyph (make-glyph tx)))
  609. (push ov org-clock-overlays)))
  610. (defun org-clock-remove-overlays (&optional beg end noremove)
  611. "Remove the occur highlights from the buffer.
  612. BEG and END are ignored. If NOREMOVE is nil, remove this function
  613. from the `before-change-functions' in the current buffer."
  614. (interactive)
  615. (unless org-inhibit-highlight-removal
  616. (mapc 'org-delete-overlay org-clock-overlays)
  617. (setq org-clock-overlays nil)
  618. (unless noremove
  619. (remove-hook 'before-change-functions
  620. 'org-clock-remove-overlays 'local))))
  621. (defvar state) ;; dynamically scoped into this function
  622. (defun org-clock-out-if-current ()
  623. "Clock out if the current entry contains the running clock.
  624. This is used to stop the clock after a TODO entry is marked DONE,
  625. and is only done if the variable `org-clock-out-when-done' is not nil."
  626. (when (and org-clock-out-when-done
  627. (member state org-done-keywords)
  628. (equal (or (buffer-base-buffer (marker-buffer org-clock-marker))
  629. (marker-buffer org-clock-marker))
  630. (or (buffer-base-buffer (current-buffer))
  631. (current-buffer)))
  632. (< (point) org-clock-marker)
  633. (> (save-excursion (outline-next-heading) (point))
  634. org-clock-marker))
  635. ;; Clock out, but don't accept a logging message for this.
  636. (let ((org-log-note-clock-out nil))
  637. (org-clock-out))))
  638. (add-hook 'org-after-todo-state-change-hook
  639. 'org-clock-out-if-current)
  640. ;;;###autoload
  641. (defun org-get-clocktable (&rest props)
  642. "Get a formatted clocktable with parameters according to PROPS.
  643. The table is created in a temporary buffer, fully formatted and
  644. fontified, and then returned."
  645. ;; Set the defaults
  646. (setq props (plist-put props :name "clocktable"))
  647. (unless (plist-member props :maxlevel)
  648. (setq props (plist-put props :maxlevel 2)))
  649. (unless (plist-member props :scope)
  650. (setq props (plist-put props :scope 'agenda)))
  651. (with-temp-buffer
  652. (org-mode)
  653. (org-create-dblock props)
  654. (org-update-dblock)
  655. (font-lock-fontify-buffer)
  656. (forward-line 2)
  657. (buffer-substring (point) (progn
  658. (re-search-forward "^#\\+END" nil t)
  659. (point-at-bol)))))
  660. (defun org-clock-report (&optional arg)
  661. "Create a table containing a report about clocked time.
  662. If the cursor is inside an existing clocktable block, then the table
  663. will be updated. If not, a new clocktable will be inserted.
  664. When called with a prefix argument, move to the first clock table in the
  665. buffer and update it."
  666. (interactive "P")
  667. (org-clock-remove-overlays)
  668. (when arg
  669. (org-find-dblock "clocktable")
  670. (org-show-entry))
  671. (if (org-in-clocktable-p)
  672. (goto-char (org-in-clocktable-p))
  673. (org-create-dblock (list :name "clocktable"
  674. :maxlevel 2 :scope 'file)))
  675. (org-update-dblock))
  676. (defun org-in-clocktable-p ()
  677. "Check if the cursor is in a clocktable."
  678. (let ((pos (point)) start)
  679. (save-excursion
  680. (end-of-line 1)
  681. (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
  682. (setq start (match-beginning 0))
  683. (re-search-forward "^#\\+END:.*" nil t)
  684. (>= (match-end 0) pos)
  685. start))))
  686. (defun org-clock-special-range (key &optional time as-strings)
  687. "Return two times bordering a special time range.
  688. Key is a symbol specifying the range and can be one of `today', `yesterday',
  689. `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
  690. A week starts Monday 0:00 and ends Sunday 24:00.
  691. The range is determined relative to TIME. TIME defaults to the current time.
  692. The return value is a cons cell with two internal times like the ones
  693. returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
  694. the returned times will be formatted strings."
  695. (if (integerp key) (setq key (intern (number-to-string key))))
  696. (let* ((tm (decode-time (or time (current-time))))
  697. (s 0) (m (nth 1 tm)) (h (nth 2 tm))
  698. (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
  699. (dow (nth 6 tm))
  700. (skey (symbol-name key))
  701. (shift 0)
  702. s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
  703. (cond
  704. ((string-match "^[0-9]+$" skey)
  705. (setq y (string-to-number skey) m 1 d 1 key 'year))
  706. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  707. (setq y (string-to-number (match-string 1 skey))
  708. month (string-to-number (match-string 2 skey))
  709. d 1 key 'month))
  710. ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
  711. (require 'cal-iso)
  712. (setq y (string-to-number (match-string 1 skey))
  713. w (string-to-number (match-string 2 skey)))
  714. (setq date (calendar-gregorian-from-absolute
  715. (calendar-absolute-from-iso (list w 1 y))))
  716. (setq d (nth 1 date) month (car date) y (nth 2 date)
  717. dow 1
  718. key 'week))
  719. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  720. (setq y (string-to-number (match-string 1 skey))
  721. month (string-to-number (match-string 2 skey))
  722. d (string-to-number (match-string 3 skey))
  723. key 'day))
  724. ((string-match "\\([-+][0-9]+\\)$" skey)
  725. (setq shift (string-to-number (match-string 1 skey))
  726. key (intern (substring skey 0 (match-beginning 1))))))
  727. (when (= shift 0)
  728. (cond ((eq key 'yesterday) (setq key 'today shift -1))
  729. ((eq key 'lastweek) (setq key 'week shift -1))
  730. ((eq key 'lastmonth) (setq key 'month shift -1))
  731. ((eq key 'lastyear) (setq key 'year shift -1))))
  732. (cond
  733. ((memq key '(day today))
  734. (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
  735. ((memq key '(week thisweek))
  736. (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
  737. m 0 h 0 d (- d diff) d1 (+ 7 d)))
  738. ((memq key '(month thismonth))
  739. (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
  740. ((memq key '(year thisyear))
  741. (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
  742. (t (error "No such time block %s" key)))
  743. (setq ts (encode-time s m h d month y)
  744. te (encode-time (or s1 s) (or m1 m) (or h1 h)
  745. (or d1 d) (or month1 month) (or y1 y)))
  746. (setq fm (cdr org-time-stamp-formats))
  747. (cond
  748. ((memq key '(day today))
  749. (setq txt (format-time-string "%A, %B %d, %Y" ts)))
  750. ((memq key '(week thisweek))
  751. (setq txt (format-time-string "week %G-W%V" ts)))
  752. ((memq key '(month thismonth))
  753. (setq txt (format-time-string "%B %Y" ts)))
  754. ((memq key '(year thisyear))
  755. (setq txt (format-time-string "the year %Y" ts))))
  756. (if as-strings
  757. (list (format-time-string fm ts) (format-time-string fm te) txt)
  758. (list ts te txt))))
  759. (defun org-clocktable-shift (dir n)
  760. "Try to shift the :block date of the clocktable at point.
  761. Point must be in the #+BEGIN: line of a clocktable, or this function
  762. will throw an error.
  763. DIR is a direction, a symbol `left', `right', `up', or `down'.
  764. Both `left' and `down' shift the block toward the past, `up' and `right'
  765. push it toward the future.
  766. N is the number of shift steps to take. The size of the step depends on
  767. the currently selected interval size."
  768. (setq n (prefix-numeric-value n))
  769. (and (memq dir '(left down)) (setq n (- n)))
  770. (save-excursion
  771. (goto-char (point-at-bol))
  772. (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
  773. (error "Line needs a :block definition before this command works")
  774. (let* ((b (match-beginning 1)) (e (match-end 1))
  775. (s (match-string 1))
  776. block shift ins y mw d date wp m)
  777. (cond
  778. ((equal s "yesterday") (setq s "today-1"))
  779. ((equal s "lastweek") (setq s "thisweek-1"))
  780. ((equal s "lastmonth") (setq s "thismonth-1"))
  781. ((equal s "lastyear") (setq s "thisyear-1")))
  782. (cond
  783. ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
  784. (setq block (match-string 1 s)
  785. shift (if (match-end 2)
  786. (string-to-number (match-string 2 s))
  787. 0))
  788. (setq shift (+ shift n))
  789. (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
  790. ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
  791. ;; 1 1 2 3 3 4 4 5 6 6 5 2
  792. (setq y (string-to-number (match-string 1 s))
  793. wp (and (match-end 3) (match-string 3 s))
  794. mw (and (match-end 4) (string-to-number (match-string 4 s)))
  795. d (and (match-end 6) (string-to-number (match-string 6 s))))
  796. (cond
  797. (d (setq ins (format-time-string
  798. "%Y-%m-%d"
  799. (encode-time 0 0 0 (+ d n) m y))))
  800. ((and wp mw (> (length wp) 0))
  801. (require 'cal-iso)
  802. (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
  803. (setq ins (format-time-string
  804. "%G-W%V"
  805. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  806. (mw
  807. (setq ins (format-time-string
  808. "%Y-%m"
  809. (encode-time 0 0 0 1 (+ mw n) y))))
  810. (y
  811. (setq ins (number-to-string (+ y n))))))
  812. (t (error "Cannot shift clocktable block")))
  813. (when ins
  814. (goto-char b)
  815. (insert ins)
  816. (delete-region (point) (+ (point) (- e b)))
  817. (beginning-of-line 1)
  818. (org-update-dblock)
  819. t)))))
  820. (defun org-dblock-write:clocktable (params)
  821. "Write the standard clocktable."
  822. (catch 'exit
  823. (let* ((hlchars '((1 . "*") (2 . "/")))
  824. (ins (make-marker))
  825. (total-time nil)
  826. (scope (plist-get params :scope))
  827. (tostring (plist-get params :tostring))
  828. (multifile (plist-get params :multifile))
  829. (header (plist-get params :header))
  830. (maxlevel (or (plist-get params :maxlevel) 3))
  831. (step (plist-get params :step))
  832. (emph (plist-get params :emphasize))
  833. (ts (plist-get params :tstart))
  834. (te (plist-get params :tend))
  835. (block (plist-get params :block))
  836. (link (plist-get params :link))
  837. ipos time p level hlc hdl content recalc formula pcol
  838. cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
  839. (setq org-clock-file-total-minutes nil)
  840. (when step
  841. (unless (or block (and ts te))
  842. (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
  843. (org-clocktable-steps params)
  844. (throw 'exit nil))
  845. (when block
  846. (setq cc (org-clock-special-range block nil t)
  847. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  848. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  849. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  850. (when (and ts (listp ts))
  851. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  852. (when (and te (listp te))
  853. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  854. ;; Now the times are strings we can parse.
  855. (if ts (setq ts (time-to-seconds
  856. (apply 'encode-time (org-parse-time-string ts)))))
  857. (if te (setq te (time-to-seconds
  858. (apply 'encode-time (org-parse-time-string te)))))
  859. (move-marker ins (point))
  860. (setq ipos (point))
  861. ;; Get the right scope
  862. (setq pos (point))
  863. (cond
  864. ((and scope (listp scope) (symbolp (car scope)))
  865. (setq scope (eval scope)))
  866. ((eq scope 'agenda)
  867. (setq scope (org-agenda-files t)))
  868. ((eq scope 'agenda-with-archives)
  869. (setq scope (org-agenda-files t))
  870. (setq scope (org-add-archive-files scope)))
  871. ((eq scope 'file-with-archives)
  872. (setq scope (org-add-archive-files (list (buffer-file-name)))
  873. rm-file-column t)))
  874. (setq scope-is-list (and scope (listp scope)))
  875. (save-restriction
  876. (cond
  877. ((not scope))
  878. ((eq scope 'file) (widen))
  879. ((eq scope 'subtree) (org-narrow-to-subtree))
  880. ((eq scope 'tree)
  881. (while (org-up-heading-safe))
  882. (org-narrow-to-subtree))
  883. ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
  884. (symbol-name scope)))
  885. (setq level (string-to-number (match-string 1 (symbol-name scope))))
  886. (catch 'exit
  887. (while (org-up-heading-safe)
  888. (looking-at outline-regexp)
  889. (if (<= (org-reduced-level (funcall outline-level)) level)
  890. (throw 'exit nil))))
  891. (org-narrow-to-subtree))
  892. (scope-is-list
  893. (let* ((files scope)
  894. (scope 'agenda)
  895. (p1 (copy-sequence params))
  896. file)
  897. (setq p1 (plist-put p1 :tostring t))
  898. (setq p1 (plist-put p1 :multifile t))
  899. (setq p1 (plist-put p1 :scope 'file))
  900. (org-prepare-agenda-buffers files)
  901. (while (setq file (pop files))
  902. (with-current-buffer (find-buffer-visiting file)
  903. (setq tbl1 (org-dblock-write:clocktable p1))
  904. (when tbl1
  905. (push (org-clocktable-add-file
  906. file
  907. (concat "| |*File time*|*"
  908. (org-minutes-to-hh:mm-string
  909. org-clock-file-total-minutes)
  910. "*|\n"
  911. tbl1)) tbl)
  912. (setq total-time (+ (or total-time 0)
  913. org-clock-file-total-minutes))))))))
  914. (goto-char pos)
  915. (unless scope-is-list
  916. (org-clock-sum ts te)
  917. (goto-char (point-min))
  918. (setq st t)
  919. (while (or (and (bobp) (prog1 st (setq st nil))
  920. (get-text-property (point) :org-clock-minutes)
  921. (setq p (point-min)))
  922. (setq p (next-single-property-change (point) :org-clock-minutes)))
  923. (goto-char p)
  924. (when (setq time (get-text-property p :org-clock-minutes))
  925. (save-excursion
  926. (beginning-of-line 1)
  927. (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
  928. (setq level (org-reduced-level
  929. (- (match-end 1) (match-beginning 1))))
  930. (<= level maxlevel))
  931. (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
  932. hdl (if (not link)
  933. (match-string 2)
  934. (org-make-link-string
  935. (format "file:%s::%s"
  936. (buffer-file-name)
  937. (save-match-data
  938. (org-make-org-heading-search-string
  939. (match-string 2))))
  940. (match-string 2))))
  941. (if (and (not multifile) (= level 1)) (push "|-" tbl))
  942. (push (concat
  943. "| " (int-to-string level) "|" hlc hdl hlc " |"
  944. (make-string (1- level) ?|)
  945. hlc (org-minutes-to-hh:mm-string time) hlc
  946. " |") tbl))))))
  947. (setq tbl (nreverse tbl))
  948. (if tostring
  949. (if tbl (mapconcat 'identity tbl "\n") nil)
  950. (goto-char ins)
  951. (insert-before-markers
  952. (or header
  953. (concat
  954. "Clock summary at ["
  955. (substring
  956. (format-time-string (cdr org-time-stamp-formats))
  957. 1 -1)
  958. "]"
  959. (if block (concat ", for " range-text ".") "")
  960. "\n\n"))
  961. (if scope-is-list "|File" "")
  962. "|L|Headline|Time|\n")
  963. (setq total-time (or total-time org-clock-file-total-minutes))
  964. (insert-before-markers
  965. "|-\n|"
  966. (if scope-is-list "|" "")
  967. "|"
  968. "*Total time*| *"
  969. (org-minutes-to-hh:mm-string (or total-time 0))
  970. "*|\n|-\n")
  971. (setq tbl (delq nil tbl))
  972. (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
  973. (equal (substring (car tbl) 0 2) "|-"))
  974. (pop tbl))
  975. (insert-before-markers (mapconcat
  976. 'identity (delq nil tbl)
  977. (if scope-is-list "\n|-\n" "\n")))
  978. (backward-delete-char 1)
  979. (if (setq formula (plist-get params :formula))
  980. (cond
  981. ((eq formula '%)
  982. (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
  983. (insert
  984. (format
  985. "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
  986. pcol
  987. 2
  988. (+ 3 (if scope-is-list 1 0))
  989. (+ (if scope-is-list 1 0) 3)
  990. (1- pcol)))
  991. (setq recalc t))
  992. ((stringp formula)
  993. (insert "\n#+TBLFM: " formula)
  994. (setq recalc t))
  995. (t (error "invalid formula in clocktable")))
  996. ;; Should we rescue an old formula?
  997. (when (stringp (setq content (plist-get params :content)))
  998. (when (string-match "^\\(#\\+TBLFM:.*\\)" content)
  999. (setq recalc t)
  1000. (insert "\n" (match-string 1 (plist-get params :content)))
  1001. (beginning-of-line 0))))
  1002. (goto-char ipos)
  1003. (skip-chars-forward "^|")
  1004. (org-table-align)
  1005. (when recalc
  1006. (if (eq formula '%)
  1007. (save-excursion (org-table-goto-column pcol nil 'force)
  1008. (insert "%")))
  1009. (org-table-recalculate 'all))
  1010. (when rm-file-column
  1011. (forward-char 1)
  1012. (org-table-delete-column)))))))
  1013. (defun org-clocktable-steps (params)
  1014. (let* ((p1 (copy-sequence params))
  1015. (ts (plist-get p1 :tstart))
  1016. (te (plist-get p1 :tend))
  1017. (step0 (plist-get p1 :step))
  1018. (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
  1019. (block (plist-get p1 :block))
  1020. cc range-text)
  1021. (when block
  1022. (setq cc (org-clock-special-range block nil t)
  1023. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  1024. (if ts (setq ts (time-to-seconds
  1025. (apply 'encode-time (org-parse-time-string ts)))))
  1026. (if te (setq te (time-to-seconds
  1027. (apply 'encode-time (org-parse-time-string te)))))
  1028. (setq p1 (plist-put p1 :header ""))
  1029. (setq p1 (plist-put p1 :step nil))
  1030. (setq p1 (plist-put p1 :block nil))
  1031. (while (< ts te)
  1032. (or (bolp) (insert "\n"))
  1033. (setq p1 (plist-put p1 :tstart (format-time-string
  1034. (org-time-stamp-format nil t)
  1035. (seconds-to-time ts))))
  1036. (setq p1 (plist-put p1 :tend (format-time-string
  1037. (org-time-stamp-format nil t)
  1038. (seconds-to-time (setq ts (+ ts step))))))
  1039. (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
  1040. (plist-get p1 :tstart) "\n")
  1041. (org-dblock-write:clocktable p1)
  1042. (re-search-forward "#\\+END:")
  1043. (end-of-line 0))))
  1044. (defun org-clocktable-add-file (file table)
  1045. (if table
  1046. (let ((lines (org-split-string table "\n"))
  1047. (ff (file-name-nondirectory file)))
  1048. (mapconcat 'identity
  1049. (mapcar (lambda (x)
  1050. (if (string-match org-table-dataline-regexp x)
  1051. (concat "|" ff x)
  1052. x))
  1053. lines)
  1054. "\n"))))
  1055. (defun org-clock-time% (total &rest strings)
  1056. "Compute a time fraction in percent.
  1057. TOTAL s a time string like 10:21 specifying the total times.
  1058. STRINGS is a list of strings that should be checked for a time.
  1059. The first string that does have a time will be used.
  1060. This function is made for clock tables."
  1061. (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
  1062. tot s)
  1063. (save-match-data
  1064. (catch 'exit
  1065. (if (not (string-match re total))
  1066. (throw 'exit 0.)
  1067. (setq tot (+ (string-to-number (match-string 2 total))
  1068. (* 60 (string-to-number (match-string 1 total)))))
  1069. (if (= tot 0.) (throw 'exit 0.)))
  1070. (while (setq s (pop strings))
  1071. (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  1072. (throw 'exit
  1073. (/ (* 100.0 (+ (string-to-number (match-string 2 s))
  1074. (* 60 (string-to-number (match-string 1 s)))))
  1075. tot))))
  1076. 0))))
  1077. (defun org-clock-save ()
  1078. "Persist various clock-related data to disk.
  1079. The details of what will be saved are regulated by the variable
  1080. `org-clock-persist'."
  1081. (when org-clock-persist
  1082. (let (b)
  1083. (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
  1084. (progn
  1085. (delete-region (point-min) (point-max))
  1086. ;;Store clock
  1087. (insert (format ";; org-persist.el - %s at %s\n"
  1088. system-name (format-time-string
  1089. (cdr org-time-stamp-formats))))
  1090. (if (and (setq b (marker-buffer org-clock-marker))
  1091. (setq b (or (buffer-base-buffer b) b))
  1092. (buffer-live-p b)
  1093. (buffer-file-name b)
  1094. (or (not org-clock-persist-query-save)
  1095. (y-or-n-p (concat "Save current clock ("
  1096. (substring-no-properties org-clock-heading)
  1097. ") "))))
  1098. (insert "(setq resume-clock '(\""
  1099. (buffer-file-name (marker-buffer org-clock-marker))
  1100. "\" . " (int-to-string (marker-position org-clock-marker))
  1101. "))\n"))
  1102. ;; Store clocked task history. Tasks are stored reversed to make
  1103. ;; reading simpler
  1104. (when (and org-clock-history (eq org-clock-persist t))
  1105. (insert
  1106. "(setq stored-clock-history '("
  1107. (mapconcat
  1108. (lambda (m)
  1109. (when (and (setq b (marker-buffer m))
  1110. (setq b (or (buffer-base-buffer b) b))
  1111. (buffer-live-p b)
  1112. (buffer-file-name b))
  1113. (concat "(\"" (buffer-file-name b)
  1114. "\" . " (int-to-string (marker-position m))
  1115. ")")))
  1116. (reverse org-clock-history) " ") "))\n"))
  1117. (save-buffer)
  1118. (kill-buffer (current-buffer)))))))
  1119. (defvar org-clock-loaded nil
  1120. "Was the clock file loaded?")
  1121. (defun org-clock-load ()
  1122. "Load clock-related data from disk, maybe resuming a stored clock."
  1123. (when (and org-clock-persist (not org-clock-loaded))
  1124. (let ((filename (expand-file-name org-clock-persist-file))
  1125. (org-clock-in-resume 'auto-restart)
  1126. resume-clock stored-clock-history)
  1127. (if (not (file-readable-p filename))
  1128. (message "Not restoring clock data; %s not found"
  1129. org-clock-persist-file)
  1130. (message "%s" "Restoring clock data")
  1131. (setq org-clock-loaded t)
  1132. (load-file filename)
  1133. ;; load history
  1134. (when stored-clock-history
  1135. (save-window-excursion
  1136. (mapc (lambda (task)
  1137. (if (file-exists-p (car task))
  1138. (org-clock-history-push (cdr task)
  1139. (find-file (car task)))))
  1140. stored-clock-history)))
  1141. ;; resume clock
  1142. (when (and resume-clock org-clock-persist
  1143. (file-exists-p (car resume-clock))
  1144. (or (not org-clock-persist-query-resume)
  1145. (y-or-n-p
  1146. (concat
  1147. "Resume clock ("
  1148. (with-current-buffer (find-file (car resume-clock))
  1149. (save-excursion
  1150. (goto-char (cdr resume-clock))
  1151. (org-back-to-heading t)
  1152. (and (looking-at org-complex-heading-regexp)
  1153. (match-string 4))))
  1154. ") "))))
  1155. (when (file-exists-p (car resume-clock))
  1156. (with-current-buffer (find-file (car resume-clock))
  1157. (goto-char (cdr resume-clock))
  1158. (org-clock-in)
  1159. (if (org-invisible-p)
  1160. (org-show-context)))))))))
  1161. ;;;###autoload
  1162. (defun org-clock-persistence-insinuate ()
  1163. "Set up hooks for clock persistence"
  1164. (add-hook 'org-mode-hook 'org-clock-load)
  1165. (add-hook 'kill-emacs-hook 'org-clock-save))
  1166. (provide 'org-clock)
  1167. ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
  1168. ;;; org-clock.el ends here