org-clock.el 55 KB

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