org-clock.el 53 KB

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