org-clock.el 71 KB

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