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