org-clock.el 69 KB

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