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 (defmacro elmo-get-hash-val (string hashtable)
936 (static-if (fboundp 'unintern)
937 `(symbol-value (intern-soft ,string ,hashtable))
938 `(let ((sym (intern-soft ,string ,hashtable)))
940 (symbol-value sym)))))
942 (defmacro elmo-set-hash-val (string value hashtable)
943 `(set (intern ,string ,hashtable) ,value))
945 (defmacro elmo-clear-hash-val (string hashtable)
946 (static-if (fboundp 'unintern)
947 (list 'unintern string hashtable)
948 (list 'makunbound (list 'intern string hashtable))))
950 (defmacro elmo-unintern (string)
951 "`unintern' symbol named STRING, When can use `unintern'.
952 Emacs 19.28 or earlier does not have `unintern'."
953 (static-if (fboundp 'unintern)
954 (list 'unintern string)))
956 (defun elmo-make-hash (&optional hashsize)
957 "Make a new hash table which have HASHSIZE size."
961 ;; Prime numbers as lengths tend to result in good
962 ;; hashing; lengths one less than a power of two are
966 (while (< (- i 1) hashsize)
969 elmo-hash-maximum-size)
970 elmo-hash-minimum-size)
971 elmo-hash-minimum-size)
974 (defsubst elmo-mime-string (string)
975 "Normalize MIME encoded STRING."
977 (elmo-with-enable-multibyte
978 (encode-mime-charset-string
980 (eword-decode-and-unfold-unstructured-field-body string))
982 elmo-mime-charset))))
984 (defsubst elmo-collect-field (beg end downcase-field-name)
987 (narrow-to-region beg end)
988 (goto-char (point-min))
989 (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
991 (while (re-search-forward regexp nil t)
992 (setq name (buffer-substring-no-properties
993 (match-beginning 1)(1- (match-end 1))))
994 (if downcase-field-name
995 (setq name (downcase name)))
996 (setq body (buffer-substring-no-properties
997 (match-end 0) (std11-field-end)))
998 (or (assoc name dest)
999 (setq dest (cons (cons name body) dest))))
1002 (defsubst elmo-collect-field-from-string (string downcase-field-name)
1005 (goto-char (point-min))
1006 (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
1008 (while (re-search-forward regexp nil t)
1009 (setq name (buffer-substring-no-properties
1010 (match-beginning 1)(1- (match-end 1))))
1011 (if downcase-field-name
1012 (setq name (downcase name)))
1013 (setq body (buffer-substring-no-properties
1014 (match-end 0) (std11-field-end)))
1015 (or (assoc name dest)
1016 (setq dest (cons (cons name body) dest))))
1019 (defun elmo-safe-filename (filename)
1020 (let* ((replace-alist '(("/" . " ")
1025 (regexp-quote (mapconcat 'car replace-alist ""))
1029 (while (string-match regexp rest)
1030 (setq converted (concat converted
1031 (substring rest 0 (match-beginning 0))
1032 (cdr (assoc (substring rest
1036 rest (substring rest (match-end 0))))
1037 (concat converted rest)))
1039 (defvar elmo-filename-replace-chars nil)
1041 (defsubst elmo-replace-string-as-filename (msgid)
1042 "Replace string as filename."
1043 (setq msgid (elmo-replace-in-string msgid " " " "))
1044 (if (null elmo-filename-replace-chars)
1045 (setq elmo-filename-replace-chars
1046 (regexp-quote (mapconcat
1047 'car elmo-filename-replace-string-alist ""))))
1048 (while (string-match (concat "[" elmo-filename-replace-chars "]")
1051 (substring msgid 0 (match-beginning 0))
1054 (match-beginning 0) (match-end 0))
1055 elmo-filename-replace-string-alist))
1056 (substring msgid (match-end 0)))))
1059 (defsubst elmo-recover-string-from-filename (filename)
1060 "Recover string from FILENAME."
1062 (while (string-match " " filename)
1063 (setq tmp (substring filename
1065 (+ (match-end 0) 1)))
1066 (if (string= tmp " ")
1068 (setq tmp (car (rassoc tmp
1069 elmo-filename-replace-string-alist))))
1072 (substring filename 0 (match-beginning 0))
1074 (setq filename (substring filename (+ (match-end 0) 1))))
1075 (concat result filename)))
1077 (defsubst elmo-copy-file (src dst &optional ok-if-already-exists)
1079 (elmo-add-name-to-file src dst ok-if-already-exists)
1080 (error (copy-file src dst ok-if-already-exists t))))
1082 (defsubst elmo-buffer-exists-p (buffer)
1083 (if (bufferp buffer)
1084 (buffer-live-p buffer)
1085 (get-buffer buffer)))
1087 (defsubst elmo-kill-buffer (buffer)
1088 (when (elmo-buffer-exists-p buffer)
1089 (kill-buffer buffer)))
1091 (defun elmo-delete-if (pred lst)
1092 "Return new list contain items which don't satisfy PRED in LST."
1095 (unless (funcall pred (car lst))
1096 (setq result (cons (car lst) result)))
1097 (setq lst (cdr lst)))
1100 (defun elmo-list-delete (list1 list2 &optional delete-function)
1101 "Delete by side effect any occurrences equal to elements of LIST1 from LIST2.
1102 Return the modified LIST2. Deletion is done with `delete'.
1103 Write `(setq foo (elmo-list-delete bar foo))' to be sure of changing
1105 If optional DELETE-FUNCTION is speficied, it is used as delete procedure."
1106 (setq delete-function (or delete-function 'delete))
1108 (setq list2 (funcall delete-function (car list1) list2))
1109 (setq list1 (cdr list1)))
1112 (defun elmo-list-member (list1 list2)
1113 "If any element of LIST1 is member of LIST2, return t."
1116 (if (member (car list1) list2)
1118 (setq list1 (cdr list1)))))
1120 (defun elmo-count-matches (regexp beg end)
1124 (while (re-search-forward regexp end t)
1125 (setq count (1+ count)))
1128 (if (fboundp 'display-error)
1129 (defalias 'elmo-display-error 'display-error)
1130 (defun elmo-display-error (error-object stream)
1131 "A tiny function to display ERROR-OBJECT to the STREAM."
1133 (errobj error-object)
1136 (setq err-mes (concat err-mes (format
1137 (if (stringp (car errobj))
1141 (setq errobj (cdr errobj))
1142 (if errobj (setq err-mes (concat err-mes (if first ": " ", "))))
1144 (princ err-mes stream))))
1146 (if (fboundp 'define-error)
1147 (defalias 'elmo-define-error 'define-error)
1148 (defun elmo-define-error (error doc &optional parents)
1150 (setq parents 'error))
1151 (let ((conds (get parents 'error-conditions)))
1153 (error "Not an error symbol: %s" error))
1155 (list 'error-message doc
1156 'error-conditions (cons error conds))))))
1158 (defvar elmo-progress-counter nil)
1160 (defalias 'elmo-progress-counter-label 'car-safe)
1162 (defmacro elmo-progress-counter-value (counter)
1163 `(aref (cdr ,counter) 0))
1165 (defmacro elmo-progress-counter-set-value (counter value)
1166 `(aset (cdr ,counter) 0 ,value))
1168 (defmacro elmo-progress-counter-total (counter)
1169 `(aref (cdr ,counter) 1))
1171 (defmacro elmo-progress-counter-set-total (counter value)
1172 `(aset (cdr ,counter) 1 ,value))
1174 (defmacro elmo-progress-counter-action (counter)
1175 `(aref (cdr ,counter) 2))
1177 (defmacro elmo-progress-counter-set-action (counter action)
1178 `(aset (cdr ,counter) 2, action))
1180 (defvar elmo-progress-callback-function nil)
1182 (defun elmo-progress-call-callback (counter &optional value)
1183 (when elmo-progress-callback-function
1184 (funcall elmo-progress-callback-function
1185 (elmo-progress-counter-label counter)
1186 (elmo-progress-counter-action counter)
1188 (elmo-progress-counter-value counter))
1189 (elmo-progress-counter-total counter))))
1191 (defun elmo-progress-start (label total action)
1192 (when (and (null elmo-progress-counter)
1195 (let ((counter (cons label (vector 0 total action))))
1196 (elmo-progress-call-callback counter 'start)
1197 (setq elmo-progress-counter
1200 ((elmo-progress-call-callback counter 'query)
1201 (elmo-progress-call-callback counter)
1207 (defun elmo-progress-clear (counter)
1209 (when (and (elmo-progress-counter-label elmo-progress-counter)
1210 (elmo-progress-counter-total elmo-progress-counter))
1211 (elmo-progress-call-callback elmo-progress-counter 100))
1212 (setq elmo-progress-counter nil)))
1214 (defun elmo-progress-done (counter)
1215 (when (elmo-progress-counter-label counter)
1216 (elmo-progress-call-callback counter 'done)))
1218 (defun elmo-progress-notify (label &rest params)
1219 (when (eq label (elmo-progress-counter-label elmo-progress-counter))
1220 (let ((counter elmo-progress-counter))
1221 (if (or (elmo-progress-counter-total counter)
1222 (and (elmo-progress-counter-set-total
1224 (plist-get params :total))
1225 (elmo-progress-call-callback counter 'query)))
1227 (elmo-progress-counter-set-value
1229 (or (plist-get params :set)
1230 (+ (elmo-progress-counter-value counter)
1231 (or (plist-get params :inc)
1234 (elmo-progress-call-callback counter))
1235 (setq elmo-progress-counter t)))))
1237 (defmacro elmo-with-progress-display (spec message &rest body)
1238 "Evaluate BODY with progress message.
1239 SPEC is a list as followed (LABEL TOTAL [VAR])."
1240 (let ((label (nth 0 spec))
1241 (total (nth 1 spec))
1242 (var (or (nth 2 spec) (make-symbol "--elmo-progress-temp--"))))
1243 `(let ((,var (elmo-progress-start (quote ,label) ,total ,message)))
1248 (elmo-progress-clear ,var))
1249 (elmo-progress-done ,var)))))
1251 (put 'elmo-with-progress-display 'lisp-indent-function '2)
1252 (def-edebug-spec elmo-with-progress-display
1253 ((symbolp form &optional symbolp) form &rest form))
1255 (defun elmo-time-expire (before-time diff-time)
1256 (let* ((current (current-time))
1257 (rest (when (< (nth 1 current) (nth 1 before-time))
1261 (list (- (+ (car current) (if rest -1 0)) (car before-time))
1262 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1263 (and (eq (car diff) 0)
1264 (< diff-time (nth 1 diff)))))
1266 (if (fboundp 'std11-fetch-field)
1267 (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1268 (defalias 'elmo-field-body 'std11-field-body))
1270 (defun elmo-unfold-field-body (name)
1271 (let ((value (elmo-field-body name)))
1273 (std11-unfold-string value))))
1275 (defun elmo-decoded-field-body (field-name &optional mode)
1276 (let ((field-body (elmo-field-body field-name)))
1279 (elmo-with-enable-multibyte
1280 (mime-decode-field-body field-body field-name mode)))
1283 (defun elmo-address-quote-specials (word)
1284 "Make quoted string of WORD if needed."
1285 (let ((lal (std11-lexical-analyze word)))
1286 (if (or (assq 'specials lal)
1287 (assq 'domain-literal lal))
1288 (prin1-to-string word)
1291 (defmacro elmo-string (string)
1292 "STRING without text property."
1293 (` (let ((obj (copy-sequence (, string))))
1294 (and obj (set-text-properties 0 (length obj) nil obj))
1297 (defun elmo-flatten (list-of-list)
1298 "Flatten LIST-OF-LIST."
1301 (mapcar (lambda (element)
1302 (if (listp element) element (list element)))
1305 (defun elmo-y-or-n-p (prompt &optional auto default)
1306 "Same as `y-or-n-p'.
1307 But if optional argument AUTO is non-nil, DEFAULT is returned."
1312 (defun elmo-string-member (string slist)
1314 (dolist (element slist)
1315 (cond ((null element))
1317 (when (string= string element)
1320 (when (string= string (symbol-value element))
1321 (throw 'found t)))))))
1323 (static-cond ((fboundp 'member-ignore-case)
1324 (defalias 'elmo-string-member-ignore-case 'member-ignore-case))
1325 ((fboundp 'compare-strings)
1326 (defun elmo-string-member-ignore-case (elt list)
1327 "Like `member', but ignores differences in case and text representation.
1328 ELT must be a string. Upper-case and lower-case letters are treated as equal.
1329 Unibyte strings are converted to multibyte for comparison."
1330 (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
1331 (setq list (cdr list)))
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 (let ((str (downcase elt)))
1338 (while (and list (not (string= str (downcase (car list)))))
1339 (setq list (cdr list)))
1342 (defun elmo-string-match-member (str list &optional case-ignore)
1343 (let ((case-fold-search case-ignore))
1346 (if (string-match (car list) str)
1347 (throw 'member (car list)))
1348 (setq list (cdr list))))))
1350 (defun elmo-string-matched-member (str list &optional case-ignore)
1351 (let ((case-fold-search case-ignore))
1354 (if (string-match str (car list))
1355 (throw 'member (car list)))
1356 (setq list (cdr list))))))
1358 (defsubst elmo-string-delete-match (string pos)
1359 (concat (substring string
1360 0 (match-beginning pos))
1365 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1366 (let ((case-fold-search case-ignore)
1370 (setq a (car alist))
1373 (string-match key (car a)))
1375 (setq alist (cdr alist))))))
1377 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1378 (let ((case-fold-search case-ignore)
1382 (setq a (car alist))
1385 (string-match (car a) key))
1387 (setq alist (cdr alist))))))
1389 (defun elmo-string-assoc (key alist)
1393 (setq a (car alist))
1396 (string= key (car a)))
1398 (setq alist (cdr alist))))))
1400 (defun elmo-string-assoc-all (key alist)
1403 (if (string= key (car (car alist)))
1407 (setq alist (cdr alist)))
1410 (defun elmo-string-rassoc (key alist)
1414 (setq a (car alist))
1417 (string= key (cdr a)))
1419 (setq alist (cdr alist))))))
1421 (defun elmo-string-rassoc-all (key alist)
1424 (if (string= key (cdr (car alist)))
1428 (setq alist (cdr alist)))
1431 (defun elmo-expand-newtext (newtext original)
1432 (let ((len (length newtext))
1434 c expanded beg N did-expand)
1437 (while (and (< pos len)
1438 (not (= (aref newtext pos) ?\\)))
1439 (setq pos (1+ pos)))
1441 (push (substring newtext beg pos) expanded))
1443 ;; We hit a \; expand it.
1446 c (aref newtext pos))
1447 (if (not (or (= c ?\&)
1450 ;; \ followed by some character we don't expand.
1451 (push (char-to-string c) expanded)
1456 (when (match-beginning N)
1457 (push (substring original (match-beginning N) (match-end N))
1459 (setq pos (1+ pos)))
1461 (apply (function concat) (nreverse expanded))
1464 ;;; Folder parser utils.
1465 (defconst elmo-quoted-specials-list '(?\\ ?\"))
1467 (defun elmo-quoted-token (string)
1469 (std11-wrap-as-quoted-pairs string elmo-quoted-specials-list)
1472 (defun elmo-token-valid-p (token requirement)
1473 (cond ((null requirement))
1474 ((stringp requirement)
1475 (string-match requirement token))
1476 ((functionp requirement)
1477 (funcall requirement token))))
1479 (defun elmo-parse-token (string &optional seps requirement)
1480 "Parse atom from STRING using SEPS as a string of separator char list."
1481 (let ((len (length string))
1482 (seps (and seps (string-to-char-list seps)))
1488 (while (and (< i len) (or in (null sep)))
1489 (setq c (aref string i))
1491 ((and in (eq c ?\\))
1493 content (cons (aref string i) content)
1498 (in (setq content (cons c content)
1502 (t (setq content (cons c content)
1504 (if in (error "Parse error in quoted"))
1505 (let ((atom (if (null content)
1507 (char-list-to-string (nreverse content)))))
1508 (if (elmo-token-valid-p atom requirement)
1509 (cons atom (substring string i))
1510 (cons "" string))))))
1512 (defun elmo-parse-prefixed-element (prefix string &optional seps requirement)
1514 (if (and (not (eq (length string) 0))
1515 (eq (aref string 0) prefix)
1516 (setq parsed (elmo-parse-token (substring string 1) seps))
1517 (elmo-token-valid-p (car parsed) requirement))
1521 (defun elmo-collect-separators (spec)
1523 (let ((result (elmo-collect-separators-internal spec)))
1525 (char-list-to-string (elmo-uniq-list result #'delq))))))
1527 (defun elmo-collect-separators-internal (specs &optional separators)
1529 (let ((spec (car specs)))
1532 (setq separators (elmo-collect-separators-internal spec separators)
1535 (setq separators (cons spec separators)
1538 (setq specs nil)))))
1541 (defun elmo-collect-trail-separators (element specs)
1546 (eq (aref specs 0) element))
1549 (while (setq spec (car specs))
1550 (if (setq result (elmo-collect-trail-separators element spec))
1551 (setq result (concat (if (stringp result) result)
1552 (elmo-collect-separators (cdr specs)))
1554 (setq specs (cdr specs))))
1557 (defun elmo-parse-separated-tokens (string spec)
1558 (let ((result (elmo-parse-separated-tokens-internal string spec)))
1559 (if (eq (car result) t)
1560 (cons nil (cdr result))
1563 (defun elmo-parse-separated-tokens-internal (string spec &optional separators)
1566 (let ((parse (elmo-parse-token string separators)))
1567 (cons (list (cons spec (car parse))) (cdr parse))))
1569 (let ((parse (elmo-parse-token string separators)))
1570 (if (elmo-token-valid-p (car parse) (aref spec 1))
1571 (cons (list (cons (aref spec 0) (car parse))) (cdr parse))
1572 (cons nil string))))
1574 (if (and (> (length string) 0)
1575 (eq (aref string 0) spec))
1576 (cons t (substring string 1))
1583 (setq result (elmo-parse-separated-tokens-internal
1586 (concat (elmo-collect-separators (cdr spec))
1588 (cond ((null (car result))
1589 (throw 'unmatch (cons t string)))
1590 ((eq t (car result)))
1592 (setq tokens (nconc (car result) tokens))))
1593 (setq rest (cdr result)
1595 (cons (or tokens t) rest))))))
1597 (defun elmo-quote-syntactical-element (value element syntax)
1598 (let ((separators (elmo-collect-trail-separators element syntax)))
1600 (string-match (concat "[" separators "]") value))
1601 (elmo-quoted-token value)
1604 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1606 ;; number ::= [0-9]+
1609 ;; number-range ::= "(" beg " . " end ")" ;; cons cell
1610 ;; number-set-elem ::= number / number-range
1611 ;; number-set ::= "(" *number-set-elem ")" ;; list
1613 (defun elmo-number-set-member (number number-set)
1614 "Return non-nil if NUMBER is an element of NUMBER-SET.
1615 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1616 (or (memq number number-set)
1618 (while (and number-set (not found))
1619 (if (and (consp (car number-set))
1620 (and (<= (car (car number-set)) number)
1621 (<= number (cdr (car number-set)))))
1623 (setq number-set (cdr number-set))))
1626 (defun elmo-number-set-append-list (number-set list)
1627 "Append LIST of numbers to the NUMBER-SET.
1628 NUMBER-SET is altered."
1629 (let ((appended number-set))
1631 (setq appended (elmo-number-set-append appended (car list)))
1632 (setq list (cdr list)))
1635 (defun elmo-number-set-append (number-set number)
1636 "Append NUMBER to the NUMBER-SET.
1637 NUMBER-SET is altered."
1638 (let ((number-set-1 number-set)
1640 (while (and number-set (not found))
1641 (setq elem (car number-set))
1644 (eq (+ 1 (cdr elem)) number))
1645 (setcdr elem number)
1647 ((and (integerp elem)
1648 (eq (+ 1 elem) number))
1649 (setcar number-set (cons elem number))
1651 ((or (and (integerp elem) (eq elem number))
1653 (<= (car elem) number)
1654 (<= number (cdr elem))))
1656 (setq number-set (cdr number-set)))
1658 (setq number-set-1 (nconc number-set-1 (list number))))
1661 (defun elmo-number-set-delete-list (number-set list)
1662 "Delete LIST of numbers from the NUMBER-SET.
1663 NUMBER-SET is altered."
1664 (let ((deleted number-set))
1665 (dolist (number list)
1666 (setq deleted (elmo-number-set-delete deleted number)))
1669 (defun elmo-number-set-delete (number-set number)
1670 "Delete NUMBER from the NUMBER-SET.
1671 NUMBER-SET is altered."
1672 (let* ((curr number-set)
1673 (top (cons 'dummy number-set))
1676 (while (and curr (not found))
1677 (setq elem (car curr))
1680 ((eq (car elem) number)
1681 (if (eq (cdr elem) (1+ number))
1682 (setcar curr (cdr elem))
1683 (setcar elem (1+ number)))
1685 ((eq (cdr elem) number)
1686 (if (eq (car elem) (1- number))
1687 (setcar curr (car elem))
1688 (setcdr elem (1- number)))
1690 ((and (> number (car elem))
1691 (< number (cdr elem)))
1696 ;; (beg . (1- number))
1697 (let ((new (cons (car elem) (1- number))))
1698 (if (eq (car new) (cdr new))
1701 ;; ((1+ number) . end)
1702 (let ((new (cons (1+ number) (cdr elem))))
1703 (if (eq (car new) (cdr new))
1707 (when (eq elem number)
1708 (setcdr prev (cdr curr))
1714 (defun elmo-make-number-list (beg end)
1715 (let (number-list i)
1718 (setq number-list (cons i number-list))
1722 (defun elmo-number-set-to-number-list (number-set)
1723 "Return a number list which corresponds to NUMBER-SET."
1724 (let ((number-list (list 'dummy))
1727 (setq elem (car number-set))
1730 (nconc number-list (elmo-make-number-list (car elem) (cdr elem))))
1732 (nconc number-list (list elem))))
1733 (setq number-set (cdr number-set)))
1736 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1737 "*Regexp to filter subfolders."
1741 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1742 (let ((root (zerop (length curdir)))
1743 (w32-get-true-file-link-count t) ; for Meadow
1746 (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1747 (when (and (not (string-match
1748 elmo-list-subdirectories-ignore-regexp
1750 (car (setq attr (file-attributes
1751 (expand-file-name file dir)))))
1752 (when (eq one-level 'check) (throw 'done t))
1754 (concat curdir (and (not root) elmo-path-sep) file))
1756 (setq dirs (nconc dirs
1757 (if (if elmo-have-link-count (< 2 (nth 1 attr))
1759 (elmo-list-subdirectories-1
1762 (if one-level 'check))))
1764 (list (list relpath))
1767 (elmo-list-subdirectories-1
1771 (list relpath)))))))
1774 (defun elmo-list-subdirectories (directory file one-level)
1775 (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1776 (if (zerop (length file))
1778 (cons file subdirs))))
1780 (defun elmo-mapcar-list-of-list (func list-of-list)
1783 (cond ((listp x) (elmo-mapcar-list-of-list func x))
1784 (t (funcall func x))))
1787 (defun elmo-map-recursive (function object)
1789 (let* ((prev (list 'dummy))
1791 (while (consp object)
1792 (setq prev (setcdr prev (list (elmo-map-recursive function
1794 object (cdr object)))
1796 (setcdr prev (funcall function object)))
1798 (funcall function object)))
1800 (defun elmo-map-until-success (function sequence)
1802 (while (and (null result)
1804 (setq result (funcall function (car sequence))
1805 sequence (cdr sequence)))
1808 (defun elmo-string-match-substring (regexp string &optional matchn)
1809 (when (string-match regexp string)
1810 (match-string (or matchn 1) string)))
1812 (defun elmo-parse (string regexp &optional matchn)
1813 (or matchn (setq matchn 1))
1815 (store-match-data nil)
1816 (while (string-match regexp string (match-end 0))
1817 (setq list (cons (substring string (match-beginning matchn)
1818 (match-end matchn)) list)))
1821 (defun elmo-find-list-match-value (specs getter)
1822 (lexical-let ((getter getter))
1823 (elmo-map-until-success
1827 (funcall getter spec))
1829 (lexical-let ((value (funcall getter (car spec))))
1831 (elmo-map-until-success
1835 (elmo-string-match-substring rule value))
1837 (elmo-string-match-substring (car rule) value (cdr rule)))))
1842 (defmacro elmo-make-file-cache (path status)
1843 "PATH is the cache file name.
1844 STATUS is one of 'section, 'entire or nil.
1845 nil means no cache exists.
1846 'section means partial section cache exists.
1847 'entire means entire cache exists.
1848 If the cache is partial file-cache, TYPE is 'partial."
1849 (` (cons (, path) (, status))))
1851 (defmacro elmo-file-cache-path (file-cache)
1852 "Returns the file path of the FILE-CACHE."
1853 (` (car (, file-cache))))
1855 (defmacro elmo-file-cache-status (file-cache)
1856 "Returns the status of the FILE-CACHE."
1857 (` (cdr (, file-cache))))
1859 (defsubst elmo-cache-to-msgid (filename)
1860 (concat "<" (elmo-recover-string-from-filename filename) ">"))
1862 (defsubst elmo-cache-get-path-subr (msgid)
1863 (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1864 (clist (string-to-char-list msgid))
1867 (setq sum (+ sum (car clist)))
1868 (setq clist (cdr clist)))
1870 (nth (% (/ sum 16) 2) chars)
1871 (nth (% sum 16) chars))))
1874 (defun elmo-file-cache-get-path (msgid &optional section)
1875 "Get cache path for MSGID.
1876 If optional argument SECTION is specified, partial cache path is returned."
1877 (if (setq msgid (elmo-msgid-to-cache msgid))
1880 (format "%s/%s/%s/%s"
1881 elmo-cache-directory
1882 (elmo-cache-get-path-subr msgid)
1886 elmo-cache-directory
1887 (elmo-cache-get-path-subr msgid)
1890 (defmacro elmo-file-cache-expand-path (path section)
1891 "Return file name for the file-cache corresponds to the section.
1892 PATH is the file-cache path.
1893 SECTION is the section string."
1894 (` (expand-file-name (or (, section) "") (, path))))
1896 (defun elmo-file-cache-delete (path)
1897 "Delete a cache on PATH."
1898 (when (file-exists-p path)
1899 (if (file-directory-p path)
1901 (dolist (file (directory-files path t "^[^\\.]"))
1903 (delete-directory path))
1907 (defun elmo-file-cache-exists-p (msgid)
1908 "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1909 (elmo-file-cache-status (elmo-file-cache-get msgid)))
1911 (defun elmo-file-cache-save (cache-path section)
1912 "Save current buffer as cache on PATH.
1913 Return t if cache is saved successfully."
1915 (let ((path (if section (expand-file-name section cache-path)
1918 (if (and (null section)
1919 (file-directory-p path))
1921 (setq files (directory-files path t "^[^\\.]"))
1923 (delete-file (car files))
1924 (setq files (cdr files)))
1925 (delete-directory path))
1927 (not (file-directory-p cache-path)))
1928 (delete-file cache-path)))
1930 (setq dir (directory-file-name (file-name-directory path)))
1931 (if (not (file-exists-p dir))
1932 (elmo-make-directory dir))
1933 (write-region-as-binary (point-min) (point-max)
1939 (defun elmo-file-cache-load (cache-path section)
1940 "Load cache on PATH into the current buffer.
1941 Return t if cache is loaded successfully."
1944 (when (and cache-path
1945 (if (elmo-cache-path-section-p cache-path)
1948 (setq cache-file (elmo-file-cache-expand-path
1951 (file-exists-p cache-file))
1952 (insert-file-contents-as-binary cache-file)
1957 (defun elmo-cache-path-section-p (path)
1958 "Return non-nil when PATH is `section' cache path."
1959 (file-directory-p path))
1961 (defun elmo-file-cache-get (msgid &optional section)
1962 "Returns the current file-cache object associated with MSGID.
1963 MSGID is the message-id of the message.
1964 If optional argument SECTION is specified, get partial file-cache object
1965 associated with SECTION."
1967 (let ((path (elmo-cache-get-path msgid)))
1968 (if (and path (file-exists-p path))
1969 (if (elmo-cache-path-section-p path)
1971 (if (file-exists-p (setq path (expand-file-name
1973 (cons path 'section))
1974 ;; section is not specified but sectional.
1975 (cons path 'section))
1978 (cons path 'entire)))
1985 (defun elmo-cache-expire ()
1987 (let* ((completion-ignore-case t)
1988 (method (completing-read (format "Expire by (%s): "
1989 elmo-cache-expire-default-method)
1993 (when (string= method "")
1994 (setq method elmo-cache-expire-default-method))
1995 (funcall (intern (concat "elmo-cache-expire-by-" method)))))
1997 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
1998 (let ((str (read-from-minibuffer prompt initial)))
2000 ((string-match "[0-9]*\\.[0-9]+" str)
2001 (string-to-number str))
2002 ((string-match "[0-9]+" str)
2003 (string-to-number (concat str ".0")))
2004 (t (error "%s is not number" str)))))
2006 (defun elmo-cache-expire-by-size (&optional kbytes)
2007 "Expire cache file by size.
2008 If KBYTES is kilo bytes (This value must be float)."
2010 (let ((size (or kbytes
2011 (and (interactive-p)
2012 (elmo-read-float-value-from-minibuffer
2013 "Enter cache disk size (Kbytes): "
2015 (if (integerp elmo-cache-expire-default-size)
2016 (float elmo-cache-expire-default-size)
2017 elmo-cache-expire-default-size))))
2018 (if (integerp elmo-cache-expire-default-size)
2019 (float elmo-cache-expire-default-size))))
2023 (message "Checking disk usage...")
2024 (setq total (/ (elmo-disk-usage
2025 elmo-cache-directory) Kbytes))
2026 (setq beginning total)
2027 (message "Checking disk usage...done")
2028 (let ((cfl (elmo-cache-get-sorted-cache-file-list))
2032 (while (and (<= size total)
2033 (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
2034 (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
2035 (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
2036 (when (elmo-file-cache-delete cur-file)
2037 (setq count (+ count 1))
2038 (message "%d cache(s) are expired." count))
2039 (setq deleted (+ deleted cur-size))
2040 (setq total (- total cur-size)))
2041 (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
2042 count deleted beginning))))
2044 (defun elmo-cache-make-file-entity (filename path)
2045 (cons filename (elmo-get-last-accessed-time filename path)))
2047 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
2048 (let ((cfl cache-file-list)
2049 flist firsts oldest-entity wonlist)
2051 (setq flist (cdr (car cfl)))
2052 (setq firsts (append firsts (list
2053 (cons (car (car cfl))
2055 (setq cfl (cdr cfl)))
2058 (if (and (not oldest-entity)
2059 (cdr (cdr (car firsts))))
2060 (setq oldest-entity (car firsts)))
2061 (if (and (cdr (cdr (car firsts)))
2062 (cdr (cdr oldest-entity))
2063 (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
2064 (setq oldest-entity (car firsts)))
2065 (setq firsts (cdr firsts)))
2066 (setq wonlist (assoc (car oldest-entity) cache-file-list))
2068 (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
2071 (defun elmo-cache-get-sorted-cache-file-list ()
2072 (let ((dirs (directory-files elmo-cache-directory t "^[^\\.]"))
2074 (elmo-with-progress-display (elmo-collecting-cache (length dirs))
2075 "Collecting cache info"
2077 (setq elist (mapcar (lambda (x)
2078 (elmo-cache-make-file-entity x dir))
2079 (directory-files dir nil "^[^\\.]")))
2080 (setq ret-val (append ret-val
2090 (defun elmo-cache-expire-by-age (&optional days)
2091 "Expire cache file by age.
2092 Optional argument DAYS specifies the days to expire caches."
2094 (let ((age (or (and days (int-to-string days))
2095 (and (interactive-p)
2096 (read-from-minibuffer
2097 (format "Enter days (%s): "
2098 elmo-cache-expire-default-age)))
2099 (int-to-string elmo-cache-expire-default-age)))
2100 (dirs (directory-files
2101 elmo-cache-directory
2105 (if (string= age "")
2106 (setq age elmo-cache-expire-default-age)
2107 (setq age (string-to-int age)))
2108 (setq curtime (current-time))
2109 (setq curtime (+ (* (nth 0 curtime)
2110 (float 65536)) (nth 1 curtime)))
2112 (let ((files (directory-files (car dirs) t "^[^\\.]"))
2113 (limit-age (* age 86400)))
2115 (when (> (- curtime (elmo-get-last-accessed-time (car files)))
2117 (when (elmo-file-cache-delete (car files))
2118 (setq count (+ 1 count))
2119 (message "%d cache file(s) are expired." count)))
2120 (setq files (cdr files))))
2121 (setq dirs (cdr dirs)))))
2125 (defun elmo-msgid-to-cache (msgid)
2128 (string-match "<\\(.+\\)>$" msgid))
2129 (elmo-replace-string-as-filename (elmo-match-string 1 msgid)))))
2131 (defun elmo-cache-get-path (msgid &optional folder number)
2132 "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
2133 (if (setq msgid (elmo-msgid-to-cache msgid))
2137 (format "%s/%s/%s@%s"
2138 (elmo-cache-get-path-subr msgid)
2141 (elmo-safe-filename folder))
2143 (elmo-cache-get-path-subr msgid)
2145 elmo-cache-directory))))
2150 (static-if (fboundp 'display-warning)
2151 (defmacro elmo-warning (&rest args)
2152 "Display a warning with `elmo' group."
2153 `(display-warning 'elmo (format ,@args)))
2154 (defconst elmo-warning-buffer-name "*elmo warning*")
2155 (defun elmo-warning (&rest args)
2156 "Display a warning. ARGS are passed to `format'."
2157 (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
2158 (goto-char (point-max))
2159 (funcall 'insert (apply 'format (append args '("\n"))))
2160 (ignore-errors (recenter 1))
2161 (display-buffer elmo-warning-buffer-name))))
2163 (defvar elmo-obsolete-variable-alist nil)
2165 (defcustom elmo-obsolete-variable-show-warnings t
2166 "Show warning window if obsolete variable is treated."
2170 (defun elmo-define-obsolete-variable (obsolete var)
2171 "Define obsolete variable.
2172 OBSOLETE is a symbol for obsolete variable.
2173 VAR is a symbol for new variable.
2174 Definition is stored in `elmo-obsolete-variable-alist'."
2175 (let ((pair (assq var elmo-obsolete-variable-alist)))
2177 (setcdr pair obsolete)
2178 (setq elmo-obsolete-variable-alist
2179 (cons (cons var obsolete)
2180 elmo-obsolete-variable-alist)))))
2182 (defun elmo-resque-obsolete-variable (obsolete var)
2183 "Resque obsolete variable OBSOLETE as VAR.
2184 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
2185 (when (boundp obsolete)
2186 (static-if (and (fboundp 'defvaralias)
2187 (subrp (symbol-function 'defvaralias)))
2188 (defvaralias var obsolete)
2189 (set var (symbol-value obsolete)))
2190 (if elmo-obsolete-variable-show-warnings
2191 (elmo-warning "%s is obsolete. Use %s instead."
2192 (symbol-name obsolete)
2193 (symbol-name var)))))
2195 (defun elmo-resque-obsolete-variables (&optional alist)
2196 "Resque obsolete variables in ALIST.
2197 ALIST is a list of cons cell of
2198 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
2199 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
2200 (dolist (pair elmo-obsolete-variable-alist)
2201 (elmo-resque-obsolete-variable (cdr pair)
2204 (defsubst elmo-msgdb-get-last-message-id (string)
2210 (goto-char (point-max))
2211 (when (search-backward "<" nil t)
2213 (if (search-forward ">" nil t)
2214 (elmo-replace-in-string
2215 (buffer-substring beg (point)) "\n[ \t]*" ""))))))))
2217 (defun elmo-msgdb-get-message-id-from-buffer ()
2218 (let ((msgid (elmo-field-body "message-id")))
2220 (if (string-match "<\\(.+\\)>$" msgid)
2222 (concat "<" msgid ">")) ; Invaild message-id.
2223 ;; no message-id, so put dummy msgid.
2225 (if (elmo-unfold-field-body "date")
2226 (timezone-make-date-sortable (elmo-unfold-field-body "date"))
2227 (md5 (string-as-unibyte (buffer-string))))
2228 (nth 1 (eword-extract-address-components
2229 (or (elmo-field-body "from") "nobody"))) ">"))))
2231 (defun elmo-msgdb-get-references-from-buffer ()
2232 (if elmo-msgdb-prefer-in-reply-to-for-parent
2233 (or (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to"))
2234 (elmo-msgdb-get-last-message-id (elmo-field-body "references")))
2235 (or (elmo-msgdb-get-last-message-id (elmo-field-body "references"))
2236 (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to")))))
2238 (defsubst elmo-msgdb-insert-file-header (file)
2239 "Insert the header of the article."
2241 insert-file-contents-pre-hook ; To avoid autoconv-xmas...
2242 insert-file-contents-post-hook
2244 (when (file-exists-p file)
2245 ;; Read until header separator is found.
2246 (while (and (eq elmo-msgdb-file-header-chop-length
2248 (insert-file-contents-as-binary
2250 (incf beg elmo-msgdb-file-header-chop-length))))
2251 (prog1 (not (search-forward "\n\n" nil t))
2252 (goto-char (point-max))))))))
2255 ;; overview handling
2257 (defun elmo-multiple-field-body (name &optional boundary)
2260 (std11-narrow-to-header boundary)
2261 (goto-char (point-min))
2262 (let ((case-fold-search t)
2264 (while (re-search-forward (concat "^" name ":[ \t]*") nil t)
2267 (list (buffer-substring-no-properties
2268 (match-end 0) (std11-field-end))))))
2271 (defun elmo-parse-addresses (string)
2275 (let (list start s char)
2277 (goto-char (point-min))
2278 (skip-chars-forward "\t\f\n\r ")
2279 (setq start (point))
2281 (skip-chars-forward "^\"\\,(")
2282 (setq char (following-char))
2288 (setq s (buffer-substring start (point)))
2289 (if (or (null (string-match "^[\t\f\n\r ]+$" s))
2290 (not (string= s "")))
2291 (setq list (cons s list)))
2292 (skip-chars-forward ",\t\f\n\r ")
2293 (setq start (point)))
2295 (re-search-forward "[^\\]\"" nil 0))
2299 (while (and (not (eobp)) (not (zerop parens)))
2300 (re-search-forward "[()]" nil 0)
2302 (= (char-after (- (point) 2)) ?\\)))
2303 ((= (preceding-char) ?\()
2304 (setq parens (1+ parens)))
2306 (setq parens (1- parens)))))))))
2307 (setq s (buffer-substring start (point)))
2308 (if (and (null (string-match "^[\t\f\n\r ]+$" s))
2309 (not (string= s "")))
2310 (setq list (cons s list)))
2314 (defvar elmo-dop-queue-filename "queue"
2315 "*Disconnected operation queue is saved in this file.")
2317 (defun elmo-dop-queue-load ()
2318 (setq elmo-dop-queue
2320 (expand-file-name elmo-dop-queue-filename
2321 elmo-msgdb-directory))))
2323 (defun elmo-dop-queue-save ()
2325 (expand-file-name elmo-dop-queue-filename
2326 elmo-msgdb-directory)
2329 (if (and (fboundp 'regexp-opt)
2330 (not (featurep 'xemacs)))
2331 (defalias 'elmo-regexp-opt 'regexp-opt)
2332 (defun elmo-regexp-opt (strings &optional paren)
2333 "Return a regexp to match a string in STRINGS.
2334 Each string should be unique in STRINGS and should not contain any regexps,
2335 quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
2336 is enclosed by at least one regexp grouping construct."
2337 (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
2338 (concat open-paren (mapconcat 'regexp-quote strings "\\|")
2342 (product-provide (provide 'elmo-util) (require 'elmo-version))
2344 ;;; elmo-util.el ends here