org-clock.el 74 KB

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