org-clock.el 92 KB

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