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