org-clock.el 104 KB

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