org-clock.el 106 KB

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