org-clock.el 73 KB

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