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