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