(nnimap-request-list): Protect against not being able to open the server.
[gnus] / lisp / time-date.el
1 ;;; time-date.el --- Date and time handling functions
2
3 ;; Copyright (C) 1998-2011  Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Masanobu Umeda <umerin@mse.kyutech.ac.jp>
7 ;; Keywords: mail news util
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Time values come in three formats.  The oldest format is a cons
27 ;; cell of the form (HIGH . LOW).  This format is obsolete, but still
28 ;; supported.  The two other formats are the lists (HIGH LOW) and
29 ;; (HIGH LOW MICRO).  The first two formats specify HIGH * 2^16 + LOW
30 ;; seconds; the third format specifies HIGH * 2^16 + LOW + MICRO /
31 ;; 1000000 seconds.  We should have 0 <= MICRO < 1000000 and 0 <= LOW
32 ;; < 2^16.  If the time value represents a point in time, then HIGH is
33 ;; nonnegative.  If the time value is a time difference, then HIGH can
34 ;; be negative as well.  The macro `with-decoded-time-value' and the
35 ;; function `encode-time-value' make it easier to deal with these
36 ;; three formats.  See `time-subtract' for an example of how to use
37 ;; them.
38
39 ;;; Code:
40
41 (defmacro with-decoded-time-value (varlist &rest body)
42   "Decode a time value and bind it according to VARLIST, then eval BODY.
43
44 The value of the last form in BODY is returned.
45
46 Each element of the list VARLIST is a list of the form
47 \(HIGH-SYMBOL LOW-SYMBOL MICRO-SYMBOL [TYPE-SYMBOL] TIME-VALUE).
48 The time value TIME-VALUE is decoded and the result it bound to
49 the symbols HIGH-SYMBOL, LOW-SYMBOL and MICRO-SYMBOL.
50
51 The optional TYPE-SYMBOL is bound to the type of the time value.
52 Type 0 is the cons cell (HIGH . LOW), type 1 is the list (HIGH
53 LOW), and type 2 is the list (HIGH LOW MICRO)."
54   (declare (indent 1)
55            (debug ((&rest (symbolp symbolp symbolp &or [symbolp form] form))
56                    body)))
57   (if varlist
58       (let* ((elt (pop varlist))
59              (high (pop elt))
60              (low (pop elt))
61              (micro (pop elt))
62              (type (unless (eq (length elt) 1)
63                      (pop elt)))
64              (time-value (car elt))
65              (gensym (make-symbol "time")))
66         `(let* ,(append `((,gensym ,time-value)
67                           (,high (pop ,gensym))
68                           ,low ,micro)
69                         (when type `(,type)))
70            (if (consp ,gensym)
71                (progn
72                  (setq ,low (pop ,gensym))
73                  (if ,gensym
74                      ,(append `(setq ,micro (car ,gensym))
75                               (when type `(,type 2)))
76                    ,(append `(setq ,micro 0)
77                             (when type `(,type 1)))))
78              ,(append `(setq ,low ,gensym ,micro 0)
79                       (when type `(,type 0))))
80            (with-decoded-time-value ,varlist ,@body)))
81     `(progn ,@body)))
82
83 (defun encode-time-value (high low micro type)
84   "Encode HIGH, LOW, and MICRO into a time value of type TYPE.
85 Type 0 is the cons cell (HIGH . LOW), type 1 is the list (HIGH LOW),
86 and type 2 is the list (HIGH LOW MICRO)."
87   (cond
88    ((eq type 0) (cons high low))
89    ((eq type 1) (list high low))
90    ((eq type 2) (list high low micro))))
91
92 (autoload 'parse-time-string "parse-time")
93 (autoload 'timezone-make-date-arpa-standard "timezone")
94
95 ;;;###autoload
96 ;; `parse-time-string' isn't sufficiently general or robust.  It fails
97 ;; to grok some of the formats that timezone does (e.g. dodgy
98 ;; post-2000 stuff from some Elms) and either fails or returns bogus
99 ;; values.  timezone-make-date-arpa-standard should help.
100 (defun date-to-time (date)
101   "Parse a string DATE that represents a date-time and return a time value.
102 If DATE lacks timezone information, GMT is assumed."
103   (condition-case ()
104       (apply 'encode-time (parse-time-string date))
105     (error (condition-case ()
106                (apply 'encode-time
107                       (parse-time-string
108                        (timezone-make-date-arpa-standard date)))
109              (error (error "Invalid date: %s" date))))))
110
111 ;; Bit of a mess.  Emacs has float-time since at least 21.1.
112 ;; This file is synced to Gnus, and XEmacs packages may have been written
113 ;; using time-to-seconds from the Gnus library.
114 ;;;###autoload(if (or (featurep 'emacs)
115 ;;;###autoload        (and (fboundp 'float-time)
116 ;;;###autoload             (subrp (symbol-function 'float-time))))
117 ;;;###autoload    (progn
118 ;;;###autoload      (defalias 'time-to-seconds 'float-time)
119 ;;;###autoload      (make-obsolete 'time-to-seconds 'float-time "21.1"))
120 ;;;###autoload  (autoload 'time-to-seconds "time-date"))
121
122 (eval-when-compile
123   (or (featurep 'emacs)
124       (and (fboundp 'float-time)
125            (subrp (symbol-function 'float-time)))
126       (defun time-to-seconds (time)
127         "Convert time value TIME to a floating point number."
128         (with-decoded-time-value ((high low micro time))
129           (+ (* 1.0 high 65536)
130              low
131              (/ micro 1000000.0))))))
132
133 ;;;###autoload
134 (defun seconds-to-time (seconds)
135   "Convert SECONDS (a floating point number) to a time value."
136   (list (floor seconds 65536)
137         (floor (mod seconds 65536))
138         (floor (* (- seconds (ffloor seconds)) 1000000))))
139
140 ;;;###autoload
141 (defun time-less-p (t1 t2)
142   "Return non-nil if time value T1 is earlier than time value T2."
143   (with-decoded-time-value ((high1 low1 micro1 t1)
144                             (high2 low2 micro2 t2))
145     (or (< high1 high2)
146         (and (= high1 high2)
147              (or (< low1 low2)
148                  (and (= low1 low2)
149                       (< micro1 micro2)))))))
150
151 ;;;###autoload
152 (defun days-to-time (days)
153   "Convert DAYS into a time value."
154   (let* ((seconds (* 1.0 days 60 60 24))
155          (high (condition-case nil (floor (/ seconds 65536))
156                  (range-error most-positive-fixnum))))
157     (list high (condition-case nil (floor (- seconds (* 1.0 high 65536)))
158                  (range-error 65535)))))
159
160 ;;;###autoload
161 (defun time-since (time)
162   "Return the time elapsed since TIME.
163 TIME should be either a time value or a date-time string."
164   (when (stringp time)
165     ;; Convert date strings to internal time.
166     (setq time (date-to-time time)))
167   (time-subtract (current-time) time))
168
169 ;;;###autoload
170 (defalias 'subtract-time 'time-subtract)
171
172 ;;;###autoload
173 (defun time-subtract (t1 t2)
174   "Subtract two time values, T1 minus T2.
175 Return the difference in the format of a time value."
176   (with-decoded-time-value ((high low micro type t1)
177                             (high2 low2 micro2 type2 t2))
178     (setq high (- high high2)
179           low (- low low2)
180           micro (- micro micro2)
181           type (max type type2))
182     (when (< micro 0)
183       (setq low (1- low)
184             micro (+ micro 1000000)))
185     (when (< low 0)
186       (setq high (1- high)
187             low (+ low 65536)))
188     (encode-time-value high low micro type)))
189
190 ;;;###autoload
191 (defun time-add (t1 t2)
192   "Add two time values T1 and T2.  One should represent a time difference."
193   (with-decoded-time-value ((high low micro type t1)
194                             (high2 low2 micro2 type2 t2))
195     (setq high (+ high high2)
196           low (+ low low2)
197           micro (+ micro micro2)
198           type (max type type2))
199     (when (>= micro 1000000)
200       (setq low (1+ low)
201             micro (- micro 1000000)))
202     (when (>= low 65536)
203       (setq high (1+ high)
204             low (- low 65536)))
205     (encode-time-value high low micro type)))
206
207 ;;;###autoload
208 (defun date-to-day (date)
209   "Return the number of days between year 1 and DATE.
210 DATE should be a date-time string."
211   (time-to-days (date-to-time date)))
212
213 ;;;###autoload
214 (defun days-between (date1 date2)
215   "Return the number of days between DATE1 and DATE2.
216 DATE1 and DATE2 should be date-time strings."
217   (- (date-to-day date1) (date-to-day date2)))
218
219 ;;;###autoload
220 (defun date-leap-year-p (year)
221   "Return t if YEAR is a leap year."
222   (or (and (zerop (% year 4))
223            (not (zerop (% year 100))))
224       (zerop (% year 400))))
225
226 ;;;###autoload
227 (defun time-to-day-in-year (time)
228   "Return the day number within the year corresponding to TIME."
229   (let* ((tim (decode-time time))
230          (month (nth 4 tim))
231          (day (nth 3 tim))
232          (year (nth 5 tim))
233          (day-of-year (+ day (* 31 (1- month)))))
234     (when (> month 2)
235       (setq day-of-year (- day-of-year (/ (+ 23 (* 4 month)) 10)))
236       (when (date-leap-year-p year)
237         (setq day-of-year (1+ day-of-year))))
238     day-of-year))
239
240 ;;;###autoload
241 (defun time-to-days (time)
242   "The number of days between the Gregorian date 0001-12-31bce and TIME.
243 TIME should be a time value.
244 The Gregorian date Sunday, December 31, 1bce is imaginary."
245   (let* ((tim (decode-time time))
246          (month (nth 4 tim))
247          (day (nth 3 tim))
248          (year (nth 5 tim)))
249     (+ (time-to-day-in-year time)       ;       Days this year
250        (* 365 (1- year))                ;       + Days in prior years
251        (/ (1- year) 4)                  ;       + Julian leap years
252        (- (/ (1- year) 100))            ;       - century years
253        (/ (1- year) 400))))             ;       + Gregorian leap years
254
255 (defun time-to-number-of-days (time)
256   "Return the number of days represented by TIME.
257 Returns a floating point number."
258   (/ (funcall (eval-when-compile
259                 (if (or (featurep 'emacs)
260                         (and (fboundp 'float-time)
261                              (subrp (symbol-function 'float-time))))
262                     'float-time
263                   'time-to-seconds)) time) (* 60 60 24)))
264
265 ;;;###autoload
266 (defun safe-date-to-time (date)
267   "Parse a string DATE that represents a date-time and return a time value.
268 If DATE is malformed, return a time value of zeros."
269   (condition-case ()
270       (date-to-time date)
271     (error '(0 0))))
272
273 \f
274 ;;;###autoload
275 (defun format-seconds (string seconds)
276   "Use format control STRING to format the number SECONDS.
277 The valid format specifiers are:
278 %y is the number of (365-day) years.
279 %d is the number of days.
280 %h is the number of hours.
281 %m is the number of minutes.
282 %s is the number of seconds.
283 %z is a non-printing control flag (see below).
284 %% is a literal \"%\".
285
286 Upper-case specifiers are followed by the unit-name (e.g. \"years\").
287 Lower-case specifiers return only the unit.
288
289 \"%\" may be followed by a number specifying a width, with an
290 optional leading \".\" for zero-padding.  For example, \"%.3Y\" will
291 return something of the form \"001 year\".
292
293 The \"%z\" specifier does not print anything.  When it is used, specifiers
294 must be given in order of decreasing size.  To the left of \"%z\", nothing
295 is output until the first non-zero unit is encountered.
296
297 This function does not work for SECONDS greater than `most-positive-fixnum'."
298   (let ((start 0)
299         (units '(("y" "year"   31536000)
300                  ("d" "day"       86400)
301                  ("h" "hour"       3600)
302                  ("m" "minute"       60)
303                  ("s" "second"        1)
304                  ("z")))
305         (case-fold-search t)
306         spec match usedunits zeroflag larger prev name unit num zeropos)
307     (while (string-match "%\\.?[0-9]*\\(.\\)" string start)
308       (setq start (match-end 0)
309             spec (match-string 1 string))
310       (unless (string-equal spec "%")
311         ;; `assoc-string' is not available in XEmacs.  So when compiling
312         ;; Gnus (`time-date.el' is part of Gnus) with XEmacs, we get
313         ;; a warning here.  But `format-seconds' is not used anywhere in
314         ;; Gnus so it's not a real problem. --rsteib
315         (or (setq match (assoc-string spec units t))
316             (error "Bad format specifier: `%s'" spec))
317         (if (assoc-string spec usedunits t)
318             (error "Multiple instances of specifier: `%s'" spec))
319         (if (string-equal (car match) "z")
320             (setq zeroflag t)
321           (unless larger
322             (setq unit (nth 2 match)
323                   larger (and prev (> unit prev))
324                   prev unit)))
325         (push match usedunits)))
326     (and zeroflag larger
327          (error "Units are not in decreasing order of size"))
328     (dolist (u units)
329       (setq spec (car u)
330             name (cadr u)
331             unit (nth 2 u))
332       (when (string-match (format "%%\\(\\.?[0-9]+\\)?\\(%s\\)" spec) string)
333         (if (string-equal spec "z")     ; must be last in units
334             (setq string
335                   (replace-regexp-in-string
336                    "%z" ""
337                    (substring string (min (or zeropos (match-end 0))
338                                           (match-beginning 0)))))
339           ;; Cf article-make-date-line in gnus-art.
340           (setq num (floor seconds unit)
341                 seconds (- seconds (* num unit)))
342           ;; Start position of the first non-zero unit.
343           (or zeropos
344               (setq zeropos (unless (zerop num) (match-beginning 0))))
345           (setq string
346                 (replace-match
347                  (format (concat "%" (match-string 1 string) "d%s") num
348                          (if (string-equal (match-string 2 string) spec)
349                              ""       ; lower-case, no unit-name
350                            (format " %s%s" name
351                                    (if (= num 1) "" "s"))))
352                  t t string))))))
353   (replace-regexp-in-string "%%" "%" string))
354
355
356 (provide 'time-date)
357
358 ;;; time-date.el ends here