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