org-clock.el 102 KB

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