org-clock.el 73 KB

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