org-clock.el 112 KB

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