org-clock.el 91 KB

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