* wl-util.el (wl-parse-addresses): Define alias of
[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-day-number (date)
451   (let ((dat (mapcar '(lambda (s) (and s (string-to-int s)) )
452                      (timezone-parse-date date))))
453     (timezone-absolute-from-gregorian
454      (nth 1 dat) (nth 2 dat) (car dat))))
455
456 (defun wl-url-news (url &rest args)
457   (interactive "sURL: ")
458   (if (string-match "^news:\\(.*\\)$" url)
459       (wl-summary-goto-folder-subr
460        (concat "-" (elmo-match-string 1 url)) nil nil nil t)
461     (message "Not a news: url.")))
462
463 (defun wl-url-nntp (url &rest args)
464   (interactive "sURL: ")
465   (let (folder fld-name server port msg)
466     (if (string-match
467          "^nntp://\\([^:/]*\\):?\\([0-9]*\\)/\\([^/]*\\)/\\([0-9]*\\).*$" url)
468         (progn
469           (if (eq (length (setq fld-name
470                                 (elmo-match-string 3 url))) 0)
471               (setq fld-name nil))
472           (if (eq (length (setq port
473                                 (elmo-match-string 2 url))) 0)
474               (setq port (int-to-string elmo-nntp-default-port)))
475           (if (eq (length (setq server
476                                 (elmo-match-string 1 url))) 0)
477               (setq server elmo-nntp-default-server))
478           (setq folder (concat "-" fld-name "@" server ":" port))
479           (if (eq (length (setq msg
480                                 (elmo-match-string 4 url))) 0)
481               (wl-summary-goto-folder-subr
482                folder nil nil nil t)
483             (wl-summary-goto-folder-subr
484              folder 'update nil nil t)
485             (wl-summary-jump-to-msg (string-to-number msg))
486             (wl-summary-redisplay)))
487       (message "Not a nntp: url."))))
488
489 (defmacro wl-concat-list (list separator)
490   (` (mapconcat 'identity (delete "" (delq nil (, list))) (, separator))))
491
492 (defun wl-current-message-buffer ()
493   (when (buffer-live-p wl-current-summary-buffer)
494     (with-current-buffer wl-current-summary-buffer
495       (or wl-message-buffer
496           (and (wl-summary-message-number)
497                (wl-message-buffer-display
498                 wl-summary-buffer-elmo-folder
499                 (wl-summary-message-number)
500                 wl-summary-buffer-display-mime-mode
501                 nil nil))))))
502
503 (defmacro wl-kill-buffers (regexp)
504   (` (mapcar (function
505               (lambda (x)
506                 (if (and (buffer-name x)
507                          (string-match (, regexp) (buffer-name x)))
508                     (and (get-buffer x)
509                          (kill-buffer x)))))
510              (buffer-list))))
511
512 (defun wl-collect-summary ()
513   (let (result)
514     (mapcar
515      (function (lambda (x)
516                  (if (and (string-match "^Summary"
517                                         (buffer-name x))
518                           (save-excursion
519                             (set-buffer x)
520                             (equal major-mode 'wl-summary-mode)))
521                      (setq result (nconc result (list x))))))
522      (buffer-list))
523     result))
524
525 (defun wl-collect-draft ()
526   (let ((draft-regexp (concat
527                        "^" (regexp-quote wl-draft-folder)))
528         result buf)
529     (mapcar
530      (function (lambda (x)
531                  (if (with-current-buffer x
532                        (and (eq major-mode 'wl-draft-mode)
533                             (buffer-name)
534                             (string-match draft-regexp (buffer-name))))
535                      (setq result (nconc result (list x))))))
536      (buffer-list))
537     result))
538
539 (defun wl-save-drafts ()
540   (let ((msg (current-message))
541         (buffers (wl-collect-draft)))
542     (save-excursion
543       (while buffers
544         (set-buffer (car buffers))
545         (if (buffer-modified-p) (wl-draft-save))
546         (setq buffers (cdr buffers))))
547     (message "%s" (or msg ""))))
548
549 (static-if (fboundp 'read-directory-name)
550     (defun wl-read-directory-name (prompt dir)
551       (read-directory-name prompt dir dir))
552   (defun wl-read-directory-name (prompt dir)
553     (let ((dir (read-file-name prompt dir)))
554       (unless (file-directory-p dir)
555         (error "%s is not directory" dir))
556       dir)))
557
558 ;; local variable check.
559 (static-if (fboundp 'local-variable-p)
560     (defalias 'wl-local-variable-p 'local-variable-p)
561   (defmacro wl-local-variable-p (symbol &optional buffer)
562     (` (if (assq (, symbol) (buffer-local-variables (, buffer)))
563            t))))
564
565 (defun wl-number-base36 (num len)
566   (if (if (< len 0)
567           (<= num 0)
568         (= len 0))
569       ""
570     (concat (wl-number-base36 (/ num 36) (1- len))
571             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
572                                   (% num 36))))))
573
574 (defvar wl-unique-id-char nil)
575
576 (defun wl-unique-id ()
577   ;; Don't use microseconds from (current-time), they may be unsupported.
578   ;; Instead we use this randomly inited counter.
579   (setq wl-unique-id-char
580         (% (1+ (or wl-unique-id-char (logand (random t) (1- (lsh 1 20)))))
581            ;; (current-time) returns 16-bit ints,
582            ;; and 2^16*25 just fits into 4 digits i base 36.
583            (* 25 25)))
584   (let ((tm (static-if (fboundp 'current-time)
585                 (current-time)
586               (let* ((cts (split-string (current-time-string) "[ :]"))
587                      (m (cdr (assoc (nth 1 cts)
588                                     '(("Jan" . "01") ("Feb" . "02")
589                                       ("Mar" . "03") ("Apr" . "04")
590                                       ("May" . "05") ("Jun" . "06")
591                                       ("Jul" . "07") ("Aug" . "08")
592                                       ("Sep" . "09") ("Oct" . "10")
593                                       ("Nov" . "11") ("Dec" . "12"))))))
594                 (list (string-to-int (concat (nth 6 cts) m
595                                              (substring (nth 2 cts) 0 1)))
596                       (string-to-int (concat (substring (nth 2 cts) 1)
597                                              (nth 4 cts) (nth 5 cts)
598                                              (nth 6 cts))))))))
599     (concat
600      (if (memq system-type '(ms-dos emx vax-vms))
601          (let ((user (downcase (user-login-name))))
602            (while (string-match "[^a-z0-9_]" user)
603              (aset user (match-beginning 0) ?_))
604            user)
605        (wl-number-base36 (user-uid) -1))
606      (wl-number-base36 (+ (car   tm)
607                           (lsh (% wl-unique-id-char 25) 16)) 4)
608      (wl-number-base36 (+ (nth 1 tm)
609                           (lsh (/ wl-unique-id-char 25) 16)) 4)
610      ;; Append the name of the message interface, because while the
611      ;; generated ID is unique to this newsreader, other newsreaders
612      ;; might otherwise generate the same ID via another algorithm.
613      wl-unique-id-suffix)))
614
615 (defvar wl-message-id-function 'wl-draft-make-message-id-string)
616 (defun wl-draft-make-message-id-string ()
617   "Return Message-ID field value."
618   (concat "<" (wl-unique-id)
619           (let (from user domain)
620             (if (and wl-message-id-use-wl-from
621                      (progn
622                        (setq from (wl-address-header-extract-address wl-from))
623                        (and (string-match "^\\(.*\\)@\\(.*\\)$" from)
624                             (setq user   (match-string 1 from))
625                             (setq domain (match-string 2 from)))))
626                 (format "%%%s@%s>" user domain)
627               (format "@%s>"
628                       (or wl-message-id-domain
629                           (if wl-local-domain
630                               (concat (system-name) "." wl-local-domain)
631                             (system-name))))))))
632
633 ;;; Profile loading.
634 (defvar wl-load-profile-function 'wl-local-load-profile)
635 (defun wl-local-load-profile ()
636   "Load `wl-init-file'."
637   (message "Initializing...")
638   (load wl-init-file 'noerror 'nomessage))
639
640 (defun wl-load-profile ()
641   "Call `wl-load-profile-function' function."
642   (funcall wl-load-profile-function))
643
644 ;;;
645
646 (defmacro wl-count-lines ()
647   (` (save-excursion
648        (beginning-of-line)
649        (count-lines 1 (point)))))
650
651 (defun wl-horizontal-recenter ()
652   "Recenter the current buffer horizontally."
653   (beginning-of-line)
654   (re-search-forward "[[<]" (point-at-eol) t)
655   (if (< (current-column) (/ (window-width) 2))
656       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
657     (let* ((orig (point))
658            (end (window-end (get-buffer-window (current-buffer) t)))
659            (max 0))
660       (when end
661         ;; Find the longest line currently displayed in the window.
662         (goto-char (window-start))
663         (while (and (not (eobp))
664                     (< (point) end))
665           (end-of-line)
666           (setq max (max max (current-column)))
667           (forward-line 1))
668         (goto-char orig)
669         ;; Scroll horizontally to center (sort of) the point.
670         (if (> max (window-width))
671             (set-window-hscroll
672              (get-buffer-window (current-buffer) t)
673              (min (- (current-column) (/ (window-width) 3))
674                   (+ 2 (- max (window-width)))))
675           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
676         max))))
677
678 ;; Draft auto-save
679 (static-cond
680  (wl-on-xemacs
681   (defvar wl-save-drafts-timer-name "wl-save-drafts")
682
683   (defun wl-set-save-drafts ()
684     (if (numberp wl-auto-save-drafts-interval)
685         (unless (get-itimer wl-save-drafts-timer-name)
686           (start-itimer wl-save-drafts-timer-name 'wl-save-drafts
687                         wl-auto-save-drafts-interval wl-auto-save-drafts-interval
688                         t))
689       (when (get-itimer wl-save-drafts-timer-name)
690         (delete-itimer wl-save-drafts-timer-name)))))
691  (t
692   (defun wl-set-save-drafts ()
693     (if (numberp wl-auto-save-drafts-interval)
694         (progn
695           (require 'timer)
696           (if (get 'wl-save-drafts 'timer)
697               (progn (timer-set-idle-time (get 'wl-save-drafts 'timer)
698                                           wl-auto-save-drafts-interval t)
699                      (timer-activate-when-idle (get 'wl-save-drafts 'timer)))
700             (put 'wl-save-drafts 'timer
701                  (run-with-idle-timer
702                   wl-auto-save-drafts-interval t 'wl-save-drafts))))
703       (when (get 'wl-save-drafts 'timer)
704         (cancel-timer (get 'wl-save-drafts 'timer)))))))
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       (start-itimer wl-biff-timer-name 'wl-biff-check-folders
719                     wl-biff-check-interval wl-biff-check-interval
720                     wl-biff-use-idle-timer))))
721
722  (t
723   (defun wl-biff-stop ()
724     (when (get 'wl-biff 'timer)
725       (cancel-timer (get 'wl-biff 'timer))))
726
727   (defun wl-biff-start ()
728     (require 'timer)
729     (when wl-biff-check-folder-list
730       (if wl-biff-use-idle-timer
731           (if (get 'wl-biff 'timer)
732               (progn (timer-set-idle-time (get 'wl-biff 'timer)
733                                           wl-biff-check-interval t)
734                      (timer-activate-when-idle (get 'wl-biff 'timer)))
735             (put 'wl-biff 'timer
736                  (run-with-idle-timer
737                   wl-biff-check-interval t 'wl-biff-event-handler)))
738         (if (get 'wl-biff 'timer)
739             (progn
740               (timer-set-time (get 'wl-biff 'timer)
741                               (timer-next-integral-multiple-of-time
742                                (current-time) wl-biff-check-interval)
743                               wl-biff-check-interval)
744               (timer-activate (get 'wl-biff 'timer)))
745           (put 'wl-biff 'timer
746                (run-at-time
747                 (timer-next-integral-multiple-of-time
748                  (current-time) wl-biff-check-interval)
749                 wl-biff-check-interval
750                 'wl-biff-event-handler))))))
751
752   (defun-maybe timer-next-integral-multiple-of-time (time secs)
753     "Yield the next value after TIME that is an integral multiple of SECS.
754 More precisely, the next value, after TIME, that is an integral multiple
755 of SECS seconds since the epoch.  SECS may be a fraction.
756 This function is imported from Emacs 20.7."
757     (let ((time-base (ash 1 16)))
758       (if (fboundp 'atan)
759           ;; Use floating point, taking care to not lose precision.
760           (let* ((float-time-base (float time-base))
761                  (million 1000000.0)
762                  (time-usec (+ (* million
763                                   (+ (* float-time-base (nth 0 time))
764                                      (nth 1 time)))
765                                (nth 2 time)))
766                  (secs-usec (* million secs))
767                  (mod-usec (mod time-usec secs-usec))
768                  (next-usec (+ (- time-usec mod-usec) secs-usec))
769                  (time-base-million (* float-time-base million)))
770             (list (floor next-usec time-base-million)
771                   (floor (mod next-usec time-base-million) million)
772                   (floor (mod next-usec million))))
773         ;; Floating point is not supported.
774         ;; Use integer arithmetic, avoiding overflow if possible.
775         (let* ((mod-sec (mod (+ (* (mod time-base secs)
776                                    (mod (nth 0 time) secs))
777                                 (nth 1 time))
778                              secs))
779                (next-1-sec (+ (- (nth 1 time) mod-sec) secs)))
780           (list (+ (nth 0 time) (floor next-1-sec time-base))
781                 (mod next-1-sec time-base)
782                 0)))))
783
784   (defun wl-biff-event-handler ()
785     ;; PAKURing from FSF:time.el
786     (wl-biff-check-folders)
787     ;; Do redisplay right now, if no input pending.
788     (sit-for 0)
789     (let* ((current (current-time))
790            (timer (get 'wl-biff 'timer))
791            ;; Compute the time when this timer will run again, next.
792            (next-time (timer-relative-time
793                        (list (aref timer 1) (aref timer 2) (aref timer 3))
794                        (* 5 (aref timer 4)) 0)))
795       ;; If the activation time is far in the past,
796       ;; skip executions until we reach a time in the future.
797       ;; This avoids a long pause if Emacs has been suspended for hours.
798       (or (> (nth 0 next-time) (nth 0 current))
799           (and (= (nth 0 next-time) (nth 0 current))
800                (> (nth 1 next-time) (nth 1 current)))
801           (and (= (nth 0 next-time) (nth 0 current))
802                (= (nth 1 next-time) (nth 1 current))
803                (> (nth 2 next-time) (nth 2 current)))
804           (progn
805             (timer-set-time timer (timer-next-integral-multiple-of-time
806                                    current wl-biff-check-interval)
807                             wl-biff-check-interval)
808             (timer-activate timer)))))))
809
810 (defsubst wl-biff-notify (new-mails notify-minibuf)
811   (when (and (not wl-modeline-biff-status) (> new-mails 0))
812     (run-hooks 'wl-biff-notify-hook))
813   (when (and wl-modeline-biff-status (eq new-mails 0))
814     (run-hooks 'wl-biff-unnotify-hook))
815   (setq wl-modeline-biff-status (> new-mails 0))
816   (force-mode-line-update t)
817   (when notify-minibuf
818     (cond ((zerop new-mails) (message "No mail."))
819           ((= 1 new-mails) (message "You have a new mail."))
820           (t (message "You have %d new mails." new-mails)))))
821
822 ;; Internal variable.
823 (defvar wl-biff-check-folders-running nil)
824
825 (defun wl-biff-check-folders ()
826   (interactive)
827   (if wl-biff-check-folders-running
828       (when (interactive-p)
829         (message "Biff process is running."))
830     (setq wl-biff-check-folders-running t)
831     (when (interactive-p)
832       (message "Checking new mails..."))
833     (let ((new-mails 0)
834           (flist (or wl-biff-check-folder-list (list wl-default-folder)))
835           folder)
836       (if (eq (length flist) 1)
837           (wl-biff-check-folder-async (wl-folder-get-elmo-folder
838                                        (car flist) 'biff) (interactive-p))
839         (unwind-protect
840             (while flist
841               (setq folder (wl-folder-get-elmo-folder (car flist))
842                     flist (cdr flist))
843               (when (and (elmo-folder-plugged-p folder)
844                          (elmo-folder-exists-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   (if (and (elmo-folder-plugged-p folder)
875            (wl-folder-entity-exists-p (elmo-folder-name-internal folder)))
876       (progn
877         (elmo-folder-set-biff-internal folder t)
878         (if (and (eq (elmo-folder-type-internal folder) 'imap4)
879                  (elmo-folder-use-flag-p folder))
880             ;; Check asynchronously only when IMAP4 and use server diff.
881             (progn
882               (setq elmo-folder-diff-async-callback
883                     'wl-biff-check-folder-async-callback)
884               (setq elmo-folder-diff-async-callback-data
885                     (list (elmo-folder-name-internal folder)
886                           (get-buffer wl-folder-buffer-name)
887                           notify-minibuf))
888               (elmo-folder-diff-async folder))
889           (unwind-protect
890               (wl-biff-notify (car (wl-biff-check-folder folder))
891                               notify-minibuf)
892             (setq wl-biff-check-folders-running nil))))
893     (setq wl-biff-check-folders-running nil)))
894
895 (if (and (fboundp 'regexp-opt)
896          (not (featurep 'xemacs)))
897     (defalias 'wl-regexp-opt 'regexp-opt)
898   (defun wl-regexp-opt (strings &optional paren)
899     "Return a regexp to match a string in STRINGS.
900 Each string should be unique in STRINGS and should not contain any regexps,
901 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
902 is enclosed by at least one regexp grouping construct."
903     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
904       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
905               close-paren))))
906
907 (defalias 'wl-expand-newtext 'elmo-expand-newtext)
908 (defalias 'wl-regexp-opt 'elmo-regexp-opt)
909
910 (defun wl-region-exists-p ()
911   "Return non-nil if a region exists on current buffer."
912   (static-if (featurep 'xemacs)
913       (region-active-p)
914     (and transient-mark-mode mark-active)))
915
916 (defun wl-deactivate-region ()
917   "Deactivate region on current buffer"
918   (static-if (not (featurep 'xemacs))
919       (setq mark-active nil)))
920
921 (defvar wl-line-string)
922 (defun wl-line-parse-format (format spec-alist)
923   "Make a formatter from FORMAT and SPEC-ALIST."
924   (let (f spec specs stack)
925     (setq f
926           (with-temp-buffer
927             (insert format)
928             (goto-char (point-min))
929             (while (search-forward "%" nil t)
930               (cond
931                ((looking-at "%")
932                 (goto-char (match-end 0)))
933                ((looking-at "\\(-?\\(0?\\)[0-9]*\\)\\([^0-9]\\)")
934                 (cond
935                  ((string= (match-string 3) "(")
936                   (if (zerop (length (match-string 1)))
937                       (error "No number specification for %%( line format"))
938                   (push (list
939                          (match-beginning 0) ; start
940                          (match-end 0)       ; start-content
941                          (string-to-number
942                           (match-string 1))  ; width
943                          specs) ; specs
944                         stack)
945                   (setq specs nil))
946                  ((string= (match-string 3) ")")
947                   (let ((entry (pop stack))
948                         form)
949                     (unless entry
950                       (error
951                        "No matching %%( parenthesis in summary line format"))
952                     (goto-char (car entry)) ; start
953                     (setq form (buffer-substring (nth 1 entry) ; start-content
954                                                  (- (match-beginning 0) 1)))
955                     (delete-region (car entry) (match-end 0))
956                     (insert "s")
957                     (setq specs
958                           (append
959                            (nth 3 entry)
960                            (list (list 'wl-set-string-width (nth 2 entry)
961                                        (append
962                                         (list 'format form)
963                                         specs)))))))
964                  (t
965                   (setq spec
966                         (if (setq spec (assq (string-to-char (match-string 3))
967                                              spec-alist))
968                             (nth 1 spec)
969                           (match-string 3)))
970                   (unless (string= "" (match-string 1))
971                     (setq spec (list 'wl-set-string-width
972                                      (string-to-number (match-string 1))
973                                      spec
974                                      (unless (string= "" (match-string 2))
975                                        (string-to-char (match-string 2))))))
976                   (replace-match "s" 'fixed)
977                   (setq specs (append specs
978                                       (list
979                                        (list
980                                         'setq 'wl-line-string
981                                         spec)))))))))
982             (buffer-string)))
983     (append (list 'format f) specs)))
984
985 (defmacro wl-line-formatter-setup (formatter format alist)
986   (` (let (byte-compile-warnings)
987        (setq (, formatter)
988              (byte-compile
989               (list 'lambda ()
990                     (wl-line-parse-format (, format) (, alist)))))
991        (when (get-buffer "*Compile-Log*")
992          (bury-buffer "*Compile-Log*"))
993        (when (get-buffer "*Compile-Log-Show*")
994          (bury-buffer "*Compile-Log-Show*")))))
995
996 (defsubst wl-copy-local-variables (src dst local-variables)
997   "Copy value of LOCAL-VARIABLES from SRC buffer to DST buffer."
998   (with-current-buffer dst
999     (dolist (variable local-variables)
1000       (set (make-local-variable variable)
1001            (with-current-buffer src
1002              (symbol-value variable))))))
1003
1004 ;;; Search Condition
1005 (defun wl-read-search-condition (default)
1006   "Read search condition string interactively."
1007   (wl-read-search-condition-internal "Search by" default))
1008
1009 (defun wl-read-search-condition-internal (prompt default &optional paren)
1010   (let* ((completion-ignore-case t)
1011          (denial-fields (nconc (mapcar 'capitalize elmo-msgdb-extra-fields)
1012                                '("Flag" "Since" "Before"
1013                                  "From" "Subject" "To" "Cc" "Body" "ToCc")))
1014          (field (completing-read
1015                  (format "%s (%s): " prompt default)
1016                  (mapcar 'list
1017                          (append '("AND" "OR" "Last" "First")
1018                                  denial-fields
1019                                  (mapcar (lambda (f) (concat "!" f))
1020                                          denial-fields)))))
1021          value)
1022     (setq field (if (string= field "")
1023                     (setq field default)
1024                   field))
1025     (cond
1026      ((or (string= field "AND") (string= field "OR"))
1027       (concat (if paren "(" "")
1028               (wl-read-search-condition-internal
1029                (concat field "(1) Search by") default 'paren)
1030               (if (string= field "AND") "&" "|")
1031               (wl-read-search-condition-internal
1032                (concat field "(2) Search by") default 'paren)
1033               (if paren ")" "")))
1034      ((string-match "Since\\|Before" field)
1035       (let ((default (format-time-string "%Y-%m-%d")))
1036         (setq value (completing-read
1037                      (format "Value for '%s' [%s]: " field default)
1038                      (mapcar (function
1039                               (lambda (x)
1040                                 (list (format "%s" (car x)))))
1041                              elmo-date-descriptions)))
1042         (concat (downcase field) ":"
1043                 (if (equal value "") default value))))
1044      ((string-match "!?Flag" field)
1045       (while (null value)
1046         (setq value (downcase
1047                      (completing-read
1048                       (format "Value for '%s': " field)
1049                       (mapcar (lambda (f) (list (capitalize (symbol-name f))))
1050                               (elmo-uniq-list
1051                                (append
1052                                 '(unread answered forwarded digest any)
1053                                 (copy-sequence elmo-global-flags))
1054                                #'delq)))))
1055         (unless (elmo-flag-valid-p value)
1056           (message "Invalid char in `%s'" value)
1057           (setq value nil)
1058           (sit-for 1)))
1059       (unless (string-match (concat "^" elmo-condition-atom-regexp "$")
1060                             value)
1061         (setq value (prin1-to-string value)))
1062       (concat (downcase field) ":" value))
1063      (t
1064       (setq value (read-from-minibuffer (format "Value for '%s': " field)))
1065       (unless (string-match (concat "^" elmo-condition-atom-regexp "$")
1066                             value)
1067         (setq value (prin1-to-string value)))
1068       (concat (downcase field) ":" value)))))
1069
1070 (require 'product)
1071 (product-provide (provide 'wl-util) (require 'wl-version))
1072
1073 ;;; wl-util.el ends here