org-clock.el 106 KB

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