org-clock.el 99 KB

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