org-clock.el 85 KB

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