org-clock.el 51 KB

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