org-clock.el 74 KB

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