Use *-function instead of *-func.
[elisp/wanderlust.git] / wl / wl-util.el
1 ;;; wl-util.el -- Utility modules for Wanderlust.
2
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
4 ;; Copyright (C) 2000 A. SAGATA <sagata@nttvdt.hil.ntt.co.jp>
5 ;; Copyright (C) 2000 Katsumi Yamaoka <yamaoka@jpl.org>
6
7 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
8 ;;      A. SAGATA <sagata@nttvdt.hil.ntt.co.jp>
9 ;;      Katsumi Yamaoka <yamaoka@jpl.org>
10 ;; Keywords: mail, net news
11
12 ;; This file is part of Wanderlust (Yet Another Message Interface on Emacsen).
13
14 ;; This program is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18 ;;
19 ;; This program is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23 ;;
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28 ;;
29
30 ;;; Commentary:
31 ;;
32
33 ;;; Code:
34 ;;
35
36 (eval-when-compile
37   (require 'elmo-util))
38
39 (condition-case nil (require 'tm-edit) (error nil))
40 (condition-case nil (require 'pp) (error nil))
41
42 (eval-when-compile
43   (require 'time-stamp)
44   (defalias-maybe 'next-command-event 'ignore)
45   (defalias-maybe 'event-to-character 'ignore)
46   (defalias-maybe 'key-press-event-p 'ignore)
47   (defalias-maybe 'button-press-event-p 'ignore)
48   (defalias-maybe 'set-process-kanji-code 'ignore)
49   (defalias-maybe 'set-process-coding-system 'ignore)
50   (defalias-maybe 'dispatch-event 'ignore))
51
52 (defalias 'wl-set-work-buf 'elmo-set-work-buf)
53 (make-obsolete 'wl-set-work-buf 'elmo-set-work-buf)
54
55 (defmacro wl-append (val func)
56   (list 'if val
57       (list 'nconc val func)
58     (list 'setq val func)))
59
60 (defalias 'wl-parse 'elmo-parse)
61 (make-obsolete 'wl-parse 'elmo-parse)
62
63 (defun wl-delete-duplicates (list &optional all hack-addresses)
64   "Delete duplicate equivalent strings from the LIST.
65 If ALL is t, then if there is more than one occurrence of a string in the LIST,
66  then all occurrences of it are removed instead of just the subsequent ones.
67 If HACK-ADDRESSES is t, then the strings are considered to be mail addresses,
68  and only the address part is compared (so that \"Name <foo>\" and \"foo\"
69  would be considered to be equivalent.)"
70   (let ((hashtable (make-vector 29 0))
71         (new-list nil)
72         sym-string sym)
73     (fillarray hashtable 0)
74     (while list
75       (setq sym-string
76             (if hack-addresses
77                 (wl-address-header-extract-address (car list))
78               (car list))
79             sym-string (or sym-string "-unparseable-garbage-")
80             sym (intern sym-string hashtable))
81       (if (boundp sym)
82           (and all (setcar (symbol-value sym) nil))
83         (setq new-list (cons (car list) new-list))
84         (set sym new-list))
85       (setq list (cdr list)))
86     (delq nil (nreverse new-list))))
87
88 ;; string utils.
89 (defalias 'wl-string-member 'elmo-string-member)
90 (defalias 'wl-string-match-member 'elmo-string-match-member)
91 (defalias 'wl-string-delete-match 'elmo-string-delete-match)
92 (defalias 'wl-string-match-assoc 'elmo-string-match-assoc)
93 (defalias 'wl-string-assoc 'elmo-string-assoc)
94 (defalias 'wl-string-rassoc 'elmo-string-rassoc)
95
96 (defun wl-parse-addresses (string)
97   (if (null string)
98       ()
99     (elmo-set-work-buf
100      ;;(unwind-protect
101      (let (list start s char)
102        (insert string)
103        (goto-char (point-min))
104        (skip-chars-forward "\t\f\n\r ")
105        (setq start (point))
106        (while (not (eobp))
107          (skip-chars-forward "^\"\\,(")
108          (setq char (following-char))
109          (cond ((= char ?\\)
110                 (forward-char 1)
111                 (if (not (eobp))
112                     (forward-char 1)))
113                ((= char ?,)
114                 (setq s (buffer-substring start (point)))
115                 (if (or (null (string-match "^[\t\f\n\r ]+$" s))
116                         (not (string= s "")))
117                     (setq list (cons s list)))
118                 (skip-chars-forward ",\t\f\n\r ")
119                 (setq start (point)))
120                ((= char ?\")
121                 (re-search-forward "[^\\]\"" nil 0))
122                ((= char ?\()
123                 (let ((parens 1))
124                   (forward-char 1)
125                   (while (and (not (eobp)) (not (zerop parens)))
126                     (re-search-forward "[()]" nil 0)
127                     (cond ((or (eobp)
128                                (= (char-after (- (point) 2)) ?\\)))
129                           ((= (preceding-char) ?\()
130                            (setq parens (1+ parens)))
131                           (t
132                            (setq parens (1- parens)))))))))
133        (setq s (buffer-substring start (point)))
134        (if (and (null (string-match "^[\t\f\n\r ]+$" s))
135                 (not (string= s "")))
136            (setq list (cons s list)))
137        (nreverse list)) ; jwz: fixed order
138      )))
139
140 (defun wl-append-element (list element)
141   (if element
142       (append list (list element))
143     list))
144
145 (defmacro wl-push (v l)
146   "Insert V at the head of the list stored in L."
147   (list 'setq l (list 'cons v l)))
148
149 (defmacro wl-pop (l)
150   "Remove the head of the list stored in L."
151   (list 'car (list 'prog1 l (list 'setq l (list 'cdr l)))))
152
153 (defun wl-ask-folder (func mes-string)
154   (let* (key keve
155              (cmd (if (featurep 'xemacs)
156                       (event-to-character last-command-event)
157                     (string-to-char (format "%s" (this-command-keys))))))
158     (message mes-string)
159     (setq key (car (setq keve (wl-read-event-char))))
160     (if (or (equal key ?\ )
161             (and cmd
162                  (equal key cmd)))
163         (progn
164           (message "")
165           (funcall func))
166       (wl-push (cdr keve) unread-command-events))))
167
168 ;(defalias 'wl-make-hash 'elmo-make-hash)
169 ;;(make-obsolete 'wl-make-hash 'elmo-make-hash)
170
171 ;;(defalias 'wl-get-hash-val 'elmo-get-hash-val)
172 ;;(make-obsolete 'wl-get-hash-val 'elmo-get-hash-val)
173
174 ;;(defalias 'wl-set-hash-val 'elmo-set-hash-val)
175 ;;(make-obsolete 'wl-set-hash-val 'elmo-set-hash-val)
176
177 (defsubst wl-set-string-width (width string)
178   (elmo-set-work-buf
179    (elmo-set-buffer-multibyte default-enable-multibyte-characters)
180    (insert string)
181    (if (> (current-column) width)
182        (if (> (move-to-column width) width)
183            (progn
184              (condition-case nil ; ignore error
185                  (backward-char 1)
186                (error))
187              (concat (buffer-substring (point-min) (point)) " "))
188          (buffer-substring (point-min) (point)))
189      (if (= (current-column) width)
190          string
191        (concat string
192                (format (format "%%%ds"
193                                (- width (current-column)))
194                        " "))))))
195
196 (defun wl-display-bytes (num)
197   (let (result remain)
198     (cond
199      ((> (setq result (/ num 1000000)) 0)
200       (setq remain (% num 1000000))
201       (if (> remain 400000)
202           (setq result (+ 1 result)))
203       (format "%dM" result))
204      ((> (setq result (/ num 1000)) 0)
205       (setq remain (% num 1000))
206       (if (> remain 400)
207           (setq result (+ 1 result)))
208       (format "%dK" result))
209      (t (format "%dB" result)))))
210
211 (defun wl-mode-line-buffer-identification (&optional id)
212   (let ((priorities '(biff plug title)))
213     (let ((items (reverse wl-mode-line-display-priority-list))
214           item)
215       (while items
216         (setq item (car items)
217               items (cdr items))
218         (unless (memq item '(biff plug))
219           (setq item 'title))
220         (setq priorities (cons item (delq item priorities)))))
221     (let (priority result)
222       (while priorities
223         (setq priority (car priorities)
224               priorities (cdr priorities))
225         (cond
226          ((eq 'biff priority)
227           (when wl-biff-check-folder-list
228             (setq result (append result '((wl-modeline-biff-status
229                                            wl-modeline-biff-state-on
230                                            wl-modeline-biff-state-off))))))
231          ((eq 'plug priority)
232           (when wl-show-plug-status-on-modeline
233             (setq result (append result '((wl-modeline-plug-status
234                                            wl-modeline-plug-state-on
235                                            wl-modeline-plug-state-off))))))
236          (t
237           (setq result (append result (or id '("Wanderlust: %12b")))))))
238       (prog1
239           (setq mode-line-buffer-identification (if (stringp (car result))
240                                                     result
241                                                   (cons "" result)))
242         (force-mode-line-update t)))))
243
244 (defalias 'wl-display-error 'elmo-display-error)
245 (make-obsolete 'wl-display-error 'elmo-display-error)
246
247 (defun wl-get-assoc-list-value (assoc-list folder &optional match)
248   (catch 'found
249     (let ((alist assoc-list)
250           value pair)
251       (while alist
252         (setq pair (car alist))
253         (if (string-match (car pair) folder)
254             (cond ((eq match 'all)
255                    (setq value (append value (list (cdr pair)))))
256                   ((eq match 'all-list)
257                    (setq value (append value (cdr pair))))
258                   ((not match)
259                    (throw 'found (cdr pair)))))
260         (setq alist (cdr alist)))
261       value)))
262
263 (defmacro wl-match-string (pos string)
264   "Substring POSth matched STRING."
265   (` (substring (, string) (match-beginning (, pos)) (match-end (, pos)))))
266
267 (defmacro wl-match-buffer (pos)
268   "Substring POSth matched from the current buffer."
269   (` (buffer-substring-no-properties
270       (match-beginning (, pos)) (match-end (, pos)))))
271
272 (put 'wl-as-coding-system 'lisp-indent-function 1)
273 (put 'wl-as-mime-charset 'lisp-indent-function 1)
274
275 (eval-and-compile
276   (if wl-on-mule3
277       (defmacro wl-as-coding-system (coding-system &rest body)
278         (` (let ((coding-system-for-read (, coding-system))
279                  (coding-system-for-write (, coding-system)))
280              (,@ body))))
281     (if wl-on-mule
282         (defmacro wl-as-coding-system (coding-system &rest body)
283           (` (let ((file-coding-system-for-read (, coding-system))
284                    (file-coding-system (, coding-system)))
285                (,@ body))))
286       (if wl-on-nemacs
287           (defmacro wl-as-coding-system (coding-system &rest body)
288             (` (let ((default-kanji-fileio-code (, coding-system))
289                      (kanji-fileio-code (, coding-system))
290                      kanji-expected-code)
291                  (,@ body))))))))
292
293 (defmacro wl-as-mime-charset (mime-charset &rest body)
294   (` (wl-as-coding-system (mime-charset-to-coding-system (, mime-charset))
295        (,@ body))))
296
297 (defalias 'wl-string 'elmo-string)
298 (make-obsolete 'wl-string 'elmo-string)
299
300 ;; Check if active region exists or not.
301 (if (boundp 'mark-active)
302     (defmacro wl-region-exists-p ()
303       'mark-active)
304   (if (fboundp 'region-exists-p)
305       (defmacro wl-region-exists-p ()
306         (list 'region-exists-p))))
307
308 (if (not (fboundp 'overlays-in))
309     (defun overlays-in (beg end)
310       "Return a list of the overlays that overlap the region BEG ... END.
311 Overlap means that at least one character is contained within the overlay
312 and also contained within the specified region.
313 Empty overlays are included in the result if they are located at BEG
314 or between BEG and END."
315       (let ((ovls (overlay-lists))
316             tmp retval)
317         (if (< end beg)
318             (setq tmp end
319                   end beg
320                   beg tmp))
321         (setq ovls (nconc (car ovls) (cdr ovls)))
322         (while ovls
323           (setq tmp (car ovls)
324                 ovls (cdr ovls))
325           (if (or (and (<= (overlay-start tmp) end)
326                        (>= (overlay-start tmp) beg))
327                   (and (<= (overlay-end tmp) end)
328                        (>= (overlay-end tmp) beg)))
329               (setq retval (cons tmp retval))))
330         retval)))
331
332 (defsubst wl-repeat-string (str times)
333   (let ((loop times)
334         ret-val)
335     (while (> loop 0)
336       (setq ret-val (concat ret-val str))
337       (setq loop (- loop 1)))
338     ret-val))
339
340 (defun wl-list-diff (list1 list2)
341   "Return a list of elements of LIST1 that do not appear in LIST2."
342   (let ((list1 (copy-sequence list1)))
343     (while list2
344       (setq list1 (delq (car list2) list1))
345       (setq list2 (cdr list2)))
346     list1))
347
348 (defun wl-append-assoc-list (item value alist)
349   "make assoc list '((item1 value1-1 value1-2 ...)) (item2 value2-1 ...)))"
350   (let ((entry (assoc item alist)))
351     (if entry
352         (progn
353           (when (not (member value (cdr entry)))
354             (nconc entry (list value)))
355           alist)
356       (append alist
357               (list (list item value))))))
358
359 (defun wl-delete-alist (key alist)
360   "Delete by side effect any entries specified with KEY from ALIST.
361 Return the modified ALIST.  Key comparison is done with `assq'.
362 Write `(setq foo (wl-delete-alist key foo))' to be sure of changing
363 the value of `foo'."
364   (let (entry)
365     (while (setq entry (assq key alist))
366       (setq alist (delq entry alist)))
367     alist))
368
369 (defun wl-delete-associations (keys alist)
370   "Delete by side effect any entries specified with KEYS from ALIST.
371 Return the modified ALIST.  KEYS must be a list of keys for ALIST.
372 Deletion is done with `wl-delete-alist'.
373 Write `(setq foo (wl-delete-associations keys foo))' to be sure of
374 changing the value of `foo'."
375   (while keys
376     (setq alist (wl-delete-alist (car keys) alist))
377     (setq keys (cdr keys)))
378   alist)
379
380 (defun wl-inverse-alist (keys alist)
381   "Inverse ALIST, copying.
382 Return an association list represents the inverse mapping of ALIST,
383 from objects to KEYS.
384 The objects mapped (cdrs of elements of the ALIST) are shared."
385   (let (x y tmp result)
386     (while keys
387       (setq x (car keys))
388       (setq y (cdr (assq x alist)))
389       (if y
390           (if (setq tmp (assoc y result))
391               (setq result (cons (append tmp (list x))
392                                  (delete tmp result)))
393             (setq result (cons (list y x) result))))
394       (setq keys (cdr keys)))
395     result))
396
397 (eval-when-compile
398   (require 'static))
399 (static-unless (fboundp 'pp)
400   (defvar pp-escape-newlines t)
401   (defun pp (object &optional stream)
402     "Output the pretty-printed representation of OBJECT, any Lisp object.
403 Quoting characters are printed when needed to make output that `read'
404 can handle, whenever this is possible.
405 Output stream is STREAM, or value of `standard-output' (which see)."
406     (princ (pp-to-string object) (or stream standard-output)))
407
408   (defun pp-to-string (object)
409     "Return a string containing the pretty-printed representation of OBJECT,
410 any Lisp object.  Quoting characters are used when needed to make output
411 that `read' can handle, whenever this is possible."
412     (save-excursion
413       (set-buffer (generate-new-buffer " pp-to-string"))
414       (unwind-protect
415           (progn
416             (lisp-mode-variables t)
417             (let ((print-escape-newlines pp-escape-newlines))
418               (prin1 object (current-buffer)))
419             (goto-char (point-min))
420             (while (not (eobp))
421               (cond
422                ((looking-at "\\s(\\|#\\s(")
423                 (while (looking-at "\\s(\\|#\\s(")
424                   (forward-char 1)))
425                ((and (looking-at "\\(quote[ \t]+\\)\\([^.)]\\)")
426                      (> (match-beginning 1) 1)
427                      (= ?\( (char-after (1- (match-beginning 1))))
428                      ;; Make sure this is a two-element list.
429                      (save-excursion
430                        (goto-char (match-beginning 2))
431                        (forward-sexp)
432                        ;; Avoid mucking with match-data; does this test work?
433                        (char-equal ?\) (char-after (point)))))
434                 ;; -1 gets the paren preceding the quote as well.
435                 (delete-region (1- (match-beginning 1)) (match-end 1))
436                 (insert "'")
437                 (forward-sexp 1)
438                 (if (looking-at "[ \t]*\)")
439                     (delete-region (match-beginning 0) (match-end 0))
440                   (error "Malformed quote"))
441                 (backward-sexp 1))
442                ((condition-case err-var
443                     (prog1 t (down-list 1))
444                   (error nil))
445                 (backward-char 1)
446                 (skip-chars-backward " \t")
447                 (delete-region
448                  (point)
449                  (progn (skip-chars-forward " \t") (point)))
450                 (if (not (char-equal ?' (char-after (1- (point)))))
451                     (insert ?\n)))
452                ((condition-case err-var
453                     (prog1 t (up-list 1))
454                   (error nil))
455                 (while (looking-at "\\s)")
456                   (forward-char 1))
457                 (skip-chars-backward " \t")
458                 (delete-region
459                  (point)
460                  (progn (skip-chars-forward " \t") (point)))
461                 (if (not (char-equal ?' (char-after (1- (point)))))
462                     (insert ?\n)))
463                (t (goto-char (point-max)))))
464             (goto-char (point-min))
465             (indent-sexp)
466             (buffer-string))
467         (kill-buffer (current-buffer))))))
468
469 (defsubst wl-get-date-iso8601 (date)
470   (or (get-text-property 0 'wl-date date)
471       (let* ((d1 (timezone-fix-time date nil nil))
472              (time (format "%04d%02d%02dT%02d%02d%02d"
473                            (aref d1 0) (aref d1 1) (aref d1 2)
474                            (aref d1 3) (aref d1 4) (aref d1 5))))
475         (put-text-property 0 1 'wl-date time date)
476         time)))
477
478 (defun wl-make-date-string ()
479   (let ((s (current-time-string)))
480     (string-match "\\`\\([A-Z][a-z][a-z]\\) +[A-Z][a-z][a-z] +[0-9][0-9]? *[0-9][0-9]?:[0-9][0-9]:[0-9][0-9] *[0-9]?[0-9]?[0-9][0-9]"
481                   s)
482     (concat (wl-match-string 1 s) ", "
483             (timezone-make-date-arpa-standard s (current-time-zone)))))
484
485 (defun wl-date-iso8601 (date)
486   "Convert the DATE to YYMMDDTHHMMSS."
487   (condition-case ()
488       (wl-get-date-iso8601 date)
489     (error "")))
490
491 (defun wl-day-number (date)
492   (let ((dat (mapcar '(lambda (s) (and s (string-to-int s)) )
493                      (timezone-parse-date date))))
494     (timezone-absolute-from-gregorian
495      (nth 1 dat) (nth 2 dat) (car dat))))
496
497 (defun wl-url-news (url &rest args)
498   (interactive "sURL: ")
499   (if (string-match "^news:\\(.*\\)$" url)
500       (wl-summary-goto-folder-subr
501        (concat "-" (elmo-match-string 1 url)) nil nil nil t)
502     (message "Not a news: url.")))
503
504 (defun wl-url-nntp (url &rest args)
505   (interactive "sURL: ")
506   (let (folder fld-name server port msg)
507     (if (string-match
508          "^nntp://\\([^:/]*\\):?\\([0-9]*\\)/\\([^/]*\\)/\\([0-9]*\\).*$" url)
509         (progn
510           (if (eq (length (setq fld-name
511                                 (elmo-match-string 3 url))) 0)
512               (setq fld-name nil))
513           (if (eq (length (setq port
514                                 (elmo-match-string 2 url))) 0)
515               (setq port (int-to-string elmo-nntp-default-port)))
516           (if (eq (length (setq server
517                                 (elmo-match-string 1 url))) 0)
518               (setq server elmo-nntp-default-server))
519           (setq folder (concat "-" fld-name "@" server ":" port))
520           (if (eq (length (setq msg
521                                 (elmo-match-string 4 url))) 0)
522               (wl-summary-goto-folder-subr
523                folder nil nil nil t)
524             (wl-summary-goto-folder-subr
525              folder 'update nil nil t)
526             (goto-char (point-min))
527             (re-search-forward (concat "^ *" msg) nil t)
528             (wl-summary-redisplay)))
529       (message "Not a nntp: url."))))
530
531 (defmacro wl-concat-list (list separator)
532   (` (mapconcat 'identity (delete "" (delq nil (, list))) (, separator))))
533
534 (defmacro wl-current-message-buffer ()
535   (` (save-excursion
536        (if (buffer-live-p wl-current-summary-buffer)
537            (set-buffer wl-current-summary-buffer))
538        wl-message-buffer)))
539
540 (defmacro wl-kill-buffers (regexp)
541   (` (mapcar (function
542               (lambda (x)
543                 (if (and (buffer-name x)
544                          (string-match (, regexp) (buffer-name x)))
545                     (and (get-buffer x)
546                          (kill-buffer x)))))
547              (buffer-list))))
548
549 (defun wl-sendlog-time ()
550   (static-if (fboundp 'format-time-string)
551       (format-time-string "%Y/%m/%d %T")
552     (let ((date (current-time-string)))
553       (format "%s/%02d/%02d %s"
554               (substring date -4)
555               (cdr (assoc (upcase (substring date 4 7))
556                           timezone-months-assoc))
557               (string-to-int (substring date 8 10))
558               (substring date 11 19)))))
559
560 (defun wl-collect-summary ()
561   (let (result)
562     (mapcar
563      (function (lambda (x)
564                  (if (and (string-match "^Summary"
565                                         (buffer-name x))
566                           (save-excursion
567                             (set-buffer x)
568                             (equal major-mode 'wl-summary-mode)))
569                      (setq result (nconc result (list x))))))
570      (buffer-list))
571     result))
572
573 (static-if (fboundp 'read-directory-name)
574     (defalias 'wl-read-directory-name 'read-directory-name)
575   (defun wl-read-directory-name (prompt dir)
576     (let ((dir (read-file-name prompt dir)))
577       (unless (file-directory-p dir)
578         (error "%s is not directory" dir))
579       dir)))
580
581 ;; local variable check.
582 (static-if (fboundp 'local-variable-p)
583     (defalias 'wl-local-variable-p 'local-variable-p)
584   (defmacro wl-local-variable-p (symbol &optional buffer)
585     (` (if (assq (, symbol) (buffer-local-variables (, buffer)))
586            t))))
587
588 (defun wl-number-base36 (num len)
589   (if (if (< len 0)
590           (<= num 0)
591         (= len 0))
592       ""
593     (concat (wl-number-base36 (/ num 36) (1- len))
594             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
595                                   (% num 36))))))
596
597 (defvar wl-unique-id-char nil)
598
599 (defun wl-unique-id ()
600   ;; Don't use microseconds from (current-time), they may be unsupported.
601   ;; Instead we use this randomly inited counter.
602   (setq wl-unique-id-char
603         (% (1+ (or wl-unique-id-char (logand (random t) (1- (lsh 1 20)))))
604            ;; (current-time) returns 16-bit ints,
605            ;; and 2^16*25 just fits into 4 digits i base 36.
606            (* 25 25)))
607   (let ((tm (static-if (fboundp 'current-time)
608                 (current-time)
609               (let* ((cts (split-string (current-time-string) "[ :]"))
610                      (m (cdr (assoc (nth 1 cts)
611                                     '(("Jan" . "01") ("Feb" . "02")
612                                       ("Mar" . "03") ("Apr" . "04")
613                                       ("May" . "05") ("Jun" . "06")
614                                       ("Jul" . "07") ("Aug" . "08")
615                                       ("Sep" . "09") ("Oct" . "10")
616                                       ("Nov" . "11") ("Dec" . "12"))))))
617                 (list (string-to-int (concat (nth 6 cts) m
618                                              (substring (nth 2 cts) 0 1)))
619                       (string-to-int (concat (substring (nth 2 cts) 1)
620                                              (nth 4 cts) (nth 5 cts)
621                                              (nth 6 cts))))))))
622     (concat
623      (if (memq system-type '(ms-dos emx vax-vms))
624          (let ((user (downcase (user-login-name))))
625            (while (string-match "[^a-z0-9_]" user)
626              (aset user (match-beginning 0) ?_))
627            user)
628        (wl-number-base36 (user-uid) -1))
629      (wl-number-base36 (+ (car   tm)
630                           (lsh (% wl-unique-id-char 25) 16)) 4)
631      (wl-number-base36 (+ (nth 1 tm)
632                           (lsh (/ wl-unique-id-char 25) 16)) 4)
633      ;; Append the name of the message interface, because while the
634      ;; generated ID is unique to this newsreader, other newsreaders
635      ;; might otherwise generate the same ID via another algorithm.
636      ".wl")))
637
638 (defun wl-draft-make-message-id-string ()
639   "Return Message-ID field value."
640   (concat "<" (wl-unique-id) "@"
641           (or wl-message-id-domain
642               (if wl-local-domain
643                   (concat (system-name) "." wl-local-domain)
644                 (system-name)))
645           ">"))
646
647 ;;; Profile loading.
648 (defvar wl-load-profile-function 'wl-local-load-profile)
649 (defun wl-local-load-profile ()
650   "Load `wl-init-file'."
651   (message "Initializing ...")
652   (load wl-init-file 'noerror 'nomessage))
653
654 (defun wl-load-profile ()
655   "Call `wl-load-profile-function' function."
656   (funcall wl-load-profile-function))
657
658 ;;;
659
660 (defmacro wl-count-lines ()
661   (` (save-excursion
662        (beginning-of-line)
663        (count-lines 1 (point)))))
664
665 (defun wl-horizontal-recenter ()
666   "Recenter the current buffer horizontally."
667   (beginning-of-line)
668   (re-search-forward "[[<]" (point-at-eol) t)
669   (if (< (current-column) (/ (window-width) 2))
670       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
671     (let* ((orig (point))
672            (end (window-end (get-buffer-window (current-buffer) t)))
673            (max 0))
674       (when end
675         ;; Find the longest line currently displayed in the window.
676         (goto-char (window-start))
677         (while (and (not (eobp))
678                     (< (point) end))
679           (end-of-line)
680           (setq max (max max (current-column)))
681           (forward-line 1))
682         (goto-char orig)
683         ;; Scroll horizontally to center (sort of) the point.
684         (if (> max (window-width))
685             (set-window-hscroll
686              (get-buffer-window (current-buffer) t)
687              (min (- (current-column) (/ (window-width) 3))
688                   (+ 2 (- max (window-width)))))
689           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
690         max))))
691
692 ;; Biff
693 (static-cond
694  (wl-on-xemacs
695   (defvar wl-biff-timer-name "wl-biff")
696
697   (defun wl-biff-stop ()
698     (when (get-itimer wl-biff-timer-name)
699       (delete-itimer wl-biff-timer-name)))
700
701   (defun wl-biff-start ()
702     (wl-biff-stop)
703     (when wl-biff-check-folder-list
704       (wl-biff-check-folders)
705       (start-itimer wl-biff-timer-name 'wl-biff-check-folders
706                     wl-biff-check-interval wl-biff-check-interval))))
707
708  ((and (condition-case nil (require 'timer) (error nil));; FSFmacs 19+
709        (fboundp 'timer-activate))
710
711   (defun wl-biff-stop ()
712     (when (get 'wl-biff 'timer)
713       (cancel-timer (get 'wl-biff 'timer))))
714
715   (defun wl-biff-start ()
716     (require 'timer)
717     (when wl-biff-check-folder-list
718       (wl-biff-check-folders)
719       (if (get 'wl-biff 'timer)
720           (timer-activate (get 'wl-biff 'timer))
721         (put 'wl-biff 'timer (run-at-time
722                               (timer-next-integral-multiple-of-time
723                                (current-time) wl-biff-check-interval)
724                               wl-biff-check-interval
725                               'wl-biff-event-handler)))))
726
727   (defun-maybe timer-next-integral-multiple-of-time (time secs)
728     "Yield the next value after TIME that is an integral multiple of SECS.
729 More precisely, the next value, after TIME, that is an integral multiple
730 of SECS seconds since the epoch.  SECS may be a fraction.
731 This function is imported from Emacs 20.7."
732     (let ((time-base (ash 1 16)))
733       (if (fboundp 'atan)
734           ;; Use floating point, taking care to not lose precision.
735           (let* ((float-time-base (float time-base))
736                  (million 1000000.0)
737                  (time-usec (+ (* million
738                                   (+ (* float-time-base (nth 0 time))
739                                      (nth 1 time)))
740                                (nth 2 time)))
741                  (secs-usec (* million secs))
742                  (mod-usec (mod time-usec secs-usec))
743                  (next-usec (+ (- time-usec mod-usec) secs-usec))
744                  (time-base-million (* float-time-base million)))
745             (list (floor next-usec time-base-million)
746                   (floor (mod next-usec time-base-million) million)
747                   (floor (mod next-usec million))))
748         ;; Floating point is not supported.
749         ;; Use integer arithmetic, avoiding overflow if possible.
750         (let* ((mod-sec (mod (+ (* (mod time-base secs)
751                                    (mod (nth 0 time) secs))
752                                 (nth 1 time))
753                              secs))
754                (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
755           (list (+ (nth 0 time) (floor next-1-sec time-base))
756                 (mod next-1-sec time-base)
757                 0)))))
758
759   (defun wl-biff-event-handler ()
760     ;; PAKURing from FSF:time.el
761     (wl-biff-check-folders)
762     ;; Do redisplay right now, if no input pending.
763     (sit-for 0)
764     (let* ((current (current-time))
765            (timer (get 'wl-biff 'timer))
766            ;; Compute the time when this timer will run again, next.
767            (next-time (timer-relative-time
768                        (list (aref timer 1) (aref timer 2) (aref timer 3))
769                        (* 5 (aref timer 4)) 0)))
770       ;; If the activation time is far in the past,
771       ;; skip executions until we reach a time in the future.
772       ;; This avoids a long pause if Emacs has been suspended for hours.
773       (or (> (nth 0 next-time) (nth 0 current))
774           (and (= (nth 0 next-time) (nth 0 current))
775                (> (nth 1 next-time) (nth 1 current)))
776           (and (= (nth 0 next-time) (nth 0 current))
777                (= (nth 1 next-time) (nth 1 current))
778                (> (nth 2 next-time) (nth 2 current)))
779           (progn
780             (timer-set-time timer (timer-next-integral-multiple-of-time
781                                    current wl-biff-check-interval)
782                             wl-biff-check-interval)
783             (timer-activate timer))))))
784  (t
785   (fset 'wl-biff-stop 'ignore)
786   (fset 'wl-biff-start 'ignore)))
787
788 (defsubst wl-biff-notify (new-mails notify-minibuf)
789   (when (and (not wl-modeline-biff-status) (> new-mails 0))
790     (run-hooks 'wl-biff-notify-hook))
791   (setq wl-modeline-biff-status (> new-mails 0))
792   (force-mode-line-update t)
793   (when notify-minibuf
794     (cond ((zerop new-mails) (message "No mail."))
795           ((= 1 new-mails) (message "You have a new mail."))
796           (t (message "You have %d new mails." new-mails)))))
797
798 ;; Internal variable.
799 (defvar wl-biff-check-folders-running nil)
800
801 (defun wl-biff-check-folders ()
802   (interactive)
803   (if wl-biff-check-folders-running
804       (when (interactive-p)
805         (message "Biff process is running."))
806     (setq wl-biff-check-folders-running t)
807     (when (interactive-p)
808       (message "Checking new mails..."))
809     (let ((new-mails 0)
810           (flist (or wl-biff-check-folder-list (list wl-default-folder)))
811           folder)
812       (if (eq (length flist) 1)
813           (wl-biff-check-folder-async (wl-folder-get-elmo-folder
814                                        (car flist)) (interactive-p))
815         (unwind-protect
816             (while flist
817               (setq folder (wl-folder-get-elmo-folder (car flist))
818                     flist (cdr flist))
819               (when (elmo-folder-plugged-p folder)
820                 (setq new-mails
821                       (+ new-mails
822                          (nth 0 (wl-biff-check-folder folder))))))
823           (setq wl-biff-check-folders-running nil)
824           (wl-biff-notify new-mails (interactive-p)))))))
825
826 (defun wl-biff-check-folder (folder)
827   (if (eq (elmo-folder-type folder) 'pop3)
828       ;; pop3 biff should share the session.
829       (prog2
830           (elmo-folder-close folder) ; Close session.
831           (wl-folder-check-one-entity (elmo-folder-name-internal folder))
832         (elmo-folder-close folder))
833     (let ((elmo-network-session-name-prefix "BIFF-"))
834       (wl-folder-check-one-entity (elmo-folder-name-internal folder)))))
835
836 (defun wl-biff-check-folder-async-callback (diff data)
837   (if (nth 1 data)
838       (with-current-buffer (nth 1 data)
839         (wl-folder-entity-hashtb-set wl-folder-entity-hashtb
840                                      (nth 0 data)
841                                      (list (car diff) 0 (cdr diff))
842                                      (current-buffer))))
843   (setq wl-folder-info-alist-modified t)
844   (setq wl-biff-check-folders-running nil)
845   (sit-for 0)
846   (wl-biff-notify (car diff) (nth 2 data)))
847
848 (defun wl-biff-check-folder-async (folder notify-minibuf)
849   (when (elmo-folder-plugged-p folder)
850     (if (and (eq (elmo-folder-type-internal folder) 'imap4)
851              (elmo-folder-use-flag-p folder))
852         ;; Check asynchronously only when IMAP4 and use server diff.
853         (progn
854           (setq elmo-folder-diff-async-callback
855                 'wl-biff-check-folder-async-callback)
856           (setq elmo-folder-diff-async-callback-data
857                 (list (elmo-folder-name-internal folder)
858                       (get-buffer wl-folder-buffer-name)
859                       notify-minibuf))
860           (let ((elmo-network-session-name-prefix "BIFF-"))
861             (elmo-folder-diff-async folder)))
862       (wl-biff-notify (car (wl-biff-check-folder folder))
863                       notify-minibuf)
864       (setq wl-biff-check-folders-running nil))))
865
866 (if (and (fboundp 'regexp-opt)
867          (not (featurep 'xemacs)))
868     (defalias 'wl-regexp-opt 'regexp-opt)
869   (defun wl-regexp-opt (strings &optional paren)
870     "Return a regexp to match a string in STRINGS.
871 Each string should be unique in STRINGS and should not contain any regexps,
872 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
873 is enclosed by at least one regexp grouping construct."
874     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
875       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
876               close-paren))))
877
878 (require 'product)
879 (product-provide (provide 'wl-util) (require 'wl-version))
880
881 ;;; wl-util.el ends here