org-clock.el 107 KB

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