5fcb7c0f9d14f6b0fecc9fe838a8de65e8352de1
[gnus] / lisp / parse-time.el
1 ;;; parse-time.el --- parsing time strings
2
3 ;; Copyright (C) 1996, 2000-2015 Free Software Foundation, Inc.
4
5 ;; Author: Erik Naggum <erik@naggum.no>
6 ;; Keywords: util
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; With the introduction of the `encode-time', `decode-time', and
26 ;; `format-time-string' functions, dealing with time became simpler in
27 ;; Emacs.  However, parsing time strings is still largely a matter of
28 ;; heuristics and no common interface has been designed.
29
30 ;; `parse-time-string' parses a time in a string and returns a list of 9
31 ;; values, just like `decode-time', where unspecified elements in the
32 ;; string are returned as nil.  `encode-time' may be applied on these
33 ;; values to obtain an internal time value.
34
35 ;;; Code:
36
37 (eval-and-compile
38   (ignore-errors (require 'cl-lib)))
39 (eval-when-compile
40   (require 'cl)                         ;and ah ain't kiddin' 'bout it
41   (defalias 'parse-time-incf (if (featurep 'cl-lib) 'cl-incf 'incf)))
42
43 ;; Byte-compiler warnings
44 (defvar parse-time-elt)
45 (defvar parse-time-val)
46
47 (eval-and-compile
48   (if (featurep 'xemacs)
49       (progn
50         (defvar parse-time-syntax (make-vector 256 nil))
51         (loop for i from ?0 to ?9
52               do (aset parse-time-syntax i ?0))
53         (loop for i from ?A to ?Z
54               do (aset parse-time-syntax i ?A))
55         (loop for i from ?a to ?z
56               do (aset parse-time-syntax i ?a))
57         (aset parse-time-syntax ?+ 1)
58         (aset parse-time-syntax ?- -1)
59         (aset parse-time-syntax ?: ?d)
60         (defsubst parse-time-string-chars (char)
61           (and (< char (length parse-time-syntax))
62                (aref parse-time-syntax char))))
63     (defsubst parse-time-string-chars (char)
64       (save-match-data
65         (let (case-fold-search str)
66           (cond ((eq char ?+) 1)
67                 ((eq char ?-) -1)
68                 ((eq char ?:) ?d)
69                 ((string-match "[[:upper:]]" (setq str (string char))) ?A)
70                 ((string-match "[[:lower:]]" str) ?a)
71                 ((string-match "[[:digit:]]" str) ?0)))))))
72
73 (eval-and-compile
74   (if (fboundp 'cl-parse-integer)
75       (defalias 'parse-time-integer 'cl-parse-integer)
76     (defvar parse-time-digits (make-vector 256 nil))
77     (loop for i from ?0 to ?9
78           do (aset parse-time-digits i (- i ?0)))
79     (defun parse-time-integer (string &rest keys)
80       "[CL] Parse and return the integer in STRING, or nil if none."
81       (let* ((start (plist-get keys :start))
82              (end (or (plist-get keys :end) (length string)))
83              (integer 0)
84              (digit 0)
85              (index (or start 0)))
86         (when (< index end)
87           (let ((sign (aref string index)))
88             (if (or (eq sign ?+) (eq sign ?-))
89                 (setq sign (parse-time-string-chars sign)
90                       index (1+ index))
91               (setq sign 1))
92             (while (and (< index end)
93                         (setq digit (aref parse-time-digits
94                                           (aref string index))))
95               (setq integer (+ (* integer 10) digit)
96                     index (1+ index)))
97             (if (/= index end)
98                 (error "Not an integer string: `%s'" string)
99               (* sign integer))))))))
100
101 (defun parse-time-tokenize (string)
102   "Tokenize STRING into substrings."
103   (let ((start nil)
104         (end (length string))
105         (all-digits nil)
106         (list ())
107         (index 0)
108         (c nil))
109     (while (< index end)
110       (while (and (< index end)         ;Skip invalid characters.
111                   (not (setq c (parse-time-string-chars (aref string index)))))
112         (parse-time-incf index))
113       (setq start index all-digits (eq c ?0))
114       (while (and (< (parse-time-incf index) end) ;Scan valid characters.
115                   (setq c (parse-time-string-chars (aref string index))))
116         (setq all-digits (and all-digits (eq c ?0))))
117       (if (<= index end)
118           (push (if all-digits (parse-time-integer string
119                                                    :start start :end index)
120                   (substring string start index))
121                 list)))
122     (nreverse list)))
123
124 (defvar parse-time-months '(("jan" . 1) ("feb" . 2) ("mar" . 3)
125                             ("apr" . 4) ("may" . 5) ("jun" . 6)
126                             ("jul" . 7) ("aug" . 8) ("sep" . 9)
127                             ("oct" . 10) ("nov" . 11) ("dec" . 12)
128                             ("january" . 1) ("february" . 2)
129                             ("march" . 3) ("april" . 4) ("june" . 6)
130                             ("july" . 7) ("august" . 8)
131                             ("september" . 9) ("october" . 10)
132                             ("november" . 11) ("december" . 12)))
133 (defvar parse-time-weekdays '(("sun" . 0) ("mon" . 1) ("tue" . 2)
134                               ("wed" . 3) ("thu" . 4) ("fri" . 5)
135                               ("sat" . 6) ("sunday" . 0) ("monday" . 1)
136                               ("tuesday" . 2) ("wednesday" . 3)
137                               ("thursday" . 4) ("friday" . 5)
138                               ("saturday" . 6)))
139 (defvar parse-time-zoneinfo `(("z" 0) ("ut" 0) ("gmt" 0)
140                               ("pst" ,(* -8 3600)) ("pdt" ,(* -7 3600) t)
141                               ("mst" ,(* -7 3600)) ("mdt" ,(* -6 3600) t)
142                               ("cst" ,(* -6 3600)) ("cdt" ,(* -5 3600) t)
143                               ("est" ,(* -5 3600)) ("edt" ,(* -4 3600) t))
144   "(zoneinfo seconds-off daylight-savings-time-p)")
145
146 (defvar parse-time-rules
147   `(((6) parse-time-weekdays)
148     ((3) (1 31))
149     ((4) parse-time-months)
150     ((5) (100 ,most-positive-fixnum))
151     ((2 1 0)
152      ,#'(lambda () (and (stringp parse-time-elt)
153                         (= (length parse-time-elt) 8)
154                         (= (aref parse-time-elt 2) ?:)
155                         (= (aref parse-time-elt 5) ?:)))
156      [0 2] [3 5] [6 8])
157     ((8 7) parse-time-zoneinfo
158      ,#'(lambda () (car parse-time-val))
159      ,#'(lambda () (cadr parse-time-val)))
160     ((8)
161      ,#'(lambda ()
162           (and (stringp parse-time-elt)
163                (= 5 (length parse-time-elt))
164                (or (= (aref parse-time-elt 0) ?+)
165                    (= (aref parse-time-elt 0) ?-))))
166      ,#'(lambda () (* 60 (+ (parse-time-integer parse-time-elt :start 3 :end 5)
167                             (* 60 (parse-time-integer parse-time-elt
168                                                       :start 1 :end 3)))
169                       (if (= (aref parse-time-elt 0) ?-) -1 1))))
170     ((5 4 3)
171      ,#'(lambda () (and (stringp parse-time-elt)
172                         (= (length parse-time-elt) 10)
173                         (= (aref parse-time-elt 4) ?-)
174                         (= (aref parse-time-elt 7) ?-)))
175      [0 4] [5 7] [8 10])
176     ((2 1 0)
177      ,#'(lambda () (and (stringp parse-time-elt)
178                         (= (length parse-time-elt) 5)
179                         (= (aref parse-time-elt 2) ?:)))
180      [0 2] [3 5] ,#'(lambda () 0))
181     ((2 1 0)
182      ,#'(lambda () (and (stringp parse-time-elt)
183                         (= (length parse-time-elt) 4)
184                         (= (aref parse-time-elt 1) ?:)))
185      [0 1] [2 4] ,#'(lambda () 0))
186     ((2 1 0)
187      ,#'(lambda () (and (stringp parse-time-elt)
188                         (= (length parse-time-elt) 7)
189                         (= (aref parse-time-elt 1) ?:)))
190      [0 1] [2 4] [5 7])
191     ((5) (50 110) ,#'(lambda () (+ 1900 parse-time-elt)))
192     ((5) (0 49) ,#'(lambda () (+ 2000 parse-time-elt))))
193   "(slots predicate extractor...)")
194 ;;;###autoload(put 'parse-time-rules 'risky-local-variable t)
195
196 ;;;###autoload
197 (defun parse-time-string (string)
198   "Parse the time-string STRING into (SEC MIN HOUR DAY MON YEAR DOW DST TZ).
199 The values are identical to those of `decode-time', but any values that are
200 unknown are returned as nil."
201   (let ((time (list nil nil nil nil nil nil nil nil nil))
202         (temp (parse-time-tokenize (downcase string))))
203     (while temp
204       (let ((parse-time-elt (pop temp))
205             (rules parse-time-rules)
206             (exit nil))
207         (while (and rules (not exit))
208           (let* ((rule (pop rules))
209                  (slots (pop rule))
210                  (predicate (pop rule))
211                  (parse-time-val))
212             (when (and (not (nth (car slots) time)) ;not already set
213                        (setq parse-time-val
214                              (cond ((and (consp predicate)
215                                          (not (eq (car predicate)
216                                                   'lambda)))
217                                     (and (numberp parse-time-elt)
218                                          (<= (car predicate) parse-time-elt)
219                                          (<= parse-time-elt (cadr predicate))
220                                          parse-time-elt))
221                                    ((symbolp predicate)
222                                     (cdr (assoc parse-time-elt
223                                                 (symbol-value predicate))))
224                                    ((funcall predicate)))))
225               (setq exit t)
226               (while slots
227                 (let ((new-val (if rule
228                                    (let ((this (pop rule)))
229                                      (if (vectorp this)
230                                          (parse-time-integer
231                                           parse-time-elt
232                                           :start (aref this 0)
233                                           :end (aref this 1))
234                                        (funcall this)))
235                                  parse-time-val)))
236                   (rplaca (nthcdr (pop slots) time) new-val))))))))
237     time))
238
239 (defconst parse-time-iso8601-regexp
240   (let* ((dash "-?")
241          (colon ":?")
242          (4digit "\\([0-9][0-9][0-9][0-9]\\)")
243          (2digit "\\([0-9][0-9]\\)")
244          (date-fullyear 4digit)
245          (date-month 2digit)
246          (date-mday 2digit)
247          (time-hour 2digit)
248          (time-minute 2digit)
249          (time-second 2digit)
250          (time-secfrac "\\(\\.[0-9]+\\)?")
251          (time-numoffset (concat "[-+]\\(" time-hour "\\):" time-minute))
252          (time-offset (concat "Z" time-numoffset))
253          (partial-time (concat time-hour colon time-minute colon time-second
254                                time-secfrac))
255          (full-date (concat date-fullyear dash date-month dash date-mday))
256          (full-time (concat partial-time time-offset))
257          (date-time (concat full-date "T" full-time)))
258     (list (concat "^" full-date)
259           (concat "T" partial-time)
260           (concat "Z" time-numoffset)))
261   "List of regular expressions matching ISO 8601 dates.
262 1st regular expression matches the date.
263 2nd regular expression matches the time.
264 3rd regular expression matches the (optional) timezone specification.")
265
266 (defun parse-iso8601-time-string (date-string)
267   (let* ((date-re (nth 0 parse-time-iso8601-regexp))
268          (time-re (nth 1 parse-time-iso8601-regexp))
269          (tz-re (nth 2 parse-time-iso8601-regexp))
270          re-start
271          time seconds minute hour fractional-seconds
272          day month year day-of-week dst tz)
273     ;; We need to populate 'time' with
274     ;; (SEC MIN HOUR DAY MON YEAR DOW DST TZ)
275
276     ;; Nobody else handles iso8601 correctly, let's do it ourselves.
277     (when (string-match date-re date-string re-start)
278       (setq year (string-to-number (match-string 1 date-string))
279             month (string-to-number (match-string 2 date-string))
280             day (string-to-number (match-string 3 date-string))
281             re-start (match-end 0))
282       (when (string-match time-re date-string re-start)
283         (setq hour (string-to-number (match-string 1 date-string))
284               minute (string-to-number (match-string 2 date-string))
285               seconds (string-to-number (match-string 3 date-string))
286               fractional-seconds (string-to-number (or
287                                                     (match-string 4 date-string)
288                                                     "0"))
289               re-start (match-end 0))
290         (when (string-match tz-re date-string re-start)
291           (setq tz (match-string 1 date-string)))
292         (setq time (list seconds minute hour day month year day-of-week dst tz))))
293
294     ;; Fall back to having Gnus do fancy things for us.
295     (when (not time)
296       (setq time (parse-time-string date-string)))
297
298     (and time
299          (apply 'encode-time time))))
300
301 (provide 'parse-time)
302
303 ;;; parse-time.el ends here