org-clock.el 66 KB

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