org-clock.el 101 KB

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