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