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