org-clock.el 108 KB

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