org-clock.el 106 KB

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