org-clock.el 97 KB

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