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