org-clock.el 112 KB

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