Remove non-free old and crusty clearcase pkg
[packages] / xemacs-packages / calendar / timeclock.el
1 ;;; timeclock.el --- mode for keeping track of how much you work
2
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
4 ;;   Free Software Foundation, Inc.
5
6 ;; Author: John Wiegley <johnw@gnu.org>
7 ;; Created: 25 Mar 1999
8 ;; Version: 2.6
9 ;; Keywords: calendar data
10
11 ;; This file is part of XEmacs.
12
13 ;; XEmacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; XEmacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with XEmacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Synched up with: FSF Emacs 22 CVS 2007-03-30
29 ;;; and contrib/timeclock.el from
30 ;;; http://arch.gna.org/planner-el/archive-2006/planner-el--devel--0/
31
32 ;;; Commentary:
33
34 ;; This mode is for keeping track of time intervals.  You can use it
35 ;; for whatever purpose you like, but the typical scenario is to keep
36 ;; track of how much time you spend working on certain projects.
37 ;;
38 ;; Use `timeclock-in' when you start on a project, and `timeclock-out'
39 ;; when you're done.  Once you've collected some data, you can use
40 ;; `timeclock-workday-remaining' to see how much time is left to be
41 ;; worked today (where `timeclock-workday' specifies the length of the
42 ;; working day), and `timeclock-when-to-leave' to calculate when you're free.
43
44 ;; You'll probably want to bind the timeclock commands to some handy
45 ;; keystrokes.  At the moment, C-x t is unused:
46 ;;
47 ;;   (require 'timeclock)
48 ;;
49 ;;   (define-key ctl-x-map "ti" 'timeclock-in)
50 ;;   (define-key ctl-x-map "to" 'timeclock-out)
51 ;;   (define-key ctl-x-map "tc" 'timeclock-change)
52 ;;   (define-key ctl-x-map "tr" 'timeclock-reread-log)
53 ;;   (define-key ctl-x-map "tu" 'timeclock-update-modeline)
54 ;;   (define-key ctl-x-map "tw" 'timeclock-when-to-leave-string)
55
56 ;; If you want XEmacs to display the amount of time "left" to your
57 ;; workday in the modeline, you can either set the value of
58 ;; `timeclock-modeline-display' to t using M-x customize, or you
59 ;; can add this code to your .emacs file:
60 ;;
61 ;;   (require 'timeclock)
62 ;;   (timeclock-modeline-display)
63 ;;
64 ;; To cancel this modeline display at any time, just call
65 ;; `timeclock-modeline-display' again.
66
67 ;; You may also want XEmacs to ask you before exiting, if you are
68 ;; currently working on a project.  This can be done either by setting
69 ;; `timeclock-ask-before-exiting' to t using M-x customize (this is
70 ;; the default), or by adding the following to your .emacs file:
71 ;;
72 ;;   (add-hook 'kill-emacs-query-functions 'timeclock-query-out)
73
74 ;; NOTE: If you change your .timelog file without using timeclock's
75 ;; functions, or if you change the value of any of timeclock's
76 ;; customizable variables, you should run the command
77 ;; `timeclock-reread-log'.  This will recompute any discrepancies in
78 ;; your average working time, and will make sure that the various
79 ;; display functions return the correct value.
80
81 ;;; History:
82
83 ;;; Code:
84
85 ;; XEmacs change
86 (if (featurep 'xemacs)
87     (defalias 'timeclock-cancel-timer 'delete-itimer)
88   (defalias 'timeclock-cancel-timer 'cancel-timer))
89
90 (defgroup timeclock nil
91   "Keeping track of the time that gets spent."
92   :group 'data)
93
94 ;;; User Variables:
95
96 (defcustom timeclock-file (convert-standard-filename "~/.timelog")
97   "*The file used to store timeclock data in."
98   :type 'file
99   :group 'timeclock)
100
101 (defcustom timeclock-workday (* 8 60 60)
102   "*The length of a work period."
103   :type 'integer
104   :group 'timeclock)
105
106 (defcustom timeclock-relative t
107   "*Whether to make reported time relative to `timeclock-workday'.
108 For example, if the length of a normal workday is eight hours, and you
109 work four hours on Monday, then the amount of time \"remaining\" on
110 Tuesday is twelve hours -- relative to an averaged work period of
111 eight hours -- or eight hours, non-relative.  So relative time takes
112 into account any discrepancy of time under-worked or over-worked on
113 previous days.  This only affects the timeclock modeline display."
114   :type 'boolean
115   :group 'timeclock)
116
117 (defcustom timeclock-get-project-function 'timeclock-ask-for-project
118   "*The function used to determine the name of the current project.
119 When clocking in, and no project is specified, this function will be
120 called to determine what is the current project to be worked on.
121 If this variable is nil, no questions will be asked."
122   :type 'function
123   :group 'timeclock)
124
125 (defcustom timeclock-get-reason-function 'timeclock-ask-for-reason
126   "*A function used to determine the reason for clocking out.
127 When clocking out, and no reason is specified, this function will be
128 called to determine what is the reason.
129 If this variable is nil, no questions will be asked."
130   :type 'function
131   :group 'timeclock)
132
133 (defcustom timeclock-get-workday-function nil
134   "*A function used to determine the length of today's workday.
135 The first time that a user clocks in each day, this function will be
136 called to determine what is the length of the current workday.  If
137 the return value is nil, or equal to `timeclock-workday', nothing special
138 will be done.  If it is a quantity different from `timeclock-workday',
139 however, a record will be output to the timelog file to note the fact that
140 that day has a length that is different from the norm."
141   :type '(choice (const nil) function)
142   :group 'timeclock)
143
144 (defcustom timeclock-ask-before-exiting t
145   "*If non-nil, ask if the user wants to clock out before exiting Emacs.
146 This variable only has effect if set with \\[customize]."
147   :set (lambda (symbol value)
148          (if value
149              (add-hook 'kill-emacs-query-functions 'timeclock-query-out)
150            (remove-hook 'kill-emacs-query-functions 'timeclock-query-out))
151          (setq timeclock-ask-before-exiting value))
152   :type 'boolean
153   :group 'timeclock)
154
155 (defvar timeclock-history '()
156   "History of previously used timeclock values.")
157
158 (defcustom timeclock-use-history nil
159   "*If non-nil, user is prompted for timestamp, previous values are
160 available via history mechanism.
161
162 \\{minibuffer-local-map}.
163
164 This variable only has effect if set with \\[customize]."
165 :type 'boolean
166 :group 'timeclock)
167
168 (defvar timeclock-update-timer nil
169   "The timer used to update `timeclock-mode-string'.")
170
171 ;; For byte-compiler.
172 (defvar display-time-hook)
173 (defvar timeclock-modeline-display)
174
175 (defcustom timeclock-use-display-time t
176   "*If non-nil, use `display-time-hook' for doing modeline updates.
177 The advantage of this is that one less timer has to be set running
178 amok in Emacs' process space.  The disadvantage is that it requires
179 you to have `display-time' running.  If you don't want to use
180 `display-time', but still want the modeline to show how much time is
181 left, set this variable to nil.  Changing the value of this variable
182 while timeclock information is being displayed in the modeline has no
183 effect.  You should call the function `timeclock-modeline-display' with
184 a positive argument to force an update."
185   :set (lambda (symbol value)
186          (let ((currently-displaying
187                 (and (boundp 'timeclock-modeline-display)
188                      timeclock-modeline-display)))
189            ;; if we're changing to the state that
190            ;; `timeclock-modeline-display' is already using, don't
191            ;; bother toggling it.  This happens on the initial loading
192            ;; of timeclock.el.
193            (if (and currently-displaying
194                     (or (and value
195                              (boundp 'display-time-hook)
196                              (memq 'timeclock-update-modeline
197                                    display-time-hook))
198                         (and (not value)
199                              timeclock-update-timer)))
200                (setq currently-displaying nil))
201            (and currently-displaying
202                 (set-variable 'timeclock-modeline-display nil))
203            (setq timeclock-use-display-time value)
204            (and currently-displaying
205                 (set-variable 'timeclock-modeline-display t))
206            timeclock-use-display-time))
207   :type 'boolean
208   :group 'timeclock
209   :require 'time)
210
211 (defcustom timeclock-first-in-hook nil
212   "*A hook run for the first \"in\" event each day.
213 Note that this hook is run before recording any events.  Thus the
214 value of `timeclock-hours-today', `timeclock-last-event' and the
215 return value of function `timeclock-last-period' are relative previous
216 to today."
217   :type 'hook
218   :group 'timeclock)
219
220 (defcustom timeclock-load-hook nil
221   "*Hook that gets run after timeclock has been loaded."
222   :type 'hook
223   :group 'timeclock)
224
225 (defcustom timeclock-in-hook nil
226   "*A hook run every time an \"in\" event is recorded."
227   :type 'hook
228   :group 'timeclock)
229
230 (defcustom timeclock-day-over-hook nil
231   "*A hook that is run when the workday has been completed.
232 This hook is only run if the current time remaining is being displayed
233 in the modeline.  See the variable `timeclock-modeline-display'."
234   :type 'hook
235   :group 'timeclock)
236
237 (defcustom timeclock-out-hook nil
238   "*A hook run every time an \"out\" event is recorded."
239   :type 'hook
240   :group 'timeclock)
241
242 (defcustom timeclock-done-hook nil
243   "*A hook run every time a project is marked as completed."
244   :type 'hook
245   :group 'timeclock)
246
247 (defcustom timeclock-event-hook nil
248   "*A hook run every time any event is recorded."
249   :type 'hook
250   :group 'timeclock)
251
252 (defvar timeclock-last-event nil
253   "A list containing the last event that was recorded.
254 The format of this list is (CODE TIME PROJECT).")
255
256 (defvar timeclock-last-event-workday nil
257   "The number of seconds in the workday of `timeclock-last-event'.")
258
259 ;;; Internal Variables:
260
261 (defvar timeclock-discrepancy nil
262   "A variable containing the time discrepancy before the last event.
263 Normally, timeclock assumes that you intend to work for
264 `timeclock-workday' seconds every day.  Any days in which you work
265 more or less than this amount is considered either a positive or
266 a negative discrepancy.  If you work in such a manner that the
267 discrepancy is always brought back to zero, then you will by
268 definition have worked an average amount equal to `timeclock-workday'
269 each day.")
270
271 (defvar timeclock-elapsed nil
272   "A variable containing the time elapsed for complete periods today.
273 This value is not accurate enough to be useful by itself.  Rather,
274 call `timeclock-workday-elapsed', to determine how much time has been
275 worked so far today.  Also, if `timeclock-relative' is nil, this value
276 will be the same as `timeclock-discrepancy'.")
277
278 (defvar timeclock-use-elapsed nil
279   "Non-nil if the modeline should display time elapsed, not remaining.")
280
281 (defvar timeclock-last-period nil
282   "Integer representing the number of seconds in the last period.
283 Note that you shouldn't access this value, but instead should use the
284 function `timeclock-last-period'.")
285
286 (defvar timeclock-mode-string nil
287   "The timeclock string (optionally) displayed in the modeline.
288 The time is bracketed by <> if you are clocked in, otherwise by [].")
289
290 (defvar timeclock-day-over nil
291   "The date of the last day when notified \"day over\" for.")
292
293 ;;; User Functions:
294
295 ;;;###autoload
296 (defun timeclock-modeline-display (&optional arg)
297   "Toggle display of the amount of time left today in the modeline.
298 If `timeclock-use-display-time' is non-nil (the default), then
299 the function `display-time-mode' must be active, and the modeline
300 will be updated whenever the time display is updated.  Otherwise,
301 the timeclock will use its own sixty second timer to do its
302 updating.  With prefix ARG, turn modeline display on if and only
303 if ARG is positive.  Returns the new status of timeclock modeline
304 display (non-nil means on)."
305   (interactive "P")
306   ;; cf display-time-mode.
307   (setq timeclock-mode-string "")
308   (or global-mode-string (setq global-mode-string '("")))
309   (let ((on-p (if arg
310                   (> (prefix-numeric-value arg) 0)
311                 (not timeclock-modeline-display))))
312     (if on-p
313         (progn
314           (or (memq 'timeclock-mode-string global-mode-string)
315               (setq global-mode-string
316                     (append global-mode-string '(timeclock-mode-string))))
317           (unless (memq 'timeclock-update-modeline timeclock-event-hook)
318             (add-hook 'timeclock-event-hook 'timeclock-update-modeline))
319           (when timeclock-update-timer
320             ;; XEmacs change, we don't have cancel-timer
321             (timeclock-cancel-timer timeclock-update-timer)
322             (setq timeclock-update-timer nil))
323           (if (boundp 'display-time-hook)
324               (remove-hook 'display-time-hook 'timeclock-update-modeline))
325           (if timeclock-use-display-time
326               (progn
327                 ;; Update immediately so there is a visible change
328                 ;; on calling this function.
329                 ;; (if display-time-mode (timeclock-update-modeline))
330                 ;; XEmacs change, our display-time doesn't have display-time-mode
331                 ;; So, we'll check display-time-string and see if it's nil
332                 (if (and (boundp 'display-time-string)
333                          display-time-string)
334                     (timeclock-update-modeline)
335                   (message "Activate `display-time-mode' to see \
336 timeclock information"))
337                 (add-hook 'display-time-hook 'timeclock-update-modeline))
338             (setq timeclock-update-timer
339                   (run-at-time nil 60 'timeclock-update-modeline))))
340       (setq global-mode-string
341             (delq 'timeclock-mode-string global-mode-string))
342       (remove-hook 'timeclock-event-hook 'timeclock-update-modeline)
343       (if (boundp 'display-time-hook)
344           (remove-hook 'display-time-hook
345                        'timeclock-update-modeline))
346       (when timeclock-update-timer
347         ;; XEmacs change, we don't have cancel-timer
348         (timeclock-cancel-timer timeclock-update-timer)
349         (setq timeclock-update-timer nil)))
350     (force-mode-line-update)
351     (setq timeclock-modeline-display on-p)))
352
353 ;; This has to be here so that the function definition of
354 ;; `timeclock-modeline-display' is known to the "set" function.
355 (defcustom timeclock-modeline-display nil
356   "Toggle modeline display of time remaining.
357 You must modify via \\[customize] for this variable to have an effect."
358   :set (lambda (symbol value)
359          (setq timeclock-modeline-display
360                (timeclock-modeline-display (or value 0))))
361   :type 'boolean
362   :group 'timeclock
363   :require 'timeclock)
364
365 (defsubst timeclock-time-to-date (time)
366   "Convert the TIME value to a textual date string."
367   (format-time-string "%Y/%m/%d" time))
368
369 ;;;###autoload
370 (defun timeclock-in (&optional arg project find-project)
371   "Clock in, recording the current time moment in the timelog.
372 With a numeric prefix ARG, record the fact that today has only that
373 many hours in it to be worked.  If arg is a non-numeric prefix arg
374 \(non-nil, but not a number), 0 is assumed (working on a holiday or
375 weekend).  *If not called interactively, ARG should be the number of
376 _seconds_ worked today*.  This feature only has effect the first time
377 this function is called within a day.
378
379 PROJECT is the project being clocked into.  If PROJECT is nil, and
380 FIND-PROJECT is non-nil -- or the user calls `timeclock-in'
381 interactively -- call the function `timeclock-get-project-function' to
382 discover the name of the project."
383   (interactive
384    (list (and current-prefix-arg
385               (if (numberp current-prefix-arg)
386                   (* current-prefix-arg 60 60)
387                 0))))
388   (if (equal (car timeclock-last-event) "i")
389       (error "You've already clocked in!")
390     (unless timeclock-last-event
391       (timeclock-reread-log))
392     ;; Either no log file, or day has rolled over.
393     (unless (and timeclock-last-event
394                  (equal (timeclock-time-to-date
395                          (cadr timeclock-last-event))
396                         (timeclock-time-to-date (current-time))))
397       (let ((workday (or (and (numberp arg) arg)
398                          (and arg 0)
399                          (and timeclock-get-workday-function
400                               (funcall timeclock-get-workday-function))
401                          timeclock-workday)))
402         (run-hooks 'timeclock-first-in-hook)
403         ;; settle the discrepancy for the new day
404         (setq timeclock-discrepancy
405               (- (or timeclock-discrepancy 0) workday))
406         (if (not (= workday timeclock-workday))
407             (timeclock-log "h" (and (numberp arg)
408                                     (number-to-string arg))))))
409     (timeclock-log "i" (or project
410                            (and timeclock-get-project-function
411                                 (or find-project (interactive-p))
412                                 (funcall timeclock-get-project-function))))
413     (run-hooks 'timeclock-in-hook)))
414
415 ;;;###autoload
416 (defun timeclock-out (&optional arg reason find-reason)
417   "Clock out, recording the current time moment in the timelog.
418 If a prefix ARG is given, the user has completed the project that was
419 begun during the last time segment.
420
421 REASON is the user's reason for clocking out.  If REASON is nil, and
422 FIND-REASON is non-nil -- or the user calls `timeclock-out'
423 interactively -- call the function `timeclock-get-reason-function' to
424 discover the reason."
425   (interactive "P")
426   (or timeclock-last-event
427       (error "You haven't clocked in!"))
428   (if (equal (downcase (car timeclock-last-event)) "o")
429       (error "You've already clocked out!")
430     (timeclock-log
431      (if arg "O" "o")
432      (or reason
433          (and timeclock-get-reason-function
434               (or find-reason (interactive-p))
435               (funcall timeclock-get-reason-function))))
436     (run-hooks 'timeclock-out-hook)
437     (if arg
438         (run-hooks 'timeclock-done-hook))))
439
440 ;; Should today-only be removed in favour of timeclock-relative? - gm
441 (defsubst timeclock-workday-remaining (&optional today-only)
442   "Return the number of seconds until the workday is complete.
443 The amount returned is relative to the value of `timeclock-workday'.
444 If TODAY-ONLY is non-nil, the value returned will be relative only to
445 the time worked today, and not to past time."
446   (let ((discrep (timeclock-find-discrep)))
447     (if discrep
448         (- (if today-only (cadr discrep)
449              (car discrep)))
450       0.0)))
451
452 ;;;###autoload
453 (defun timeclock-status-string (&optional show-seconds today-only)
454   "Report the overall timeclock status at the present moment.
455 If SHOW-SECONDS is non-nil, display second resolution.
456 If TODAY-ONLY is non-nil, the display will be relative only to time
457 worked today, ignoring the time worked on previous days."
458   (interactive "P")
459   (let ((remainder (timeclock-workday-remaining
460                     (or today-only
461                         (not timeclock-relative))))
462         (last-in (equal (car timeclock-last-event) "i"))
463         status)
464     (setq status
465           (format "Currently %s since %s (%s), %s %s, leave at %s"
466                   (if last-in "IN" "OUT")
467                   (if show-seconds
468                       (format-time-string "%-I:%M:%S %p"
469                                           (nth 1 timeclock-last-event))
470                     (format-time-string "%-I:%M %p"
471                                         (nth 1 timeclock-last-event)))
472                   (or (nth 2 timeclock-last-event)
473                       (if last-in "**UNKNOWN**" "workday over"))
474                   (timeclock-seconds-to-string remainder show-seconds t)
475                   (if (> remainder 0)
476                       "remaining" "over")
477                   (timeclock-when-to-leave-string show-seconds today-only)))
478     (if (interactive-p)
479         (message "%s" status)
480       status)))
481
482 ;;;###autoload
483 (defun timeclock-change (&optional arg project)
484   "Change to working on a different project.
485 This clocks out of the current project, then clocks in on a new one.
486 With a prefix ARG, consider the previous project as finished at the
487 time of changeover.  PROJECT is the name of the last project you were
488 working on."
489   (interactive "P")
490   (timeclock-out arg)
491   (timeclock-in nil project (interactive-p)))
492
493 ;;;###autoload
494 (defun timeclock-query-out ()
495   "Ask the user whether to clock out.
496 This is a useful function for adding to `kill-emacs-query-functions'."
497   (and (equal (car timeclock-last-event) "i")
498        (y-or-n-p "You're currently clocking time, clock out? ")
499        (timeclock-out))
500   ;; Unconditionally return t for `kill-emacs-query-functions'.
501   t)
502
503 ;;;###autoload
504 (defun timeclock-reread-log ()
505   "Re-read the timeclock, to account for external changes.
506 Returns the new value of `timeclock-discrepancy'."
507   (interactive)
508   (setq timeclock-discrepancy nil)
509   (timeclock-find-discrep)
510   (if (and timeclock-discrepancy timeclock-modeline-display)
511       (timeclock-update-modeline))
512   timeclock-discrepancy)
513
514 (defun timeclock-seconds-to-string (seconds &optional show-seconds
515                                             reverse-leader)
516   "Convert SECONDS into a compact time string.
517 If SHOW-SECONDS is non-nil, make the resolution of the return string
518 include the second count.  If REVERSE-LEADER is non-nil, it means to
519 output a \"+\" if the time value is negative, rather than a \"-\".
520 This is used when negative time values have an inverted meaning (such
521 as with time remaining, where negative time really means overtime)."
522   (if show-seconds
523       (format "%s%d:%02d:%02d"
524               (if (< seconds 0) (if reverse-leader "+" "-") "")
525               (truncate (/ (abs seconds) 60 60))
526               (% (truncate (/ (abs seconds) 60)) 60)
527               (% (truncate (abs seconds)) 60))
528     (format "%s%d:%02d"
529             (if (< seconds 0) (if reverse-leader "+" "-") "")
530             (truncate (/ (abs seconds) 60 60))
531             (% (truncate (/ (abs seconds) 60)) 60))))
532
533 (defsubst timeclock-currently-in-p ()
534   "Return non-nil if the user is currently clocked in."
535   (equal (car timeclock-last-event) "i"))
536
537 ;;;###autoload
538 (defun timeclock-workday-remaining-string (&optional show-seconds
539                                                      today-only)
540   "Return a string representing the amount of time left today.
541 Display second resolution if SHOW-SECONDS is non-nil.  If TODAY-ONLY
542 is non-nil, the display will be relative only to time worked today.
543 See `timeclock-relative' for more information about the meaning of
544 \"relative to today\"."
545   (interactive)
546   (let ((string (timeclock-seconds-to-string
547                  (timeclock-workday-remaining today-only)
548                  show-seconds t)))
549     (if (interactive-p)
550         (message "%s" string)
551       string)))
552
553 (defsubst timeclock-workday-elapsed ()
554   "Return the number of seconds worked so far today.
555 If RELATIVE is non-nil, the amount returned will be relative to past
556 time worked.  The default is to return only the time that has elapsed
557 so far today."
558   (let ((discrep (timeclock-find-discrep)))
559     (if discrep
560         (nth 2 discrep)
561       0.0)))
562
563 ;;;###autoload
564 (defun timeclock-workday-elapsed-string (&optional show-seconds)
565   "Return a string representing the amount of time worked today.
566 Display seconds resolution if SHOW-SECONDS is non-nil.  If RELATIVE is
567 non-nil, the amount returned will be relative to past time worked."
568   (interactive)
569   (let ((string (timeclock-seconds-to-string (timeclock-workday-elapsed)
570                                              show-seconds)))
571     (if (interactive-p)
572         (message "%s" string)
573       string)))
574
575 (defsubst timeclock-time-to-seconds (time)
576   "Convert TIME to a floating point number."
577   (+ (* (car time) 65536.0)
578      (cadr time)
579      (/ (or (car (cdr (cdr time))) 0) 1000000.0)))
580
581 (defsubst timeclock-seconds-to-time (seconds)
582   "Convert SECONDS (a floating point number) to an Emacs time structure."
583   (list (floor seconds 65536)
584         (floor (mod seconds 65536))
585         (floor (* (- seconds (ffloor seconds)) 1000000))))
586
587 ;; Should today-only be removed in favour of timeclock-relative? - gm
588 (defsubst timeclock-when-to-leave (&optional today-only)
589   "Return a time value representing the end of today's workday.
590 If TODAY-ONLY is non-nil, the value returned will be relative only to
591 the time worked today, and not to past time."
592   (timeclock-seconds-to-time
593    (- (timeclock-time-to-seconds (current-time))
594       (let ((discrep (timeclock-find-discrep)))
595         (if discrep
596             (if today-only
597                 (cadr discrep)
598               (car discrep))
599           0.0)))))
600
601 ;;;###autoload
602 (defun timeclock-when-to-leave-string (&optional show-seconds
603                                                  today-only)
604   "Return a string representing the end of today's workday.
605 This string is relative to the value of `timeclock-workday'.  If
606 SHOW-SECONDS is non-nil, the value printed/returned will include
607 seconds.  If TODAY-ONLY is non-nil, the value returned will be
608 relative only to the time worked today, and not to past time."
609   ;; Should today-only be removed in favour of timeclock-relative? - gm
610   (interactive)
611   (let* ((then (timeclock-when-to-leave today-only))
612          (string
613           (if show-seconds
614               (format-time-string "%-I:%M:%S %p" then)
615             (format-time-string "%-I:%M %p" then))))
616     (if (interactive-p)
617         (message "%s" string)
618       string)))
619
620 ;;; Internal Functions:
621
622 (defvar timeclock-project-list nil)
623 (defvar timeclock-last-project nil)
624
625 (defun timeclock-get-timeclock-file-buffer (file)
626   "Return the buffer visiting timeclock-file FILE."
627   (or
628    (get-file-buffer file)
629    (find-file-noselect file)))
630
631 (defun timeclock-completing-read (prompt alist &optional default)
632   "A version of `completing-read' that works on both Emacs and XEmacs."
633   (if (featurep 'xemacs)
634       (let ((str (completing-read prompt alist)))
635         (if (or (null str) (= (length str) 0))
636             default
637           str))
638     (completing-read prompt alist nil nil nil nil default)))
639
640 (defun timeclock-ask-for-project ()
641   "Ask the user for the project they are clocking into."
642   (timeclock-completing-read
643    (format "Clock into which project (default \"%s\"): "
644            (or timeclock-last-project
645                (car timeclock-project-list)))
646    (mapcar 'list timeclock-project-list)
647    (or timeclock-last-project
648        (car timeclock-project-list))))
649
650 (defvar timeclock-reason-list nil)
651
652 (defun timeclock-ask-for-reason ()
653   "Ask the user for the reason they are clocking out."
654   (timeclock-completing-read "Reason for clocking out: "
655                              (mapcar 'list timeclock-reason-list)))
656
657 (defun timeclock-update-modeline ()
658   "Update the `timeclock-mode-string' displayed in the modeline.
659 The value of `timeclock-relative' affects the display as described in
660 that variable's documentation."
661   (interactive)
662   (let ((remainder
663          (if timeclock-use-elapsed
664              (timeclock-workday-elapsed)
665            (timeclock-workday-remaining (not timeclock-relative))))
666         (last-in (equal (car timeclock-last-event) "i")))
667     (when (and (< remainder 0)
668                (not (and timeclock-day-over
669                          (equal timeclock-day-over
670                                 (timeclock-time-to-date
671                                  (current-time))))))
672       (setq timeclock-day-over
673             (timeclock-time-to-date (current-time)))
674       (run-hooks 'timeclock-day-over-hook))
675     (setq timeclock-mode-string
676           (propertize
677            (format " %c%s%c "
678                    (if last-in ?< ?[)
679                    (timeclock-seconds-to-string remainder nil t)
680                    (if last-in ?> ?]))
681            'help-echo "timeclock: time remaining"))))
682
683 (put 'timeclock-mode-string 'risky-local-variable t)
684
685 (defun timeclock-log (code &optional project)
686   "Log the event CODE to the timeclock log, at the time of call.
687 If PROJECT is a string, it represents the project which the event is
688 being logged for.  Normally only \"in\" events specify a project."
689   (with-current-buffer
690       (timeclock-get-timeclock-file-buffer timeclock-file)
691     (goto-char (point-max))
692     (if (not (bolp))
693         (insert "\n"))
694     (let ((now (current-time)))
695       (insert code " "
696               (if timeclock-use-history
697                   (read-string "timeclock time: "
698                                (format-time-string "%Y/%m/%d %H:%M:%S" now)
699                                'timeclock-history
700                                (format-time-string "%Y/%m/%d %H:%M:%S" now))
701                 (format-time-string "%Y/%m/%d %H:%M:%S" now))
702               (or (and project
703                        (stringp project)
704                        (> (length project) 0)
705                        (concat " " project))
706                   "")
707               "\n")
708       (if (equal (downcase code) "o")
709           (setq timeclock-last-period
710                 (- (timeclock-time-to-seconds now)
711                    (timeclock-time-to-seconds
712                     (cadr timeclock-last-event)))
713                 timeclock-discrepancy
714                 (+ timeclock-discrepancy
715                    timeclock-last-period)))
716       (setq timeclock-last-event (list code now project)))
717     (save-buffer)
718     (run-hooks 'timeclock-event-hook)
719     ;; APA: Don't kill buffer to avoid having to read in (potentially
720     ;; encrypted) file.
721     ;; (kill-buffer (current-buffer))
722     ))
723
724 (defvar timeclock-moment-regexp
725   (concat "\\([bhioO]\\)\\s-+"
726           "\\([0-9]+\\)/\\([0-9]+\\)/\\([0-9]+\\)\\s-+"
727           "\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)[ \t]*" "\\([^\n]*\\)"))
728
729 (defsubst timeclock-read-moment ()
730   "Read the moment under point from the timelog."
731   (cond
732    ((looking-at timeclock-moment-regexp)
733       (let ((code (match-string 1))
734             (year (string-to-number (match-string 2)))
735             (mon  (string-to-number (match-string 3)))
736             (mday (string-to-number (match-string 4)))
737             (hour (string-to-number (match-string 5)))
738             (min  (string-to-number (match-string 6)))
739             (sec  (string-to-number (match-string 7)))
740             (project (match-string 8)))
741       (list code (encode-time sec min hour mday mon year) project)))
742    ((not (eobp))
743     (error "unexpected data in %s, line %d: %s"
744            timeclock-file
745            ;; XEmacs change
746            (line-number)
747            (buffer-substring
748             (point-at-bol)
749             (point-at-eol))))))
750
751 (defun timeclock-last-period (&optional moment)
752   "Return the value of the last event period.
753 If the last event was a clock-in, the period will be open ended, and
754 growing every second.  Otherwise, it is a fixed amount which has been
755 recorded to disk.  If MOMENT is non-nil, use that as the current time.
756 This is only provided for coherency when used by
757 `timeclock-discrepancy'."
758   (if (equal (car timeclock-last-event) "i")
759       (- (timeclock-time-to-seconds (or moment (current-time)))
760          (timeclock-time-to-seconds
761           (cadr timeclock-last-event)))
762     timeclock-last-period))
763
764 (defsubst timeclock-entry-length (entry)
765   (- (timeclock-time-to-seconds (cadr entry))
766      (timeclock-time-to-seconds (car entry))))
767
768 (defsubst timeclock-entry-begin (entry)
769   (car entry))
770
771 (defsubst timeclock-entry-end (entry)
772   (cadr entry))
773
774 (defsubst timeclock-entry-project (entry)
775   (nth 2 entry))
776
777 (defsubst timeclock-entry-comment (entry)
778   (nth 3 entry))
779
780
781 (defsubst timeclock-entry-list-length (entry-list)
782   (let ((length 0))
783     (while entry-list
784       (setq length (+ length (timeclock-entry-length (car entry-list))))
785       (setq entry-list (cdr entry-list)))
786     length))
787
788 (defsubst timeclock-entry-list-begin (entry-list)
789   (timeclock-entry-begin (car entry-list)))
790
791 (defsubst timeclock-entry-list-end (entry-list)
792   (timeclock-entry-end (car (last entry-list))))
793
794 (defsubst timeclock-entry-list-span (entry-list)
795   (- (timeclock-time-to-seconds (timeclock-entry-list-end entry-list))
796      (timeclock-time-to-seconds (timeclock-entry-list-begin entry-list))))
797
798 (defsubst timeclock-entry-list-break (entry-list)
799   (- (timeclock-entry-list-span entry-list)
800      (timeclock-entry-list-length entry-list)))
801
802 (defsubst timeclock-entry-list-projects (entry-list)
803   (let (projects)
804     (while entry-list
805       (let ((project (timeclock-entry-project (car entry-list))))
806         (if projects
807             (add-to-list 'projects project)
808           (setq projects (list project))))
809       (setq entry-list (cdr entry-list)))
810     projects))
811
812
813 (defsubst timeclock-day-required (day)
814   (or (car day) timeclock-workday))
815
816 (defsubst timeclock-day-length (day)
817   (timeclock-entry-list-length (cdr day)))
818
819 (defsubst timeclock-day-debt (day)
820   (- (timeclock-day-required day)
821      (timeclock-day-length day)))
822
823 (defsubst timeclock-day-begin (day)
824   (timeclock-entry-list-begin (cdr day)))
825
826 (defsubst timeclock-day-end (day)
827   (timeclock-entry-list-end (cdr day)))
828
829 (defsubst timeclock-day-span (day)
830   (timeclock-entry-list-span (cdr day)))
831
832 (defsubst timeclock-day-break (day)
833   (timeclock-entry-list-break (cdr day)))
834
835 (defsubst timeclock-day-projects (day)
836   (timeclock-entry-list-projects (cdr day)))
837
838 (defmacro timeclock-day-list-template (func)
839   `(let ((length 0))
840      (while day-list
841        (setq length (+ length (,(eval func) (car day-list))))
842        (setq day-list (cdr day-list)))
843      length))
844
845 (defun timeclock-day-list-required (day-list)
846   (timeclock-day-list-template 'timeclock-day-required))
847
848 (defun timeclock-day-list-length (day-list)
849   (timeclock-day-list-template 'timeclock-day-length))
850
851 (defun timeclock-day-list-debt (day-list)
852   (timeclock-day-list-template 'timeclock-day-debt))
853
854 (defsubst timeclock-day-list-begin (day-list)
855   (timeclock-day-begin (car day-list)))
856
857 (defsubst timeclock-day-list-end (day-list)
858   (timeclock-day-end (car (last day-list))))
859
860 (defun timeclock-day-list-span (day-list)
861   (timeclock-day-list-template 'timeclock-day-span))
862
863 (defun timeclock-day-list-break (day-list)
864   (timeclock-day-list-template 'timeclock-day-break))
865
866 (defun timeclock-day-list-projects (day-list)
867   (let (projects)
868     (while day-list
869       (let ((projs (timeclock-day-projects (car day-list))))
870         (while projs
871           (if projects
872               (add-to-list 'projects (car projs))
873             (setq projects (list (car projs))))
874           (setq projs (cdr projs))))
875       (setq day-list (cdr day-list)))
876     projects))
877
878
879 (defsubst timeclock-current-debt (&optional log-data)
880   (nth 0 (or log-data (timeclock-log-data))))
881
882 (defsubst timeclock-day-alist (&optional log-data)
883   (nth 1 (or log-data (timeclock-log-data))))
884
885 (defun timeclock-day-list (&optional log-data)
886   (let ((alist (timeclock-day-alist log-data))
887         day-list)
888     (while alist
889       (setq day-list (cons (cdar alist) day-list)
890             alist (cdr alist)))
891     day-list))
892
893 (defsubst timeclock-project-alist (&optional log-data)
894   (nth 2 (or log-data (timeclock-log-data))))
895
896
897 (defun timeclock-log-data (&optional recent-only filename)
898   "Return the contents of the timelog file, in a useful format.
899 If the optional argument RECENT-ONLY is non-nil, only show the contents
900 from the last point where the time debt (see below) was set.
901 If the optional argument FILENAME is non-nil, it is used instead of
902 the file specified by `timeclock-file.'
903
904 A timelog contains data in the form of a single entry per line.
905 Each entry has the form:
906
907   CODE YYYY/MM/DD HH:MM:SS [COMMENT]
908
909 CODE is one of: b, h, i, o or O.  COMMENT is optional when the code is
910 i, o or O.  The meanings of the codes are:
911
912   b  Set the current time balance, or \"time debt\".  Useful when
913      archiving old log data, when a debt must be carried forward.
914      The COMMENT here is the number of seconds of debt.
915
916   h  Set the required working time for the given day.  This must
917      be the first entry for that day.  The COMMENT in this case is
918      the number of hours in this workday.  Floating point amounts
919      are allowed.
920
921   i  Clock in.  The COMMENT in this case should be the name of the
922      project worked on.
923
924   o  Clock out.  COMMENT is unnecessary, but can be used to provide
925      a description of how the period went, for example.
926
927   O  Final clock out.  Whatever project was being worked on, it is
928      now finished.  Useful for creating summary reports.
929
930 When this function is called, it will return a data structure with the
931 following format:
932
933   (DEBT ENTRIES-BY-DAY ENTRIES-BY-PROJECT)
934
935 DEBT is a floating point number representing the number of seconds
936 \"owed\" before any work was done.  For a new file (one without a 'b'
937 entry), this is always zero.
938
939 The two entries lists have similar formats.  They are both alists,
940 where the CAR is the index, and the CDR is a list of time entries.
941 For ENTRIES-BY-DAY, the CAR is a textual date string, of the form
942 YYYY/MM/DD.  For ENTRIES-BY-PROJECT, it is the name of the project
943 worked on, or t for the default project.
944
945 The CDR for ENTRIES-BY-DAY is slightly different than for
946 ENTRIES-BY-PROJECT.  It has the following form:
947
948   (DAY-LENGTH TIME-ENTRIES...)
949
950 For ENTRIES-BY-PROJECT, there is no DAY-LENGTH member.  It is simply a
951 list of TIME-ENTRIES.  Note that if DAY-LENGTH is nil, it means
952 whatever is the default should be used.
953
954 A TIME-ENTRY is a recorded time interval.  It has the following format
955 \(although generally one does not have to manipulate these entries
956 directly; see below):
957
958   (BEGIN-TIME END-TIME PROJECT [COMMENT] [FINAL-P])
959
960 Anyway, suffice it to say there are a lot of structures.  Typically
961 the user is expected to manipulate to the day(s) or project(s) that he
962 or she wants, at which point the following helper functions may be
963 used:
964
965   timeclock-day-required
966   timeclock-day-length
967   timeclock-day-debt
968   timeclock-day-begin
969   timeclock-day-end
970   timeclock-day-span
971   timeclock-day-break
972   timeclock-day-projects
973
974   timeclock-day-list-required
975   timeclock-day-list-length
976   timeclock-day-list-debt
977   timeclock-day-list-begin
978   timeclock-day-list-end
979   timeclock-day-list-span
980   timeclock-day-list-break
981   timeclock-day-list-projects
982
983   timeclock-entry-length
984   timeclock-entry-begin
985   timeclock-entry-end
986   timeclock-entry-project
987   timeclock-entry-comment
988
989   timeclock-entry-list-length
990   timeclock-entry-list-begin
991   timeclock-entry-list-end
992   timeclock-entry-list-span
993   timeclock-entry-list-break
994   timeclock-entry-list-projects
995
996 A few comments should make the use of the above functions obvious:
997
998   `required' is the amount of time that must be spent during a day, or
999   sequence of days, in order to have no debt.
1000
1001   `length' is the actual amount of time that was spent.
1002
1003   `debt' is the difference between required time and length.  A
1004   negative debt signifies overtime.
1005
1006   `begin' is the earliest moment at which work began.
1007
1008   `end' is the final moment work was done.
1009
1010   `span' is the difference between begin and end.
1011
1012   `break' is the difference between span and length.
1013
1014   `project' is the project that was worked on, and `projects' is a
1015   list of all the projects that were worked on during a given period.
1016
1017   `comment', where it applies, could mean anything.
1018
1019 There are a few more functions available, for locating day and entry
1020 lists:
1021
1022   timeclock-day-alist LOG-DATA
1023   timeclock-project-alist LOG-DATA
1024   timeclock-current-debt LOG-DATA
1025
1026 See the documentation for the given function if more info is needed."
1027   (let* ((log-data (list 0.0 nil nil))
1028          (now (current-time))
1029          (todays-date (timeclock-time-to-date now))
1030          last-date-limited last-date-seconds last-date
1031          last beg day entry event)
1032     (with-temp-buffer
1033       (insert-buffer
1034        (timeclock-get-timeclock-file-buffer (or filename timeclock-file)))
1035       (when recent-only
1036         (goto-char (point-max))
1037         (unless (re-search-backward "^b\\s-+" nil t)
1038           (goto-char (point-min))))
1039       (while (or (setq event (timeclock-read-moment))
1040                  (and beg (not last)
1041                       (setq last t event (list "o" now))))
1042         (cond ((equal (car event) "b")
1043                (setcar log-data (string-to-number (nth 2 event))))
1044               ((equal (car event) "h")
1045                (setq last-date-limited (timeclock-time-to-date (cadr event))
1046                      last-date-seconds (* (string-to-number (nth 2 event))
1047                                           3600.0)))
1048               ((equal (car event) "i")
1049                (if beg
1050                    (error "Error in format of timelog file, line %d"
1051                           (line-number))
1052                  (setq beg t))
1053                (setq entry (list (cadr event) nil
1054                                  (and (> (length (nth 2 event)) 0)
1055                                       (nth 2 event))))
1056                (let ((date (timeclock-time-to-date (cadr event))))
1057                  (if (and last-date
1058                           (not (equal date last-date)))
1059                      (progn
1060                        (setcar (cdr log-data)
1061                                (cons (cons last-date day)
1062                                      (cadr log-data)))
1063                        (setq day (list (and last-date-limited
1064                                             last-date-seconds))))
1065                    (unless day
1066                      (setq day (list (and last-date-limited
1067                                           last-date-seconds)))))
1068                  (setq last-date date
1069                        last-date-limited nil)))
1070               ((equal (downcase (car event)) "o")
1071                (if (not beg)
1072                    (error "Error in format of timelog file, line %d"
1073                           (line-number))
1074                  (setq beg nil))
1075                (setcar (cdr entry) (cadr event))
1076                (let ((desc (and (> (length (nth 2 event)) 0)
1077                                 (nth 2 event))))
1078                  (if desc
1079                      (nconc entry (list (nth 2 event))))
1080                  (if (equal (car event) "O")
1081                      (nconc entry (if desc
1082                                       (list t)
1083                                     (list nil t))))
1084                  (nconc day (list entry))
1085                  (setq desc (nth 2 entry))
1086                  (let ((proj (assoc desc (nth 2 log-data))))
1087                    (if (null proj)
1088                        (setcar (cddr log-data)
1089                                (cons (cons desc (list entry))
1090                                      (car (cddr log-data))))
1091                      (nconc (cdr proj) (list entry)))))))
1092         (forward-line))
1093       (if day
1094           (setcar (cdr log-data)
1095                   (cons (cons last-date day)
1096                         (cadr log-data))))
1097       log-data)))
1098
1099 (defun timeclock-find-discrep ()
1100   "Calculate time discrepancies, in seconds.
1101 The result is a three element list, containing the total time
1102 discrepancy, today's discrepancy, and the time worked today."
1103   ;; This is not implemented in terms of the functions above, because
1104   ;; it's a bit wasteful to read all of that data in, just to throw
1105   ;; away more than 90% of the information afterwards.
1106   ;;
1107   ;; If it were implemented using those functions, it would look
1108   ;; something like this:
1109   ;;  (let ((days (timeclock-day-alist (timeclock-log-data)))
1110   ;;        (total 0.0))
1111   ;;    (while days
1112   ;;      (setq total (+ total (- (timeclock-day-length (cdar days))
1113   ;;                              (timeclock-day-required (cdar days))))
1114   ;;            days (cdr days)))
1115   ;;    total)
1116   (let* ((now (current-time))
1117          (todays-date (timeclock-time-to-date now))
1118          (first t) (accum 0) (elapsed 0)
1119          event beg last-date avg
1120          last-date-limited last-date-seconds)
1121     (unless timeclock-discrepancy
1122       (when (file-readable-p timeclock-file)
1123         (setq timeclock-project-list nil
1124               timeclock-last-project nil
1125               timeclock-reason-list nil
1126               timeclock-elapsed 0)
1127         (with-temp-buffer
1128           (insert-buffer
1129            (timeclock-get-timeclock-file-buffer timeclock-file))
1130           (goto-char (point-max))
1131           (unless (re-search-backward "^b\\s-+" nil t)
1132             (goto-char (point-min)))
1133           (while (setq event (timeclock-read-moment))
1134             (cond ((equal (car event) "b")
1135                    (setq accum (string-to-number (nth 2 event))))
1136                   ((equal (car event) "h")
1137                    (setq last-date-limited
1138                          (timeclock-time-to-date (cadr event))
1139                          last-date-seconds
1140                          (* (string-to-number (nth 2 event)) 3600.0)))
1141                   ((equal (car event) "i")
1142                    (when (and (nth 2 event)
1143                               (> (length (nth 2 event)) 0))
1144                      (add-to-list 'timeclock-project-list (nth 2 event))
1145                      (setq timeclock-last-project (nth 2 event)))
1146                    (let ((date (timeclock-time-to-date (cadr event))))
1147                      (if (if last-date
1148                              (not (equal date last-date))
1149                            first)
1150                          (setq first nil
1151                                accum (- accum (if last-date-limited
1152                                                   last-date-seconds
1153                                                 timeclock-workday))))
1154                      (setq last-date date
1155                            last-date-limited nil)
1156                      (if beg
1157                          ;; XEmacs change
1158                          (error "Error in format of timelog file, line %d"
1159                                 (line-number))
1160                        (setq beg (timeclock-time-to-seconds (cadr event))))))
1161                   ((equal (downcase (car event)) "o")
1162                    (if (and (nth 2 event)
1163                             (> (length (nth 2 event)) 0))
1164                        (add-to-list 'timeclock-reason-list (nth 2 event)))
1165                    (if (not beg)
1166                        ;; XEmacs change
1167                        (error "Error in format of timelog file, line %d"
1168                               (line-number))
1169                      (setq timeclock-last-period
1170                            (- (timeclock-time-to-seconds (cadr event)) beg)
1171                            accum (+ timeclock-last-period accum)
1172                            beg nil))
1173                    (if (equal last-date todays-date)
1174                        (setq timeclock-elapsed
1175                              (+ timeclock-last-period timeclock-elapsed)))))
1176             (setq timeclock-last-event event
1177                   timeclock-last-event-workday
1178                   (if (equal (timeclock-time-to-date now) last-date-limited)
1179                       last-date-seconds
1180                     timeclock-workday))
1181             (forward-line))
1182           (setq timeclock-discrepancy accum))))
1183     (unless timeclock-last-event-workday
1184       (setq timeclock-last-event-workday timeclock-workday))
1185     (setq accum (or timeclock-discrepancy 0)
1186           elapsed (or timeclock-elapsed elapsed))
1187     (if timeclock-last-event
1188         (if (equal (car timeclock-last-event) "i")
1189             (let ((last-period (timeclock-last-period now)))
1190               (setq accum (+ accum last-period)
1191                     elapsed (+ elapsed last-period)))
1192           (if (not (equal (timeclock-time-to-date
1193                            (cadr timeclock-last-event))
1194                           (timeclock-time-to-date now)))
1195               (setq accum (- accum timeclock-last-event-workday)))))
1196     (list accum (- elapsed timeclock-last-event-workday)
1197           elapsed)))
1198
1199 ;;; A reporting function that uses timeclock-log-data
1200
1201 (defun timeclock-day-base (&optional time)
1202   "Given a time within a day, return 0:0:0 within that day.
1203 If optional argument TIME is non-nil, use that instead of the current time."
1204   (let ((decoded (decode-time (or time (current-time)))))
1205     (setcar (nthcdr 0 decoded) 0)
1206     (setcar (nthcdr 1 decoded) 0)
1207     (setcar (nthcdr 2 decoded) 0)
1208     (apply 'encode-time decoded)))
1209
1210 (defun timeclock-geometric-mean (l)
1211   "Compute the geometric mean of the values in the list L."
1212   (let ((total 0)
1213         (count 0))
1214     (while l
1215       (setq total (+ total (car l))
1216             count (1+ count)
1217             l (cdr l)))
1218     (if (> count 0)
1219         (/ total count)
1220       0)))
1221
1222 (defun timeclock-generate-report (&optional html-p)
1223   "Generate a summary report based on the current timelog file.
1224 By default, the report is in plain text, but if the optional argument
1225 HTML-P is non-nil, HTML markup is added."
1226   (interactive)
1227   (let ((log (timeclock-log-data))
1228         (today (timeclock-day-base)))
1229     (if html-p (insert "<p>"))
1230     (insert "Currently ")
1231     (let ((project (nth 2 timeclock-last-event))
1232           (begin (nth 1 timeclock-last-event))
1233           done)
1234       (if (timeclock-currently-in-p)
1235           (insert "IN")
1236         (if (or (null project) (= (length project) 0))
1237             (progn (insert "Done Working Today")
1238                    (setq done t))
1239           (insert "OUT")))
1240       (unless done
1241         (insert " since " (format-time-string "%Y/%m/%d %-I:%M %p" begin))
1242         (if html-p
1243             (insert "<br>\n<b>")
1244           (insert "\n*"))
1245         (if (timeclock-currently-in-p)
1246             (insert "Working on "))
1247         (if html-p
1248             (insert project "</b><br>\n")
1249           (insert project "*\n"))
1250         (let ((proj-data (cdr (assoc project (timeclock-project-alist log))))
1251               (two-weeks-ago (timeclock-seconds-to-time
1252                               (- (timeclock-time-to-seconds today)
1253                                  (* 2 7 24 60 60))))
1254               two-week-len today-len)
1255           (while proj-data
1256             (if (not (time-less-p
1257                       (timeclock-entry-begin (car proj-data)) today))
1258                 (setq today-len (timeclock-entry-list-length proj-data)
1259                       proj-data nil)
1260               (if (and (null two-week-len)
1261                        (not (time-less-p
1262                              (timeclock-entry-begin (car proj-data))
1263                              two-weeks-ago)))
1264                   (setq two-week-len (timeclock-entry-list-length proj-data)))
1265               (setq proj-data (cdr proj-data))))
1266           (if (null two-week-len)
1267               (setq two-week-len today-len))
1268           (if html-p (insert "<p>"))
1269           (if today-len
1270               (insert "\nTime spent on this task today: "
1271                       (timeclock-seconds-to-string today-len)
1272                       ".  In the last two weeks: "
1273                       (timeclock-seconds-to-string two-week-len))
1274             (if two-week-len
1275                 (insert "\nTime spent on this task in the last two weeks: "
1276                         (timeclock-seconds-to-string two-week-len))))
1277           (if html-p (insert "<br>"))
1278           (insert "\n"
1279                   (timeclock-seconds-to-string (timeclock-workday-elapsed))
1280                   " worked today, "
1281                   (timeclock-seconds-to-string (timeclock-workday-remaining))
1282                   " remaining, done at "
1283                   (timeclock-when-to-leave-string) "\n")))
1284       (if html-p (insert "<p>"))
1285       (insert "\nThere have been "
1286               (number-to-string
1287                (length (timeclock-day-alist log)))
1288               " days of activity, starting "
1289               (caar (last (timeclock-day-alist log))))
1290       (if html-p (insert "</p>"))
1291       (when html-p
1292         (insert "<p>
1293 <table>
1294 <td width=\"25\"><br></td><td>
1295 <table border=1 cellpadding=3>
1296 <tr><th><i>Statistics</i></th>
1297     <th>Entire</th>
1298     <th>-30 days</th>
1299     <th>-3 mons</th>
1300     <th>-6 mons</th>
1301     <th>-1 year</th>
1302 </tr>")
1303         (let* ((day-list (timeclock-day-list))
1304                (thirty-days-ago (timeclock-seconds-to-time
1305                                  (- (timeclock-time-to-seconds today)
1306                                     (* 30 24 60 60))))
1307                (three-months-ago (timeclock-seconds-to-time
1308                                   (- (timeclock-time-to-seconds today)
1309                                      (* 90 24 60 60))))
1310                (six-months-ago (timeclock-seconds-to-time
1311                                 (- (timeclock-time-to-seconds today)
1312                                    (* 180 24 60 60))))
1313                (one-year-ago (timeclock-seconds-to-time
1314                               (- (timeclock-time-to-seconds today)
1315                                  (* 365 24 60 60))))
1316                (time-in  (vector (list t) (list t) (list t) (list t) (list t)))
1317                (time-out (vector (list t) (list t) (list t) (list t) (list t)))
1318                (breaks   (vector (list t) (list t) (list t) (list t) (list t)))
1319                (workday  (vector (list t) (list t) (list t) (list t) (list t)))
1320                (lengths  (vector '(0 0) thirty-days-ago three-months-ago
1321                                  six-months-ago one-year-ago)))
1322           ;; collect statistics from complete timelog
1323           (while day-list
1324             (let ((i 0) (l 5))
1325               (while (< i l)
1326                 (unless (time-less-p
1327                          (timeclock-day-begin (car day-list))
1328                          (aref lengths i))
1329                   (let ((base (timeclock-time-to-seconds
1330                                (timeclock-day-base
1331                                 (timeclock-day-begin (car day-list))))))
1332                     (nconc (aref time-in i)
1333                            (list (- (timeclock-time-to-seconds
1334                                      (timeclock-day-begin (car day-list)))
1335                                     base)))
1336                     (let ((span (timeclock-day-span (car day-list)))
1337                           (len (timeclock-day-length (car day-list)))
1338                           (req (timeclock-day-required (car day-list))))
1339                       ;; If the day's actual work length is less than
1340                       ;; 70% of its span, then likely the exit time
1341                       ;; and break amount are not worthwhile adding to
1342                       ;; the statistic
1343                       (when (and (> span 0)
1344                                  (> (/ (float len) (float span)) 0.70))
1345                         (nconc (aref time-out i)
1346                                (list (- (timeclock-time-to-seconds
1347                                          (timeclock-day-end (car day-list)))
1348                                         base)))
1349                         (nconc (aref breaks i) (list (- span len))))
1350                       (if req
1351                           (setq len (+ len (- timeclock-workday req))))
1352                       (nconc (aref workday i) (list len)))))
1353                 (setq i (1+ i))))
1354             (setq day-list (cdr day-list)))
1355           ;; average statistics
1356           (let ((i 0) (l 5))
1357             (while (< i l)
1358               (aset time-in i (timeclock-geometric-mean
1359                                (cdr (aref time-in i))))
1360               (aset time-out i (timeclock-geometric-mean
1361                                 (cdr (aref time-out i))))
1362               (aset breaks i (timeclock-geometric-mean
1363                               (cdr (aref breaks i))))
1364               (aset workday i (timeclock-geometric-mean
1365                                (cdr (aref workday i))))
1366               (setq i (1+ i))))
1367           ;; Output the HTML table
1368           (insert "<tr>\n")
1369           (insert "<td align=\"center\">Time in</td>\n")
1370           (let ((i 0) (l 5))
1371             (while (< i l)
1372               (insert "<td align=\"right\">"
1373                       (timeclock-seconds-to-string (aref time-in i))
1374                       "</td>\n")
1375               (setq i (1+ i))))
1376           (insert "</tr>\n")
1377
1378           (insert "<tr>\n")
1379           (insert "<td align=\"center\">Time out</td>\n")
1380           (let ((i 0) (l 5))
1381             (while (< i l)
1382               (insert "<td align=\"right\">"
1383                       (timeclock-seconds-to-string (aref time-out i))
1384                       "</td>\n")
1385               (setq i (1+ i))))
1386           (insert "</tr>\n")
1387
1388           (insert "<tr>\n")
1389           (insert "<td align=\"center\">Break</td>\n")
1390           (let ((i 0) (l 5))
1391             (while (< i l)
1392               (insert "<td align=\"right\">"
1393                       (timeclock-seconds-to-string (aref breaks i))
1394                       "</td>\n")
1395               (setq i (1+ i))))
1396           (insert "</tr>\n")
1397
1398           (insert "<tr>\n")
1399           (insert "<td align=\"center\">Workday</td>\n")
1400           (let ((i 0) (l 5))
1401             (while (< i l)
1402               (insert "<td align=\"right\">"
1403                       (timeclock-seconds-to-string (aref workday i))
1404                       "</td>\n")
1405               (setq i (1+ i))))
1406           (insert "</tr>\n"))
1407         (insert "<tfoot>
1408 <td colspan=\"6\" align=\"center\">
1409   <i>These are approximate figures</i></td>
1410 </tfoot>
1411 </table>
1412 </td></table>")))))
1413
1414 ;;; A helpful little function
1415
1416 (defun timeclock-visit-timelog ()
1417   "Open the file named by `timeclock-file' in another window."
1418   (interactive)
1419   (switch-to-buffer-other-window
1420    (timeclock-get-timeclock-file-buffer timeclock-file)))
1421
1422 (provide 'timeclock)
1423
1424 (run-hooks 'timeclock-load-hook)
1425
1426 ;; make sure we know the list of reasons, projects, and have computed
1427 ;; the last event and current discrepancy.
1428 (if (file-readable-p timeclock-file)
1429     (timeclock-reread-log))
1430
1431 ;;; arch-tag: a0be3377-deb6-44ec-b9a2-a7be28436a40
1432 ;;; timeclock.el ends here