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