org-clock.el 110 KB

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