* wl-utils.el (wl-message-id-function): New variable.
[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-unique-id-suffix)))
642
643 (defvar wl-message-id-function 'wl-draft-make-message-id-string)
644 (defun wl-draft-make-message-id-string ()
645   "Return Message-ID field value."
646   (concat "<" (wl-unique-id)
647           (let (from user domain)
648             (if (and wl-message-id-use-wl-from
649                      (progn
650                        (setq from (wl-address-header-extract-address wl-from))
651                        (and (string-match "^\\(.*\\)@\\(.*\\)$" from)
652                             (setq user   (match-string 1 from))
653                             (setq domain (match-string 2 from)))))
654                 (format "%%%s@%s>" user domain)
655               (format "@%s>"
656                       (or wl-message-id-domain
657                           (if wl-local-domain
658                               (concat (system-name) "." wl-local-domain)
659                             (system-name))))))))
660
661 ;;; Profile loading.
662 (defvar wl-load-profile-function 'wl-local-load-profile)
663 (defun wl-local-load-profile ()
664   "Load `wl-init-file'."
665   (message "Initializing ...")
666   (load wl-init-file 'noerror 'nomessage))
667
668 (defun wl-load-profile ()
669   "Call `wl-load-profile-function' function."
670   (funcall wl-load-profile-function))
671
672 ;;;
673
674 (defmacro wl-count-lines ()
675   (` (save-excursion
676        (beginning-of-line)
677        (count-lines 1 (point)))))
678
679 (defun wl-horizontal-recenter ()
680   "Recenter the current buffer horizontally."
681   (beginning-of-line)
682   (re-search-forward "[[<]" (point-at-eol) t)
683   (if (< (current-column) (/ (window-width) 2))
684       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
685     (let* ((orig (point))
686            (end (window-end (get-buffer-window (current-buffer) t)))
687            (max 0))
688       (when end
689         ;; Find the longest line currently displayed in the window.
690         (goto-char (window-start))
691         (while (and (not (eobp))
692                     (< (point) end))
693           (end-of-line)
694           (setq max (max max (current-column)))
695           (forward-line 1))
696         (goto-char orig)
697         ;; Scroll horizontally to center (sort of) the point.
698         (if (> max (window-width))
699             (set-window-hscroll
700              (get-buffer-window (current-buffer) t)
701              (min (- (current-column) (/ (window-width) 3))
702                   (+ 2 (- max (window-width)))))
703           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
704         max))))
705
706 ;; Biff
707 (static-cond
708  (wl-on-xemacs
709   (defvar wl-biff-timer-name "wl-biff")
710
711   (defun wl-biff-stop ()
712     (when (get-itimer wl-biff-timer-name)
713       (delete-itimer wl-biff-timer-name)))
714
715   (defun wl-biff-start ()
716     (wl-biff-stop)
717     (when wl-biff-check-folder-list
718       (wl-biff-check-folders)
719       (start-itimer wl-biff-timer-name 'wl-biff-check-folders
720                     wl-biff-check-interval wl-biff-check-interval))))
721
722  ((and (condition-case nil (require 'timer) (error nil));; FSFmacs 19+
723        (fboundp 'timer-activate))
724
725   (defun wl-biff-stop ()
726     (when (get 'wl-biff 'timer)
727       (cancel-timer (get 'wl-biff 'timer))))
728
729   (defun wl-biff-start ()
730     (require 'timer)
731     (when wl-biff-check-folder-list
732       (wl-biff-check-folders)
733       (if (get 'wl-biff 'timer)
734           (timer-activate (get 'wl-biff 'timer))
735         (put 'wl-biff 'timer (run-at-time
736                               (timer-next-integral-multiple-of-time
737                                (current-time) wl-biff-check-interval)
738                               wl-biff-check-interval
739                               'wl-biff-event-handler)))))
740
741   (defun-maybe timer-next-integral-multiple-of-time (time secs)
742     "Yield the next value after TIME that is an integral multiple of SECS.
743 More precisely, the next value, after TIME, that is an integral multiple
744 of SECS seconds since the epoch.  SECS may be a fraction.
745 This function is imported from Emacs 20.7."
746     (let ((time-base (ash 1 16)))
747       (if (fboundp 'atan)
748           ;; Use floating point, taking care to not lose precision.
749           (let* ((float-time-base (float time-base))
750                  (million 1000000.0)
751                  (time-usec (+ (* million
752                                   (+ (* float-time-base (nth 0 time))
753                                      (nth 1 time)))
754                                (nth 2 time)))
755                  (secs-usec (* million secs))
756                  (mod-usec (mod time-usec secs-usec))
757                  (next-usec (+ (- time-usec mod-usec) secs-usec))
758                  (time-base-million (* float-time-base million)))
759             (list (floor next-usec time-base-million)
760                   (floor (mod next-usec time-base-million) million)
761                   (floor (mod next-usec million))))
762         ;; Floating point is not supported.
763         ;; Use integer arithmetic, avoiding overflow if possible.
764         (let* ((mod-sec (mod (+ (* (mod time-base secs)
765                                    (mod (nth 0 time) secs))
766                                 (nth 1 time))
767                              secs))
768                (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
769           (list (+ (nth 0 time) (floor next-1-sec time-base))
770                 (mod next-1-sec time-base)
771                 0)))))
772
773   (defun wl-biff-event-handler ()
774     ;; PAKURing from FSF:time.el
775     (wl-biff-check-folders)
776     ;; Do redisplay right now, if no input pending.
777     (sit-for 0)
778     (let* ((current (current-time))
779            (timer (get 'wl-biff 'timer))
780            ;; Compute the time when this timer will run again, next.
781            (next-time (timer-relative-time
782                        (list (aref timer 1) (aref timer 2) (aref timer 3))
783                        (* 5 (aref timer 4)) 0)))
784       ;; If the activation time is far in the past,
785       ;; skip executions until we reach a time in the future.
786       ;; This avoids a long pause if Emacs has been suspended for hours.
787       (or (> (nth 0 next-time) (nth 0 current))
788           (and (= (nth 0 next-time) (nth 0 current))
789                (> (nth 1 next-time) (nth 1 current)))
790           (and (= (nth 0 next-time) (nth 0 current))
791                (= (nth 1 next-time) (nth 1 current))
792                (> (nth 2 next-time) (nth 2 current)))
793           (progn
794             (timer-set-time timer (timer-next-integral-multiple-of-time
795                                    current wl-biff-check-interval)
796                             wl-biff-check-interval)
797             (timer-activate timer))))))
798  (t
799   (fset 'wl-biff-stop 'ignore)
800   (fset 'wl-biff-start 'ignore)))
801
802 (defsubst wl-biff-notify (new-mails notify-minibuf)
803   (when (and (not wl-modeline-biff-status) (> new-mails 0))
804     (run-hooks 'wl-biff-notify-hook))
805   (when (and wl-modeline-biff-status (eq new-mails 0))
806     (run-hooks 'wl-biff-unnotify-hook))
807   (setq wl-modeline-biff-status (> new-mails 0))
808   (force-mode-line-update t)
809   (when notify-minibuf
810     (cond ((zerop new-mails) (message "No mail."))
811           ((= 1 new-mails) (message "You have a new mail."))
812           (t (message "You have %d new mails." new-mails)))))
813
814 ;; Internal variable.
815 (defvar wl-biff-check-folders-running nil)
816
817 (defun wl-biff-check-folders ()
818   (interactive)
819   (if wl-biff-check-folders-running
820       (when (interactive-p)
821         (message "Biff process is running."))
822     (setq wl-biff-check-folders-running t)
823     (when (interactive-p)
824       (message "Checking new mails..."))
825     (let ((new-mails 0)
826           (flist (or wl-biff-check-folder-list (list wl-default-folder)))
827           folder)
828       (if (eq (length flist) 1)
829           (wl-biff-check-folder-async (wl-folder-get-elmo-folder
830                                        (car flist) 'biff) (interactive-p))
831         (unwind-protect
832             (while flist
833               (setq folder (wl-folder-get-elmo-folder (car flist))
834                     flist (cdr flist))
835               (when (elmo-folder-plugged-p folder)
836                 (setq new-mails
837                       (+ new-mails
838                          (nth 0 (wl-biff-check-folder folder))))))
839           (setq wl-biff-check-folders-running nil)
840           (wl-biff-notify new-mails (interactive-p)))))))
841
842 (defun wl-biff-check-folder (folder)
843   (if (eq (elmo-folder-type-internal folder) 'pop3)
844       (unless (elmo-pop3-get-session folder 'if-exists)
845         (wl-folder-check-one-entity (elmo-folder-name-internal folder)
846                                     'biff))
847     (wl-folder-check-one-entity (elmo-folder-name-internal folder)
848                                 'biff)))
849
850 (defun wl-biff-check-folder-async-callback (diff data)
851   (if (nth 1 data)
852       (with-current-buffer (nth 1 data)
853         (wl-folder-entity-hashtb-set wl-folder-entity-hashtb
854                                      (nth 0 data)
855                                      (list (nth 0 diff)
856                                            (- (nth 1 diff) (nth 0 diff))
857                                            (nth 2 diff))
858                                      (current-buffer))))
859   (setq wl-folder-info-alist-modified t)
860   (setq wl-biff-check-folders-running nil)
861   (sit-for 0)
862   (wl-biff-notify (car diff) (nth 2 data)))
863
864 (defun wl-biff-check-folder-async (folder notify-minibuf)
865   (when (elmo-folder-plugged-p folder)
866     (elmo-folder-set-biff-internal folder t)
867     (if (and (eq (elmo-folder-type-internal folder) 'imap4)
868              (elmo-folder-use-flag-p folder))
869         ;; Check asynchronously only when IMAP4 and use server diff.
870         (progn
871           (setq elmo-folder-diff-async-callback
872                 'wl-biff-check-folder-async-callback)
873           (setq elmo-folder-diff-async-callback-data
874                 (list (elmo-folder-name-internal folder)
875                       (get-buffer wl-folder-buffer-name)
876                       notify-minibuf))
877           (elmo-folder-diff-async folder))
878       (unwind-protect
879           (wl-biff-notify (car (wl-biff-check-folder folder))
880                           notify-minibuf)
881         (setq wl-biff-check-folders-running nil)))))
882
883 (if (and (fboundp 'regexp-opt)
884          (not (featurep 'xemacs)))
885     (defalias 'wl-regexp-opt 'regexp-opt)
886   (defun wl-regexp-opt (strings &optional paren)
887     "Return a regexp to match a string in STRINGS.
888 Each string should be unique in STRINGS and should not contain any regexps,
889 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
890 is enclosed by at least one regexp grouping construct."
891     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
892       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
893               close-paren))))
894
895 (defun wl-expand-newtext (newtext original)
896   (let ((len (length newtext))
897         (pos 0)
898         c expanded beg N did-expand)
899     (while (< pos len)
900       (setq beg pos)
901       (while (and (< pos len)
902                   (not (= (aref newtext pos) ?\\)))
903         (setq pos (1+ pos)))
904       (unless (= beg pos)
905         (push (substring newtext beg pos) expanded))
906       (when (< pos len)
907         ;; We hit a \; expand it.
908         (setq did-expand t
909               pos (1+ pos)
910               c (aref newtext pos))
911         (if (not (or (= c ?\&)
912                      (and (>= c ?1)
913                           (<= c ?9))))
914             ;; \ followed by some character we don't expand.
915             (push (char-to-string c) expanded)
916           ;; \& or \N
917           (if (= c ?\&)
918               (setq N 0)
919             (setq N (- c ?0)))
920           (when (match-beginning N)
921             (push (substring original (match-beginning N) (match-end N))
922                   expanded))))
923       (setq pos (1+ pos)))
924     (if did-expand
925         (apply (function concat) (nreverse expanded))
926       newtext)))
927
928 (require 'product)
929 (product-provide (provide 'wl-util) (require 'wl-version))
930
931 ;;; wl-util.el ends here