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