org-clock.el 109 KB

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