org-clock.el 96 KB

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