org-clock.el 105 KB

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