org-clock.el 107 KB

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