org-clock.el 98 KB

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