org-clock.el 106 KB

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