org-clock.el 110 KB

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