org-clock.el 94 KB

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