* modb-standard.el (elmo-msgdb-set-flag): Use
[elisp/wanderlust.git] / elmo / elmo-util.el
1 ;;; elmo-util.el --- Utilities for ELMO.
2
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
4
5 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
6 ;; Keywords: mail, net news
7
8 ;; This file is part of ELMO (Elisp Library for Message Orchestration).
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14 ;;
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19 ;;
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24 ;;
25
26 ;;; Commentary:
27 ;;
28
29 ;;; Code:
30 ;;
31
32 (eval-when-compile (require 'cl))
33 (require 'elmo-vars)
34 (require 'elmo-date)
35 (require 'mcharset)
36 (require 'pces)
37 (require 'std11)
38 (require 'eword-decode)
39 (require 'utf7)
40 (require 'poem)
41 (require 'emu)
42
43 (eval-and-compile
44   (autoload 'md5 "md5"))
45
46 (defvar elmo-work-buf-name " *elmo work*")
47 (defvar elmo-temp-buf-name " *elmo temp*")
48
49 (or (boundp 'default-enable-multibyte-characters)
50     (defvar default-enable-multibyte-characters (featurep 'mule)
51       "The mock variable except for Emacs 20."))
52
53 (defun elmo-base64-encode-string (string &optional no-line-break))
54 (defun elmo-base64-decode-string (string))
55
56 ;; base64 encoding/decoding
57 (require 'mel)
58 (fset 'elmo-base64-encode-string
59       (mel-find-function 'mime-encode-string "base64"))
60 (fset 'elmo-base64-decode-string
61       (mel-find-function 'mime-decode-string "base64"))
62
63 ;; Any Emacsen may have add-name-to-file(), because loadup.el requires it. :-p
64 ;; Check make-symbolic-link() instead.  -- 981002 by Fuji
65 (if (fboundp 'make-symbolic-link)  ;; xxx
66     (defalias 'elmo-add-name-to-file 'add-name-to-file)
67   (defun elmo-add-name-to-file
68     (filename newname &optional ok-if-already-exists)
69     (copy-file filename newname ok-if-already-exists t)))
70
71 (defmacro elmo-set-work-buf (&rest body)
72   "Execute BODY on work buffer.  Work buffer remains."
73   (` (save-excursion
74        (set-buffer (get-buffer-create elmo-work-buf-name))
75        (set-buffer-multibyte default-enable-multibyte-characters)
76        (erase-buffer)
77        (,@ body))))
78
79 (put 'elmo-set-work-buf 'lisp-indent-function 0)
80 (def-edebug-spec elmo-set-work-buf t)
81
82 (defmacro elmo-bind-directory (dir &rest body)
83   "Set current directory DIR and execute BODY."
84   (` (let ((default-directory (file-name-as-directory (, dir))))
85        (,@ body))))
86
87 (put 'elmo-bind-directory 'lisp-indent-function 1)
88 (def-edebug-spec elmo-bind-directory
89   (form &rest form))
90
91 (defconst elmo-multibyte-buffer-name " *elmo-multibyte-buffer*")
92
93 (defmacro elmo-with-enable-multibyte (&rest body)
94   "Evaluate BODY with `enable-multibyte-character' as non-nil."
95   `(let ((default-enable-multibyte-characters t))
96      (with-current-buffer (get-buffer-create elmo-multibyte-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)
742   (let ((clist1 (sort (copy-sequence list1) #'<))
743         (clist2 (sort (copy-sequence list2) #'<))
744         list1-only list2-only)
745     (while (or clist1 clist2)
746       (cond
747        ((null clist1)
748         (while clist2
749           (setq list2-only (cons (car clist2) list2-only))
750           (setq clist2 (cdr clist2))))
751        ((null clist2)
752         (while clist1
753           (setq list1-only (cons (car clist1) list1-only))
754           (setq clist1 (cdr clist1))))
755        ((< (car clist1) (car clist2))
756         (while (not (eq (car clist1) (car clist2)))
757           (setq list1-only (cons (car clist1) list1-only))
758           (setq clist1 (cdr clist1)))
759         (setq clist1 (cdr clist1)
760               clist2 (cdr clist2)))
761        ((< (car clist2) (car clist1))
762         (while (not (eq (car clist1) (car clist2)))
763           (setq list2-only (cons (car clist2) list2-only))
764           (setq clist2 (cdr clist2)))
765         (setq clist1 (cdr clist1)
766               clist2 (cdr clist2)))
767        ((= (car clist1) (car clist2))
768         (setq clist1 (cdr clist1)
769               clist2 (cdr clist2)))))
770     (list list1-only list2-only)))
771
772 (defun elmo-list-diff-nonsortable (list1 list2)
773   (let ((clist1 (copy-sequence list1))
774         (clist2 (copy-sequence list2)))
775     (while list2
776       (setq clist1 (delq (car list2) clist1))
777       (setq list2 (cdr list2)))
778     (while list1
779       (setq clist2 (delq (car list1) clist2))
780       (setq list1 (cdr list1)))
781     (list clist1 clist2)))
782
783 (defun elmo-list-bigger-diff (list1 list2 &optional mes)
784   "Returns a list (- +). + is bigger than max of LIST1, in LIST2."
785   (if (null list2)
786       (cons list1  nil)
787     (let* ((l1 list1)
788            (l2 list2)
789            (max-of-l2 (or (nth (max 0 (1- (length l2))) l2) 0))
790            diff1 num i percent
791            )
792       (setq i 0)
793       (setq num (+ (length l1)))
794       (while l1
795         (if (memq (car l1) l2)
796             (if (eq (car l1) (car l2))
797                 (setq l2 (cdr l2))
798               (delq (car l1) l2))
799           (if (> (car l1) max-of-l2)
800               (setq diff1 (nconc diff1 (list (car l1))))))
801         (if mes
802             (progn
803               (setq i (+ i 1))
804               (setq percent (/ (* i 100) num))
805               (if (eq (% percent 5) 0)
806                   (elmo-display-progress
807                    'elmo-list-bigger-diff "%s%d%%" percent mes))))
808         (setq l1 (cdr l1)))
809       (cons diff1 (list l2)))))
810
811 (defmacro elmo-filter-condition-p (filter)
812   `(or (vectorp ,filter) (consp ,filter)))
813
814 (defmacro elmo-filter-type (filter)
815   (` (aref (, filter) 0)))
816
817 (defmacro elmo-filter-key (filter)
818   (` (aref (, filter) 1)))
819
820 (defmacro elmo-filter-value (filter)
821   (` (aref (, filter) 2)))
822
823 (defsubst elmo-buffer-field-primitive-condition-match (condition
824                                                        number
825                                                        number-list)
826   (let (result)
827     (goto-char (point-min))
828     (cond
829      ((string= (elmo-filter-key condition) "last")
830       (setq result (<= (length (memq number number-list))
831                        (string-to-int (elmo-filter-value condition)))))
832      ((string= (elmo-filter-key condition) "first")
833       (setq result (< (- (length number-list)
834                          (length (memq number number-list)))
835                       (string-to-int (elmo-filter-value condition)))))
836      ((string= (elmo-filter-key condition) "since")
837       (let ((field-date (elmo-date-make-sortable-string
838                          (timezone-fix-time
839                           (std11-field-body "date")
840                           (current-time-zone) nil)))
841             (specified-date (elmo-date-make-sortable-string
842                              (elmo-date-get-datevec
843                               (elmo-filter-value condition)))))
844         (setq result
845               (or (string= field-date specified-date)
846                   (string< specified-date field-date)))))
847      ((string= (elmo-filter-key condition) "before")
848       (setq result
849             (string<
850              (elmo-date-make-sortable-string
851               (timezone-fix-time
852                (std11-field-body "date")
853                (current-time-zone) nil))
854              (elmo-date-make-sortable-string
855               (elmo-date-get-datevec
856                (elmo-filter-value condition))))))
857      ((string= (elmo-filter-key condition) "body")
858       (and (re-search-forward "^$" nil t)          ; goto body
859            (setq result (search-forward (elmo-filter-value condition)
860                                         nil t))))
861      (t
862       (dolist (fval (elmo-multiple-field-body (elmo-filter-key condition)))
863         (if (eq (length fval) 0) (setq fval nil))
864         (if fval (setq fval (eword-decode-string fval)))
865         (setq result (or result
866                          (and fval (string-match
867                                     (elmo-filter-value condition) fval)))))))
868     (if (eq (elmo-filter-type condition) 'unmatch)
869         (setq result (not result)))
870     result))
871
872 (defun elmo-condition-in-msgdb-p-internal (condition fields)
873   (cond
874    ((vectorp condition)
875     (if (not (member (elmo-filter-key condition) fields))
876         (throw 'found t)))
877    ((or (eq (car condition) 'and)
878         (eq (car condition) 'or))
879     (elmo-condition-in-msgdb-p-internal (nth 1 condition) fields)
880     (elmo-condition-in-msgdb-p-internal (nth 2 condition) fields))))
881
882 (defun elmo-condition-in-msgdb-p (condition)
883   (not (catch 'found
884          (elmo-condition-in-msgdb-p-internal condition
885                                              (append
886                                               elmo-msgdb-extra-fields
887                                               '("last" "first" "from"
888                                                 "subject" "to" "cc" "since"
889                                                 "before"))))))
890
891 (defun elmo-buffer-field-condition-match (condition number number-list)
892   (cond
893    ((vectorp condition)
894     (elmo-buffer-field-primitive-condition-match
895      condition number number-list))
896    ((eq (car condition) 'and)
897     (and (elmo-buffer-field-condition-match
898           (nth 1 condition) number number-list)
899          (elmo-buffer-field-condition-match
900           (nth 2 condition) number number-list)))
901    ((eq (car condition) 'or)
902     (or (elmo-buffer-field-condition-match
903          (nth 1 condition) number number-list)
904         (elmo-buffer-field-condition-match
905          (nth 2 condition) number number-list)))))
906
907 (defsubst elmo-file-field-primitive-condition-match (file
908                                                      condition
909                                                      number
910                                                      number-list)
911   (let (result)
912     (goto-char (point-min))
913     (cond
914      ((string= (elmo-filter-key condition) "last")
915       (setq result (<= (length (memq number number-list))
916                        (string-to-int (elmo-filter-value condition))))
917       (if (eq (elmo-filter-type condition) 'unmatch)
918           (setq result (not result))))
919      ((string= (elmo-filter-key condition) "first")
920       (setq result (< (- (length number-list)
921                          (length (memq number number-list)))
922                       (string-to-int (elmo-filter-value condition))))
923       (if (eq (elmo-filter-type condition) 'unmatch)
924           (setq result (not result))))
925      (t
926       (elmo-set-work-buf
927        (as-binary-input-file (insert-file-contents file))
928        (set-buffer-multibyte default-enable-multibyte-characters)
929        ;; Should consider charset?
930        (decode-mime-charset-region (point-min)(point-max) elmo-mime-charset)
931        (setq result
932              (elmo-buffer-field-primitive-condition-match
933               condition number number-list)))))
934     result))
935
936 (defun elmo-file-field-condition-match (file condition number number-list)
937   (cond
938    ((vectorp condition)
939     (elmo-file-field-primitive-condition-match
940      file condition number number-list))
941    ((eq (car condition) 'and)
942     (and (elmo-file-field-condition-match
943           file (nth 1 condition) number number-list)
944          (elmo-file-field-condition-match
945           file (nth 2 condition) number number-list)))
946    ((eq (car condition) 'or)
947     (or (elmo-file-field-condition-match
948          file (nth 1 condition) number number-list)
949         (elmo-file-field-condition-match
950          file (nth 2 condition) number number-list)))))
951
952 (defmacro elmo-get-hash-val (string hashtable)
953   (static-if (fboundp 'unintern)
954       `(symbol-value (intern-soft ,string ,hashtable))
955     `(let ((sym (intern-soft ,string ,hashtable)))
956        (and (boundp sym)
957             (symbol-value sym)))))
958
959 (defmacro elmo-set-hash-val (string value hashtable)
960   `(set (intern ,string ,hashtable) ,value))
961
962 (defmacro elmo-clear-hash-val (string hashtable)
963   (static-if (fboundp 'unintern)
964       (list 'unintern string hashtable)
965     (list 'makunbound (list 'intern string hashtable))))
966
967 (defmacro elmo-unintern (string)
968   "`unintern' symbol named STRING,  When can use `unintern'.
969 Emacs 19.28 or earlier does not have `unintern'."
970   (static-if (fboundp 'unintern)
971       (list 'unintern string)))
972
973 (defun elmo-make-hash (&optional hashsize)
974   "Make a new hash table which have HASHSIZE size."
975   (make-vector
976    (if hashsize
977        (max
978         ;; Prime numbers as lengths tend to result in good
979         ;; hashing; lengths one less than a power of two are
980         ;; also good.
981         (min
982          (let ((i 1))
983            (while (< (- i 1) hashsize)
984              (setq i (* 2 i)))
985            (- i 1))
986          elmo-hash-maximum-size)
987         elmo-hash-minimum-size)
988      elmo-hash-minimum-size)
989    0))
990
991 (defsubst elmo-mime-string (string)
992   "Normalize MIME encoded STRING."
993   (and string
994        (elmo-set-work-buf
995         (set-buffer-multibyte default-enable-multibyte-characters)
996         (setq string
997               (encode-mime-charset-string
998                (eword-decode-and-unfold-unstructured-field-body
999                 string)
1000                elmo-mime-charset))
1001         (set-buffer-multibyte nil)
1002         string)))
1003
1004 (defsubst elmo-collect-field (beg end downcase-field-name)
1005   (save-excursion
1006     (save-restriction
1007       (narrow-to-region beg end)
1008       (goto-char (point-min))
1009       (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
1010             dest name body)
1011         (while (re-search-forward regexp nil t)
1012           (setq name (buffer-substring-no-properties
1013                       (match-beginning 1)(1- (match-end 1))))
1014           (if downcase-field-name
1015               (setq name (downcase name)))
1016           (setq body (buffer-substring-no-properties
1017                       (match-end 0) (std11-field-end)))
1018           (or (assoc name dest)
1019               (setq dest (cons (cons name body) dest))))
1020         dest))))
1021
1022 (defsubst elmo-collect-field-from-string (string downcase-field-name)
1023   (with-temp-buffer
1024     (insert string)
1025     (goto-char (point-min))
1026     (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
1027           dest name body)
1028       (while (re-search-forward regexp nil t)
1029         (setq name (buffer-substring-no-properties
1030                     (match-beginning 1)(1- (match-end 1))))
1031         (if downcase-field-name
1032             (setq name (downcase name)))
1033         (setq body (buffer-substring-no-properties
1034                     (match-end 0) (std11-field-end)))
1035         (or (assoc name dest)
1036             (setq dest (cons (cons name body) dest))))
1037       dest)))
1038
1039 (defun elmo-safe-filename (folder)
1040   (elmo-replace-in-string
1041    (elmo-replace-in-string
1042     (elmo-replace-in-string folder "/" " ")
1043     ":" "__")
1044    "|" "_or_"))
1045
1046 (defvar elmo-filename-replace-chars nil)
1047
1048 (defsubst elmo-replace-string-as-filename (msgid)
1049   "Replace string as filename."
1050   (setq msgid (elmo-replace-in-string msgid " " "  "))
1051   (if (null elmo-filename-replace-chars)
1052       (setq elmo-filename-replace-chars
1053             (regexp-quote (mapconcat
1054                            'car elmo-filename-replace-string-alist ""))))
1055   (while (string-match (concat "[" elmo-filename-replace-chars "]")
1056                        msgid)
1057     (setq msgid (concat
1058                  (substring msgid 0 (match-beginning 0))
1059                  (cdr (assoc
1060                        (substring msgid
1061                                   (match-beginning 0) (match-end 0))
1062                        elmo-filename-replace-string-alist))
1063                  (substring msgid (match-end 0)))))
1064   msgid)
1065
1066 (defsubst elmo-recover-string-from-filename (filename)
1067   "Recover string from FILENAME."
1068   (let (tmp result)
1069     (while (string-match " " filename)
1070       (setq tmp (substring filename
1071                            (match-beginning 0)
1072                            (+ (match-end 0) 1)))
1073       (if (string= tmp "  ")
1074           (setq tmp " ")
1075         (setq tmp (car (rassoc tmp
1076                                elmo-filename-replace-string-alist))))
1077       (setq result
1078             (concat result
1079                     (substring filename 0 (match-beginning 0))
1080                     tmp))
1081       (setq filename (substring filename (+ (match-end 0) 1))))
1082     (concat result filename)))
1083
1084 (defsubst elmo-copy-file (src dst &optional ok-if-already-exists)
1085   (condition-case err
1086       (elmo-add-name-to-file src dst ok-if-already-exists)
1087     (error (copy-file src dst ok-if-already-exists t))))
1088
1089 (defsubst elmo-buffer-exists-p (buffer)
1090   (if (bufferp buffer)
1091       (buffer-live-p buffer)
1092     (get-buffer buffer)))
1093
1094 (defsubst elmo-kill-buffer (buffer)
1095   (when (elmo-buffer-exists-p buffer)
1096     (kill-buffer buffer)))
1097
1098 (defun elmo-delete-if (pred lst)
1099   "Return new list contain items which don't satisfy PRED in LST."
1100   (let (result)
1101     (while lst
1102       (unless (funcall pred (car lst))
1103         (setq result (cons (car lst) result)))
1104       (setq lst (cdr lst)))
1105     (nreverse result)))
1106
1107 (defun elmo-list-delete (list1 list2 &optional delete-function)
1108   "Delete by side effect any occurrences equal to elements of LIST1 from LIST2.
1109 Return the modified LIST2.  Deletion is done with `delete'.
1110 Write `(setq foo (elmo-list-delete bar foo))' to be sure of changing
1111 the value of `foo'.
1112 If optional DELETE-FUNCTION is speficied, it is used as delete procedure."
1113   (setq delete-function (or delete-function 'delete))
1114   (while list1
1115     (setq list2 (funcall delete-function (car list1) list2))
1116     (setq list1 (cdr list1)))
1117   list2)
1118
1119 (defun elmo-list-member (list1 list2)
1120   "If any element of LIST1 is member of LIST2, return t."
1121   (catch 'done
1122     (while list1
1123       (if (member (car list1) list2)
1124           (throw 'done t))
1125       (setq list1 (cdr list1)))))
1126
1127 (defun elmo-count-matches (regexp beg end)
1128   (let ((count 0))
1129     (save-excursion
1130       (goto-char beg)
1131       (while (re-search-forward regexp end t)
1132         (setq count (1+ count)))
1133       count)))
1134
1135 (if (fboundp 'display-error)
1136     (defalias 'elmo-display-error 'display-error)
1137   (defun elmo-display-error (error-object stream)
1138     "A tiny function to display ERROR-OBJECT to the STREAM."
1139     (let ((first t)
1140           (errobj error-object)
1141           err-mes)
1142       (while errobj
1143         (setq err-mes (concat err-mes (format
1144                                        (if (stringp (car errobj))
1145                                            "%s"
1146                                          "%S")
1147                                        (car errobj))))
1148         (setq errobj (cdr errobj))
1149         (if errobj (setq err-mes (concat err-mes (if first ": " ", "))))
1150         (setq first nil))
1151       (princ err-mes stream))))
1152
1153 (if (fboundp 'define-error)
1154     (defalias 'elmo-define-error 'define-error)
1155   (defun elmo-define-error (error doc &optional parents)
1156     (or parents
1157         (setq parents 'error))
1158     (let ((conds (get parents 'error-conditions)))
1159       (or conds
1160           (error "Not an error symbol: %s" error))
1161       (setplist error
1162                 (list 'error-message doc
1163                       'error-conditions (cons error conds))))))
1164
1165 (cond ((fboundp 'progress-feedback-with-label)
1166        (defalias 'elmo-display-progress 'progress-feedback-with-label))
1167       ((fboundp 'lprogress-display)
1168        (defalias 'elmo-display-progress 'lprogress-display))
1169       (t
1170        (defun elmo-display-progress (label format &optional value &rest args)
1171          "Print a progress message."
1172          (if (and (null format) (null args))
1173              (message nil)
1174            (apply (function message) (concat format " %d%%")
1175                   (nconc args (list value)))))))
1176
1177 (defvar elmo-progress-counter-alist nil)
1178
1179 (defmacro elmo-progress-counter-value (counter)
1180   (` (aref (cdr (, counter)) 0)))
1181
1182 (defmacro elmo-progress-counter-all-value (counter)
1183   (` (aref (cdr (, counter)) 1)))
1184
1185 (defmacro elmo-progress-counter-format (counter)
1186   (` (aref (cdr (, counter)) 2)))
1187
1188 (defmacro elmo-progress-counter-set-value (counter value)
1189   (` (aset (cdr (, counter)) 0 (, value))))
1190
1191 (defun elmo-progress-set (label all-value &optional format)
1192   (unless (assq label elmo-progress-counter-alist)
1193     (setq elmo-progress-counter-alist
1194           (cons (cons label (vector 0 all-value (or format "")))
1195                 elmo-progress-counter-alist))))
1196
1197 (defun elmo-progress-clear (label)
1198   (let ((counter (assq label elmo-progress-counter-alist)))
1199     (when counter
1200       (elmo-display-progress label
1201                              (elmo-progress-counter-format counter)
1202                              100)
1203       (setq elmo-progress-counter-alist
1204             (delq counter elmo-progress-counter-alist)))))
1205
1206 (defun elmo-progress-notify (label &optional value op &rest args)
1207   (let ((counter (assq label elmo-progress-counter-alist)))
1208     (when counter
1209       (let* ((value (or value 1))
1210              (cur-value (elmo-progress-counter-value counter))
1211              (all-value (elmo-progress-counter-all-value counter))
1212              (new-value (if (eq op 'set) value (+ cur-value value)))
1213              (cur-rate (/ (* cur-value 100) all-value))
1214              (new-rate (/ (* new-value 100) all-value)))
1215         (elmo-progress-counter-set-value counter new-value)
1216         (unless (= cur-rate new-rate)
1217           (apply 'elmo-display-progress
1218                  label
1219                  (elmo-progress-counter-format counter)
1220                  new-rate
1221                  args))
1222         (when (>= new-rate 100)
1223           (elmo-progress-clear label))))))
1224
1225 (put 'elmo-with-progress-display 'lisp-indent-function '2)
1226 (def-edebug-spec elmo-with-progress-display
1227   (form (symbolp form &optional form) &rest form))
1228
1229 (defmacro elmo-with-progress-display (condition spec &rest body)
1230   "Evaluate BODY with progress gauge if CONDITION is non-nil.
1231 SPEC is a list as followed (LABEL MAX-VALUE [FORMAT])."
1232   (let ((label (car spec))
1233         (max-value (cadr spec))
1234         (fmt (caddr spec)))
1235     `(unwind-protect
1236          (progn
1237            (when ,condition
1238              (elmo-progress-set (quote ,label) ,max-value ,fmt))
1239            ,@body)
1240        (elmo-progress-clear (quote ,label)))))
1241
1242 (defun elmo-time-expire (before-time diff-time)
1243   (let* ((current (current-time))
1244          (rest (when (< (nth 1 current) (nth 1 before-time))
1245                  (expt 2 16)))
1246          diff)
1247     (setq diff
1248           (list (- (+ (car current) (if rest -1 0)) (car before-time))
1249                 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1250     (and (eq (car diff) 0)
1251          (< diff-time (nth 1 diff)))))
1252
1253 (if (fboundp 'std11-fetch-field)
1254     (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1255   (defalias 'elmo-field-body 'std11-field-body))
1256
1257 (defun elmo-unfold-field-body (name)
1258   (let ((value (elmo-field-body name)))
1259     (and value
1260          (std11-unfold-string value))))
1261
1262 (defun elmo-decoded-field-body (field-name &optional mode)
1263   (let ((field-body (elmo-field-body field-name)))
1264     (and field-body
1265          (elmo-set-work-buf
1266           (mime-decode-field-body field-body field-name mode)))))
1267
1268 (defun elmo-address-quote-specials (word)
1269   "Make quoted string of WORD if needed."
1270   (let ((lal (std11-lexical-analyze word)))
1271     (if (or (assq 'specials lal)
1272             (assq 'domain-literal lal))
1273         (prin1-to-string word)
1274       word)))
1275
1276 (defmacro elmo-string (string)
1277   "STRING without text property."
1278   (` (let ((obj (copy-sequence (, string))))
1279        (and obj (set-text-properties 0 (length obj) nil obj))
1280        obj)))
1281
1282 (defun elmo-flatten (list-of-list)
1283   "Flatten LIST-OF-LIST."
1284   (unless (null list-of-list)
1285     (append (if (and (car list-of-list)
1286                      (listp (car list-of-list)))
1287                 (car list-of-list)
1288               (list (car list-of-list)))
1289             (elmo-flatten (cdr list-of-list)))))
1290
1291 (defun elmo-y-or-n-p (prompt &optional auto default)
1292   "Same as `y-or-n-p'.
1293 But if optional argument AUTO is non-nil, DEFAULT is returned."
1294   (if auto
1295       default
1296     (y-or-n-p prompt)))
1297
1298 (defun elmo-string-member (string slist)
1299   (catch 'found
1300     (while slist
1301       (if (and (stringp (car slist))
1302                (string= string (car slist)))
1303           (throw 'found t))
1304       (setq slist (cdr slist)))))
1305
1306 (static-cond ((fboundp 'member-ignore-case)
1307        (defalias 'elmo-string-member-ignore-case 'member-ignore-case))
1308       ((fboundp 'compare-strings)
1309        (defun elmo-string-member-ignore-case (elt list)
1310          "Like `member', but ignores differences in case and text representation.
1311 ELT must be a string.  Upper-case and lower-case letters are treated as equal.
1312 Unibyte strings are converted to multibyte for comparison."
1313          (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
1314            (setq list (cdr list)))
1315          list))
1316       (t
1317        (defun elmo-string-member-ignore-case (elt list)
1318          "Like `member', but ignores differences in case and text representation.
1319 ELT must be a string.  Upper-case and lower-case letters are treated as equal."
1320          (let ((str (downcase elt)))
1321            (while (and list (not (string= str (downcase (car list)))))
1322              (setq list (cdr list)))
1323            list))))
1324
1325 (defun elmo-string-match-member (str list &optional case-ignore)
1326   (let ((case-fold-search case-ignore))
1327     (catch 'member
1328       (while list
1329         (if (string-match (car list) str)
1330             (throw 'member (car list)))
1331         (setq list (cdr list))))))
1332
1333 (defun elmo-string-matched-member (str list &optional case-ignore)
1334   (let ((case-fold-search case-ignore))
1335     (catch 'member
1336       (while list
1337         (if (string-match str (car list))
1338             (throw 'member (car list)))
1339         (setq list (cdr list))))))
1340
1341 (defsubst elmo-string-delete-match (string pos)
1342   (concat (substring string
1343                      0 (match-beginning pos))
1344           (substring string
1345                      (match-end pos)
1346                      (length string))))
1347
1348 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1349   (let ((case-fold-search case-ignore)
1350         a)
1351     (catch 'loop
1352       (while alist
1353         (setq a (car alist))
1354         (if (and (consp a)
1355                  (stringp (car a))
1356                  (string-match key (car a)))
1357             (throw 'loop a))
1358         (setq alist (cdr alist))))))
1359
1360 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1361   (let ((case-fold-search case-ignore)
1362         a)
1363     (catch 'loop
1364       (while alist
1365         (setq a (car alist))
1366         (if (and (consp a)
1367                  (stringp (car a))
1368                  (string-match (car a) key))
1369             (throw 'loop a))
1370         (setq alist (cdr alist))))))
1371
1372 (defun elmo-string-assoc (key alist)
1373   (let (a)
1374     (catch 'loop
1375       (while alist
1376         (setq a (car alist))
1377         (if (and (consp a)
1378                  (stringp (car a))
1379                  (string= key (car a)))
1380             (throw 'loop a))
1381         (setq alist (cdr alist))))))
1382
1383 (defun elmo-string-assoc-all (key alist)
1384   (let (matches)
1385     (while alist
1386       (if (string= key (car (car alist)))
1387           (setq matches
1388                 (cons (car alist)
1389                       matches)))
1390       (setq alist (cdr alist)))
1391     matches))
1392
1393 (defun elmo-string-rassoc (key alist)
1394   (let (a)
1395     (catch 'loop
1396       (while alist
1397         (setq a (car alist))
1398         (if (and (consp a)
1399                  (stringp (cdr a))
1400                  (string= key (cdr a)))
1401             (throw 'loop a))
1402         (setq alist (cdr alist))))))
1403
1404 (defun elmo-string-rassoc-all (key alist)
1405   (let (matches)
1406     (while alist
1407       (if (string= key (cdr (car alist)))
1408           (setq matches
1409                 (cons (car alist)
1410                       matches)))
1411       (setq alist (cdr alist)))
1412     matches))
1413
1414 (defun elmo-expand-newtext (newtext original)
1415   (let ((len (length newtext))
1416         (pos 0)
1417         c expanded beg N did-expand)
1418     (while (< pos len)
1419       (setq beg pos)
1420       (while (and (< pos len)
1421                   (not (= (aref newtext pos) ?\\)))
1422         (setq pos (1+ pos)))
1423       (unless (= beg pos)
1424         (push (substring newtext beg pos) expanded))
1425       (when (< pos len)
1426         ;; We hit a \; expand it.
1427         (setq did-expand t
1428               pos (1+ pos)
1429               c (aref newtext pos))
1430         (if (not (or (= c ?\&)
1431                      (and (>= c ?1)
1432                           (<= c ?9))))
1433             ;; \ followed by some character we don't expand.
1434             (push (char-to-string c) expanded)
1435           ;; \& or \N
1436           (if (= c ?\&)
1437               (setq N 0)
1438             (setq N (- c ?0)))
1439           (when (match-beginning N)
1440             (push (substring original (match-beginning N) (match-end N))
1441                   expanded))))
1442       (setq pos (1+ pos)))
1443     (if did-expand
1444         (apply (function concat) (nreverse expanded))
1445       newtext)))
1446
1447 ;;; Folder parser utils.
1448 (defun elmo-parse-token (string &optional seps)
1449   "Parse atom from STRING using SEPS as a string of separator char list."
1450   (let ((len (length string))
1451         (seps (and seps (string-to-char-list seps)))
1452         (i 0)
1453         (sep nil)
1454         content c in)
1455     (if (eq len 0)
1456         (cons "" "")
1457       (while (and (< i len) (or in (null sep)))
1458         (setq c (aref string i))
1459         (cond
1460          ((and in (eq c ?\\))
1461           (setq i (1+ i)
1462                 content (cons (aref string i) content)
1463                 i (1+ i)))
1464          ((eq c ?\")
1465           (setq in (not in)
1466                 i (1+ i)))
1467          (in (setq content (cons c content)
1468                    i (1+ i)))
1469          ((memq c seps)
1470           (setq sep c))
1471          (t (setq content (cons c content)
1472                   i (1+ i)))))
1473       (if in (error "Parse error in quoted"))
1474       (cons (if (null content) "" (char-list-to-string (nreverse content)))
1475             (substring string i)))))
1476
1477 (defun elmo-parse-prefixed-element (prefix string &optional seps)
1478   (if (and (not (eq (length string) 0))
1479            (eq (aref string 0) prefix))
1480       (elmo-parse-token (substring string 1) seps)
1481     (cons "" string)))
1482
1483 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1484 ;;
1485 ;; number          ::= [0-9]+
1486 ;; beg             ::= number
1487 ;; end             ::= number
1488 ;; number-range    ::= "(" beg " . " end ")"      ;; cons cell
1489 ;; number-set-elem ::= number / number-range
1490 ;; number-set      ::= "(" *number-set-elem ")"   ;; list
1491
1492 (defun elmo-number-set-member (number number-set)
1493   "Return non-nil if NUMBER is an element of NUMBER-SET.
1494 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1495   (or (memq number number-set)
1496       (let (found)
1497         (while (and number-set (not found))
1498           (if (and (consp (car number-set))
1499                    (and (<= (car (car number-set)) number)
1500                         (<= number (cdr (car number-set)))))
1501               (setq found t)
1502             (setq number-set (cdr number-set))))
1503         number-set)))
1504
1505 (defun elmo-number-set-append-list (number-set list)
1506   "Append LIST of numbers to the NUMBER-SET.
1507 NUMBER-SET is altered."
1508   (let ((appended number-set))
1509     (while list
1510       (setq appended (elmo-number-set-append appended (car list)))
1511       (setq list (cdr list)))
1512     appended))
1513
1514 (defun elmo-number-set-append (number-set number)
1515   "Append NUMBER to the NUMBER-SET.
1516 NUMBER-SET is altered."
1517   (let ((number-set-1 number-set)
1518         found elem)
1519     (while (and number-set (not found))
1520       (setq elem (car number-set))
1521       (cond
1522        ((and (consp elem)
1523              (eq (+ 1 (cdr elem)) number))
1524         (setcdr elem number)
1525         (setq found t))
1526        ((and (integerp elem)
1527              (eq (+ 1 elem) number))
1528         (setcar number-set (cons elem number))
1529         (setq found t))
1530        ((or (and (integerp elem) (eq elem number))
1531             (and (consp elem)
1532                  (<= (car elem) number)
1533                  (<= number (cdr elem))))
1534         (setq found t)))
1535       (setq number-set (cdr number-set)))
1536     (if (not found)
1537         (setq number-set-1 (nconc number-set-1 (list number))))
1538     number-set-1))
1539
1540 (defun elmo-number-set-delete-list (number-set list)
1541   "Delete LIST of numbers from the NUMBER-SET.
1542 NUMBER-SET is altered."
1543   (let ((deleted number-set))
1544     (dolist (number list)
1545       (setq deleted (elmo-number-set-delete deleted number)))
1546     deleted))
1547
1548 (defun elmo-number-set-delete (number-set number)
1549   "Delete NUMBER from the NUMBER-SET.
1550 NUMBER-SET is altered."
1551   (let* ((curr number-set)
1552          (top (cons 'dummy number-set))
1553          (prev top)
1554          elem found)
1555     (while (and curr (not found))
1556       (setq elem (car curr))
1557       (if (consp elem)
1558           (cond
1559            ((eq (car elem) number)
1560             (if (eq (cdr elem) (1+ number))
1561                 (setcar curr (cdr elem))
1562               (setcar elem (1+ number)))
1563             (setq found t))
1564            ((eq (cdr elem) number)
1565             (if (eq (car elem) (1- number))
1566                 (setcar curr (car elem))
1567               (setcdr elem (1- number)))
1568             (setq found t))
1569            ((and (> number (car elem))
1570                  (< number (cdr elem)))
1571             (setcdr
1572              prev
1573              (nconc
1574               (list
1575                ;; (beg . (1- number))
1576                (let ((new (cons (car elem) (1- number))))
1577                  (if (eq (car new) (cdr new))
1578                      (car new)
1579                    new))
1580                ;; ((1+ number) . end)
1581                (let ((new (cons (1+ number) (cdr elem))))
1582                  (if (eq (car new) (cdr new))
1583                      (car new)
1584                    new)))
1585               (cdr curr)))))
1586         (when (eq elem number)
1587           (setcdr prev (cdr curr))
1588           (setq found t)))
1589       (setq prev curr
1590             curr (cdr curr)))
1591     (cdr top)))
1592
1593 (defun elmo-make-number-list (beg end)
1594   (let (number-list i)
1595     (setq i end)
1596     (while (>= i beg)
1597       (setq number-list (cons i number-list))
1598       (setq i (1- i)))
1599     number-list))
1600
1601 (defun elmo-number-set-to-number-list (number-set)
1602   "Return a number list which corresponds to NUMBER-SET."
1603   (let ((number-list (list 'dummy))
1604         elem)
1605     (while number-set
1606       (setq elem (car number-set))
1607       (cond
1608        ((consp elem)
1609         (nconc number-list (elmo-make-number-list (car elem) (cdr elem))))
1610        ((integerp elem)
1611         (nconc number-list (list elem))))
1612       (setq number-set (cdr number-set)))
1613     (cdr number-list)))
1614
1615 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1616   "*Regexp to filter subfolders."
1617   :type 'regexp
1618   :group 'elmo)
1619
1620 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1621   (let ((root (zerop (length curdir)))
1622         (w32-get-true-file-link-count t) ; for Meadow
1623         attr dirs dir)
1624     (catch 'done
1625       (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1626         (when (and (not (string-match
1627                          elmo-list-subdirectories-ignore-regexp
1628                          file))
1629                    (car (setq attr (file-attributes
1630                                     (expand-file-name file dir)))))
1631           (when (eq one-level 'check) (throw 'done t))
1632           (let ((relpath
1633                  (concat curdir (and (not root) elmo-path-sep) file))
1634                 subdirs)
1635             (setq dirs (nconc dirs
1636                               (if (if elmo-have-link-count (< 2 (nth 1 attr))
1637                                     (setq subdirs
1638                                           (elmo-list-subdirectories-1
1639                                            basedir
1640                                            relpath
1641                                            (if one-level 'check))))
1642                                   (if one-level
1643                                       (list (list relpath))
1644                                     (cons relpath
1645                                           (or subdirs
1646                                               (elmo-list-subdirectories-1
1647                                                basedir
1648                                                relpath
1649                                                nil))))
1650                                 (list relpath)))))))
1651       dirs)))
1652
1653 (defun elmo-list-subdirectories (directory file one-level)
1654   (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1655     (if (zerop (length file))
1656         subdirs
1657       (cons file subdirs))))
1658
1659 (defun elmo-mapcar-list-of-list (func list-of-list)
1660   (mapcar
1661    (lambda (x)
1662      (cond ((listp x) (elmo-mapcar-list-of-list func x))
1663            (t (funcall func x))))
1664    list-of-list))
1665
1666 (defun elmo-parse (string regexp &optional matchn)
1667   (or matchn (setq matchn 1))
1668   (let (list)
1669     (store-match-data nil)
1670     (while (string-match regexp string (match-end 0))
1671       (setq list (cons (substring string (match-beginning matchn)
1672                                   (match-end matchn)) list)))
1673     (nreverse list)))
1674
1675 ;;; File cache.
1676 (defmacro elmo-make-file-cache (path status)
1677   "PATH is the cache file name.
1678 STATUS is one of 'section, 'entire or nil.
1679  nil means no cache exists.
1680 'section means partial section cache exists.
1681 'entire means entire cache exists.
1682 If the cache is partial file-cache, TYPE is 'partial."
1683   (` (cons (, path) (, status))))
1684
1685 (defmacro elmo-file-cache-path (file-cache)
1686   "Returns the file path of the FILE-CACHE."
1687   (` (car (, file-cache))))
1688
1689 (defmacro elmo-file-cache-status (file-cache)
1690   "Returns the status of the FILE-CACHE."
1691   (` (cdr (, file-cache))))
1692
1693 (defsubst elmo-cache-to-msgid (filename)
1694   (concat "<" (elmo-recover-string-from-filename filename) ">"))
1695
1696 (defsubst elmo-cache-get-path-subr (msgid)
1697   (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1698         (clist (string-to-char-list msgid))
1699         (sum 0))
1700     (while clist
1701       (setq sum (+ sum (car clist)))
1702       (setq clist (cdr clist)))
1703     (format "%c%c"
1704             (nth (% (/ sum 16) 2) chars)
1705             (nth (% sum 16) chars))))
1706
1707 ;;;
1708 (defun elmo-file-cache-get-path (msgid &optional section)
1709   "Get cache path for MSGID.
1710 If optional argument SECTION is specified, partial cache path is returned."
1711   (if (setq msgid (elmo-msgid-to-cache msgid))
1712       (expand-file-name
1713        (if section
1714            (format "%s/%s/%s/%s"
1715                    elmo-cache-directory
1716                    (elmo-cache-get-path-subr msgid)
1717                    msgid
1718                    section)
1719          (format "%s/%s/%s"
1720                  elmo-cache-directory
1721                  (elmo-cache-get-path-subr msgid)
1722                  msgid)))))
1723
1724 (defmacro elmo-file-cache-expand-path (path section)
1725   "Return file name for the file-cache corresponds to the section.
1726 PATH is the file-cache path.
1727 SECTION is the section string."
1728   (` (expand-file-name (or (, section) "") (, path))))
1729
1730 (defun elmo-file-cache-delete (path)
1731   "Delete a cache on PATH."
1732   (when (file-exists-p path)
1733     (if (file-directory-p path)
1734         (progn
1735           (dolist (file (directory-files path t "^[^\\.]"))
1736             (delete-file file))
1737           (delete-directory path))
1738       (delete-file path))
1739     t))
1740
1741 (defun elmo-file-cache-exists-p (msgid)
1742   "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1743   (elmo-file-cache-status (elmo-file-cache-get msgid)))
1744
1745 (defun elmo-file-cache-save (cache-path section)
1746   "Save current buffer as cache on PATH.
1747 Return t if cache is saved successfully."
1748   (condition-case nil
1749       (let ((path (if section (expand-file-name section cache-path)
1750                     cache-path))
1751             files dir)
1752         (if (and (null section)
1753                  (file-directory-p path))
1754             (progn
1755               (setq files (directory-files path t "^[^\\.]"))
1756               (while files
1757                 (delete-file (car files))
1758                 (setq files (cdr files)))
1759               (delete-directory path))
1760           (if (and section
1761                    (not (file-directory-p cache-path)))
1762               (delete-file cache-path)))
1763         (when path
1764           (setq dir (directory-file-name (file-name-directory path)))
1765           (if (not (file-exists-p dir))
1766               (elmo-make-directory dir))
1767           (write-region-as-binary (point-min) (point-max)
1768                                   path nil 'no-msg)
1769           t))
1770     ;; ignore error
1771     (error)))
1772
1773 (defun elmo-file-cache-load (cache-path section)
1774   "Load cache on PATH into the current buffer.
1775 Return t if cache is loaded successfully."
1776   (condition-case nil
1777       (let (cache-file)
1778         (when (and cache-path
1779                    (if (elmo-cache-path-section-p cache-path)
1780                        section
1781                      (null section))
1782                    (setq cache-file (elmo-file-cache-expand-path
1783                                      cache-path
1784                                      section))
1785                    (file-exists-p cache-file))
1786           (insert-file-contents-as-binary cache-file)
1787           t))
1788     ;; igore error
1789     (error)))
1790
1791 (defun elmo-cache-path-section-p (path)
1792   "Return non-nil when PATH is `section' cache path."
1793   (file-directory-p path))
1794
1795 (defun elmo-file-cache-get (msgid &optional section)
1796   "Returns the current file-cache object associated with MSGID.
1797 MSGID is the message-id of the message.
1798 If optional argument SECTION is specified, get partial file-cache object
1799 associated with SECTION."
1800   (if msgid
1801       (let ((path (elmo-cache-get-path msgid)))
1802         (if (and path (file-exists-p path))
1803             (if (elmo-cache-path-section-p path)
1804                 (if section
1805                     (if (file-exists-p (setq path (expand-file-name
1806                                                    section path)))
1807                         (cons path 'section))
1808                   ;; section is not specified but sectional.
1809                   (cons path 'section))
1810               ;; not directory.
1811               (unless section
1812                 (cons path 'entire)))
1813           ;; no cache.
1814           (cons path nil)))))
1815
1816 ;;;
1817 ;; Expire cache.
1818
1819 (defun elmo-cache-expire ()
1820   (interactive)
1821   (let* ((completion-ignore-case t)
1822          (method (completing-read (format "Expire by (%s): "
1823                                           elmo-cache-expire-default-method)
1824                                   '(("size" . "size")
1825                                     ("age" . "age"))
1826                                   nil t)))
1827     (when (string= method "")
1828       (setq method elmo-cache-expire-default-method))
1829     (funcall (intern (concat "elmo-cache-expire-by-" method)))))
1830
1831 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
1832   (let ((str (read-from-minibuffer prompt initial)))
1833     (cond
1834      ((string-match "[0-9]*\\.[0-9]+" str)
1835       (string-to-number str))
1836      ((string-match "[0-9]+" str)
1837       (string-to-number (concat str ".0")))
1838      (t (error "%s is not number" str)))))
1839
1840 (defun elmo-cache-expire-by-size (&optional kbytes)
1841   "Expire cache file by size.
1842 If KBYTES is kilo bytes (This value must be float)."
1843   (interactive)
1844   (let ((size (or kbytes
1845                   (and (interactive-p)
1846                        (elmo-read-float-value-from-minibuffer
1847                         "Enter cache disk size (Kbytes): "
1848                         (number-to-string
1849                          (if (integerp elmo-cache-expire-default-size)
1850                              (float elmo-cache-expire-default-size)
1851                            elmo-cache-expire-default-size))))
1852                   (if (integerp elmo-cache-expire-default-size)
1853                       (float elmo-cache-expire-default-size))))
1854         (count 0)
1855         (Kbytes 1024)
1856         total beginning)
1857     (message "Checking disk usage...")
1858     (setq total (/ (elmo-disk-usage
1859                     elmo-cache-directory) Kbytes))
1860     (setq beginning total)
1861     (message "Checking disk usage...done")
1862     (let ((cfl (elmo-cache-get-sorted-cache-file-list))
1863           (deleted 0)
1864           oldest
1865           cur-size cur-file)
1866       (while (and (<= size total)
1867                   (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
1868         (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
1869         (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
1870         (when (elmo-file-cache-delete cur-file)
1871           (setq count (+ count 1))
1872           (message "%d cache(s) are expired." count))
1873         (setq deleted (+ deleted cur-size))
1874         (setq total (- total cur-size)))
1875       (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
1876                count deleted beginning))))
1877
1878 (defun elmo-cache-make-file-entity (filename path)
1879   (cons filename (elmo-get-last-accessed-time filename path)))
1880
1881 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
1882   (let ((cfl cache-file-list)
1883         flist firsts oldest-entity wonlist)
1884     (while cfl
1885       (setq flist (cdr (car cfl)))
1886       (setq firsts (append firsts (list
1887                                    (cons (car (car cfl))
1888                                          (car flist)))))
1889       (setq cfl (cdr cfl)))
1890 ;;; (prin1 firsts)
1891     (while firsts
1892       (if (and (not oldest-entity)
1893                (cdr (cdr (car firsts))))
1894           (setq oldest-entity (car firsts)))
1895       (if (and (cdr (cdr (car firsts)))
1896                (cdr (cdr oldest-entity))
1897                (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
1898           (setq oldest-entity (car firsts)))
1899       (setq firsts (cdr firsts)))
1900     (setq wonlist (assoc (car oldest-entity) cache-file-list))
1901     (and wonlist
1902          (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
1903     oldest-entity))
1904
1905 (defun elmo-cache-get-sorted-cache-file-list ()
1906   (let ((dirs (directory-files
1907                elmo-cache-directory
1908                t "^[^\\.]"))
1909         (i 0) num
1910         elist
1911         ret-val)
1912     (setq num (length dirs))
1913     (message "Collecting cache info...")
1914     (while dirs
1915       (setq elist (mapcar (lambda (x)
1916                             (elmo-cache-make-file-entity x (car dirs)))
1917                           (directory-files (car dirs) nil "^[^\\.]")))
1918       (setq ret-val (append ret-val
1919                             (list (cons
1920                                    (car dirs)
1921                                    (sort
1922                                     elist
1923                                     (lambda (x y)
1924                                       (< (cdr x)
1925                                          (cdr y))))))))
1926       (when (> num elmo-display-progress-threshold)
1927         (setq i (+ i 1))
1928         (elmo-display-progress
1929          'elmo-cache-get-sorted-cache-file-list "Collecting cache info..."
1930          (/ (* i 100) num)))
1931       (setq dirs (cdr dirs)))
1932     (message "Collecting cache info...done")
1933     ret-val))
1934
1935 (defun elmo-cache-expire-by-age (&optional days)
1936   (let ((age (or (and days (int-to-string days))
1937                  (and (interactive-p)
1938                       (read-from-minibuffer
1939                        (format "Enter days (%s): "
1940                                elmo-cache-expire-default-age)))
1941                  (int-to-string elmo-cache-expire-default-age)))
1942         (dirs (directory-files
1943                elmo-cache-directory
1944                t "^[^\\.]"))
1945         (count 0)
1946         curtime)
1947     (if (string= age "")
1948         (setq age elmo-cache-expire-default-age)
1949       (setq age (string-to-int age)))
1950     (setq curtime (current-time))
1951     (setq curtime (+ (* (nth 0 curtime)
1952                         (float 65536)) (nth 1 curtime)))
1953     (while dirs
1954       (let ((files (directory-files (car dirs) t "^[^\\.]"))
1955             (limit-age (* age 86400)))
1956         (while files
1957           (when (> (- curtime (elmo-get-last-accessed-time (car files)))
1958                    limit-age)
1959             (when (elmo-file-cache-delete (car files))
1960               (setq count (+ 1 count))
1961               (message "%d cache file(s) are expired." count)))
1962           (setq files (cdr files))))
1963       (setq dirs (cdr dirs)))))
1964
1965 ;;;
1966 ;; msgid to path.
1967 (defun elmo-msgid-to-cache (msgid)
1968   (save-match-data
1969     (when (and msgid
1970                (string-match "<\\(.+\\)>$" msgid))
1971       (elmo-replace-string-as-filename (elmo-match-string 1 msgid)))))
1972
1973 (defun elmo-cache-get-path (msgid &optional folder number)
1974   "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
1975   (if (setq msgid (elmo-msgid-to-cache msgid))
1976       (expand-file-name
1977        (expand-file-name
1978         (if folder
1979             (format "%s/%s/%s@%s"
1980                     (elmo-cache-get-path-subr msgid)
1981                     msgid
1982                     (or number "")
1983                     (elmo-safe-filename folder))
1984           (format "%s/%s"
1985                   (elmo-cache-get-path-subr msgid)
1986                   msgid))
1987         elmo-cache-directory))))
1988
1989 ;;;
1990 ;; Warnings.
1991
1992 (static-if (fboundp 'display-warning)
1993     (defmacro elmo-warning (&rest args)
1994       "Display a warning with `elmo' group."
1995       `(display-warning 'elmo (format ,@args)))
1996   (defconst elmo-warning-buffer-name "*elmo warning*")
1997   (defun elmo-warning (&rest args)
1998     "Display a warning. ARGS are passed to `format'."
1999     (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
2000       (goto-char (point-max))
2001       (funcall 'insert (apply 'format (append args '("\n"))))
2002       (ignore-errors (recenter 1))
2003       (display-buffer elmo-warning-buffer-name))))
2004
2005 (defvar elmo-obsolete-variable-alist nil)
2006
2007 (defcustom elmo-obsolete-variable-show-warnings t
2008   "Show warning window if obsolete variable is treated."
2009   :type 'boolean
2010   :group 'elmo)
2011
2012 (defun elmo-define-obsolete-variable (obsolete var)
2013   "Define obsolete variable.
2014 OBSOLETE is a symbol for obsolete variable.
2015 VAR is a symbol for new variable.
2016 Definition is stored in `elmo-obsolete-variable-alist'."
2017   (let ((pair (assq var elmo-obsolete-variable-alist)))
2018     (if pair
2019         (setcdr pair obsolete)
2020       (setq elmo-obsolete-variable-alist
2021             (cons (cons var obsolete)
2022                   elmo-obsolete-variable-alist)))))
2023
2024 (defun elmo-resque-obsolete-variable (obsolete var)
2025   "Resque obsolete variable OBSOLETE as VAR.
2026 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
2027   (when (boundp obsolete)
2028     (static-if (and (fboundp 'defvaralias)
2029                     (subrp (symbol-function 'defvaralias)))
2030         (defvaralias var obsolete)
2031       (set var (symbol-value obsolete)))
2032     (if elmo-obsolete-variable-show-warnings
2033         (elmo-warning "%s is obsolete. Use %s instead."
2034                       (symbol-name obsolete)
2035                       (symbol-name var)))))
2036
2037 (defun elmo-resque-obsolete-variables (&optional alist)
2038   "Resque obsolete variables in ALIST.
2039 ALIST is a list of cons cell of
2040 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
2041 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
2042   (dolist (pair elmo-obsolete-variable-alist)
2043     (elmo-resque-obsolete-variable (cdr pair)
2044                                    (car pair))))
2045
2046 (defsubst elmo-msgdb-get-last-message-id (string)
2047   (if string
2048       (save-match-data
2049         (let (beg)
2050           (elmo-set-work-buf
2051            (insert string)
2052            (goto-char (point-max))
2053            (when (search-backward "<" nil t)
2054              (setq beg (point))
2055              (if (search-forward ">" nil t)
2056                  (elmo-replace-in-string
2057                   (buffer-substring beg (point)) "\n[ \t]*" ""))))))))
2058
2059 (defun elmo-msgdb-get-message-id-from-buffer ()
2060   (let ((msgid (elmo-field-body "message-id")))
2061     (if msgid
2062         (if (string-match "<\\(.+\\)>$" msgid)
2063             msgid
2064           (concat "<" msgid ">"))       ; Invaild message-id.
2065       ;; no message-id, so put dummy msgid.
2066       (concat "<"
2067               (if (elmo-unfold-field-body "date")
2068                   (timezone-make-date-sortable (elmo-unfold-field-body "date"))
2069                 (md5 (string-as-unibyte (buffer-string))))
2070               (nth 1 (eword-extract-address-components
2071                       (or (elmo-field-body "from") "nobody"))) ">"))))
2072
2073 (defsubst elmo-msgdb-insert-file-header (file)
2074   "Insert the header of the article."
2075   (let ((beg 0)
2076         insert-file-contents-pre-hook   ; To avoid autoconv-xmas...
2077         insert-file-contents-post-hook
2078         format-alist)
2079     (when (file-exists-p file)
2080       ;; Read until header separator is found.
2081       (while (and (eq elmo-msgdb-file-header-chop-length
2082                       (nth 1
2083                            (insert-file-contents-as-binary
2084                             file nil beg
2085                             (incf beg elmo-msgdb-file-header-chop-length))))
2086                   (prog1 (not (search-forward "\n\n" nil t))
2087                     (goto-char (point-max))))))))
2088
2089 ;;
2090 ;; overview handling
2091 ;;
2092 (defun elmo-multiple-field-body (name &optional boundary)
2093   (save-excursion
2094     (save-restriction
2095       (std11-narrow-to-header boundary)
2096       (goto-char (point-min))
2097       (let ((case-fold-search t)
2098             (field-body nil))
2099         (while (re-search-forward (concat "^" name ":[ \t]*") nil t)
2100           (setq field-body
2101                 (nconc field-body
2102                        (list (buffer-substring-no-properties
2103                               (match-end 0) (std11-field-end))))))
2104         field-body))))
2105
2106 ;;; Queue.
2107 (defvar elmo-dop-queue-filename "queue"
2108   "*Disconnected operation queue is saved in this file.")
2109
2110 (defun elmo-dop-queue-load ()
2111   (setq elmo-dop-queue
2112         (elmo-object-load
2113          (expand-file-name elmo-dop-queue-filename
2114                            elmo-msgdb-directory))))
2115
2116 (defun elmo-dop-queue-save ()
2117   (elmo-object-save
2118    (expand-file-name elmo-dop-queue-filename
2119                      elmo-msgdb-directory)
2120    elmo-dop-queue))
2121
2122 (if (and (fboundp 'regexp-opt)
2123          (not (featurep 'xemacs)))
2124     (defalias 'elmo-regexp-opt 'regexp-opt)
2125   (defun elmo-regexp-opt (strings &optional paren)
2126     "Return a regexp to match a string in STRINGS.
2127 Each string should be unique in STRINGS and should not contain any regexps,
2128 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
2129 is enclosed by at least one regexp grouping construct."
2130     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
2131       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
2132               close-paren))))
2133
2134 (require 'product)
2135 (product-provide (provide 'elmo-util) (require 'elmo-version))
2136
2137 ;;; elmo-util.el ends here