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