org-clock.el 53 KB

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