org-clock.el 96 KB

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