org-clock.el 55 KB

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