org-clock.el 104 KB

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