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