* wl-summary.el (wl-summary-prefetch-region-no-mark): Update
[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 (require 'bytecomp)
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 "%s" 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 &optional padding ignore-invalid)
177   "Make a new string which have specified WIDTH and content of STRING.
178 `wl-invalid-character-message' is used when invalid character is contained.
179 If WIDTH is negative number, padding chars are added to the head and
180 otherwise, padding chars are added to the tail of the string.
181 The optional 3rd arg PADDING, if non-nil, specifies a padding character
182 to add the result instead of white space.
183 If optional 4th argument is non-nil, don't use `wl-invalid-character-message'
184 even when invalid character is contained."
185   (static-cond
186    ((and (fboundp 'string-width) (fboundp 'truncate-string-to-width)
187          (not (featurep 'xemacs)))
188     (if (> (string-width string) (abs width))
189         (setq string (truncate-string-to-width string (abs width))))
190     (if (= (string-width string) (abs width))
191         string
192       (when (and (not ignore-invalid)
193                  (< (abs width) (string-width string)))
194         (setq string
195               (truncate-string-to-width wl-invalid-character-message
196                                         (abs width))))
197       (let ((paddings (make-string
198                        (max 0 (- (abs width) (string-width string)))
199                        (or padding ?\ ))))
200         (if (< width 0)
201             (concat paddings string)
202           (concat string paddings)))))
203    (t
204     (elmo-set-work-buf
205      (elmo-set-buffer-multibyte default-enable-multibyte-characters)
206      (insert string)
207      (when (> (current-column) (abs width))
208        (when (> (move-to-column (abs width)) (abs width))
209          (condition-case nil ; ignore error
210              (backward-char 1)
211            (error)))
212        (setq string (buffer-substring (point-min) (point))))
213      (if (= (current-column) (abs width))
214          string
215        (let ((paddings (make-string (- (abs width) (current-column))
216                                     (or padding ?\ ))))
217          (if (< width 0)
218              (concat paddings string)
219            (concat string paddings))))))))
220
221 (defun wl-mode-line-buffer-identification (&optional id)
222   (let ((priorities '(biff plug title)))
223     (let ((items (reverse wl-mode-line-display-priority-list))
224           item)
225       (while items
226         (setq item (car items)
227               items (cdr items))
228         (unless (memq item '(biff plug))
229           (setq item 'title))
230         (setq priorities (cons item (delq item priorities)))))
231     (let (priority result)
232       (while priorities
233         (setq priority (car priorities)
234               priorities (cdr priorities))
235         (cond
236          ((eq 'biff priority)
237           (when wl-biff-check-folder-list
238             (setq result (append result '((wl-modeline-biff-status
239                                            wl-modeline-biff-state-on
240                                            wl-modeline-biff-state-off))))))
241          ((eq 'plug priority)
242           (when wl-show-plug-status-on-modeline
243             (setq result (append result '((wl-modeline-plug-status
244                                            wl-modeline-plug-state-on
245                                            wl-modeline-plug-state-off))))))
246          (t
247           (setq result (append result (or id '("Wanderlust: %12b")))))))
248       (prog1
249           (setq mode-line-buffer-identification (if (stringp (car result))
250                                                     result
251                                                   (cons "" result)))
252         (force-mode-line-update t)))))
253
254 (defalias 'wl-display-error 'elmo-display-error)
255 (make-obsolete 'wl-display-error 'elmo-display-error)
256
257 (defun wl-get-assoc-list-value (assoc-list folder &optional match)
258   (catch 'found
259     (let ((alist assoc-list)
260           value pair)
261       (while alist
262         (setq pair (car alist))
263         (if (string-match (car pair) folder)
264             (cond ((eq match 'all)
265                    (setq value (append value (list (cdr pair)))))
266                   ((eq match 'all-list)
267                    (setq value (append value (cdr pair))))
268                   ((not match)
269                    (throw 'found (cdr pair)))))
270         (setq alist (cdr alist)))
271       value)))
272
273 (defmacro wl-match-string (pos string)
274   "Substring POSth matched STRING."
275   (` (substring (, string) (match-beginning (, pos)) (match-end (, pos)))))
276
277 (defmacro wl-match-buffer (pos)
278   "Substring POSth matched from the current buffer."
279   (` (buffer-substring-no-properties
280       (match-beginning (, pos)) (match-end (, pos)))))
281
282 (put 'wl-as-coding-system 'lisp-indent-function 1)
283 (put 'wl-as-mime-charset 'lisp-indent-function 1)
284
285 (eval-and-compile
286   (cond
287    (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    (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    (t
298     (defmacro wl-as-coding-system (coding-system &rest body)
299       (` (progn (,@ body)))))))
300
301 (defmacro wl-as-mime-charset (mime-charset &rest body)
302   (` (wl-as-coding-system (mime-charset-to-coding-system (, mime-charset))
303        (,@ body))))
304
305 (defalias 'wl-string 'elmo-string)
306 (make-obsolete 'wl-string 'elmo-string)
307
308 ;; Check if active region exists or not.
309 (if (boundp 'mark-active)
310     (defmacro wl-region-exists-p ()
311       'mark-active)
312   (if (fboundp 'region-exists-p)
313       (defmacro wl-region-exists-p ()
314         (list 'region-exists-p))))
315
316 (if (not (fboundp 'overlays-in))
317     (defun overlays-in (beg end)
318       "Return a list of the overlays that overlap the region BEG ... END.
319 Overlap means that at least one character is contained within the overlay
320 and also contained within the specified region.
321 Empty overlays are included in the result if they are located at BEG
322 or between BEG and END."
323       (let ((ovls (overlay-lists))
324             tmp retval)
325         (if (< end beg)
326             (setq tmp end
327                   end beg
328                   beg tmp))
329         (setq ovls (nconc (car ovls) (cdr ovls)))
330         (while ovls
331           (setq tmp (car ovls)
332                 ovls (cdr ovls))
333           (if (or (and (<= (overlay-start tmp) end)
334                        (>= (overlay-start tmp) beg))
335                   (and (<= (overlay-end tmp) end)
336                        (>= (overlay-end tmp) beg)))
337               (setq retval (cons tmp retval))))
338         retval)))
339
340 (defsubst wl-repeat-string (str times)
341   (let ((loop times)
342         ret-val)
343     (while (> loop 0)
344       (setq ret-val (concat ret-val str))
345       (setq loop (- loop 1)))
346     ret-val))
347
348 (defun wl-list-diff (list1 list2)
349   "Return a list of elements of LIST1 that do not appear in LIST2."
350   (let ((list1 (copy-sequence list1)))
351     (while list2
352       (setq list1 (delq (car list2) list1))
353       (setq list2 (cdr list2)))
354     list1))
355
356 (defun wl-append-assoc-list (item value alist)
357   "make assoc list '((item1 value1-1 value1-2 ...)) (item2 value2-1 ...)))"
358   (let ((entry (assoc item alist)))
359     (if entry
360         (progn
361           (when (not (member value (cdr entry)))
362             (nconc entry (list value)))
363           alist)
364       (append alist
365               (list (list item value))))))
366
367 (defun wl-delete-alist (key alist)
368   "Delete by side effect any entries specified with KEY from ALIST.
369 Return the modified ALIST.  Key comparison is done with `assq'.
370 Write `(setq foo (wl-delete-alist key foo))' to be sure of changing
371 the value of `foo'."
372   (let (entry)
373     (while (setq entry (assq key alist))
374       (setq alist (delq entry alist)))
375     alist))
376
377 (defun wl-delete-associations (keys alist)
378   "Delete by side effect any entries specified with KEYS from ALIST.
379 Return the modified ALIST.  KEYS must be a list of keys for ALIST.
380 Deletion is done with `wl-delete-alist'.
381 Write `(setq foo (wl-delete-associations keys foo))' to be sure of
382 changing the value of `foo'."
383   (while keys
384     (setq alist (wl-delete-alist (car keys) alist))
385     (setq keys (cdr keys)))
386   alist)
387
388 (defun wl-inverse-alist (keys alist)
389   "Inverse ALIST, copying.
390 Return an association list represents the inverse mapping of ALIST,
391 from objects to KEYS.
392 The objects mapped (cdrs of elements of the ALIST) are shared."
393   (let (x y tmp result)
394     (while keys
395       (setq x (car keys))
396       (setq y (cdr (assq x alist)))
397       (if y
398           (if (setq tmp (assoc y result))
399               (setq result (cons (append tmp (list x))
400                                  (delete tmp result)))
401             (setq result (cons (list y x) result))))
402       (setq keys (cdr keys)))
403     result))
404
405 (eval-when-compile
406   (require 'static))
407 (static-unless (fboundp 'pp)
408   (defvar pp-escape-newlines t)
409   (defun pp (object &optional stream)
410     "Output the pretty-printed representation of OBJECT, any Lisp object.
411 Quoting characters are printed when needed to make output that `read'
412 can handle, whenever this is possible.
413 Output stream is STREAM, or value of `standard-output' (which see)."
414     (princ (pp-to-string object) (or stream standard-output)))
415
416   (defun pp-to-string (object)
417     "Return a string containing the pretty-printed representation of OBJECT,
418 any Lisp object.  Quoting characters are used when needed to make output
419 that `read' can handle, whenever this is possible."
420     (save-excursion
421       (set-buffer (generate-new-buffer " pp-to-string"))
422       (unwind-protect
423           (progn
424             (lisp-mode-variables t)
425             (let ((print-escape-newlines pp-escape-newlines))
426               (prin1 object (current-buffer)))
427             (goto-char (point-min))
428             (while (not (eobp))
429               (cond
430                ((looking-at "\\s(\\|#\\s(")
431                 (while (looking-at "\\s(\\|#\\s(")
432                   (forward-char 1)))
433                ((and (looking-at "\\(quote[ \t]+\\)\\([^.)]\\)")
434                      (> (match-beginning 1) 1)
435                      (= ?\( (char-after (1- (match-beginning 1))))
436                      ;; Make sure this is a two-element list.
437                      (save-excursion
438                        (goto-char (match-beginning 2))
439                        (forward-sexp)
440                        ;; Avoid mucking with match-data; does this test work?
441                        (char-equal ?\) (char-after (point)))))
442                 ;; -1 gets the paren preceding the quote as well.
443                 (delete-region (1- (match-beginning 1)) (match-end 1))
444                 (insert "'")
445                 (forward-sexp 1)
446                 (if (looking-at "[ \t]*\)")
447                     (delete-region (match-beginning 0) (match-end 0))
448                   (error "Malformed quote"))
449                 (backward-sexp 1))
450                ((condition-case err-var
451                     (prog1 t (down-list 1))
452                   (error nil))
453                 (backward-char 1)
454                 (skip-chars-backward " \t")
455                 (delete-region
456                  (point)
457                  (progn (skip-chars-forward " \t") (point)))
458                 (if (not (char-equal ?' (char-after (1- (point)))))
459                     (insert ?\n)))
460                ((condition-case err-var
461                     (prog1 t (up-list 1))
462                   (error nil))
463                 (while (looking-at "\\s)")
464                   (forward-char 1))
465                 (skip-chars-backward " \t")
466                 (delete-region
467                  (point)
468                  (progn (skip-chars-forward " \t") (point)))
469                 (if (not (char-equal ?' (char-after (1- (point)))))
470                     (insert ?\n)))
471                (t (goto-char (point-max)))))
472             (goto-char (point-min))
473             (indent-sexp)
474             (buffer-string))
475         (kill-buffer (current-buffer))))))
476
477 (defsubst wl-get-date-iso8601 (date)
478   (or (get-text-property 0 'wl-date date)
479       (let* ((d1 (timezone-fix-time date nil nil))
480              (time (format "%04d%02d%02dT%02d%02d%02d"
481                            (aref d1 0) (aref d1 1) (aref d1 2)
482                            (aref d1 3) (aref d1 4) (aref d1 5))))
483         (put-text-property 0 1 'wl-date time date)
484         time)))
485
486 (defun wl-make-date-string ()
487   (let ((s (current-time-string)))
488     (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]"
489                   s)
490     (concat (wl-match-string 1 s) ", "
491             (timezone-make-date-arpa-standard s (current-time-zone)))))
492
493 (defun wl-date-iso8601 (date)
494   "Convert the DATE to YYMMDDTHHMMSS."
495   (condition-case ()
496       (wl-get-date-iso8601 date)
497     (error "")))
498
499 (defun wl-day-number (date)
500   (let ((dat (mapcar '(lambda (s) (and s (string-to-int s)) )
501                      (timezone-parse-date date))))
502     (timezone-absolute-from-gregorian
503      (nth 1 dat) (nth 2 dat) (car dat))))
504
505 (defun wl-url-news (url &rest args)
506   (interactive "sURL: ")
507   (if (string-match "^news:\\(.*\\)$" url)
508       (wl-summary-goto-folder-subr
509        (concat "-" (elmo-match-string 1 url)) nil nil nil t)
510     (message "Not a news: url.")))
511
512 (defun wl-url-nntp (url &rest args)
513   (interactive "sURL: ")
514   (let (folder fld-name server port msg)
515     (if (string-match
516          "^nntp://\\([^:/]*\\):?\\([0-9]*\\)/\\([^/]*\\)/\\([0-9]*\\).*$" url)
517         (progn
518           (if (eq (length (setq fld-name
519                                 (elmo-match-string 3 url))) 0)
520               (setq fld-name nil))
521           (if (eq (length (setq port
522                                 (elmo-match-string 2 url))) 0)
523               (setq port (int-to-string elmo-nntp-default-port)))
524           (if (eq (length (setq server
525                                 (elmo-match-string 1 url))) 0)
526               (setq server elmo-nntp-default-server))
527           (setq folder (concat "-" fld-name "@" server ":" port))
528           (if (eq (length (setq msg
529                                 (elmo-match-string 4 url))) 0)
530               (wl-summary-goto-folder-subr
531                folder nil nil nil t)
532             (wl-summary-goto-folder-subr
533              folder 'update nil nil t)
534             (goto-char (point-min))
535             (re-search-forward (concat "^ *" msg) nil t)
536             (wl-summary-redisplay)))
537       (message "Not a nntp: url."))))
538
539 (defmacro wl-concat-list (list separator)
540   (` (mapconcat 'identity (delete "" (delq nil (, list))) (, separator))))
541
542 (defmacro wl-current-message-buffer ()
543   (` (save-excursion
544        (if (buffer-live-p wl-current-summary-buffer)
545            (set-buffer wl-current-summary-buffer))
546        wl-message-buffer)))
547
548 (defmacro wl-kill-buffers (regexp)
549   (` (mapcar (function
550               (lambda (x)
551                 (if (and (buffer-name x)
552                          (string-match (, regexp) (buffer-name x)))
553                     (and (get-buffer x)
554                          (kill-buffer x)))))
555              (buffer-list))))
556
557 (defun wl-collect-summary ()
558   (let (result)
559     (mapcar
560      (function (lambda (x)
561                  (if (and (string-match "^Summary"
562                                         (buffer-name x))
563                           (save-excursion
564                             (set-buffer x)
565                             (equal major-mode 'wl-summary-mode)))
566                      (setq result (nconc result (list x))))))
567      (buffer-list))
568     result))
569
570 (defun wl-collect-draft ()
571   (let ((draft-regexp (concat
572                        "^" (regexp-quote
573                             (elmo-localdir-folder-directory-internal
574                              (wl-folder-get-elmo-folder wl-draft-folder)))))
575         result buf)
576     (mapcar
577      (function (lambda (x)
578                  (if (and
579                       (setq buf (with-current-buffer x
580                                   wl-draft-buffer-file-name))
581                       (string-match draft-regexp buf))
582                      (setq result (nconc result (list x))))))
583      (buffer-list))
584     result))
585
586 (static-if (fboundp 'read-directory-name)
587     (defun wl-read-directory-name (prompt dir)
588       (read-directory-name prompt dir dir))
589   (defun wl-read-directory-name (prompt dir)
590     (let ((dir (read-file-name prompt dir)))
591       (unless (file-directory-p dir)
592         (error "%s is not directory" dir))
593       dir)))
594
595 ;; local variable check.
596 (static-if (fboundp 'local-variable-p)
597     (defalias 'wl-local-variable-p 'local-variable-p)
598   (defmacro wl-local-variable-p (symbol &optional buffer)
599     (` (if (assq (, symbol) (buffer-local-variables (, buffer)))
600            t))))
601
602 (defun wl-number-base36 (num len)
603   (if (if (< len 0)
604           (<= num 0)
605         (= len 0))
606       ""
607     (concat (wl-number-base36 (/ num 36) (1- len))
608             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
609                                   (% num 36))))))
610
611 (defvar wl-unique-id-char nil)
612
613 (defun wl-unique-id ()
614   ;; Don't use microseconds from (current-time), they may be unsupported.
615   ;; Instead we use this randomly inited counter.
616   (setq wl-unique-id-char
617         (% (1+ (or wl-unique-id-char (logand (random t) (1- (lsh 1 20)))))
618            ;; (current-time) returns 16-bit ints,
619            ;; and 2^16*25 just fits into 4 digits i base 36.
620            (* 25 25)))
621   (let ((tm (static-if (fboundp 'current-time)
622                 (current-time)
623               (let* ((cts (split-string (current-time-string) "[ :]"))
624                      (m (cdr (assoc (nth 1 cts)
625                                     '(("Jan" . "01") ("Feb" . "02")
626                                       ("Mar" . "03") ("Apr" . "04")
627                                       ("May" . "05") ("Jun" . "06")
628                                       ("Jul" . "07") ("Aug" . "08")
629                                       ("Sep" . "09") ("Oct" . "10")
630                                       ("Nov" . "11") ("Dec" . "12"))))))
631                 (list (string-to-int (concat (nth 6 cts) m
632                                              (substring (nth 2 cts) 0 1)))
633                       (string-to-int (concat (substring (nth 2 cts) 1)
634                                              (nth 4 cts) (nth 5 cts)
635                                              (nth 6 cts))))))))
636     (concat
637      (if (memq system-type '(ms-dos emx vax-vms))
638          (let ((user (downcase (user-login-name))))
639            (while (string-match "[^a-z0-9_]" user)
640              (aset user (match-beginning 0) ?_))
641            user)
642        (wl-number-base36 (user-uid) -1))
643      (wl-number-base36 (+ (car   tm)
644                           (lsh (% wl-unique-id-char 25) 16)) 4)
645      (wl-number-base36 (+ (nth 1 tm)
646                           (lsh (/ wl-unique-id-char 25) 16)) 4)
647      ;; Append the name of the message interface, because while the
648      ;; generated ID is unique to this newsreader, other newsreaders
649      ;; might otherwise generate the same ID via another algorithm.
650      wl-unique-id-suffix)))
651
652 (defvar wl-message-id-function 'wl-draft-make-message-id-string)
653 (defun wl-draft-make-message-id-string ()
654   "Return Message-ID field value."
655   (concat "<" (wl-unique-id)
656           (let (from user domain)
657             (if (and wl-message-id-use-wl-from
658                      (progn
659                        (setq from (wl-address-header-extract-address wl-from))
660                        (and (string-match "^\\(.*\\)@\\(.*\\)$" from)
661                             (setq user   (match-string 1 from))
662                             (setq domain (match-string 2 from)))))
663                 (format "%%%s@%s>" user domain)
664               (format "@%s>"
665                       (or wl-message-id-domain
666                           (if wl-local-domain
667                               (concat (system-name) "." wl-local-domain)
668                             (system-name))))))))
669
670 ;;; Profile loading.
671 (defvar wl-load-profile-function 'wl-local-load-profile)
672 (defun wl-local-load-profile ()
673   "Load `wl-init-file'."
674   (message "Initializing...")
675   (load wl-init-file 'noerror 'nomessage))
676
677 (defun wl-load-profile ()
678   "Call `wl-load-profile-function' function."
679   (funcall wl-load-profile-function))
680
681 ;;;
682
683 (defmacro wl-count-lines ()
684   (` (save-excursion
685        (beginning-of-line)
686        (count-lines 1 (point)))))
687
688 (defun wl-horizontal-recenter ()
689   "Recenter the current buffer horizontally."
690   (beginning-of-line)
691   (re-search-forward "[[<]" (point-at-eol) t)
692   (if (< (current-column) (/ (window-width) 2))
693       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
694     (let* ((orig (point))
695            (end (window-end (get-buffer-window (current-buffer) t)))
696            (max 0))
697       (when end
698         ;; Find the longest line currently displayed in the window.
699         (goto-char (window-start))
700         (while (and (not (eobp))
701                     (< (point) end))
702           (end-of-line)
703           (setq max (max max (current-column)))
704           (forward-line 1))
705         (goto-char orig)
706         ;; Scroll horizontally to center (sort of) the point.
707         (if (> max (window-width))
708             (set-window-hscroll
709              (get-buffer-window (current-buffer) t)
710              (min (- (current-column) (/ (window-width) 3))
711                   (+ 2 (- max (window-width)))))
712           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
713         max))))
714
715 ;; Biff
716 (static-cond
717  (wl-on-xemacs
718   (defvar wl-biff-timer-name "wl-biff")
719
720   (defun wl-biff-stop ()
721     (when (get-itimer wl-biff-timer-name)
722       (delete-itimer wl-biff-timer-name)))
723
724   (defun wl-biff-start ()
725     (wl-biff-stop)
726     (when wl-biff-check-folder-list
727       (wl-biff-check-folders)
728       (start-itimer wl-biff-timer-name 'wl-biff-check-folders
729                     wl-biff-check-interval wl-biff-check-interval))))
730
731  ((and (condition-case nil (require 'timer) (error nil));; FSFmacs 19+
732        (fboundp 'timer-activate))
733
734   (defun wl-biff-stop ()
735     (when (get 'wl-biff 'timer)
736       (cancel-timer (get 'wl-biff 'timer))))
737
738   (defun wl-biff-start ()
739     (require 'timer)
740     (when wl-biff-check-folder-list
741       (wl-biff-check-folders)
742       (if (get 'wl-biff 'timer)
743           (timer-activate (get 'wl-biff 'timer))
744         (put 'wl-biff 'timer (run-at-time
745                               (timer-next-integral-multiple-of-time
746                                (current-time) wl-biff-check-interval)
747                               wl-biff-check-interval
748                               'wl-biff-event-handler)))))
749
750   (defun-maybe timer-next-integral-multiple-of-time (time secs)
751     "Yield the next value after TIME that is an integral multiple of SECS.
752 More precisely, the next value, after TIME, that is an integral multiple
753 of SECS seconds since the epoch.  SECS may be a fraction.
754 This function is imported from Emacs 20.7."
755     (let ((time-base (ash 1 16)))
756       (if (fboundp 'atan)
757           ;; Use floating point, taking care to not lose precision.
758           (let* ((float-time-base (float time-base))
759                  (million 1000000.0)
760                  (time-usec (+ (* million
761                                   (+ (* float-time-base (nth 0 time))
762                                      (nth 1 time)))
763                                (nth 2 time)))
764                  (secs-usec (* million secs))
765                  (mod-usec (mod time-usec secs-usec))
766                  (next-usec (+ (- time-usec mod-usec) secs-usec))
767                  (time-base-million (* float-time-base million)))
768             (list (floor next-usec time-base-million)
769                   (floor (mod next-usec time-base-million) million)
770                   (floor (mod next-usec million))))
771         ;; Floating point is not supported.
772         ;; Use integer arithmetic, avoiding overflow if possible.
773         (let* ((mod-sec (mod (+ (* (mod time-base secs)
774                                    (mod (nth 0 time) secs))
775                                 (nth 1 time))
776                              secs))
777                (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
778           (list (+ (nth 0 time) (floor next-1-sec time-base))
779                 (mod next-1-sec time-base)
780                 0)))))
781
782   (defun wl-biff-event-handler ()
783     ;; PAKURing from FSF:time.el
784     (wl-biff-check-folders)
785     ;; Do redisplay right now, if no input pending.
786     (sit-for 0)
787     (let* ((current (current-time))
788            (timer (get 'wl-biff 'timer))
789            ;; Compute the time when this timer will run again, next.
790            (next-time (timer-relative-time
791                        (list (aref timer 1) (aref timer 2) (aref timer 3))
792                        (* 5 (aref timer 4)) 0)))
793       ;; If the activation time is far in the past,
794       ;; skip executions until we reach a time in the future.
795       ;; This avoids a long pause if Emacs has been suspended for hours.
796       (or (> (nth 0 next-time) (nth 0 current))
797           (and (= (nth 0 next-time) (nth 0 current))
798                (> (nth 1 next-time) (nth 1 current)))
799           (and (= (nth 0 next-time) (nth 0 current))
800                (= (nth 1 next-time) (nth 1 current))
801                (> (nth 2 next-time) (nth 2 current)))
802           (progn
803             (timer-set-time timer (timer-next-integral-multiple-of-time
804                                    current wl-biff-check-interval)
805                             wl-biff-check-interval)
806             (timer-activate timer))))))
807  (t
808   (fset 'wl-biff-stop 'ignore)
809   (fset 'wl-biff-start 'ignore)))
810
811 (defsubst wl-biff-notify (new-mails notify-minibuf)
812   (when (and (not wl-modeline-biff-status) (> new-mails 0))
813     (run-hooks 'wl-biff-notify-hook))
814   (when (and wl-modeline-biff-status (eq new-mails 0))
815     (run-hooks 'wl-biff-unnotify-hook))
816   (setq wl-modeline-biff-status (> new-mails 0))
817   (force-mode-line-update t)
818   (when notify-minibuf
819     (cond ((zerop new-mails) (message "No mail."))
820           ((= 1 new-mails) (message "You have a new mail."))
821           (t (message "You have %d new mails." new-mails)))))
822
823 ;; Internal variable.
824 (defvar wl-biff-check-folders-running nil)
825
826 (defun wl-biff-check-folders ()
827   (interactive)
828   (if wl-biff-check-folders-running
829       (when (interactive-p)
830         (message "Biff process is running."))
831     (setq wl-biff-check-folders-running t)
832     (when (interactive-p)
833       (message "Checking new mails..."))
834     (let ((new-mails 0)
835           (flist (or wl-biff-check-folder-list (list wl-default-folder)))
836           folder)
837       (if (eq (length flist) 1)
838           (wl-biff-check-folder-async (wl-folder-get-elmo-folder
839                                        (car flist) 'biff) (interactive-p))
840         (unwind-protect
841             (while flist
842               (setq folder (wl-folder-get-elmo-folder (car flist))
843                     flist (cdr flist))
844               (when (elmo-folder-plugged-p folder)
845                 (setq new-mails
846                       (+ new-mails
847                          (nth 0 (wl-biff-check-folder folder))))))
848           (setq wl-biff-check-folders-running nil)
849           (wl-biff-notify new-mails (interactive-p)))))))
850
851 (defun wl-biff-check-folder (folder)
852   (if (eq (elmo-folder-type-internal folder) 'pop3)
853       (unless (elmo-pop3-get-session folder 'any-exists)
854         (wl-folder-check-one-entity (elmo-folder-name-internal folder)
855                                     'biff))
856     (wl-folder-check-one-entity (elmo-folder-name-internal folder)
857                                 'biff)))
858
859 (defun wl-biff-check-folder-async-callback (diff data)
860   (if (nth 1 data)
861       (with-current-buffer (nth 1 data)
862         (wl-folder-entity-hashtb-set wl-folder-entity-hashtb
863                                      (nth 0 data)
864                                      (list (nth 0 diff)
865                                            (- (nth 1 diff) (nth 0 diff))
866                                            (nth 2 diff))
867                                      (current-buffer))))
868   (setq wl-folder-info-alist-modified t)
869   (setq wl-biff-check-folders-running nil)
870   (sit-for 0)
871   (wl-biff-notify (car diff) (nth 2 data)))
872
873 (defun wl-biff-check-folder-async (folder notify-minibuf)
874   (when (elmo-folder-plugged-p folder)
875     (elmo-folder-set-biff-internal folder t)
876     (if (and (eq (elmo-folder-type-internal folder) 'imap4)
877              (elmo-folder-use-flag-p folder))
878         ;; Check asynchronously only when IMAP4 and use server diff.
879         (progn
880           (setq elmo-folder-diff-async-callback
881                 'wl-biff-check-folder-async-callback)
882           (setq elmo-folder-diff-async-callback-data
883                 (list (elmo-folder-name-internal folder)
884                       (get-buffer wl-folder-buffer-name)
885                       notify-minibuf))
886           (elmo-folder-diff-async folder))
887       (unwind-protect
888           (wl-biff-notify (car (wl-biff-check-folder folder))
889                           notify-minibuf)
890         (setq wl-biff-check-folders-running nil)))))
891
892 (if (and (fboundp 'regexp-opt)
893          (not (featurep 'xemacs)))
894     (defalias 'wl-regexp-opt 'regexp-opt)
895   (defun wl-regexp-opt (strings &optional paren)
896     "Return a regexp to match a string in STRINGS.
897 Each string should be unique in STRINGS and should not contain any regexps,
898 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
899 is enclosed by at least one regexp grouping construct."
900     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
901       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
902               close-paren))))
903
904 (defalias 'wl-expand-newtext 'elmo-expand-newtext)
905 (defalias 'wl-regexp-opt 'elmo-regexp-opt)
906
907 (defun wl-region-exists-p ()
908   "Return non-nil if a region exists on current buffer."
909   (static-if (featurep 'xemacs)
910       (and zmacs-regions zmacs-region-active-p)
911     (and transient-mark-mode mark-active)))
912
913 (defvar wl-line-string)
914 (defun wl-line-parse-format (format spec-alist)
915   "Make a formatter from FORMAT and SPEC-ALIST."
916   (let (f spec specs stack)
917     (setq f
918           (with-temp-buffer
919             (insert format)
920             (goto-char (point-min))
921             (while (search-forward "%" nil t)
922               (cond
923                ((looking-at "%")
924                 (goto-char (match-end 0)))
925                ((looking-at "\\(-?\\(0?\\)[0-9]*\\)\\([^0-9]\\)")
926                 (cond
927                  ((string= (match-string 3) "(")
928                   (if (zerop (length (match-string 1)))
929                       (error "No number specification for %%( line format"))
930                   (push (list
931                          (match-beginning 0) ; start
932                          (match-end 0)       ; start-content
933                          (string-to-number
934                           (match-string 1))  ; width
935                          specs) ; specs
936                         stack)
937                   (setq specs nil))
938                  ((string= (match-string 3) ")")
939                   (let ((entry (pop stack))
940                         form)
941                     (unless entry
942                       (error
943                        "No matching %%( parenthesis in summary line format"))
944                     (goto-char (car entry)) ; start
945                     (setq form (buffer-substring (nth 1 entry) ; start-content
946                                                  (- (match-beginning 0) 1)))
947                     (delete-region (car entry) (match-end 0))
948                     (insert "s")
949                     (setq specs
950                           (append
951                            (nth 3 entry)
952                            (list (list 'wl-set-string-width (nth 2 entry)
953                                        (append
954                                         (list 'format form)
955                                         specs)))))))
956                  (t
957                   (setq spec
958                         (if (setq spec (assq (string-to-char (match-string 3))
959                                              spec-alist))
960                             (nth 1 spec)
961                           (match-string 3)))
962                   (unless (string= "" (match-string 1))
963                     (setq spec (list 'wl-set-string-width
964                                      (string-to-number (match-string 1))
965                                      spec
966                                      (unless (string= "" (match-string 2))
967                                        (string-to-char (match-string 2))))))
968                   (replace-match "s" 'fixed)
969                   (setq specs (append specs
970                                       (list
971                                        (list
972                                         'setq 'wl-line-string
973                                         spec)))))))))
974             (buffer-string)))
975     (append (list 'format f) specs)))
976
977 (defmacro wl-line-formatter-setup (formatter format alist)
978   (` (let (byte-compile-warnings)
979        (setq (, formatter)
980              (byte-compile
981               (list 'lambda ()
982                     (wl-line-parse-format (, format) (, alist)))))
983        (when (get-buffer "*Compile-Log*")
984          (bury-buffer "*Compile-Log*"))
985        (when (get-buffer "*Compile-Log-Show*")
986          (bury-buffer "*Compile-Log-Show*")))))
987
988 (require 'product)
989 (product-provide (provide 'wl-util) (require 'wl-version))
990
991 ;;; wl-util.el ends here