org-clock.el 110 KB

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