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