1 ;;; elmo-util.el --- Utilities for ELMO.
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
5 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
6 ;; Keywords: mail, net news
8 ;; This file is part of ELMO (Elisp Library for Message Orchestration).
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)
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.
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.
32 (eval-when-compile (require 'cl))
38 (require 'eword-decode)
44 (autoload 'md5 "md5"))
46 (defvar elmo-work-buf-name " *elmo work*")
47 (defvar elmo-temp-buf-name " *elmo temp*")
49 (or (boundp 'default-enable-multibyte-characters)
50 (defvar default-enable-multibyte-characters (featurep 'mule)
51 "The mock variable except for Emacs 20."))
53 (defun elmo-base64-encode-string (string &optional no-line-break))
54 (defun elmo-base64-decode-string (string))
56 ;; base64 encoding/decoding
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"))
64 (defalias 'elmo-add-name-to-file 'add-name-to-file)
65 (defun elmo-add-name-to-file
66 (filename newname &optional ok-if-already-exists)
67 (copy-file filename newname ok-if-already-exists t)))
69 (defmacro elmo-set-work-buf (&rest body)
70 "Execute BODY on work buffer. Work buffer remains."
72 (set-buffer (get-buffer-create elmo-work-buf-name))
73 (set-buffer-multibyte default-enable-multibyte-characters)
77 (put 'elmo-set-work-buf 'lisp-indent-function 0)
78 (def-edebug-spec elmo-set-work-buf t)
80 (defmacro elmo-bind-directory (dir &rest body)
81 "Set current directory DIR and execute BODY."
82 (` (let ((default-directory (file-name-as-directory (, dir))))
85 (put 'elmo-bind-directory 'lisp-indent-function 1)
86 (def-edebug-spec elmo-bind-directory
89 (defconst elmo-multibyte-buffer-name " *elmo-multibyte-buffer*")
91 (defmacro elmo-with-enable-multibyte (&rest body)
92 "Evaluate BODY with `default-enable-multibyte-character'."
93 `(with-current-buffer (get-buffer-create elmo-multibyte-buffer-name)
96 (put 'elmo-with-enable-multibyte 'lisp-indent-function 0)
97 (def-edebug-spec elmo-with-enable-multibyte t)
100 (unless (fboundp 'coding-system-base)
101 (defalias 'coding-system-base 'ignore))
102 (unless (fboundp 'coding-system-name)
103 (defalias 'coding-system-name 'ignore))
104 (unless (fboundp 'find-file-coding-system-for-read-from-filename)
105 (defalias 'find-file-coding-system-for-read-from-filename 'ignore))
106 (unless (fboundp 'find-operation-coding-system)
107 (defalias 'find-operation-coding-system 'ignore)))
109 (defun elmo-set-auto-coding (&optional filename)
110 "Find coding system used to decode the contents of the current buffer.
111 This function looks for the coding system magic cookie or examines the
112 coding system specified by `file-coding-system-alist' being associated
113 with FILENAME which defaults to `buffer-file-name'."
115 ((boundp 'set-auto-coding-function) ;; Emacs
117 (or (funcall (symbol-value 'set-auto-coding-function)
118 filename (- (point-max) (point-min)))
119 (car (find-operation-coding-system 'insert-file-contents
121 (let (auto-coding-alist)
123 (funcall (symbol-value 'set-auto-coding-function)
124 nil (- (point-max) (point-min)))
126 ((featurep 'file-coding) ;; XEmacs
127 (let ((case-fold-search t)
131 (and (re-search-forward "-\\*-+[\t ]*" end t)
133 (setq start (match-end 0))
134 (re-search-forward "[\t ]*-+\\*-" end t))
136 (setq end (match-beginning 0))
138 (or (looking-at "coding:[\t ]*\\([^\t ;]+\\)")
140 "[\t ;]+coding:[\t ]*\\([^\t ;]+\\)"
142 (find-coding-system (setq codesys
143 (intern (match-string 1))))
145 (and (re-search-forward "^[\t ]*;+[\t ]*Local[\t ]+Variables:"
148 (setq start (match-end 0))
149 (re-search-forward "^[\t ]*;+[\t ]*End:" nil t))
151 (setq end (match-beginning 0))
154 "^[\t ]*;+[\t ]*coding:[\t ]*\\([^\t\n\r ]+\\)"
156 (find-coding-system (setq codesys
157 (intern (match-string 1))))
160 (goto-char (point-min))
161 (setq case-fold-search nil)
162 (re-search-forward "^;;;coding system: "
163 ;;(+ (point-min) 3000) t))
165 (looking-at "[^\t\n\r ]+")
167 (setq codesys (intern (match-string 0))))
171 (find-file-coding-system-for-read-from-filename
173 (coding-system-name (coding-system-base codesys))))))))
175 (defun elmo-object-load (filename &optional mime-charset no-err)
176 "Load OBJECT from the file specified by FILENAME.
177 File content is decoded with MIME-CHARSET."
178 (if (not (file-readable-p filename))
181 (insert-file-contents-as-binary filename)
182 (let ((coding-system (or (elmo-set-auto-coding)
183 (mime-charset-to-coding-system
186 (decode-coding-region (point-min) (point-max) coding-system)))
187 (goto-char (point-min))
189 (read (current-buffer))
190 (error (unless no-err
191 (message "Warning: Loading object from %s failed."
193 (elmo-object-save filename nil mime-charset))
196 (defsubst elmo-save-buffer (filename &optional mime-charset)
197 "Save current buffer to the file specified by FILENAME.
198 Directory of the file is created if it doesn't exist.
199 File content is encoded with MIME-CHARSET."
200 (let ((dir (directory-file-name (file-name-directory filename))))
201 (if (file-directory-p dir)
203 (unless (file-exists-p dir)
204 (elmo-make-directory dir)))
205 (if (file-writable-p filename)
208 ;;; (set-buffer-multibyte default-enable-multibyte-characters)
209 (encode-mime-charset-region (point-min) (point-max) mime-charset))
210 (as-binary-output-file
211 (write-region (point-min) (point-max) filename nil 'no-msg)))
212 (message "%s is not writable." filename))))
214 (defun elmo-object-save (filename object &optional mime-charset)
215 "Save OBJECT to the file specified by FILENAME.
216 Directory of the file is created if it doesn't exist.
217 File content is encoded with MIME-CHARSET."
219 (let (print-length print-level)
220 (prin1 object (current-buffer)))
222 (let ((coding (mime-charset-to-coding-system
223 (or (detect-mime-charset-region (point-min) (point-max))
225 (goto-char (point-min))
226 (insert ";;; -*- mode: emacs-lisp; coding: "
227 (symbol-name coding) " -*-\n")
228 (encode-coding-region (point-min) (point-max) coding)))
229 (elmo-save-buffer filename)))
233 (defconst elmo-condition-atom-regexp "[^/ \")|&]*")
235 (defsubst elmo-condition-parse-error ()
236 (error "Syntax error in '%s'" (buffer-string)))
238 (defun elmo-parse-search-condition (condition)
240 Return value is a cons cell of (STRUCTURE . REST)"
243 (goto-char (point-min))
244 (cons (elmo-condition-parse) (buffer-substring (point) (point-max)))))
246 ;; condition ::= or-expr
247 (defun elmo-condition-parse ()
248 (or (elmo-condition-parse-or-expr)
249 (elmo-condition-parse-error)))
251 ;; or-expr ::= and-expr /
252 ;; and-expr "|" or-expr
253 (defun elmo-condition-parse-or-expr ()
254 (let ((left (elmo-condition-parse-and-expr)))
255 (if (looking-at "| *")
257 (goto-char (match-end 0))
258 (list 'or left (elmo-condition-parse-or-expr)))
261 ;; and-expr ::= primitive /
262 ;; primitive "&" and-expr
263 (defun elmo-condition-parse-and-expr ()
264 (let ((left (elmo-condition-parse-primitive)))
265 (if (looking-at "& *")
267 (goto-char (match-end 0))
268 (list 'and left (elmo-condition-parse-and-expr)))
271 ;; primitive ::= "(" expr ")" /
272 ;; ["!"] search-key SPACE* ":" SPACE* search-value
273 (defun elmo-condition-parse-primitive ()
276 (goto-char (match-end 0))
277 (prog1 (elmo-condition-parse)
278 (unless (looking-at ") *")
279 (elmo-condition-parse-error))
280 (goto-char (match-end 0))))
281 ;; search-key ::= [A-Za-z-]+
282 ;; ;; "since" / "before" / "last" / "first" /
283 ;; ;; "body" / "flag" / field-name
284 ((looking-at "\\(!\\)? *\\([A-Za-z-]+\\) *: *")
285 (goto-char (match-end 0))
286 (let ((search-key (vector
287 (if (match-beginning 1) 'unmatch 'match)
288 (downcase (elmo-match-buffer 2))
289 (elmo-condition-parse-search-value))))
291 (if (string= (aref search-key 1) "tocc")
292 (if (eq (aref search-key 0) 'match)
294 (vector 'match "to" (aref search-key 2))
295 (vector 'match "cc" (aref search-key 2)))
297 (vector 'unmatch "to" (aref search-key 2))
298 (vector 'unmatch "cc" (aref search-key 2))))
301 ;; search-value ::= quoted / time / number / atom
302 ;; quoted ::= <elisp string expression>
303 ;; time ::= "yesterday" / "lastweek" / "lastmonth" / "lastyear" /
304 ;; number SPACE* "daysago" /
305 ;; number "-" month "-" number ; ex. 10-May-2000
306 ;; number "-" number "-" number ; ex. 2000-05-10
308 ;; month ::= "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
309 ;; "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
310 ;; atom ::= ATOM_CHARS*
311 ;; SPACE ::= <ascii space character, 0x20>
312 ;; ATOM_CHARS ::= <any character except specials>
313 ;; specials ::= SPACE / <"> / </> / <)> / <|> / <&>
314 ;; ;; These characters should be quoted.
315 (defun elmo-condition-parse-search-value ()
318 (read (current-buffer)))
319 ((or (looking-at elmo-condition-atom-regexp)
320 (looking-at "yesterday") (looking-at "lastweek")
321 (looking-at "lastmonth") (looking-at "lastyear")
322 (looking-at "[0-9]+ *daysago")
323 (looking-at "[0-9]+-[A-Za-z]+-[0-9]+")
324 (looking-at "[0-9]+-[0-9]+-[0-9]+")
325 (looking-at "[0-9]+"))
326 (prog1 (elmo-match-buffer 0)
327 (goto-char (match-end 0))))
328 (t (error "Syntax error '%s'" (buffer-string)))))
330 (defmacro elmo-filter-condition-p (filter)
331 `(or (vectorp ,filter) (consp ,filter)))
333 (defmacro elmo-filter-type (filter)
336 (defmacro elmo-filter-key (filter)
339 (defmacro elmo-filter-value (filter)
342 (defun elmo-condition-match (condition match-primitive args)
345 (if (eq (elmo-filter-type condition) 'unmatch)
346 (not (apply match-primitive condition args))
347 (apply match-primitive condition args)))
348 ((eq (car condition) 'and)
349 (let ((lhs (elmo-condition-match (nth 1 condition) match-primitive args)))
351 ((elmo-filter-condition-p lhs)
352 (let ((rhs (elmo-condition-match (nth 2 condition)
353 match-primitive args)))
354 (cond ((elmo-filter-condition-p rhs)
359 (elmo-condition-match (nth 2 condition) match-primitive args)))))
360 ((eq (car condition) 'or)
361 (let ((lhs (elmo-condition-match (nth 1 condition) match-primitive args)))
363 ((elmo-filter-condition-p lhs)
364 (let ((rhs (elmo-condition-match (nth 2 condition)
365 match-primitive args)))
366 (cond ((elmo-filter-condition-p rhs)
375 (elmo-condition-match (nth 2 condition) match-primitive args)))))))
377 (defun elmo-condition-optimize (condition)
380 (let ((key (elmo-filter-key condition)))
381 (cond ((cdr (assoc key '(("first" . 0)
385 ((member key '("since" "before" "from" "subject" "to" "cc"))
387 ((member key elmo-msgdb-extra-fields)
392 (let ((weight-l (elmo-condition-optimize (nth 1 condition)))
393 (weight-r (elmo-condition-optimize (nth 2 condition))))
394 (if (> weight-l weight-r)
395 (let ((lhs (nth 1 condition)))
396 (setcar (nthcdr 1 condition) (nth 2 condition))
397 (setcar (nthcdr 2 condition) lhs)
402 (defsubst elmo-buffer-replace (regexp &optional newtext)
403 (goto-char (point-min))
404 (while (re-search-forward regexp nil t)
405 (replace-match (or newtext ""))))
407 (defsubst elmo-delete-char (char string &optional unibyte)
410 (let ((coding-system-for-read 'no-conversion)
411 (coding-system-for-write 'no-conversion))
412 (if unibyte (set-buffer-multibyte nil))
414 (goto-char (point-min))
415 (while (search-forward (char-to-string char) nil t)
419 (defsubst elmo-delete-cr-buffer ()
420 "Delete CR from buffer."
422 (goto-char (point-min))
423 (while (search-forward "\r\n" nil t)
424 (replace-match "\n")) ))
426 (defsubst elmo-delete-cr-get-content-type ()
428 (goto-char (point-min))
429 (while (search-forward "\r\n" nil t)
430 (replace-match "\n"))
431 (goto-char (point-min))
432 (or (std11-field-body "content-type")
435 (defun elmo-delete-cr (string)
439 (goto-char (point-min))
440 (while (search-forward "\r\n" nil t)
441 (replace-match "\n"))
444 (defun elmo-last (list)
445 (and list (nth (1- (length list)) list)))
447 (defun elmo-set-list (vars vals)
450 (set (car vars) (car vals)))
451 (setq vars (cdr vars)
454 (defun elmo-uniq-list (lst &optional delete-function)
455 "Distractively uniqfy elements of LST."
456 (setq delete-function (or delete-function #'delete))
462 (funcall delete-function
467 (defun elmo-uniq-sorted-list (list &optional equal-function)
468 "Distractively uniqfy elements of sorted LIST."
469 (setq equal-function (or equal-function #'equal))
472 (while (funcall equal-function (car list) (cadr list))
473 (setcdr list (cddr list)))
474 (setq list (cdr list))))
477 (defun elmo-list-insert (list element after)
478 (let* ((match (memq after list))
479 (rest (and match (cdr (memq after list)))))
482 (setcdr match (list element))
484 (nconc list (list element)))))
486 (defun elmo-get-file-string (filename &optional remove-final-newline)
488 (let (insert-file-contents-pre-hook ; To avoid autoconv-xmas...
489 insert-file-contents-post-hook)
490 (when (file-exists-p filename)
492 (as-binary-input-file (insert-file-contents filename)))
493 (when (and remove-final-newline
495 (= (char-after (1- (point-max))) ?\n))
496 (goto-char (point-max))
497 (delete-backward-char 1))
500 (defun elmo-save-string (string filename)
503 (as-binary-output-file
505 (write-region (point-min) (point-max)
506 filename nil 'no-msg))
509 (defun elmo-max-of-list (nlist)
513 (if (< max-num (car l))
514 (setq max-num (car l)))
518 (defun elmo-concat-path (path filename)
519 (if (not (string= path ""))
520 (elmo-replace-in-string
521 (if (string= elmo-path-sep (substring path (- (length path) 1)))
522 (concat path filename)
523 (concat path elmo-path-sep filename))
524 (concat (regexp-quote elmo-path-sep)(regexp-quote elmo-path-sep))
528 (defvar elmo-passwd-alist nil)
530 (defun elmo-passwd-alist-load ()
531 (let ((filename (expand-file-name elmo-passwd-alist-file-name
532 elmo-msgdb-directory)))
533 (if (not (file-readable-p filename))
536 (let (insert-file-contents-pre-hook ; To avoid autoconv-xmas...
537 insert-file-contents-post-hook)
538 (insert-file-contents filename)
539 (goto-char (point-min))
541 (read (current-buffer))))))))
543 (defun elmo-passwd-alist-clear ()
544 "Clear password cache."
546 (dolist (pair elmo-passwd-alist)
547 (when (stringp (cdr-safe pair))
548 (fillarray (cdr pair) 0)))
549 (setq elmo-passwd-alist nil))
551 (defun elmo-passwd-alist-save ()
552 "Save password into file."
555 (let ((filename (expand-file-name elmo-passwd-alist-file-name
556 elmo-msgdb-directory))
557 print-length print-level)
558 (prin1 elmo-passwd-alist (current-buffer))
559 (princ "\n" (current-buffer))
560 ;;; (if (and (file-exists-p filename)
561 ;;; (not (equal 384 (file-modes filename))))
562 ;;; (error "%s is not safe.chmod 600 %s!" filename filename))
563 (if (file-writable-p filename)
565 (write-region (point-min) (point-max)
566 filename nil 'no-msg)
567 (set-file-modes filename 384))
568 (message "%s is not writable." filename)))))
570 (defun elmo-get-passwd (key)
571 "Get password from password pool."
573 (if (not elmo-passwd-alist)
574 (setq elmo-passwd-alist (elmo-passwd-alist-load)))
575 (setq pair (assoc key elmo-passwd-alist))
577 (elmo-base64-decode-string (cdr pair))
578 (setq pass (elmo-read-passwd (format "Password for %s: "
580 (setq elmo-passwd-alist
581 (append elmo-passwd-alist
583 (elmo-base64-encode-string pass)))))
584 (if elmo-passwd-life-time
585 (run-with-timer elmo-passwd-life-time nil
586 (` (lambda () (elmo-remove-passwd (, key))))))
589 (defun elmo-remove-passwd (key)
590 "Remove password from password pool (for failure)."
592 (while (setq pass-cons (assoc key elmo-passwd-alist))
594 (fillarray (cdr pass-cons) 0)
595 (setq elmo-passwd-alist
596 (delete pass-cons elmo-passwd-alist))))))
598 (defmacro elmo-read-char-exclusive ()
599 (cond ((featurep 'xemacs)
600 '(let ((table (quote ((backspace . ?\C-h) (delete . ?\C-?)
605 (key-press-event-p (setq event (next-command-event)))
606 (setq key (or (event-to-character event)
607 (cdr (assq (event-key event) table)))))))
609 ((fboundp 'read-char-exclusive)
610 '(read-char-exclusive))
614 (defun elmo-read-passwd (prompt &optional stars)
615 "Read a single line of text from user without echoing, and return it."
619 (cursor-in-echo-area t)
620 (log-message-max-size 0)
621 message-log-max done msg truncate)
623 (if (or (not stars) (string= "" ans))
625 (setq msg (concat prompt (make-string (length ans) ?.)))
627 (1+ (- (length msg) (window-width (minibuffer-window)))))
629 (setq msg (concat "$" (substring msg (1+ truncate))))))
631 (setq c (elmo-read-char-exclusive))
635 ((or (= c ?\r) (= c ?\n) (= c ?\e))
639 ((and (/= c ?\b) (/= c ?\177))
640 (setq ans (concat ans (char-to-string c))))
642 (setq ans (substring ans 0 -1)))))
651 (defun elmo-string-to-list (string)
654 (goto-char (point-min))
656 (goto-char (point-max))
658 (goto-char (point-min))
659 (read (current-buffer))))
661 (defun elmo-list-to-string (list)
670 (if (symbolp (car tlist))
671 (symbol-name (car tlist))
676 (setq tlist (cdr tlist)))
686 (defun elmo-plug-on-by-servers (alist &optional servers)
687 (let ((server-list (or servers elmo-plug-on-servers)))
690 (if (elmo-plugged-p (car server-list))
692 (setq server-list (cdr server-list))))))
694 (defun elmo-plug-on-by-exclude-servers (alist &optional servers)
695 (let ((server-list (or servers elmo-plug-on-exclude-servers))
696 server other-servers)
698 (when (and (not (member (setq server (caaar alist)) server-list))
699 (not (member server other-servers)))
700 (push server other-servers))
701 (setq alist (cdr alist)))
702 (elmo-plug-on-by-servers alist other-servers)))
704 (defun elmo-plugged-p (&optional server port stream-type alist label-exp)
705 (let ((alist (or alist elmo-plugged-alist))
707 (cond ((and (not port) (not server))
708 (cond ((eq elmo-plugged-condition 'one)
712 (if (nth 2 (car alist))
714 (setq alist (cdr alist))))
716 ((eq elmo-plugged-condition 'all)
720 (if (not (nth 2 (car alist)))
721 (throw 'plugged nil))
722 (setq alist (cdr alist)))
725 ((functionp elmo-plugged-condition)
726 (funcall elmo-plugged-condition alist))
729 ((not port) ;; server
732 (when (string= server (caaar alist))
733 (if (nth 2 (car alist))
735 (setq alist (cdr alist)))))
737 (setq plugged-info (assoc (list server port stream-type) alist))
738 (if (not plugged-info)
739 ;; add elmo-plugged-alist automatically
741 (elmo-set-plugged elmo-plugged server port stream-type
742 nil nil nil label-exp)
744 (if (and elmo-auto-change-plugged
745 (> elmo-auto-change-plugged 0)
746 (nth 3 plugged-info) ;; time
747 (elmo-time-expire (nth 3 plugged-info)
748 elmo-auto-change-plugged))
750 (nth 2 plugged-info)))))))
752 (defun elmo-set-plugged (plugged &optional server port stream-type time
754 (let ((alist (or alist elmo-plugged-alist))
756 (cond ((and (not port) (not server))
757 (setq elmo-plugged plugged)
758 ;; set plugged all element of elmo-plugged-alist.
760 (setcdr (cdar alist) (list plugged time))
761 (setq alist (cdr alist))))
763 ;; set plugged all port of server
765 (when (string= server (caaar alist))
766 (setcdr (cdar alist) (list plugged time)))
767 (setq alist (cdr alist))))
769 ;; set plugged one port of server
770 (setq plugged-info (assoc (list server port stream-type) alist))
771 (setq label (if label-exp
773 (nth 1 plugged-info)))
775 ;; if add is non-nil, don't reset plug state.
777 (setcdr plugged-info (list label plugged time)))
779 (setq elmo-plugged-alist
783 (list (list server port stream-type)
784 label plugged time))))))))
787 (defun elmo-delete-plugged (&optional server port alist)
788 (let* ((alist (or alist elmo-plugged-alist))
790 (cond ((and (not port) (not server))
793 ;; delete plugged all port of server
795 (when (string= server (caaar alist2))
796 (setq alist (delete (car alist2) alist)))
797 (setq alist2 (cdr alist2))))
799 ;; delete plugged one port of server
801 (delete (assoc (cons server port) alist) alist))))
804 (defun elmo-disk-usage (path)
805 "Get disk usage (bytes) in PATH."
807 (condition-case () (file-attributes path) (error nil))))
809 (if (nth 0 file-attr) ; directory
810 (let ((files (condition-case ()
811 (directory-files path t "^[^\\.]")
814 ;; (result (nth 7 file-attr))) ... directory size
816 (setq result (+ result (or (elmo-disk-usage (car files)) 0)))
817 (setq files (cdr files)))
819 (float (nth 7 file-attr)))
822 (defun elmo-get-last-accessed-time (path &optional dir)
823 "Return the last accessed time of PATH."
824 (let ((last-accessed (nth 4 (file-attributes (or (and dir
829 (setq last-accessed (+ (* (nth 0 last-accessed)
830 (float 65536)) (nth 1 last-accessed)))
833 (defun elmo-get-last-modification-time (path &optional dir)
834 "Return the last accessed time of PATH."
835 (let ((last-modified (nth 5 (file-attributes (or (and dir
839 (setq last-modified (+ (* (nth 0 last-modified)
840 (float 65536)) (nth 1 last-modified)))))
842 (defun elmo-make-directory (path &optional mode)
843 "Create directory recursively."
844 (let ((parent (directory-file-name (file-name-directory path))))
845 (if (null (file-directory-p parent))
846 (elmo-make-directory parent))
847 (make-directory path)
848 (set-file-modes path (or mode
849 (+ (* 64 7) (* 8 0) 0))))) ; chmod 0700
851 (defun elmo-delete-directory (path &optional no-hierarchy)
852 "Delete directory recursively."
853 (if (stringp path) ; nil is not permitted.
854 (let ((dirent (directory-files path))
855 relpath abspath hierarchy)
857 (setq relpath (car dirent)
859 abspath (expand-file-name relpath path))
860 (when (not (string-match "^\\.\\.?$" relpath))
861 (if (eq (nth 0 (file-attributes abspath)) t)
864 (elmo-delete-directory abspath no-hierarchy))
865 (delete-file abspath))))
867 (delete-directory path)))))
869 (defun elmo-delete-match-files (path regexp &optional remove-if-empty)
870 "Delete directory files specified by PATH.
871 If optional REMOVE-IF-EMPTY is non-nil, delete directory itself if
872 the directory becomes empty after deletion."
873 (when (stringp path) ; nil is not permitted.
874 (dolist (file (directory-files path t regexp))
878 (delete-directory path) ; should be removed if empty.
881 (defun elmo-list-filter (l1 l2)
882 "Return a list from L2 in which each element is a member of L1."
885 (if (memq element l1)
886 (setq result (cons element result))))
889 (defsubst elmo-list-delete-if-smaller (list number)
890 (let ((ret-val (copy-sequence list)))
892 (if (< (car list) number)
893 (setq ret-val (delq (car list) ret-val)))
894 (setq list (cdr list)))
897 (defun elmo-list-diff (list1 list2)
898 (let ((clist1 (sort (copy-sequence list1) #'<))
899 (clist2 (sort (copy-sequence list2) #'<))
900 list1-only list2-only)
901 (while (or clist1 clist2)
905 (setq list2-only (cons (car clist2) list2-only))
906 (setq clist2 (cdr clist2))))
909 (setq list1-only (cons (car clist1) list1-only))
910 (setq clist1 (cdr clist1))))
911 ((< (car clist1) (car clist2))
912 (while (and clist1 (< (car clist1) (car clist2)))
913 (setq list1-only (cons (car clist1) list1-only))
914 (setq clist1 (cdr clist1))))
915 ((< (car clist2) (car clist1))
916 (while (and clist2 (< (car clist2) (car clist1)))
917 (setq list2-only (cons (car clist2) list2-only))
918 (setq clist2 (cdr clist2))))
919 ((= (car clist1) (car clist2))
920 (setq clist1 (cdr clist1)
921 clist2 (cdr clist2)))))
922 (list list1-only list2-only)))
924 (defun elmo-list-diff-nonsortable (list1 list2)
925 (let ((clist1 (copy-sequence list1))
926 (clist2 (copy-sequence list2)))
928 (setq clist1 (delq (car list2) clist1))
929 (setq list2 (cdr list2)))
931 (setq clist2 (delq (car list1) clist2))
932 (setq list1 (cdr list1)))
933 (list clist1 clist2)))
935 (defun elmo-list-bigger-diff (list1 list2 &optional mes)
936 "Returns a list (- +). + is bigger than max of LIST1, in LIST2."
941 (max-of-l2 (or (nth (max 0 (1- (length l2))) l2) 0))
945 (setq num (+ (length l1)))
947 (if (memq (car l1) l2)
948 (if (eq (car l1) (car l2))
951 (if (> (car l1) max-of-l2)
952 (setq diff1 (nconc diff1 (list (car l1))))))
956 (setq percent (/ (* i 100) num))
957 (if (eq (% percent 5) 0)
958 (elmo-display-progress
959 'elmo-list-bigger-diff "%s%d%%" percent mes))))
961 (cons diff1 (list l2)))))
963 (defmacro elmo-get-hash-val (string hashtable)
964 (static-if (fboundp 'unintern)
965 `(symbol-value (intern-soft ,string ,hashtable))
966 `(let ((sym (intern-soft ,string ,hashtable)))
968 (symbol-value sym)))))
970 (defmacro elmo-set-hash-val (string value hashtable)
971 `(set (intern ,string ,hashtable) ,value))
973 (defmacro elmo-clear-hash-val (string hashtable)
974 (static-if (fboundp 'unintern)
975 (list 'unintern string hashtable)
976 (list 'makunbound (list 'intern string hashtable))))
978 (defmacro elmo-unintern (string)
979 "`unintern' symbol named STRING, When can use `unintern'.
980 Emacs 19.28 or earlier does not have `unintern'."
981 (static-if (fboundp 'unintern)
982 (list 'unintern string)))
984 (defun elmo-make-hash (&optional hashsize)
985 "Make a new hash table which have HASHSIZE size."
989 ;; Prime numbers as lengths tend to result in good
990 ;; hashing; lengths one less than a power of two are
994 (while (< (- i 1) hashsize)
997 elmo-hash-maximum-size)
998 elmo-hash-minimum-size)
999 elmo-hash-minimum-size)
1002 (defsubst elmo-mime-string (string)
1003 "Normalize MIME encoded STRING."
1005 (elmo-with-enable-multibyte
1006 (encode-mime-charset-string
1008 (eword-decode-and-unfold-unstructured-field-body string))
1010 elmo-mime-charset))))
1012 (defsubst elmo-collect-field (beg end downcase-field-name)
1015 (narrow-to-region beg end)
1016 (goto-char (point-min))
1017 (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
1019 (while (re-search-forward regexp nil t)
1020 (setq name (buffer-substring-no-properties
1021 (match-beginning 1)(1- (match-end 1))))
1022 (if downcase-field-name
1023 (setq name (downcase name)))
1024 (setq body (buffer-substring-no-properties
1025 (match-end 0) (std11-field-end)))
1026 (or (assoc name dest)
1027 (setq dest (cons (cons name body) dest))))
1030 (defsubst elmo-collect-field-from-string (string downcase-field-name)
1033 (goto-char (point-min))
1034 (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
1036 (while (re-search-forward regexp nil t)
1037 (setq name (buffer-substring-no-properties
1038 (match-beginning 1)(1- (match-end 1))))
1039 (if downcase-field-name
1040 (setq name (downcase name)))
1041 (setq body (buffer-substring-no-properties
1042 (match-end 0) (std11-field-end)))
1043 (or (assoc name dest)
1044 (setq dest (cons (cons name body) dest))))
1047 (defun elmo-safe-filename (filename)
1048 (let* ((replace-alist '(("/" . " ")
1053 (regexp-quote (mapconcat 'car replace-alist ""))
1057 (while (string-match regexp rest)
1058 (setq converted (concat converted
1059 (substring rest 0 (match-beginning 0))
1060 (cdr (assoc (substring rest
1064 rest (substring rest (match-end 0))))
1065 (concat converted rest)))
1067 (defvar elmo-filename-replace-chars nil)
1069 (defsubst elmo-replace-string-as-filename (msgid)
1070 "Replace string as filename."
1071 (setq msgid (elmo-replace-in-string msgid " " " "))
1072 (if (null elmo-filename-replace-chars)
1073 (setq elmo-filename-replace-chars
1074 (regexp-quote (mapconcat
1075 'car elmo-filename-replace-string-alist ""))))
1076 (while (string-match (concat "[" elmo-filename-replace-chars "]")
1079 (substring msgid 0 (match-beginning 0))
1082 (match-beginning 0) (match-end 0))
1083 elmo-filename-replace-string-alist))
1084 (substring msgid (match-end 0)))))
1087 (defsubst elmo-recover-string-from-filename (filename)
1088 "Recover string from FILENAME."
1090 (while (string-match " " filename)
1091 (setq tmp (substring filename
1093 (+ (match-end 0) 1)))
1094 (if (string= tmp " ")
1096 (setq tmp (car (rassoc tmp
1097 elmo-filename-replace-string-alist))))
1100 (substring filename 0 (match-beginning 0))
1102 (setq filename (substring filename (+ (match-end 0) 1))))
1103 (concat result filename)))
1105 (defsubst elmo-copy-file (src dst &optional ok-if-already-exists)
1107 (elmo-add-name-to-file src dst ok-if-already-exists)
1108 (error (copy-file src dst ok-if-already-exists t))))
1110 (defsubst elmo-buffer-exists-p (buffer)
1111 (if (bufferp buffer)
1112 (buffer-live-p buffer)
1113 (get-buffer buffer)))
1115 (defsubst elmo-kill-buffer (buffer)
1116 (when (elmo-buffer-exists-p buffer)
1117 (kill-buffer buffer)))
1119 (defun elmo-delete-if (pred lst)
1120 "Return new list contain items which don't satisfy PRED in LST."
1123 (unless (funcall pred (car lst))
1124 (setq result (cons (car lst) result)))
1125 (setq lst (cdr lst)))
1128 (defun elmo-list-delete (list1 list2 &optional delete-function)
1129 "Delete by side effect any occurrences equal to elements of LIST1 from LIST2.
1130 Return the modified LIST2. Deletion is done with `delete'.
1131 Write `(setq foo (elmo-list-delete bar foo))' to be sure of changing
1133 If optional DELETE-FUNCTION is speficied, it is used as delete procedure."
1134 (setq delete-function (or delete-function 'delete))
1136 (setq list2 (funcall delete-function (car list1) list2))
1137 (setq list1 (cdr list1)))
1140 (defun elmo-list-member (list1 list2)
1141 "If any element of LIST1 is member of LIST2, return t."
1144 (if (member (car list1) list2)
1146 (setq list1 (cdr list1)))))
1148 (defun elmo-count-matches (regexp beg end)
1152 (while (re-search-forward regexp end t)
1153 (setq count (1+ count)))
1156 (if (fboundp 'display-error)
1157 (defalias 'elmo-display-error 'display-error)
1158 (defun elmo-display-error (error-object stream)
1159 "A tiny function to display ERROR-OBJECT to the STREAM."
1161 (errobj error-object)
1164 (setq err-mes (concat err-mes (format
1165 (if (stringp (car errobj))
1169 (setq errobj (cdr errobj))
1170 (if errobj (setq err-mes (concat err-mes (if first ": " ", "))))
1172 (princ err-mes stream))))
1174 (if (fboundp 'define-error)
1175 (defalias 'elmo-define-error 'define-error)
1176 (defun elmo-define-error (error doc &optional parents)
1178 (setq parents 'error))
1179 (let ((conds (get parents 'error-conditions)))
1181 (error "Not an error symbol: %s" error))
1183 (list 'error-message doc
1184 'error-conditions (cons error conds))))))
1186 (cond ((fboundp 'progress-feedback-with-label)
1187 (defalias 'elmo-display-progress 'progress-feedback-with-label))
1188 ((fboundp 'lprogress-display)
1189 (defalias 'elmo-display-progress 'lprogress-display))
1191 (defun elmo-display-progress (label format &optional value &rest args)
1192 "Print a progress message."
1193 (if (and (null format) (null args))
1195 (apply (function message) (concat format " %d%%")
1196 (nconc args (list value)))))))
1198 (defvar elmo-progress-counter-alist nil)
1200 (defmacro elmo-progress-counter-value (counter)
1201 (` (aref (cdr (, counter)) 0)))
1203 (defmacro elmo-progress-counter-all-value (counter)
1204 (` (aref (cdr (, counter)) 1)))
1206 (defmacro elmo-progress-counter-format (counter)
1207 (` (aref (cdr (, counter)) 2)))
1209 (defmacro elmo-progress-counter-set-value (counter value)
1210 (` (aset (cdr (, counter)) 0 (, value))))
1212 (defun elmo-progress-set (label all-value &optional format)
1213 (unless (assq label elmo-progress-counter-alist)
1214 (setq elmo-progress-counter-alist
1215 (cons (cons label (vector 0 all-value (or format "")))
1216 elmo-progress-counter-alist))))
1218 (defun elmo-progress-clear (label)
1219 (let ((counter (assq label elmo-progress-counter-alist)))
1221 (elmo-display-progress label
1222 (elmo-progress-counter-format counter)
1224 (setq elmo-progress-counter-alist
1225 (delq counter elmo-progress-counter-alist)))))
1227 (defun elmo-progress-notify (label &optional value op &rest args)
1228 (let ((counter (assq label elmo-progress-counter-alist)))
1230 (let* ((value (or value 1))
1231 (cur-value (elmo-progress-counter-value counter))
1232 (all-value (elmo-progress-counter-all-value counter))
1233 (new-value (if (eq op 'set) value (+ cur-value value)))
1234 (cur-rate (/ (* cur-value 100) all-value))
1235 (new-rate (/ (* new-value 100) all-value)))
1236 (elmo-progress-counter-set-value counter new-value)
1237 (unless (= cur-rate new-rate)
1238 (apply 'elmo-display-progress
1240 (elmo-progress-counter-format counter)
1243 (when (>= new-rate 100)
1244 (elmo-progress-clear label))))))
1246 (put 'elmo-with-progress-display 'lisp-indent-function '2)
1247 (def-edebug-spec elmo-with-progress-display
1248 (form (symbolp form &optional form) &rest form))
1250 (defmacro elmo-with-progress-display (condition spec &rest body)
1251 "Evaluate BODY with progress gauge if CONDITION is non-nil.
1252 SPEC is a list as followed (LABEL MAX-VALUE [FORMAT])."
1253 (let ((label (car spec))
1254 (max-value (cadr spec))
1259 (elmo-progress-set (quote ,label) ,max-value ,fmt))
1261 (elmo-progress-clear (quote ,label)))))
1263 (defun elmo-time-expire (before-time diff-time)
1264 (let* ((current (current-time))
1265 (rest (when (< (nth 1 current) (nth 1 before-time))
1269 (list (- (+ (car current) (if rest -1 0)) (car before-time))
1270 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1271 (and (eq (car diff) 0)
1272 (< diff-time (nth 1 diff)))))
1274 (if (fboundp 'std11-fetch-field)
1275 (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1276 (defalias 'elmo-field-body 'std11-field-body))
1278 (defun elmo-unfold-field-body (name)
1279 (let ((value (elmo-field-body name)))
1281 (std11-unfold-string value))))
1283 (defun elmo-decoded-field-body (field-name &optional mode)
1284 (let ((field-body (elmo-field-body field-name)))
1287 (elmo-with-enable-multibyte
1288 (mime-decode-field-body field-body field-name mode)))
1291 (defun elmo-address-quote-specials (word)
1292 "Make quoted string of WORD if needed."
1293 (let ((lal (std11-lexical-analyze word)))
1294 (if (or (assq 'specials lal)
1295 (assq 'domain-literal lal))
1296 (prin1-to-string word)
1299 (defmacro elmo-string (string)
1300 "STRING without text property."
1301 (` (let ((obj (copy-sequence (, string))))
1302 (and obj (set-text-properties 0 (length obj) nil obj))
1305 (defun elmo-flatten (list-of-list)
1306 "Flatten LIST-OF-LIST."
1309 (mapcar (lambda (element)
1310 (if (listp element) element (list element)))
1313 (defun elmo-y-or-n-p (prompt &optional auto default)
1314 "Same as `y-or-n-p'.
1315 But if optional argument AUTO is non-nil, DEFAULT is returned."
1320 (defun elmo-string-member (string slist)
1322 (dolist (element slist)
1323 (cond ((null element))
1325 (when (string= string element)
1328 (when (string= string (symbol-value element))
1329 (throw 'found t)))))))
1331 (static-cond ((fboundp 'member-ignore-case)
1332 (defalias 'elmo-string-member-ignore-case 'member-ignore-case))
1333 ((fboundp 'compare-strings)
1334 (defun elmo-string-member-ignore-case (elt list)
1335 "Like `member', but ignores differences in case and text representation.
1336 ELT must be a string. Upper-case and lower-case letters are treated as equal.
1337 Unibyte strings are converted to multibyte for comparison."
1338 (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
1339 (setq list (cdr list)))
1342 (defun elmo-string-member-ignore-case (elt list)
1343 "Like `member', but ignores differences in case and text representation.
1344 ELT must be a string. Upper-case and lower-case letters are treated as equal."
1345 (let ((str (downcase elt)))
1346 (while (and list (not (string= str (downcase (car list)))))
1347 (setq list (cdr list)))
1350 (defun elmo-string-match-member (str list &optional case-ignore)
1351 (let ((case-fold-search case-ignore))
1354 (if (string-match (car list) str)
1355 (throw 'member (car list)))
1356 (setq list (cdr list))))))
1358 (defun elmo-string-matched-member (str list &optional case-ignore)
1359 (let ((case-fold-search case-ignore))
1362 (if (string-match str (car list))
1363 (throw 'member (car list)))
1364 (setq list (cdr list))))))
1366 (defsubst elmo-string-delete-match (string pos)
1367 (concat (substring string
1368 0 (match-beginning pos))
1373 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1374 (let ((case-fold-search case-ignore)
1378 (setq a (car alist))
1381 (string-match key (car a)))
1383 (setq alist (cdr alist))))))
1385 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1386 (let ((case-fold-search case-ignore)
1390 (setq a (car alist))
1393 (string-match (car a) key))
1395 (setq alist (cdr alist))))))
1397 (defun elmo-string-assoc (key alist)
1401 (setq a (car alist))
1404 (string= key (car a)))
1406 (setq alist (cdr alist))))))
1408 (defun elmo-string-assoc-all (key alist)
1411 (if (string= key (car (car alist)))
1415 (setq alist (cdr alist)))
1418 (defun elmo-string-rassoc (key alist)
1422 (setq a (car alist))
1425 (string= key (cdr a)))
1427 (setq alist (cdr alist))))))
1429 (defun elmo-string-rassoc-all (key alist)
1432 (if (string= key (cdr (car alist)))
1436 (setq alist (cdr alist)))
1439 (defun elmo-expand-newtext (newtext original)
1440 (let ((len (length newtext))
1442 c expanded beg N did-expand)
1445 (while (and (< pos len)
1446 (not (= (aref newtext pos) ?\\)))
1447 (setq pos (1+ pos)))
1449 (push (substring newtext beg pos) expanded))
1451 ;; We hit a \; expand it.
1454 c (aref newtext pos))
1455 (if (not (or (= c ?\&)
1458 ;; \ followed by some character we don't expand.
1459 (push (char-to-string c) expanded)
1464 (when (match-beginning N)
1465 (push (substring original (match-beginning N) (match-end N))
1467 (setq pos (1+ pos)))
1469 (apply (function concat) (nreverse expanded))
1472 ;;; Folder parser utils.
1473 (defconst elmo-quoted-specials-list '(?\\ ?\"))
1475 (defun elmo-quoted-token (string)
1477 (std11-wrap-as-quoted-pairs string elmo-quoted-specials-list)
1480 (defun elmo-token-valid-p (token requirement)
1481 (cond ((null requirement))
1482 ((stringp requirement)
1483 (string-match requirement token))
1484 ((functionp requirement)
1485 (funcall requirement token))))
1487 (defun elmo-parse-token (string &optional seps requirement)
1488 "Parse atom from STRING using SEPS as a string of separator char list."
1489 (let ((len (length string))
1490 (seps (and seps (string-to-char-list seps)))
1496 (while (and (< i len) (or in (null sep)))
1497 (setq c (aref string i))
1499 ((and in (eq c ?\\))
1501 content (cons (aref string i) content)
1506 (in (setq content (cons c content)
1510 (t (setq content (cons c content)
1512 (if in (error "Parse error in quoted"))
1513 (let ((atom (if (null content)
1515 (char-list-to-string (nreverse content)))))
1516 (if (elmo-token-valid-p atom requirement)
1517 (cons atom (substring string i))
1518 (cons "" string))))))
1520 (defun elmo-parse-prefixed-element (prefix string &optional seps requirement)
1522 (if (and (not (eq (length string) 0))
1523 (eq (aref string 0) prefix)
1524 (setq parsed (elmo-parse-token (substring string 1) seps))
1525 (elmo-token-valid-p (car parsed) requirement))
1529 (defun elmo-collect-separators (spec)
1531 (let ((result (elmo-collect-separators-internal spec)))
1533 (char-list-to-string (elmo-uniq-list result #'delq))))))
1535 (defun elmo-collect-separators-internal (specs &optional separators)
1537 (let ((spec (car specs)))
1540 (setq separators (elmo-collect-separators-internal spec separators)
1543 (setq separators (cons spec separators)
1546 (setq specs nil)))))
1549 (defun elmo-collect-trail-separators (element specs)
1554 (eq (aref specs 0) element))
1557 (while (setq spec (car specs))
1558 (if (setq result (elmo-collect-trail-separators element spec))
1559 (setq result (concat (if (stringp result) result)
1560 (elmo-collect-separators (cdr specs)))
1562 (setq specs (cdr specs))))
1565 (defun elmo-parse-separated-tokens (string spec)
1566 (let ((result (elmo-parse-separated-tokens-internal string spec)))
1567 (if (eq (car result) t)
1568 (cons nil (cdr result))
1571 (defun elmo-parse-separated-tokens-internal (string spec &optional separators)
1574 (let ((parse (elmo-parse-token string separators)))
1575 (cons (list (cons spec (car parse))) (cdr parse))))
1577 (let ((parse (elmo-parse-token string separators)))
1578 (if (elmo-token-valid-p (car parse) (aref spec 1))
1579 (cons (list (cons (aref spec 0) (car parse))) (cdr parse))
1580 (cons nil string))))
1582 (if (and (> (length string) 0)
1583 (eq (aref string 0) spec))
1584 (cons t (substring string 1))
1591 (setq result (elmo-parse-separated-tokens-internal
1594 (concat (elmo-collect-separators (cdr spec))
1596 (cond ((null (car result))
1597 (throw 'unmatch (cons t string)))
1598 ((eq t (car result)))
1600 (setq tokens (nconc (car result) tokens))))
1601 (setq rest (cdr result)
1603 (cons (or tokens t) rest))))))
1605 (defun elmo-quote-syntactical-element (value element syntax)
1606 (let ((separators (elmo-collect-trail-separators element syntax)))
1608 (string-match (concat "[" separators "]") value))
1609 (elmo-quoted-token value)
1612 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1614 ;; number ::= [0-9]+
1617 ;; number-range ::= "(" beg " . " end ")" ;; cons cell
1618 ;; number-set-elem ::= number / number-range
1619 ;; number-set ::= "(" *number-set-elem ")" ;; list
1621 (defun elmo-number-set-member (number number-set)
1622 "Return non-nil if NUMBER is an element of NUMBER-SET.
1623 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1624 (or (memq number number-set)
1626 (while (and number-set (not found))
1627 (if (and (consp (car number-set))
1628 (and (<= (car (car number-set)) number)
1629 (<= number (cdr (car number-set)))))
1631 (setq number-set (cdr number-set))))
1634 (defun elmo-number-set-append-list (number-set list)
1635 "Append LIST of numbers to the NUMBER-SET.
1636 NUMBER-SET is altered."
1637 (let ((appended number-set))
1639 (setq appended (elmo-number-set-append appended (car list)))
1640 (setq list (cdr list)))
1643 (defun elmo-number-set-append (number-set number)
1644 "Append NUMBER to the NUMBER-SET.
1645 NUMBER-SET is altered."
1646 (let ((number-set-1 number-set)
1648 (while (and number-set (not found))
1649 (setq elem (car number-set))
1652 (eq (+ 1 (cdr elem)) number))
1653 (setcdr elem number)
1655 ((and (integerp elem)
1656 (eq (+ 1 elem) number))
1657 (setcar number-set (cons elem number))
1659 ((or (and (integerp elem) (eq elem number))
1661 (<= (car elem) number)
1662 (<= number (cdr elem))))
1664 (setq number-set (cdr number-set)))
1666 (setq number-set-1 (nconc number-set-1 (list number))))
1669 (defun elmo-number-set-delete-list (number-set list)
1670 "Delete LIST of numbers from the NUMBER-SET.
1671 NUMBER-SET is altered."
1672 (let ((deleted number-set))
1673 (dolist (number list)
1674 (setq deleted (elmo-number-set-delete deleted number)))
1677 (defun elmo-number-set-delete (number-set number)
1678 "Delete NUMBER from the NUMBER-SET.
1679 NUMBER-SET is altered."
1680 (let* ((curr number-set)
1681 (top (cons 'dummy number-set))
1684 (while (and curr (not found))
1685 (setq elem (car curr))
1688 ((eq (car elem) number)
1689 (if (eq (cdr elem) (1+ number))
1690 (setcar curr (cdr elem))
1691 (setcar elem (1+ number)))
1693 ((eq (cdr elem) number)
1694 (if (eq (car elem) (1- number))
1695 (setcar curr (car elem))
1696 (setcdr elem (1- number)))
1698 ((and (> number (car elem))
1699 (< number (cdr elem)))
1704 ;; (beg . (1- number))
1705 (let ((new (cons (car elem) (1- number))))
1706 (if (eq (car new) (cdr new))
1709 ;; ((1+ number) . end)
1710 (let ((new (cons (1+ number) (cdr elem))))
1711 (if (eq (car new) (cdr new))
1715 (when (eq elem number)
1716 (setcdr prev (cdr curr))
1722 (defun elmo-make-number-list (beg end)
1723 (let (number-list i)
1726 (setq number-list (cons i number-list))
1730 (defun elmo-number-set-to-number-list (number-set)
1731 "Return a number list which corresponds to NUMBER-SET."
1732 (let ((number-list (list 'dummy))
1735 (setq elem (car number-set))
1738 (nconc number-list (elmo-make-number-list (car elem) (cdr elem))))
1740 (nconc number-list (list elem))))
1741 (setq number-set (cdr number-set)))
1744 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1745 "*Regexp to filter subfolders."
1749 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1750 (let ((root (zerop (length curdir)))
1751 (w32-get-true-file-link-count t) ; for Meadow
1754 (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1755 (when (and (not (string-match
1756 elmo-list-subdirectories-ignore-regexp
1758 (car (setq attr (file-attributes
1759 (expand-file-name file dir)))))
1760 (when (eq one-level 'check) (throw 'done t))
1762 (concat curdir (and (not root) elmo-path-sep) file))
1764 (setq dirs (nconc dirs
1765 (if (if elmo-have-link-count (< 2 (nth 1 attr))
1767 (elmo-list-subdirectories-1
1770 (if one-level 'check))))
1772 (list (list relpath))
1775 (elmo-list-subdirectories-1
1779 (list relpath)))))))
1782 (defun elmo-list-subdirectories (directory file one-level)
1783 (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1784 (if (zerop (length file))
1786 (cons file subdirs))))
1788 (defun elmo-mapcar-list-of-list (func list-of-list)
1791 (cond ((listp x) (elmo-mapcar-list-of-list func x))
1792 (t (funcall func x))))
1795 (defun elmo-map-recursive (function object)
1797 (let* ((prev (list 'dummy))
1799 (while (consp object)
1800 (setq prev (setcdr prev (list (elmo-map-recursive function
1802 object (cdr object)))
1804 (setcdr prev (funcall function object)))
1806 (funcall function object)))
1808 (defun elmo-map-until-success (function sequence)
1810 (while (and (null result)
1812 (setq result (funcall function (car sequence))
1813 sequence (cdr sequence)))
1816 (defun elmo-string-match-substring (regexp string &optional matchn)
1817 (when (string-match regexp string)
1818 (match-string (or matchn 1) string)))
1820 (defun elmo-parse (string regexp &optional matchn)
1821 (or matchn (setq matchn 1))
1823 (store-match-data nil)
1824 (while (string-match regexp string (match-end 0))
1825 (setq list (cons (substring string (match-beginning matchn)
1826 (match-end matchn)) list)))
1829 (defun elmo-find-list-match-value (specs getter)
1830 (lexical-let ((getter getter))
1831 (elmo-map-until-success
1835 (funcall getter spec))
1837 (lexical-let ((value (funcall getter (car spec))))
1839 (elmo-map-until-success
1843 (elmo-string-match-substring rule value))
1845 (elmo-string-match-substring (car rule) value (cdr rule)))))
1850 (defmacro elmo-make-file-cache (path status)
1851 "PATH is the cache file name.
1852 STATUS is one of 'section, 'entire or nil.
1853 nil means no cache exists.
1854 'section means partial section cache exists.
1855 'entire means entire cache exists.
1856 If the cache is partial file-cache, TYPE is 'partial."
1857 (` (cons (, path) (, status))))
1859 (defmacro elmo-file-cache-path (file-cache)
1860 "Returns the file path of the FILE-CACHE."
1861 (` (car (, file-cache))))
1863 (defmacro elmo-file-cache-status (file-cache)
1864 "Returns the status of the FILE-CACHE."
1865 (` (cdr (, file-cache))))
1867 (defsubst elmo-cache-to-msgid (filename)
1868 (concat "<" (elmo-recover-string-from-filename filename) ">"))
1870 (defsubst elmo-cache-get-path-subr (msgid)
1871 (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1872 (clist (string-to-char-list msgid))
1875 (setq sum (+ sum (car clist)))
1876 (setq clist (cdr clist)))
1878 (nth (% (/ sum 16) 2) chars)
1879 (nth (% sum 16) chars))))
1882 (defun elmo-file-cache-get-path (msgid &optional section)
1883 "Get cache path for MSGID.
1884 If optional argument SECTION is specified, partial cache path is returned."
1885 (if (setq msgid (elmo-msgid-to-cache msgid))
1888 (format "%s/%s/%s/%s"
1889 elmo-cache-directory
1890 (elmo-cache-get-path-subr msgid)
1894 elmo-cache-directory
1895 (elmo-cache-get-path-subr msgid)
1898 (defmacro elmo-file-cache-expand-path (path section)
1899 "Return file name for the file-cache corresponds to the section.
1900 PATH is the file-cache path.
1901 SECTION is the section string."
1902 (` (expand-file-name (or (, section) "") (, path))))
1904 (defun elmo-file-cache-delete (path)
1905 "Delete a cache on PATH."
1906 (when (file-exists-p path)
1907 (if (file-directory-p path)
1909 (dolist (file (directory-files path t "^[^\\.]"))
1911 (delete-directory path))
1915 (defun elmo-file-cache-exists-p (msgid)
1916 "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1917 (elmo-file-cache-status (elmo-file-cache-get msgid)))
1919 (defun elmo-file-cache-save (cache-path section)
1920 "Save current buffer as cache on PATH.
1921 Return t if cache is saved successfully."
1923 (let ((path (if section (expand-file-name section cache-path)
1926 (if (and (null section)
1927 (file-directory-p path))
1929 (setq files (directory-files path t "^[^\\.]"))
1931 (delete-file (car files))
1932 (setq files (cdr files)))
1933 (delete-directory path))
1935 (not (file-directory-p cache-path)))
1936 (delete-file cache-path)))
1938 (setq dir (directory-file-name (file-name-directory path)))
1939 (if (not (file-exists-p dir))
1940 (elmo-make-directory dir))
1941 (write-region-as-binary (point-min) (point-max)
1947 (defun elmo-file-cache-load (cache-path section)
1948 "Load cache on PATH into the current buffer.
1949 Return t if cache is loaded successfully."
1952 (when (and cache-path
1953 (if (elmo-cache-path-section-p cache-path)
1956 (setq cache-file (elmo-file-cache-expand-path
1959 (file-exists-p cache-file))
1960 (insert-file-contents-as-binary cache-file)
1965 (defun elmo-cache-path-section-p (path)
1966 "Return non-nil when PATH is `section' cache path."
1967 (file-directory-p path))
1969 (defun elmo-file-cache-get (msgid &optional section)
1970 "Returns the current file-cache object associated with MSGID.
1971 MSGID is the message-id of the message.
1972 If optional argument SECTION is specified, get partial file-cache object
1973 associated with SECTION."
1975 (let ((path (elmo-cache-get-path msgid)))
1976 (if (and path (file-exists-p path))
1977 (if (elmo-cache-path-section-p path)
1979 (if (file-exists-p (setq path (expand-file-name
1981 (cons path 'section))
1982 ;; section is not specified but sectional.
1983 (cons path 'section))
1986 (cons path 'entire)))
1993 (defun elmo-cache-expire ()
1995 (let* ((completion-ignore-case t)
1996 (method (completing-read (format "Expire by (%s): "
1997 elmo-cache-expire-default-method)
2001 (when (string= method "")
2002 (setq method elmo-cache-expire-default-method))
2003 (funcall (intern (concat "elmo-cache-expire-by-" method)))))
2005 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
2006 (let ((str (read-from-minibuffer prompt initial)))
2008 ((string-match "[0-9]*\\.[0-9]+" str)
2009 (string-to-number str))
2010 ((string-match "[0-9]+" str)
2011 (string-to-number (concat str ".0")))
2012 (t (error "%s is not number" str)))))
2014 (defun elmo-cache-expire-by-size (&optional kbytes)
2015 "Expire cache file by size.
2016 If KBYTES is kilo bytes (This value must be float)."
2018 (let ((size (or kbytes
2019 (and (interactive-p)
2020 (elmo-read-float-value-from-minibuffer
2021 "Enter cache disk size (Kbytes): "
2023 (if (integerp elmo-cache-expire-default-size)
2024 (float elmo-cache-expire-default-size)
2025 elmo-cache-expire-default-size))))
2026 (if (integerp elmo-cache-expire-default-size)
2027 (float elmo-cache-expire-default-size))))
2031 (message "Checking disk usage...")
2032 (setq total (/ (elmo-disk-usage
2033 elmo-cache-directory) Kbytes))
2034 (setq beginning total)
2035 (message "Checking disk usage...done")
2036 (let ((cfl (elmo-cache-get-sorted-cache-file-list))
2040 (while (and (<= size total)
2041 (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
2042 (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
2043 (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
2044 (when (elmo-file-cache-delete cur-file)
2045 (setq count (+ count 1))
2046 (message "%d cache(s) are expired." count))
2047 (setq deleted (+ deleted cur-size))
2048 (setq total (- total cur-size)))
2049 (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
2050 count deleted beginning))))
2052 (defun elmo-cache-make-file-entity (filename path)
2053 (cons filename (elmo-get-last-accessed-time filename path)))
2055 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
2056 (let ((cfl cache-file-list)
2057 flist firsts oldest-entity wonlist)
2059 (setq flist (cdr (car cfl)))
2060 (setq firsts (append firsts (list
2061 (cons (car (car cfl))
2063 (setq cfl (cdr cfl)))
2066 (if (and (not oldest-entity)
2067 (cdr (cdr (car firsts))))
2068 (setq oldest-entity (car firsts)))
2069 (if (and (cdr (cdr (car firsts)))
2070 (cdr (cdr oldest-entity))
2071 (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
2072 (setq oldest-entity (car firsts)))
2073 (setq firsts (cdr firsts)))
2074 (setq wonlist (assoc (car oldest-entity) cache-file-list))
2076 (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
2079 (defun elmo-cache-get-sorted-cache-file-list ()
2080 (let ((dirs (directory-files
2081 elmo-cache-directory
2086 (setq num (length dirs))
2087 (message "Collecting cache info...")
2089 (setq elist (mapcar (lambda (x)
2090 (elmo-cache-make-file-entity x (car dirs)))
2091 (directory-files (car dirs) nil "^[^\\.]")))
2092 (setq ret-val (append ret-val
2100 (when (> num elmo-display-progress-threshold)
2102 (elmo-display-progress
2103 'elmo-cache-get-sorted-cache-file-list "Collecting cache info..."
2105 (setq dirs (cdr dirs)))
2106 (message "Collecting cache info...done")
2109 (defun elmo-cache-expire-by-age (&optional days)
2110 (let ((age (or (and days (int-to-string days))
2111 (and (interactive-p)
2112 (read-from-minibuffer
2113 (format "Enter days (%s): "
2114 elmo-cache-expire-default-age)))
2115 (int-to-string elmo-cache-expire-default-age)))
2116 (dirs (directory-files
2117 elmo-cache-directory
2121 (if (string= age "")
2122 (setq age elmo-cache-expire-default-age)
2123 (setq age (string-to-int age)))
2124 (setq curtime (current-time))
2125 (setq curtime (+ (* (nth 0 curtime)
2126 (float 65536)) (nth 1 curtime)))
2128 (let ((files (directory-files (car dirs) t "^[^\\.]"))
2129 (limit-age (* age 86400)))
2131 (when (> (- curtime (elmo-get-last-accessed-time (car files)))
2133 (when (elmo-file-cache-delete (car files))
2134 (setq count (+ 1 count))
2135 (message "%d cache file(s) are expired." count)))
2136 (setq files (cdr files))))
2137 (setq dirs (cdr dirs)))))
2141 (defun elmo-msgid-to-cache (msgid)
2144 (string-match "<\\(.+\\)>$" msgid))
2145 (elmo-replace-string-as-filename (elmo-match-string 1 msgid)))))
2147 (defun elmo-cache-get-path (msgid &optional folder number)
2148 "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
2149 (if (setq msgid (elmo-msgid-to-cache msgid))
2153 (format "%s/%s/%s@%s"
2154 (elmo-cache-get-path-subr msgid)
2157 (elmo-safe-filename folder))
2159 (elmo-cache-get-path-subr msgid)
2161 elmo-cache-directory))))
2166 (static-if (fboundp 'display-warning)
2167 (defmacro elmo-warning (&rest args)
2168 "Display a warning with `elmo' group."
2169 `(display-warning 'elmo (format ,@args)))
2170 (defconst elmo-warning-buffer-name "*elmo warning*")
2171 (defun elmo-warning (&rest args)
2172 "Display a warning. ARGS are passed to `format'."
2173 (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
2174 (goto-char (point-max))
2175 (funcall 'insert (apply 'format (append args '("\n"))))
2176 (ignore-errors (recenter 1))
2177 (display-buffer elmo-warning-buffer-name))))
2179 (defvar elmo-obsolete-variable-alist nil)
2181 (defcustom elmo-obsolete-variable-show-warnings t
2182 "Show warning window if obsolete variable is treated."
2186 (defun elmo-define-obsolete-variable (obsolete var)
2187 "Define obsolete variable.
2188 OBSOLETE is a symbol for obsolete variable.
2189 VAR is a symbol for new variable.
2190 Definition is stored in `elmo-obsolete-variable-alist'."
2191 (let ((pair (assq var elmo-obsolete-variable-alist)))
2193 (setcdr pair obsolete)
2194 (setq elmo-obsolete-variable-alist
2195 (cons (cons var obsolete)
2196 elmo-obsolete-variable-alist)))))
2198 (defun elmo-resque-obsolete-variable (obsolete var)
2199 "Resque obsolete variable OBSOLETE as VAR.
2200 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
2201 (when (boundp obsolete)
2202 (static-if (and (fboundp 'defvaralias)
2203 (subrp (symbol-function 'defvaralias)))
2204 (defvaralias var obsolete)
2205 (set var (symbol-value obsolete)))
2206 (if elmo-obsolete-variable-show-warnings
2207 (elmo-warning "%s is obsolete. Use %s instead."
2208 (symbol-name obsolete)
2209 (symbol-name var)))))
2211 (defun elmo-resque-obsolete-variables (&optional alist)
2212 "Resque obsolete variables in ALIST.
2213 ALIST is a list of cons cell of
2214 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
2215 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
2216 (dolist (pair elmo-obsolete-variable-alist)
2217 (elmo-resque-obsolete-variable (cdr pair)
2220 (defsubst elmo-msgdb-get-last-message-id (string)
2226 (goto-char (point-max))
2227 (when (search-backward "<" nil t)
2229 (if (search-forward ">" nil t)
2230 (elmo-replace-in-string
2231 (buffer-substring beg (point)) "\n[ \t]*" ""))))))))
2233 (defun elmo-msgdb-get-message-id-from-buffer ()
2234 (let ((msgid (elmo-field-body "message-id")))
2236 (if (string-match "<\\(.+\\)>$" msgid)
2238 (concat "<" msgid ">")) ; Invaild message-id.
2239 ;; no message-id, so put dummy msgid.
2241 (if (elmo-unfold-field-body "date")
2242 (timezone-make-date-sortable (elmo-unfold-field-body "date"))
2243 (md5 (string-as-unibyte (buffer-string))))
2244 (nth 1 (eword-extract-address-components
2245 (or (elmo-field-body "from") "nobody"))) ">"))))
2247 (defun elmo-msgdb-get-references-from-buffer ()
2248 (if elmo-msgdb-prefer-in-reply-to-for-parent
2249 (or (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to"))
2250 (elmo-msgdb-get-last-message-id (elmo-field-body "references")))
2251 (or (elmo-msgdb-get-last-message-id (elmo-field-body "references"))
2252 (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to")))))
2254 (defsubst elmo-msgdb-insert-file-header (file)
2255 "Insert the header of the article."
2257 insert-file-contents-pre-hook ; To avoid autoconv-xmas...
2258 insert-file-contents-post-hook
2260 (when (file-exists-p file)
2261 ;; Read until header separator is found.
2262 (while (and (eq elmo-msgdb-file-header-chop-length
2264 (insert-file-contents-as-binary
2266 (incf beg elmo-msgdb-file-header-chop-length))))
2267 (prog1 (not (search-forward "\n\n" nil t))
2268 (goto-char (point-max))))))))
2271 ;; overview handling
2273 (defun elmo-multiple-field-body (name &optional boundary)
2276 (std11-narrow-to-header boundary)
2277 (goto-char (point-min))
2278 (let ((case-fold-search t)
2280 (while (re-search-forward (concat "^" name ":[ \t]*") nil t)
2283 (list (buffer-substring-no-properties
2284 (match-end 0) (std11-field-end))))))
2287 (defun elmo-parse-addresses (string)
2291 (let (list start s char)
2293 (goto-char (point-min))
2294 (skip-chars-forward "\t\f\n\r ")
2295 (setq start (point))
2297 (skip-chars-forward "^\"\\,(")
2298 (setq char (following-char))
2304 (setq s (buffer-substring start (point)))
2305 (if (or (null (string-match "^[\t\f\n\r ]+$" s))
2306 (not (string= s "")))
2307 (setq list (cons s list)))
2308 (skip-chars-forward ",\t\f\n\r ")
2309 (setq start (point)))
2311 (re-search-forward "[^\\]\"" nil 0))
2315 (while (and (not (eobp)) (not (zerop parens)))
2316 (re-search-forward "[()]" nil 0)
2318 (= (char-after (- (point) 2)) ?\\)))
2319 ((= (preceding-char) ?\()
2320 (setq parens (1+ parens)))
2322 (setq parens (1- parens)))))))))
2323 (setq s (buffer-substring start (point)))
2324 (if (and (null (string-match "^[\t\f\n\r ]+$" s))
2325 (not (string= s "")))
2326 (setq list (cons s list)))
2330 (defvar elmo-dop-queue-filename "queue"
2331 "*Disconnected operation queue is saved in this file.")
2333 (defun elmo-dop-queue-load ()
2334 (setq elmo-dop-queue
2336 (expand-file-name elmo-dop-queue-filename
2337 elmo-msgdb-directory))))
2339 (defun elmo-dop-queue-save ()
2341 (expand-file-name elmo-dop-queue-filename
2342 elmo-msgdb-directory)
2345 (if (and (fboundp 'regexp-opt)
2346 (not (featurep 'xemacs)))
2347 (defalias 'elmo-regexp-opt 'regexp-opt)
2348 (defun elmo-regexp-opt (strings &optional paren)
2349 "Return a regexp to match a string in STRINGS.
2350 Each string should be unique in STRINGS and should not contain any regexps,
2351 quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
2352 is enclosed by at least one regexp grouping construct."
2353 (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
2354 (concat open-paren (mapconcat 'regexp-quote strings "\\|")
2358 (product-provide (provide 'elmo-util) (require 'elmo-version))
2360 ;;; elmo-util.el ends here