org-clock.el 91 KB

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