org-clock.el 105 KB

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