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