org-clock.el 109 KB

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