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