org-clock.el 99 KB

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