org-clock.el 70 KB

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