org-clock.el 116 KB

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