org-clock.el 118 KB

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