org-clock.el 115 KB

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