org-clock.el 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. ;;; org-clock.el --- The time clocking code for Org-mode
  2. ;; Copyright (C) 2004-2011 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: http://orgmode.org
  6. ;; Version: 7.7
  7. ;;
  8. ;; This file is part of GNU Emacs.
  9. ;;
  10. ;; GNU Emacs is free software: you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation, either version 3 of the License, or
  13. ;; (at your option) any later version.
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  20. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  21. ;;
  22. ;;; Commentary:
  23. ;; This file contains the time clocking code for Org-mode
  24. (require 'org)
  25. (require 'org-exp)
  26. ;;; Code:
  27. (eval-when-compile
  28. (require 'cl))
  29. (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
  30. (declare-function notifications-notify "notifications" (&rest params))
  31. (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
  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 org-outline-regexp)
  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. (def-edebug-spec org-with-clock-position (form body))
  620. (put 'org-with-clock-position 'lisp-indent-function 1)
  621. (defmacro org-with-clock (clock &rest forms)
  622. "Evaluate FORMS with CLOCK as the current active clock.
  623. This macro also protects the current active clock from being altered."
  624. `(org-with-clock-position ,clock
  625. (let ((org-clock-start-time (cdr ,clock))
  626. (org-clock-total-time)
  627. (org-clock-history)
  628. (org-clock-effort)
  629. (org-clock-marker (car ,clock))
  630. (org-clock-hd-marker (save-excursion
  631. (outline-back-to-heading t)
  632. (point-marker))))
  633. ,@forms)))
  634. (def-edebug-spec org-with-clock (form body))
  635. (put 'org-with-clock 'lisp-indent-function 1)
  636. (defsubst org-clock-clock-in (clock &optional resume start-time)
  637. "Clock in to the clock located by CLOCK.
  638. If necessary, clock-out of the currently active clock."
  639. (org-with-clock-position clock
  640. (let ((org-clock-in-resume (or resume org-clock-in-resume)))
  641. (org-clock-in nil start-time))))
  642. (defsubst org-clock-clock-out (clock &optional fail-quietly at-time)
  643. "Clock out of the clock located by CLOCK."
  644. (let ((temp (copy-marker (car clock)
  645. (marker-insertion-type (car clock)))))
  646. (if (org-is-active-clock clock)
  647. (org-clock-out fail-quietly at-time)
  648. (org-with-clock clock
  649. (org-clock-out fail-quietly at-time)))
  650. (setcar clock temp)))
  651. (defsubst org-clock-clock-cancel (clock)
  652. "Cancel the clock located by CLOCK."
  653. (let ((temp (copy-marker (car clock)
  654. (marker-insertion-type (car clock)))))
  655. (if (org-is-active-clock clock)
  656. (org-clock-cancel)
  657. (org-with-clock clock
  658. (org-clock-cancel)))
  659. (setcar clock temp)))
  660. (defvar org-clock-clocking-in nil)
  661. (defvar org-clock-resolving-clocks nil)
  662. (defvar org-clock-resolving-clocks-due-to-idleness nil)
  663. (defun org-clock-resolve-clock (clock resolve-to clock-out-time
  664. &optional close-p restart-p fail-quietly)
  665. "Resolve `CLOCK' given the time `RESOLVE-TO', and the present.
  666. `CLOCK' is a cons cell of the form (MARKER START-TIME)."
  667. (let ((org-clock-resolving-clocks t))
  668. (cond
  669. ((null resolve-to)
  670. (org-clock-clock-cancel clock)
  671. (if (and restart-p (not org-clock-clocking-in))
  672. (org-clock-clock-in clock)))
  673. ((eq resolve-to 'now)
  674. (if restart-p
  675. (error "RESTART-P is not valid here"))
  676. (if (or close-p org-clock-clocking-in)
  677. (org-clock-clock-out clock fail-quietly)
  678. (unless (org-is-active-clock clock)
  679. (org-clock-clock-in clock t))))
  680. ((not (time-less-p resolve-to (current-time)))
  681. (error "RESOLVE-TO must refer to a time in the past"))
  682. (t
  683. (if restart-p
  684. (error "RESTART-P is not valid here"))
  685. (org-clock-clock-out clock fail-quietly (or clock-out-time
  686. resolve-to))
  687. (unless org-clock-clocking-in
  688. (if close-p
  689. (setq org-clock-leftover-time (and (null clock-out-time)
  690. resolve-to))
  691. (org-clock-clock-in clock nil (and clock-out-time
  692. resolve-to))))))))
  693. (defun org-clock-jump-to-current-clock (&optional effective-clock)
  694. (interactive)
  695. (let ((org-clock-into-drawer (org-clock-into-drawer))
  696. (clock (or effective-clock (cons org-clock-marker
  697. org-clock-start-time))))
  698. (unless (marker-buffer (car clock))
  699. (error "No clock is currently running"))
  700. (org-with-clock clock (org-clock-goto))
  701. (with-current-buffer (marker-buffer (car clock))
  702. (goto-char (car clock))
  703. (if org-clock-into-drawer
  704. (let ((logbook
  705. (if (stringp org-clock-into-drawer)
  706. (concat ":" org-clock-into-drawer ":")
  707. ":LOGBOOK:")))
  708. (ignore-errors
  709. (outline-flag-region
  710. (save-excursion
  711. (outline-back-to-heading t)
  712. (search-forward logbook)
  713. (goto-char (match-beginning 0)))
  714. (save-excursion
  715. (outline-back-to-heading t)
  716. (search-forward logbook)
  717. (search-forward ":END:")
  718. (goto-char (match-end 0)))
  719. nil)))))))
  720. (defun org-clock-resolve (clock &optional prompt-fn last-valid fail-quietly)
  721. "Resolve an open org-mode clock.
  722. An open clock was found, with `dangling' possibly being non-nil.
  723. If this function was invoked with a prefix argument, non-dangling
  724. open clocks are ignored. The given clock requires some sort of
  725. user intervention to resolve it, either because a clock was left
  726. dangling or due to an idle timeout. The clock resolution can
  727. either be:
  728. (a) deleted, the user doesn't care about the clock
  729. (b) restarted from the current time (if no other clock is open)
  730. (c) closed, giving the clock X minutes
  731. (d) closed and then restarted
  732. (e) resumed, as if the user had never left
  733. The format of clock is (CONS MARKER START-TIME), where MARKER
  734. identifies the buffer and position the clock is open at (and
  735. thus, the heading it's under), and START-TIME is when the clock
  736. was started."
  737. (assert clock)
  738. (let* ((ch
  739. (save-window-excursion
  740. (save-excursion
  741. (unless org-clock-resolving-clocks-due-to-idleness
  742. (org-clock-jump-to-current-clock clock))
  743. (unless org-clock-resolve-expert
  744. (with-output-to-temp-buffer "*Org Clock*"
  745. (princ "Select a Clock Resolution Command:
  746. i/q/C-g Ignore this question; the same as keeping all the idle time.
  747. k/K Keep X minutes of the idle time (default is all). If this
  748. amount is less than the default, you will be clocked out
  749. that many minutes after the time that idling began, and then
  750. clocked back in at the present time.
  751. g/G Indicate that you \"got back\" X minutes ago. This is quite
  752. different from 'k': it clocks you out from the beginning of
  753. the idle period and clock you back in X minutes ago.
  754. s/S Subtract the idle time from the current clock. This is the
  755. same as keeping 0 minutes.
  756. C Cancel the open timer altogether. It will be as though you
  757. never clocked in.
  758. j/J Jump to the current clock, to make manual adjustments.
  759. For all these options, using uppercase makes your final state
  760. to be CLOCKED OUT.")))
  761. (org-fit-window-to-buffer (get-buffer-window "*Org Clock*"))
  762. (let (char-pressed)
  763. (when (featurep 'xemacs)
  764. (message (concat (funcall prompt-fn clock)
  765. " [jkKgGsScCiq]? "))
  766. (setq char-pressed (read-char-exclusive)))
  767. (while (or (null char-pressed)
  768. (and (not (memq char-pressed
  769. '(?k ?K ?g ?G ?s ?S ?C
  770. ?j ?J ?i ?q)))
  771. (or (ding) t)))
  772. (setq char-pressed
  773. (read-char (concat (funcall prompt-fn clock)
  774. " [jkKgGSscCiq]? ")
  775. nil 45)))
  776. (and (not (memq char-pressed '(?i ?q))) char-pressed)))))
  777. (default
  778. (floor (/ (org-float-time
  779. (time-subtract (current-time) last-valid)) 60)))
  780. (keep
  781. (and (memq ch '(?k ?K))
  782. (read-number "Keep how many minutes? " default)))
  783. (gotback
  784. (and (memq ch '(?g ?G))
  785. (read-number "Got back how many minutes ago? " default)))
  786. (subtractp (memq ch '(?s ?S)))
  787. (barely-started-p (< (- (org-float-time last-valid)
  788. (org-float-time (cdr clock))) 45))
  789. (start-over (and subtractp barely-started-p)))
  790. (cond
  791. ((memq ch '(?j ?J))
  792. (if (eq ch ?J)
  793. (org-clock-resolve-clock clock 'now nil t nil fail-quietly))
  794. (org-clock-jump-to-current-clock clock))
  795. ((or (null ch)
  796. (not (memq ch '(?k ?K ?g ?G ?s ?S ?C))))
  797. (message ""))
  798. (t
  799. (org-clock-resolve-clock
  800. clock (cond
  801. ((or (eq ch ?C)
  802. ;; If the time on the clock was less than a minute before
  803. ;; the user went away, and they've ask to subtract all the
  804. ;; time...
  805. start-over)
  806. nil)
  807. ((or subtractp
  808. (and gotback (= gotback 0)))
  809. last-valid)
  810. ((or (and keep (= keep default))
  811. (and gotback (= gotback default)))
  812. 'now)
  813. (keep
  814. (time-add last-valid (seconds-to-time (* 60 keep))))
  815. (gotback
  816. (time-subtract (current-time)
  817. (seconds-to-time (* 60 gotback))))
  818. (t
  819. (error "Unexpected, please report this as a bug")))
  820. (and gotback last-valid)
  821. (memq ch '(?K ?G ?S))
  822. (and start-over
  823. (not (memq ch '(?K ?G ?S ?C))))
  824. fail-quietly)))))
  825. (defun org-resolve-clocks (&optional only-dangling-p prompt-fn last-valid)
  826. "Resolve all currently open org-mode clocks.
  827. If `only-dangling-p' is non-nil, only ask to resolve dangling
  828. \(i.e., not currently open and valid) clocks."
  829. (interactive "P")
  830. (unless org-clock-resolving-clocks
  831. (let ((org-clock-resolving-clocks t))
  832. (dolist (file (org-files-list))
  833. (let ((clocks (org-find-open-clocks file)))
  834. (dolist (clock clocks)
  835. (let ((dangling (or (not (org-clock-is-active))
  836. (/= (car clock) org-clock-marker))))
  837. (if (or (not only-dangling-p) dangling)
  838. (org-clock-resolve
  839. clock
  840. (or prompt-fn
  841. (function
  842. (lambda (clock)
  843. (format
  844. "Dangling clock started %d mins ago"
  845. (floor
  846. (/ (- (org-float-time (current-time))
  847. (org-float-time (cdr clock))) 60))))))
  848. (or last-valid
  849. (cdr clock)))))))))))
  850. (defun org-emacs-idle-seconds ()
  851. "Return the current Emacs idle time in seconds, or nil if not idle."
  852. (let ((idle-time (current-idle-time)))
  853. (if idle-time
  854. (org-float-time idle-time)
  855. 0)))
  856. (defun org-mac-idle-seconds ()
  857. "Return the current Mac idle time in seconds."
  858. (string-to-number (shell-command-to-string "ioreg -c IOHIDSystem | perl -ane 'if (/Idle/) {$idle=(pop @F)/1000000000; print $idle; last}'")))
  859. (defun org-x11-idle-seconds ()
  860. "Return the current X11 idle time in seconds."
  861. (/ (string-to-number (shell-command-to-string "x11idle")) 1000))
  862. (defun org-user-idle-seconds ()
  863. "Return the number of seconds the user has been idle for.
  864. This routine returns a floating point number."
  865. (cond
  866. ((eq system-type 'darwin)
  867. (org-mac-idle-seconds))
  868. ((eq window-system 'x)
  869. (org-x11-idle-seconds))
  870. (t
  871. (org-emacs-idle-seconds))))
  872. (defvar org-clock-user-idle-seconds)
  873. (defun org-resolve-clocks-if-idle ()
  874. "Resolve all currently open org-mode clocks.
  875. This is performed after `org-clock-idle-time' minutes, to check
  876. if the user really wants to stay clocked in after being idle for
  877. so long."
  878. (when (and org-clock-idle-time (not org-clock-resolving-clocks)
  879. org-clock-marker)
  880. (let* ((org-clock-user-idle-seconds (org-user-idle-seconds))
  881. (org-clock-user-idle-start
  882. (time-subtract (current-time)
  883. (seconds-to-time org-clock-user-idle-seconds)))
  884. (org-clock-resolving-clocks-due-to-idleness t))
  885. (if (> org-clock-user-idle-seconds (* 60 org-clock-idle-time))
  886. (org-clock-resolve
  887. (cons org-clock-marker
  888. org-clock-start-time)
  889. (function
  890. (lambda (clock)
  891. (format "Clocked in & idle for %.1f mins"
  892. (/ (org-float-time
  893. (time-subtract (current-time)
  894. org-clock-user-idle-start))
  895. 60.0))))
  896. org-clock-user-idle-start)))))
  897. (defvar org-clock-current-task nil
  898. "Task currently clocked in.")
  899. (defun org-clock-set-current ()
  900. "Set `org-clock-current-task' to the task currently clocked in."
  901. (setq org-clock-current-task (nth 4 (org-heading-components))))
  902. (defun org-clock-delete-current ()
  903. "Reset `org-clock-current-task' to nil."
  904. (setq org-clock-current-task nil))
  905. (defun org-clock-in (&optional select start-time)
  906. "Start the clock on the current item.
  907. If necessary, clock-out of the currently active clock.
  908. With a prefix argument SELECT (\\[universal-argument]), offer a list of \
  909. recently clocked tasks to
  910. clock into. When SELECT is \\[universal-argument] \\[universal-argument], \
  911. clock into the current task and mark
  912. is as the default task, a special task that will always be offered in
  913. the clocking selection, associated with the letter `d'."
  914. (interactive "P")
  915. (setq org-clock-notification-was-shown nil)
  916. (catch 'abort
  917. (let ((interrupting (and (not org-clock-resolving-clocks-due-to-idleness)
  918. (org-clocking-p)))
  919. ts selected-task target-pos (msg-extra "")
  920. (leftover (and (not org-clock-resolving-clocks)
  921. org-clock-leftover-time)))
  922. (when (and org-clock-auto-clock-resolution
  923. (or (not interrupting)
  924. (eq t org-clock-auto-clock-resolution))
  925. (not org-clock-clocking-in)
  926. (not org-clock-resolving-clocks))
  927. (setq org-clock-leftover-time nil)
  928. (let ((org-clock-clocking-in t))
  929. (org-resolve-clocks))) ; check if any clocks are dangling
  930. (when (equal select '(4))
  931. (setq selected-task (org-clock-select-task "Clock-in on task: "))
  932. (if selected-task
  933. (setq selected-task (copy-marker selected-task))
  934. (error "Abort")))
  935. (when (equal select '(16))
  936. ;; Mark as default clocking task
  937. (org-clock-mark-default-task))
  938. (when interrupting
  939. ;; We are interrupting the clocking of a different task.
  940. ;; Save a marker to this task, so that we can go back.
  941. ;; First check if we are trying to clock into the same task!
  942. (when (save-excursion
  943. (unless selected-task
  944. (org-back-to-heading t))
  945. (and (equal (marker-buffer org-clock-hd-marker)
  946. (if selected-task
  947. (marker-buffer selected-task)
  948. (current-buffer)))
  949. (= (marker-position org-clock-hd-marker)
  950. (if selected-task
  951. (marker-position selected-task)
  952. (point)))
  953. (equal org-clock-current-task (nth 4 (org-heading-components)))))
  954. (message "Clock continues in \"%s\"" org-clock-heading)
  955. (throw 'abort nil))
  956. (move-marker org-clock-interrupted-task
  957. (marker-position org-clock-marker)
  958. (marker-buffer org-clock-marker))
  959. (let ((org-clock-clocking-in t))
  960. (org-clock-out t)))
  961. ;; Clock in at which position?
  962. (setq target-pos
  963. (if (and (eobp) (not (org-on-heading-p)))
  964. (point-at-bol 0)
  965. (point)))
  966. (run-hooks 'org-clock-in-prepare-hook)
  967. (save-excursion
  968. (when (and selected-task (marker-buffer selected-task))
  969. ;; There is a selected task, move to the correct buffer
  970. ;; and set the new target position.
  971. (set-buffer (org-base-buffer (marker-buffer selected-task)))
  972. (setq target-pos (marker-position selected-task))
  973. (move-marker selected-task nil))
  974. (save-excursion
  975. (save-restriction
  976. (widen)
  977. (goto-char target-pos)
  978. (org-back-to-heading t)
  979. (or interrupting (move-marker org-clock-interrupted-task nil))
  980. (org-clock-history-push)
  981. (org-clock-set-current)
  982. (cond ((functionp org-clock-in-switch-to-state)
  983. (looking-at org-complex-heading-regexp)
  984. (let ((newstate (funcall org-clock-in-switch-to-state
  985. (match-string 2))))
  986. (if newstate (org-todo newstate))))
  987. ((and org-clock-in-switch-to-state
  988. (not (looking-at (concat org-outline-regexp "[ \t]*"
  989. org-clock-in-switch-to-state
  990. "\\>"))))
  991. (org-todo org-clock-in-switch-to-state)))
  992. (setq org-clock-heading-for-remember
  993. (and (looking-at org-complex-heading-regexp)
  994. (match-end 4)
  995. (org-trim (buffer-substring (match-end 1)
  996. (match-end 4)))))
  997. (setq org-clock-heading
  998. (cond ((and org-clock-heading-function
  999. (functionp org-clock-heading-function))
  1000. (funcall org-clock-heading-function))
  1001. ((looking-at org-complex-heading-regexp)
  1002. (replace-regexp-in-string
  1003. "\\[\\[.*?\\]\\[\\(.*?\\)\\]\\]" "\\1"
  1004. (match-string 4)))
  1005. (t "???")))
  1006. (setq org-clock-heading (org-propertize org-clock-heading
  1007. 'face nil))
  1008. (org-clock-find-position org-clock-in-resume)
  1009. (cond
  1010. ((and org-clock-in-resume
  1011. (looking-at
  1012. (concat "^[ \t]* " org-clock-string
  1013. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1014. " +\\sw+\.? +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")))
  1015. (message "Matched %s" (match-string 1))
  1016. (setq ts (concat "[" (match-string 1) "]"))
  1017. (goto-char (match-end 1))
  1018. (setq org-clock-start-time
  1019. (apply 'encode-time
  1020. (org-parse-time-string (match-string 1))))
  1021. (setq org-clock-effort (org-get-effort))
  1022. (setq org-clock-total-time (org-clock-sum-current-item
  1023. (org-clock-get-sum-start))))
  1024. ((eq org-clock-in-resume 'auto-restart)
  1025. ;; called from org-clock-load during startup,
  1026. ;; do not interrupt, but warn!
  1027. (message "Cannot restart clock because task does not contain unfinished clock")
  1028. (ding)
  1029. (sit-for 2)
  1030. (throw 'abort nil))
  1031. (t
  1032. (insert-before-markers "\n")
  1033. (backward-char 1)
  1034. (org-indent-line-function)
  1035. (when (and (save-excursion
  1036. (end-of-line 0)
  1037. (org-in-item-p)))
  1038. (beginning-of-line 1)
  1039. (org-indent-line-to (- (org-get-indentation) 2)))
  1040. (insert org-clock-string " ")
  1041. (setq org-clock-effort (org-get-effort))
  1042. (setq org-clock-total-time (org-clock-sum-current-item
  1043. (org-clock-get-sum-start)))
  1044. (setq org-clock-start-time
  1045. (or (and leftover
  1046. (y-or-n-p
  1047. (format
  1048. "You stopped another clock %d mins ago; start this one from then? "
  1049. (/ (- (org-float-time (current-time))
  1050. (org-float-time leftover)) 60)))
  1051. leftover)
  1052. start-time
  1053. (current-time)))
  1054. (setq ts (org-insert-time-stamp org-clock-start-time
  1055. 'with-hm 'inactive))))
  1056. (move-marker org-clock-marker (point) (buffer-base-buffer))
  1057. (move-marker org-clock-hd-marker
  1058. (save-excursion (org-back-to-heading t) (point))
  1059. (buffer-base-buffer))
  1060. (setq org-clock-has-been-used t)
  1061. (or global-mode-string (setq global-mode-string '("")))
  1062. (or (memq 'org-mode-line-string global-mode-string)
  1063. (setq global-mode-string
  1064. (append global-mode-string '(org-mode-line-string))))
  1065. (org-clock-update-mode-line)
  1066. (when org-clock-mode-line-timer
  1067. (cancel-timer org-clock-mode-line-timer)
  1068. (setq org-clock-mode-line-timer nil))
  1069. (setq org-clock-mode-line-timer
  1070. (run-with-timer org-clock-update-period
  1071. org-clock-update-period
  1072. 'org-clock-update-mode-line))
  1073. (when org-clock-idle-timer
  1074. (cancel-timer org-clock-idle-timer)
  1075. (setq org-clock-idle-timer nil))
  1076. (setq org-clock-idle-timer
  1077. (run-with-timer 60 60 'org-resolve-clocks-if-idle))
  1078. (message "Clock starts at %s - %s" ts msg-extra)
  1079. (run-hooks 'org-clock-in-hook)))))))
  1080. (defun org-clock-mark-default-task ()
  1081. "Mark current task as default task."
  1082. (interactive)
  1083. (save-excursion
  1084. (org-back-to-heading t)
  1085. (move-marker org-clock-default-task (point))))
  1086. (defvar msg-extra)
  1087. (defun org-clock-get-sum-start ()
  1088. "Return the time from which clock times should be counted.
  1089. This is for the currently running clock as it is displayed
  1090. in the mode line. This function looks at the properties
  1091. LAST_REPEAT and in particular CLOCK_MODELINE_TOTAL and the
  1092. corresponding variable `org-clock-modeline-total' and then
  1093. decides which time to use."
  1094. (let ((cmt (or (org-entry-get nil "CLOCK_MODELINE_TOTAL")
  1095. (symbol-name org-clock-modeline-total)))
  1096. (lr (org-entry-get nil "LAST_REPEAT")))
  1097. (cond
  1098. ((equal cmt "current")
  1099. (setq msg-extra "showing time in current clock instance")
  1100. (current-time))
  1101. ((equal cmt "today")
  1102. (setq msg-extra "showing today's task time.")
  1103. (let* ((dt (decode-time (current-time))))
  1104. (setq dt (append (list 0 0 0) (nthcdr 3 dt)))
  1105. (if org-extend-today-until
  1106. (setf (nth 2 dt) org-extend-today-until))
  1107. (apply 'encode-time dt)))
  1108. ((or (equal cmt "all")
  1109. (and (or (not cmt) (equal cmt "auto"))
  1110. (not lr)))
  1111. (setq msg-extra "showing entire task time.")
  1112. nil)
  1113. ((or (equal cmt "repeat")
  1114. (and (or (not cmt) (equal cmt "auto"))
  1115. lr))
  1116. (setq msg-extra "showing task time since last repeat.")
  1117. (if (not lr)
  1118. nil
  1119. (org-time-string-to-time lr)))
  1120. (t nil))))
  1121. (defun org-clock-find-position (find-unclosed)
  1122. "Find the location where the next clock line should be inserted.
  1123. When FIND-UNCLOSED is non-nil, first check if there is an unclosed clock
  1124. line and position cursor in that line."
  1125. (org-back-to-heading t)
  1126. (catch 'exit
  1127. (let* ((org-clock-into-drawer (org-clock-into-drawer))
  1128. (beg (save-excursion
  1129. (beginning-of-line 2)
  1130. (or (bolp) (newline))
  1131. (point)))
  1132. (end (progn (outline-next-heading) (point)))
  1133. (re (concat "^[ \t]*" org-clock-string))
  1134. (cnt 0)
  1135. (drawer (if (stringp org-clock-into-drawer)
  1136. org-clock-into-drawer "LOGBOOK"))
  1137. first last ind-last)
  1138. (goto-char beg)
  1139. (when (and find-unclosed
  1140. (re-search-forward
  1141. (concat "^[ \t]* " org-clock-string
  1142. " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}"
  1143. " +\\sw+ +[012][0-9]:[0-5][0-9]\\)\\][ \t]*$")
  1144. end t))
  1145. (beginning-of-line 1)
  1146. (throw 'exit t))
  1147. (when (eobp) (newline) (setq end (max (point) end)))
  1148. (when (re-search-forward (concat "^[ \t]*:" drawer ":") end t)
  1149. ;; we seem to have a CLOCK drawer, so go there.
  1150. (beginning-of-line 2)
  1151. (or org-log-states-order-reversed
  1152. (and (re-search-forward org-property-end-re nil t)
  1153. (goto-char (match-beginning 0))))
  1154. (throw 'exit t))
  1155. ;; Lets count the CLOCK lines
  1156. (goto-char beg)
  1157. (while (re-search-forward re end t)
  1158. (setq first (or first (match-beginning 0))
  1159. last (match-beginning 0)
  1160. cnt (1+ cnt)))
  1161. (when (and (integerp org-clock-into-drawer)
  1162. last
  1163. (>= (1+ cnt) org-clock-into-drawer))
  1164. ;; Wrap current entries into a new drawer
  1165. (goto-char last)
  1166. (setq ind-last (org-get-indentation))
  1167. (beginning-of-line 2)
  1168. (if (and (>= (org-get-indentation) ind-last)
  1169. (org-at-item-p))
  1170. (when (and (>= (org-get-indentation) ind-last)
  1171. (org-at-item-p))
  1172. (let ((struct (org-list-struct)))
  1173. (goto-char (org-list-get-bottom-point struct)))))
  1174. (insert ":END:\n")
  1175. (beginning-of-line 0)
  1176. (org-indent-line-to ind-last)
  1177. (goto-char first)
  1178. (insert ":" drawer ":\n")
  1179. (beginning-of-line 0)
  1180. (org-indent-line-function)
  1181. (org-flag-drawer t)
  1182. (beginning-of-line 2)
  1183. (or org-log-states-order-reversed
  1184. (and (re-search-forward org-property-end-re nil t)
  1185. (goto-char (match-beginning 0))))
  1186. (throw 'exit nil))
  1187. (goto-char beg)
  1188. (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1189. (not (equal (match-string 1) org-clock-string)))
  1190. ;; Planning info, skip to after it
  1191. (beginning-of-line 2)
  1192. (or (bolp) (newline)))
  1193. (when (or (eq org-clock-into-drawer t)
  1194. (stringp org-clock-into-drawer)
  1195. (and (integerp org-clock-into-drawer)
  1196. (< org-clock-into-drawer 2)))
  1197. (insert ":" drawer ":\n:END:\n")
  1198. (beginning-of-line -1)
  1199. (org-indent-line-function)
  1200. (org-flag-drawer t)
  1201. (beginning-of-line 2)
  1202. (org-indent-line-function)
  1203. (beginning-of-line)
  1204. (or org-log-states-order-reversed
  1205. (and (re-search-forward org-property-end-re nil t)
  1206. (goto-char (match-beginning 0))))))))
  1207. (defun org-clock-out (&optional fail-quietly at-time)
  1208. "Stop the currently running clock.
  1209. If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
  1210. (interactive)
  1211. (catch 'exit
  1212. (when (not (org-clocking-p))
  1213. (setq global-mode-string
  1214. (delq 'org-mode-line-string global-mode-string))
  1215. (force-mode-line-update)
  1216. (if fail-quietly (throw 'exit t) (error "No active clock")))
  1217. (let (ts te s h m remove)
  1218. (save-excursion ; Do not replace this with `with-current-buffer'.
  1219. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1220. (save-restriction
  1221. (widen)
  1222. (goto-char org-clock-marker)
  1223. (beginning-of-line 1)
  1224. (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
  1225. (equal (match-string 1) org-clock-string))
  1226. (setq ts (match-string 2))
  1227. (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
  1228. (goto-char (match-end 0))
  1229. (delete-region (point) (point-at-eol))
  1230. (insert "--")
  1231. (setq te (org-insert-time-stamp (or at-time (current-time))
  1232. 'with-hm 'inactive))
  1233. (setq s (- (org-float-time (apply 'encode-time (org-parse-time-string te)))
  1234. (org-float-time (apply 'encode-time (org-parse-time-string ts))))
  1235. h (floor (/ s 3600))
  1236. s (- s (* 3600 h))
  1237. m (floor (/ s 60))
  1238. s (- s (* 60 s)))
  1239. (insert " => " (format "%2d:%02d" h m))
  1240. (when (setq remove (and org-clock-out-remove-zero-time-clocks
  1241. (= (+ h m) 0)))
  1242. (beginning-of-line 1)
  1243. (delete-region (point) (point-at-eol))
  1244. (and (looking-at "\n") (> (point-max) (1+ (point)))
  1245. (delete-char 1)))
  1246. (move-marker org-clock-marker nil)
  1247. (move-marker org-clock-hd-marker nil)
  1248. (when org-log-note-clock-out
  1249. (org-add-log-setup 'clock-out nil nil nil nil
  1250. (concat "# Task: " (org-get-heading t) "\n\n")))
  1251. (when org-clock-mode-line-timer
  1252. (cancel-timer org-clock-mode-line-timer)
  1253. (setq org-clock-mode-line-timer nil))
  1254. (when org-clock-idle-timer
  1255. (cancel-timer org-clock-idle-timer)
  1256. (setq org-clock-idle-timer nil))
  1257. (setq global-mode-string
  1258. (delq 'org-mode-line-string global-mode-string))
  1259. (when org-clock-out-switch-to-state
  1260. (save-excursion
  1261. (org-back-to-heading t)
  1262. (let ((org-inhibit-logging t)
  1263. (org-clock-out-when-done nil))
  1264. (cond
  1265. ((functionp org-clock-out-switch-to-state)
  1266. (looking-at org-complex-heading-regexp)
  1267. (let ((newstate (funcall org-clock-out-switch-to-state
  1268. (match-string 2))))
  1269. (if newstate (org-todo newstate))))
  1270. ((and org-clock-out-switch-to-state
  1271. (not (looking-at (concat org-outline-regexp "[ \t]*"
  1272. org-clock-out-switch-to-state
  1273. "\\>"))))
  1274. (org-todo org-clock-out-switch-to-state))))))
  1275. (force-mode-line-update)
  1276. (message (concat "Clock stopped at %s after HH:MM = " org-time-clocksum-format "%s") te h m
  1277. (if remove " => LINE REMOVED" ""))
  1278. (run-hooks 'org-clock-out-hook)
  1279. (org-clock-delete-current))))))
  1280. (add-hook 'org-clock-out-hook 'org-clock-remove-empty-clock-drawer)
  1281. (defun org-clock-remove-empty-clock-drawer nil
  1282. "Remove empty clock drawer in the current subtree."
  1283. (let* ((olid (or (org-entry-get (point) "LOG_INTO_DRAWER")
  1284. org-log-into-drawer))
  1285. (clock-drawer (if (eq t olid) "LOGBOOK" olid))
  1286. (end (save-excursion (org-end-of-subtree t t))))
  1287. (when clock-drawer
  1288. (save-excursion
  1289. (org-back-to-heading t)
  1290. (while (search-forward clock-drawer end t)
  1291. (goto-char (match-beginning 0))
  1292. (org-remove-empty-drawer-at clock-drawer (point))
  1293. (forward-line 1))))))
  1294. (defun org-at-clock-log-p nil
  1295. "Is the cursor on the clock log line?"
  1296. (save-excursion
  1297. (move-beginning-of-line 1)
  1298. (looking-at "^[ \t]*CLOCK:")))
  1299. (defun org-clock-timestamps-up nil
  1300. "Increase CLOCK timestamps at cursor."
  1301. (interactive)
  1302. (org-clock-timestamps-change 'up))
  1303. (defun org-clock-timestamps-down nil
  1304. "Increase CLOCK timestamps at cursor."
  1305. (interactive)
  1306. (org-clock-timestamps-change 'down))
  1307. (defun org-clock-timestamps-change (updown)
  1308. "Change CLOCK timestamps synchronously at cursor.
  1309. UPDOWN tells whether to change 'up or 'down."
  1310. (setq org-ts-what nil)
  1311. (when (org-at-timestamp-p t)
  1312. (let ((tschange (if (eq updown 'up) 'org-timestamp-up
  1313. 'org-timestamp-down))
  1314. ts1 begts1 ts2 begts2 updatets1 tdiff)
  1315. (save-excursion
  1316. (move-beginning-of-line 1)
  1317. (re-search-forward org-ts-regexp3 nil t)
  1318. (setq ts1 (match-string 0) begts1 (match-beginning 0))
  1319. (when (re-search-forward org-ts-regexp3 nil t)
  1320. (setq ts2 (match-string 0) begts2 (match-beginning 0))))
  1321. ;; Are we on the second timestamp?
  1322. (if (<= begts2 (point)) (setq updatets1 t))
  1323. (if (not ts2)
  1324. ;; fall back on org-timestamp-up if there is only one
  1325. (funcall tschange)
  1326. ;; setq this so that (boundp 'org-ts-what is non-nil)
  1327. (funcall tschange)
  1328. (let ((ts (if updatets1 ts2 ts1))
  1329. (begts (if updatets1 begts1 begts2)))
  1330. (setq tdiff
  1331. (subtract-time
  1332. (org-time-string-to-time org-last-changed-timestamp)
  1333. (org-time-string-to-time ts)))
  1334. (save-excursion
  1335. (goto-char begts)
  1336. (org-timestamp-change
  1337. (round (/ (org-float-time tdiff)
  1338. (cond ((eq org-ts-what 'minute) 60)
  1339. ((eq org-ts-what 'hour) 3600)
  1340. ((eq org-ts-what 'day) (* 24 3600))
  1341. ((eq org-ts-what 'month) (* 24 3600 31))
  1342. ((eq org-ts-what 'year) (* 24 3600 365.2)))))
  1343. org-ts-what 'updown)))))))
  1344. (defun org-clock-cancel ()
  1345. "Cancel the running clock by removing the start timestamp."
  1346. (interactive)
  1347. (when (not (org-clocking-p))
  1348. (setq global-mode-string
  1349. (delq 'org-mode-line-string global-mode-string))
  1350. (force-mode-line-update)
  1351. (error "No active clock"))
  1352. (save-excursion ; Do not replace this with `with-current-buffer'.
  1353. (with-no-warnings (set-buffer (org-clocking-buffer)))
  1354. (goto-char org-clock-marker)
  1355. (delete-region (1- (point-at-bol)) (point-at-eol))
  1356. ;; Just in case, remove any empty LOGBOOK left over
  1357. (org-remove-empty-drawer-at "LOGBOOK" (point)))
  1358. (move-marker org-clock-marker nil)
  1359. (move-marker org-clock-hd-marker nil)
  1360. (setq global-mode-string
  1361. (delq 'org-mode-line-string global-mode-string))
  1362. (force-mode-line-update)
  1363. (message "Clock canceled")
  1364. (run-hooks 'org-clock-cancel-hook))
  1365. (defun org-clock-goto (&optional select)
  1366. "Go to the currently clocked-in entry, or to the most recently clocked one.
  1367. With prefix arg SELECT, offer recently clocked tasks for selection."
  1368. (interactive "@P")
  1369. (let* ((recent nil)
  1370. (m (cond
  1371. (select
  1372. (or (org-clock-select-task "Select task to go to: ")
  1373. (error "No task selected")))
  1374. ((org-clocking-p) org-clock-marker)
  1375. ((and org-clock-goto-may-find-recent-task
  1376. (car org-clock-history)
  1377. (marker-buffer (car org-clock-history)))
  1378. (setq recent t)
  1379. (car org-clock-history))
  1380. (t (error "No active or recent clock task")))))
  1381. (org-pop-to-buffer-same-window (marker-buffer m))
  1382. (if (or (< m (point-min)) (> m (point-max))) (widen))
  1383. (goto-char m)
  1384. (org-show-entry)
  1385. (org-back-to-heading t)
  1386. (org-cycle-hide-drawers 'children)
  1387. (recenter)
  1388. (org-reveal)
  1389. (if recent
  1390. (message "No running clock, this is the most recently clocked task"))
  1391. (run-hooks 'org-clock-goto-hook)))
  1392. (defvar org-clock-file-total-minutes nil
  1393. "Holds the file total time in minutes, after a call to `org-clock-sum'.")
  1394. (make-variable-buffer-local 'org-clock-file-total-minutes)
  1395. (defun org-clock-sum (&optional tstart tend headline-filter)
  1396. "Sum the times for each subtree.
  1397. Puts the resulting times in minutes as a text property on each headline.
  1398. TSTART and TEND can mark a time range to be considered. HEADLINE-FILTER is a
  1399. zero-arg function that, if specified, is called for each headline in the time
  1400. range with point at the headline. Headlines for which HEADLINE-FILTER returns
  1401. nil are excluded from the clock summation."
  1402. (interactive)
  1403. (let* ((bmp (buffer-modified-p))
  1404. (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
  1405. org-clock-string
  1406. "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
  1407. (lmax 30)
  1408. (ltimes (make-vector lmax 0))
  1409. (t1 0)
  1410. (level 0)
  1411. ts te dt
  1412. time)
  1413. (if (stringp tstart) (setq tstart (org-time-string-to-seconds tstart)))
  1414. (if (stringp tend) (setq tend (org-time-string-to-seconds tend)))
  1415. (if (consp tstart) (setq tstart (org-float-time tstart)))
  1416. (if (consp tend) (setq tend (org-float-time tend)))
  1417. (remove-text-properties (point-min) (point-max)
  1418. '(:org-clock-minutes t
  1419. :org-clock-force-headline-inclusion t))
  1420. (save-excursion
  1421. (goto-char (point-max))
  1422. (while (re-search-backward re nil t)
  1423. (cond
  1424. ((match-end 2)
  1425. ;; Two time stamps
  1426. (setq ts (match-string 2)
  1427. te (match-string 3)
  1428. ts (org-float-time
  1429. (apply 'encode-time (org-parse-time-string ts)))
  1430. te (org-float-time
  1431. (apply 'encode-time (org-parse-time-string te)))
  1432. ts (if tstart (max ts tstart) ts)
  1433. te (if tend (min te tend) te)
  1434. dt (- te ts)
  1435. t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
  1436. ((match-end 4)
  1437. ;; A naked time
  1438. (setq t1 (+ t1 (string-to-number (match-string 5))
  1439. (* 60 (string-to-number (match-string 4))))))
  1440. (t ;; A headline
  1441. ;; Add the currently clocking item time to the total
  1442. (when (and org-clock-report-include-clocking-task
  1443. (equal (org-clocking-buffer) (current-buffer))
  1444. (equal (marker-position org-clock-hd-marker) (point))
  1445. tstart
  1446. tend
  1447. (>= (org-float-time org-clock-start-time) tstart)
  1448. (<= (org-float-time org-clock-start-time) tend))
  1449. (let ((time (floor (- (org-float-time)
  1450. (org-float-time org-clock-start-time)) 60)))
  1451. (setq t1 (+ t1 time))))
  1452. (let* ((headline-forced
  1453. (get-text-property (point)
  1454. :org-clock-force-headline-inclusion))
  1455. (headline-included
  1456. (or (null headline-filter)
  1457. (save-excursion
  1458. (save-match-data (funcall headline-filter))))))
  1459. (setq level (- (match-end 1) (match-beginning 1)))
  1460. (when (or (> t1 0) (> (aref ltimes level) 0))
  1461. (when (or headline-included headline-forced)
  1462. (if headline-included
  1463. (loop for l from 0 to level do
  1464. (aset ltimes l (+ (aref ltimes l) t1))))
  1465. (setq time (aref ltimes level))
  1466. (goto-char (match-beginning 0))
  1467. (put-text-property (point) (point-at-eol) :org-clock-minutes time)
  1468. (if headline-filter
  1469. (save-excursion
  1470. (save-match-data
  1471. (while
  1472. (> (funcall outline-level) 1)
  1473. (outline-up-heading 1 t)
  1474. (put-text-property
  1475. (point) (point-at-eol)
  1476. :org-clock-force-headline-inclusion t))))))
  1477. (setq t1 0)
  1478. (loop for l from level to (1- lmax) do
  1479. (aset ltimes l 0)))))))
  1480. (setq org-clock-file-total-minutes (aref ltimes 0)))
  1481. (set-buffer-modified-p bmp)))
  1482. (defun org-clock-sum-current-item (&optional tstart)
  1483. "Return time, clocked on current item in total."
  1484. (save-excursion
  1485. (save-restriction
  1486. (org-narrow-to-subtree)
  1487. (org-clock-sum tstart)
  1488. org-clock-file-total-minutes)))
  1489. (defun org-clock-display (&optional total-only)
  1490. "Show subtree times in the entire buffer.
  1491. If TOTAL-ONLY is non-nil, only show the total time for the entire file
  1492. in the echo area.
  1493. Use \\[org-clock-remove-overlays] to remove the subtree times."
  1494. (interactive)
  1495. (org-clock-remove-overlays)
  1496. (let (time h m p)
  1497. (org-clock-sum)
  1498. (unless total-only
  1499. (save-excursion
  1500. (goto-char (point-min))
  1501. (while (or (and (equal (setq p (point)) (point-min))
  1502. (get-text-property p :org-clock-minutes))
  1503. (setq p (next-single-property-change
  1504. (point) :org-clock-minutes)))
  1505. (goto-char p)
  1506. (when (setq time (get-text-property p :org-clock-minutes))
  1507. (org-clock-put-overlay time (funcall outline-level))))
  1508. (setq h (/ org-clock-file-total-minutes 60)
  1509. m (- org-clock-file-total-minutes (* 60 h)))
  1510. ;; Arrange to remove the overlays upon next change.
  1511. (when org-remove-highlights-with-change
  1512. (org-add-hook 'before-change-functions 'org-clock-remove-overlays
  1513. nil 'local))))
  1514. (if org-time-clocksum-use-fractional
  1515. (message (concat "Total file time: " org-time-clocksum-fractional-format
  1516. " (%d hours and %d minutes)")
  1517. (/ (+ (* h 60.0) m) 60.0) h m)
  1518. (message (concat "Total file time: " org-time-clocksum-format
  1519. " (%d hours and %d minutes)") h m h m))))
  1520. (defvar org-clock-overlays nil)
  1521. (make-variable-buffer-local 'org-clock-overlays)
  1522. (defun org-clock-put-overlay (time &optional level)
  1523. "Put an overlays on the current line, displaying TIME.
  1524. If LEVEL is given, prefix time with a corresponding number of stars.
  1525. This creates a new overlay and stores it in `org-clock-overlays', so that it
  1526. will be easy to remove."
  1527. (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
  1528. (l (if level (org-get-valid-level level 0) 0))
  1529. (fmt (concat "%s " (if org-time-clocksum-use-fractional
  1530. org-time-clocksum-fractional-format
  1531. org-time-clocksum-format) "%s"))
  1532. (off 0)
  1533. ov tx)
  1534. (org-move-to-column c)
  1535. (unless (eolp) (skip-chars-backward "^ \t"))
  1536. (skip-chars-backward " \t")
  1537. (setq ov (make-overlay (1- (point)) (point-at-eol))
  1538. tx (concat (buffer-substring (1- (point)) (point))
  1539. (make-string (+ off (max 0 (- c (current-column)))) ?.)
  1540. (org-add-props (if org-time-clocksum-use-fractional
  1541. (format fmt
  1542. (make-string l ?*)
  1543. (/ (+ (* h 60.0) m) 60.0)
  1544. (make-string (- 16 l) ?\ ))
  1545. (format fmt
  1546. (make-string l ?*) h m
  1547. (make-string (- 16 l) ?\ )))
  1548. (list 'face 'org-clock-overlay))
  1549. ""))
  1550. (if (not (featurep 'xemacs))
  1551. (overlay-put ov 'display tx)
  1552. (overlay-put ov 'invisible t)
  1553. (overlay-put ov 'end-glyph (make-glyph tx)))
  1554. (push ov org-clock-overlays)))
  1555. (defun org-clock-remove-overlays (&optional beg end noremove)
  1556. "Remove the occur highlights from the buffer.
  1557. BEG and END are ignored. If NOREMOVE is nil, remove this function
  1558. from the `before-change-functions' in the current buffer."
  1559. (interactive)
  1560. (unless org-inhibit-highlight-removal
  1561. (mapc 'delete-overlay org-clock-overlays)
  1562. (setq org-clock-overlays nil)
  1563. (unless noremove
  1564. (remove-hook 'before-change-functions
  1565. 'org-clock-remove-overlays 'local))))
  1566. (defvar state) ;; dynamically scoped into this function
  1567. (defun org-clock-out-if-current ()
  1568. "Clock out if the current entry contains the running clock.
  1569. This is used to stop the clock after a TODO entry is marked DONE,
  1570. and is only done if the variable `org-clock-out-when-done' is not nil."
  1571. (when (and org-clock-out-when-done
  1572. (or (and (eq t org-clock-out-when-done)
  1573. (member state org-done-keywords))
  1574. (and (listp org-clock-out-when-done)
  1575. (member state org-clock-out-when-done)))
  1576. (equal (or (buffer-base-buffer (org-clocking-buffer))
  1577. (org-clocking-buffer))
  1578. (or (buffer-base-buffer (current-buffer))
  1579. (current-buffer)))
  1580. (< (point) org-clock-marker)
  1581. (> (save-excursion (outline-next-heading) (point))
  1582. org-clock-marker))
  1583. ;; Clock out, but don't accept a logging message for this.
  1584. (let ((org-log-note-clock-out nil)
  1585. (org-clock-out-switch-to-state nil))
  1586. (org-clock-out))))
  1587. (add-hook 'org-after-todo-state-change-hook
  1588. 'org-clock-out-if-current)
  1589. ;;;###autoload
  1590. (defun org-get-clocktable (&rest props)
  1591. "Get a formatted clocktable with parameters according to PROPS.
  1592. The table is created in a temporary buffer, fully formatted and
  1593. fontified, and then returned."
  1594. ;; Set the defaults
  1595. (setq props (plist-put props :name "clocktable"))
  1596. (unless (plist-member props :maxlevel)
  1597. (setq props (plist-put props :maxlevel 2)))
  1598. (unless (plist-member props :scope)
  1599. (setq props (plist-put props :scope 'agenda)))
  1600. (with-temp-buffer
  1601. (org-mode)
  1602. (org-create-dblock props)
  1603. (org-update-dblock)
  1604. (font-lock-fontify-buffer)
  1605. (forward-line 2)
  1606. (buffer-substring (point) (progn
  1607. (re-search-forward "^[ \t]*#\\+END" nil t)
  1608. (point-at-bol)))))
  1609. (defun org-clock-report (&optional arg)
  1610. "Create a table containing a report about clocked time.
  1611. If the cursor is inside an existing clocktable block, then the table
  1612. will be updated. If not, a new clocktable will be inserted. The scope
  1613. of the new clock will be subtree when called from within a subtree, and
  1614. file elsewhere.
  1615. When called with a prefix argument, move to the first clock table in the
  1616. buffer and update it."
  1617. (interactive "P")
  1618. (org-clock-remove-overlays)
  1619. (when arg
  1620. (org-find-dblock "clocktable")
  1621. (org-show-entry))
  1622. (if (org-in-clocktable-p)
  1623. (goto-char (org-in-clocktable-p))
  1624. (let ((props (if (ignore-errors
  1625. (save-excursion (org-back-to-heading)))
  1626. (list :name "clocktable" :scope 'subtree)
  1627. (list :name "clocktable"))))
  1628. (org-create-dblock
  1629. (org-combine-plists org-clock-clocktable-default-properties props))))
  1630. (org-update-dblock))
  1631. (defun org-in-clocktable-p ()
  1632. "Check if the cursor is in a clocktable."
  1633. (let ((pos (point)) start)
  1634. (save-excursion
  1635. (end-of-line 1)
  1636. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  1637. (setq start (match-beginning 0))
  1638. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  1639. (>= (match-end 0) pos)
  1640. start))))
  1641. (defun org-day-of-week (day month year)
  1642. "Returns the day of the week as an integer."
  1643. (nth 6
  1644. (decode-time
  1645. (date-to-time
  1646. (format "%d-%02d-%02dT00:00:00" year month day)))))
  1647. (defun org-quarter-to-date (quarter year)
  1648. "Get the date (week day year) of the first day of a given quarter."
  1649. (let (startday)
  1650. (cond
  1651. ((= quarter 1)
  1652. (setq startday (org-day-of-week 1 1 year))
  1653. (cond
  1654. ((= startday 0)
  1655. (list 52 7 (- year 1)))
  1656. ((= startday 6)
  1657. (list 52 6 (- year 1)))
  1658. ((<= startday 4)
  1659. (list 1 startday year))
  1660. ((> startday 4)
  1661. (list 53 startday (- year 1)))
  1662. )
  1663. )
  1664. ((= quarter 2)
  1665. (setq startday (org-day-of-week 1 4 year))
  1666. (cond
  1667. ((= startday 0)
  1668. (list 13 startday year))
  1669. ((< startday 4)
  1670. (list 14 startday year))
  1671. ((>= startday 4)
  1672. (list 13 startday year))
  1673. )
  1674. )
  1675. ((= quarter 3)
  1676. (setq startday (org-day-of-week 1 7 year))
  1677. (cond
  1678. ((= startday 0)
  1679. (list 26 startday year))
  1680. ((< startday 4)
  1681. (list 27 startday year))
  1682. ((>= startday 4)
  1683. (list 26 startday year))
  1684. )
  1685. )
  1686. ((= quarter 4)
  1687. (setq startday (org-day-of-week 1 10 year))
  1688. (cond
  1689. ((= startday 0)
  1690. (list 39 startday year))
  1691. ((<= startday 4)
  1692. (list 40 startday year))
  1693. ((> startday 4)
  1694. (list 39 startday year)))))))
  1695. (defun org-clock-special-range (key &optional time as-strings)
  1696. "Return two times bordering a special time range.
  1697. Key is a symbol specifying the range and can be one of `today', `yesterday',
  1698. `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
  1699. A week starts Monday 0:00 and ends Sunday 24:00.
  1700. The range is determined relative to TIME. TIME defaults to the current time.
  1701. The return value is a cons cell with two internal times like the ones
  1702. returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
  1703. the returned times will be formatted strings."
  1704. (if (integerp key) (setq key (intern (number-to-string key))))
  1705. (let* ((tm (decode-time (or time (current-time))))
  1706. (s 0) (m (nth 1 tm)) (h (nth 2 tm))
  1707. (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
  1708. (dow (nth 6 tm))
  1709. (skey (symbol-name key))
  1710. (shift 0)
  1711. (q (cond ((>= (nth 4 tm) 10) 4)
  1712. ((>= (nth 4 tm) 7) 3)
  1713. ((>= (nth 4 tm) 4) 2)
  1714. ((>= (nth 4 tm) 1) 1)))
  1715. s1 m1 h1 d1 month1 y1 diff ts te fm txt w date
  1716. interval tmp shiftedy shiftedm shiftedq)
  1717. (cond
  1718. ((string-match "^[0-9]+$" skey)
  1719. (setq y (string-to-number skey) m 1 d 1 key 'year))
  1720. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  1721. (setq y (string-to-number (match-string 1 skey))
  1722. month (string-to-number (match-string 2 skey))
  1723. d 1 key 'month))
  1724. ((string-match "^\\([0-9]+\\)-[wW]\\([0-9]\\{1,2\\}\\)$" skey)
  1725. (require 'cal-iso)
  1726. (setq y (string-to-number (match-string 1 skey))
  1727. w (string-to-number (match-string 2 skey)))
  1728. (setq date (calendar-gregorian-from-absolute
  1729. (calendar-absolute-from-iso (list w 1 y))))
  1730. (setq d (nth 1 date) month (car date) y (nth 2 date)
  1731. dow 1
  1732. key 'week))
  1733. ((string-match "^\\([0-9]+\\)-[qQ]\\([1-4]\\)$" skey)
  1734. (require 'cal-iso)
  1735. (setq y (string-to-number (match-string 1 skey)))
  1736. (setq q (string-to-number (match-string 2 skey)))
  1737. (setq date (calendar-gregorian-from-absolute
  1738. (calendar-absolute-from-iso (org-quarter-to-date q y))))
  1739. (setq d (nth 1 date) month (car date) y (nth 2 date)
  1740. dow 1
  1741. key 'quarter))
  1742. ((string-match "^\\([0-9]+\\)-\\([0-9]\\{1,2\\}\\)-\\([0-9]\\{1,2\\}\\)$" skey)
  1743. (setq y (string-to-number (match-string 1 skey))
  1744. month (string-to-number (match-string 2 skey))
  1745. d (string-to-number (match-string 3 skey))
  1746. key 'day))
  1747. ((string-match "\\([-+][0-9]+\\)$" skey)
  1748. (setq shift (string-to-number (match-string 1 skey))
  1749. key (intern (substring skey 0 (match-beginning 1))))
  1750. (if(and (memq key '(quarter thisq)) (> shift 0))
  1751. (error "Looking forward with quarters isn't implemented.")
  1752. ())))
  1753. (when (= shift 0)
  1754. (cond ((eq key 'yesterday) (setq key 'today shift -1))
  1755. ((eq key 'lastweek) (setq key 'week shift -1))
  1756. ((eq key 'lastmonth) (setq key 'month shift -1))
  1757. ((eq key 'lastyear) (setq key 'year shift -1))
  1758. ((eq key 'lastq) (setq key 'quarter shift -1))))
  1759. (cond
  1760. ((memq key '(day today))
  1761. (setq d (+ d shift) h 0 m 0 h1 24 m1 0))
  1762. ((memq key '(week thisweek))
  1763. (setq diff (+ (* -7 shift) (if (= dow 0) 6 (1- dow)))
  1764. m 0 h 0 d (- d diff) d1 (+ 7 d)))
  1765. ((memq key '(month thismonth))
  1766. (setq d 1 h 0 m 0 d1 1 month (+ month shift) month1 (1+ month) h1 0 m1 0))
  1767. ((memq key '(quarter thisq))
  1768. ; compute if this shift remains in this year
  1769. ; if not, compute how many years and quarters we have to shift (via floor*)
  1770. ; and compute the shifted years, months and quarters
  1771. (cond
  1772. ((< (+ (- q 1) shift) 0) ; shift not in this year
  1773. (setq interval (* -1 (+ (- q 1) shift)))
  1774. ; set tmp to ((years to shift) (quarters to shift))
  1775. (setq tmp (org-floor* interval 4))
  1776. ; due to the use of floor, 0 quarters actually means 4
  1777. (if (= 0 (nth 1 tmp))
  1778. (setq shiftedy (- y (nth 0 tmp))
  1779. shiftedm 1
  1780. shiftedq 1)
  1781. (setq shiftedy (- y (+ 1 (nth 0 tmp)))
  1782. shiftedm (- 13 (* 3 (nth 1 tmp)))
  1783. shiftedq (- 5 (nth 1 tmp))))
  1784. (setq d 1 h 0 m 0 d1 1 month shiftedm month1 (+ 3 shiftedm) h1 0 m1 0 y shiftedy))
  1785. ((> (+ q shift) 0) ; shift is whitin this year
  1786. (setq shiftedq (+ q shift))
  1787. (setq shiftedy y)
  1788. (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))))
  1789. ((memq key '(year thisyear))
  1790. (setq m 0 h 0 d 1 month 1 y (+ y shift) y1 (1+ y)))
  1791. (t (error "No such time block %s" key)))
  1792. (setq ts (encode-time s m h d month y)
  1793. te (encode-time (or s1 s) (or m1 m) (or h1 h)
  1794. (or d1 d) (or month1 month) (or y1 y)))
  1795. (setq fm (cdr org-time-stamp-formats))
  1796. (cond
  1797. ((memq key '(day today))
  1798. (setq txt (format-time-string "%A, %B %d, %Y" ts)))
  1799. ((memq key '(week thisweek))
  1800. (setq txt (format-time-string "week %G-W%V" ts)))
  1801. ((memq key '(month thismonth))
  1802. (setq txt (format-time-string "%B %Y" ts)))
  1803. ((memq key '(year thisyear))
  1804. (setq txt (format-time-string "the year %Y" ts)))
  1805. ((memq key '(quarter thisq))
  1806. (setq txt (concatenate 'string (org-count-quarter shiftedq) " quarter of " (number-to-string shiftedy))))
  1807. )
  1808. (if as-strings
  1809. (list (format-time-string fm ts) (format-time-string fm te) txt)
  1810. (list ts te txt))))
  1811. (defun org-count-quarter (n)
  1812. (cond
  1813. ((= n 1) "1st")
  1814. ((= n 2) "2nd")
  1815. ((= n 3) "3rd")
  1816. ((= n 4) "4th")))
  1817. (defun org-clocktable-shift (dir n)
  1818. "Try to shift the :block date of the clocktable at point.
  1819. Point must be in the #+BEGIN: line of a clocktable, or this function
  1820. will throw an error.
  1821. DIR is a direction, a symbol `left', `right', `up', or `down'.
  1822. Both `left' and `down' shift the block toward the past, `up' and `right'
  1823. push it toward the future.
  1824. N is the number of shift steps to take. The size of the step depends on
  1825. the currently selected interval size."
  1826. (setq n (prefix-numeric-value n))
  1827. (and (memq dir '(left down)) (setq n (- n)))
  1828. (save-excursion
  1829. (goto-char (point-at-bol))
  1830. (if (not (looking-at "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>.*?:block[ \t]+\\(\\S-+\\)"))
  1831. (error "Line needs a :block definition before this command works")
  1832. (let* ((b (match-beginning 1)) (e (match-end 1))
  1833. (s (match-string 1))
  1834. block shift ins y mw d date wp m)
  1835. (cond
  1836. ((equal s "yesterday") (setq s "today-1"))
  1837. ((equal s "lastweek") (setq s "thisweek-1"))
  1838. ((equal s "lastmonth") (setq s "thismonth-1"))
  1839. ((equal s "lastyear") (setq s "thisyear-1"))
  1840. ((equal s "lastq") (setq s "thisq-1")))
  1841. (cond
  1842. ((string-match "^\\(today\\|thisweek\\|thismonth\\|thisyear\\|thisq\\)\\([-+][0-9]+\\)?$" s)
  1843. (setq block (match-string 1 s)
  1844. shift (if (match-end 2)
  1845. (string-to-number (match-string 2 s))
  1846. 0))
  1847. (setq shift (+ shift n))
  1848. (setq ins (if (= shift 0) block (format "%s%+d" block shift))))
  1849. ((string-match "\\([0-9]+\\)\\(-\\([wWqQ]?\\)\\([0-9]\\{1,2\\}\\)\\(-\\([0-9]\\{1,2\\}\\)\\)?\\)?" s)
  1850. ;; 1 1 2 3 3 4 4 5 6 6 5 2
  1851. (setq y (string-to-number (match-string 1 s))
  1852. wp (and (match-end 3) (match-string 3 s))
  1853. mw (and (match-end 4) (string-to-number (match-string 4 s)))
  1854. d (and (match-end 6) (string-to-number (match-string 6 s))))
  1855. (cond
  1856. (d (setq ins (format-time-string
  1857. "%Y-%m-%d"
  1858. (encode-time 0 0 0 (+ d n) m y))))
  1859. ((and wp (string-match "w\\|W" wp) mw (> (length wp) 0))
  1860. (require 'cal-iso)
  1861. (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (list (+ mw n) 1 y))))
  1862. (setq ins (format-time-string
  1863. "%G-W%V"
  1864. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  1865. ((and wp (string-match "q\\|Q" wp) mw (> (length wp) 0))
  1866. (require 'cal-iso)
  1867. ; if the 4th + 1 quarter is requested we flip to the 1st quarter of the next year
  1868. (if (> (+ mw n) 4)
  1869. (setq mw 0
  1870. y (+ 1 y))
  1871. ())
  1872. ; if the 1st - 1 quarter is requested we flip to the 4th quarter of the previous year
  1873. (if (= (+ mw n) 0)
  1874. (setq mw 5
  1875. y (- y 1))
  1876. ())
  1877. (setq date (calendar-gregorian-from-absolute (calendar-absolute-from-iso (org-quarter-to-date (+ mw n) y))))
  1878. (setq ins (format-time-string
  1879. (concatenate 'string (number-to-string y) "-Q" (number-to-string (+ mw n)))
  1880. (encode-time 0 0 0 (nth 1 date) (car date) (nth 2 date)))))
  1881. (mw
  1882. (setq ins (format-time-string
  1883. "%Y-%m"
  1884. (encode-time 0 0 0 1 (+ mw n) y))))
  1885. (y
  1886. (setq ins (number-to-string (+ y n))))))
  1887. (t (error "Cannot shift clocktable block")))
  1888. (when ins
  1889. (goto-char b)
  1890. (insert ins)
  1891. (delete-region (point) (+ (point) (- e b)))
  1892. (beginning-of-line 1)
  1893. (org-update-dblock)
  1894. t)))))
  1895. (defun org-dblock-write:clocktable (params)
  1896. "Write the standard clocktable."
  1897. (setq params (org-combine-plists org-clocktable-defaults params))
  1898. (catch 'exit
  1899. (let* ((scope (plist-get params :scope))
  1900. (block (plist-get params :block))
  1901. (ts (plist-get params :tstart))
  1902. (te (plist-get params :tend))
  1903. (link (plist-get params :link))
  1904. (maxlevel (or (plist-get params :maxlevel) 3))
  1905. (step (plist-get params :step))
  1906. (timestamp (plist-get params :timestamp))
  1907. (formatter (or (plist-get params :formatter)
  1908. org-clock-clocktable-formatter
  1909. 'org-clocktable-write-default))
  1910. cc range-text ipos pos one-file-with-archives
  1911. scope-is-list tbls level)
  1912. ;; Check if we need to do steps
  1913. (when block
  1914. ;; Get the range text for the header
  1915. (setq cc (org-clock-special-range block nil t)
  1916. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  1917. (when step
  1918. ;; Write many tables, in steps
  1919. (unless (or block (and ts te))
  1920. (error "Clocktable `:step' can only be used with `:block' or `:tstart,:end'"))
  1921. (org-clocktable-steps params)
  1922. (throw 'exit nil))
  1923. (setq ipos (point)) ; remember the insertion position
  1924. ;; Get the right scope
  1925. (setq pos (point))
  1926. (cond
  1927. ((and scope (listp scope) (symbolp (car scope)))
  1928. (setq scope (eval scope)))
  1929. ((eq scope 'agenda)
  1930. (setq scope (org-agenda-files t)))
  1931. ((eq scope 'agenda-with-archives)
  1932. (setq scope (org-agenda-files t))
  1933. (setq scope (org-add-archive-files scope)))
  1934. ((eq scope 'file-with-archives)
  1935. (setq scope (org-add-archive-files (list (buffer-file-name)))
  1936. one-file-with-archives t)))
  1937. (setq scope-is-list (and scope (listp scope)))
  1938. (if scope-is-list
  1939. ;; we collect from several files
  1940. (let* ((files scope)
  1941. file)
  1942. (org-prepare-agenda-buffers files)
  1943. (while (setq file (pop files))
  1944. (with-current-buffer (find-buffer-visiting file)
  1945. (save-excursion
  1946. (save-restriction
  1947. (push (org-clock-get-table-data file params) tbls))))))
  1948. ;; Just from the current file
  1949. (save-restriction
  1950. ;; get the right range into the restriction
  1951. (org-prepare-agenda-buffers (list (buffer-file-name)))
  1952. (cond
  1953. ((not scope)) ; use the restriction as it is now
  1954. ((eq scope 'file) (widen))
  1955. ((eq scope 'subtree) (org-narrow-to-subtree))
  1956. ((eq scope 'tree)
  1957. (while (org-up-heading-safe))
  1958. (org-narrow-to-subtree))
  1959. ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
  1960. (symbol-name scope)))
  1961. (setq level (string-to-number (match-string 1 (symbol-name scope))))
  1962. (catch 'exit
  1963. (while (org-up-heading-safe)
  1964. (looking-at org-outline-regexp)
  1965. (if (<= (org-reduced-level (funcall outline-level)) level)
  1966. (throw 'exit nil))))
  1967. (org-narrow-to-subtree)))
  1968. ;; do the table, with no file name.
  1969. (push (org-clock-get-table-data nil params) tbls)))
  1970. ;; OK, at this point we tbls as a list of tables, one per file
  1971. (setq tbls (nreverse tbls))
  1972. (setq params (plist-put params :multifile scope-is-list))
  1973. (setq params (plist-put params :one-file-with-archives
  1974. one-file-with-archives))
  1975. (funcall formatter ipos tbls params))))
  1976. (defun org-clocktable-write-default (ipos tables params)
  1977. "Write out a clock table at position IPOS in the current buffer.
  1978. TABLES is a list of tables with clocking data as produced by
  1979. `org-clock-get-table-data'. PARAMS is the parameter property list obtained
  1980. from the dynamic block defintion."
  1981. ;; This function looks quite complicated, mainly because there are a
  1982. ;; lot of options which can add or remove columns. I have massively
  1983. ;; commented this function, the I hope it is understandable. If
  1984. ;; someone wants to write their own special formatter, this maybe
  1985. ;; much easier because there can be a fixed format with a
  1986. ;; well-defined number of columns...
  1987. (let* ((hlchars '((1 . "*") (2 . "/")))
  1988. (lwords (assoc (or (plist-get params :lang)
  1989. org-export-default-language)
  1990. org-clock-clocktable-language-setup))
  1991. (multifile (plist-get params :multifile))
  1992. (block (plist-get params :block))
  1993. (ts (plist-get params :tstart))
  1994. (te (plist-get params :tend))
  1995. (header (plist-get params :header))
  1996. (narrow (plist-get params :narrow))
  1997. (link (plist-get params :link))
  1998. (maxlevel (or (plist-get params :maxlevel) 3))
  1999. (emph (plist-get params :emphasize))
  2000. (level-p (plist-get params :level))
  2001. (timestamp (plist-get params :timestamp))
  2002. (properties (plist-get params :properties))
  2003. (ntcol (max 1 (or (plist-get params :tcolumns) 100)))
  2004. (rm-file-column (plist-get params :one-file-with-archives))
  2005. (indent (plist-get params :indent))
  2006. range-text total-time tbl level hlc formula pcol
  2007. file-time entries entry headline
  2008. recalc content narrow-cut-p tcol)
  2009. ;; Implement abbreviations
  2010. (when (plist-get params :compact)
  2011. (setq level nil indent t narrow (or narrow '40!) ntcol 1))
  2012. ;; Some consistency test for parameters
  2013. (unless (integerp ntcol)
  2014. (setq params (plist-put params :tcolumns (setq ntcol 100))))
  2015. (when (and narrow (integerp narrow) link)
  2016. ;; We cannot have both integer narrow and link
  2017. (message
  2018. "Using hard narrowing in clocktable to allow for links")
  2019. (setq narrow (intern (format "%d!" narrow))))
  2020. (when narrow
  2021. (cond
  2022. ((integerp narrow))
  2023. ((and (symbolp narrow)
  2024. (string-match "\\`[0-9]+!\\'" (symbol-name narrow)))
  2025. (setq narrow-cut-p t
  2026. narrow (string-to-number (substring (symbol-name narrow)
  2027. 0 -1))))
  2028. (t
  2029. (error "Invalid value %s of :narrow property in clock table"
  2030. narrow))))
  2031. (when block
  2032. ;; Get the range text for the header
  2033. (setq range-text (nth 2 (org-clock-special-range block nil t))))
  2034. ;; Compute the total time
  2035. (setq total-time (apply '+ (mapcar 'cadr tables)))
  2036. ;; Now we need to output this tsuff
  2037. (goto-char ipos)
  2038. ;; Insert the text *before* the actual table
  2039. (insert-before-markers
  2040. (or header
  2041. ;; Format the standard header
  2042. (concat
  2043. (nth 9 lwords) " ["
  2044. (substring
  2045. (format-time-string (cdr org-time-stamp-formats))
  2046. 1 -1)
  2047. "]"
  2048. (if block (concat ", for " range-text ".") "")
  2049. "\n\n")))
  2050. ;; Insert the narrowing line
  2051. (when (and narrow (integerp narrow) (not narrow-cut-p))
  2052. (insert-before-markers
  2053. "|" ; table line starter
  2054. (if multifile "|" "") ; file column, maybe
  2055. (if level-p "|" "") ; level column, maybe
  2056. (if timestamp "|" "") ; timestamp column, maybe
  2057. (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
  2058. (format "<%d>| |\n" narrow))) ; headline and time columns
  2059. ;; Insert the table header line
  2060. (insert-before-markers
  2061. "|" ; table line starter
  2062. (if multifile (concat (nth 1 lwords) "|") "") ; file column, maybe
  2063. (if level-p (concat (nth 2 lwords) "|") "") ; level column, maybe
  2064. (if timestamp (concat (nth 3 lwords) "|") "") ; timestamp column, maybe
  2065. (if properties (concat (mapconcat 'identity properties "|") "|") "") ;properties columns, maybe
  2066. (concat (nth 4 lwords) "|"
  2067. (nth 5 lwords) "|\n")) ; headline and time columns
  2068. ;; Insert the total time in the table
  2069. (insert-before-markers
  2070. "|-\n" ; a hline
  2071. "|" ; table line starter
  2072. (if multifile (concat "| " (nth 6 lwords) " ") "")
  2073. ; file column, maybe
  2074. (if level-p "|" "") ; level column, maybe
  2075. (if timestamp "|" "") ; timestamp column, maybe
  2076. (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
  2077. (concat "*" (nth 7 lwords) "*| ") ; instead of a headline
  2078. "*"
  2079. (org-minutes-to-hh:mm-string (or total-time 0)) ; the time
  2080. "*|\n") ; close line
  2081. ;; Now iterate over the tables and insert the data
  2082. ;; but only if any time has been collected
  2083. (when (and total-time (> total-time 0))
  2084. (while (setq tbl (pop tables))
  2085. ;; now tbl is the table resulting from one file.
  2086. (setq file-time (nth 1 tbl))
  2087. (when (or (and file-time (> file-time 0))
  2088. (not (plist-get params :fileskip0)))
  2089. (insert-before-markers "|-\n") ; a hline because a new file starts
  2090. ;; First the file time, if we have multiple files
  2091. (when multifile
  2092. ;; Summarize the time collected from this file
  2093. (insert-before-markers
  2094. (format (concat "| %s %s | %s%s*" (nth 8 lwords) "* | *%s*|\n")
  2095. (file-name-nondirectory (car tbl))
  2096. (if level-p "| " "") ; level column, maybe
  2097. (if timestamp "| " "") ; timestamp column, maybe
  2098. (if properties (make-string (length properties) ?|) "") ;properties columns, maybe
  2099. (org-minutes-to-hh:mm-string (nth 1 tbl))))) ; the time
  2100. ;; Get the list of node entries and iterate over it
  2101. (setq entries (nth 2 tbl))
  2102. (while (setq entry (pop entries))
  2103. (setq level (car entry)
  2104. headline (nth 1 entry)
  2105. hlc (if emph (or (cdr (assoc level hlchars)) "") ""))
  2106. (when narrow-cut-p
  2107. (if (and (string-match (concat "\\`" org-bracket-link-regexp
  2108. "\\'")
  2109. headline)
  2110. (match-end 3))
  2111. (setq headline
  2112. (format "[[%s][%s]]"
  2113. (match-string 1 headline)
  2114. (org-shorten-string (match-string 3 headline)
  2115. narrow)))
  2116. (setq headline (org-shorten-string headline narrow))))
  2117. (insert-before-markers
  2118. "|" ; start the table line
  2119. (if multifile "|" "") ; free space for file name column?
  2120. (if level-p (format "%d|" (car entry)) "") ; level, maybe
  2121. (if timestamp (concat (nth 2 entry) "|") "") ; timestamp, maybe
  2122. (if properties
  2123. (concat
  2124. (mapconcat
  2125. (lambda (p) (or (cdr (assoc p (nth 4 entry))) ""))
  2126. properties "|") "|") "") ;properties columns, maybe
  2127. (if indent (org-clocktable-indent-string level) "") ; indentation
  2128. hlc headline hlc "|" ; headline
  2129. (make-string (min (1- ntcol) (or (- level 1))) ?|)
  2130. ; empty fields for higher levels
  2131. hlc (org-minutes-to-hh:mm-string (nth 3 entry)) hlc ; time
  2132. "|\n" ; close line
  2133. )))))
  2134. (backward-delete-char 1)
  2135. (if (setq formula (plist-get params :formula))
  2136. (cond
  2137. ((eq formula '%)
  2138. ;; compute the column where the % numbers need to go
  2139. (setq pcol (+ 2
  2140. (if multifile 1 0)
  2141. (if level-p 1 0)
  2142. (if timestamp 1 0)
  2143. (min maxlevel (or ntcol 100))))
  2144. ;; compute the column where the total time is
  2145. (setq tcol (+ 2
  2146. (if multifile 1 0)
  2147. (if level-p 1 0)
  2148. (if timestamp 1 0)))
  2149. (insert
  2150. (format
  2151. "\n#+TBLFM: $%d='(org-clock-time%% @%d$%d $%d..$%d);%%.1f"
  2152. pcol ; the column where the % numbers should go
  2153. (if (and narrow (not narrow-cut-p)) 3 2) ; row of the total time
  2154. tcol ; column of the total time
  2155. tcol (1- pcol) ; range of columns where times can be found
  2156. ))
  2157. (setq recalc t))
  2158. ((stringp formula)
  2159. (insert "\n#+TBLFM: " formula)
  2160. (setq recalc t))
  2161. (t (error "invalid formula in clocktable")))
  2162. ;; Should we rescue an old formula?
  2163. (when (stringp (setq content (plist-get params :content)))
  2164. (when (string-match "^\\([ \t]*#\\+TBLFM:.*\\)" content)
  2165. (setq recalc t)
  2166. (insert "\n" (match-string 1 (plist-get params :content)))
  2167. (beginning-of-line 0))))
  2168. ;; Back to beginning, align the table, recalculate if necessary
  2169. (goto-char ipos)
  2170. (skip-chars-forward "^|")
  2171. (org-table-align)
  2172. (when org-hide-emphasis-markers
  2173. ;; we need to align a second time
  2174. (org-table-align))
  2175. (when recalc
  2176. (if (eq formula '%)
  2177. (save-excursion
  2178. (if (and narrow (not narrow-cut-p)) (beginning-of-line 2))
  2179. (org-table-goto-column pcol nil 'force)
  2180. (insert "%")))
  2181. (org-table-recalculate 'all))
  2182. (when rm-file-column
  2183. ;; The file column is actually not wanted
  2184. (forward-char 1)
  2185. (org-table-delete-column))
  2186. total-time))
  2187. (defun org-clocktable-indent-string (level)
  2188. (if (= level 1)
  2189. ""
  2190. (let ((str "\\__"))
  2191. (while (> level 2)
  2192. (setq level (1- level)
  2193. str (concat str "___")))
  2194. (concat str " "))))
  2195. (defun org-clocktable-steps (params)
  2196. "Step through the range to make a number of clock tables."
  2197. (let* ((p1 (copy-sequence params))
  2198. (ts (plist-get p1 :tstart))
  2199. (te (plist-get p1 :tend))
  2200. (step0 (plist-get p1 :step))
  2201. (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
  2202. (stepskip0 (plist-get p1 :stepskip0))
  2203. (block (plist-get p1 :block))
  2204. cc range-text step-time)
  2205. (when block
  2206. (setq cc (org-clock-special-range block nil t)
  2207. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  2208. (cond
  2209. ((numberp ts)
  2210. ;; If ts is a number, it's an absolute day number from org-agenda.
  2211. (destructuring-bind (month day year) (calendar-gregorian-from-absolute ts)
  2212. (setq ts (org-float-time (encode-time 0 0 0 day month year)))))
  2213. (ts
  2214. (setq ts (org-float-time
  2215. (apply 'encode-time (org-parse-time-string ts))))))
  2216. (cond
  2217. ((numberp te)
  2218. ;; Likewise for te.
  2219. (destructuring-bind (month day year) (calendar-gregorian-from-absolute te)
  2220. (setq te (org-float-time (encode-time 0 0 0 day month year)))))
  2221. (te
  2222. (setq te (org-float-time
  2223. (apply 'encode-time (org-parse-time-string te))))))
  2224. (setq p1 (plist-put p1 :header ""))
  2225. (setq p1 (plist-put p1 :step nil))
  2226. (setq p1 (plist-put p1 :block nil))
  2227. (while (< ts te)
  2228. (or (bolp) (insert "\n"))
  2229. (setq p1 (plist-put p1 :tstart (format-time-string
  2230. (org-time-stamp-format nil t)
  2231. (seconds-to-time ts))))
  2232. (setq p1 (plist-put p1 :tend (format-time-string
  2233. (org-time-stamp-format nil t)
  2234. (seconds-to-time (setq ts (+ ts step))))))
  2235. (insert "\n" (if (eq step0 'day) "Daily report: "
  2236. "Weekly report starting on: ")
  2237. (plist-get p1 :tstart) "\n")
  2238. (setq step-time (org-dblock-write:clocktable p1))
  2239. (re-search-forward "^[ \t]*#\\+END:")
  2240. (when (and (equal step-time 0) stepskip0)
  2241. ;; Remove the empty table
  2242. (delete-region (point-at-bol)
  2243. (save-excursion
  2244. (re-search-backward "^\\(Daily\\|Weekly\\) report"
  2245. nil t)
  2246. (point))))
  2247. (end-of-line 0))))
  2248. (defun org-clock-get-table-data (file params)
  2249. "Get the clocktable data for file FILE, with parameters PARAMS.
  2250. FILE is only for identification - this function assumes that
  2251. the correct buffer is current, and that the wanted restriction is
  2252. in place.
  2253. The return value will be a list with the file name and the total
  2254. file time (in minutes) as 1st and 2nd elements. The third element
  2255. of this list will be a list of headline entries. Each entry has the
  2256. following structure:
  2257. (LEVEL HEADLINE TIMESTAMP TIME)
  2258. LEVEL: The level of the headline, as an integer. This will be
  2259. the reduced leve, so 1,2,3,... even if only odd levels
  2260. are being used.
  2261. HEADLINE: The text of the headline. Depending on PARAMS, this may
  2262. already be formatted like a link.
  2263. TIMESTAMP: If PARAMS require it, this will be a time stamp found in the
  2264. entry, any of SCHEDULED, DEADLINE, NORMAL, or first inactive,
  2265. in this sequence.
  2266. TIME: The sum of all time spend in this tree, in minutes. This time
  2267. will of cause be restricted to the time block and tags match
  2268. specified in PARAMS."
  2269. (let* ((maxlevel (or (plist-get params :maxlevel) 3))
  2270. (timestamp (plist-get params :timestamp))
  2271. (ts (plist-get params :tstart))
  2272. (te (plist-get params :tend))
  2273. (block (plist-get params :block))
  2274. (link (plist-get params :link))
  2275. (tags (plist-get params :tags))
  2276. (properties (plist-get params :properties))
  2277. (inherit-property-p (plist-get params :inherit-props))
  2278. (matcher (if tags (cdr (org-make-tags-matcher tags))))
  2279. cc range-text st p time level hdl props tsp tbl)
  2280. (setq org-clock-file-total-minutes nil)
  2281. (when block
  2282. (setq cc (org-clock-special-range block nil t)
  2283. ts (car cc) te (nth 1 cc) range-text (nth 2 cc)))
  2284. (when (integerp ts) (setq ts (calendar-gregorian-from-absolute ts)))
  2285. (when (integerp te) (setq te (calendar-gregorian-from-absolute te)))
  2286. (when (and ts (listp ts))
  2287. (setq ts (format "%4d-%02d-%02d" (nth 2 ts) (car ts) (nth 1 ts))))
  2288. (when (and te (listp te))
  2289. (setq te (format "%4d-%02d-%02d" (nth 2 te) (car te) (nth 1 te))))
  2290. ;; Now the times are strings we can parse.
  2291. (if ts (setq ts (org-float-time
  2292. (apply 'encode-time (org-parse-time-string ts)))))
  2293. (if te (setq te (org-float-time
  2294. (apply 'encode-time (org-parse-time-string te)))))
  2295. (save-excursion
  2296. (org-clock-sum ts te
  2297. (unless (null matcher)
  2298. (lambda ()
  2299. (let ((tags-list (org-get-tags-at)))
  2300. (eval matcher)))))
  2301. (goto-char (point-min))
  2302. (setq st t)
  2303. (while (or (and (bobp) (prog1 st (setq st nil))
  2304. (get-text-property (point) :org-clock-minutes)
  2305. (setq p (point-min)))
  2306. (setq p (next-single-property-change
  2307. (point) :org-clock-minutes)))
  2308. (goto-char p)
  2309. (when (setq time (get-text-property p :org-clock-minutes))
  2310. (save-excursion
  2311. (beginning-of-line 1)
  2312. (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
  2313. (setq level (org-reduced-level
  2314. (- (match-end 1) (match-beginning 1))))
  2315. (<= level maxlevel))
  2316. (setq hdl (if (not link)
  2317. (match-string 2)
  2318. (org-make-link-string
  2319. (format "file:%s::%s"
  2320. (buffer-file-name)
  2321. (save-match-data
  2322. (org-make-org-heading-search-string
  2323. (match-string 2))))
  2324. (match-string 2)))
  2325. tsp (when timestamp
  2326. (setq props (org-entry-properties (point)))
  2327. (or (cdr (assoc "SCHEDULED" props))
  2328. (cdr (assoc "DEADLINE" props))
  2329. (cdr (assoc "TIMESTAMP" props))
  2330. (cdr (assoc "TIMESTAMP_IA" props))))
  2331. props (when properties
  2332. (remove nil
  2333. (mapcar
  2334. (lambda (p)
  2335. (when (org-entry-get (point) p inherit-property-p)
  2336. (cons p (org-entry-get (point) p inherit-property-p))))
  2337. properties))))
  2338. (when (> time 0) (push (list level hdl tsp time props) tbl))))))
  2339. (setq tbl (nreverse tbl))
  2340. (list file org-clock-file-total-minutes tbl))))
  2341. (defun org-clock-time% (total &rest strings)
  2342. "Compute a time fraction in percent.
  2343. TOTAL s a time string like 10:21 specifying the total times.
  2344. STRINGS is a list of strings that should be checked for a time.
  2345. The first string that does have a time will be used.
  2346. This function is made for clock tables."
  2347. (let ((re "\\([0-9]+\\):\\([0-9]+\\)")
  2348. tot s)
  2349. (save-match-data
  2350. (catch 'exit
  2351. (if (not (string-match re total))
  2352. (throw 'exit 0.)
  2353. (setq tot (+ (string-to-number (match-string 2 total))
  2354. (* 60 (string-to-number (match-string 1 total)))))
  2355. (if (= tot 0.) (throw 'exit 0.)))
  2356. (while (setq s (pop strings))
  2357. (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
  2358. (throw 'exit
  2359. (/ (* 100.0 (+ (string-to-number (match-string 2 s))
  2360. (* 60 (string-to-number
  2361. (match-string 1 s)))))
  2362. tot))))
  2363. 0))))
  2364. ;; Saving and loading the clock
  2365. (defvar org-clock-loaded nil
  2366. "Was the clock file loaded?")
  2367. (defun org-clock-save ()
  2368. "Persist various clock-related data to disk.
  2369. The details of what will be saved are regulated by the variable
  2370. `org-clock-persist'."
  2371. (when (and org-clock-persist
  2372. (or org-clock-loaded
  2373. org-clock-has-been-used
  2374. (not (file-exists-p org-clock-persist-file))))
  2375. (let (b)
  2376. (with-current-buffer (find-file (expand-file-name org-clock-persist-file))
  2377. (progn
  2378. (delete-region (point-min) (point-max))
  2379. ;;Store clock
  2380. (insert (format ";; org-persist.el - %s at %s\n"
  2381. system-name (format-time-string
  2382. (cdr org-time-stamp-formats))))
  2383. (if (and (memq org-clock-persist '(t clock))
  2384. (setq b (org-clocking-buffer))
  2385. (setq b (or (buffer-base-buffer b) b))
  2386. (buffer-live-p b)
  2387. (buffer-file-name b)
  2388. (or (not org-clock-persist-query-save)
  2389. (y-or-n-p (concat "Save current clock ("
  2390. (substring-no-properties
  2391. org-clock-heading)
  2392. ") "))))
  2393. (insert "(setq resume-clock '(\""
  2394. (buffer-file-name (org-clocking-buffer))
  2395. "\" . " (int-to-string (marker-position org-clock-marker))
  2396. "))\n"))
  2397. ;; Store clocked task history. Tasks are stored reversed to make
  2398. ;; reading simpler
  2399. (when (and (memq org-clock-persist '(t history))
  2400. org-clock-history)
  2401. (insert
  2402. "(setq stored-clock-history '("
  2403. (mapconcat
  2404. (lambda (m)
  2405. (when (and (setq b (marker-buffer m))
  2406. (setq b (or (buffer-base-buffer b) b))
  2407. (buffer-live-p b)
  2408. (buffer-file-name b))
  2409. (concat "(\"" (buffer-file-name b)
  2410. "\" . " (int-to-string (marker-position m))
  2411. ")")))
  2412. (reverse org-clock-history) " ") "))\n"))
  2413. (save-buffer)
  2414. (kill-buffer (current-buffer)))))))
  2415. (defun org-clock-load ()
  2416. "Load clock-related data from disk, maybe resuming a stored clock."
  2417. (when (and org-clock-persist (not org-clock-loaded))
  2418. (let ((filename (expand-file-name org-clock-persist-file))
  2419. (org-clock-in-resume 'auto-restart)
  2420. resume-clock stored-clock-history)
  2421. (if (not (file-readable-p filename))
  2422. (message "Not restoring clock data; %s not found"
  2423. org-clock-persist-file)
  2424. (message "%s" "Restoring clock data")
  2425. (setq org-clock-loaded t)
  2426. (load-file filename)
  2427. ;; load history
  2428. (when stored-clock-history
  2429. (save-window-excursion
  2430. (mapc (lambda (task)
  2431. (if (file-exists-p (car task))
  2432. (org-clock-history-push (cdr task)
  2433. (find-file (car task)))))
  2434. stored-clock-history)))
  2435. ;; resume clock
  2436. (when (and resume-clock org-clock-persist
  2437. (file-exists-p (car resume-clock))
  2438. (or (not org-clock-persist-query-resume)
  2439. (y-or-n-p
  2440. (concat
  2441. "Resume clock ("
  2442. (with-current-buffer (find-file (car resume-clock))
  2443. (save-excursion
  2444. (goto-char (cdr resume-clock))
  2445. (org-back-to-heading t)
  2446. (and (looking-at org-complex-heading-regexp)
  2447. (match-string 4))))
  2448. ") "))))
  2449. (when (file-exists-p (car resume-clock))
  2450. (with-current-buffer (find-file (car resume-clock))
  2451. (goto-char (cdr resume-clock))
  2452. (let ((org-clock-auto-clock-resolution nil))
  2453. (org-clock-in)
  2454. (if (outline-invisible-p)
  2455. (org-show-context))))))))))
  2456. ;;;###autoload
  2457. (defun org-clock-persistence-insinuate ()
  2458. "Set up hooks for clock persistence."
  2459. (add-hook 'org-mode-hook 'org-clock-load)
  2460. (add-hook 'kill-emacs-hook 'org-clock-save))
  2461. ;; Suggested bindings
  2462. (org-defkey org-mode-map "\C-c\C-x\C-e" 'org-clock-modify-effort-estimate)
  2463. (provide 'org-clock)
  2464. ;; arch-tag: 7b42c5d4-9b36-48be-97c0-66a869daed4c
  2465. ;;; org-clock.el ends here