(elmo-set-auto-coding): New function.
[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 filename)
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 (folder)
1045   (elmo-replace-in-string
1046    (elmo-replace-in-string
1047     (elmo-replace-in-string folder "/" " ")
1048     ":" "__")
1049    "|" "_or_"))
1050
1051 (defvar elmo-filename-replace-chars nil)
1052
1053 (defsubst elmo-replace-string-as-filename (msgid)
1054   "Replace string as filename."
1055   (setq msgid (elmo-replace-in-string msgid " " "  "))
1056   (if (null elmo-filename-replace-chars)
1057       (setq elmo-filename-replace-chars
1058             (regexp-quote (mapconcat
1059                            'car elmo-filename-replace-string-alist ""))))
1060   (while (string-match (concat "[" elmo-filename-replace-chars "]")
1061                        msgid)
1062     (setq msgid (concat
1063                  (substring msgid 0 (match-beginning 0))
1064                  (cdr (assoc
1065                        (substring msgid
1066                                   (match-beginning 0) (match-end 0))
1067                        elmo-filename-replace-string-alist))
1068                  (substring msgid (match-end 0)))))
1069   msgid)
1070
1071 (defsubst elmo-recover-string-from-filename (filename)
1072   "Recover string from FILENAME."
1073   (let (tmp result)
1074     (while (string-match " " filename)
1075       (setq tmp (substring filename
1076                            (match-beginning 0)
1077                            (+ (match-end 0) 1)))
1078       (if (string= tmp "  ")
1079           (setq tmp " ")
1080         (setq tmp (car (rassoc tmp
1081                                elmo-filename-replace-string-alist))))
1082       (setq result
1083             (concat result
1084                     (substring filename 0 (match-beginning 0))
1085                     tmp))
1086       (setq filename (substring filename (+ (match-end 0) 1))))
1087     (concat result filename)))
1088
1089 (defsubst elmo-copy-file (src dst &optional ok-if-already-exists)
1090   (condition-case err
1091       (elmo-add-name-to-file src dst ok-if-already-exists)
1092     (error (copy-file src dst ok-if-already-exists t))))
1093
1094 (defsubst elmo-buffer-exists-p (buffer)
1095   (if (bufferp buffer)
1096       (buffer-live-p buffer)
1097     (get-buffer buffer)))
1098
1099 (defsubst elmo-kill-buffer (buffer)
1100   (when (elmo-buffer-exists-p buffer)
1101     (kill-buffer buffer)))
1102
1103 (defun elmo-delete-if (pred lst)
1104   "Return new list contain items which don't satisfy PRED in LST."
1105   (let (result)
1106     (while lst
1107       (unless (funcall pred (car lst))
1108         (setq result (cons (car lst) result)))
1109       (setq lst (cdr lst)))
1110     (nreverse result)))
1111
1112 (defun elmo-list-delete (list1 list2 &optional delete-function)
1113   "Delete by side effect any occurrences equal to elements of LIST1 from LIST2.
1114 Return the modified LIST2.  Deletion is done with `delete'.
1115 Write `(setq foo (elmo-list-delete bar foo))' to be sure of changing
1116 the value of `foo'.
1117 If optional DELETE-FUNCTION is speficied, it is used as delete procedure."
1118   (setq delete-function (or delete-function 'delete))
1119   (while list1
1120     (setq list2 (funcall delete-function (car list1) list2))
1121     (setq list1 (cdr list1)))
1122   list2)
1123
1124 (defun elmo-list-member (list1 list2)
1125   "If any element of LIST1 is member of LIST2, return t."
1126   (catch 'done
1127     (while list1
1128       (if (member (car list1) list2)
1129           (throw 'done t))
1130       (setq list1 (cdr list1)))))
1131
1132 (defun elmo-count-matches (regexp beg end)
1133   (let ((count 0))
1134     (save-excursion
1135       (goto-char beg)
1136       (while (re-search-forward regexp end t)
1137         (setq count (1+ count)))
1138       count)))
1139
1140 (if (fboundp 'display-error)
1141     (defalias 'elmo-display-error 'display-error)
1142   (defun elmo-display-error (error-object stream)
1143     "A tiny function to display ERROR-OBJECT to the STREAM."
1144     (let ((first t)
1145           (errobj error-object)
1146           err-mes)
1147       (while errobj
1148         (setq err-mes (concat err-mes (format
1149                                        (if (stringp (car errobj))
1150                                            "%s"
1151                                          "%S")
1152                                        (car errobj))))
1153         (setq errobj (cdr errobj))
1154         (if errobj (setq err-mes (concat err-mes (if first ": " ", "))))
1155         (setq first nil))
1156       (princ err-mes stream))))
1157
1158 (if (fboundp 'define-error)
1159     (defalias 'elmo-define-error 'define-error)
1160   (defun elmo-define-error (error doc &optional parents)
1161     (or parents
1162         (setq parents 'error))
1163     (let ((conds (get parents 'error-conditions)))
1164       (or conds
1165           (error "Not an error symbol: %s" error))
1166       (setplist error
1167                 (list 'error-message doc
1168                       'error-conditions (cons error conds))))))
1169
1170 (cond ((fboundp 'progress-feedback-with-label)
1171        (defalias 'elmo-display-progress 'progress-feedback-with-label))
1172       ((fboundp 'lprogress-display)
1173        (defalias 'elmo-display-progress 'lprogress-display))
1174       (t
1175        (defun elmo-display-progress (label format &optional value &rest args)
1176          "Print a progress message."
1177          (if (and (null format) (null args))
1178              (message nil)
1179            (apply (function message) (concat format " %d%%")
1180                   (nconc args (list value)))))))
1181
1182 (defvar elmo-progress-counter-alist nil)
1183
1184 (defmacro elmo-progress-counter-value (counter)
1185   (` (aref (cdr (, counter)) 0)))
1186
1187 (defmacro elmo-progress-counter-all-value (counter)
1188   (` (aref (cdr (, counter)) 1)))
1189
1190 (defmacro elmo-progress-counter-format (counter)
1191   (` (aref (cdr (, counter)) 2)))
1192
1193 (defmacro elmo-progress-counter-set-value (counter value)
1194   (` (aset (cdr (, counter)) 0 (, value))))
1195
1196 (defun elmo-progress-set (label all-value &optional format)
1197   (unless (assq label elmo-progress-counter-alist)
1198     (setq elmo-progress-counter-alist
1199           (cons (cons label (vector 0 all-value (or format "")))
1200                 elmo-progress-counter-alist))))
1201
1202 (defun elmo-progress-clear (label)
1203   (let ((counter (assq label elmo-progress-counter-alist)))
1204     (when counter
1205       (elmo-display-progress label
1206                              (elmo-progress-counter-format counter)
1207                              100)
1208       (setq elmo-progress-counter-alist
1209             (delq counter elmo-progress-counter-alist)))))
1210
1211 (defun elmo-progress-notify (label &optional value op &rest args)
1212   (let ((counter (assq label elmo-progress-counter-alist)))
1213     (when counter
1214       (let* ((value (or value 1))
1215              (cur-value (elmo-progress-counter-value counter))
1216              (all-value (elmo-progress-counter-all-value counter))
1217              (new-value (if (eq op 'set) value (+ cur-value value)))
1218              (cur-rate (/ (* cur-value 100) all-value))
1219              (new-rate (/ (* new-value 100) all-value)))
1220         (elmo-progress-counter-set-value counter new-value)
1221         (unless (= cur-rate new-rate)
1222           (apply 'elmo-display-progress
1223                  label
1224                  (elmo-progress-counter-format counter)
1225                  new-rate
1226                  args))
1227         (when (>= new-rate 100)
1228           (elmo-progress-clear label))))))
1229
1230 (put 'elmo-with-progress-display 'lisp-indent-function '2)
1231 (def-edebug-spec elmo-with-progress-display
1232   (form (symbolp form &optional form) &rest form))
1233
1234 (defmacro elmo-with-progress-display (condition spec &rest body)
1235   "Evaluate BODY with progress gauge if CONDITION is non-nil.
1236 SPEC is a list as followed (LABEL MAX-VALUE [FORMAT])."
1237   (let ((label (car spec))
1238         (max-value (cadr spec))
1239         (fmt (caddr spec)))
1240     `(unwind-protect
1241          (progn
1242            (when ,condition
1243              (elmo-progress-set (quote ,label) ,max-value ,fmt))
1244            ,@body)
1245        (elmo-progress-clear (quote ,label)))))
1246
1247 (defun elmo-time-expire (before-time diff-time)
1248   (let* ((current (current-time))
1249          (rest (when (< (nth 1 current) (nth 1 before-time))
1250                  (expt 2 16)))
1251          diff)
1252     (setq diff
1253           (list (- (+ (car current) (if rest -1 0)) (car before-time))
1254                 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1255     (and (eq (car diff) 0)
1256          (< diff-time (nth 1 diff)))))
1257
1258 (if (fboundp 'std11-fetch-field)
1259     (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1260   (defalias 'elmo-field-body 'std11-field-body))
1261
1262 (defun elmo-unfold-field-body (name)
1263   (let ((value (elmo-field-body name)))
1264     (and value
1265          (std11-unfold-string value))))
1266
1267 (defun elmo-decoded-field-body (field-name &optional mode)
1268   (let ((field-body (elmo-field-body field-name)))
1269     (and field-body
1270          (elmo-with-enable-multibyte
1271            (mime-decode-field-body field-body field-name mode)))))
1272
1273 (defun elmo-address-quote-specials (word)
1274   "Make quoted string of WORD if needed."
1275   (let ((lal (std11-lexical-analyze word)))
1276     (if (or (assq 'specials lal)
1277             (assq 'domain-literal lal))
1278         (prin1-to-string word)
1279       word)))
1280
1281 (defmacro elmo-string (string)
1282   "STRING without text property."
1283   (` (let ((obj (copy-sequence (, string))))
1284        (and obj (set-text-properties 0 (length obj) nil obj))
1285        obj)))
1286
1287 (defun elmo-flatten (list-of-list)
1288   "Flatten LIST-OF-LIST."
1289   (unless (null list-of-list)
1290     (append (if (and (car list-of-list)
1291                      (listp (car list-of-list)))
1292                 (car list-of-list)
1293               (list (car list-of-list)))
1294             (elmo-flatten (cdr list-of-list)))))
1295
1296 (defun elmo-y-or-n-p (prompt &optional auto default)
1297   "Same as `y-or-n-p'.
1298 But if optional argument AUTO is non-nil, DEFAULT is returned."
1299   (if auto
1300       default
1301     (y-or-n-p prompt)))
1302
1303 (defun elmo-string-member (string slist)
1304   (catch 'found
1305     (while slist
1306       (if (and (stringp (car slist))
1307                (string= string (car slist)))
1308           (throw 'found t))
1309       (setq slist (cdr slist)))))
1310
1311 (static-cond ((fboundp 'member-ignore-case)
1312        (defalias 'elmo-string-member-ignore-case 'member-ignore-case))
1313       ((fboundp 'compare-strings)
1314        (defun elmo-string-member-ignore-case (elt list)
1315          "Like `member', but ignores differences in case and text representation.
1316 ELT must be a string.  Upper-case and lower-case letters are treated as equal.
1317 Unibyte strings are converted to multibyte for comparison."
1318          (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
1319            (setq list (cdr list)))
1320          list))
1321       (t
1322        (defun elmo-string-member-ignore-case (elt list)
1323          "Like `member', but ignores differences in case and text representation.
1324 ELT must be a string.  Upper-case and lower-case letters are treated as equal."
1325          (let ((str (downcase elt)))
1326            (while (and list (not (string= str (downcase (car list)))))
1327              (setq list (cdr list)))
1328            list))))
1329
1330 (defun elmo-string-match-member (str list &optional case-ignore)
1331   (let ((case-fold-search case-ignore))
1332     (catch 'member
1333       (while list
1334         (if (string-match (car list) str)
1335             (throw 'member (car list)))
1336         (setq list (cdr list))))))
1337
1338 (defun elmo-string-matched-member (str list &optional case-ignore)
1339   (let ((case-fold-search case-ignore))
1340     (catch 'member
1341       (while list
1342         (if (string-match str (car list))
1343             (throw 'member (car list)))
1344         (setq list (cdr list))))))
1345
1346 (defsubst elmo-string-delete-match (string pos)
1347   (concat (substring string
1348                      0 (match-beginning pos))
1349           (substring string
1350                      (match-end pos)
1351                      (length string))))
1352
1353 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1354   (let ((case-fold-search case-ignore)
1355         a)
1356     (catch 'loop
1357       (while alist
1358         (setq a (car alist))
1359         (if (and (consp a)
1360                  (stringp (car a))
1361                  (string-match key (car a)))
1362             (throw 'loop a))
1363         (setq alist (cdr alist))))))
1364
1365 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1366   (let ((case-fold-search case-ignore)
1367         a)
1368     (catch 'loop
1369       (while alist
1370         (setq a (car alist))
1371         (if (and (consp a)
1372                  (stringp (car a))
1373                  (string-match (car a) key))
1374             (throw 'loop a))
1375         (setq alist (cdr alist))))))
1376
1377 (defun elmo-string-assoc (key alist)
1378   (let (a)
1379     (catch 'loop
1380       (while alist
1381         (setq a (car alist))
1382         (if (and (consp a)
1383                  (stringp (car a))
1384                  (string= key (car a)))
1385             (throw 'loop a))
1386         (setq alist (cdr alist))))))
1387
1388 (defun elmo-string-assoc-all (key alist)
1389   (let (matches)
1390     (while alist
1391       (if (string= key (car (car alist)))
1392           (setq matches
1393                 (cons (car alist)
1394                       matches)))
1395       (setq alist (cdr alist)))
1396     matches))
1397
1398 (defun elmo-string-rassoc (key alist)
1399   (let (a)
1400     (catch 'loop
1401       (while alist
1402         (setq a (car alist))
1403         (if (and (consp a)
1404                  (stringp (cdr a))
1405                  (string= key (cdr a)))
1406             (throw 'loop a))
1407         (setq alist (cdr alist))))))
1408
1409 (defun elmo-string-rassoc-all (key alist)
1410   (let (matches)
1411     (while alist
1412       (if (string= key (cdr (car alist)))
1413           (setq matches
1414                 (cons (car alist)
1415                       matches)))
1416       (setq alist (cdr alist)))
1417     matches))
1418
1419 (defun elmo-expand-newtext (newtext original)
1420   (let ((len (length newtext))
1421         (pos 0)
1422         c expanded beg N did-expand)
1423     (while (< pos len)
1424       (setq beg pos)
1425       (while (and (< pos len)
1426                   (not (= (aref newtext pos) ?\\)))
1427         (setq pos (1+ pos)))
1428       (unless (= beg pos)
1429         (push (substring newtext beg pos) expanded))
1430       (when (< pos len)
1431         ;; We hit a \; expand it.
1432         (setq did-expand t
1433               pos (1+ pos)
1434               c (aref newtext pos))
1435         (if (not (or (= c ?\&)
1436                      (and (>= c ?1)
1437                           (<= c ?9))))
1438             ;; \ followed by some character we don't expand.
1439             (push (char-to-string c) expanded)
1440           ;; \& or \N
1441           (if (= c ?\&)
1442               (setq N 0)
1443             (setq N (- c ?0)))
1444           (when (match-beginning N)
1445             (push (substring original (match-beginning N) (match-end N))
1446                   expanded))))
1447       (setq pos (1+ pos)))
1448     (if did-expand
1449         (apply (function concat) (nreverse expanded))
1450       newtext)))
1451
1452 ;;; Folder parser utils.
1453 (defun elmo-parse-token (string &optional seps)
1454   "Parse atom from STRING using SEPS as a string of separator char list."
1455   (let ((len (length string))
1456         (seps (and seps (string-to-char-list seps)))
1457         (i 0)
1458         (sep nil)
1459         content c in)
1460     (if (eq len 0)
1461         (cons "" "")
1462       (while (and (< i len) (or in (null sep)))
1463         (setq c (aref string i))
1464         (cond
1465          ((and in (eq c ?\\))
1466           (setq i (1+ i)
1467                 content (cons (aref string i) content)
1468                 i (1+ i)))
1469          ((eq c ?\")
1470           (setq in (not in)
1471                 i (1+ i)))
1472          (in (setq content (cons c content)
1473                    i (1+ i)))
1474          ((memq c seps)
1475           (setq sep c))
1476          (t (setq content (cons c content)
1477                   i (1+ i)))))
1478       (if in (error "Parse error in quoted"))
1479       (cons (if (null content) "" (char-list-to-string (nreverse content)))
1480             (substring string i)))))
1481
1482 (defun elmo-parse-prefixed-element (prefix string &optional seps)
1483   (if (and (not (eq (length string) 0))
1484            (eq (aref string 0) prefix))
1485       (elmo-parse-token (substring string 1) seps)
1486     (cons "" string)))
1487
1488 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1489 ;;
1490 ;; number          ::= [0-9]+
1491 ;; beg             ::= number
1492 ;; end             ::= number
1493 ;; number-range    ::= "(" beg " . " end ")"      ;; cons cell
1494 ;; number-set-elem ::= number / number-range
1495 ;; number-set      ::= "(" *number-set-elem ")"   ;; list
1496
1497 (defun elmo-number-set-member (number number-set)
1498   "Return non-nil if NUMBER is an element of NUMBER-SET.
1499 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1500   (or (memq number number-set)
1501       (let (found)
1502         (while (and number-set (not found))
1503           (if (and (consp (car number-set))
1504                    (and (<= (car (car number-set)) number)
1505                         (<= number (cdr (car number-set)))))
1506               (setq found t)
1507             (setq number-set (cdr number-set))))
1508         number-set)))
1509
1510 (defun elmo-number-set-append-list (number-set list)
1511   "Append LIST of numbers to the NUMBER-SET.
1512 NUMBER-SET is altered."
1513   (let ((appended number-set))
1514     (while list
1515       (setq appended (elmo-number-set-append appended (car list)))
1516       (setq list (cdr list)))
1517     appended))
1518
1519 (defun elmo-number-set-append (number-set number)
1520   "Append NUMBER to the NUMBER-SET.
1521 NUMBER-SET is altered."
1522   (let ((number-set-1 number-set)
1523         found elem)
1524     (while (and number-set (not found))
1525       (setq elem (car number-set))
1526       (cond
1527        ((and (consp elem)
1528              (eq (+ 1 (cdr elem)) number))
1529         (setcdr elem number)
1530         (setq found t))
1531        ((and (integerp elem)
1532              (eq (+ 1 elem) number))
1533         (setcar number-set (cons elem number))
1534         (setq found t))
1535        ((or (and (integerp elem) (eq elem number))
1536             (and (consp elem)
1537                  (<= (car elem) number)
1538                  (<= number (cdr elem))))
1539         (setq found t)))
1540       (setq number-set (cdr number-set)))
1541     (if (not found)
1542         (setq number-set-1 (nconc number-set-1 (list number))))
1543     number-set-1))
1544
1545 (defun elmo-number-set-delete-list (number-set list)
1546   "Delete LIST of numbers from the NUMBER-SET.
1547 NUMBER-SET is altered."
1548   (let ((deleted number-set))
1549     (dolist (number list)
1550       (setq deleted (elmo-number-set-delete deleted number)))
1551     deleted))
1552
1553 (defun elmo-number-set-delete (number-set number)
1554   "Delete NUMBER from the NUMBER-SET.
1555 NUMBER-SET is altered."
1556   (let* ((curr number-set)
1557          (top (cons 'dummy number-set))
1558          (prev top)
1559          elem found)
1560     (while (and curr (not found))
1561       (setq elem (car curr))
1562       (if (consp elem)
1563           (cond
1564            ((eq (car elem) number)
1565             (if (eq (cdr elem) (1+ number))
1566                 (setcar curr (cdr elem))
1567               (setcar elem (1+ number)))
1568             (setq found t))
1569            ((eq (cdr elem) number)
1570             (if (eq (car elem) (1- number))
1571                 (setcar curr (car elem))
1572               (setcdr elem (1- number)))
1573             (setq found t))
1574            ((and (> number (car elem))
1575                  (< number (cdr elem)))
1576             (setcdr
1577              prev
1578              (nconc
1579               (list
1580                ;; (beg . (1- number))
1581                (let ((new (cons (car elem) (1- number))))
1582                  (if (eq (car new) (cdr new))
1583                      (car new)
1584                    new))
1585                ;; ((1+ number) . end)
1586                (let ((new (cons (1+ number) (cdr elem))))
1587                  (if (eq (car new) (cdr new))
1588                      (car new)
1589                    new)))
1590               (cdr curr)))))
1591         (when (eq elem number)
1592           (setcdr prev (cdr curr))
1593           (setq found t)))
1594       (setq prev curr
1595             curr (cdr curr)))
1596     (cdr top)))
1597
1598 (defun elmo-make-number-list (beg end)
1599   (let (number-list i)
1600     (setq i end)
1601     (while (>= i beg)
1602       (setq number-list (cons i number-list))
1603       (setq i (1- i)))
1604     number-list))
1605
1606 (defun elmo-number-set-to-number-list (number-set)
1607   "Return a number list which corresponds to NUMBER-SET."
1608   (let ((number-list (list 'dummy))
1609         elem)
1610     (while number-set
1611       (setq elem (car number-set))
1612       (cond
1613        ((consp elem)
1614         (nconc number-list (elmo-make-number-list (car elem) (cdr elem))))
1615        ((integerp elem)
1616         (nconc number-list (list elem))))
1617       (setq number-set (cdr number-set)))
1618     (cdr number-list)))
1619
1620 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1621   "*Regexp to filter subfolders."
1622   :type 'regexp
1623   :group 'elmo)
1624
1625 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1626   (let ((root (zerop (length curdir)))
1627         (w32-get-true-file-link-count t) ; for Meadow
1628         attr dirs dir)
1629     (catch 'done
1630       (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1631         (when (and (not (string-match
1632                          elmo-list-subdirectories-ignore-regexp
1633                          file))
1634                    (car (setq attr (file-attributes
1635                                     (expand-file-name file dir)))))
1636           (when (eq one-level 'check) (throw 'done t))
1637           (let ((relpath
1638                  (concat curdir (and (not root) elmo-path-sep) file))
1639                 subdirs)
1640             (setq dirs (nconc dirs
1641                               (if (if elmo-have-link-count (< 2 (nth 1 attr))
1642                                     (setq subdirs
1643                                           (elmo-list-subdirectories-1
1644                                            basedir
1645                                            relpath
1646                                            (if one-level 'check))))
1647                                   (if one-level
1648                                       (list (list relpath))
1649                                     (cons relpath
1650                                           (or subdirs
1651                                               (elmo-list-subdirectories-1
1652                                                basedir
1653                                                relpath
1654                                                nil))))
1655                                 (list relpath)))))))
1656       dirs)))
1657
1658 (defun elmo-list-subdirectories (directory file one-level)
1659   (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1660     (if (zerop (length file))
1661         subdirs
1662       (cons file subdirs))))
1663
1664 (defun elmo-mapcar-list-of-list (func list-of-list)
1665   (mapcar
1666    (lambda (x)
1667      (cond ((listp x) (elmo-mapcar-list-of-list func x))
1668            (t (funcall func x))))
1669    list-of-list))
1670
1671 (defun elmo-map-recursive (function object)
1672   (if (consp object)
1673       (let* ((prev (list 'dummy))
1674              (result prev))
1675         (while (consp object)
1676           (setq prev (setcdr prev (list (elmo-map-recursive function
1677                                                             (car object))))
1678                 object (cdr object)))
1679         (when object
1680           (setcdr prev (funcall function object)))
1681         (cdr result))
1682     (funcall function object)))
1683
1684 (defun elmo-parse (string regexp &optional matchn)
1685   (or matchn (setq matchn 1))
1686   (let (list)
1687     (store-match-data nil)
1688     (while (string-match regexp string (match-end 0))
1689       (setq list (cons (substring string (match-beginning matchn)
1690                                   (match-end matchn)) list)))
1691     (nreverse list)))
1692
1693 ;;; File cache.
1694 (defmacro elmo-make-file-cache (path status)
1695   "PATH is the cache file name.
1696 STATUS is one of 'section, 'entire or nil.
1697  nil means no cache exists.
1698 'section means partial section cache exists.
1699 'entire means entire cache exists.
1700 If the cache is partial file-cache, TYPE is 'partial."
1701   (` (cons (, path) (, status))))
1702
1703 (defmacro elmo-file-cache-path (file-cache)
1704   "Returns the file path of the FILE-CACHE."
1705   (` (car (, file-cache))))
1706
1707 (defmacro elmo-file-cache-status (file-cache)
1708   "Returns the status of the FILE-CACHE."
1709   (` (cdr (, file-cache))))
1710
1711 (defsubst elmo-cache-to-msgid (filename)
1712   (concat "<" (elmo-recover-string-from-filename filename) ">"))
1713
1714 (defsubst elmo-cache-get-path-subr (msgid)
1715   (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1716         (clist (string-to-char-list msgid))
1717         (sum 0))
1718     (while clist
1719       (setq sum (+ sum (car clist)))
1720       (setq clist (cdr clist)))
1721     (format "%c%c"
1722             (nth (% (/ sum 16) 2) chars)
1723             (nth (% sum 16) chars))))
1724
1725 ;;;
1726 (defun elmo-file-cache-get-path (msgid &optional section)
1727   "Get cache path for MSGID.
1728 If optional argument SECTION is specified, partial cache path is returned."
1729   (if (setq msgid (elmo-msgid-to-cache msgid))
1730       (expand-file-name
1731        (if section
1732            (format "%s/%s/%s/%s"
1733                    elmo-cache-directory
1734                    (elmo-cache-get-path-subr msgid)
1735                    msgid
1736                    section)
1737          (format "%s/%s/%s"
1738                  elmo-cache-directory
1739                  (elmo-cache-get-path-subr msgid)
1740                  msgid)))))
1741
1742 (defmacro elmo-file-cache-expand-path (path section)
1743   "Return file name for the file-cache corresponds to the section.
1744 PATH is the file-cache path.
1745 SECTION is the section string."
1746   (` (expand-file-name (or (, section) "") (, path))))
1747
1748 (defun elmo-file-cache-delete (path)
1749   "Delete a cache on PATH."
1750   (when (file-exists-p path)
1751     (if (file-directory-p path)
1752         (progn
1753           (dolist (file (directory-files path t "^[^\\.]"))
1754             (delete-file file))
1755           (delete-directory path))
1756       (delete-file path))
1757     t))
1758
1759 (defun elmo-file-cache-exists-p (msgid)
1760   "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1761   (elmo-file-cache-status (elmo-file-cache-get msgid)))
1762
1763 (defun elmo-file-cache-save (cache-path section)
1764   "Save current buffer as cache on PATH.
1765 Return t if cache is saved successfully."
1766   (condition-case nil
1767       (let ((path (if section (expand-file-name section cache-path)
1768                     cache-path))
1769             files dir)
1770         (if (and (null section)
1771                  (file-directory-p path))
1772             (progn
1773               (setq files (directory-files path t "^[^\\.]"))
1774               (while files
1775                 (delete-file (car files))
1776                 (setq files (cdr files)))
1777               (delete-directory path))
1778           (if (and section
1779                    (not (file-directory-p cache-path)))
1780               (delete-file cache-path)))
1781         (when path
1782           (setq dir (directory-file-name (file-name-directory path)))
1783           (if (not (file-exists-p dir))
1784               (elmo-make-directory dir))
1785           (write-region-as-binary (point-min) (point-max)
1786                                   path nil 'no-msg)
1787           t))
1788     ;; ignore error
1789     (error)))
1790
1791 (defun elmo-file-cache-load (cache-path section)
1792   "Load cache on PATH into the current buffer.
1793 Return t if cache is loaded successfully."
1794   (condition-case nil
1795       (let (cache-file)
1796         (when (and cache-path
1797                    (if (elmo-cache-path-section-p cache-path)
1798                        section
1799                      (null section))
1800                    (setq cache-file (elmo-file-cache-expand-path
1801                                      cache-path
1802                                      section))
1803                    (file-exists-p cache-file))
1804           (insert-file-contents-as-binary cache-file)
1805           t))
1806     ;; igore error
1807     (error)))
1808
1809 (defun elmo-cache-path-section-p (path)
1810   "Return non-nil when PATH is `section' cache path."
1811   (file-directory-p path))
1812
1813 (defun elmo-file-cache-get (msgid &optional section)
1814   "Returns the current file-cache object associated with MSGID.
1815 MSGID is the message-id of the message.
1816 If optional argument SECTION is specified, get partial file-cache object
1817 associated with SECTION."
1818   (if msgid
1819       (let ((path (elmo-cache-get-path msgid)))
1820         (if (and path (file-exists-p path))
1821             (if (elmo-cache-path-section-p path)
1822                 (if section
1823                     (if (file-exists-p (setq path (expand-file-name
1824                                                    section path)))
1825                         (cons path 'section))
1826                   ;; section is not specified but sectional.
1827                   (cons path 'section))
1828               ;; not directory.
1829               (unless section
1830                 (cons path 'entire)))
1831           ;; no cache.
1832           (cons path nil)))))
1833
1834 ;;;
1835 ;; Expire cache.
1836
1837 (defun elmo-cache-expire ()
1838   (interactive)
1839   (let* ((completion-ignore-case t)
1840          (method (completing-read (format "Expire by (%s): "
1841                                           elmo-cache-expire-default-method)
1842                                   '(("size" . "size")
1843                                     ("age" . "age"))
1844                                   nil t)))
1845     (when (string= method "")
1846       (setq method elmo-cache-expire-default-method))
1847     (funcall (intern (concat "elmo-cache-expire-by-" method)))))
1848
1849 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
1850   (let ((str (read-from-minibuffer prompt initial)))
1851     (cond
1852      ((string-match "[0-9]*\\.[0-9]+" str)
1853       (string-to-number str))
1854      ((string-match "[0-9]+" str)
1855       (string-to-number (concat str ".0")))
1856      (t (error "%s is not number" str)))))
1857
1858 (defun elmo-cache-expire-by-size (&optional kbytes)
1859   "Expire cache file by size.
1860 If KBYTES is kilo bytes (This value must be float)."
1861   (interactive)
1862   (let ((size (or kbytes
1863                   (and (interactive-p)
1864                        (elmo-read-float-value-from-minibuffer
1865                         "Enter cache disk size (Kbytes): "
1866                         (number-to-string
1867                          (if (integerp elmo-cache-expire-default-size)
1868                              (float elmo-cache-expire-default-size)
1869                            elmo-cache-expire-default-size))))
1870                   (if (integerp elmo-cache-expire-default-size)
1871                       (float elmo-cache-expire-default-size))))
1872         (count 0)
1873         (Kbytes 1024)
1874         total beginning)
1875     (message "Checking disk usage...")
1876     (setq total (/ (elmo-disk-usage
1877                     elmo-cache-directory) Kbytes))
1878     (setq beginning total)
1879     (message "Checking disk usage...done")
1880     (let ((cfl (elmo-cache-get-sorted-cache-file-list))
1881           (deleted 0)
1882           oldest
1883           cur-size cur-file)
1884       (while (and (<= size total)
1885                   (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
1886         (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
1887         (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
1888         (when (elmo-file-cache-delete cur-file)
1889           (setq count (+ count 1))
1890           (message "%d cache(s) are expired." count))
1891         (setq deleted (+ deleted cur-size))
1892         (setq total (- total cur-size)))
1893       (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
1894                count deleted beginning))))
1895
1896 (defun elmo-cache-make-file-entity (filename path)
1897   (cons filename (elmo-get-last-accessed-time filename path)))
1898
1899 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
1900   (let ((cfl cache-file-list)
1901         flist firsts oldest-entity wonlist)
1902     (while cfl
1903       (setq flist (cdr (car cfl)))
1904       (setq firsts (append firsts (list
1905                                    (cons (car (car cfl))
1906                                          (car flist)))))
1907       (setq cfl (cdr cfl)))
1908 ;;; (prin1 firsts)
1909     (while firsts
1910       (if (and (not oldest-entity)
1911                (cdr (cdr (car firsts))))
1912           (setq oldest-entity (car firsts)))
1913       (if (and (cdr (cdr (car firsts)))
1914                (cdr (cdr oldest-entity))
1915                (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
1916           (setq oldest-entity (car firsts)))
1917       (setq firsts (cdr firsts)))
1918     (setq wonlist (assoc (car oldest-entity) cache-file-list))
1919     (and wonlist
1920          (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
1921     oldest-entity))
1922
1923 (defun elmo-cache-get-sorted-cache-file-list ()
1924   (let ((dirs (directory-files
1925                elmo-cache-directory
1926                t "^[^\\.]"))
1927         (i 0) num
1928         elist
1929         ret-val)
1930     (setq num (length dirs))
1931     (message "Collecting cache info...")
1932     (while dirs
1933       (setq elist (mapcar (lambda (x)
1934                             (elmo-cache-make-file-entity x (car dirs)))
1935                           (directory-files (car dirs) nil "^[^\\.]")))
1936       (setq ret-val (append ret-val
1937                             (list (cons
1938                                    (car dirs)
1939                                    (sort
1940                                     elist
1941                                     (lambda (x y)
1942                                       (< (cdr x)
1943                                          (cdr y))))))))
1944       (when (> num elmo-display-progress-threshold)
1945         (setq i (+ i 1))
1946         (elmo-display-progress
1947          'elmo-cache-get-sorted-cache-file-list "Collecting cache info..."
1948          (/ (* i 100) num)))
1949       (setq dirs (cdr dirs)))
1950     (message "Collecting cache info...done")
1951     ret-val))
1952
1953 (defun elmo-cache-expire-by-age (&optional days)
1954   (let ((age (or (and days (int-to-string days))
1955                  (and (interactive-p)
1956                       (read-from-minibuffer
1957                        (format "Enter days (%s): "
1958                                elmo-cache-expire-default-age)))
1959                  (int-to-string elmo-cache-expire-default-age)))
1960         (dirs (directory-files
1961                elmo-cache-directory
1962                t "^[^\\.]"))
1963         (count 0)
1964         curtime)
1965     (if (string= age "")
1966         (setq age elmo-cache-expire-default-age)
1967       (setq age (string-to-int age)))
1968     (setq curtime (current-time))
1969     (setq curtime (+ (* (nth 0 curtime)
1970                         (float 65536)) (nth 1 curtime)))
1971     (while dirs
1972       (let ((files (directory-files (car dirs) t "^[^\\.]"))
1973             (limit-age (* age 86400)))
1974         (while files
1975           (when (> (- curtime (elmo-get-last-accessed-time (car files)))
1976                    limit-age)
1977             (when (elmo-file-cache-delete (car files))
1978               (setq count (+ 1 count))
1979               (message "%d cache file(s) are expired." count)))
1980           (setq files (cdr files))))
1981       (setq dirs (cdr dirs)))))
1982
1983 ;;;
1984 ;; msgid to path.
1985 (defun elmo-msgid-to-cache (msgid)
1986   (save-match-data
1987     (when (and msgid
1988                (string-match "<\\(.+\\)>$" msgid))
1989       (elmo-replace-string-as-filename (elmo-match-string 1 msgid)))))
1990
1991 (defun elmo-cache-get-path (msgid &optional folder number)
1992   "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
1993   (if (setq msgid (elmo-msgid-to-cache msgid))
1994       (expand-file-name
1995        (expand-file-name
1996         (if folder
1997             (format "%s/%s/%s@%s"
1998                     (elmo-cache-get-path-subr msgid)
1999                     msgid
2000                     (or number "")
2001                     (elmo-safe-filename folder))
2002           (format "%s/%s"
2003                   (elmo-cache-get-path-subr msgid)
2004                   msgid))
2005         elmo-cache-directory))))
2006
2007 ;;;
2008 ;; Warnings.
2009
2010 (static-if (fboundp 'display-warning)
2011     (defmacro elmo-warning (&rest args)
2012       "Display a warning with `elmo' group."
2013       `(display-warning 'elmo (format ,@args)))
2014   (defconst elmo-warning-buffer-name "*elmo warning*")
2015   (defun elmo-warning (&rest args)
2016     "Display a warning. ARGS are passed to `format'."
2017     (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
2018       (goto-char (point-max))
2019       (funcall 'insert (apply 'format (append args '("\n"))))
2020       (ignore-errors (recenter 1))
2021       (display-buffer elmo-warning-buffer-name))))
2022
2023 (defvar elmo-obsolete-variable-alist nil)
2024
2025 (defcustom elmo-obsolete-variable-show-warnings t
2026   "Show warning window if obsolete variable is treated."
2027   :type 'boolean
2028   :group 'elmo)
2029
2030 (defun elmo-define-obsolete-variable (obsolete var)
2031   "Define obsolete variable.
2032 OBSOLETE is a symbol for obsolete variable.
2033 VAR is a symbol for new variable.
2034 Definition is stored in `elmo-obsolete-variable-alist'."
2035   (let ((pair (assq var elmo-obsolete-variable-alist)))
2036     (if pair
2037         (setcdr pair obsolete)
2038       (setq elmo-obsolete-variable-alist
2039             (cons (cons var obsolete)
2040                   elmo-obsolete-variable-alist)))))
2041
2042 (defun elmo-resque-obsolete-variable (obsolete var)
2043   "Resque obsolete variable OBSOLETE as VAR.
2044 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
2045   (when (boundp obsolete)
2046     (static-if (and (fboundp 'defvaralias)
2047                     (subrp (symbol-function 'defvaralias)))
2048         (defvaralias var obsolete)
2049       (set var (symbol-value obsolete)))
2050     (if elmo-obsolete-variable-show-warnings
2051         (elmo-warning "%s is obsolete. Use %s instead."
2052                       (symbol-name obsolete)
2053                       (symbol-name var)))))
2054
2055 (defun elmo-resque-obsolete-variables (&optional alist)
2056   "Resque obsolete variables in ALIST.
2057 ALIST is a list of cons cell of
2058 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
2059 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
2060   (dolist (pair elmo-obsolete-variable-alist)
2061     (elmo-resque-obsolete-variable (cdr pair)
2062                                    (car pair))))
2063
2064 (defsubst elmo-msgdb-get-last-message-id (string)
2065   (if string
2066       (save-match-data
2067         (let (beg)
2068           (elmo-set-work-buf
2069            (insert string)
2070            (goto-char (point-max))
2071            (when (search-backward "<" nil t)
2072              (setq beg (point))
2073              (if (search-forward ">" nil t)
2074                  (elmo-replace-in-string
2075                   (buffer-substring beg (point)) "\n[ \t]*" ""))))))))
2076
2077 (defun elmo-msgdb-get-message-id-from-buffer ()
2078   (let ((msgid (elmo-field-body "message-id")))
2079     (if msgid
2080         (if (string-match "<\\(.+\\)>$" msgid)
2081             msgid
2082           (concat "<" msgid ">"))       ; Invaild message-id.
2083       ;; no message-id, so put dummy msgid.
2084       (concat "<"
2085               (if (elmo-unfold-field-body "date")
2086                   (timezone-make-date-sortable (elmo-unfold-field-body "date"))
2087                 (md5 (string-as-unibyte (buffer-string))))
2088               (nth 1 (eword-extract-address-components
2089                       (or (elmo-field-body "from") "nobody"))) ">"))))
2090
2091 (defun elmo-msgdb-get-references-from-buffer ()
2092   (if elmo-msgdb-prefer-in-reply-to-for-parent
2093       (or (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to"))
2094           (elmo-msgdb-get-last-message-id (elmo-field-body "references")))
2095     (or (elmo-msgdb-get-last-message-id (elmo-field-body "references"))
2096         (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to")))))
2097
2098 (defsubst elmo-msgdb-insert-file-header (file)
2099   "Insert the header of the article."
2100   (let ((beg 0)
2101         insert-file-contents-pre-hook   ; To avoid autoconv-xmas...
2102         insert-file-contents-post-hook
2103         format-alist)
2104     (when (file-exists-p file)
2105       ;; Read until header separator is found.
2106       (while (and (eq elmo-msgdb-file-header-chop-length
2107                       (nth 1
2108                            (insert-file-contents-as-binary
2109                             file nil beg
2110                             (incf beg elmo-msgdb-file-header-chop-length))))
2111                   (prog1 (not (search-forward "\n\n" nil t))
2112                     (goto-char (point-max))))))))
2113
2114 ;;
2115 ;; overview handling
2116 ;;
2117 (defun elmo-multiple-field-body (name &optional boundary)
2118   (save-excursion
2119     (save-restriction
2120       (std11-narrow-to-header boundary)
2121       (goto-char (point-min))
2122       (let ((case-fold-search t)
2123             (field-body nil))
2124         (while (re-search-forward (concat "^" name ":[ \t]*") nil t)
2125           (setq field-body
2126                 (nconc field-body
2127                        (list (buffer-substring-no-properties
2128                               (match-end 0) (std11-field-end))))))
2129         field-body))))
2130
2131 (defun elmo-parse-addresses (string)
2132   (if (null string)
2133       ()
2134     (elmo-set-work-buf
2135       (let (list start s char)
2136         (insert string)
2137         (goto-char (point-min))
2138         (skip-chars-forward "\t\f\n\r ")
2139         (setq start (point))
2140         (while (not (eobp))
2141           (skip-chars-forward "^\"\\,(")
2142           (setq char (following-char))
2143           (cond ((= char ?\\)
2144                  (forward-char 1)
2145                  (if (not (eobp))
2146                      (forward-char 1)))
2147                 ((= char ?,)
2148                  (setq s (buffer-substring start (point)))
2149                  (if (or (null (string-match "^[\t\f\n\r ]+$" s))
2150                          (not (string= s "")))
2151                      (setq list (cons s list)))
2152                  (skip-chars-forward ",\t\f\n\r ")
2153                  (setq start (point)))
2154                 ((= char ?\")
2155                  (re-search-forward "[^\\]\"" nil 0))
2156                 ((= char ?\()
2157                  (let ((parens 1))
2158                    (forward-char 1)
2159                    (while (and (not (eobp)) (not (zerop parens)))
2160                      (re-search-forward "[()]" nil 0)
2161                      (cond ((or (eobp)
2162                                 (= (char-after (- (point) 2)) ?\\)))
2163                            ((= (preceding-char) ?\()
2164                             (setq parens (1+ parens)))
2165                            (t
2166                             (setq parens (1- parens)))))))))
2167         (setq s (buffer-substring start (point)))
2168         (if (and (null (string-match "^[\t\f\n\r ]+$" s))
2169                  (not (string= s "")))
2170             (setq list (cons s list)))
2171         (nreverse list)))))
2172
2173 ;;; Queue.
2174 (defvar elmo-dop-queue-filename "queue"
2175   "*Disconnected operation queue is saved in this file.")
2176
2177 (defun elmo-dop-queue-load ()
2178   (setq elmo-dop-queue
2179         (elmo-object-load
2180          (expand-file-name elmo-dop-queue-filename
2181                            elmo-msgdb-directory))))
2182
2183 (defun elmo-dop-queue-save ()
2184   (elmo-object-save
2185    (expand-file-name elmo-dop-queue-filename
2186                      elmo-msgdb-directory)
2187    elmo-dop-queue))
2188
2189 (if (and (fboundp 'regexp-opt)
2190          (not (featurep 'xemacs)))
2191     (defalias 'elmo-regexp-opt 'regexp-opt)
2192   (defun elmo-regexp-opt (strings &optional paren)
2193     "Return a regexp to match a string in STRINGS.
2194 Each string should be unique in STRINGS and should not contain any regexps,
2195 quoted or not.  If optional PAREN is non-nil, ensure that the returned regexp
2196 is enclosed by at least one regexp grouping construct."
2197     (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
2198       (concat open-paren (mapconcat 'regexp-quote strings "\\|")
2199               close-paren))))
2200
2201 (require 'product)
2202 (product-provide (provide 'elmo-util) (require 'elmo-version))
2203
2204 ;;; elmo-util.el ends here