org-clock.el 99 KB

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