(elmo-condition-optimize): Discriminated against
[elisp/wanderlust.git] / elmo / elmo-util.el
1 ;;; elmo-util.el --- Utilities for ELMO.
2
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
4
5 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
6 ;; Keywords: mail, net news
7
8 ;; This file is part of ELMO (Elisp Library for Message Orchestration).
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14 ;;
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19 ;;
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24 ;;
25
26 ;;; Commentary:
27 ;;
28
29 ;;; Code:
30 ;;
31
32 (eval-when-compile (require 'cl))
33 (require 'elmo-vars)
34 (require 'elmo-date)
35 (require 'mcharset)
36 (require 'pces)
37 (require 'std11)
38 (require 'eword-decode)
39 (require 'utf7)
40 (require 'poem)
41 (require 'emu)
42
43 (eval-and-compile
44   (autoload 'md5 "md5"))
45
46 (defvar elmo-work-buf-name " *elmo work*")
47 (defvar elmo-temp-buf-name " *elmo temp*")
48
49 (or (boundp 'default-enable-multibyte-characters)
50     (defvar default-enable-multibyte-characters (featurep 'mule)
51       "The mock variable except for Emacs 20."))
52
53 (defun elmo-base64-encode-string (string &optional no-line-break))
54 (defun elmo-base64-decode-string (string))
55
56 ;; base64 encoding/decoding
57 (require 'mel)
58 (fset 'elmo-base64-encode-string
59       (mel-find-function 'mime-encode-string "base64"))
60 (fset 'elmo-base64-decode-string
61       (mel-find-function 'mime-decode-string "base64"))
62
63 ;; Any Emacsen may have add-name-to-file(), because loadup.el requires it. :-p
64 ;; Check make-symbolic-link() instead.  -- 981002 by Fuji
65 (if (fboundp 'make-symbolic-link)  ;; xxx
66     (defalias 'elmo-add-name-to-file 'add-name-to-file)
67   (defun elmo-add-name-to-file
68     (filename newname &optional ok-if-already-exists)
69     (copy-file filename newname ok-if-already-exists t)))
70
71 (defmacro elmo-set-work-buf (&rest body)
72   "Execute BODY on work buffer.  Work buffer remains."
73   (` (save-excursion
74        (set-buffer (get-buffer-create elmo-work-buf-name))
75        (set-buffer-multibyte default-enable-multibyte-characters)
76        (erase-buffer)
77        (,@ body))))
78
79 (put 'elmo-set-work-buf 'lisp-indent-function 0)
80 (def-edebug-spec elmo-set-work-buf t)
81
82 (defmacro elmo-bind-directory (dir &rest body)
83   "Set current directory DIR and execute BODY."
84   (` (let ((default-directory (file-name-as-directory (, dir))))
85        (,@ body))))
86
87 (put 'elmo-bind-directory 'lisp-indent-function 1)
88 (def-edebug-spec elmo-bind-directory
89   (form &rest form))
90
91 (defconst elmo-multibyte-buffer-name " *elmo-multibyte-buffer*")
92
93 (defmacro elmo-with-enable-multibyte (&rest body)
94   "Evaluate BODY with `default-enable-multibyte-character'."
95   `(with-current-buffer (get-buffer-create elmo-multibyte-buffer-name)
96      ,@body))
97
98 (put 'elmo-with-enable-multibyte 'lisp-indent-function 0)
99 (def-edebug-spec elmo-with-enable-multibyte t)
100
101 (defun elmo-object-load (filename &optional mime-charset no-err)
102   "Load OBJECT from the file specified by FILENAME.
103 File content is decoded with MIME-CHARSET."
104   (if (not (file-readable-p filename))
105       nil
106     (with-temp-buffer
107       (insert-file-contents-as-binary filename)
108       (let ((coding-system (or (funcall set-auto-coding-function
109                                         filename
110                                         (- (point-max) (point-min)))
111                                (mime-charset-to-coding-system
112                                 mime-charset))))
113         (when coding-system
114           (decode-coding-region (point-min) (point-max) coding-system)))
115       (goto-char (point-min))
116       (condition-case nil
117           (read (current-buffer))
118         (error (unless no-err
119                  (message "Warning: Loading object from %s failed."
120                           filename)
121                  (elmo-object-save filename nil mime-charset))
122                nil)))))
123
124 (defsubst elmo-save-buffer (filename &optional mime-charset)
125   "Save current buffer to the file specified by FILENAME.
126 Directory of the file is created if it doesn't exist.
127 File content is encoded with MIME-CHARSET."
128   (let ((dir (directory-file-name (file-name-directory filename))))
129     (if (file-directory-p dir)
130         () ; ok.
131       (unless (file-exists-p dir)
132         (elmo-make-directory dir)))
133     (if (file-writable-p filename)
134         (progn
135           (when mime-charset
136 ;;;         (set-buffer-multibyte default-enable-multibyte-characters)
137             (encode-mime-charset-region (point-min) (point-max) mime-charset))
138           (as-binary-output-file
139            (write-region (point-min) (point-max) filename nil 'no-msg)))
140       (message "%s is not writable." filename))))
141
142 (defun elmo-object-save (filename object &optional mime-charset)
143   "Save OBJECT to the file specified by FILENAME.
144 Directory of the file is created if it doesn't exist.
145 File content is encoded with MIME-CHARSET."
146   (with-temp-buffer
147     (let (print-length print-level)
148       (prin1 object (current-buffer)))
149     (when mime-charset
150       (let ((coding (mime-charset-to-coding-system
151                      (or (detect-mime-charset-region (point-min) (point-max))
152                          mime-charset))))
153         (goto-char (point-min))
154         (insert ";;; -*- mode: emacs-lisp; coding: "
155                 (symbol-name coding) " -*-\n")
156         (encode-coding-region (point-min) (point-max) coding)))
157     (elmo-save-buffer filename)))
158
159 ;;; Search Condition
160
161 (defconst elmo-condition-atom-regexp "[^/ \")|&]*")
162
163 (defsubst elmo-condition-parse-error ()
164   (error "Syntax error in '%s'" (buffer-string)))
165
166 (defun elmo-parse-search-condition (condition)
167   "Parse CONDITION.
168 Return value is a cons cell of (STRUCTURE . REST)"
169   (with-temp-buffer
170     (insert condition)
171     (goto-char (point-min))
172     (cons (elmo-condition-parse) (buffer-substring (point) (point-max)))))
173
174 ;; condition    ::= or-expr
175 (defun elmo-condition-parse ()
176   (or (elmo-condition-parse-or-expr)
177       (elmo-condition-parse-error)))
178
179 ;; or-expr      ::= and-expr /
180 ;;                  and-expr "|" or-expr
181 (defun elmo-condition-parse-or-expr ()
182   (let ((left (elmo-condition-parse-and-expr)))
183     (if (looking-at "| *")
184         (progn
185           (goto-char (match-end 0))
186           (list 'or left (elmo-condition-parse-or-expr)))
187       left)))
188
189 ;; and-expr     ::= primitive /
190 ;;                  primitive "&" and-expr
191 (defun elmo-condition-parse-and-expr ()
192   (let ((left (elmo-condition-parse-primitive)))
193     (if (looking-at "& *")
194         (progn
195           (goto-char (match-end 0))
196           (list 'and left (elmo-condition-parse-and-expr)))
197       left)))
198
199 ;; primitive    ::= "(" expr ")" /
200 ;;                  ["!"] search-key SPACE* ":" SPACE* search-value
201 (defun elmo-condition-parse-primitive ()
202   (cond
203    ((looking-at "( *")
204     (goto-char (match-end 0))
205     (prog1 (elmo-condition-parse)
206       (unless (looking-at ") *")
207         (elmo-condition-parse-error))
208       (goto-char (match-end 0))))
209 ;; search-key   ::= [A-Za-z-]+
210 ;;                 ;; "since" / "before" / "last" / "first" /
211 ;;                 ;; "body" / "flag" / field-name
212    ((looking-at "\\(!\\)? *\\([A-Za-z-]+\\) *: *")
213     (goto-char (match-end 0))
214     (let ((search-key (vector
215                        (if (match-beginning 1) 'unmatch 'match)
216                        (downcase (elmo-match-buffer 2))
217                        (elmo-condition-parse-search-value))))
218       ;; syntax sugar.
219       (if (string= (aref search-key 1) "tocc")
220           (if (eq (aref search-key 0) 'match)
221               (list 'or
222                     (vector 'match "to" (aref search-key 2))
223                     (vector 'match "cc" (aref search-key 2)))
224             (list 'and
225                   (vector 'unmatch "to" (aref search-key 2))
226                   (vector 'unmatch "cc" (aref search-key 2))))
227         search-key)))))
228
229 ;; search-value ::= quoted / time / number / atom
230 ;; quoted       ::= <elisp string expression>
231 ;; time         ::= "yesterday" / "lastweek" / "lastmonth" / "lastyear" /
232 ;;                   number SPACE* "daysago" /
233 ;;                   number "-" month "-" number  ; ex. 10-May-2000
234 ;;                   number "-" number "-" number  ; ex. 2000-05-10
235 ;; number       ::= [0-9]+
236 ;; month        ::= "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
237 ;;                  "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
238 ;; atom         ::= ATOM_CHARS*
239 ;; SPACE        ::= <ascii space character, 0x20>
240 ;; ATOM_CHARS   ::= <any character except specials>
241 ;; specials     ::= SPACE / <"> / </> / <)> / <|> / <&>
242 ;;                  ;; These characters should be quoted.
243 (defun elmo-condition-parse-search-value ()
244   (cond
245    ((looking-at "\"")
246     (read (current-buffer)))
247    ((or (looking-at elmo-condition-atom-regexp)
248         (looking-at "yesterday") (looking-at "lastweek")
249         (looking-at "lastmonth") (looking-at "lastyear")
250         (looking-at "[0-9]+ *daysago")
251         (looking-at "[0-9]+-[A-Za-z]+-[0-9]+")
252         (looking-at "[0-9]+-[0-9]+-[0-9]+")
253         (looking-at "[0-9]+"))
254     (prog1 (elmo-match-buffer 0)
255       (goto-char (match-end 0))))
256    (t (error "Syntax error '%s'" (buffer-string)))))
257
258 (defmacro elmo-filter-condition-p (filter)
259   `(or (vectorp ,filter) (consp ,filter)))
260
261 (defmacro elmo-filter-type (filter)
262   `(aref ,filter 0))
263
264 (defmacro elmo-filter-key (filter)
265   `(aref ,filter 1))
266
267 (defmacro elmo-filter-value (filter)
268   `(aref ,filter 2))
269
270 (defun elmo-condition-match (condition match-primitive args)
271   (cond
272    ((vectorp condition)
273     (if (eq (elmo-filter-type condition) 'unmatch)
274         (not (apply match-primitive condition args))
275       (apply match-primitive condition args)))
276    ((eq (car condition) 'and)
277     (let ((lhs (elmo-condition-match (nth 1 condition) match-primitive args)))
278       (cond
279        ((elmo-filter-condition-p lhs)
280         (let ((rhs (elmo-condition-match (nth 2 condition)
281                                          match-primitive args)))
282           (cond ((elmo-filter-condition-p rhs)
283                  (list 'and lhs rhs))
284                 (rhs
285                  lhs))))
286        (lhs
287         (elmo-condition-match (nth 2 condition) match-primitive args)))))
288    ((eq (car condition) 'or)
289     (let ((lhs (elmo-condition-match (nth 1 condition) match-primitive args)))
290       (cond
291        ((elmo-filter-condition-p lhs)
292         (let ((rhs (elmo-condition-match (nth 2 condition)
293                                          match-primitive args)))
294           (cond ((elmo-filter-condition-p rhs)
295                  (list 'or lhs rhs))
296                 (rhs
297                  t)
298                 (t
299                  lhs))))
300        (lhs
301         t)
302        (t
303         (elmo-condition-match (nth 2 condition) match-primitive args)))))))
304
305 (defun elmo-condition-optimize (condition)
306   (cond
307    ((vectorp condition)
308     (let ((key (elmo-filter-key condition)))
309       (cond ((cdr (assoc key '(("first" . 0)
310                                ("last"  . 0)
311                                ("flag"  . 1)
312                                ("body"  . 5)))))
313             ((member key '("since" "before" "from" "subject" "to" "cc"))
314              2)
315             ((member key elmo-msgdb-extra-fields)
316              3)
317             (t
318              4))))
319    (t
320     (let ((weight-l (elmo-condition-optimize (nth 1 condition)))
321           (weight-r (elmo-condition-optimize (nth 2 condition))))
322       (if (> weight-l weight-r)
323           (let ((lhs (nth 1 condition)))
324             (setcar (nthcdr 1 condition) (nth 2 condition))
325             (setcar (nthcdr 2 condition) lhs)
326             weight-l)
327         weight-r)))))
328
329 ;;;
330 (defsubst elmo-buffer-replace (regexp &optional newtext)
331   (goto-char (point-min))
332   (while (re-search-forward regexp nil t)
333     (replace-match (or newtext ""))))
334
335 (defsubst elmo-delete-char (char string &optional unibyte)
336   (save-match-data
337     (elmo-set-work-buf
338      (let ((coding-system-for-read 'no-conversion)
339            (coding-system-for-write 'no-conversion))
340        (if unibyte (set-buffer-multibyte nil))
341        (insert string)
342        (goto-char (point-min))
343        (while (search-forward (char-to-string char) nil t)
344          (replace-match ""))
345        (buffer-string)))))
346
347 (defsubst elmo-delete-cr-buffer ()
348   "Delete CR from buffer."
349   (save-excursion
350     (goto-char (point-min))
351     (while (search-forward "\r\n" nil t)
352       (replace-match "\n")) ))
353
354 (defsubst elmo-delete-cr-get-content-type ()
355   (save-excursion
356     (goto-char (point-min))
357     (while (search-forward "\r\n" nil t)
358       (replace-match "\n"))
359     (goto-char (point-min))
360     (or (std11-field-body "content-type")
361         t)))
362
363 (defun elmo-delete-cr (string)
364   (save-match-data
365     (elmo-set-work-buf
366      (insert string)
367      (goto-char (point-min))
368      (while (search-forward "\r\n" nil t)
369        (replace-match "\n"))
370      (buffer-string))))
371
372 (defun elmo-last (list)
373   (and list (nth (1- (length list)) list)))
374
375 (defun elmo-set-list (vars vals)
376   (while vars
377     (when (car vars)
378       (set (car vars) (car vals)))
379     (setq vars (cdr vars)
380           vals (cdr vals))))
381
382 (defun elmo-uniq-list (lst &optional delete-function)
383   "Distractively uniqfy elements of LST."
384   (setq delete-function (or delete-function #'delete))
385   (let ((tmp lst))
386     (while tmp
387       (setq tmp
388             (setcdr tmp
389                     (and (cdr tmp)
390                          (funcall delete-function
391                                   (car tmp)
392                                   (cdr tmp)))))))
393   lst)
394
395 (defun elmo-uniq-sorted-list (list &optional equal-function)
396   "Distractively uniqfy elements of sorted LIST."
397   (setq equal-function (or equal-function #'equal))
398   (let ((list list))
399     (while list
400       (while (funcall equal-function (car list) (cadr list))
401         (setcdr list (cddr list)))
402       (setq list (cdr list))))
403   list)
404
405 (defun elmo-list-insert (list element after)
406   (let* ((match (memq after list))
407          (rest (and match (cdr (memq after list)))))
408     (if match
409         (progn
410           (setcdr match (list element))
411           (nconc list rest))
412       (nconc list (list element)))))
413
414 (defun elmo-get-file-string (filename &optional remove-final-newline)
415   (elmo-set-work-buf
416    (let (insert-file-contents-pre-hook   ; To avoid autoconv-xmas...
417          insert-file-contents-post-hook)
418      (when (file-exists-p filename)
419        (if filename
420            (as-binary-input-file (insert-file-contents filename)))
421        (when (and remove-final-newline
422                   (> (buffer-size) 0)
423                   (= (char-after (1- (point-max))) ?\n))
424          (goto-char (point-max))
425          (delete-backward-char 1))
426        (buffer-string)))))
427
428 (defun elmo-save-string (string filename)
429   (if string
430       (elmo-set-work-buf
431        (as-binary-output-file
432         (insert string)
433         (write-region (point-min) (point-max)
434                       filename nil 'no-msg))
435        )))
436
437 (defun elmo-max-of-list (nlist)
438   (let ((l nlist)
439         (max-num 0))
440     (while l
441       (if (< max-num (car l))
442           (setq max-num (car l)))
443       (setq l (cdr l)))
444     max-num))
445
446 (defun elmo-concat-path (path filename)
447   (if (not (string= path ""))
448       (elmo-replace-in-string
449        (if (string= elmo-path-sep (substring path (- (length path) 1)))
450            (concat path filename)
451          (concat path elmo-path-sep filename))
452        (concat (regexp-quote elmo-path-sep)(regexp-quote elmo-path-sep))
453        elmo-path-sep)
454     filename))
455
456 (defvar elmo-passwd-alist nil)
457
458 (defun elmo-passwd-alist-load ()
459   (with-temp-buffer
460     (let ((filename (expand-file-name elmo-passwd-alist-file-name
461                                       elmo-msgdb-directory))
462           insert-file-contents-pre-hook ; To avoid autoconv-xmas...
463           insert-file-contents-post-hook
464           ret-val)
465       (if (not (file-readable-p filename))
466           ()
467         (insert-file-contents filename)
468         (condition-case nil
469             (read (current-buffer))
470           (error nil nil))))))
471
472 (defun elmo-passwd-alist-clear ()
473   "Clear password cache."
474   (interactive)
475   (dolist (pair elmo-passwd-alist)
476     (when (stringp (cdr-safe pair))
477       (fillarray (cdr pair) 0)))
478   (setq elmo-passwd-alist nil))
479
480 (defun elmo-passwd-alist-save ()
481   "Save password into file."
482   (interactive)
483   (with-temp-buffer
484     (let ((filename (expand-file-name elmo-passwd-alist-file-name
485                                       elmo-msgdb-directory))
486           print-length print-level)
487       (prin1 elmo-passwd-alist (current-buffer))
488       (princ "\n" (current-buffer))
489 ;;;   (if (and (file-exists-p filename)
490 ;;;            (not (equal 384 (file-modes filename))))
491 ;;;       (error "%s is not safe.chmod 600 %s!" filename filename))
492       (if (file-writable-p filename)
493           (progn
494             (write-region (point-min) (point-max)
495                           filename nil 'no-msg)
496             (set-file-modes filename 384))
497         (message "%s is not writable." filename)))))
498
499 (defun elmo-get-passwd (key)
500   "Get password from password pool."
501   (let (pair pass)
502     (if (not elmo-passwd-alist)
503         (setq elmo-passwd-alist (elmo-passwd-alist-load)))
504     (setq pair (assoc key elmo-passwd-alist))
505     (if pair
506         (elmo-base64-decode-string (cdr pair))
507       (setq pass (elmo-read-passwd (format "Password for %s: "
508                                            key) t))
509       (setq elmo-passwd-alist
510             (append elmo-passwd-alist
511                     (list (cons key
512                                 (elmo-base64-encode-string pass)))))
513       (if elmo-passwd-life-time
514           (run-with-timer elmo-passwd-life-time nil
515                           (` (lambda () (elmo-remove-passwd (, key))))))
516       pass)))
517
518 (defun elmo-remove-passwd (key)
519   "Remove password from password pool (for failure)."
520   (let (pass-cons)
521     (while (setq pass-cons (assoc key elmo-passwd-alist))
522       (unwind-protect
523           (fillarray (cdr pass-cons) 0)
524         (setq elmo-passwd-alist
525               (delete pass-cons elmo-passwd-alist))))))
526
527 (defmacro elmo-read-char-exclusive ()
528   (cond ((featurep 'xemacs)
529          '(let ((table (quote ((backspace . ?\C-h) (delete . ?\C-?)
530                                (left . ?\C-h))))
531                 event key)
532             (while (not
533                     (and
534                      (key-press-event-p (setq event (next-command-event)))
535                      (setq key (or (event-to-character event)
536                                    (cdr (assq (event-key event) table)))))))
537             key))
538         ((fboundp 'read-char-exclusive)
539          '(read-char-exclusive))
540         (t
541          '(read-char))))
542
543 (defun elmo-read-passwd (prompt &optional stars)
544   "Read a single line of text from user without echoing, and return it."
545   (let ((ans "")
546         (c 0)
547         (echo-keystrokes 0)
548         (cursor-in-echo-area t)
549         (log-message-max-size 0)
550         message-log-max done msg truncate)
551     (while (not done)
552       (if (or (not stars) (string= "" ans))
553           (setq msg prompt)
554         (setq msg (concat prompt (make-string (length ans) ?.)))
555         (setq truncate
556               (1+ (- (length msg) (window-width (minibuffer-window)))))
557         (and (> truncate 0)
558              (setq msg (concat "$" (substring msg (1+ truncate))))))
559       (message "%s" msg)
560       (setq c (elmo-read-char-exclusive))
561       (cond ((= c ?\C-g)
562              (setq quit-flag t
563                    done t))
564             ((or (= c ?\r) (= c ?\n) (= c ?\e))
565              (setq done t))
566             ((= c ?\C-u)
567              (setq ans ""))
568             ((and (/= c ?\b) (/= c ?\177))
569              (setq ans (concat ans (char-to-string c))))
570             ((> (length ans) 0)
571              (setq ans (substring ans 0 -1)))))
572     (if quit-flag
573         (prog1
574             (setq quit-flag nil)
575           (message "Quit")
576           (beep t))
577       (message "")
578       ans)))
579
580 (defun elmo-string-to-list (string)
581   (elmo-set-work-buf
582    (insert string)
583    (goto-char (point-min))
584    (insert "(")
585    (goto-char (point-max))
586    (insert ")")
587    (goto-char (point-min))
588    (read (current-buffer))))
589
590 (defun elmo-list-to-string (list)
591   (let ((tlist list)
592         str)
593     (if (listp tlist)
594         (progn
595           (setq str "(")
596           (while (car tlist)
597             (setq str
598                   (concat str
599                           (if (symbolp (car tlist))
600                               (symbol-name (car tlist))
601                             (car tlist))))
602             (if (cdr tlist)
603                 (setq str
604                       (concat str " ")))
605             (setq tlist (cdr tlist)))
606           (setq str
607                 (concat str ")")))
608       (setq str
609             (if (symbolp tlist)
610                 (symbol-name tlist)
611               tlist)))
612     str))
613
614
615 (defun elmo-plug-on-by-servers (alist &optional servers)
616   (let ((server-list (or servers elmo-plug-on-servers)))
617     (catch 'plugged
618       (while server-list
619         (if (elmo-plugged-p (car server-list))
620             (throw 'plugged t))
621         (setq server-list (cdr server-list))))))
622
623 (defun elmo-plug-on-by-exclude-servers (alist &optional servers)
624   (let ((server-list (or servers elmo-plug-on-exclude-servers))
625         server other-servers)
626     (while alist
627       (when (and (not (member (setq server (caaar alist)) server-list))
628                  (not (member server other-servers)))
629         (push server other-servers))
630       (setq alist (cdr alist)))
631     (elmo-plug-on-by-servers alist other-servers)))
632
633 (defun elmo-plugged-p (&optional server port stream-type alist label-exp)
634   (let ((alist (or alist elmo-plugged-alist))
635         plugged-info)
636     (cond ((and (not port) (not server))
637            (cond ((eq elmo-plugged-condition 'one)
638                   (if alist
639                       (catch 'plugged
640                         (while alist
641                           (if (nth 2 (car alist))
642                               (throw 'plugged t))
643                           (setq alist (cdr alist))))
644                     elmo-plugged))
645                  ((eq elmo-plugged-condition 'all)
646                   (if alist
647                       (catch 'plugged
648                         (while alist
649                           (if (not (nth 2 (car alist)))
650                               (throw 'plugged nil))
651                           (setq alist (cdr alist)))
652                         t)
653                     elmo-plugged))
654                  ((functionp elmo-plugged-condition)
655                   (funcall elmo-plugged-condition alist))
656                  (t ;; independent
657                   elmo-plugged)))
658           ((not port) ;; server
659            (catch 'plugged
660              (while alist
661                (when (string= server (caaar alist))
662                  (if (nth 2 (car alist))
663                      (throw 'plugged t)))
664                (setq alist (cdr alist)))))
665           (t
666            (setq plugged-info (assoc (list server port stream-type) alist))
667            (if (not plugged-info)
668                ;; add elmo-plugged-alist automatically
669                (progn
670                  (elmo-set-plugged elmo-plugged server port stream-type
671                                    nil nil nil label-exp)
672                  elmo-plugged)
673              (if (and elmo-auto-change-plugged
674                       (> elmo-auto-change-plugged 0)
675                       (nth 3 plugged-info)  ;; time
676                       (elmo-time-expire (nth 3 plugged-info)
677                                         elmo-auto-change-plugged))
678                  t
679                (nth 2 plugged-info)))))))
680
681 (defun elmo-set-plugged (plugged &optional server port stream-type time
682                                  alist label-exp add)
683   (let ((alist (or alist elmo-plugged-alist))
684         label plugged-info)
685     (cond ((and (not port) (not server))
686            (setq elmo-plugged plugged)
687            ;; set plugged all element of elmo-plugged-alist.
688            (while alist
689              (setcdr (cdar alist) (list plugged time))
690              (setq alist (cdr alist))))
691           ((not port)
692            ;; set plugged all port of server
693            (while alist
694              (when (string= server (caaar alist))
695                (setcdr (cdar alist) (list plugged time)))
696              (setq alist (cdr alist))))
697           (t
698            ;; set plugged one port of server
699            (setq plugged-info (assoc (list server port stream-type) alist))
700            (setq label (if label-exp
701                            (eval label-exp)
702                          (nth 1 plugged-info)))
703            (if plugged-info
704                ;; if add is non-nil, don't reset plug state.
705                (unless add
706                  (setcdr plugged-info (list label plugged time)))
707              (setq alist
708                    (setq elmo-plugged-alist
709                          (nconc
710                           elmo-plugged-alist
711                           (list
712                            (list (list server port stream-type)
713                                  label plugged time))))))))
714     alist))
715
716 (defun elmo-delete-plugged (&optional server port alist)
717   (let* ((alist (or alist elmo-plugged-alist))
718          (alist2 alist))
719     (cond ((and (not port) (not server))
720            (setq alist nil))
721           ((not port)
722            ;; delete plugged all port of server
723            (while alist2
724              (when (string= server (caaar alist2))
725                (setq alist (delete (car alist2) alist)))
726              (setq alist2 (cdr alist2))))
727           (t
728            ;; delete plugged one port of server
729            (setq alist
730                  (delete (assoc (cons server port) alist) alist))))
731     alist))
732
733 (defun elmo-disk-usage (path)
734   "Get disk usage (bytes) in PATH."
735   (let ((file-attr
736          (condition-case () (file-attributes path) (error nil))))
737     (if file-attr
738         (if (nth 0 file-attr) ; directory
739             (let ((files (condition-case ()
740                              (directory-files path t "^[^\\.]")
741                            (error nil)))
742                   (result 0.0))
743               ;; (result (nth 7 file-attr))) ... directory size
744               (while files
745                 (setq result (+ result (or (elmo-disk-usage (car files)) 0)))
746                 (setq files (cdr files)))
747               result)
748           (float (nth 7 file-attr)))
749       0)))
750
751 (defun elmo-get-last-accessed-time (path &optional dir)
752   "Return the last accessed time of PATH."
753   (let ((last-accessed (nth 4 (file-attributes (or (and dir
754                                                         (expand-file-name
755                                                          path dir))
756                                                    path)))))
757     (if last-accessed
758         (setq last-accessed (+ (* (nth 0 last-accessed)
759                                   (float 65536)) (nth 1 last-accessed)))
760       0)))
761
762 (defun elmo-get-last-modification-time (path &optional dir)
763   "Return the last accessed time of PATH."
764   (let ((last-modified (nth 5 (file-attributes (or (and dir
765                                                         (expand-file-name
766                                                          path dir))
767                                                    path)))))
768     (setq last-modified (+ (* (nth 0 last-modified)
769                               (float 65536)) (nth 1 last-modified)))))
770
771 (defun elmo-make-directory (path &optional mode)
772   "Create directory recursively."
773   (let ((parent (directory-file-name (file-name-directory path))))
774     (if (null (file-directory-p parent))
775         (elmo-make-directory parent))
776     (make-directory path)
777     (set-file-modes path (or mode
778                              (+ (* 64 7) (* 8 0) 0))))) ; chmod 0700
779
780 (defun elmo-delete-directory (path &optional no-hierarchy)
781   "Delete directory recursively."
782   (if (stringp path) ; nil is not permitted.
783   (let ((dirent (directory-files path))
784         relpath abspath hierarchy)
785     (while dirent
786       (setq relpath (car dirent)
787             dirent (cdr dirent)
788             abspath (expand-file-name relpath path))
789       (when (not (string-match "^\\.\\.?$" relpath))
790         (if (eq (nth 0 (file-attributes abspath)) t)
791             (if no-hierarchy
792                 (setq hierarchy t)
793               (elmo-delete-directory abspath no-hierarchy))
794           (delete-file abspath))))
795     (unless hierarchy
796       (delete-directory path)))))
797
798 (defun elmo-delete-match-files (path regexp &optional remove-if-empty)
799   "Delete directory files specified by PATH.
800 If optional REMOVE-IF-EMPTY is non-nil, delete directory itself if
801 the directory becomes empty after deletion."
802   (when (stringp path) ; nil is not permitted.
803     (dolist (file (directory-files path t regexp))
804       (delete-file file))
805     (if remove-if-empty
806         (ignore-errors
807           (delete-directory path) ; should be removed if empty.
808           ))))
809
810 (defun elmo-list-filter (l1 l2)
811   "Rerurn a list from L2 in which each element is a member of L1."
812   (elmo-delete-if (lambda (x) (not (memq x l1))) l2))
813
814 (defsubst elmo-list-delete-if-smaller (list number)
815   (let ((ret-val (copy-sequence list)))
816     (while list
817       (if (< (car list) number)
818           (setq ret-val (delq (car list) ret-val)))
819       (setq list (cdr list)))
820     ret-val))
821
822 (defun elmo-list-diff (list1 list2)
823   (let ((clist1 (sort (copy-sequence list1) #'<))
824         (clist2 (sort (copy-sequence list2) #'<))
825         list1-only list2-only)
826     (while (or clist1 clist2)
827       (cond
828        ((null clist1)
829         (while clist2
830           (setq list2-only (cons (car clist2) list2-only))
831           (setq clist2 (cdr clist2))))
832        ((null clist2)
833         (while clist1
834           (setq list1-only (cons (car clist1) list1-only))
835           (setq clist1 (cdr clist1))))
836        ((< (car clist1) (car clist2))
837         (while (and clist1 (< (car clist1) (car clist2)))
838           (setq list1-only (cons (car clist1) list1-only))
839           (setq clist1 (cdr clist1))))
840        ((< (car clist2) (car clist1))
841         (while (and clist2 (< (car clist2) (car clist1)))
842           (setq list2-only (cons (car clist2) list2-only))
843           (setq clist2 (cdr clist2))))
844        ((= (car clist1) (car clist2))
845         (setq clist1 (cdr clist1)
846               clist2 (cdr clist2)))))
847     (list list1-only list2-only)))
848
849 (defun elmo-list-diff-nonsortable (list1 list2)
850   (let ((clist1 (copy-sequence list1))
851         (clist2 (copy-sequence list2)))
852     (while list2
853       (setq clist1 (delq (car list2) clist1))
854       (setq list2 (cdr list2)))
855     (while list1
856       (setq clist2 (delq (car list1) clist2))
857       (setq list1 (cdr list1)))
858     (list clist1 clist2)))
859
860 (defun elmo-list-bigger-diff (list1 list2 &optional mes)
861   "Returns a list (- +). + is bigger than max of LIST1, in LIST2."
862   (if (null list2)
863       (cons list1  nil)
864     (let* ((l1 list1)
865            (l2 list2)
866            (max-of-l2 (or (nth (max 0 (1- (length l2))) l2) 0))
867            diff1 num i percent
868            )
869       (setq i 0)
870       (setq num (+ (length l1)))
871       (while l1
872         (if (memq (car l1) l2)
873             (if (eq (car l1) (car l2))
874                 (setq l2 (cdr l2))
875               (delq (car l1) l2))
876           (if (> (car l1) max-of-l2)
877               (setq diff1 (nconc diff1 (list (car l1))))))
878         (if mes
879             (progn
880               (setq i (+ i 1))
881               (setq percent (/ (* i 100) num))
882               (if (eq (% percent 5) 0)
883                   (elmo-display-progress
884                    'elmo-list-bigger-diff "%s%d%%" percent mes))))
885         (setq l1 (cdr l1)))
886       (cons diff1 (list l2)))))
887
888 (defmacro elmo-get-hash-val (string hashtable)
889   (static-if (fboundp 'unintern)
890       `(symbol-value (intern-soft ,string ,hashtable))
891     `(let ((sym (intern-soft ,string ,hashtable)))
892        (and (boundp sym)
893             (symbol-value sym)))))
894
895 (defmacro elmo-set-hash-val (string value hashtable)
896   `(set (intern ,string ,hashtable) ,value))
897
898 (defmacro elmo-clear-hash-val (string hashtable)
899   (static-if (fboundp 'unintern)
900       (list 'unintern string hashtable)
901     (list 'makunbound (list 'intern string hashtable))))
902
903 (defmacro elmo-unintern (string)
904   "`unintern' symbol named STRING,  When can use `unintern'.
905 Emacs 19.28 or earlier does not have `unintern'."
906   (static-if (fboundp 'unintern)
907       (list 'unintern string)))
908
909 (defun elmo-make-hash (&optional hashsize)
910   "Make a new hash table which have HASHSIZE size."
911   (make-vector
912    (if hashsize
913        (max
914         ;; Prime numbers as lengths tend to result in good
915         ;; hashing; lengths one less than a power of two are
916         ;; also good.
917         (min
918          (let ((i 1))
919            (while (< (- i 1) hashsize)
920              (setq i (* 2 i)))
921            (- i 1))
922          elmo-hash-maximum-size)
923         elmo-hash-minimum-size)
924      elmo-hash-minimum-size)
925    0))
926
927 (defsubst elmo-mime-string (string)
928   "Normalize MIME encoded STRING."
929   (and string
930        (elmo-with-enable-multibyte
931          (encode-mime-charset-string
932           (eword-decode-and-unfold-unstructured-field-body string)
933           elmo-mime-charset))))
934
935 (defsubst elmo-collect-field (beg end downcase-field-name)
936   (save-excursion
937     (save-restriction
938       (narrow-to-region beg end)
939       (goto-char (point-min))
940       (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
941             dest name body)
942         (while (re-search-forward regexp nil t)
943           (setq name (buffer-substring-no-properties
944                       (match-beginning 1)(1- (match-end 1))))
945           (if downcase-field-name
946               (setq name (downcase name)))
947           (setq body (buffer-substring-no-properties
948                       (match-end 0) (std11-field-end)))
949           (or (assoc name dest)
950               (setq dest (cons (cons name body) dest))))
951         dest))))
952
953 (defsubst elmo-collect-field-from-string (string downcase-field-name)
954   (with-temp-buffer
955     (insert string)
956     (goto-char (point-min))
957     (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
958           dest name body)
959       (while (re-search-forward regexp nil t)
960         (setq name (buffer-substring-no-properties
961                     (match-beginning 1)(1- (match-end 1))))
962         (if downcase-field-name
963             (setq name (downcase name)))
964         (setq body (buffer-substring-no-properties
965                     (match-end 0) (std11-field-end)))
966         (or (assoc name dest)
967             (setq dest (cons (cons name body) dest))))
968       dest)))
969
970 (defun elmo-safe-filename (folder)
971   (elmo-replace-in-string
972    (elmo-replace-in-string
973     (elmo-replace-in-string folder "/" " ")
974     ":" "__")
975    "|" "_or_"))
976
977 (defvar elmo-filename-replace-chars nil)
978
979 (defsubst elmo-replace-string-as-filename (msgid)
980   "Replace string as filename."
981   (setq msgid (elmo-replace-in-string msgid " " "  "))
982   (if (null elmo-filename-replace-chars)
983       (setq elmo-filename-replace-chars
984             (regexp-quote (mapconcat
985                            'car elmo-filename-replace-string-alist ""))))
986   (while (string-match (concat "[" elmo-filename-replace-chars "]")
987                        msgid)
988     (setq msgid (concat
989                  (substring msgid 0 (match-beginning 0))
990                  (cdr (assoc
991                        (substring msgid
992                                   (match-beginning 0) (match-end 0))
993                        elmo-filename-replace-string-alist))
994                  (substring msgid (match-end 0)))))
995   msgid)
996
997 (defsubst elmo-recover-string-from-filename (filename)
998   "Recover string from FILENAME."
999   (let (tmp result)
1000     (while (string-match " " filename)
1001       (setq tmp (substring filename
1002                            (match-beginning 0)
1003                            (+ (match-end 0) 1)))
1004       (if (string= tmp "  ")
1005           (setq tmp " ")
1006         (setq tmp (car (rassoc tmp
1007                                elmo-filename-replace-string-alist))))
1008       (setq result
1009             (concat result
1010                     (substring filename 0 (match-beginning 0))
1011                     tmp))
1012       (setq filename (substring filename (+ (match-end 0) 1))))
1013     (concat result filename)))
1014
1015 (defsubst elmo-copy-file (src dst &optional ok-if-already-exists)
1016   (condition-case err
1017       (elmo-add-name-to-file src dst ok-if-already-exists)
1018     (error (copy-file src dst ok-if-already-exists t))))
1019
1020 (defsubst elmo-buffer-exists-p (buffer)
1021   (if (bufferp buffer)
1022       (buffer-live-p buffer)
1023     (get-buffer buffer)))
1024
1025 (defsubst elmo-kill-buffer (buffer)
1026   (when (elmo-buffer-exists-p buffer)
1027     (kill-buffer buffer)))
1028
1029 (defun elmo-delete-if (pred lst)
1030   "Return new list contain items which don't satisfy PRED in LST."
1031   (let (result)
1032     (while lst
1033       (unless (funcall pred (car lst))
1034         (setq result (cons (car lst) result)))
1035       (setq lst (cdr lst)))
1036     (nreverse result)))
1037
1038 (defun elmo-list-delete (list1 list2 &optional delete-function)
1039   "Delete by side effect any occurrences equal to elements of LIST1 from LIST2.
1040 Return the modified LIST2.  Deletion is done with `delete'.
1041 Write `(setq foo (elmo-list-delete bar foo))' to be sure of changing
1042 the value of `foo'.
1043 If optional DELETE-FUNCTION is speficied, it is used as delete procedure."
1044   (setq delete-function (or delete-function 'delete))
1045   (while list1
1046     (setq list2 (funcall delete-function (car list1) list2))
1047     (setq list1 (cdr list1)))
1048   list2)
1049
1050 (defun elmo-list-member (list1 list2)
1051   "If any element of LIST1 is member of LIST2, return t."
1052   (catch 'done
1053     (while list1
1054       (if (member (car list1) list2)
1055           (throw 'done t))
1056       (setq list1 (cdr list1)))))
1057
1058 (defun elmo-count-matches (regexp beg end)
1059   (let ((count 0))
1060     (save-excursion
1061       (goto-char beg)
1062       (while (re-search-forward regexp end t)
1063         (setq count (1+ count)))
1064       count)))
1065
1066 (if (fboundp 'display-error)
1067     (defalias 'elmo-display-error 'display-error)
1068   (defun elmo-display-error (error-object stream)
1069     "A tiny function to display ERROR-OBJECT to the STREAM."
1070     (let ((first t)
1071           (errobj error-object)
1072           err-mes)
1073       (while errobj
1074         (setq err-mes (concat err-mes (format
1075                                        (if (stringp (car errobj))
1076                                            "%s"
1077                                          "%S")
1078                                        (car errobj))))
1079         (setq errobj (cdr errobj))
1080         (if errobj (setq err-mes (concat err-mes (if first ": " ", "))))
1081         (setq first nil))
1082       (princ err-mes stream))))
1083
1084 (if (fboundp 'define-error)
1085     (defalias 'elmo-define-error 'define-error)
1086   (defun elmo-define-error (error doc &optional parents)
1087     (or parents
1088         (setq parents 'error))
1089     (let ((conds (get parents 'error-conditions)))
1090       (or conds
1091           (error "Not an error symbol: %s" error))
1092       (setplist error
1093                 (list 'error-message doc
1094                       'error-conditions (cons error conds))))))
1095
1096 (cond ((fboundp 'progress-feedback-with-label)
1097        (defalias 'elmo-display-progress 'progress-feedback-with-label))
1098       ((fboundp 'lprogress-display)
1099        (defalias 'elmo-display-progress 'lprogress-display))
1100       (t
1101        (defun elmo-display-progress (label format &optional value &rest args)
1102          "Print a progress message."
1103          (if (and (null format) (null args))
1104              (message nil)
1105            (apply (function message) (concat format " %d%%")
1106                   (nconc args (list value)))))))
1107
1108 (defvar elmo-progress-counter-alist nil)
1109
1110 (defmacro elmo-progress-counter-value (counter)
1111   (` (aref (cdr (, counter)) 0)))
1112
1113 (defmacro elmo-progress-counter-all-value (counter)
1114   (` (aref (cdr (, counter)) 1)))
1115
1116 (defmacro elmo-progress-counter-format (counter)
1117   (` (aref (cdr (, counter)) 2)))
1118
1119 (defmacro elmo-progress-counter-set-value (counter value)
1120   (` (aset (cdr (, counter)) 0 (, value))))
1121
1122 (defun elmo-progress-set (label all-value &optional format)
1123   (unless (assq label elmo-progress-counter-alist)
1124     (setq elmo-progress-counter-alist
1125           (cons (cons label (vector 0 all-value (or format "")))
1126                 elmo-progress-counter-alist))))
1127
1128 (defun elmo-progress-clear (label)
1129   (let ((counter (assq label elmo-progress-counter-alist)))
1130     (when counter
1131       (elmo-display-progress label
1132                              (elmo-progress-counter-format counter)
1133                              100)
1134       (setq elmo-progress-counter-alist
1135             (delq counter elmo-progress-counter-alist)))))
1136
1137 (defun elmo-progress-notify (label &optional value op &rest args)
1138   (let ((counter (assq label elmo-progress-counter-alist)))
1139     (when counter
1140       (let* ((value (or value 1))
1141              (cur-value (elmo-progress-counter-value counter))
1142              (all-value (elmo-progress-counter-all-value counter))
1143              (new-value (if (eq op 'set) value (+ cur-value value)))
1144              (cur-rate (/ (* cur-value 100) all-value))
1145              (new-rate (/ (* new-value 100) all-value)))
1146         (elmo-progress-counter-set-value counter new-value)
1147         (unless (= cur-rate new-rate)
1148           (apply 'elmo-display-progress
1149                  label
1150                  (elmo-progress-counter-format counter)
1151                  new-rate
1152                  args))
1153         (when (>= new-rate 100)
1154           (elmo-progress-clear label))))))
1155
1156 (put 'elmo-with-progress-display 'lisp-indent-function '2)
1157 (def-edebug-spec elmo-with-progress-display
1158   (form (symbolp form &optional form) &rest form))
1159
1160 (defmacro elmo-with-progress-display (condition spec &rest body)
1161   "Evaluate BODY with progress gauge if CONDITION is non-nil.
1162 SPEC is a list as followed (LABEL MAX-VALUE [FORMAT])."
1163   (let ((label (car spec))
1164         (max-value (cadr spec))
1165         (fmt (caddr spec)))
1166     `(unwind-protect
1167          (progn
1168            (when ,condition
1169              (elmo-progress-set (quote ,label) ,max-value ,fmt))
1170            ,@body)
1171        (elmo-progress-clear (quote ,label)))))
1172
1173 (defun elmo-time-expire (before-time diff-time)
1174   (let* ((current (current-time))
1175          (rest (when (< (nth 1 current) (nth 1 before-time))
1176                  (expt 2 16)))
1177          diff)
1178     (setq diff
1179           (list (- (+ (car current) (if rest -1 0)) (car before-time))
1180                 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1181     (and (eq (car diff) 0)
1182          (< diff-time (nth 1 diff)))))
1183
1184 (if (fboundp 'std11-fetch-field)
1185     (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1186   (defalias 'elmo-field-body 'std11-field-body))
1187
1188 (defun elmo-unfold-field-body (name)
1189   (let ((value (elmo-field-body name)))
1190     (and value
1191          (std11-unfold-string value))))
1192
1193 (defun elmo-decoded-field-body (field-name &optional mode)
1194   (let ((field-body (elmo-field-body field-name)))
1195     (and field-body
1196          (elmo-with-enable-multibyte
1197            (mime-decode-field-body field-body field-name mode)))))
1198
1199 (defun elmo-address-quote-specials (word)
1200   "Make quoted string of WORD if needed."
1201   (let ((lal (std11-lexical-analyze word)))
1202     (if (or (assq 'specials lal)
1203             (assq 'domain-literal lal))
1204         (prin1-to-string word)
1205       word)))
1206
1207 (defmacro elmo-string (string)
1208   "STRING without text property."
1209   (` (let ((obj (copy-sequence (, string))))
1210        (and obj (set-text-properties 0 (length obj) nil obj))
1211        obj)))
1212
1213 (defun elmo-flatten (list-of-list)
1214   "Flatten LIST-OF-LIST."
1215   (unless (null list-of-list)
1216     (append (if (and (car list-of-list)
1217                      (listp (car list-of-list)))
1218                 (car list-of-list)
1219               (list (car list-of-list)))
1220             (elmo-flatten (cdr list-of-list)))))
1221
1222 (defun elmo-y-or-n-p (prompt &optional auto default)
1223   "Same as `y-or-n-p'.
1224 But if optional argument AUTO is non-nil, DEFAULT is returned."
1225   (if auto
1226       default
1227     (y-or-n-p prompt)))
1228
1229 (defun elmo-string-member (string slist)
1230   (catch 'found
1231     (while slist
1232       (if (and (stringp (car slist))
1233                (string= string (car slist)))
1234           (throw 'found t))
1235       (setq slist (cdr slist)))))
1236
1237 (static-cond ((fboundp 'member-ignore-case)
1238        (defalias 'elmo-string-member-ignore-case 'member-ignore-case))
1239       ((fboundp 'compare-strings)
1240        (defun elmo-string-member-ignore-case (elt list)
1241          "Like `member', but ignores differences in case and text representation.
1242 ELT must be a string.  Upper-case and lower-case letters are treated as equal.
1243 Unibyte strings are converted to multibyte for comparison."
1244          (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
1245            (setq list (cdr list)))
1246          list))
1247       (t
1248        (defun elmo-string-member-ignore-case (elt list)
1249          "Like `member', but ignores differences in case and text representation.
1250 ELT must be a string.  Upper-case and lower-case letters are treated as equal."
1251          (let ((str (downcase elt)))
1252            (while (and list (not (string= str (downcase (car list)))))
1253              (setq list (cdr list)))
1254            list))))
1255
1256 (defun elmo-string-match-member (str list &optional case-ignore)
1257   (let ((case-fold-search case-ignore))
1258     (catch 'member
1259       (while list
1260         (if (string-match (car list) str)
1261             (throw 'member (car list)))
1262         (setq list (cdr list))))))
1263
1264 (defun elmo-string-matched-member (str list &optional case-ignore)
1265   (let ((case-fold-search case-ignore))
1266     (catch 'member
1267       (while list
1268         (if (string-match str (car list))
1269             (throw 'member (car list)))
1270         (setq list (cdr list))))))
1271
1272 (defsubst elmo-string-delete-match (string pos)
1273   (concat (substring string
1274                      0 (match-beginning pos))
1275           (substring string
1276                      (match-end pos)
1277                      (length string))))
1278
1279 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1280   (let ((case-fold-search case-ignore)
1281         a)
1282     (catch 'loop
1283       (while alist
1284         (setq a (car alist))
1285         (if (and (consp a)
1286                  (stringp (car a))
1287                  (string-match key (car a)))
1288             (throw 'loop a))
1289         (setq alist (cdr alist))))))
1290
1291 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1292   (let ((case-fold-search case-ignore)
1293         a)
1294     (catch 'loop
1295       (while alist
1296         (setq a (car alist))
1297         (if (and (consp a)
1298                  (stringp (car a))
1299                  (string-match (car a) key))
1300             (throw 'loop a))
1301         (setq alist (cdr alist))))))
1302
1303 (defun elmo-string-assoc (key alist)
1304   (let (a)
1305     (catch 'loop
1306       (while alist
1307         (setq a (car alist))
1308         (if (and (consp a)
1309                  (stringp (car a))
1310                  (string= key (car a)))
1311             (throw 'loop a))
1312         (setq alist (cdr alist))))))
1313
1314 (defun elmo-string-assoc-all (key alist)
1315   (let (matches)
1316     (while alist
1317       (if (string= key (car (car alist)))
1318           (setq matches
1319                 (cons (car alist)
1320                       matches)))
1321       (setq alist (cdr alist)))
1322     matches))
1323
1324 (defun elmo-string-rassoc (key alist)
1325   (let (a)
1326     (catch 'loop
1327       (while alist
1328         (setq a (car alist))
1329         (if (and (consp a)
1330                  (stringp (cdr a))
1331                  (string= key (cdr a)))
1332             (throw 'loop a))
1333         (setq alist (cdr alist))))))
1334
1335 (defun elmo-string-rassoc-all (key alist)
1336   (let (matches)
1337     (while alist
1338       (if (string= key (cdr (car alist)))
1339           (setq matches
1340                 (cons (car alist)
1341                       matches)))
1342       (setq alist (cdr alist)))
1343     matches))
1344
1345 (defun elmo-expand-newtext (newtext original)
1346   (let ((len (length newtext))
1347         (pos 0)
1348         c expanded beg N did-expand)
1349     (while (< pos len)
1350       (setq beg pos)
1351       (while (and (< pos len)
1352                   (not (= (aref newtext pos) ?\\)))
1353         (setq pos (1+ pos)))
1354       (unless (= beg pos)
1355         (push (substring newtext beg pos) expanded))
1356       (when (< pos len)
1357         ;; We hit a \; expand it.
1358         (setq did-expand t
1359               pos (1+ pos)
1360               c (aref newtext pos))
1361         (if (not (or (= c ?\&)
1362                      (and (>= c ?1)
1363                           (<= c ?9))))
1364             ;; \ followed by some character we don't expand.
1365             (push (char-to-string c) expanded)
1366           ;; \& or \N
1367           (if (= c ?\&)
1368               (setq N 0)
1369             (setq N (- c ?0)))
1370           (when (match-beginning N)
1371             (push (substring original (match-beginning N) (match-end N))
1372                   expanded))))
1373       (setq pos (1+ pos)))
1374     (if did-expand
1375         (apply (function concat) (nreverse expanded))
1376       newtext)))
1377
1378 ;;; Folder parser utils.
1379 (defun elmo-parse-token (string &optional seps)
1380   "Parse atom from STRING using SEPS as a string of separator char list."
1381   (let ((len (length string))
1382         (seps (and seps (string-to-char-list seps)))
1383         (i 0)
1384         (sep nil)
1385         content c in)
1386     (if (eq len 0)
1387         (cons "" "")
1388       (while (and (< i len) (or in (null sep)))
1389         (setq c (aref string i))
1390         (cond
1391          ((and in (eq c ?\\))
1392           (setq i (1+ i)
1393                 content (cons (aref string i) content)
1394                 i (1+ i)))
1395          ((eq c ?\")
1396           (setq in (not in)
1397                 i (1+ i)))
1398          (in (setq content (cons c content)
1399                    i (1+ i)))
1400          ((memq c seps)
1401           (setq sep c))
1402          (t (setq content (cons c content)
1403                   i (1+ i)))))
1404       (if in (error "Parse error in quoted"))
1405       (cons (if (null content) "" (char-list-to-string (nreverse content)))
1406             (substring string i)))))
1407
1408 (defun elmo-parse-prefixed-element (prefix string &optional seps)
1409   (if (and (not (eq (length string) 0))
1410            (eq (aref string 0) prefix))
1411       (elmo-parse-token (substring string 1) seps)
1412     (cons "" string)))
1413
1414 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1415 ;;
1416 ;; number          ::= [0-9]+
1417 ;; beg             ::= number
1418 ;; end             ::= number
1419 ;; number-range    ::= "(" beg " . " end ")"      ;; cons cell
1420 ;; number-set-elem ::= number / number-range
1421 ;; number-set      ::= "(" *number-set-elem ")"   ;; list
1422
1423 (defun elmo-number-set-member (number number-set)
1424   "Return non-nil if NUMBER is an element of NUMBER-SET.
1425 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1426   (or (memq number number-set)
1427       (let (found)
1428         (while (and number-set (not found))
1429           (if (and (consp (car number-set))
1430                    (and (<= (car (car number-set)) number)
1431                         (<= number (cdr (car number-set)))))
1432               (setq found t)
1433             (setq number-set (cdr number-set))))
1434         number-set)))
1435
1436 (defun elmo-number-set-append-list (number-set list)
1437   "Append LIST of numbers to the NUMBER-SET.
1438 NUMBER-SET is altered."
1439   (let ((appended number-set))
1440     (while list
1441       (setq appended (elmo-number-set-append appended (car list)))
1442       (setq list (cdr list)))
1443     appended))
1444
1445 (defun elmo-number-set-append (number-set number)
1446   "Append NUMBER to the NUMBER-SET.
1447 NUMBER-SET is altered."
1448   (let ((number-set-1 number-set)
1449         found elem)
1450     (while (and number-set (not found))
1451       (setq elem (car number-set))
1452       (cond
1453        ((and (consp elem)
1454              (eq (+ 1 (cdr elem)) number))
1455         (setcdr elem number)
1456         (setq found t))
1457        ((and (integerp elem)
1458              (eq (+ 1 elem) number))
1459         (setcar number-set (cons elem number))
1460         (setq found t))
1461        ((or (and (integerp elem) (eq elem number))
1462             (and (consp elem)
1463                  (<= (car elem) number)
1464                  (<= number (cdr elem))))
1465         (setq found t)))
1466       (setq number-set (cdr number-set)))
1467     (if (not found)
1468         (setq number-set-1 (nconc number-set-1 (list number))))
1469     number-set-1))
1470
1471 (defun elmo-number-set-delete-list (number-set list)
1472   "Delete LIST of numbers from the NUMBER-SET.
1473 NUMBER-SET is altered."
1474   (let ((deleted number-set))
1475     (dolist (number list)
1476       (setq deleted (elmo-number-set-delete deleted number)))
1477     deleted))
1478
1479 (defun elmo-number-set-delete (number-set number)
1480   "Delete NUMBER from the NUMBER-SET.
1481 NUMBER-SET is altered."
1482   (let* ((curr number-set)
1483          (top (cons 'dummy number-set))
1484          (prev top)
1485          elem found)
1486     (while (and curr (not found))
1487       (setq elem (car curr))
1488       (if (consp elem)
1489           (cond
1490            ((eq (car elem) number)
1491             (if (eq (cdr elem) (1+ number))
1492                 (setcar curr (cdr elem))
1493               (setcar elem (1+ number)))
1494             (setq found t))
1495            ((eq (cdr elem) number)
1496             (if (eq (car elem) (1- number))
1497                 (setcar curr (car elem))
1498               (setcdr elem (1- number)))
1499             (setq found t))
1500            ((and (> number (car elem))
1501                  (< number (cdr elem)))
1502             (setcdr
1503              prev
1504              (nconc
1505               (list
1506                ;; (beg . (1- number))
1507                (let ((new (cons (car elem) (1- number))))
1508                  (if (eq (car new) (cdr new))
1509                      (car new)
1510                    new))
1511                ;; ((1+ number) . end)
1512                (let ((new (cons (1+ number) (cdr elem))))
1513                  (if (eq (car new) (cdr new))
1514                      (car new)
1515                    new)))
1516               (cdr curr)))))
1517         (when (eq elem number)
1518           (setcdr prev (cdr curr))
1519           (setq found t)))
1520       (setq prev curr
1521             curr (cdr curr)))
1522     (cdr top)))
1523
1524 (defun elmo-make-number-list (beg end)
1525   (let (number-list i)
1526     (setq i end)
1527     (while (>= i beg)
1528       (setq number-list (cons i number-list))
1529       (setq i (1- i)))
1530     number-list))
1531
1532 (defun elmo-number-set-to-number-list (number-set)
1533   "Return a number list which corresponds to NUMBER-SET."
1534   (let ((number-list (list 'dummy))
1535         elem)
1536     (while number-set
1537       (setq elem (car number-set))
1538       (cond
1539        ((consp elem)
1540         (nconc number-list (elmo-make-number-list (car elem) (cdr elem))))
1541        ((integerp elem)
1542         (nconc number-list (list elem))))
1543       (setq number-set (cdr number-set)))
1544     (cdr number-list)))
1545
1546 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1547   "*Regexp to filter subfolders."
1548   :type 'regexp
1549   :group 'elmo)
1550
1551 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1552   (let ((root (zerop (length curdir)))
1553         (w32-get-true-file-link-count t) ; for Meadow
1554         attr dirs dir)
1555     (catch 'done
1556       (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1557         (when (and (not (string-match
1558                          elmo-list-subdirectories-ignore-regexp
1559                          file))
1560                    (car (setq attr (file-attributes
1561                                     (expand-file-name file dir)))))
1562           (when (eq one-level 'check) (throw 'done t))
1563           (let ((relpath
1564                  (concat curdir (and (not root) elmo-path-sep) file))
1565                 subdirs)
1566             (setq dirs (nconc dirs
1567                               (if (if elmo-have-link-count (< 2 (nth 1 attr))
1568                                     (setq subdirs
1569                                           (elmo-list-subdirectories-1
1570                                            basedir
1571                                            relpath
1572                                            (if one-level 'check))))
1573                                   (if one-level
1574                                       (list (list relpath))
1575                                     (cons relpath
1576                                           (or subdirs
1577                                               (elmo-list-subdirectories-1
1578                                                basedir
1579                                                relpath
1580                                                nil))))
1581                                 (list relpath)))))))
1582       dirs)))
1583
1584 (defun elmo-list-subdirectories (directory file one-level)
1585   (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1586     (if (zerop (length file))
1587         subdirs
1588       (cons file subdirs))))
1589
1590 (defun elmo-mapcar-list-of-list (func list-of-list)
1591   (mapcar
1592    (lambda (x)
1593      (cond ((listp x) (elmo-mapcar-list-of-list func x))
1594            (t (funcall func x))))
1595    list-of-list))
1596
1597 (defun elmo-parse (string regexp &optional matchn)
1598   (or matchn (setq matchn 1))
1599   (let (list)
1600     (store-match-data nil)
1601     (while (string-match regexp string (match-end 0))
1602       (setq list (cons (substring string (match-beginning matchn)
1603                                   (match-end matchn)) list)))
1604     (nreverse list)))
1605
1606 ;;; File cache.
1607 (defmacro elmo-make-file-cache (path status)
1608   "PATH is the cache file name.
1609 STATUS is one of 'section, 'entire or nil.
1610  nil means no cache exists.
1611 'section means partial section cache exists.
1612 'entire means entire cache exists.
1613 If the cache is partial file-cache, TYPE is 'partial."
1614   (` (cons (, path) (, status))))
1615
1616 (defmacro elmo-file-cache-path (file-cache)
1617   "Returns the file path of the FILE-CACHE."
1618   (` (car (, file-cache))))
1619
1620 (defmacro elmo-file-cache-status (file-cache)
1621   "Returns the status of the FILE-CACHE."
1622   (` (cdr (, file-cache))))
1623
1624 (defsubst elmo-cache-to-msgid (filename)
1625   (concat "<" (elmo-recover-string-from-filename filename) ">"))
1626
1627 (defsubst elmo-cache-get-path-subr (msgid)
1628   (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1629         (clist (string-to-char-list msgid))
1630         (sum 0))
1631     (while clist
1632       (setq sum (+ sum (car clist)))
1633       (setq clist (cdr clist)))
1634     (format "%c%c"
1635             (nth (% (/ sum 16) 2) chars)
1636             (nth (% sum 16) chars))))
1637
1638 ;;;
1639 (defun elmo-file-cache-get-path (msgid &optional section)
1640   "Get cache path for MSGID.
1641 If optional argument SECTION is specified, partial cache path is returned."
1642   (if (setq msgid (elmo-msgid-to-cache msgid))
1643       (expand-file-name
1644        (if section
1645            (format "%s/%s/%s/%s"
1646                    elmo-cache-directory
1647                    (elmo-cache-get-path-subr msgid)
1648                    msgid
1649                    section)
1650          (format "%s/%s/%s"
1651                  elmo-cache-directory
1652                  (elmo-cache-get-path-subr msgid)
1653                  msgid)))))
1654
1655 (defmacro elmo-file-cache-expand-path (path section)
1656   "Return file name for the file-cache corresponds to the section.
1657 PATH is the file-cache path.
1658 SECTION is the section string."
1659   (` (expand-file-name (or (, section) "") (, path))))
1660
1661 (defun elmo-file-cache-delete (path)
1662   "Delete a cache on PATH."
1663   (when (file-exists-p path)
1664     (if (file-directory-p path)
1665         (progn
1666           (dolist (file (directory-files path t "^[^\\.]"))
1667             (delete-file file))
1668           (delete-directory path))
1669       (delete-file path))
1670     t))
1671
1672 (defun elmo-file-cache-exists-p (msgid)
1673   "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1674   (elmo-file-cache-status (elmo-file-cache-get msgid)))
1675
1676 (defun elmo-file-cache-save (cache-path section)
1677   "Save current buffer as cache on PATH.
1678 Return t if cache is saved successfully."
1679   (condition-case nil
1680       (let ((path (if section (expand-file-name section cache-path)
1681                     cache-path))
1682             files dir)
1683         (if (and (null section)
1684                  (file-directory-p path))
1685             (progn
1686               (setq files (directory-files path t "^[^\\.]"))
1687               (while files
1688                 (delete-file (car files))
1689                 (setq files (cdr files)))
1690               (delete-directory path))
1691           (if (and section
1692                    (not (file-directory-p cache-path)))
1693               (delete-file cache-path)))
1694         (when path
1695           (setq dir (directory-file-name (file-name-directory path)))
1696           (if (not (file-exists-p dir))
1697               (elmo-make-directory dir))
1698           (write-region-as-binary (point-min) (point-max)
1699                                   path nil 'no-msg)
1700           t))
1701     ;; ignore error
1702     (error)))
1703
1704 (defun elmo-file-cache-load (cache-path section)
1705   "Load cache on PATH into the current buffer.
1706 Return t if cache is loaded successfully."
1707   (condition-case nil
1708       (let (cache-file)
1709         (when (and cache-path
1710                    (if (elmo-cache-path-section-p cache-path)
1711                        section
1712                      (null section))
1713                    (setq cache-file (elmo-file-cache-expand-path
1714                                      cache-path
1715                                      section))
1716                    (file-exists-p cache-file))
1717           (insert-file-contents-as-binary cache-file)
1718           t))
1719     ;; igore error
1720     (error)))
1721
1722 (defun elmo-cache-path-section-p (path)
1723   "Return non-nil when PATH is `section' cache path."
1724   (file-directory-p path))
1725
1726 (defun elmo-file-cache-get (msgid &optional section)
1727   "Returns the current file-cache object associated with MSGID.
1728 MSGID is the message-id of the message.
1729 If optional argument SECTION is specified, get partial file-cache object
1730 associated with SECTION."
1731   (if msgid
1732       (let ((path (elmo-cache-get-path msgid)))
1733         (if (and path (file-exists-p path))
1734             (if (elmo-cache-path-section-p path)
1735                 (if section
1736                     (if (file-exists-p (setq path (expand-file-name
1737                                                    section path)))
1738                         (cons path 'section))
1739                   ;; section is not specified but sectional.
1740                   (cons path 'section))
1741               ;; not directory.
1742               (unless section
1743                 (cons path 'entire)))
1744           ;; no cache.
1745           (cons path nil)))))
1746
1747 ;;;
1748 ;; Expire cache.
1749
1750 (defun elmo-cache-expire ()
1751   (interactive)
1752   (let* ((completion-ignore-case t)
1753          (method (completing-read (format "Expire by (%s): "
1754                                           elmo-cache-expire-default-method)
1755                                   '(("size" . "size")
1756                                     ("age" . "age"))
1757                                   nil t)))
1758     (when (string= method "")
1759       (setq method elmo-cache-expire-default-method))
1760     (funcall (intern (concat "elmo-cache-expire-by-" method)))))
1761
1762 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
1763   (let ((str (read-from-minibuffer prompt initial)))
1764     (cond
1765      ((string-match "[0-9]*\\.[0-9]+" str)
1766       (string-to-number str))
1767      ((string-match "[0-9]+" str)
1768       (string-to-number (concat str ".0")))
1769      (t (error "%s is not number" str)))))
1770
1771 (defun elmo-cache-expire-by-size (&optional kbytes)
1772   "Expire cache file by size.
1773 If KBYTES is kilo bytes (This value must be float)."
1774   (interactive)
1775   (let ((size (or kbytes
1776                   (and (interactive-p)
1777                        (elmo-read-float-value-from-minibuffer
1778                         "Enter cache disk size (Kbytes): "
1779                         (number-to-string
1780                          (if (integerp elmo-cache-expire-default-size)
1781                              (float elmo-cache-expire-default-size)
1782                            elmo-cache-expire-default-size))))
1783                   (if (integerp elmo-cache-expire-default-size)
1784                       (float elmo-cache-expire-default-size))))
1785         (count 0)
1786         (Kbytes 1024)
1787         total beginning)
1788     (message "Checking disk usage...")
1789     (setq total (/ (elmo-disk-usage
1790                     elmo-cache-directory) Kbytes))
1791     (setq beginning total)
1792     (message "Checking disk usage...done")
1793     (let ((cfl (elmo-cache-get-sorted-cache-file-list))
1794           (deleted 0)
1795           oldest
1796           cur-size cur-file)
1797       (while (and (<= size total)
1798                   (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
1799         (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
1800         (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
1801         (when (elmo-file-cache-delete cur-file)
1802           (setq count (+ count 1))
1803           (message "%d cache(s) are expired." count))
1804         (setq deleted (+ deleted cur-size))
1805         (setq total (- total cur-size)))
1806       (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
1807                count deleted beginning))))
1808
1809 (defun elmo-cache-make-file-entity (filename path)
1810   (cons filename (elmo-get-last-accessed-time filename path)))
1811
1812 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
1813   (let ((cfl cache-file-list)
1814         flist firsts oldest-entity wonlist)
1815     (while cfl
1816       (setq flist (cdr (car cfl)))
1817       (setq firsts (append firsts (list
1818                                    (cons (car (car cfl))
1819                                          (car flist)))))
1820       (setq cfl (cdr cfl)))
1821 ;;; (prin1 firsts)
1822     (while firsts
1823       (if (and (not oldest-entity)
1824                (cdr (cdr (car firsts))))
1825           (setq oldest-entity (car firsts)))
1826       (if (and (cdr (cdr (car firsts)))
1827                (cdr (cdr oldest-entity))
1828                (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
1829           (setq oldest-entity (car firsts)))
1830       (setq firsts (cdr firsts)))
1831     (setq wonlist (assoc (car oldest-entity) cache-file-list))
1832     (and wonlist
1833          (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
1834     oldest-entity))
1835
1836 (defun elmo-cache-get-sorted-cache-file-list ()
1837   (let ((dirs (directory-files
1838                elmo-cache-directory
1839                t "^[^\\.]"))
1840         (i 0) num
1841         elist
1842         ret-val)
1843     (setq num (length dirs))
1844     (message "Collecting cache info...")
1845     (while dirs
1846       (setq elist (mapcar (lambda (x)
1847                             (elmo-cache-make-file-entity x (car dirs)))
1848                           (directory-files (car dirs) nil "^[^\\.]")))
1849       (setq ret-val (append ret-val
1850                             (list (cons
1851                                    (car dirs)
1852                                    (sort
1853                                     elist
1854                                     (lambda (x y)
1855                                       (< (cdr x)
1856                                          (cdr y))))))))
1857       (when (> num elmo-display-progress-threshold)
1858         (setq i (+ i 1))
1859         (elmo-display-progress
1860          'elmo-cache-get-sorted-cache-file-list "Collecting cache info..."
1861          (/ (* i 100) num)))
1862       (setq dirs (cdr dirs)))
1863     (message "Collecting cache info...done")
1864     ret-val))
1865
1866 (defun elmo-cache-expire-by-age (&optional days)
1867   (let ((age (or (and days (int-to-string days))
1868                  (and (interactive-p)
1869                       (read-from-minibuffer
1870                        (format "Enter days (%s): "
1871                                elmo-cache-expire-default-age)))
1872                  (int-to-string elmo-cache-expire-default-age)))
1873         (dirs (directory-files
1874                elmo-cache-directory
1875                t "^[^\\.]"))
1876         (count 0)
1877         curtime)
1878     (if (string= age "")
1879         (setq age elmo-cache-expire-default-age)
1880       (setq age (string-to-int age)))
1881     (setq curtime (current-time))
1882     (setq curtime (+ (* (nth 0 curtime)
1883                         (float 65536)) (nth 1 curtime)))
1884     (while dirs
1885       (let ((files (directory-files (car dirs) t "^[^\\.]"))
1886             (limit-age (* age 86400)))
1887         (while files
1888           (when (> (- curtime (elmo-get-last-accessed-time (car files)))
1889                    limit-age)
1890             (when (elmo-file-cache-delete (car files))
1891               (setq count (+ 1 count))
1892               (message "%d cache file(s) are expired." count)))
1893           (setq files (cdr files))))
1894       (setq dirs (cdr dirs)))))
1895
1896 ;;;
1897 ;; msgid to path.
1898 (defun elmo-msgid-to-cache (msgid)
1899   (save-match-data
1900     (when (and msgid
1901                (string-match "<\\(.+\\)>$" msgid))
1902       (elmo-replace-string-as-filename (elmo-match-string 1 msgid)))))
1903
1904 (defun elmo-cache-get-path (msgid &optional folder number)
1905   "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
1906   (if (setq msgid (elmo-msgid-to-cache msgid))
1907       (expand-file-name
1908        (expand-file-name
1909         (if folder
1910             (format "%s/%s/%s@%s"
1911                     (elmo-cache-get-path-subr msgid)
1912                     msgid
1913                     (or number "")
1914                     (elmo-safe-filename folder))
1915           (format "%s/%s"
1916                   (elmo-cache-get-path-subr msgid)
1917                   msgid))
1918         elmo-cache-directory))))
1919
1920 ;;;
1921 ;; Warnings.
1922
1923 (static-if (fboundp 'display-warning)
1924     (defmacro elmo-warning (&rest args)
1925       "Display a warning with `elmo' group."
1926       `(display-warning 'elmo (format ,@args)))
1927   (defconst elmo-warning-buffer-name "*elmo warning*")
1928   (defun elmo-warning (&rest args)
1929     "Display a warning. ARGS are passed to `format'."
1930     (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
1931       (goto-char (point-max))
1932       (funcall 'insert (apply 'format (append args '("\n"))))
1933       (ignore-errors (recenter 1))
1934       (display-buffer elmo-warning-buffer-name))))
1935
1936 (defvar elmo-obsolete-variable-alist nil)
1937
1938 (defcustom elmo-obsolete-variable-show-warnings t
1939   "Show warning window if obsolete variable is treated."
1940   :type 'boolean
1941   :group 'elmo)
1942
1943 (defun elmo-define-obsolete-variable (obsolete var)
1944   "Define obsolete variable.
1945 OBSOLETE is a symbol for obsolete variable.
1946 VAR is a symbol for new variable.
1947 Definition is stored in `elmo-obsolete-variable-alist'."
1948   (let ((pair (assq var elmo-obsolete-variable-alist)))
1949     (if pair
1950         (setcdr pair obsolete)
1951       (setq elmo-obsolete-variable-alist
1952             (cons (cons var obsolete)
1953                   elmo-obsolete-variable-alist)))))
1954
1955 (defun elmo-resque-obsolete-variable (obsolete var)
1956   "Resque obsolete variable OBSOLETE as VAR.
1957 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
1958   (when (boundp obsolete)
1959     (static-if (and (fboundp 'defvaralias)
1960                     (subrp (symbol-function 'defvaralias)))
1961         (defvaralias var obsolete)
1962       (set var (symbol-value obsolete)))
1963     (if elmo-obsolete-variable-show-warnings
1964         (elmo-warning "%s is obsolete. Use %s instead."
1965                       (symbol-name obsolete)
1966                       (symbol-name var)))))
1967
1968 (defun elmo-resque-obsolete-variables (&optional alist)
1969   "Resque obsolete variables in ALIST.
1970 ALIST is a list of cons cell of
1971 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
1972 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
1973   (dolist (pair elmo-obsolete-variable-alist)
1974     (elmo-resque-obsolete-variable (cdr pair)
1975                                    (car pair))))
1976
1977 (defsubst elmo-msgdb-get-last-message-id (string)
1978   (if string
1979       (save-match-data
1980         (let (beg)
1981           (elmo-set-work-buf
1982            (insert string)
1983            (goto-char (point-max))
1984            (when (search-backward "<" nil t)
1985              (setq beg (point))
1986              (if (search-forward ">" nil t)
1987                  (elmo-replace-in-string
1988                   (buffer-substring beg (point)) "\n[ \t]*" ""))))))))
1989
1990 (defun elmo-msgdb-get-message-id-from-buffer ()
1991   (let ((msgid (elmo-field-body "message-id")))
1992     (if msgid
1993         (if (string-match "<\\(.+\\)>$" msgid)
1994             msgid
1995           (concat "<" msgid ">"))       ; Invaild message-id.
1996       ;; no message-id, so put dummy msgid.
1997       (concat "<"
1998               (if (elmo-unfold-field-body "date")
1999                   (timezone-make-date-sortable (elmo-unfold-field-body "date"))
2000                 (md5 (string-as-unibyte (buffer-string))))
2001               (nth 1 (eword-extract-address-components
2002                       (or (elmo-field-body "from") "nobody"))) ">"))))
2003
2004 (defun elmo-msgdb-get-references-from-buffer ()
2005   (if elmo-msgdb-prefer-in-reply-to-for-parent
2006       (or (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to"))
2007           (elmo-msgdb-get-last-message-id (elmo-field-body "references")))
2008     (or (elmo-msgdb-get-last-message-id (elmo-field-body "references"))
2009         (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to")))))
2010
2011 (defsubst elmo-msgdb-insert-file-header (file)
2012   "Insert the header of the article."
2013   (let ((beg 0)
2014         insert-file-contents-pre-hook   ; To avoid autoconv-xmas...
2015         insert-file-contents-post-hook
2016         format-alist)
2017     (when (file-exists-p file)
2018       ;; Read until header separator is found.
2019       (while (and (eq elmo-msgdb-file-header-chop-length
2020                       (nth 1
2021                            (insert-file-contents-as-binary
2022                             file nil beg
2023                             (incf beg elmo-msgdb-file-header-chop-length))))
2024                   (prog1 (not (search-forward "\n\n" nil t))
2025                     (goto-char (point-max))))))))
2026
2027 ;;
2028 ;; overview handling
2029 ;;
2030 (defun elmo-multiple-field-body (name &optional boundary)
2031   (save-excursion
2032     (save-restriction
2033       (std11-narrow-to-header boundary)
2034       (goto-char (point-min))
2035       (let ((case-fold-search t)
2036             (field-body nil))
2037         (while (re-search-forward (concat "^" name ":[ \t]*") nil t)
2038           (setq field-body
2039                 (nconc field-body
2040                        (list (buffer-substring-no-properties
2041                               (match-end 0) (std11-field-end))))))
2042         field-body))))
2043
2044 (defun elmo-parse-addresses (string)
2045   (if (null string)
2046       ()
2047     (elmo-set-work-buf
2048       (let (list start s char)
2049         (insert string)
2050         (goto-char (point-min))
2051         (skip-chars-forward "\t\f\n\r ")
2052         (setq start (point))
2053         (while (not (eobp))
2054           (skip-chars-forward "^\"\\,(")
2055           (setq char (following-char))
2056           (cond ((= char ?\\)
2057                  (forward-char 1)
2058                  (if (not (eobp))
2059                      (forward-char 1)))
2060                 ((= char ?,)
2061                  (setq s (buffer-substring start (point)))
2062                  (if (or (null (string-match "^[\t\f\n\r ]+$" s))
2063                          (not (string= s "")))
2064                      (setq list (cons s list)))
2065                  (skip-chars-forward ",\t\f\n\r ")
2066                  (setq start (point)))
2067                 ((= char ?\")
2068                  (re-search-forward "[^\\]\"" nil 0))
2069                 ((= char ?\()
2070                  (let ((parens 1))
2071                    (forward-char 1)
2072                    (while (and (not (eobp)) (not (zerop parens)))
2073                      (re-search-forward "[()]" nil 0)
2074                      (cond ((or (eobp)
2075                                 (= (char-after (- (point) 2)) ?\\)))
2076                            ((= (preceding-char) ?\()
2077                             (setq parens (1+ parens)))
2078                            (t
2079                             (setq parens (1- parens)))))))))
2080         (setq s (buffer-substring start (point)))
2081         (if (and (null (string-match "^[\t\f\n\r ]+$" s))
2082                  (not (string= s "")))
2083             (setq list (cons s list)))
2084         (nreverse list)))))
2085
2086 ;;; Queue.
2087 (defvar elmo-dop-queue-filename "queue"
2088   "*Disconnected operation queue is saved in this file.")
2089
2090 (defun elmo-dop-queue-load ()
2091   (setq elmo-dop-queue
2092         (elmo-object-load
2093          (expand-file-name elmo-dop-queue-filename
2094                            elmo-msgdb-directory))))
2095
2096 (defun elmo-dop-queue-save ()
2097   (elmo-object-save
2098    (expand-file-name elmo-dop-queue-filename
2099                      elmo-msgdb-directory)
2100    elmo-dop-queue))
2101
2102 (if (and (fboundp 'regexp-opt)
2103          (not (featurep 'xemacs)))
2104     (defalias 'elmo-regexp-opt 'regexp-opt)
2105   (defun elmo-regexp-opt (strings &optional paren)
2106     "Return a regexp to match a string in STRINGS.
2107 Each string should be unique in STRINGS and should not contain any regexps,
2108 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
2109 is enclosed by at least one regexp grouping construct."
2110     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
2111       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
2112               close-paren))))
2113
2114 (require 'product)
2115 (product-provide (provide 'elmo-util) (require 'elmo-version))
2116
2117 ;;; elmo-util.el ends here