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