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