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