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