org-clock.el 91 KB

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