org-clock.el 71 KB

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