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