* elmo.el (elmo-folder-list-importants): Rewirte. Use global mark
[elisp/wanderlust.git] / elmo / elmo-util.el
1 ;;; elmo-util.el -- Utilities for Elmo.
2
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
4
5 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
6 ;; Keywords: mail, net news
7
8 ;; This file is part of ELMO (Elisp Library for Message Orchestration).
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14 ;;
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19 ;;
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24 ;;
25
26 ;;; Commentary:
27 ;; 
28
29 ;;; Code:
30 ;; 
31
32 (eval-when-compile (require 'cl))
33 (require 'elmo-vars)
34 (require 'elmo-date)
35 (require 'mcharset)
36 (require 'pces)
37 (require 'std11)
38 (require 'eword-decode)
39 (require 'utf7)
40 (require 'poem)
41
42 (defmacro elmo-set-buffer-multibyte (flag)
43   "Set the multibyte flag of the current buffer to FLAG."
44   (cond ((boundp 'MULE)
45          (list 'setq 'mc-flag flag))
46         ((featurep 'xemacs)
47          flag)
48         ((and (boundp 'emacs-major-version) (>= emacs-major-version 20))
49          (list 'set-buffer-multibyte flag))
50         (t
51          flag)))
52
53 (defvar elmo-work-buf-name " *elmo work*")
54 (defvar elmo-temp-buf-name " *elmo temp*")
55
56 (or (boundp 'default-enable-multibyte-characters)
57     (defvar default-enable-multibyte-characters (featurep 'mule)
58       "The mock variable except for Emacs 20."))
59
60 (defun elmo-base64-encode-string (string &optional no-line-break))
61 (defun elmo-base64-decode-string (string))
62
63 ;; base64 encoding/decoding
64 (require 'mel)
65 (fset 'elmo-base64-encode-string
66       (mel-find-function 'mime-encode-string "base64"))
67 (fset 'elmo-base64-decode-string
68       (mel-find-function 'mime-decode-string "base64"))
69
70 ;; Any Emacsen may have add-name-to-file(), because loadup.el requires it. :-p
71 ;; Check make-symbolic-link() instead.  -- 981002 by Fuji
72 (if (fboundp 'make-symbolic-link)  ;; xxx
73     (defalias 'elmo-add-name-to-file 'add-name-to-file)
74   (defun elmo-add-name-to-file
75     (filename newname &optional ok-if-already-exists)
76     (copy-file filename newname ok-if-already-exists t)))
77
78 ;; 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-condition-match (file condition number number-list)
900   (elmo-set-work-buf
901    (as-binary-input-file (insert-file-contents file))
902    (elmo-set-buffer-multibyte default-enable-multibyte-characters)
903    ;; Should consider charset?
904    (decode-mime-charset-region (point-min)(point-max) elmo-mime-charset)
905    (elmo-buffer-field-condition-match condition number number-list)))
906
907 (defmacro elmo-get-hash-val (string hashtable)
908   (let ((sym (list 'intern-soft string hashtable)))
909     (list 'if (list 'boundp sym)
910        (list 'symbol-value sym))))
911
912 (defmacro elmo-set-hash-val (string value hashtable)
913   (list 'set (list 'intern string hashtable) value))
914
915 (defmacro elmo-clear-hash-val (string hashtable)
916   (static-if (fboundp 'unintern)
917       (list 'unintern string hashtable)
918     (list 'makunbound (list 'intern string hashtable))))
919
920 (defmacro elmo-unintern (string)
921   "`unintern' symbol named STRING,  When can use `unintern'.
922 Emacs 19.28 or earlier does not have `unintern'."
923   (static-if (fboundp 'unintern)
924       (list 'unintern string)))
925
926 (defun elmo-make-hash (&optional hashsize)
927   "Make a new hash table which have HASHSIZE size."
928   (make-vector
929    (if hashsize 
930        (max
931         ;; Prime numbers as lengths tend to result in good
932         ;; hashing; lengths one less than a power of two are 
933         ;; also good.
934         (min
935          (let ((i 1))
936            (while (< (- i 1) hashsize)
937              (setq i (* 2 i)))
938            (- i 1))
939          elmo-hash-maximum-size)
940         elmo-hash-minimum-size)
941      elmo-hash-minimum-size)
942    0))
943
944 (defsubst elmo-mime-string (string)
945   "Normalize MIME encoded STRING."
946     (and string
947          (let (str)
948            (elmo-set-work-buf
949             (elmo-set-buffer-multibyte default-enable-multibyte-characters)
950             (setq str (eword-decode-string
951                        (decode-mime-charset-string string elmo-mime-charset)))
952             (setq str (encode-mime-charset-string str elmo-mime-charset))
953             (elmo-set-buffer-multibyte nil)
954             str))))
955
956 (defsubst elmo-collect-field (beg end downcase-field-name)
957   (save-excursion
958     (save-restriction
959       (narrow-to-region beg end)
960       (goto-char (point-min))
961       (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
962             dest name body)
963         (while (re-search-forward regexp nil t)
964           (setq name (buffer-substring-no-properties
965                       (match-beginning 1)(1- (match-end 1))))
966           (if downcase-field-name
967               (setq name (downcase name)))
968           (setq body (buffer-substring-no-properties
969                       (match-end 0) (std11-field-end)))
970           (or (assoc name dest)
971               (setq dest (cons (cons name body) dest))))
972         dest))))
973
974 (defsubst elmo-collect-field-from-string (string downcase-field-name)
975   (with-temp-buffer
976     (insert string)
977     (goto-char (point-min))
978     (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
979           dest name body)
980       (while (re-search-forward regexp nil t)
981         (setq name (buffer-substring-no-properties
982                     (match-beginning 1)(1- (match-end 1))))
983         (if downcase-field-name
984             (setq name (downcase name)))
985         (setq body (buffer-substring-no-properties
986                     (match-end 0) (std11-field-end)))
987         (or (assoc name dest)
988             (setq dest (cons (cons name body) dest))))
989       dest)))
990
991 (defun elmo-safe-filename (folder)
992   (elmo-replace-in-string
993    (elmo-replace-in-string
994     (elmo-replace-in-string folder "/" " ")
995     ":" "__")
996    "|" "_or_"))
997
998 (defvar elmo-filename-replace-chars nil)
999
1000 (defsubst elmo-replace-string-as-filename (msgid)
1001   "Replace string as filename."
1002   (setq msgid (elmo-replace-in-string msgid " " "  "))
1003   (if (null elmo-filename-replace-chars)
1004       (setq elmo-filename-replace-chars
1005             (regexp-quote (mapconcat
1006                            'car elmo-filename-replace-string-alist ""))))
1007   (while (string-match (concat "[" elmo-filename-replace-chars "]")
1008                        msgid)
1009     (setq msgid (concat
1010                  (substring msgid 0 (match-beginning 0))
1011                  (cdr (assoc
1012                        (substring msgid
1013                                   (match-beginning 0) (match-end 0))
1014                        elmo-filename-replace-string-alist))
1015                  (substring msgid (match-end 0)))))
1016   msgid)
1017
1018 (defsubst elmo-recover-string-from-filename (filename)
1019   "Recover string from FILENAME."
1020   (let (tmp result)
1021     (while (string-match " " filename)
1022       (setq tmp (substring filename
1023                            (match-beginning 0)
1024                            (+ (match-end 0) 1)))
1025       (if (string= tmp "  ")
1026           (setq tmp " ")
1027         (setq tmp (car (rassoc tmp
1028                                elmo-filename-replace-string-alist))))
1029       (setq result
1030             (concat result
1031                     (substring filename 0 (match-beginning 0))
1032                     tmp))
1033       (setq filename (substring filename (+ (match-end 0) 1))))
1034     (concat result filename)))
1035
1036 (defsubst elmo-copy-file (src dst)
1037   (condition-case err
1038       (elmo-add-name-to-file src dst t)
1039     (error (copy-file src dst t))))
1040
1041 (defsubst elmo-buffer-exists-p (buffer)
1042   (if (bufferp buffer)
1043       (buffer-live-p buffer)
1044     (get-buffer buffer)))
1045
1046 (defsubst elmo-kill-buffer (buffer)
1047   (when (elmo-buffer-exists-p buffer)
1048     (kill-buffer buffer)))
1049
1050 (defun elmo-delete-if (pred lst)
1051   "Return new list contain items which don't satisfy PRED in LST."
1052   (let (result)
1053     (while lst
1054       (unless (funcall pred (car lst))
1055         (setq result (nconc result (list (car lst)))))
1056       (setq lst (cdr lst)))
1057     result))
1058
1059 (defun elmo-list-delete (list1 list2)
1060   "Delete by side effect any occurrences equal to elements of LIST1 from LIST2.
1061 Return the modified LIST2.  Deletion is done with `delete'.
1062 Write `(setq foo (elmo-list-delete bar foo))' to be sure of changing
1063 the value of `foo'."
1064   (while list1
1065     (setq list2 (delete (car list1) list2))
1066     (setq list1 (cdr list1)))
1067   list2)
1068
1069 (defun elmo-list-member (list1 list2)
1070   "If any element of LIST1 is member of LIST2, return t."
1071   (catch 'done
1072     (while list1
1073       (if (member (car list1) list2)
1074           (throw 'done t))
1075       (setq list1 (cdr list1)))))
1076
1077 (defun elmo-count-matches (regexp beg end)
1078   (let ((count 0))
1079     (save-excursion
1080       (goto-char beg)
1081       (while (re-search-forward regexp end t)
1082         (setq count (1+ count)))
1083       count)))
1084
1085 (if (fboundp 'display-error)
1086     (defalias 'elmo-display-error 'display-error)
1087   (defun elmo-display-error (error-object stream)
1088     "A tiny function to display ERROR-OBJECT to the STREAM."
1089     (let ((first t)
1090           (errobj error-object)
1091           err-mes)
1092       (while errobj
1093         (setq err-mes (concat err-mes (format
1094                                        (if (stringp (car errobj))
1095                                            "%s"
1096                                          (if (boundp 'nemacs-version)
1097                                              "%s"
1098                                            "%S")) (car errobj))))
1099         (setq errobj (cdr errobj))
1100         (if errobj (setq err-mes (concat err-mes (if first ": " ", "))))
1101         (setq first nil))
1102       (princ err-mes stream))))
1103
1104 (if (fboundp 'define-error)
1105     (defalias 'elmo-define-error 'define-error)
1106   (defun elmo-define-error (error doc &optional parents)
1107     (or parents
1108         (setq parents 'error))
1109     (let ((conds (get parents 'error-conditions)))
1110       (or conds
1111           (error "Not an error symbol: %s" error))
1112       (setplist error
1113                 (list 'error-message doc
1114                       'error-conditions (cons error conds))))))
1115
1116 (cond ((fboundp 'progress-feedback-with-label)
1117        (defalias 'elmo-display-progress 'progress-feedback-with-label))
1118       ((fboundp 'lprogress-display)
1119        (defalias 'elmo-display-progress 'lprogress-display))
1120       (t
1121        (defun elmo-display-progress (label format &optional value &rest args)
1122          "Print a progress message."
1123          (if (and (null format) (null args))
1124              (message nil)
1125            (apply (function message) (concat format " %d%%")
1126                   (nconc args (list value)))))))
1127
1128 (defun elmo-time-expire (before-time diff-time)
1129   (let* ((current (current-time))
1130          (rest (when (< (nth 1 current) (nth 1 before-time))
1131                  (expt 2 16)))
1132          diff)
1133     (setq diff
1134           (list (- (+ (car current) (if rest -1 0)) (car before-time))
1135                 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1136     (and (eq (car diff) 0)
1137          (< diff-time (nth 1 diff)))))
1138
1139 (if (fboundp 'std11-fetch-field)
1140     (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1141   (defalias 'elmo-field-body 'std11-field-body))
1142
1143 (defmacro elmo-string (string)
1144   "STRING without text property."
1145   (` (let ((obj (copy-sequence (, string))))
1146        (set-text-properties 0 (length obj) nil obj)
1147        obj)))
1148
1149 (defun elmo-flatten (list-of-list)
1150   "Flatten LIST-OF-LIST."
1151   (unless (null list-of-list)
1152     (append (if (and (car list-of-list)
1153                      (listp (car list-of-list)))
1154                 (car list-of-list)
1155               (list (car list-of-list)))
1156             (elmo-flatten (cdr list-of-list)))))
1157
1158 (defun elmo-y-or-n-p (prompt &optional auto default)
1159   "Same as `y-or-n-p'.
1160 But if optional argument AUTO is non-nil, DEFAULT is returned."
1161   (if auto
1162       default
1163     (y-or-n-p prompt)))
1164
1165 (defun elmo-string-member (string slist)
1166   "Return t if STRING is a member of the SLIST."
1167   (catch 'found
1168     (while slist
1169       (if (and (stringp (car slist))
1170                (string= string (car slist)))
1171           (throw 'found t))
1172       (setq slist (cdr slist)))))
1173
1174 (defun elmo-string-match-member (str list &optional case-ignore)
1175   (let ((case-fold-search case-ignore))
1176     (catch 'member
1177       (while list
1178         (if (string-match (car list) str)
1179             (throw 'member (car list)))
1180         (setq list (cdr list))))))
1181
1182 (defun elmo-string-matched-member (str list &optional case-ignore)
1183   (let ((case-fold-search case-ignore))
1184     (catch 'member
1185       (while list
1186         (if (string-match str (car list))
1187             (throw 'member (car list)))
1188         (setq list (cdr list))))))
1189
1190 (defsubst elmo-string-delete-match (string pos)
1191   (concat (substring string
1192                      0 (match-beginning pos))
1193           (substring string
1194                      (match-end pos)
1195                      (length string))))
1196
1197 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1198   (let ((case-fold-search case-ignore)
1199         a)
1200     (catch 'loop
1201       (while alist
1202         (setq a (car alist))
1203         (if (and (consp a)
1204                  (stringp (car a))
1205                  (string-match key (car a)))
1206             (throw 'loop a))
1207         (setq alist (cdr alist))))))
1208
1209 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1210   (let ((case-fold-search case-ignore)
1211         a)
1212     (catch 'loop
1213       (while alist
1214         (setq a (car alist))
1215         (if (and (consp a)
1216                  (stringp (car a))
1217                  (string-match (car a) key))
1218             (throw 'loop a))
1219         (setq alist (cdr alist))))))
1220
1221 (defun elmo-string-assoc (key alist)
1222   (let (a)
1223     (catch 'loop
1224       (while alist
1225         (setq a (car alist))
1226         (if (and (consp a)
1227                  (stringp (car a))
1228                  (string= key (car a)))
1229             (throw 'loop a))
1230         (setq alist (cdr alist))))))
1231
1232 (defun elmo-string-rassoc (key alist)
1233   (let (a)
1234     (catch 'loop
1235       (while alist
1236         (setq a (car alist))
1237         (if (and (consp a)
1238                  (stringp (cdr a))
1239                  (string= key (cdr a)))
1240             (throw 'loop a))
1241         (setq alist (cdr alist))))))
1242
1243 (defun elmo-string-rassoc-all (key alist)
1244   (let (matches)
1245     (while alist
1246       (if (string= key (cdr (car alist)))
1247           (setq matches
1248                 (cons (car alist)
1249                       matches)))
1250       (setq alist (cdr alist)))
1251     matches))
1252
1253 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1254 ;; 
1255 ;; number          ::= [0-9]+
1256 ;; beg             ::= number
1257 ;; end             ::= number
1258 ;; number-range    ::= "(" beg " . " end ")"      ;; cons cell
1259 ;; number-set-elem ::= number / number-range
1260 ;; number-set      ::= "(" *number-set-elem ")"   ;; list
1261
1262 (defun elmo-number-set-member (number number-set)
1263   "Return non-nil if NUMBER is an element of NUMBER-SET.
1264 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1265   (or (memq number number-set)
1266       (let (found)
1267         (while (and number-set (not found))
1268           (if (and (consp (car number-set))
1269                    (and (<= (car (car number-set)) number)
1270                         (<= number (cdr (car number-set)))))
1271               (setq found t)
1272             (setq number-set (cdr number-set))))
1273         number-set)))
1274
1275 (defun elmo-number-set-append-list (number-set list)
1276   "Append LIST of numbers to the NUMBER-SET.
1277 NUMBER-SET is altered."
1278   (let ((appended number-set))
1279     (while list
1280       (setq appended (elmo-number-set-append appended (car list)))
1281       (setq list (cdr list)))
1282     appended))
1283
1284 (defun elmo-number-set-append (number-set number)
1285   "Append NUMBER to the NUMBER-SET.
1286 NUMBER-SET is altered."
1287   (let ((number-set-1 number-set)
1288         found elem)
1289     (while (and number-set (not found))
1290       (setq elem (car number-set))
1291       (cond
1292        ((and (consp elem)
1293              (eq (+ 1 (cdr elem)) number))
1294         (setcdr elem number)
1295         (setq found t))
1296        ((and (integerp elem)
1297              (eq (+ 1 elem) number))
1298         (setcar number-set (cons elem number))
1299         (setq found t))
1300        ((or (and (integerp elem) (eq elem number))
1301             (and (consp elem)
1302                  (<= (car elem) number)
1303                  (<= number (cdr elem))))
1304         (setq found t)))
1305       (setq number-set (cdr number-set)))
1306     (if (not found)
1307         (setq number-set-1 (nconc number-set-1 (list number))))
1308     number-set-1))
1309
1310 (defun elmo-number-set-to-number-list (number-set)
1311   "Return a number list which corresponds to NUMBER-SET."
1312   (let (number-list elem i)
1313     (while number-set
1314       (setq elem (car number-set))
1315       (cond
1316        ((consp elem)
1317         (setq i (car elem))
1318         (while (<= i (cdr elem))
1319           (setq number-list (cons i number-list))
1320           (incf i)))
1321        ((integerp elem)
1322         (setq number-list (cons elem number-list))))
1323       (setq number-set (cdr number-set)))
1324     (nreverse number-list)))
1325
1326 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1327   "*Regexp to filter subfolders."
1328   :type 'regexp
1329   :group 'elmo)
1330
1331 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1332   (let ((root (zerop (length curdir)))
1333         (w32-get-true-file-link-count t) ; for Meadow
1334         attr dirs dir)
1335     (catch 'done
1336       (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1337         (when (and (not (string-match
1338                          elmo-list-subdirectories-ignore-regexp
1339                          file))
1340                    (car (setq attr (file-attributes
1341                                     (expand-file-name file dir)))))
1342           (when (eq one-level 'check) (throw 'done t))
1343           (let ((relpath
1344                  (concat curdir (and (not root) elmo-path-sep) file))
1345                 subdirs)
1346             (setq dirs (nconc dirs
1347                               (if (if elmo-have-link-count (< 2 (nth 1 attr))
1348                                     (setq subdirs
1349                                           (elmo-list-subdirectories-1
1350                                            basedir
1351                                            relpath
1352                                            (if one-level 'check))))
1353                                   (if one-level
1354                                       (list (list relpath))
1355                                     (cons relpath
1356                                           (or subdirs
1357                                               (elmo-list-subdirectories-1
1358                                                basedir
1359                                                relpath
1360                                                nil))))
1361                                 (list relpath)))))))
1362       dirs)))
1363
1364 (defun elmo-list-subdirectories (directory file one-level)
1365   (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1366     (if (zerop (length file))
1367         subdirs
1368       (cons file subdirs))))
1369
1370 (defun elmo-mapcar-list-of-list (func list-of-list)
1371   (mapcar
1372    (lambda (x)
1373      (cond ((listp x) (elmo-mapcar-list-of-list func x))
1374            (t (funcall func x))))
1375    list-of-list))
1376
1377 (defun elmo-parse (string regexp &optional matchn)
1378   (or matchn (setq matchn 1))
1379   (let (list)
1380     (store-match-data nil)
1381     (while (string-match regexp string (match-end 0))
1382       (setq list (cons (substring string (match-beginning matchn)
1383                                   (match-end matchn)) list)))
1384     (nreverse list)))
1385
1386 ;;; File cache.
1387 (defmacro elmo-make-file-cache (path status)
1388   "PATH is the cache file name.
1389 STATUS is one of 'section, 'entire or nil.
1390  nil means no cache exists.
1391 'section means partial section cache exists.
1392 'entire means entire cache exists.
1393 If the cache is partial file-cache, TYPE is 'partial."
1394   (` (cons (, path) (, status))))
1395
1396 (defmacro elmo-file-cache-path (file-cache)
1397   "Returns the file path of the FILE-CACHE."
1398   (` (car (, file-cache))))
1399
1400 (defmacro elmo-file-cache-status (file-cache)
1401   "Returns the status of the FILE-CACHE."
1402   (` (cdr (, file-cache))))
1403
1404 (defsubst elmo-cache-to-msgid (filename)
1405   (concat "<" (elmo-recover-string-from-filename filename) ">"))
1406
1407 (defsubst elmo-cache-get-path-subr (msgid)
1408   (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1409         (clist (string-to-char-list msgid))
1410         (sum 0))
1411     (while clist
1412       (setq sum (+ sum (car clist)))
1413       (setq clist (cdr clist)))
1414     (format "%c%c"
1415             (nth (% (/ sum 16) 2) chars)
1416             (nth (% sum 16) chars))))
1417
1418 (defun elmo-file-cache-get-path (msgid &optional section)
1419   "Get cache path for MSGID.
1420 If optional argument SECTION is specified, partial cache path is returned."
1421   (if (setq msgid (elmo-msgid-to-cache msgid))
1422       (expand-file-name
1423        (if section
1424            (format "%s/%s/%s/%s/%s"
1425                    elmo-msgdb-dir
1426                    elmo-cache-dirname
1427                    (elmo-cache-get-path-subr msgid)
1428                    msgid
1429                    section)
1430          (format "%s/%s/%s/%s"
1431                  elmo-msgdb-dir
1432                  elmo-cache-dirname
1433                  (elmo-cache-get-path-subr msgid)
1434                  msgid)))))
1435
1436 (defmacro elmo-file-cache-expand-path (path section)
1437   "Return file name for the file-cache corresponds to the section.
1438 PATH is the file-cache path.
1439 SECTION is the section string."
1440   (` (expand-file-name (or (, section) "") (, path))))
1441
1442 (defun elmo-file-cache-delete (path)
1443   "Delete a cache on PATH."
1444   (let (files)
1445     (when (file-exists-p path)
1446       (if (file-directory-p path)
1447           (progn
1448             (setq files (directory-files path t "^[^\\.]"))
1449             (while files
1450               (delete-file (car files))
1451               (setq files (cdr files)))
1452             (delete-directory path))
1453         (delete-file path)))))
1454
1455 (defun elmo-file-cache-exists-p (msgid)
1456   "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1457   (elmo-file-cache-status (elmo-file-cache-get msgid)))
1458
1459 (defun elmo-file-cache-save (cache-path section)
1460   "Save current buffer as cache on PATH.
1461 Return t if cache is saved successfully."
1462   (condition-case nil
1463       (let ((path (if section (expand-file-name section cache-path)
1464                     cache-path))
1465             files dir)
1466         (if (and (null section)
1467                  (file-directory-p path))
1468             (progn
1469               (setq files (directory-files path t "^[^\\.]"))
1470               (while files
1471                 (delete-file (car files))
1472                 (setq files (cdr files)))
1473               (delete-directory path))
1474           (if (and section
1475                    (not (file-directory-p cache-path)))
1476               (delete-file cache-path)))
1477         (when path
1478           (setq dir (directory-file-name (file-name-directory path)))
1479           (if (not (file-exists-p dir))
1480               (elmo-make-directory dir))
1481           (write-region-as-binary (point-min) (point-max)
1482                                   path nil 'no-msg)
1483           t))
1484     ;; ignore error
1485     (error)))
1486
1487 (defun elmo-file-cache-get (msgid &optional section)
1488   "Returns the current file-cache object associated with MSGID.
1489 MSGID is the message-id of the message.
1490 If optional argument SECTION is specified, get partial file-cache object
1491 associated with SECTION."
1492   (if msgid
1493       (let ((path (elmo-cache-get-path msgid)))
1494         (if (and path (file-exists-p path))
1495             (if (file-directory-p path)
1496                 (if section
1497                     (if (file-exists-p (setq path (expand-file-name
1498                                                    section path)))
1499                         (cons path 'section))
1500                   ;; section is not specified but sectional.
1501                   (cons path 'section))
1502               ;; not directory.
1503               (unless section
1504                 (cons path 'entire)))
1505           ;; no cache.
1506           (cons path nil)))))
1507
1508 ;;;
1509 ;; Expire cache.
1510
1511 (defun elmo-cache-expire ()
1512   (interactive)
1513   (let* ((completion-ignore-case t)
1514          (method (completing-read (format "Expire by (%s): "
1515                                           elmo-cache-expire-default-method)
1516                                   '(("size" . "size")
1517                                     ("age" . "age")))))
1518     (if (string= method "")
1519         (setq method elmo-cache-expire-default-method))
1520     (funcall (intern (concat "elmo-cache-expire-by-" method)))))
1521
1522 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
1523   (let ((str (read-from-minibuffer prompt initial)))
1524     (cond
1525      ((string-match "[0-9]*\\.[0-9]+" str)
1526       (string-to-number str))
1527      ((string-match "[0-9]+" str)
1528       (string-to-number (concat str ".0")))
1529      (t (error "%s is not number" str)))))
1530
1531 (defun elmo-cache-expire-by-size (&optional kbytes)
1532   "Expire cache file by size.
1533 If KBYTES is kilo bytes (This value must be float)."
1534   (interactive)
1535   (let ((size (or kbytes
1536                   (and (interactive-p)
1537                        (elmo-read-float-value-from-minibuffer
1538                         "Enter cache disk size (Kbytes): "
1539                         (number-to-string
1540                          (if (integerp elmo-cache-expire-default-size)
1541                              (float elmo-cache-expire-default-size)
1542                            elmo-cache-expire-default-size))))
1543                   (if (integerp elmo-cache-expire-default-size)
1544                       (float elmo-cache-expire-default-size))))
1545         (count 0)
1546         (Kbytes 1024)
1547         total beginning)
1548     (message "Checking disk usage...")
1549     (setq total (/ (elmo-disk-usage
1550                     (expand-file-name
1551                      elmo-cache-dirname elmo-msgdb-dir)) Kbytes))
1552     (setq beginning total)
1553     (message "Checking disk usage...done")
1554     (let ((cfl (elmo-cache-get-sorted-cache-file-list))
1555           (deleted 0)
1556           oldest
1557           cur-size cur-file)
1558       (while (and (<= size total)
1559                   (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
1560         (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
1561         (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
1562         (when (elmo-file-cache-delete cur-file)
1563           (setq count (+ count 1))
1564           (message "%d cache(s) are expired." count))
1565         (setq deleted (+ deleted cur-size))
1566         (setq total (- total cur-size)))
1567       (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
1568                count deleted beginning))))
1569
1570 (defun elmo-cache-make-file-entity (filename path)
1571   (cons filename (elmo-get-last-accessed-time filename path)))
1572
1573 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
1574   (let ((cfl cache-file-list)
1575         flist firsts oldest-entity wonlist)
1576     (while cfl
1577       (setq flist (cdr (car cfl)))
1578       (setq firsts (append firsts (list
1579                                    (cons (car (car cfl))
1580                                          (car flist)))))
1581       (setq cfl (cdr cfl)))
1582 ;;; (prin1 firsts)
1583     (while firsts
1584       (if (and (not oldest-entity)
1585                (cdr (cdr (car firsts))))
1586           (setq oldest-entity (car firsts)))
1587       (if (and (cdr (cdr (car firsts)))
1588                (cdr (cdr oldest-entity))
1589                (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
1590           (setq oldest-entity (car firsts)))
1591       (setq firsts (cdr firsts)))
1592     (setq wonlist (assoc (car oldest-entity) cache-file-list))
1593     (and wonlist
1594          (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
1595     oldest-entity))
1596
1597 (defun elmo-cache-get-sorted-cache-file-list ()
1598   (let ((dirs (directory-files
1599                (expand-file-name elmo-cache-dirname elmo-msgdb-dir)
1600                t "^[^\\.]"))
1601         (i 0) num
1602         elist
1603         ret-val)
1604     (setq num (length dirs))
1605     (message "Collecting cache info...")
1606     (while dirs
1607       (setq elist (mapcar (lambda (x)
1608                             (elmo-cache-make-file-entity x (car dirs)))
1609                           (directory-files (car dirs) nil "^[^\\.]")))
1610       (setq ret-val (append ret-val
1611                             (list (cons
1612                                    (car dirs)
1613                                    (sort
1614                                     elist
1615                                     (lambda (x y)
1616                                       (< (cdr x)
1617                                          (cdr y))))))))
1618       (when (> num elmo-display-progress-threshold)
1619         (setq i (+ i 1))
1620         (elmo-display-progress
1621          'elmo-cache-get-sorted-cache-file-list "Collecting cache info..."
1622          (/ (* i 100) num)))
1623       (setq dirs (cdr dirs)))
1624     (message "Collecting cache info...done")
1625     ret-val))
1626
1627 (defun elmo-cache-expire-by-age (&optional days)
1628   (let ((age (or (and days (int-to-string days))
1629                  (and (interactive-p)
1630                       (read-from-minibuffer
1631                        (format "Enter days (%s): "
1632                                elmo-cache-expire-default-age)))
1633                  (int-to-string elmo-cache-expire-default-age)))
1634         (dirs (directory-files
1635                (expand-file-name elmo-cache-dirname elmo-msgdb-dir)
1636                t "^[^\\.]"))
1637         (count 0)
1638         curtime)
1639     (if (string= age "")
1640         (setq age elmo-cache-expire-default-age)
1641       (setq age (string-to-int age)))
1642     (setq curtime (current-time))
1643     (setq curtime (+ (* (nth 0 curtime)
1644                         (float 65536)) (nth 1 curtime)))
1645     (while dirs
1646       (let ((files (directory-files (car dirs) t "^[^\\.]"))
1647             (limit-age (* age 86400)))
1648         (while files
1649           (when (> (- curtime (elmo-get-last-accessed-time (car files)))
1650                    limit-age)
1651             (when (elmo-file-cache-delete (car files))
1652               (setq count (+ 1 count))
1653               (message "%d cache file(s) are expired." count)))
1654           (setq files (cdr files))))
1655       (setq dirs (cdr dirs)))))
1656
1657 ;;;
1658 ;; msgid to path.
1659 (defun elmo-msgid-to-cache (msgid)
1660   (when (and msgid
1661              (string-match "<\\(.+\\)>$" msgid))
1662     (elmo-replace-string-as-filename (elmo-match-string 1 msgid))))
1663
1664 (defun elmo-cache-get-path (msgid &optional folder number)
1665   "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
1666   (if (setq msgid (elmo-msgid-to-cache msgid))
1667       (expand-file-name
1668        (expand-file-name
1669         (if folder
1670             (format "%s/%s/%s@%s"
1671                     (elmo-cache-get-path-subr msgid)
1672                     msgid
1673                     (or number "")
1674                     (elmo-safe-filename folder))
1675           (format "%s/%s"
1676                   (elmo-cache-get-path-subr msgid)
1677                   msgid))
1678         (expand-file-name elmo-cache-dirname
1679                           elmo-msgdb-dir)))))
1680
1681 ;;;
1682 ;; Warnings.
1683
1684 (defconst elmo-warning-buffer-name "*elmo warning*")
1685
1686 (defun elmo-warning (&rest args)
1687   "Display a warning, making warning message by passing all args to `insert'."
1688   (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
1689     (goto-char (point-max))
1690     (apply 'insert (append args '("\n")))
1691     (recenter 1))
1692   (display-buffer elmo-warning-buffer-name))
1693
1694 (defvar elmo-obsolete-variable-alist nil)
1695 (defvar elmo-obsolete-variable-show-warnings nil)
1696
1697 (defun elmo-define-obsolete-variable (obsolete var)
1698   "Define obsolete variable.
1699 OBSOLETE is a symbol for obsolete variable.
1700 VAR is a symbol for new variable.
1701 Definition is stored in `elmo-obsolete-variable-alist'."
1702   (let ((pair (assq var elmo-obsolete-variable-alist)))
1703     (if pair
1704         (setcdr pair obsolete)
1705       (setq elmo-obsolete-variable-alist
1706             (cons (cons var obsolete)
1707                   elmo-obsolete-variable-alist)))))
1708
1709 (defun elmo-resque-obsolete-variable (obsolete var)
1710   "Resque obsolete variable OBSOLETE as VAR.
1711 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
1712   (when (boundp obsolete)
1713     (static-if (and (fboundp 'defvaralias)
1714                     (subrp (symbol-function 'defvaralias)))
1715         (defvaralias var obsolete)
1716       (set var (symbol-value obsolete)))
1717     (if elmo-obsolete-variable-show-warnings
1718         (elmo-warning (format "%s is obsolete. Use %s instead."
1719                               (symbol-name obsolete)
1720                               (symbol-name var))))))
1721
1722 (defun elmo-resque-obsolete-variables (&optional alist)
1723   "Resque obsolete variables in ALIST.
1724 ALIST is a list of cons cell of
1725 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
1726 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
1727   (dolist (pair elmo-obsolete-variable-alist)
1728     (elmo-resque-obsolete-variable (cdr pair)
1729                                    (car pair))))
1730
1731
1732 (require 'product)
1733 (product-provide (provide 'elmo-util) (require 'elmo-version))
1734
1735 ;;; elmo-util.el ends here