org-clock.el 111 KB

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