org-clock.el 69 KB

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