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