org-clock.el 97 KB

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