org-clock.el 98 KB

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