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