org-clock.el 92 KB

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