org-clock.el 70 KB

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