org-clock.el 107 KB

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