org-clock.el 97 KB

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