org-clock.el 111 KB

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