org-clock.el 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  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.33trans
  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 "Just the history" history)
  125. (const :tag "Clock and history" t)
  126. (const :tag "No persistence" nil)))
  127. (defcustom org-clock-persist-file (convert-standard-filename
  128. "~/.emacs.d/org-clock-save.el")
  129. "File to save clock data to."
  130. :group 'org-clock
  131. :type 'string)
  132. (defcustom org-clock-persist-query-save nil
  133. "When non-nil, ask before saving the current clock on exit."
  134. :group 'org-clock
  135. :type 'boolean)
  136. (defcustom org-clock-persist-query-resume t
  137. "When non-nil, ask before resuming any stored clock during load."
  138. :group 'org-clock
  139. :type 'boolean)
  140. (defcustom org-clock-sound nil
  141. "Sound that will used for notifications.
  142. Possible values:
  143. nil no sound played.
  144. t standard Emacs beep
  145. file name play this sound file. If not possible, fall back to beep"
  146. :group 'org-clock
  147. :type '(choice
  148. (const :tag "No sound" nil)
  149. (const :tag "Standard beep" t)
  150. (file :tag "Play sound file")))
  151. (defcustom org-clock-modeline-total 'auto
  152. "Default setting for the time included for the modeline clock.
  153. This can be overruled locally using the CLOCK_MODELINE_TOTAL property.
  154. Allowed values are:
  155. current Only the time in the current instance of the clock
  156. today All time clocked into this task today
  157. repeat All time clocked into this task since last repeat
  158. all All time ever recorded for this task
  159. auto Automatically, either `all', or `repeat' for repeating tasks"
  160. :group 'org-clock
  161. :type '(choice
  162. (const :tag "Current clock" current)
  163. (const :tag "Today's task time" today)
  164. (const :tag "Since last repeat" repeat)
  165. (const :tag "All task time" all)
  166. (const :tag "Automatically, `all' or since `repeat'" auto)))
  167. (defcustom org-show-notification-handler nil
  168. "Function or program to send notification with.
  169. The function or program will be called with the notification
  170. string as argument."
  171. :group 'org-clock
  172. :type '(choice
  173. (string :tag "Program")
  174. (function :tag "Function")))
  175. (defcustom org-clock-clocktable-default-properties '(:maxlevel 2 :scope file)
  176. "Default properties for new clocktables."
  177. :group 'org-clock
  178. :type 'plist)
  179. (defcustom org-clock-idle-time nil
  180. "When non-nil, resolve open clocks if the user is idle more than X minutes."
  181. :group 'org-clock
  182. :type '(choice
  183. (const :tag "Never" nil)
  184. (integer :tag "After N minutes")))
  185. (defcustom org-clock-auto-clock-resolution 'when-no-clock-is-running
  186. "When to automatically resolve open clocks found in Org buffers."
  187. :group 'org-clock
  188. :type '(choice
  189. (const :tag "Never" nil)
  190. (const :tag "Always" t)
  191. (const :tag "When no clock is running" when-no-clock-is-running)))
  192. (defvar org-clock-in-prepare-hook nil
  193. "Hook run when preparing the clock.
  194. This hook is run before anything happens to the task that
  195. you want to clock in. For example, you can use this hook
  196. to add an effort property.")
  197. (defvar org-clock-in-hook nil
  198. "Hook run when starting the clock.")
  199. (defvar org-clock-out-hook nil
  200. "Hook run when stopping the current clock.")
  201. (defvar org-clock-cancel-hook nil
  202. "Hook run when cancelling the current clock.")
  203. (defvar org-clock-goto-hook nil
  204. "Hook run when selecting the currently clocked-in entry.")
  205. (defvar org-clock-has-been-used nil
  206. "Has the clock been used during the current Emacs session?")
  207. ;;; The clock for measuring work time.
  208. (defvar org-mode-line-string "")
  209. (put 'org-mode-line-string 'risky-local-variable t)
  210. (defvar org-clock-mode-line-timer nil)
  211. (defvar org-clock-idle-timer nil)
  212. (defvar org-clock-heading) ; defined in org.el
  213. (defvar org-clock-heading-for-remember "")
  214. (defvar org-clock-start-time "")
  215. (defvar org-clock-left-over-time nil
  216. "If non-nil, user cancelled a clock; this is when leftover time started.")
  217. (defvar org-clock-effort ""
  218. "Effort estimate of the currently clocking task")
  219. (defvar org-clock-total-time nil
  220. "Holds total time, spent previously on currently clocked item.
  221. This does not include the time in the currently running clock.")
  222. (defvar org-clock-history nil
  223. "List of marker pointing to recent clocked tasks.")
  224. (defvar org-clock-default-task (make-marker)
  225. "Marker pointing to the default task that should clock time.
  226. The clock can be made to switch to this task after clocking out
  227. of a different task.")
  228. (defvar org-clock-interrupted-task (make-marker)
  229. "Marker pointing to the task that has been interrupted by the current clock.")
  230. (defvar org-clock-mode-line-map (make-sparse-keymap))
  231. (define-key org-clock-mode-line-map [mode-line mouse-2] 'org-clock-goto)
  232. (define-key org-clock-mode-line-map [mode-line mouse-1] 'org-clock-menu)
  233. (defun org-clock-menu ()
  234. (interactive)
  235. (popup-menu
  236. '("Clock"
  237. ["Clock out" org-clock-out t]
  238. ["Change effort estimate" org-clock-modify-effort-estimate t]
  239. ["Go to clock entry" org-clock-goto t]
  240. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"])))
  241. (defun org-clock-history-push (&optional pos buffer)
  242. "Push a marker to the clock history."
  243. (setq org-clock-history-length (max 1 (min 35 org-clock-history-length)))
  244. (let ((m (move-marker (make-marker) (or pos (point)) buffer)) n l)
  245. (while (setq n (member m org-clock-history))
  246. (move-marker (car n) nil))
  247. (setq org-clock-history
  248. (delq nil
  249. (mapcar (lambda (x) (if (marker-buffer x) x nil))
  250. org-clock-history)))
  251. (when (>= (setq l (length org-clock-history)) org-clock-history-length)
  252. (setq org-clock-history
  253. (nreverse
  254. (nthcdr (- l org-clock-history-length -1)
  255. (nreverse org-clock-history)))))
  256. (push m org-clock-history)))
  257. (defun org-clock-save-markers-for-cut-and-paste (beg end)
  258. "Save relative positions of markers in region."
  259. (org-check-and-save-marker org-clock-marker beg end)
  260. (org-check-and-save-marker org-clock-hd-marker beg end)
  261. (org-check-and-save-marker org-clock-default-task beg end)
  262. (org-check-and-save-marker org-clock-interrupted-task beg end)
  263. (mapc (lambda (m) (org-check-and-save-marker m beg end))
  264. org-clock-history))
  265. (defun org-clock-select-task (&optional prompt)
  266. "Select a task that recently was associated with clocking."
  267. (interactive)
  268. (let (sel-list rpl (i 0) s)
  269. (save-window-excursion
  270. (org-switch-to-buffer-other-window
  271. (get-buffer-create "*Clock Task Select*"))
  272. (erase-buffer)
  273. (when (marker-buffer org-clock-default-task)
  274. (insert (org-add-props "Default Task\n" nil 'face 'bold))
  275. (setq s (org-clock-insert-selection-line ?d org-clock-default-task))
  276. (push s sel-list))
  277. (when (marker-buffer org-clock-interrupted-task)
  278. (insert (org-add-props "The task interrupted by starting the last one\n" nil 'face 'bold))
  279. (setq s (org-clock-insert-selection-line ?i org-clock-interrupted-task))
  280. (push s sel-list))
  281. (when (marker-buffer org-clock-marker)
  282. (insert (org-add-props "Current Clocking Task\n" nil 'face 'bold))
  283. (setq s (org-clock-insert-selection-line ?c org-clock-marker))
  284. (push s sel-list))
  285. (insert (org-add-props "Recent Tasks\n" nil 'face 'bold))
  286. (mapc
  287. (lambda (m)
  288. (when (marker-buffer m)
  289. (setq i (1+ i)
  290. s (org-clock-insert-selection-line
  291. (if (< i 10)
  292. (+ i ?0)
  293. (+ i (- ?A 10))) m))
  294. (push s sel-list)))
  295. org-clock-history)
  296. (org-fit-window-to-buffer)
  297. (message (or prompt "Select task for clocking:"))
  298. (setq rpl (read-char-exclusive))
  299. (cond
  300. ((eq rpl ?q) nil)
  301. ((eq rpl ?x) nil)
  302. ((assoc rpl sel-list) (cdr (assoc rpl sel-list)))
  303. (t (error "Invalid task choice %c" rpl))))))
  304. (defun org-clock-insert-selection-line (i marker)
  305. "Insert a line for the clock selection menu.
  306. And return a cons cell with the selection character integer and the marker
  307. pointing to it."
  308. (when (marker-buffer marker)
  309. (let (file cat task heading prefix)
  310. (with-current-buffer (org-base-buffer (marker-buffer marker))
  311. (save-excursion
  312. (save-restriction
  313. (widen)
  314. (ignore-errors
  315. (goto-char marker)
  316. (setq file (buffer-file-name (marker-buffer marker))
  317. cat (or (org-get-category)
  318. (progn (org-refresh-category-properties)
  319. (org-get-category)))
  320. heading (org-get-heading 'notags)
  321. prefix (save-excursion
  322. (org-back-to-heading t)
  323. (looking-at "\\*+ ")
  324. (match-string 0))
  325. task (substring
  326. (org-fontify-like-in-org-mode
  327. (concat prefix heading)
  328. org-odd-levels-only)
  329. (length prefix)))))))
  330. (when (and cat task)
  331. (insert (format "[%c] %-15s %s\n" i cat task))
  332. (cons i marker)))))
  333. (defun org-clock-get-clock-string ()
  334. "Form a clock-string, that will be show in the mode line.
  335. If an effort estimate was defined for current item, use
  336. 01:30/01:50 format (clocked/estimated).
  337. If not, show simply the clocked time like 01:50."
  338. (let* ((clocked-time (org-clock-get-clocked-time))
  339. (h (floor clocked-time 60))
  340. (m (- clocked-time (* 60 h))))
  341. (if (and org-clock-effort)
  342. (let* ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
  343. (effort-h (floor effort-in-minutes 60))
  344. (effort-m (- effort-in-minutes (* effort-h 60))))
  345. (format (concat "-[" org-time-clocksum-format "/" org-time-clocksum-format " (%s)]")
  346. h m effort-h effort-m org-clock-heading))
  347. (format (concat "-[" org-time-clocksum-format " (%s)]")
  348. h m org-clock-heading))))
  349. (defun org-clock-update-mode-line ()
  350. (setq org-mode-line-string
  351. (org-propertize
  352. (let ((clock-string (org-clock-get-clock-string))
  353. (help-text "Org-mode clock is running.\nmouse-1 shows a menu\nmouse-2 will jump to task"))
  354. (if (and (> org-clock-string-limit 0)
  355. (> (length clock-string) org-clock-string-limit))
  356. (org-propertize (substring clock-string 0 org-clock-string-limit)
  357. 'help-echo (concat help-text ": " org-clock-heading))
  358. (org-propertize clock-string 'help-echo help-text)))
  359. 'local-map org-clock-mode-line-map
  360. 'mouse-face (if (featurep 'xemacs) 'highlight 'mode-line-highlight)
  361. 'face 'org-mode-line-clock))
  362. (if org-clock-effort (org-clock-notify-once-if-expired))
  363. (force-mode-line-update))
  364. (defun org-clock-get-clocked-time ()
  365. "Get the clocked time for the current item in minutes.
  366. The time returned includes the time spent on this task in
  367. previous clocking intervals."
  368. (let ((currently-clocked-time
  369. (floor (- (org-float-time)
  370. (org-float-time org-clock-start-time)) 60)))
  371. (+ currently-clocked-time (or org-clock-total-time 0))))
  372. (defun org-clock-modify-effort-estimate (&optional value)
  373. "Add to or set the effort estimate of the item currently being clocked.
  374. VALUE can be a number of minutes, or a string with format hh:mm or mm.
  375. When the string starts with a + or a - sign, the current value of the effort
  376. property will be changed by that amount.
  377. This will update the \"Effort\" property of currently clocked item, and
  378. the mode line."
  379. (interactive)
  380. (when (org-clock-is-active)
  381. (let ((current org-clock-effort) sign)
  382. (unless value
  383. ;; Prompt user for a value or a change
  384. (setq value
  385. (read-string
  386. (format "Set effort (hh:mm or mm%s): "
  387. (if current
  388. (format ", prefix + to add to %s" org-clock-effort)
  389. "")))))
  390. (when (stringp value)
  391. ;; A string. See if it is a delta
  392. (setq sign (string-to-char value))
  393. (if (member sign '(?- ?+))
  394. (setq current (org-hh:mm-string-to-minutes (substring current 1)))
  395. (setq current 0))
  396. (setq value (org-hh:mm-string-to-minutes value))
  397. (if (equal ?- sign)
  398. (setq value (- current value))
  399. (if (equal ?+ sign) (setq value (+ current value)))))
  400. (setq value (max 0 value)
  401. org-clock-effort (org-minutes-to-hh:mm-string value))
  402. (org-entry-put org-clock-marker "Effort" org-clock-effort)
  403. (org-clock-update-mode-line)
  404. (message "Effort is now %s" org-clock-effort))))
  405. (defvar org-clock-notification-was-shown nil
  406. "Shows if we have shown notification already.")
  407. (defun org-clock-notify-once-if-expired ()
  408. "Show notification if we spent more time than we estimated before.
  409. Notification is shown only once."
  410. (when (marker-buffer org-clock-marker)
  411. (let ((effort-in-minutes (org-hh:mm-string-to-minutes org-clock-effort))
  412. (clocked-time (org-clock-get-clocked-time)))
  413. (if (>= clocked-time effort-in-minutes)
  414. (unless org-clock-notification-was-shown
  415. (setq org-clock-notification-was-shown t)
  416. (org-notify
  417. (format "Task '%s' should be finished by now. (%s)"
  418. org-clock-heading org-clock-effort) t))
  419. (setq org-clock-notification-was-shown nil)))))
  420. (defun org-notify (notification &optional play-sound)
  421. "Send a NOTIFICATION and maybe PLAY-SOUND."
  422. (org-show-notification notification)
  423. (if play-sound (org-clock-play-sound)))
  424. (defun org-show-notification (notification)
  425. "Show notification.
  426. Use `org-show-notification-handler' if defined,
  427. use libnotify if available, or fall back on a message."
  428. (cond ((functionp org-show-notification-handler)
  429. (funcall org-show-notification-handler notification))
  430. ((stringp org-show-notification-handler)
  431. (start-process "emacs-timer-notification" nil
  432. org-show-notification-handler notification))
  433. ((org-program-exists "notify-send")
  434. (start-process "emacs-timer-notification" nil
  435. "notify-send" notification))
  436. ;; Maybe the handler will send a message, so only use message as
  437. ;; a fall back option
  438. (t (message "%s" notification))))
  439. (defun org-clock-play-sound ()
  440. "Play sound as configured by `org-clock-sound'.
  441. Use alsa's aplay tool if available."
  442. (cond
  443. ((not org-clock-sound))
  444. ((eq org-clock-sound t) (beep t) (beep t))
  445. ((stringp org-clock-sound)
  446. (let ((file (expand-file-name org-clock-sound)))
  447. (if (file-exists-p file)
  448. (if (org-program-exists "aplay")
  449. (start-process "org-clock-play-notification" nil
  450. "aplay" file)
  451. (condition-case nil
  452. (play-sound-file file)
  453. (error (beep t) (beep t)))))))))
  454. (defun org-program-exists (program-name)
  455. "Checks whenever we can locate program and launch it."
  456. (if (eq system-type 'gnu/linux)
  457. (= 0 (call-process "which" nil nil nil program-name))))
  458. (defvar org-clock-mode-line-entry nil
  459. "Information for the modeline about the running clock.")
  460. (defun org-find-open-clocks (file)
  461. "Search through the given file and find all open clocks."
  462. (let ((buf (or (get-file-buffer file)
  463. (find-file-noselect file)))
  464. clocks)
  465. (with-current-buffer buf
  466. (save-excursion
  467. (goto-char (point-min))
  468. (while (re-search-forward "CLOCK: \\(\\[.*?\\]\\)$" nil t)
  469. (push (cons (copy-marker (1- (match-end 1)) t)
  470. (org-time-string-to-time (match-string 1))) clocks))))
  471. clocks))
  472. (defsubst org-is-active-clock (clock)
  473. "Return t if CLOCK is the currently active clock."
  474. (and (org-clock-is-active)
  475. (= org-clock-marker (car clock))))
  476. (defmacro org-with-clock-position (clock &rest forms)
  477. "Evaluate FORMS with CLOCK as the current active clock."
  478. `(with-current-buffer (marker-buffer (car ,clock))
  479. (save-excursion
  480. (save-restriction
  481. (widen)
  482. (goto-char (car ,clock))
  483. (beginning-of-line)
  484. ,@forms))))
  485. (put 'org-with-clock-position 'lisp-indent-function 1)
  486. (defmacro org-with-clock (clock &rest forms)
  487. "Evaluate FORMS with CLOCK as the current active clock.
  488. This macro also protects the current active clock from being altered."
  489. `(org-with-clock-position ,clock
  490. (let ((org-clock-start-time (cdr ,clock))
  491. (org-clock-total-time)
  492. (org-clock-history)
  493. (org-clock-effort)
  494. (org-clock-marker (car ,clock))
  495. (org-clock-hd-marker (save-excursion
  496. (outline-back-to-heading t)
  497. (point-marker))))
  498. ,@forms)))
  499. (put 'org-with-clock 'lisp-indent-function 1)
  500. (defsubst org-clock-clock-in (clock &optional resume)
  501. "Clock in to the clock located by CLOCK.
  502. If necessary, clock-out of the currently active clock."
  503. (org-with-clock-position clock
  504. (let ((org-clock-in-resume (or resume org-clock-in-resume)))
  505. (org-clock-in))))
  506. (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
  507. "Clock out of the clock located by CLOCK."
  508. (let ((temp (copy-marker (car clock)
  509. (marker-insertion-type (car clock)))))
  510. (if (org-is-active-clock clock)
  511. (org-clock-out fail-quietly at-time)
  512. (org-with-clock clock
  513. (org-clock-out fail-quietly at-time)))
  514. (setcar clock temp)))
  515. (defsubst org-clock-clock-cancel (clock)
  516. "Cancel the clock located by CLOCK."
  517. (let ((temp (copy-marker (car clock)
  518. (marker-insertion-type (car clock)))))
  519. (if (org-is-active-clock clock)
  520. (org-clock-cancel)
  521. (org-with-clock clock
  522. (org-clock-cancel)))
  523. (setcar clock temp)))
  524. (defvar org-clock-clocking-in nil)
  525. (defvar org-clock-resolving-clocks nil)
  526. (defvar org-clock-resolving-clocks-due-to-idleness nil)
  527. (defun org-clock-resolve-clock (clock resolve-to &optional close-p
  528. restart-p fail-quietly)
  529. "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
  530. `CLOCK' is a cons cell of the form (MARKER START-TIME).
  531. This routine can do one of many things:
  532. if `RESOLVE-TO' is nil
  533. if `CLOSE-P' is non-nil, give an error
  534. if this clock is the active clock, cancel it
  535. else delete the clock line (as if it never happened)
  536. if `RESTART-P' is non-nil, start a new clock
  537. else if `RESOLVE-TO' is the symbol `now'
  538. if `RESTART-P' is non-nil, give an error
  539. if `CLOSE-P' is non-nil, clock out the entry and
  540. if this clock is the active clock, stop it
  541. else if this clock is the active clock, do nothing
  542. else if there is no active clock, resume this clock
  543. else ask to cancel the active clock, and if so,
  544. resume this clock after cancelling it
  545. else if `RESOLVE-TO' is some date in the future
  546. give an error about `RESOLVE-TO' being invalid
  547. else if `RESOLVE-TO' is some date in the past
  548. if `RESTART-P' is non-nil, give an error
  549. if `CLOSE-P' is non-nil, enter a closing time and
  550. if this clock is the active clock, stop it
  551. else if this clock is the active clock, enter a
  552. closing time, stop the current clock, then
  553. start a new clock for the same item
  554. else just enter a closing time for this clock
  555. and then start a new clock for the same item"
  556. (let ((org-clock-resolving-clocks t))
  557. (cond
  558. ((null resolve-to)
  559. (org-clock-clock-cancel clock)
  560. (if (and restart-p (not org-clock-clocking-in))
  561. (org-clock-clock-in clock)))
  562. ((eq resolve-to 'now)
  563. (if restart-p
  564. (error "RESTART-P is not valid here"))
  565. (if (or close-p org-clock-clocking-in)
  566. (org-clock-clock-out clock fail-quietly)
  567. (unless (org-is-active-clock clock)
  568. (org-clock-clock-in clock t))))
  569. ((not (time-less-p resolve-to (current-time)))
  570. (error "RESOLVE-TO must refer to a time in the past"))
  571. (t
  572. (if restart-p
  573. (error "RESTART-P is not valid here"))
  574. (org-clock-clock-out clock fail-quietly resolve-to)
  575. (unless org-clock-clocking-in
  576. (if close-p
  577. (setq org-clock-left-over-time resolve-to)
  578. (org-clock-clock-in clock)))))))
  579. (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
  580. "Resolve an open org-mode clock.
  581. An open clock was found, with `dangling' possibly being non-nil.
  582. If this function was invoked with a prefix argument, non-dangling
  583. open clocks are ignored. The given clock requires some sort of
  584. user intervention to resolve it, either because a clock was left
  585. dangling or due to an idle timeout. The clock resolution can
  586. either be:
  587. (a) deleted, the user doesn't care about the clock
  588. (b) restarted from the current time (if no other clock is open)
  589. (c) closed, giving the clock X minutes
  590. (d) closed and then restarted
  591. (e) resumed, as if the user had never left
  592. The format of clock is (CONS MARKER START-TIME), where MARKER
  593. identifies the buffer and position the clock is open at (and
  594. thus, the heading it's under), and START-TIME is when the clock
  595. was started."
  596. (assert clock)
  597. (let* ((ch
  598. (save-window-excursion
  599. (save-excursion
  600. (unless org-clock-resolving-clocks-due-to-idleness
  601. (org-with-clock clock (org-clock-goto))
  602. (with-current-buffer (marker-buffer (car clock))
  603. (goto-char (car clock))
  604. (if org-clock-into-drawer
  605. (let ((logbook
  606. (if (stringp org-clock-into-drawer)
  607. (concat ":" org-clock-into-drawer ":")
  608. ":LOGBOOK:")))
  609. (ignore-errors
  610. (outline-flag-region
  611. (save-excursion
  612. (outline-back-to-heading t)
  613. (search-forward logbook)
  614. (goto-char (match-beginning 0)))
  615. (save-excursion
  616. (outline-back-to-heading t)
  617. (search-forward logbook)
  618. (search-forward ":END:")
  619. (goto-char (match-end 0)))
  620. nil))))))
  621. (let (char-pressed)
  622. (while (null char-pressed)
  623. (setq char-pressed
  624. (read-char (concat (funcall prompt-fn clock)
  625. " [(kK)eep (sS)ubtract (C)ancel]? ")
  626. nil 45)))
  627. char-pressed))))
  628. (default (floor (/ (org-float-time
  629. (time-subtract (current-time) last-valid)) 60)))
  630. (keep (and (memq ch '(?k ?K))
  631. (read-number "Keep how many minutes? " default)))
  632. (subtractp (memq ch '(?s ?S)))
  633. (barely-started-p (< (- (org-float-time last-valid)
  634. (org-float-time (cdr clock))) 45))
  635. (start-over (and subtractp barely-started-p)))
  636. (if (or (null ch)
  637. (not (memq ch '(?k ?K ?s ?S ?C))))
  638. (message "")
  639. (org-clock-resolve-clock
  640. clock (cond
  641. ((or (eq ch ?C)
  642. ;; If the time on the clock was less than a minute before
  643. ;; the user went away, and they've ask to subtract all the
  644. ;; time...
  645. start-over)
  646. nil)
  647. (subtractp
  648. last-valid)
  649. ((= keep default)
  650. 'now)
  651. (t
  652. (time-add last-valid (seconds-to-time (* 60 keep)))))
  653. (memq ch '(?K ?S))
  654. (and start-over
  655. (not (memq ch '(?K ?S ?C))))
  656. fail-quietly))))
  657. (defun org-resolve-clocks (&optional also-non-dangling-p prompt-fn last-valid)
  658. "Resolve all currently open org-mode clocks.
  659. If `also-non-dangling-p' is non-nil, also ask to resolve
  660. non-dangling (i.e., currently open and valid) clocks."
  661. (interactive "P")
  662. (unless org-clock-resolving-clocks
  663. (let ((org-clock-resolving-clocks t))
  664. (dolist (file (org-files-list))
  665. (let ((clocks (org-find-open-clocks file)))
  666. (dolist (clock clocks)
  667. (let ((dangling (or (not (org-clock-is-active))
  668. (/= (car clock) org-clock-marker))))
  669. (unless (and (not dangling) (not also-non-dangling-p))
  670. (org-clock-resolve
  671. clock
  672. (or prompt-fn
  673. (function
  674. (lambda (clock)
  675. (format
  676. "Dangling clock started %d mins ago"
  677. (floor
  678. (/ (- (org-float-time (current-time))
  679. (org-float-time (cdr clock))) 60))))))
  680. (or last-valid
  681. (cdr clock)))))))))))
  682. (defun org-emacs-idle-seconds ()
  683. "Return the current Emacs idle time in seconds, or nil if not idle."
  684. (let ((idle-time (current-idle-time)))
  685. (if idle-time
  686. (org-float-time idle-time)
  687. 0)))
  688. (defun org-mac-idle-seconds ()
  689. "Return the current Mac idle time in seconds"
  690. (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
  691. (defun org-x11-idle-seconds ()
  692. "Return the current X11 idle time in seconds"
  693. (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
  694. (defun org-user-idle-seconds ()
  695. "Return the number of seconds the user has been idle for.
  696. This routine returns a floating point number."
  697. (if (or (eq system-type 'darwin) (eq window-system 'x))
  698. (let ((emacs-idle (org-emacs-idle-seconds)))
  699. ;; If Emacs has been idle for longer than the user's
  700. ;; `org-clock-idle-time' value, check whether the whole system has
  701. ;; really been idle for that long.
  702. (if (> emacs-idle (* 60 org-clock-idle-time))
  703. (min emacs-idle (if (eq system-type 'darwin)
  704. (org-mac-idle-seconds)
  705. (org-x11-idle-seconds)))
  706. emacs-idle))
  707. (org-emacs-idle-seconds)))
  708. (defvar org-clock-user-idle-seconds)
  709. (defun org-resolve-clocks-if-idle ()
  710. "Resolve all currently open org-mode clocks.
  711. This is performed after `org-clock-idle-time' minutes, to check
  712. if the user really wants to stay clocked in after being idle for
  713. so long."
  714. (when (and org-clock-idle-time (not org-clock-resolving-clocks)
  715. org-clock-marker)
  716. (let ((org-clock-user-idle-seconds (org-user-idle-seconds))
  717. (org-clock-user-idle-start
  718. (time-subtract (current-time)
  719. (seconds-to-time org-clock-user-idle-seconds)))
  720. (org-clock-resolving-clocks-due-to-idleness t))
  721. (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
  722. (org-clock-resolve
  723. (cons org-clock-marker
  724. org-clock-start-time)
  725. (function
  726. (lambda (clock)
  727. (format "Clocked in & idle for %.1f mins"
  728. (/ (org-float-time
  729. (time-subtract (current-time)
  730. org-clock-user-idle-start))
  731. 60.0))))
  732. org-clock-user-idle-start)))))
  733. (defun org-clock-in (&optional select)
  734. "Start the clock on the current item.
  735. If necessary, clock-out of the currently active clock.
  736. With prefix arg SELECT, offer a list of recently clocked tasks to
  737. clock into. When SELECT is `C-u C-u', clock into the current task and mark
  738. is as the default task, a special task that will always be offered in
  739. the clocking selection, associated with the letter `d'."
  740. (interactive "P")
  741. (setq org-clock-notification-was-shown nil)
  742. (catch 'abort
  743. (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
  744. (marker-buffer org-clock-marker)))
  745. ts selected-task target-pos (msg-extra "")
  746. (left-over (and (not org-clock-resolving-clocks)
  747. org-clock-left-over-time)))
  748. (when (and org-clock-auto-clock-resolution
  749. (or (not interrupting)
  750. (eq t org-clock-auto-clock-resolution))
  751. (not org-clock-clocking-in)
  752. (not org-clock-resolving-clocks))
  753. (setq org-clock-left-over-time nil)
  754. (let ((org-clock-clocking-in t))
  755. (org-resolve-clocks))) ; check if any clocks are dangling
  756. (when (equal select '(4))
  757. (setq selected-task (org-clock-select-task "Clock-in on task: "))
  758. (if selected-task
  759. (setq selected-task (copy-marker selected-task))
  760. (error "Abort")))
  761. (when interrupting
  762. ;; We are interrupting the clocking of a different task.
  763. ;; Save a marker to this task, so that we can go back.
  764. ;; First check if we are trying to clock into the same task!
  765. (when (save-excursion
  766. (org-back-to-heading t)
  767. (and (equal (marker-buffer org-clock-hd-marker)
  768. (if selected-task
  769. (marker-buffer selected-task)
  770. (current-buffer)))
  771. (= (marker-position org-clock-hd-marker)
  772. (if selected-task
  773. (marker-position selected-task)
  774. (point)))))
  775. (message "Clock continues in \"%s\"" org-clock-heading)
  776. (throw 'abort nil))
  777. (move-marker org-clock-interrupted-task
  778. (marker-position org-clock-marker)
  779. (marker-buffer org-clock-marker))
  780. (org-clock-out t))
  781. (when (equal select '(16))
  782. ;; Mark as default clocking task
  783. (org-clock-mark-default-task))
  784. ;; Clock in at which position?
  785. (setq target-pos
  786. (if (and (eobp) (not (org-on-heading-p)))
  787. (point-at-bol 0)
  788. (point)))
  789. (run-hooks 'org-clock-in-prepare-hook)
  790. (save-excursion
  791. (when (and selected-task (marker-buffer selected-task))
  792. ;; There is a selected task, move to the correct buffer
  793. ;; and set the new target position.
  794. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  795. (setq target-pos (marker-position selected-task))
  796. (move-marker selected-task nil))
  797. (save-excursion
  798. (save-restriction
  799. (widen)
  800. (goto-char target-pos)
  801. (org-back-to-heading t)
  802. (or interrupting (move-marker org-clock-interrupted-task nil))
  803. (org-clock-history-push)
  804. (cond ((functionp org-clock-in-switch-to-state)
  805. (looking-at org-complex-heading-regexp)
  806. (let ((newstate (funcall org-clock-in-switch-to-state
  807. (match-string 2))))
  808. (if newstate (org-todo newstate))))
  809. ((and org-clock-in-switch-to-state
  810. (not (looking-at (concat outline-regexp "[ \t]*"
  811. org-clock-in-switch-to-state
  812. "\\>"))))
  813. (org-todo org-clock-in-switch-to-state)))
  814. (setq org-clock-heading-for-remember
  815. (and (looking-at org-complex-heading-regexp)
  816. (match-end 4)
  817. (org-trim (buffer-substring (match-end 1)
  818. (match-end 4)))))
  819. (setq org-clock-heading
  820. (cond ((and org-clock-heading-function
  821. (functionp org-clock-heading-function))
  822. (funcall org-clock-heading-function))
  823. ((looking-at org-complex-heading-regexp)
  824. (match-string 4))
  825. (t "???")))
  826. (setq org-clock-heading (org-propertize org-clock-heading
  827. 'face nil))
  828. (org-clock-find-position org-clock-in-resume)
  829. (cond
  830. ((and org-clock-in-resume
  831. (looking-at
  832. (concat "^[ \t]* " org-clock-string
  833. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  834. " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  835. (message "Matched %s" (match-string 1))
  836. (setq ts (concat "[" (match-string 1) "]"))
  837. (goto-char (match-end 1))
  838. (setq org-clock-start-time
  839. (apply 'encode-time
  840. (org-parse-time-string (match-string 1))))
  841. (setq org-clock-effort (org-get-effort))
  842. (setq org-clock-total-time (org-clock-sum-current-item
  843. (org-clock-get-sum-start))))
  844. ((eq org-clock-in-resume 'auto-restart)
  845. ;; called from org-clock-load during startup,
  846. ;; do not interrupt, but warn!
  847. (message "Cannot restart clock because task does not contain unfinished clock")
  848. (ding)
  849. (sit-for 2)
  850. (throw 'abort nil))
  851. (t
  852. (insert-before-markers "\n")
  853. (backward-char 1)
  854. (org-indent-line-function)
  855. (when (and (save-excursion
  856. (end-of-line 0)
  857. (org-in-item-p)))
  858. (beginning-of-line 1)
  859. (org-indent-line-to (- (org-get-indentation) 2)))
  860. (insert org-clock-string " ")
  861. (setq org-clock-effort (org-get-effort))
  862. (setq org-clock-total-time (org-clock-sum-current-item
  863. (org-clock-get-sum-start)))
  864. (setq org-clock-start-time
  865. (or (and left-over
  866. (y-or-n-p
  867. (format
  868. "You stopped another clock %d mins ago; start this one from then? "
  869. (/ (- (org-float-time (current-time))
  870. (org-float-time left-over)) 60)))
  871. left-over)
  872. (current-time)))
  873. (setq ts (org-insert-time-stamp org-clock-start-time
  874. 'with-hm 'inactive))))
  875. (move-marker org-clock-marker (point) (buffer-base-buffer))
  876. (move-marker org-clock-hd-marker
  877. (save-excursion (org-back-to-heading t) (point))
  878. (buffer-base-buffer))
  879. (setq org-clock-has-been-used t)
  880. (or global-mode-string (setq global-mode-string '("")))
  881. (or (memq 'org-mode-line-string global-mode-string)
  882. (setq global-mode-string
  883. (append global-mode-string '(org-mode-line-string))))
  884. (org-clock-update-mode-line)
  885. (when org-clock-mode-line-timer
  886. (cancel-timer org-clock-mode-line-timer)
  887. (setq org-clock-mode-line-timer nil))
  888. (setq org-clock-mode-line-timer
  889. (run-with-timer 60 60 'org-clock-update-mode-line))
  890. (when org-clock-idle-timer
  891. (cancel-timer org-clock-idle-timer)
  892. (setq org-clock-idle-timer nil))
  893. (setq org-clock-idle-timer
  894. (run-with-timer 60 60 'org-resolve-clocks-if-idle))
  895. (message "Clock starts at %s - %s" ts msg-extra)
  896. (run-hooks 'org-clock-in-hook)))))))
  897. (defun org-clock-mark-default-task ()
  898. "Mark current task as default task."
  899. (interactive)
  900. (save-excursion
  901. (org-back-to-heading t)
  902. (move-marker org-clock-default-task (point))))
  903. (defvar msg-extra)
  904. (defun org-clock-get-sum-start ()
  905. "Return the time from which clock times should be counted.
  906. This is for the currently running clock as it is displayed
  907. in the mode line. This function looks at the properties
  908. LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
  909. corresponding variable `org-clock-modeline-total' and then
  910. decides which time to use."
  911. (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
  912. (symbol-name org-clock-modeline-total)))
  913. (lr (org-entry-get nil "LAST_REPEAT")))
  914. (cond
  915. ((equal cmt "current")
  916. (setq msg-extra "showing time in current clock instance")
  917. (current-time))
  918. ((equal cmt "today")
  919. (setq msg-extra "showing today's task time.")
  920. (let* ((dt (decode-time (current-time))))
  921. (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
  922. (if org-extend-today-until
  923. (setf (nth 2 dt) org-extend-today-until))
  924. (apply 'encode-time dt)))
  925. ((or (equal cmt "all")
  926. (and (or (not cmt) (equal cmt "auto"))
  927. (not lr)))
  928. (setq msg-extra "showing entire task time.")
  929. nil)
  930. ((or (equal cmt "repeat")
  931. (and (or (not cmt) (equal cmt "auto"))
  932. lr))
  933. (setq msg-extra "showing task time since last repeat.")
  934. (if (not lr)
  935. nil
  936. (org-time-string-to-time lr)))
  937. (t nil))))
  938. (defun org-clock-find-position (find-unclosed)
  939. "Find the location where the next clock line should be inserted.
  940. When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
  941. line and position cursor in that line."
  942. (org-back-to-heading t)
  943. (catch 'exit
  944. (let ((beg (save-excursion
  945. (beginning-of-line 2)
  946. (or (bolp) (newline))
  947. (point)))
  948. (end (progn (outline-next-heading) (point)))
  949. (re (concat "^[ \t]*" org-clock-string))
  950. (cnt 0)
  951. (drawer (if (stringp org-clock-into-drawer)
  952. org-clock-into-drawer "LOGBOOK"))
  953. first last ind-last)
  954. (goto-char beg)
  955. (when (and find-unclosed
  956. (re-search-forward
  957. (concat "^[ \t]* " org-clock-string
  958. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  959. " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
  960. end t))
  961. (beginning-of-line 1)
  962. (throw 'exit t))
  963. (when (eobp) (newline) (setq end (max (point) end)))
  964. (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
  965. ;; we seem to have a CLOCK drawer, so go there.
  966. (beginning-of-line 2)
  967. (or org-log-states-order-reversed
  968. (and (re-search-forward org-property-end-re nil t)
  969. (goto-char (match-beginning 0))))
  970. (throw 'exit t))
  971. ;; Lets count the CLOCK lines
  972. (goto-char beg)
  973. (while (re-search-forward re end t)
  974. (setq first (or first (match-beginning 0))
  975. last (match-beginning 0)
  976. cnt (1+ cnt)))
  977. (when (and (integerp org-clock-into-drawer)
  978. last
  979. (>= (1+ cnt) org-clock-into-drawer))
  980. ;; Wrap current entries into a new drawer
  981. (goto-char last)
  982. (setq ind-last (org-get-indentation))
  983. (beginning-of-line 2)
  984. (if (and (>= (org-get-indentation) ind-last)
  985. (org-at-item-p))
  986. (org-end-of-item))
  987. (insert ":END:\n")
  988. (beginning-of-line 0)
  989. (org-indent-line-to ind-last)
  990. (goto-char first)
  991. (insert ":" drawer ":\n")
  992. (beginning-of-line 0)
  993. (org-indent-line-function)
  994. (org-flag-drawer t)
  995. (beginning-of-line 2)
  996. (or org-log-states-order-reversed
  997. (and (re-search-forward org-property-end-re nil t)
  998. (goto-char (match-beginning 0))))
  999. (throw 'exit nil))
  1000. (goto-char beg)
  1001. (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1002. (not (equal (match-string 1) org-clock-string)))
  1003. ;; Planning info, skip to after it
  1004. (beginning-of-line 2)
  1005. (or (bolp) (newline)))
  1006. (when (or (eq org-clock-into-drawer t)
  1007. (stringp org-clock-into-drawer)
  1008. (and (integerp org-clock-into-drawer)
  1009. (< org-clock-into-drawer 2)))
  1010. (insert ":" drawer ":\n:END:\n")
  1011. (beginning-of-line -1)
  1012. (org-indent-line-function)
  1013. (org-flag-drawer t)
  1014. (beginning-of-line 2)
  1015. (org-indent-line-function)
  1016. (beginning-of-line)
  1017. (or org-log-states-order-reversed
  1018. (and (re-search-forward org-property-end-re nil t)
  1019. (goto-char (match-beginning 0))))))))
  1020. (defun org-clock-out (&optional fail-quietly at-time)
  1021. "Stop the currently running clock.
  1022. If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
  1023. (interactive)
  1024. (catch 'exit
  1025. (if (not (marker-buffer org-clock-marker))
  1026. (if fail-quietly (throw 'exit t) (error "No active clock")))
  1027. (let (ts te s h m remove)
  1028. (save-excursion
  1029. (set-buffer (marker-buffer org-clock-marker))
  1030. (save-restriction
  1031. (widen)
  1032. (goto-char org-clock-marker)
  1033. (beginning-of-line 1)
  1034. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1035. (equal (match-string 1) org-clock-string))
  1036. (setq ts (match-string 2))
  1037. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  1038. (goto-char (match-end 0))
  1039. (delete-region (point) (point-at-eol))
  1040. (insert "--")
  1041. (setq te (org-insert-time-stamp (or at-time (current-time))
  1042. 'with-hm 'inactive))
  1043. (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
  1044. (org-float-time (apply 'encode-time (org-parse-time-string ts))))
  1045. h (floor (/ s 3600))
  1046. s (- s (* 3600 h))
  1047. m (floor (/ s 60))
  1048. s (- s (* 60 s)))
  1049. (insert " => " (format "%2d:%02d" h m))
  1050. (when (setq remove (and org-clock-out-remove-zero-time-clocks
  1051. (= (+ h m) 0)))
  1052. (beginning-of-line 1)
  1053. (delete-region (point) (point-at-eol))
  1054. (and (looking-at "\n") (> (point-max) (1+ (point)))
  1055. (delete-char 1)))
  1056. (move-marker org-clock-marker nil)
  1057. (move-marker org-clock-hd-marker nil)
  1058. (when org-log-note-clock-out
  1059. (org-add-log-setup 'clock-out nil nil nil nil
  1060. (concat "# Task: " (org-get-heading t) "\n\n")))
  1061. (when org-clock-mode-line-timer
  1062. (cancel-timer org-clock-mode-line-timer)
  1063. (setq org-clock-mode-line-timer nil))
  1064. (when org-clock-idle-timer
  1065. (cancel-timer org-clock-idle-timer)
  1066. (setq org-clock-idle-timer nil))
  1067. (setq global-mode-string
  1068. (delq 'org-mode-line-string global-mode-string))
  1069. (when org-clock-out-switch-to-state
  1070. (save-excursion
  1071. (org-back-to-heading t)
  1072. (let ((org-inhibit-logging t))
  1073. (cond
  1074. ((functionp org-clock-out-switch-to-state)
  1075. (looking-at org-complex-heading-regexp)
  1076. (let ((newstate (funcall org-clock-out-switch-to-state
  1077. (match-string 2))))
  1078. (if newstate (org-todo newstate))))
  1079. ((and org-clock-out-switch-to-state
  1080. (not (looking-at (concat outline-regexp "[ \t]*"
  1081. org-clock-out-switch-to-state
  1082. "\\>"))))
  1083. (org-todo org-clock-out-switch-to-state))))))
  1084. (force-mode-line-update)
  1085. (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
  1086. (if remove " => LINE REMOVED" ""))
  1087. (run-hooks 'org-clock-out-hook))))))
  1088. (defun org-clock-cancel ()
  1089. "Cancel the running clock be removing the start timestamp."
  1090. (interactive)
  1091. (if (not (marker-buffer org-clock-marker))
  1092. (error "No active clock"))
  1093. (save-excursion
  1094. (set-buffer (marker-buffer org-clock-marker))
  1095. (goto-char org-clock-marker)
  1096. (delete-region (1- (point-at-bol)) (point-at-eol))
  1097. ;; Just in case, remove any empty LOGBOOK left over
  1098. (org-remove-empty-drawer-at "LOGBOOK" (point)))
  1099. (move-marker org-clock-marker nil)
  1100. (move-marker org-clock-hd-marker nil)
  1101. (setq global-mode-string
  1102. (delq 'org-mode-line-string global-mode-string))
  1103. (force-mode-line-update)
  1104. (message "Clock canceled")
  1105. (run-hooks 'org-clock-cancel-hook))
  1106. (defun org-clock-goto (&optional select)
  1107. "Go to the currently clocked-in entry, or to the most recently clocked one.
  1108. With prefix arg SELECT, offer recently clocked tasks for selection."
  1109. (interactive "@P")
  1110. (let* ((recent nil)
  1111. (m (cond
  1112. (select
  1113. (or (org-clock-select-task "Select task to go to: ")
  1114. (error "No task selected")))
  1115. ((marker-buffer org-clock-marker) org-clock-marker)
  1116. ((and org-clock-goto-may-find-recent-task
  1117. (car org-clock-history)
  1118. (marker-buffer (car org-clock-history)))
  1119. (setq recent t)
  1120. (car org-clock-history))
  1121. (t (error "No active or recent clock task")))))
  1122. (switch-to-buffer (marker-buffer m))
  1123. (if (or (< m (point-min)) (> m (point-max))) (widen))
  1124. (goto-char m)
  1125. (org-show-entry)
  1126. (org-back-to-heading t)
  1127. (org-cycle-hide-drawers 'children)
  1128. (recenter)
  1129. (if recent
  1130. (message "No running clock, this is the most recently clocked task"))
  1131. (run-hooks 'org-clock-goto-hook)))
  1132. (defvar org-clock-file-total-minutes nil
  1133. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  1134. (make-variable-buffer-local 'org-clock-file-total-minutes)
  1135. (defun org-clock-sum (&optional tstart tend)
  1136. "Sum the times for each subtree.
  1137. Puts the resulting times in minutes as a text property on each headline.
  1138. TSTART and TEND can mark a time range to be considered."
  1139. (interactive)
  1140. (let* ((bmp (buffer-modified-p))
  1141. (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  1142. org-clock-string
  1143. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  1144. (lmax 30)
  1145. (ltimes (make-vector lmax 0))
  1146. (t1 0)
  1147. (level 0)
  1148. ts te dt
  1149. time)
  1150. (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
  1151. (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
  1152. (if (consp tstart) (setq tstart (org-float-time tstart)))
  1153. (if (consp tend) (setq tend (org-float-time tend)))
  1154. (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
  1155. (save-excursion
  1156. (goto-char (point-max))
  1157. (while (re-search-backward re nil t)
  1158. (cond
  1159. ((match-end 2)
  1160. ;; Two time stamps
  1161. (setq ts (match-string 2)
  1162. te (match-string 3)
  1163. ts (org-float-time
  1164. (apply 'encode-time (org-parse-time-string ts)))
  1165. te (org-float-time
  1166. (apply 'encode-time (org-parse-time-string te)))
  1167. ts (if tstart (max ts tstart) ts)
  1168. te (if tend (min te tend) te)
  1169. dt (- te ts)
  1170. t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
  1171. ((match-end 4)
  1172. ;; A naked time
  1173. (setq t1 (+ t1 (string-to-number (match-string 5))
  1174. (* 60 (string-to-number (match-string 4))))))
  1175. (t ;; A headline
  1176. (setq level (- (match-end 1) (match-beginning 1)))
  1177. (when (or (> t1 0) (> (aref ltimes level) 0))
  1178. (loop for l from 0 to level do
  1179. (aset ltimes l (+ (aref ltimes l) t1)))
  1180. (setq t1 0 time (aref ltimes level))
  1181. (loop for l from level to (1- lmax) do
  1182. (aset ltimes l 0))
  1183. (goto-char (match-beginning 0))
  1184. (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
  1185. (setq org-clock-file-total-minutes (aref ltimes 0)))
  1186. (set-buffer-modified-p bmp)))
  1187. (defun org-clock-sum-current-item (&optional tstart)
  1188. "Returns time, clocked on current item in total"
  1189. (save-excursion
  1190. (save-restriction
  1191. (org-narrow-to-subtree)
  1192. (org-clock-sum tstart)
  1193. org-clock-file-total-minutes)))
  1194. (defun org-clock-display (&optional total-only)
  1195. "Show subtree times in the entire buffer.
  1196. If TOTAL-ONLY is non-nil, only show the total time for the entire file
  1197. in the echo area."
  1198. (interactive)
  1199. (org-clock-remove-overlays)
  1200. (let (time h m p)
  1201. (org-clock-sum)
  1202. (unless total-only
  1203. (save-excursion
  1204. (goto-char (point-min))
  1205. (while (or (and (equal (setq p (point)) (point-min))
  1206. (get-text-property p :org-clock-minutes))
  1207. (setq p (next-single-property-change
  1208. (point) :org-clock-minutes)))
  1209. (goto-char p)
  1210. (when (setq time (get-text-property p :org-clock-minutes))
  1211. (org-clock-put-overlay time (funcall outline-level))))
  1212. (setq h (/ org-clock-file-total-minutes 60)
  1213. m (- org-clock-file-total-minutes (* 60 h)))
  1214. ;; Arrange to remove the overlays upon next change.
  1215. (when org-remove-highlights-with-change
  1216. (org-add-hook 'before-change-functions 'org-clock-remove-overlays
  1217. nil 'local))))
  1218. (if org-time-clocksum-use-fractional
  1219. (message (concat "Total file time: " org-time-clocksum-fractional-format
  1220. " (%d hours and %d minutes)")
  1221. (/ (+ (* h 60.0) m) 60.0) h m)
  1222. (message (concat "Total file time: " org-time-clocksum-format
  1223. " (%d hours and %d minutes)") h m h m))))
  1224. (defvar org-clock-overlays nil)
  1225. (make-variable-buffer-local 'org-clock-overlays)
  1226. (defun org-clock-put-overlay (time &optional level)
  1227. "Put an overlays on the current line, displaying TIME.
  1228. If LEVEL is given, prefix time with a corresponding number of stars.
  1229. This creates a new overlay and stores it in `org-clock-overlays', so that it
  1230. will be easy to remove."
  1231. (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
  1232. (l (if level (org-get-valid-level level 0) 0))
  1233. (fmt (concat "%s " (if org-time-clocksum-use-fractional
  1234. org-time-clocksum-fractional-format
  1235. org-time-clocksum-format) "%s"))
  1236. (off 0)
  1237. ov tx)
  1238. (org-move-to-column c)
  1239. (unless (eolp) (skip-chars-backward "^ \t"))
  1240. (skip-chars-backward " \t")
  1241. (setq ov (org-make-overlay (1- (point)) (point-at-eol))
  1242. tx (concat (buffer-substring (1- (point)) (point))
  1243. (make-string (+ off (max 0 (- c (current-column)))) ?.)
  1244. (org-add-props (if org-time-clocksum-use-fractional
  1245. (format fmt
  1246. (make-string l ?*)
  1247. (/ (+ (* h 60.0) m) 60.0)
  1248. (make-string (- 16 l) ?\ ))
  1249. (format fmt
  1250. (make-string l ?*) h m
  1251. (make-string (- 16 l) ?\ )))
  1252. (list 'face 'org-clock-overlay))
  1253. ""))
  1254. (if (not (featurep 'xemacs))
  1255. (org-overlay-put ov 'display tx)
  1256. (org-overlay-put ov 'invisible t)
  1257. (org-overlay-put ov 'end-glyph (make-glyph tx)))
  1258. (push ov org-clock-overlays)))
  1259. (defun org-clock-remove-overlays (&optional beg end noremove)
  1260. "Remove the occur highlights from the buffer.
  1261. BEG and END are ignored. If NOREMOVE is nil, remove this function
  1262. from the `before-change-functions' in the current buffer."
  1263. (interactive)
  1264. (unless org-inhibit-highlight-removal
  1265. (mapc 'org-delete-overlay org-clock-overlays)
  1266. (setq org-clock-overlays nil)
  1267. (unless noremove
  1268. (remove-hook 'before-change-functions
  1269. 'org-clock-remove-overlays 'local))))
  1270. (defvar state) ;; dynamically scoped into this function
  1271. (defun org-clock-out-if-current ()
  1272. "Clock out if the current entry contains the running clock.
  1273. This is used to stop the clock after a TODO entry is marked DONE,
  1274. and is only done if the variable `org-clock-out-when-done' is not nil."
  1275. (when (and org-clock-out-when-done
  1276. (member state org-done-keywords)
  1277. (equal (or (buffer-base-buffer (marker-buffer org-clock-marker))
  1278. (marker-buffer org-clock-marker))
  1279. (or (buffer-base-buffer (current-buffer))
  1280. (current-buffer)))
  1281. (< (point) org-clock-marker)
  1282. (> (save-excursion (outline-next-heading) (point))
  1283. org-clock-marker))
  1284. ;; Clock out, but don't accept a logging message for this.
  1285. (let ((org-log-note-clock-out nil))
  1286. (org-clock-out))))
  1287. (add-hook 'org-after-todo-state-change-hook
  1288. 'org-clock-out-if-current)
  1289. ;;;###autoload
  1290. (defun org-get-clocktable (&rest props)
  1291. "Get a formatted clocktable with parameters according to PROPS.
  1292. The table is created in a temporary buffer, fully formatted and
  1293. fontified, and then returned."
  1294. ;; Set the defaults
  1295. (setq props (plist-put props :name "clocktable"))
  1296. (unless (plist-member props :maxlevel)
  1297. (setq props (plist-put props :maxlevel 2)))
  1298. (unless (plist-member props :scope)
  1299. (setq props (plist-put props :scope 'agenda)))
  1300. (with-temp-buffer
  1301. (org-mode)
  1302. (org-create-dblock props)
  1303. (org-update-dblock)
  1304. (font-lock-fontify-buffer)
  1305. (forward-line 2)
  1306. (buffer-substring (point) (progn
  1307. (re-search-forward "^#\\+END" nil t)
  1308. (point-at-bol)))))
  1309. (defun org-clock-report (&optional arg)
  1310. "Create a table containing a report about clocked time.
  1311. If the cursor is inside an existing clocktable block, then the table
  1312. will be updated. If not, a new clocktable will be inserted.
  1313. When called with a prefix argument, move to the first clock table in the
  1314. buffer and update it."
  1315. (interactive "P")
  1316. (org-clock-remove-overlays)
  1317. (when arg
  1318. (org-find-dblock "clocktable")
  1319. (org-show-entry))
  1320. (if (org-in-clocktable-p)
  1321. (goto-char (org-in-clocktable-p))
  1322. (org-create-dblock (append (list :name "clocktable")
  1323. org-clock-clocktable-default-properties)))
  1324. (org-update-dblock))
  1325. (defun org-in-clocktable-p ()
  1326. "Check if the cursor is in a clocktable."
  1327. (let ((pos (point)) start)
  1328. (save-excursion
  1329. (end-of-line 1)
  1330. (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
  1331. (setq start (match-beginning 0))
  1332. (re-search-forward "^#\\+END:.*" nil t)
  1333. (>= (match-end 0) pos)
  1334. start))))
  1335. (defun org-clock-special-range (key &optional time as-strings)
  1336. "Return two times bordering a special time range.
  1337. Key is a symbol specifying the range and can be one of `today', `yesterday',
  1338. `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
  1339. A week starts Monday 0:00 and ends Sunday 24:00.
  1340. The range is determined relative to TIME. TIME defaults to the current time.
  1341. The return value is a cons cell with two internal times like the ones
  1342. returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
  1343. the returned times will be formatted strings."
  1344. (if (integerp key) (setq key (intern (number-to-string key))))
  1345. (let* ((tm (decode-time (or time (current-time))))
  1346. (s 0) (m (nth 1 tm)) (h (nth 2 tm))
  1347. (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
  1348. (dow (nth 6 tm))
  1349. (skey (symbol-name key))
  1350. (shift 0)
  1351. s1 m1 h1 d1 month1 y1 diff ts te fm txt w date)
  1352. (cond
  1353. ((string-match "^[0-9]+$" skey)
  1354. (setq y (string-to-number skey) m 1 d 1 key 'year))
  1355. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  1356. (setq y (string-to-number (match-string 1 skey))
  1357. month (string-to-number (match-string 2 skey))
  1358. d 1 key 'month))
  1359. ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
  1360. (require 'cal-iso)
  1361. (setq y (string-to-number (match-string 1 skey))
  1362. w (string-to-number (match-string 2 skey)))
  1363. (setq date (calendar-gregorian-from-absolute
  1364. (calendar-absolute-from-iso (list w 1 y))))
  1365. (setq d (nth 1 date) month (car date) y (nth 2 date)
  1366. dow 1
  1367. key 'week))
  1368. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  1369. (setq y (string-to-number (match-string 1 skey))
  1370. month (string-to-number (match-string 2 skey))
  1371. d (string-to-number (match-string 3 skey))
  1372. key 'day))
  1373. ((string-match "\\([-+][0-9]+\\)$" skey)
  1374. (setq shift (string-to-number (match-string 1 skey))
  1375. key (intern (substring skey 0 (match-beginning 1))))))
  1376. (when (= shift 0)
  1377. (cond ((eq key 'yesterday) (setq key 'today shift -1))
  1378. ((eq key 'lastweek) (setq key 'week shift -1))
  1379. ((eq key 'lastmonth) (setq key 'month shift -1))
  1380. ((eq key 'lastyear) (setq key 'year shift -1))))
  1381. (cond
  1382. ((memq key '(day today))
  1383. (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
  1384. ((memq key '(week thisweek))
  1385. (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
  1386. m 0 h 0 d (- d diff) d1 (+ 7 d)))
  1387. ((memq key '(month thismonth))
  1388. (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
  1389. ((memq key '(year thisyear))
  1390. (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
  1391. (t (error "No such time block %s" key)))
  1392. (setq ts (encode-time s m h d month y)
  1393. te (encode-time (or s1 s) (or m1 m) (or h1 h)
  1394. (or d1 d) (or month1 month) (or y1 y)))
  1395. (setq fm (cdr org-time-stamp-formats))
  1396. (cond
  1397. ((memq key '(day today))
  1398. (setq txt (format-time-string "%A, %B %d, %Y" ts)))
  1399. ((memq key '(week thisweek))
  1400. (setq txt (format-time-string "week %G-W%V" ts)))
  1401. ((memq key '(month thismonth))
  1402. (setq txt (format-time-string "%B %Y" ts)))
  1403. ((memq key '(year thisyear))
  1404. (setq txt (format-time-string "the year %Y" ts))))
  1405. (if as-strings
  1406. (list (format-time-string fm ts) (format-time-string fm te) txt)
  1407. (list ts te txt))))
  1408. (defun org-clocktable-shift (dir n)
  1409. "Try to shift the :block date of the clocktable at point.
  1410. Point must be in the #+BEGIN: line of a clocktable, or this function
  1411. will throw an error.
  1412. DIR is a direction, a symbol `left', `right', `up', or `down'.
  1413. Both `left' and `down' shift the block toward the past, `up' and `right'
  1414. push it toward the future.
  1415. N is the number of shift steps to take. The size of the step depends on
  1416. the currently selected interval size."
  1417. (setq n (prefix-numeric-value n))
  1418. (and (memq dir '(left down)) (setq n (- n)))
  1419. (save-excursion
  1420. (goto-char (point-at-bol))
  1421. (if (not (looking-at "#\\+BEGIN: clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
  1422. (error "Line needs a :block definition before this command works")
  1423. (let* ((b (match-beginning 1)) (e (match-end 1))
  1424. (s (match-string 1))
  1425. block shift ins y mw d date wp m)
  1426. (cond
  1427. ((equal s "yesterday") (setq s "today-1"))
  1428. ((equal s "lastweek") (setq s "thisweek-1"))
  1429. ((equal s "lastmonth") (setq s "thismonth-1"))
  1430. ((equal s "lastyear") (setq s "thisyear-1")))
  1431. (cond
  1432. ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\)\\([-+][0-9]+\\)?$" s)
  1433. (setq block (match-string 1 s)
  1434. shift (if (match-end 2)
  1435. (string-to-number (match-string 2 s))
  1436. 0))
  1437. (setq shift (+ shift n))
  1438. (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
  1439. ((string-match "\\([0-9]+\\)\\(-\\([wW]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
  1440. ;; 1 1 2 3 3 4 4 5 6 6 5 2
  1441. (setq y (string-to-number (match-string 1 s))
  1442. wp (and (match-end 3) (match-string 3 s))
  1443. mw (and (match-end 4) (string-to-number (match-string 4 s)))
  1444. d (and (match-end 6) (string-to-number (match-string 6 s))))
  1445. (cond
  1446. (d (setq ins (format-time-string
  1447. "%Y-%m-%d"
  1448. (encode-time 0 0 0 (+ d n) m y))))
  1449. ((and wp mw (> (length wp) 0))
  1450. (require 'cal-iso)
  1451. (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
  1452. (setq ins (format-time-string
  1453. "%G-W%V"
  1454. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  1455. (mw
  1456. (setq ins (format-time-string
  1457. "%Y-%m"
  1458. (encode-time 0 0 0 1 (+ mw n) y))))
  1459. (y
  1460. (setq ins (number-to-string (+ y n))))))
  1461. (t (error "Cannot shift clocktable block")))
  1462. (when ins
  1463. (goto-char b)
  1464. (insert ins)
  1465. (delete-region (point) (+ (point) (- e b)))
  1466. (beginning-of-line 1)
  1467. (org-update-dblock)
  1468. t)))))
  1469. (defun org-dblock-write:clocktable (params)
  1470. "Write the standard clocktable."
  1471. (catch 'exit
  1472. (let* ((hlchars '((1 . "*") (2 . "/")))
  1473. (ins (make-marker))
  1474. (total-time nil)
  1475. (scope (plist-get params :scope))
  1476. (tostring (plist-get params :tostring))
  1477. (multifile (plist-get params :multifile))
  1478. (header (plist-get params :header))
  1479. (maxlevel (or (plist-get params :maxlevel) 3))
  1480. (step (plist-get params :step))
  1481. (emph (plist-get params :emphasize))
  1482. (timestamp (plist-get params :timestamp))
  1483. (ts (plist-get params :tstart))
  1484. (te (plist-get params :tend))
  1485. (block (plist-get params :block))
  1486. (link (plist-get params :link))
  1487. ipos time p level hlc hdl tsp props content recalc formula pcol
  1488. cc beg end pos tbl tbl1 range-text rm-file-column scope-is-list st)
  1489. (setq org-clock-file-total-minutes nil)
  1490. (when step
  1491. (unless (or block (and ts te))
  1492. (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
  1493. (org-clocktable-steps params)
  1494. (throw 'exit nil))
  1495. (when block
  1496. (setq cc (org-clock-special-range block nil t)
  1497. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  1498. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  1499. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  1500. (when (and ts (listp ts))
  1501. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  1502. (when (and te (listp te))
  1503. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  1504. ;; Now the times are strings we can parse.
  1505. (if ts (setq ts (org-float-time
  1506. (apply 'encode-time (org-parse-time-string ts)))))
  1507. (if te (setq te (org-float-time
  1508. (apply 'encode-time (org-parse-time-string te)))))
  1509. (move-marker ins (point))
  1510. (setq ipos (point))
  1511. ;; Get the right scope
  1512. (setq pos (point))
  1513. (cond
  1514. ((and scope (listp scope) (symbolp (car scope)))
  1515. (setq scope (eval scope)))
  1516. ((eq scope 'agenda)
  1517. (setq scope (org-agenda-files t)))
  1518. ((eq scope 'agenda-with-archives)
  1519. (setq scope (org-agenda-files t))
  1520. (setq scope (org-add-archive-files scope)))
  1521. ((eq scope 'file-with-archives)
  1522. (setq scope (org-add-archive-files (list (buffer-file-name)))
  1523. rm-file-column t)))
  1524. (setq scope-is-list (and scope (listp scope)))
  1525. (save-restriction
  1526. (cond
  1527. ((not scope))
  1528. ((eq scope 'file) (widen))
  1529. ((eq scope 'subtree) (org-narrow-to-subtree))
  1530. ((eq scope 'tree)
  1531. (while (org-up-heading-safe))
  1532. (org-narrow-to-subtree))
  1533. ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
  1534. (symbol-name scope)))
  1535. (setq level (string-to-number (match-string 1 (symbol-name scope))))
  1536. (catch 'exit
  1537. (while (org-up-heading-safe)
  1538. (looking-at outline-regexp)
  1539. (if (<= (org-reduced-level (funcall outline-level)) level)
  1540. (throw 'exit nil))))
  1541. (org-narrow-to-subtree))
  1542. (scope-is-list
  1543. (let* ((files scope)
  1544. (scope 'agenda)
  1545. (p1 (copy-sequence params))
  1546. file)
  1547. (setq p1 (plist-put p1 :tostring t))
  1548. (setq p1 (plist-put p1 :multifile t))
  1549. (setq p1 (plist-put p1 :scope 'file))
  1550. (org-prepare-agenda-buffers files)
  1551. (while (setq file (pop files))
  1552. (with-current-buffer (find-buffer-visiting file)
  1553. (setq tbl1 (org-dblock-write:clocktable p1))
  1554. (when tbl1
  1555. (push (org-clocktable-add-file
  1556. file
  1557. (concat "| |*File time*|*"
  1558. (org-minutes-to-hh:mm-string
  1559. org-clock-file-total-minutes)
  1560. "*|\n"
  1561. tbl1)) tbl)
  1562. (setq total-time (+ (or total-time 0)
  1563. org-clock-file-total-minutes))))))))
  1564. (goto-char pos)
  1565. (unless scope-is-list
  1566. (org-clock-sum ts te)
  1567. (goto-char (point-min))
  1568. (setq st t)
  1569. (while (or (and (bobp) (prog1 st (setq st nil))
  1570. (get-text-property (point) :org-clock-minutes)
  1571. (setq p (point-min)))
  1572. (setq p (next-single-property-change (point) :org-clock-minutes)))
  1573. (goto-char p)
  1574. (when (setq time (get-text-property p :org-clock-minutes))
  1575. (save-excursion
  1576. (beginning-of-line 1)
  1577. (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
  1578. (setq level (org-reduced-level
  1579. (- (match-end 1) (match-beginning 1))))
  1580. (<= level maxlevel))
  1581. (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
  1582. hdl (if (not link)
  1583. (match-string 2)
  1584. (org-make-link-string
  1585. (format "file:%s::%s"
  1586. (buffer-file-name)
  1587. (save-match-data
  1588. (org-make-org-heading-search-string
  1589. (match-string 2))))
  1590. (match-string 2)))
  1591. tsp (when timestamp
  1592. (setq props (org-entry-properties (point)))
  1593. (or (cdr (assoc "SCHEDULED" props))
  1594. (cdr (assoc "TIMESTAMP" props))
  1595. (cdr (assoc "DEADLINE" props))
  1596. (cdr (assoc "TIMESTAMP_IA" props)))))
  1597. (if (and (not multifile) (= level 1)) (push "|-" tbl))
  1598. (push (concat
  1599. "| " (int-to-string level) "|"
  1600. (if timestamp (concat tsp "|") "")
  1601. hlc hdl hlc " |"
  1602. (make-string (1- level) ?|)
  1603. hlc (org-minutes-to-hh:mm-string time) hlc
  1604. " |") tbl))))))
  1605. (setq tbl (nreverse tbl))
  1606. (if tostring
  1607. (if tbl (mapconcat 'identity tbl "\n") nil)
  1608. (goto-char ins)
  1609. (insert-before-markers
  1610. (or header
  1611. (concat
  1612. "Clock summary at ["
  1613. (substring
  1614. (format-time-string (cdr org-time-stamp-formats))
  1615. 1 -1)
  1616. "]"
  1617. (if block (concat ", for " range-text ".") "")
  1618. "\n\n"))
  1619. (if scope-is-list "|File" "")
  1620. "|L|" (if timestamp "Timestamp|" "") "Headline|Time|\n")
  1621. (setq total-time (or total-time org-clock-file-total-minutes))
  1622. (insert-before-markers
  1623. "|-\n|"
  1624. (if scope-is-list "|" "")
  1625. (if timestamp "|Timestamp|" "|")
  1626. "*Total time*| *"
  1627. (org-minutes-to-hh:mm-string (or total-time 0))
  1628. "*|\n|-\n")
  1629. (setq tbl (delq nil tbl))
  1630. (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
  1631. (equal (substring (car tbl) 0 2) "|-"))
  1632. (pop tbl))
  1633. (insert-before-markers (mapconcat
  1634. 'identity (delq nil tbl)
  1635. (if scope-is-list "\n|-\n" "\n")))
  1636. (backward-delete-char 1)
  1637. (if (setq formula (plist-get params :formula))
  1638. (cond
  1639. ((eq formula '%)
  1640. (setq pcol (+ (if scope-is-list 1 0) maxlevel 3))
  1641. (insert
  1642. (format
  1643. "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
  1644. pcol
  1645. 2
  1646. (+ 3 (if scope-is-list 1 0))
  1647. (+ (if scope-is-list 1 0) 3)
  1648. (1- pcol)))
  1649. (setq recalc t))
  1650. ((stringp formula)
  1651. (insert "\n#+TBLFM: " formula)
  1652. (setq recalc t))
  1653. (t (error "invalid formula in clocktable")))
  1654. ;; Should we rescue an old formula?
  1655. (when (stringp (setq content (plist-get params :content)))
  1656. (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
  1657. (setq recalc t)
  1658. (insert "\n" (match-string 1 (plist-get params :content)))
  1659. (beginning-of-line 0))))
  1660. (goto-char ipos)
  1661. (skip-chars-forward "^|")
  1662. (org-table-align)
  1663. (when recalc
  1664. (if (eq formula '%)
  1665. (save-excursion (org-table-goto-column pcol nil 'force)
  1666. (insert "%")))
  1667. (org-table-recalculate 'all))
  1668. (when rm-file-column
  1669. (forward-char 1)
  1670. (org-table-delete-column)))))))
  1671. (defun org-clocktable-steps (params)
  1672. (let* ((p1 (copy-sequence params))
  1673. (ts (plist-get p1 :tstart))
  1674. (te (plist-get p1 :tend))
  1675. (step0 (plist-get p1 :step))
  1676. (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
  1677. (block (plist-get p1 :block))
  1678. cc range-text)
  1679. (when block
  1680. (setq cc (org-clock-special-range block nil t)
  1681. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  1682. (if ts (setq ts (org-float-time
  1683. (apply 'encode-time (org-parse-time-string ts)))))
  1684. (if te (setq te (org-float-time
  1685. (apply 'encode-time (org-parse-time-string te)))))
  1686. (setq p1 (plist-put p1 :header ""))
  1687. (setq p1 (plist-put p1 :step nil))
  1688. (setq p1 (plist-put p1 :block nil))
  1689. (while (< ts te)
  1690. (or (bolp) (insert "\n"))
  1691. (setq p1 (plist-put p1 :tstart (format-time-string
  1692. (org-time-stamp-format nil t)
  1693. (seconds-to-time ts))))
  1694. (setq p1 (plist-put p1 :tend (format-time-string
  1695. (org-time-stamp-format nil t)
  1696. (seconds-to-time (setq ts (+ ts step))))))
  1697. (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
  1698. (plist-get p1 :tstart) "\n")
  1699. (org-dblock-write:clocktable p1)
  1700. (re-search-forward "#\\+END:")
  1701. (end-of-line 0))))
  1702. (defun org-clocktable-add-file (file table)
  1703. (if table
  1704. (let ((lines (org-split-string table "\n"))
  1705. (ff (file-name-nondirectory file)))
  1706. (mapconcat 'identity
  1707. (mapcar (lambda (x)
  1708. (if (string-match org-table-dataline-regexp x)
  1709. (concat "|" ff x)
  1710. x))
  1711. lines)
  1712. "\n"))))
  1713. (defun org-clock-time% (total &rest strings)
  1714. "Compute a time fraction in percent.
  1715. TOTAL s a time string like 10:21 specifying the total times.
  1716. STRINGS is a list of strings that should be checked for a time.
  1717. The first string that does have a time will be used.
  1718. This function is made for clock tables."
  1719. (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
  1720. tot s)
  1721. (save-match-data
  1722. (catch 'exit
  1723. (if (not (string-match re total))
  1724. (throw 'exit 0.)
  1725. (setq tot (+ (string-to-number (match-string 2 total))
  1726. (* 60 (string-to-number (match-string 1 total)))))
  1727. (if (= tot 0.) (throw 'exit 0.)))
  1728. (while (setq s (pop strings))
  1729. (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  1730. (throw 'exit
  1731. (/ (* 100.0 (+ (string-to-number (match-string 2 s))
  1732. (* 60 (string-to-number (match-string 1 s)))))
  1733. tot))))
  1734. 0))))
  1735. (defvar org-clock-loaded nil
  1736. "Was the clock file loaded?")
  1737. (defun org-clock-save ()
  1738. "Persist various clock-related data to disk.
  1739. The details of what will be saved are regulated by the variable
  1740. `org-clock-persist'."
  1741. (when (and org-clock-persist
  1742. (or org-clock-loaded
  1743. org-clock-has-been-used
  1744. (not (file-exists-p org-clock-persist-file))))
  1745. (let (b)
  1746. (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
  1747. (progn
  1748. (delete-region (point-min) (point-max))
  1749. ;;Store clock
  1750. (insert (format ";; org-persist.el - %s at %s\n"
  1751. system-name (format-time-string
  1752. (cdr org-time-stamp-formats))))
  1753. (if (and (memq org-clock-persist '(t clock))
  1754. (setq b (marker-buffer org-clock-marker))
  1755. (setq b (or (buffer-base-buffer b) b))
  1756. (buffer-live-p b)
  1757. (buffer-file-name b)
  1758. (or (not org-clock-persist-query-save)
  1759. (y-or-n-p (concat "Save current clock ("
  1760. (substring-no-properties org-clock-heading)
  1761. ") "))))
  1762. (insert "(setq resume-clock '(\""
  1763. (buffer-file-name (marker-buffer org-clock-marker))
  1764. "\" . " (int-to-string (marker-position org-clock-marker))
  1765. "))\n"))
  1766. ;; Store clocked task history. Tasks are stored reversed to make
  1767. ;; reading simpler
  1768. (when (and (memq org-clock-persist '(t history))
  1769. org-clock-history)
  1770. (insert
  1771. "(setq stored-clock-history '("
  1772. (mapconcat
  1773. (lambda (m)
  1774. (when (and (setq b (marker-buffer m))
  1775. (setq b (or (buffer-base-buffer b) b))
  1776. (buffer-live-p b)
  1777. (buffer-file-name b))
  1778. (concat "(\"" (buffer-file-name b)
  1779. "\" . " (int-to-string (marker-position m))
  1780. ")")))
  1781. (reverse org-clock-history) " ") "))\n"))
  1782. (save-buffer)
  1783. (kill-buffer (current-buffer)))))))
  1784. (defun org-clock-load ()
  1785. "Load clock-related data from disk, maybe resuming a stored clock."
  1786. (when (and org-clock-persist (not org-clock-loaded))
  1787. (let ((filename (expand-file-name org-clock-persist-file))
  1788. (org-clock-in-resume 'auto-restart)
  1789. resume-clock stored-clock-history)
  1790. (if (not (file-readable-p filename))
  1791. (message "Not restoring clock data; %s not found"
  1792. org-clock-persist-file)
  1793. (message "%s" "Restoring clock data")
  1794. (setq org-clock-loaded t)
  1795. (load-file filename)
  1796. ;; load history
  1797. (when stored-clock-history
  1798. (save-window-excursion
  1799. (mapc (lambda (task)
  1800. (if (file-exists-p (car task))
  1801. (org-clock-history-push (cdr task)
  1802. (find-file (car task)))))
  1803. stored-clock-history)))
  1804. ;; resume clock
  1805. (when (and resume-clock org-clock-persist
  1806. (file-exists-p (car resume-clock))
  1807. (or (not org-clock-persist-query-resume)
  1808. (y-or-n-p
  1809. (concat
  1810. "Resume clock ("
  1811. (with-current-buffer (find-file (car resume-clock))
  1812. (save-excursion
  1813. (goto-char (cdr resume-clock))
  1814. (org-back-to-heading t)
  1815. (and (looking-at org-complex-heading-regexp)
  1816. (match-string 4))))
  1817. ") "))))
  1818. (when (file-exists-p (car resume-clock))
  1819. (with-current-buffer (find-file (car resume-clock))
  1820. (goto-char (cdr resume-clock))
  1821. (let ((org-clock-auto-clock-resolution nil))
  1822. (org-clock-in)
  1823. (if (org-invisible-p)
  1824. (org-show-context))))))))))
  1825. ;;;###autoload
  1826. (defun org-clock-persistence-insinuate ()
  1827. "Set up hooks for clock persistence"
  1828. (add-hook 'org-mode-hook 'org-clock-load)
  1829. (add-hook 'kill-emacs-hook 'org-clock-save))
  1830. ;; Suggested bindings
  1831. (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
  1832. (provide 'org-clock)
  1833. ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
  1834. ;;; org-clock.el ends here