* elmo-multi.el (elmo-folder-search): Use nil for 1st argument of
[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
42 (defmacro elmo-set-buffer-multibyte (flag)
43   "Set the multibyte flag of the current buffer to FLAG."
44   (cond ((boundp 'MULE)
45          (list 'setq 'mc-flag flag))
46         ((featurep 'xemacs)
47          flag)
48         ((and (boundp 'emacs-major-version) (>= emacs-major-version 20))
49          (list 'set-buffer-multibyte flag))
50         (t
51          flag)))
52
53 (defvar elmo-work-buf-name " *elmo work*")
54 (defvar elmo-temp-buf-name " *elmo temp*")
55
56 (or (boundp 'default-enable-multibyte-characters)
57     (defvar default-enable-multibyte-characters (featurep 'mule)
58       "The mock variable except for Emacs 20."))
59
60 (defun elmo-base64-encode-string (string &optional no-line-break))
61 (defun elmo-base64-decode-string (string))
62
63 ;; base64 encoding/decoding
64 (require 'mel)
65 (fset 'elmo-base64-encode-string
66       (mel-find-function 'mime-encode-string "base64"))
67 (fset 'elmo-base64-decode-string
68       (mel-find-function 'mime-decode-string "base64"))
69
70 ;; Any Emacsen may have add-name-to-file(), because loadup.el requires it. :-p
71 ;; Check make-symbolic-link() instead.  -- 981002 by Fuji
72 (if (fboundp 'make-symbolic-link)  ;; xxx
73     (defalias 'elmo-add-name-to-file 'add-name-to-file)
74   (defun elmo-add-name-to-file
75     (filename newname &optional ok-if-already-exists)
76     (copy-file filename newname ok-if-already-exists t)))
77
78 (defmacro elmo-set-work-buf (&rest body)
79   "Execute BODY on work buffer.  Work buffer remains."
80   (` (save-excursion
81        (set-buffer (get-buffer-create elmo-work-buf-name))
82        (elmo-set-buffer-multibyte default-enable-multibyte-characters)
83        (erase-buffer)
84        (,@ body))))
85
86 (defmacro elmo-bind-directory (dir &rest body)
87   "Set current directory DIR and execute BODY."
88   (` (let ((default-directory (file-name-as-directory (, dir))))
89        (,@ body))))
90
91 (defun elmo-object-load (filename &optional mime-charset no-err)
92   "Load OBJECT from the file specified by FILENAME.
93 File content is decoded with MIME-CHARSET."
94     (if (not (file-readable-p filename))
95         nil
96       (elmo-set-work-buf
97        (as-binary-input-file
98         (insert-file-contents filename))
99        (when mime-charset
100          (elmo-set-buffer-multibyte default-enable-multibyte-characters)
101          (decode-mime-charset-region (point-min) (point-max) mime-charset))
102        (condition-case nil
103            (read (current-buffer))
104          (error (unless no-err
105                   (message "Warning: Loading object from %s failed."
106                            filename)
107                   (elmo-object-save filename nil))
108                 nil)))))
109
110 (defsubst elmo-save-buffer (filename &optional mime-charset)
111   "Save current buffer to the file specified by FILENAME.
112 Directory of the file is created if it doesn't exist.
113 File content is encoded with MIME-CHARSET."
114   (let ((dir (directory-file-name (file-name-directory filename))))
115     (if (file-directory-p dir)
116         () ; ok.
117       (unless (file-exists-p dir)
118         (elmo-make-directory dir)))
119     (if (file-writable-p filename)
120         (progn
121           (when mime-charset
122 ;;;         (elmo-set-buffer-multibyte default-enable-multibyte-characters)
123             (encode-mime-charset-region (point-min) (point-max) mime-charset))
124           (as-binary-output-file
125            (write-region (point-min) (point-max) filename nil 'no-msg)))
126       (message "%s is not writable." filename))))
127
128 (defun elmo-object-save (filename object &optional mime-charset)
129   "Save OBJECT to the file specified by FILENAME.
130 Directory of the file is created if it doesn't exist.
131 File content is encoded with MIME-CHARSET."
132   (elmo-set-work-buf
133    (let (print-length print-level)
134      (prin1 object (current-buffer)))
135 ;;;(princ "\n" (current-buffer))
136    (elmo-save-buffer filename mime-charset)))
137
138 ;;; Search Condition
139
140 (defconst elmo-condition-atom-regexp "[^/ \")|&]*")
141
142 (defun elmo-read-search-condition (default)
143   "Read search condition string interactively."
144   (elmo-read-search-condition-internal "Search by" default))
145
146 (defun elmo-read-search-condition-internal (prompt default)
147   (let* ((completion-ignore-case t)
148          (field (completing-read
149                  (format "%s (%s): " prompt default)
150                  (mapcar 'list
151                          (append '("AND" "OR"
152                                    "Last" "First" "Flag"
153                                    "From" "Subject" "To" "Cc" "Body"
154                                    "Since" "Before" "ToCc"
155                                    "!From" "!Subject" "!To" "!Cc" "!Body"
156                                    "!Since" "!Before" "!ToCc")
157                                  elmo-msgdb-extra-fields))))
158          value)
159     (setq field (if (string= field "")
160                     (setq field default)
161                   field))
162     (cond
163      ((or (string= field "AND") (string= field "OR"))
164       (concat "("
165               (elmo-read-search-condition-internal
166                (concat field "(1) Search by") default)
167               (if (string= field "AND") "&" "|")
168               (elmo-read-search-condition-internal
169                (concat field "(2) Search by") default)
170               ")"))
171      ((string-match "Since\\|Before" field)
172       (let ((default (format-time-string "%Y-%m-%d")))
173         (setq value (completing-read
174                      (format "Value for '%s' [%s]: " field default)
175                      (mapcar (function
176                               (lambda (x)
177                                 (list (format "%s" (car x)))))
178                              elmo-date-descriptions)))
179         (concat (downcase field) ":"
180                 (if (equal value "") default value))))
181      ((string= field "Flag")
182       (setq value (completing-read
183                    (format "Value for '%s': " field)
184                    (mapcar 'list
185                            '("unread" "important" "answered" "digest" "any"))))
186       (unless (string-match (concat "^" elmo-condition-atom-regexp "$")
187                             value)
188         (setq value (prin1-to-string value)))
189       (concat (downcase field) ":" value))
190      (t
191       (setq value (read-from-minibuffer (format "Value for '%s': " field)))
192       (unless (string-match (concat "^" elmo-condition-atom-regexp "$")
193                             value)
194         (setq value (prin1-to-string value)))
195       (concat (downcase field) ":" value)))))
196
197 (defsubst elmo-condition-parse-error ()
198   (error "Syntax error in '%s'" (buffer-string)))
199
200 (defun elmo-parse-search-condition (condition)
201   "Parse CONDITION.
202 Return value is a cons cell of (STRUCTURE . REST)"
203   (with-temp-buffer
204     (insert condition)
205     (goto-char (point-min))
206     (cons (elmo-condition-parse) (buffer-substring (point) (point-max)))))
207
208 ;; condition    ::= or-expr
209 (defun elmo-condition-parse ()
210   (or (elmo-condition-parse-or-expr)
211       (elmo-condition-parse-error)))
212
213 ;; or-expr      ::= and-expr /
214 ;;                  and-expr "|" or-expr
215 (defun elmo-condition-parse-or-expr ()
216   (let ((left (elmo-condition-parse-and-expr)))
217     (if (looking-at "| *")
218         (progn
219           (goto-char (match-end 0))
220           (list 'or left (elmo-condition-parse-or-expr)))
221       left)))
222
223 ;; and-expr     ::= primitive /
224 ;;                  primitive "&" and-expr
225 (defun elmo-condition-parse-and-expr ()
226   (let ((left (elmo-condition-parse-primitive)))
227     (if (looking-at "& *")
228         (progn
229           (goto-char (match-end 0))
230           (list 'and left (elmo-condition-parse-and-expr)))
231       left)))
232
233 ;; primitive    ::= "(" expr ")" /
234 ;;                  ["!"] search-key SPACE* ":" SPACE* search-value
235 (defun elmo-condition-parse-primitive ()
236   (cond
237    ((looking-at "( *")
238     (goto-char (match-end 0))
239     (prog1 (elmo-condition-parse)
240       (unless (looking-at ") *")
241         (elmo-condition-parse-error))
242       (goto-char (match-end 0))))
243 ;; search-key   ::= [A-Za-z-]+
244 ;;                 ;; "since" / "before" / "last" / "first" /
245 ;;                 ;; "body" / "mark" / field-name
246    ((looking-at "\\(!\\)? *\\([A-Za-z-]+\\) *: *")
247     (goto-char (match-end 0))
248     (let ((search-key (vector
249                        (if (match-beginning 1) 'unmatch 'match)
250                        (elmo-match-buffer 2)
251                        (elmo-condition-parse-search-value))))
252       ;; syntax sugar.
253       (if (string= (aref search-key 1) "tocc")
254           (if (eq (aref search-key 0) 'match)
255               (list 'or
256                     (vector 'match "to" (aref search-key 2))
257                     (vector 'match "cc" (aref search-key 2)))
258             (list 'and
259                   (vector 'unmatch "to" (aref search-key 2))
260                   (vector 'unmatch "cc" (aref search-key 2))))
261         search-key)))))
262
263 ;; search-value ::= quoted / time / number / atom
264 ;; quoted       ::= <elisp string expression>
265 ;; time         ::= "yesterday" / "lastweek" / "lastmonth" / "lastyear" /
266 ;;                   number SPACE* "daysago" /
267 ;;                   number "-" month "-" number  ; ex. 10-May-2000
268 ;;                   number "-" number "-" number  ; ex. 2000-05-10
269 ;; number       ::= [0-9]+
270 ;; month        ::= "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
271 ;;                  "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
272 ;; atom         ::= ATOM_CHARS*
273 ;; SPACE        ::= <ascii space character, 0x20>
274 ;; ATOM_CHARS   ::= <any character except specials>
275 ;; specials     ::= SPACE / <"> / </> / <)> / <|> / <&>
276 ;;                  ;; These characters should be quoted.
277 (defun elmo-condition-parse-search-value ()
278   (cond
279    ((looking-at "\"")
280     (read (current-buffer)))
281    ((or (looking-at "yesterday") (looking-at "lastweek")
282         (looking-at "lastmonth") (looking-at "lastyear")
283         (looking-at "[0-9]+ *daysago")
284         (looking-at "[0-9]+-[A-Za-z]+-[0-9]+")
285         (looking-at "[0-9]+-[0-9]+-[0-9]+")
286         (looking-at "[0-9]+")
287         (looking-at elmo-condition-atom-regexp))
288     (prog1 (elmo-match-buffer 0)
289       (goto-char (match-end 0))))
290    (t (error "Syntax error '%s'" (buffer-string)))))
291
292 ;;;
293 (defsubst elmo-buffer-replace (regexp &optional newtext)
294   (goto-char (point-min))
295   (while (re-search-forward regexp nil t)
296     (replace-match (or newtext ""))))
297
298 (defsubst elmo-delete-char (char string &optional unibyte)
299   (save-match-data
300     (elmo-set-work-buf
301      (let ((coding-system-for-read 'no-conversion)
302            (coding-system-for-write 'no-conversion))
303        (if unibyte (elmo-set-buffer-multibyte nil))
304        (insert string)
305        (goto-char (point-min))
306        (while (search-forward (char-to-string char) nil t)
307          (replace-match ""))
308        (buffer-string)))))
309
310 (defsubst elmo-delete-cr-buffer ()
311   "Delete CR from buffer."
312   (save-excursion
313     (goto-char (point-min))
314     (while (search-forward "\r\n" nil t)
315       (replace-match "\n")) ))
316
317 (defsubst elmo-delete-cr-get-content-type ()
318   (save-excursion
319     (goto-char (point-min))
320     (while (search-forward "\r\n" nil t)
321       (replace-match "\n"))
322     (goto-char (point-min))
323     (or (std11-field-body "content-type")
324         t)))
325
326 (defun elmo-delete-cr (string)
327   (save-match-data
328     (elmo-set-work-buf
329      (insert string)
330      (goto-char (point-min))
331      (while (search-forward "\r\n" nil t)
332        (replace-match "\n"))
333      (buffer-string))))
334
335 (defun elmo-uniq-list (lst)
336   "Distractively uniqfy elements of LST."
337   (let ((tmp lst))
338     (while tmp (setq tmp
339                      (setcdr tmp
340                              (and (cdr tmp)
341                                   (delete (car tmp)
342                                           (cdr tmp)))))))
343   lst)
344
345 (defun elmo-list-insert (list element after)
346   (let* ((match (memq after list))
347          (rest (and match (cdr (memq after list)))))
348     (if match
349         (progn
350           (setcdr match (list element))
351           (nconc list rest))
352       (nconc list (list element)))))
353
354 (defun elmo-string-partial-p (string)
355   (and (stringp string) (string-match "message/partial" string)))
356
357 (defun elmo-get-file-string (filename &optional remove-final-newline)
358   (elmo-set-work-buf
359    (let (insert-file-contents-pre-hook   ; To avoid autoconv-xmas...
360          insert-file-contents-post-hook)
361      (when (file-exists-p filename)
362        (if filename
363            (as-binary-input-file (insert-file-contents filename)))
364        (when (and remove-final-newline
365                   (> (buffer-size) 0)
366                   (= (char-after (1- (point-max))) ?\n))
367          (goto-char (point-max))
368          (delete-backward-char 1))
369        (buffer-string)))))
370
371 (defun elmo-save-string (string filename)
372   (if string
373       (elmo-set-work-buf
374        (as-binary-output-file
375         (insert string)
376         (write-region (point-min) (point-max)
377                       filename nil 'no-msg))
378        )))
379
380 (defun elmo-max-of-list (nlist)
381   (let ((l nlist)
382         (max-num 0))
383     (while l
384       (if (< max-num (car l))
385           (setq max-num (car l)))
386       (setq l (cdr l)))
387     max-num))
388
389 (defun elmo-concat-path (path filename)
390   (if (not (string= path ""))
391       (if (string= elmo-path-sep (substring path (- (length path) 1)))
392           (concat path filename)
393         (concat path elmo-path-sep filename))
394     filename))
395
396 (defvar elmo-passwd-alist nil)
397
398 (defun elmo-passwd-alist-load ()
399   (save-excursion
400     (let ((filename (expand-file-name elmo-passwd-alist-file-name
401                                       elmo-msgdb-directory))
402           (tmp-buffer (get-buffer-create " *elmo-passwd-alist-tmp*"))
403           insert-file-contents-pre-hook ; To avoid autoconv-xmas...
404           insert-file-contents-post-hook
405           ret-val)
406       (if (not (file-readable-p filename))
407           ()
408         (set-buffer tmp-buffer)
409         (insert-file-contents filename)
410         (setq ret-val
411               (condition-case nil
412                   (read (current-buffer))
413                 (error nil nil))))
414       (kill-buffer tmp-buffer)
415       ret-val)))
416
417 (defun elmo-passwd-alist-clear ()
418   "Clear password cache."
419   (interactive)
420   (setq elmo-passwd-alist nil))
421
422 (defun elmo-passwd-alist-save ()
423   "Save password into file."
424   (interactive)
425   (save-excursion
426     (let ((filename (expand-file-name elmo-passwd-alist-file-name
427                                       elmo-msgdb-directory))
428           (tmp-buffer (get-buffer-create " *elmo-passwd-alist-tmp*"))
429           print-length print-level)
430       (set-buffer tmp-buffer)
431       (erase-buffer)
432       (prin1 elmo-passwd-alist tmp-buffer)
433       (princ "\n" tmp-buffer)
434 ;;;   (if (and (file-exists-p filename)
435 ;;;            (not (equal 384 (file-modes filename))))
436 ;;;       (error "%s is not safe.chmod 600 %s!" filename filename))
437       (if (file-writable-p filename)
438           (progn
439             (write-region (point-min) (point-max)
440                           filename nil 'no-msg)
441             (set-file-modes filename 384))
442         (message "%s is not writable." filename))
443       (kill-buffer tmp-buffer))))
444
445 (defun elmo-get-passwd (key)
446   "Get password from password pool."
447   (let (pair pass)
448     (if (not elmo-passwd-alist)
449         (setq elmo-passwd-alist (elmo-passwd-alist-load)))
450     (setq pair (assoc key elmo-passwd-alist))
451     (if pair
452         (elmo-base64-decode-string (cdr pair))
453       (setq pass (elmo-read-passwd (format "Password for %s: "
454                                            key) t))
455       (setq elmo-passwd-alist
456             (append elmo-passwd-alist
457                     (list (cons key
458                                 (elmo-base64-encode-string pass)))))
459       (if elmo-passwd-life-time
460           (run-with-timer elmo-passwd-life-time nil
461                           (` (lambda () (elmo-remove-passwd (, key))))))
462       pass)))
463
464 (defun elmo-remove-passwd (key)
465   "Remove password from password pool (for failure)."
466   (let (pass-cons)
467     (if (setq pass-cons (assoc key elmo-passwd-alist))
468         (progn
469           (unwind-protect
470               (fillarray (cdr pass-cons) 0))
471           (setq elmo-passwd-alist
472                 (delete pass-cons elmo-passwd-alist))))))
473
474 (defmacro elmo-read-char-exclusive ()
475   (cond ((featurep 'xemacs)
476          '(let ((table (quote ((backspace . ?\C-h) (delete . ?\C-?)
477                                (left . ?\C-h))))
478                 event key)
479             (while (not
480                     (and
481                      (key-press-event-p (setq event (next-command-event)))
482                      (setq key (or (event-to-character event)
483                                    (cdr (assq (event-key event) table)))))))
484             key))
485         ((fboundp 'read-char-exclusive)
486          '(read-char-exclusive))
487         (t
488          '(read-char))))
489
490 (defun elmo-read-passwd (prompt &optional stars)
491   "Read a single line of text from user without echoing, and return it."
492   (let ((ans "")
493         (c 0)
494         (echo-keystrokes 0)
495         (cursor-in-echo-area t)
496         (log-message-max-size 0)
497         message-log-max done msg truncate)
498     (while (not done)
499       (if (or (not stars) (string= "" ans))
500           (setq msg prompt)
501         (setq msg (concat prompt (make-string (length ans) ?.)))
502         (setq truncate
503               (1+ (- (length msg) (window-width (minibuffer-window)))))
504         (and (> truncate 0)
505              (setq msg (concat "$" (substring msg (1+ truncate))))))
506       (message "%s" msg)
507       (setq c (elmo-read-char-exclusive))
508       (cond ((= c ?\C-g)
509              (setq quit-flag t
510                    done t))
511             ((or (= c ?\r) (= c ?\n) (= c ?\e))
512              (setq done t))
513             ((= c ?\C-u)
514              (setq ans ""))
515             ((and (/= c ?\b) (/= c ?\177))
516              (setq ans (concat ans (char-to-string c))))
517             ((> (length ans) 0)
518              (setq ans (substring ans 0 -1)))))
519     (if quit-flag
520         (prog1
521             (setq quit-flag nil)
522           (message "Quit")
523           (beep t))
524       (message "")
525       ans)))
526
527 (defun elmo-string-to-list (string)
528   (elmo-set-work-buf
529    (insert string)
530    (goto-char (point-min))
531    (insert "(")
532    (goto-char (point-max))
533    (insert ")")
534    (goto-char (point-min))
535    (read (current-buffer))))
536
537 (defun elmo-list-to-string (list)
538   (let ((tlist list)
539         str)
540     (if (listp tlist)
541         (progn
542           (setq str "(")
543           (while (car tlist)
544             (setq str
545                   (concat str
546                           (if (symbolp (car tlist))
547                               (symbol-name (car tlist))
548                             (car tlist))))
549             (if (cdr tlist)
550                 (setq str
551                       (concat str " ")))
552             (setq tlist (cdr tlist)))
553           (setq str
554                 (concat str ")")))
555       (setq str
556             (if (symbolp tlist)
557                 (symbol-name tlist)
558               tlist)))
559     str))
560
561
562 (defun elmo-plug-on-by-servers (alist &optional servers)
563   (let ((server-list (or servers elmo-plug-on-servers)))
564     (catch 'plugged
565       (while server-list
566         (if (elmo-plugged-p (car server-list))
567             (throw 'plugged t))
568         (setq server-list (cdr server-list))))))
569
570 (defun elmo-plug-on-by-exclude-servers (alist &optional servers)
571   (let ((server-list (or servers elmo-plug-on-exclude-servers))
572         server other-servers)
573     (while alist
574       (when (and (not (member (setq server (caaar alist)) server-list))
575                  (not (member server other-servers)))
576         (push server other-servers))
577       (setq alist (cdr alist)))
578     (elmo-plug-on-by-servers alist other-servers)))
579
580 (defun elmo-plugged-p (&optional server port stream-type alist label-exp)
581   (let ((alist (or alist elmo-plugged-alist))
582         plugged-info)
583     (cond ((and (not port) (not server))
584            (cond ((eq elmo-plugged-condition 'one)
585                   (if alist
586                       (catch 'plugged
587                         (while alist
588                           (if (nth 2 (car alist))
589                               (throw 'plugged t))
590                           (setq alist (cdr alist))))
591                     elmo-plugged))
592                  ((eq elmo-plugged-condition 'all)
593                   (if alist
594                       (catch 'plugged
595                         (while alist
596                           (if (not (nth 2 (car alist)))
597                               (throw 'plugged nil))
598                           (setq alist (cdr alist)))
599                         t)
600                     elmo-plugged))
601                  ((functionp elmo-plugged-condition)
602                   (funcall elmo-plugged-condition alist))
603                  (t ;; independent
604                   elmo-plugged)))
605           ((not port) ;; server
606            (catch 'plugged
607              (while alist
608                (when (string= server (caaar alist))
609                  (if (nth 2 (car alist))
610                      (throw 'plugged t)))
611                (setq alist (cdr alist)))))
612           (t
613            (setq plugged-info (assoc (list server port stream-type) alist))
614            (if (not plugged-info)
615                ;; add elmo-plugged-alist automatically
616                (progn
617                  (elmo-set-plugged elmo-plugged server port stream-type
618                                    nil nil nil label-exp)
619                  elmo-plugged)
620              (if (and elmo-auto-change-plugged
621                       (> elmo-auto-change-plugged 0)
622                       (nth 3 plugged-info)  ;; time
623                       (elmo-time-expire (nth 3 plugged-info)
624                                         elmo-auto-change-plugged))
625                  t
626                (nth 2 plugged-info)))))))
627
628 (defun elmo-set-plugged (plugged &optional server port stream-type time
629                                  alist label-exp add)
630   (let ((alist (or alist elmo-plugged-alist))
631         label plugged-info)
632     (cond ((and (not port) (not server))
633            (setq elmo-plugged plugged)
634            ;; set plugged all element of elmo-plugged-alist.
635            (while alist
636              (setcdr (cdar alist) (list plugged time))
637              (setq alist (cdr alist))))
638           ((not port)
639            ;; set plugged all port of server
640            (while alist
641              (when (string= server (caaar alist))
642                (setcdr (cdar alist) (list plugged time)))
643              (setq alist (cdr alist))))
644           (t
645            ;; set plugged one port of server
646            (setq plugged-info (assoc (list server port stream-type) alist))
647            (setq label (if label-exp
648                            (eval label-exp)
649                          (nth 1 plugged-info)))
650            (if plugged-info
651                ;; if add is non-nil, don't reset plug state.
652                (unless add
653                  (setcdr plugged-info (list label plugged time)))
654              (setq alist
655                    (setq elmo-plugged-alist
656                          (nconc
657                           elmo-plugged-alist
658                           (list
659                            (list (list server port stream-type)
660                                  label plugged time))))))))
661     alist))
662
663 (defun elmo-delete-plugged (&optional server port alist)
664   (let* ((alist (or alist elmo-plugged-alist))
665          (alist2 alist))
666     (cond ((and (not port) (not server))
667            (setq alist nil))
668           ((not port)
669            ;; delete plugged all port of server
670            (while alist2
671              (when (string= server (caaar alist2))
672                (setq alist (delete (car alist2) alist)))
673              (setq alist2 (cdr alist2))))
674           (t
675            ;; delete plugged one port of server
676            (setq alist
677                  (delete (assoc (cons server port) alist) alist))))
678     alist))
679
680 (defun elmo-disk-usage (path)
681   "Get disk usage (bytes) in PATH."
682   (let ((file-attr
683          (condition-case () (file-attributes path) (error nil))))
684     (if file-attr
685         (if (nth 0 file-attr) ; directory
686             (let ((files (condition-case ()
687                              (directory-files path t "^[^\\.]")
688                            (error nil)))
689                   (result 0.0))
690               ;; (result (nth 7 file-attr))) ... directory size
691               (while files
692                 (setq result (+ result (or (elmo-disk-usage (car files)) 0)))
693                 (setq files (cdr files)))
694               result)
695           (float (nth 7 file-attr)))
696       0)))
697
698 (defun elmo-get-last-accessed-time (path &optional dir)
699   "Return the last accessed time of PATH."
700   (let ((last-accessed (nth 4 (file-attributes (or (and dir
701                                                         (expand-file-name
702                                                          path dir))
703                                                    path)))))
704     (if last-accessed
705         (setq last-accessed (+ (* (nth 0 last-accessed)
706                                   (float 65536)) (nth 1 last-accessed)))
707       0)))
708
709 (defun elmo-get-last-modification-time (path &optional dir)
710   "Return the last accessed time of PATH."
711   (let ((last-modified (nth 5 (file-attributes (or (and dir
712                                                         (expand-file-name
713                                                          path dir))
714                                                    path)))))
715     (setq last-modified (+ (* (nth 0 last-modified)
716                               (float 65536)) (nth 1 last-modified)))))
717
718 (defun elmo-make-directory (path &optional mode)
719   "Create directory recursively."
720   (let ((parent (directory-file-name (file-name-directory path))))
721     (if (null (file-directory-p parent))
722         (elmo-make-directory parent))
723     (make-directory path)
724     (set-file-modes path (or mode
725                              (+ (* 64 7) (* 8 0) 0))))) ; chmod 0700
726
727 (defun elmo-delete-directory (path &optional no-hierarchy)
728   "Delete directory recursively."
729   (if (stringp path) ; nil is not permitted.
730   (let ((dirent (directory-files path))
731         relpath abspath hierarchy)
732     (while dirent
733       (setq relpath (car dirent)
734             dirent (cdr dirent)
735             abspath (expand-file-name relpath path))
736       (when (not (string-match "^\\.\\.?$" relpath))
737         (if (eq (nth 0 (file-attributes abspath)) t)
738             (if no-hierarchy
739                 (setq hierarchy t)
740               (elmo-delete-directory abspath no-hierarchy))
741           (delete-file abspath))))
742     (unless hierarchy
743       (delete-directory path)))))
744
745 (defun elmo-delete-match-files (path regexp &optional remove-if-empty)
746   "Delete directory files specified by PATH.
747 If optional REMOVE-IF-EMPTY is non-nil, delete directory itself if
748 the directory becomes empty after deletion."
749   (when (stringp path) ; nil is not permitted.
750     (dolist (file (directory-files path t regexp))
751       (delete-file file))
752     (if remove-if-empty
753         (ignore-errors 
754           (delete-directory path) ; should be removed if empty.
755           ))))
756
757 (defun elmo-list-filter (l1 l2)
758   "Rerurn a list from L2 in which each element is a member of L1."
759   (elmo-delete-if (lambda (x) (not (memq x l1))) l2))
760
761 (defsubst elmo-list-delete-if-smaller (list number)
762   (let ((ret-val (copy-sequence list)))
763     (while list
764       (if (< (car list) number)
765           (setq ret-val (delq (car list) ret-val)))
766       (setq list (cdr list)))
767     ret-val))
768
769 (defun elmo-list-diff (list1 list2 &optional mes)
770   (if mes
771       (message "%s" mes))
772   (let ((clist1 (copy-sequence list1))
773         (clist2 (copy-sequence list2)))
774     (while list2
775       (setq clist1 (delq (car list2) clist1))
776       (setq list2 (cdr list2)))
777     (while list1
778       (setq clist2 (delq (car list1) clist2))
779       (setq list1 (cdr list1)))
780     (if mes
781         (message "%sdone" mes))
782     (list clist1 clist2)))
783
784 (defun elmo-list-bigger-diff (list1 list2 &optional mes)
785   "Returns a list (- +). + is bigger than max of LIST1, in LIST2."
786   (if (null list2)
787       (cons list1  nil)
788     (let* ((l1 list1)
789            (l2 list2)
790            (max-of-l2 (or (nth (max 0 (1- (length l2))) l2) 0))
791            diff1 num i percent
792            )
793       (setq i 0)
794       (setq num (+ (length l1)))
795       (while l1
796         (if (memq (car l1) l2)
797             (if (eq (car l1) (car l2))
798                 (setq l2 (cdr l2))
799               (delq (car l1) l2))
800           (if (> (car l1) max-of-l2)
801               (setq diff1 (nconc diff1 (list (car l1))))))
802         (if mes
803             (progn
804               (setq i (+ i 1))
805               (setq percent (/ (* i 100) num))
806               (if (eq (% percent 5) 0)
807                   (elmo-display-progress
808                    'elmo-list-bigger-diff "%s%d%%" percent mes))))
809         (setq l1 (cdr l1)))
810       (cons diff1 (list l2)))))
811
812 (defmacro elmo-filter-condition-p (filter)
813   `(or (vectorp ,filter) (consp ,filter)))
814
815 (defmacro elmo-filter-type (filter)
816   (` (aref (, filter) 0)))
817
818 (defmacro elmo-filter-key (filter)
819   (` (aref (, filter) 1)))
820
821 (defmacro elmo-filter-value (filter)
822   (` (aref (, filter) 2)))
823
824 (defsubst elmo-buffer-field-primitive-condition-match (condition
825                                                        number
826                                                        number-list)
827   (let (result)
828     (goto-char (point-min))
829     (cond
830      ((string= (elmo-filter-key condition) "last")
831       (setq result (<= (length (memq number number-list))
832                        (string-to-int (elmo-filter-value condition)))))
833      ((string= (elmo-filter-key condition) "first")
834       (setq result (< (- (length number-list)
835                          (length (memq number number-list)))
836                       (string-to-int (elmo-filter-value condition)))))
837      ((string= (elmo-filter-key condition) "since")
838       (let ((field-date (elmo-date-make-sortable-string
839                          (timezone-fix-time
840                           (std11-field-body "date")
841                           (current-time-zone) nil)))
842             (specified-date (elmo-date-make-sortable-string
843                              (elmo-date-get-datevec
844                               (elmo-filter-value condition)))))
845         (setq result
846               (or (string= field-date specified-date)
847                   (string< specified-date field-date)))))
848      ((string= (elmo-filter-key condition) "before")
849       (setq result
850             (string<
851              (elmo-date-make-sortable-string
852               (timezone-fix-time
853                (std11-field-body "date")
854                (current-time-zone) nil))
855              (elmo-date-make-sortable-string
856               (elmo-date-get-datevec
857                (elmo-filter-value condition))))))
858      ((string= (elmo-filter-key condition) "body")
859       (and (re-search-forward "^$" nil t)          ; goto body
860            (setq result (search-forward (elmo-filter-value condition)
861                                         nil t))))
862      (t
863       (let ((fval (std11-field-body (elmo-filter-key condition))))
864         (if (eq (length fval) 0) (setq fval nil))
865         (if fval (setq fval (eword-decode-string fval)))
866         (setq result (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        (elmo-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   `(and (stringp ,string)
954         ,hashtable
955         (let ((sym (intern-soft ,string ,hashtable)))
956           (if (boundp sym)
957               (symbol-value sym)))))
958
959 (defmacro elmo-set-hash-val (string value hashtable)
960   (list 'set (list '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         (elmo-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         (elmo-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 (nconc result (list (car lst)))))
1104       (setq lst (cdr lst)))
1105     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 (defun elmo-time-expire (before-time diff-time)
1226   (let* ((current (current-time))
1227          (rest (when (< (nth 1 current) (nth 1 before-time))
1228                  (expt 2 16)))
1229          diff)
1230     (setq diff
1231           (list (- (+ (car current) (if rest -1 0)) (car before-time))
1232                 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1233     (and (eq (car diff) 0)
1234          (< diff-time (nth 1 diff)))))
1235
1236 (if (fboundp 'std11-fetch-field)
1237     (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1238   (defalias 'elmo-field-body 'std11-field-body))
1239
1240 (defun elmo-address-quote-specials (word)
1241   "Make quoted string of WORD if needed."
1242   (let ((lal (std11-lexical-analyze word)))
1243     (if (or (assq 'specials lal)
1244             (assq 'domain-literal lal))
1245         (prin1-to-string word)
1246       word)))
1247
1248 (defmacro elmo-string (string)
1249   "STRING without text property."
1250   (` (let ((obj (copy-sequence (, string))))
1251        (and obj (set-text-properties 0 (length obj) nil obj))
1252        obj)))
1253
1254 (defun elmo-flatten (list-of-list)
1255   "Flatten LIST-OF-LIST."
1256   (unless (null list-of-list)
1257     (append (if (and (car list-of-list)
1258                      (listp (car list-of-list)))
1259                 (car list-of-list)
1260               (list (car list-of-list)))
1261             (elmo-flatten (cdr list-of-list)))))
1262
1263 (defun elmo-y-or-n-p (prompt &optional auto default)
1264   "Same as `y-or-n-p'.
1265 But if optional argument AUTO is non-nil, DEFAULT is returned."
1266   (if auto
1267       default
1268     (y-or-n-p prompt)))
1269
1270 (defun elmo-string-member (string slist)
1271   (catch 'found
1272     (while slist
1273       (if (and (stringp (car slist))
1274                (string= string (car slist)))
1275           (throw 'found t))
1276       (setq slist (cdr slist)))))
1277
1278 (cond ((fboundp 'member-ignore-case)
1279        (defalias 'elmo-string-member-ignore-case 'member-ignore-case))
1280       ((fboundp 'compare-strings)
1281        (defun elmo-string-member-ignore-case (elt list)
1282          "Like `member', but ignores differences in case and text representation.
1283 ELT must be a string.  Upper-case and lower-case letters are treated as equal.
1284 Unibyte strings are converted to multibyte for comparison."
1285          (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
1286            (setq list (cdr list)))
1287          list))
1288       (t
1289        (defun elmo-string-member-ignore-case (elt list)
1290          "Like `member', but ignores differences in case and text representation.
1291 ELT must be a string.  Upper-case and lower-case letters are treated as equal."
1292          (let ((str (downcase elt)))
1293            (while (and list (not (string= str (downcase (car list)))))
1294              (setq list (cdr list)))
1295            list))))
1296
1297 (defun elmo-string-match-member (str list &optional case-ignore)
1298   (let ((case-fold-search case-ignore))
1299     (catch 'member
1300       (while list
1301         (if (string-match (car list) str)
1302             (throw 'member (car list)))
1303         (setq list (cdr list))))))
1304
1305 (defun elmo-string-matched-member (str list &optional case-ignore)
1306   (let ((case-fold-search case-ignore))
1307     (catch 'member
1308       (while list
1309         (if (string-match str (car list))
1310             (throw 'member (car list)))
1311         (setq list (cdr list))))))
1312
1313 (defsubst elmo-string-delete-match (string pos)
1314   (concat (substring string
1315                      0 (match-beginning pos))
1316           (substring string
1317                      (match-end pos)
1318                      (length string))))
1319
1320 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1321   (let ((case-fold-search case-ignore)
1322         a)
1323     (catch 'loop
1324       (while alist
1325         (setq a (car alist))
1326         (if (and (consp a)
1327                  (stringp (car a))
1328                  (string-match key (car a)))
1329             (throw 'loop a))
1330         (setq alist (cdr alist))))))
1331
1332 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1333   (let ((case-fold-search case-ignore)
1334         a)
1335     (catch 'loop
1336       (while alist
1337         (setq a (car alist))
1338         (if (and (consp a)
1339                  (stringp (car a))
1340                  (string-match (car a) key))
1341             (throw 'loop a))
1342         (setq alist (cdr alist))))))
1343
1344 (defun elmo-string-assoc (key alist)
1345   (let (a)
1346     (catch 'loop
1347       (while alist
1348         (setq a (car alist))
1349         (if (and (consp a)
1350                  (stringp (car a))
1351                  (string= key (car a)))
1352             (throw 'loop a))
1353         (setq alist (cdr alist))))))
1354
1355 (defun elmo-string-assoc-all (key alist)
1356   (let (matches)
1357     (while alist
1358       (if (string= key (car (car alist)))
1359           (setq matches
1360                 (cons (car alist)
1361                       matches)))
1362       (setq alist (cdr alist)))
1363     matches))
1364
1365 (defun elmo-string-rassoc (key alist)
1366   (let (a)
1367     (catch 'loop
1368       (while alist
1369         (setq a (car alist))
1370         (if (and (consp a)
1371                  (stringp (cdr a))
1372                  (string= key (cdr a)))
1373             (throw 'loop a))
1374         (setq alist (cdr alist))))))
1375
1376 (defun elmo-string-rassoc-all (key alist)
1377   (let (matches)
1378     (while alist
1379       (if (string= key (cdr (car alist)))
1380           (setq matches
1381                 (cons (car alist)
1382                       matches)))
1383       (setq alist (cdr alist)))
1384     matches))
1385
1386 (defun elmo-expand-newtext (newtext original)
1387   (let ((len (length newtext))
1388         (pos 0)
1389         c expanded beg N did-expand)
1390     (while (< pos len)
1391       (setq beg pos)
1392       (while (and (< pos len)
1393                   (not (= (aref newtext pos) ?\\)))
1394         (setq pos (1+ pos)))
1395       (unless (= beg pos)
1396         (push (substring newtext beg pos) expanded))
1397       (when (< pos len)
1398         ;; We hit a \; expand it.
1399         (setq did-expand t
1400               pos (1+ pos)
1401               c (aref newtext pos))
1402         (if (not (or (= c ?\&)
1403                      (and (>= c ?1)
1404                           (<= c ?9))))
1405             ;; \ followed by some character we don't expand.
1406             (push (char-to-string c) expanded)
1407           ;; \& or \N
1408           (if (= c ?\&)
1409               (setq N 0)
1410             (setq N (- c ?0)))
1411           (when (match-beginning N)
1412             (push (substring original (match-beginning N) (match-end N))
1413                   expanded))))
1414       (setq pos (1+ pos)))
1415     (if did-expand
1416         (apply (function concat) (nreverse expanded))
1417       newtext)))
1418
1419 ;;; Folder parser utils.
1420 (defun elmo-parse-token (string &optional seps)
1421   "Parse atom from STRING using SEPS as a string of separator char list."
1422   (let ((len (length string))
1423         (seps (and seps (string-to-char-list seps)))
1424         (i 0)
1425         (sep nil)
1426         content c in)
1427     (if (eq len 0)
1428         (cons "" "")
1429       (while (and (< i len) (or in (null sep)))
1430         (setq c (aref string i))
1431         (cond
1432          ((and in (eq c ?\\))
1433           (setq i (1+ i)
1434                 content (cons (aref string i) content)
1435                 i (1+ i)))
1436          ((eq c ?\")
1437           (setq in (not in)
1438                 i (1+ i)))
1439          (in (setq content (cons c content)
1440                    i (1+ i)))
1441          ((memq c seps)
1442           (setq sep c))
1443          (t (setq content (cons c content)
1444                   i (1+ i)))))
1445       (if in (error "Parse error in quoted"))
1446       (cons (if (null content) "" (char-list-to-string (nreverse content)))
1447             (substring string i)))))
1448
1449 (defun elmo-parse-prefixed-element (prefix string &optional seps)
1450   (if (and (not (eq (length string) 0))
1451            (eq (aref string 0) prefix))
1452       (elmo-parse-token (substring string 1) seps)
1453     (cons "" string)))
1454
1455 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1456 ;;
1457 ;; number          ::= [0-9]+
1458 ;; beg             ::= number
1459 ;; end             ::= number
1460 ;; number-range    ::= "(" beg " . " end ")"      ;; cons cell
1461 ;; number-set-elem ::= number / number-range
1462 ;; number-set      ::= "(" *number-set-elem ")"   ;; list
1463
1464 (defun elmo-number-set-member (number number-set)
1465   "Return non-nil if NUMBER is an element of NUMBER-SET.
1466 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1467   (or (memq number number-set)
1468       (let (found)
1469         (while (and number-set (not found))
1470           (if (and (consp (car number-set))
1471                    (and (<= (car (car number-set)) number)
1472                         (<= number (cdr (car number-set)))))
1473               (setq found t)
1474             (setq number-set (cdr number-set))))
1475         number-set)))
1476
1477 (defun elmo-number-set-append-list (number-set list)
1478   "Append LIST of numbers to the NUMBER-SET.
1479 NUMBER-SET is altered."
1480   (let ((appended number-set))
1481     (while list
1482       (setq appended (elmo-number-set-append appended (car list)))
1483       (setq list (cdr list)))
1484     appended))
1485
1486 (defun elmo-number-set-append (number-set number)
1487   "Append NUMBER to the NUMBER-SET.
1488 NUMBER-SET is altered."
1489   (let ((number-set-1 number-set)
1490         found elem)
1491     (while (and number-set (not found))
1492       (setq elem (car number-set))
1493       (cond
1494        ((and (consp elem)
1495              (eq (+ 1 (cdr elem)) number))
1496         (setcdr elem number)
1497         (setq found t))
1498        ((and (integerp elem)
1499              (eq (+ 1 elem) number))
1500         (setcar number-set (cons elem number))
1501         (setq found t))
1502        ((or (and (integerp elem) (eq elem number))
1503             (and (consp elem)
1504                  (<= (car elem) number)
1505                  (<= number (cdr elem))))
1506         (setq found t)))
1507       (setq number-set (cdr number-set)))
1508     (if (not found)
1509         (setq number-set-1 (nconc number-set-1 (list number))))
1510     number-set-1))
1511
1512 (defun elmo-number-set-to-number-list (number-set)
1513   "Return a number list which corresponds to NUMBER-SET."
1514   (let (number-list elem i)
1515     (while number-set
1516       (setq elem (car number-set))
1517       (cond
1518        ((consp elem)
1519         (setq i (car elem))
1520         (while (<= i (cdr elem))
1521           (setq number-list (cons i number-list))
1522           (incf i)))
1523        ((integerp elem)
1524         (setq number-list (cons elem number-list))))
1525       (setq number-set (cdr number-set)))
1526     (nreverse number-list)))
1527
1528 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1529   "*Regexp to filter subfolders."
1530   :type 'regexp
1531   :group 'elmo)
1532
1533 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1534   (let ((root (zerop (length curdir)))
1535         (w32-get-true-file-link-count t) ; for Meadow
1536         attr dirs dir)
1537     (catch 'done
1538       (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1539         (when (and (not (string-match
1540                          elmo-list-subdirectories-ignore-regexp
1541                          file))
1542                    (car (setq attr (file-attributes
1543                                     (expand-file-name file dir)))))
1544           (when (eq one-level 'check) (throw 'done t))
1545           (let ((relpath
1546                  (concat curdir (and (not root) elmo-path-sep) file))
1547                 subdirs)
1548             (setq dirs (nconc dirs
1549                               (if (if elmo-have-link-count (< 2 (nth 1 attr))
1550                                     (setq subdirs
1551                                           (elmo-list-subdirectories-1
1552                                            basedir
1553                                            relpath
1554                                            (if one-level 'check))))
1555                                   (if one-level
1556                                       (list (list relpath))
1557                                     (cons relpath
1558                                           (or subdirs
1559                                               (elmo-list-subdirectories-1
1560                                                basedir
1561                                                relpath
1562                                                nil))))
1563                                 (list relpath)))))))
1564       dirs)))
1565
1566 (defun elmo-list-subdirectories (directory file one-level)
1567   (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1568     (if (zerop (length file))
1569         subdirs
1570       (cons file subdirs))))
1571
1572 (defun elmo-mapcar-list-of-list (func list-of-list)
1573   (mapcar
1574    (lambda (x)
1575      (cond ((listp x) (elmo-mapcar-list-of-list func x))
1576            (t (funcall func x))))
1577    list-of-list))
1578
1579 (defun elmo-parse (string regexp &optional matchn)
1580   (or matchn (setq matchn 1))
1581   (let (list)
1582     (store-match-data nil)
1583     (while (string-match regexp string (match-end 0))
1584       (setq list (cons (substring string (match-beginning matchn)
1585                                   (match-end matchn)) list)))
1586     (nreverse list)))
1587
1588 ;;;
1589 ;; parsistent mark handling
1590 ;; (for global!)
1591 ;; (FIXME: this should be treated in the msgdb.)
1592
1593 (defvar elmo-msgdb-global-mark-alist nil)
1594
1595 (defun elmo-msgdb-global-mark-delete (msgid)
1596   (let* ((path (expand-file-name
1597                 elmo-msgdb-global-mark-filename
1598                 elmo-msgdb-directory))
1599          (malist (or elmo-msgdb-global-mark-alist
1600                      (setq elmo-msgdb-global-mark-alist
1601                            (elmo-object-load path))))
1602          match)
1603     (when (setq match (assoc msgid malist))
1604       (setq elmo-msgdb-global-mark-alist
1605             (delete match elmo-msgdb-global-mark-alist))
1606       (elmo-object-save path elmo-msgdb-global-mark-alist))))
1607
1608 (defun elmo-msgdb-global-mark-set (msgid mark)
1609   (let* ((path (expand-file-name
1610                 elmo-msgdb-global-mark-filename
1611                 elmo-msgdb-directory))
1612          (malist (or elmo-msgdb-global-mark-alist
1613                      (setq elmo-msgdb-global-mark-alist
1614                            (elmo-object-load path))))
1615          match)
1616     (if (setq match (assoc msgid malist))
1617         (setcdr match mark)
1618       (setq elmo-msgdb-global-mark-alist
1619             (nconc elmo-msgdb-global-mark-alist
1620                    (list (cons msgid mark)))))
1621     (elmo-object-save path elmo-msgdb-global-mark-alist)))
1622
1623 (defun elmo-msgdb-global-mark-get (msgid)
1624   (cdr (assoc msgid (or elmo-msgdb-global-mark-alist
1625                         (setq elmo-msgdb-global-mark-alist
1626                               (elmo-object-load
1627                                (expand-file-name
1628                                 elmo-msgdb-global-mark-filename
1629                                 elmo-msgdb-directory)))))))
1630
1631 ;;; File cache.
1632 (defmacro elmo-make-file-cache (path status)
1633   "PATH is the cache file name.
1634 STATUS is one of 'section, 'entire or nil.
1635  nil means no cache exists.
1636 'section means partial section cache exists.
1637 'entire means entire cache exists.
1638 If the cache is partial file-cache, TYPE is 'partial."
1639   (` (cons (, path) (, status))))
1640
1641 (defmacro elmo-file-cache-path (file-cache)
1642   "Returns the file path of the FILE-CACHE."
1643   (` (car (, file-cache))))
1644
1645 (defmacro elmo-file-cache-status (file-cache)
1646   "Returns the status of the FILE-CACHE."
1647   (` (cdr (, file-cache))))
1648
1649 (defsubst elmo-cache-to-msgid (filename)
1650   (concat "<" (elmo-recover-string-from-filename filename) ">"))
1651
1652 (defsubst elmo-cache-get-path-subr (msgid)
1653   (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1654         (clist (string-to-char-list msgid))
1655         (sum 0))
1656     (while clist
1657       (setq sum (+ sum (car clist)))
1658       (setq clist (cdr clist)))
1659     (format "%c%c"
1660             (nth (% (/ sum 16) 2) chars)
1661             (nth (% sum 16) chars))))
1662
1663 ;;;
1664 (defun elmo-file-cache-get-path (msgid &optional section)
1665   "Get cache path for MSGID.
1666 If optional argument SECTION is specified, partial cache path is returned."
1667   (if (setq msgid (elmo-msgid-to-cache msgid))
1668       (expand-file-name
1669        (if section
1670            (format "%s/%s/%s/%s"
1671                    elmo-cache-directory
1672                    (elmo-cache-get-path-subr msgid)
1673                    msgid
1674                    section)
1675          (format "%s/%s/%s"
1676                  elmo-cache-directory
1677                  (elmo-cache-get-path-subr msgid)
1678                  msgid)))))
1679
1680 (defmacro elmo-file-cache-expand-path (path section)
1681   "Return file name for the file-cache corresponds to the section.
1682 PATH is the file-cache path.
1683 SECTION is the section string."
1684   (` (expand-file-name (or (, section) "") (, path))))
1685
1686 (defun elmo-file-cache-delete (path)
1687   "Delete a cache on PATH."
1688   (unless (elmo-msgdb-global-mark-get
1689            (elmo-cache-to-msgid (file-name-nondirectory path)))
1690     (when (file-exists-p path)
1691       (if (file-directory-p path)
1692           (progn
1693             (dolist (file (directory-files path t "^[^\\.]"))
1694               (delete-file file))
1695             (delete-directory path))
1696         (delete-file path))
1697       t)))
1698
1699 (defun elmo-file-cache-exists-p (msgid)
1700   "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1701   (elmo-file-cache-status (elmo-file-cache-get msgid)))
1702
1703 (defun elmo-file-cache-save (cache-path section)
1704   "Save current buffer as cache on PATH.
1705 Return t if cache is saved successfully."
1706   (condition-case nil
1707       (let ((path (if section (expand-file-name section cache-path)
1708                     cache-path))
1709             files dir)
1710         (if (and (null section)
1711                  (file-directory-p path))
1712             (progn
1713               (setq files (directory-files path t "^[^\\.]"))
1714               (while files
1715                 (delete-file (car files))
1716                 (setq files (cdr files)))
1717               (delete-directory path))
1718           (if (and section
1719                    (not (file-directory-p cache-path)))
1720               (delete-file cache-path)))
1721         (when path
1722           (setq dir (directory-file-name (file-name-directory path)))
1723           (if (not (file-exists-p dir))
1724               (elmo-make-directory dir))
1725           (write-region-as-binary (point-min) (point-max)
1726                                   path nil 'no-msg)
1727           t))
1728     ;; ignore error
1729     (error)))
1730
1731 (defun elmo-file-cache-load (cache-path section)
1732   "Load cache on PATH into the current buffer.
1733 Return t if cache is loaded successfully."
1734   (condition-case nil
1735       (let (cache-file)
1736         (when (and cache-path
1737                    (if (elmo-cache-path-section-p cache-path)
1738                        section
1739                      (null section))
1740                    (setq cache-file (elmo-file-cache-expand-path
1741                                      cache-path
1742                                      section))
1743                    (file-exists-p cache-file))
1744           (insert-file-contents-as-binary cache-file)
1745           t))
1746     ;; igore error
1747     (error)))
1748
1749 (defun elmo-cache-path-section-p (path)
1750   "Return non-nil when PATH is `section' cache path."
1751   (file-directory-p path))
1752
1753 (defun elmo-file-cache-get (msgid &optional section)
1754   "Returns the current file-cache object associated with MSGID.
1755 MSGID is the message-id of the message.
1756 If optional argument SECTION is specified, get partial file-cache object
1757 associated with SECTION."
1758   (if msgid
1759       (let ((path (elmo-cache-get-path msgid)))
1760         (if (and path (file-exists-p path))
1761             (if (elmo-cache-path-section-p path)
1762                 (if section
1763                     (if (file-exists-p (setq path (expand-file-name
1764                                                    section path)))
1765                         (cons path 'section))
1766                   ;; section is not specified but sectional.
1767                   (cons path 'section))
1768               ;; not directory.
1769               (unless section
1770                 (cons path 'entire)))
1771           ;; no cache.
1772           (cons path nil)))))
1773
1774 ;;;
1775 ;; Expire cache.
1776
1777 (defun elmo-cache-expire ()
1778   (interactive)
1779   (let* ((completion-ignore-case t)
1780          (method (completing-read (format "Expire by (%s): "
1781                                           elmo-cache-expire-default-method)
1782                                   '(("size" . "size")
1783                                     ("age" . "age")))))
1784     (if (string= method "")
1785         (setq method elmo-cache-expire-default-method))
1786     (funcall (intern (concat "elmo-cache-expire-by-" method)))))
1787
1788 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
1789   (let ((str (read-from-minibuffer prompt initial)))
1790     (cond
1791      ((string-match "[0-9]*\\.[0-9]+" str)
1792       (string-to-number str))
1793      ((string-match "[0-9]+" str)
1794       (string-to-number (concat str ".0")))
1795      (t (error "%s is not number" str)))))
1796
1797 (defun elmo-cache-expire-by-size (&optional kbytes)
1798   "Expire cache file by size.
1799 If KBYTES is kilo bytes (This value must be float)."
1800   (interactive)
1801   (let ((size (or kbytes
1802                   (and (interactive-p)
1803                        (elmo-read-float-value-from-minibuffer
1804                         "Enter cache disk size (Kbytes): "
1805                         (number-to-string
1806                          (if (integerp elmo-cache-expire-default-size)
1807                              (float elmo-cache-expire-default-size)
1808                            elmo-cache-expire-default-size))))
1809                   (if (integerp elmo-cache-expire-default-size)
1810                       (float elmo-cache-expire-default-size))))
1811         (count 0)
1812         (Kbytes 1024)
1813         total beginning)
1814     (message "Checking disk usage...")
1815     (setq total (/ (elmo-disk-usage
1816                     elmo-cache-directory) Kbytes))
1817     (setq beginning total)
1818     (message "Checking disk usage...done")
1819     (let ((cfl (elmo-cache-get-sorted-cache-file-list))
1820           (deleted 0)
1821           oldest
1822           cur-size cur-file)
1823       (while (and (<= size total)
1824                   (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
1825         (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
1826         (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
1827         (when (elmo-file-cache-delete cur-file)
1828           (setq count (+ count 1))
1829           (message "%d cache(s) are expired." count))
1830         (setq deleted (+ deleted cur-size))
1831         (setq total (- total cur-size)))
1832       (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
1833                count deleted beginning))))
1834
1835 (defun elmo-cache-make-file-entity (filename path)
1836   (cons filename (elmo-get-last-accessed-time filename path)))
1837
1838 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
1839   (let ((cfl cache-file-list)
1840         flist firsts oldest-entity wonlist)
1841     (while cfl
1842       (setq flist (cdr (car cfl)))
1843       (setq firsts (append firsts (list
1844                                    (cons (car (car cfl))
1845                                          (car flist)))))
1846       (setq cfl (cdr cfl)))
1847 ;;; (prin1 firsts)
1848     (while firsts
1849       (if (and (not oldest-entity)
1850                (cdr (cdr (car firsts))))
1851           (setq oldest-entity (car firsts)))
1852       (if (and (cdr (cdr (car firsts)))
1853                (cdr (cdr oldest-entity))
1854                (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
1855           (setq oldest-entity (car firsts)))
1856       (setq firsts (cdr firsts)))
1857     (setq wonlist (assoc (car oldest-entity) cache-file-list))
1858     (and wonlist
1859          (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
1860     oldest-entity))
1861
1862 (defun elmo-cache-get-sorted-cache-file-list ()
1863   (let ((dirs (directory-files
1864                elmo-cache-directory
1865                t "^[^\\.]"))
1866         (i 0) num
1867         elist
1868         ret-val)
1869     (setq num (length dirs))
1870     (message "Collecting cache info...")
1871     (while dirs
1872       (setq elist (mapcar (lambda (x)
1873                             (elmo-cache-make-file-entity x (car dirs)))
1874                           (directory-files (car dirs) nil "^[^\\.]")))
1875       (setq ret-val (append ret-val
1876                             (list (cons
1877                                    (car dirs)
1878                                    (sort
1879                                     elist
1880                                     (lambda (x y)
1881                                       (< (cdr x)
1882                                          (cdr y))))))))
1883       (when (> num elmo-display-progress-threshold)
1884         (setq i (+ i 1))
1885         (elmo-display-progress
1886          'elmo-cache-get-sorted-cache-file-list "Collecting cache info..."
1887          (/ (* i 100) num)))
1888       (setq dirs (cdr dirs)))
1889     (message "Collecting cache info...done")
1890     ret-val))
1891
1892 (defun elmo-cache-expire-by-age (&optional days)
1893   (let ((age (or (and days (int-to-string days))
1894                  (and (interactive-p)
1895                       (read-from-minibuffer
1896                        (format "Enter days (%s): "
1897                                elmo-cache-expire-default-age)))
1898                  (int-to-string elmo-cache-expire-default-age)))
1899         (dirs (directory-files
1900                elmo-cache-directory
1901                t "^[^\\.]"))
1902         (count 0)
1903         curtime)
1904     (if (string= age "")
1905         (setq age elmo-cache-expire-default-age)
1906       (setq age (string-to-int age)))
1907     (setq curtime (current-time))
1908     (setq curtime (+ (* (nth 0 curtime)
1909                         (float 65536)) (nth 1 curtime)))
1910     (while dirs
1911       (let ((files (directory-files (car dirs) t "^[^\\.]"))
1912             (limit-age (* age 86400)))
1913         (while files
1914           (when (> (- curtime (elmo-get-last-accessed-time (car files)))
1915                    limit-age)
1916             (when (elmo-file-cache-delete (car files))
1917               (setq count (+ 1 count))
1918               (message "%d cache file(s) are expired." count)))
1919           (setq files (cdr files))))
1920       (setq dirs (cdr dirs)))))
1921
1922 ;;;
1923 ;; msgid to path.
1924 (defun elmo-msgid-to-cache (msgid)
1925   (save-match-data
1926     (when (and msgid
1927                (string-match "<\\(.+\\)>$" msgid))
1928       (elmo-replace-string-as-filename (elmo-match-string 1 msgid)))))
1929
1930 (defun elmo-cache-get-path (msgid &optional folder number)
1931   "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
1932   (if (setq msgid (elmo-msgid-to-cache msgid))
1933       (expand-file-name
1934        (expand-file-name
1935         (if folder
1936             (format "%s/%s/%s@%s"
1937                     (elmo-cache-get-path-subr msgid)
1938                     msgid
1939                     (or number "")
1940                     (elmo-safe-filename folder))
1941           (format "%s/%s"
1942                   (elmo-cache-get-path-subr msgid)
1943                   msgid))
1944         elmo-cache-directory))))
1945
1946 ;;;
1947 ;; Warnings.
1948
1949 (static-if (fboundp 'display-warning)
1950     (defmacro elmo-warning (&rest args)
1951       "Display a warning with `elmo' group."
1952       `(display-warning 'elmo (format ,@args)))
1953   (defconst elmo-warning-buffer-name "*elmo warning*")
1954   (defun elmo-warning (&rest args)
1955     "Display a warning. ARGS are passed to `format'."
1956     (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
1957       (goto-char (point-max))
1958       (funcall 'insert (apply 'format (append args '("\n"))))
1959       (ignore-errors (recenter 1))
1960       (display-buffer elmo-warning-buffer-name))))
1961
1962 (defvar elmo-obsolete-variable-alist nil)
1963
1964 (defcustom elmo-obsolete-variable-show-warnings t
1965   "Show warning window if obsolete variable is treated."
1966   :type 'boolean
1967   :group 'elmo)
1968
1969 (defun elmo-define-obsolete-variable (obsolete var)
1970   "Define obsolete variable.
1971 OBSOLETE is a symbol for obsolete variable.
1972 VAR is a symbol for new variable.
1973 Definition is stored in `elmo-obsolete-variable-alist'."
1974   (let ((pair (assq var elmo-obsolete-variable-alist)))
1975     (if pair
1976         (setcdr pair obsolete)
1977       (setq elmo-obsolete-variable-alist
1978             (cons (cons var obsolete)
1979                   elmo-obsolete-variable-alist)))))
1980
1981 (defun elmo-resque-obsolete-variable (obsolete var)
1982   "Resque obsolete variable OBSOLETE as VAR.
1983 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
1984   (when (boundp obsolete)
1985     (static-if (and (fboundp 'defvaralias)
1986                     (subrp (symbol-function 'defvaralias)))
1987         (defvaralias var obsolete)
1988       (set var (symbol-value obsolete)))
1989     (if elmo-obsolete-variable-show-warnings
1990         (elmo-warning "%s is obsolete. Use %s instead."
1991                       (symbol-name obsolete)
1992                       (symbol-name var)))))
1993
1994 (defun elmo-resque-obsolete-variables (&optional alist)
1995   "Resque obsolete variables in ALIST.
1996 ALIST is a list of cons cell of
1997 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
1998 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
1999   (dolist (pair elmo-obsolete-variable-alist)
2000     (elmo-resque-obsolete-variable (cdr pair)
2001                                    (car pair))))
2002
2003 ;;; Queue.
2004 (defvar elmo-dop-queue-filename "queue"
2005   "*Disconnected operation queue is saved in this file.")
2006
2007 (defun elmo-dop-queue-load ()
2008   (setq elmo-dop-queue
2009         (elmo-object-load
2010          (expand-file-name elmo-dop-queue-filename
2011                            elmo-msgdb-directory))))
2012
2013 (defun elmo-dop-queue-save ()
2014   (elmo-object-save
2015    (expand-file-name elmo-dop-queue-filename
2016                      elmo-msgdb-directory)
2017    elmo-dop-queue))
2018
2019 (if (and (fboundp 'regexp-opt)
2020          (not (featurep 'xemacs)))
2021     (defalias 'elmo-regexp-opt 'regexp-opt)
2022   (defun elmo-regexp-opt (strings &optional paren)
2023     "Return a regexp to match a string in STRINGS.
2024 Each string should be unique in STRINGS and should not contain any regexps,
2025 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
2026 is enclosed by at least one regexp grouping construct."
2027     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
2028       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
2029               close-paren))))
2030
2031 (require 'product)
2032 (product-provide (provide 'elmo-util) (require 'elmo-version))
2033
2034 ;;; elmo-util.el ends here