org-clock.el 109 KB

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