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