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