org-clock.el 44 KB

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