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