org-clock.el 98 KB

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