org-clock.el 91 KB

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