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