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