org-clock.el 117 KB

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