org-clock.el 110 KB

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