org-clock.el 100 KB

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