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