org-clock.el 105 KB

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