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"))
63 ;; Any Emacsen may have add-name-to-file(), because loadup.el requires it. :-p
64 ;; Check make-symbolic-link() instead. -- 981002 by Fuji
65 (if (fboundp 'make-symbolic-link) ;; xxx
66 (defalias 'elmo-add-name-to-file 'add-name-to-file)
67 (defun elmo-add-name-to-file
68 (filename newname &optional ok-if-already-exists)
69 (copy-file filename newname ok-if-already-exists t)))
71 (defmacro elmo-set-work-buf (&rest body)
72 "Execute BODY on work buffer. Work buffer remains."
74 (set-buffer (get-buffer-create elmo-work-buf-name))
75 (set-buffer-multibyte default-enable-multibyte-characters)
79 (put 'elmo-set-work-buf 'lisp-indent-function 0)
80 (def-edebug-spec elmo-set-work-buf t)
82 (defmacro elmo-bind-directory (dir &rest body)
83 "Set current directory DIR and execute BODY."
84 (` (let ((default-directory (file-name-as-directory (, dir))))
87 (put 'elmo-bind-directory 'lisp-indent-function 1)
88 (def-edebug-spec elmo-bind-directory
91 (defconst elmo-multibyte-buffer-name " *elmo-multibyte-buffer*")
93 (defmacro elmo-with-enable-multibyte (&rest body)
94 "Evaluate BODY with `default-enable-multibyte-character'."
95 `(with-current-buffer (get-buffer-create elmo-multibyte-buffer-name)
98 (put 'elmo-with-enable-multibyte 'lisp-indent-function 0)
99 (def-edebug-spec elmo-with-enable-multibyte t)
102 (unless (fboundp 'coding-system-base)
103 (defalias 'coding-system-base 'ignore))
104 (unless (fboundp 'coding-system-name)
105 (defalias 'coding-system-name 'ignore))
106 (unless (fboundp 'find-file-coding-system-for-read-from-filename)
107 (defalias 'find-file-coding-system-for-read-from-filename 'ignore))
108 (unless (fboundp 'find-operation-coding-system)
109 (defalias 'find-operation-coding-system 'ignore)))
111 (defun elmo-set-auto-coding (&optional filename)
112 "Find coding system used to decode the contents of the current buffer.
113 This function looks for the coding system magic cookie or examines the
114 coding system specified by `file-coding-system-alist' being associated
115 with FILENAME which defaults to `buffer-file-name'."
117 ((boundp 'set-auto-coding-function) ;; Emacs
119 (or (funcall (symbol-value 'set-auto-coding-function)
120 filename (- (point-max) (point-min)))
121 (car (find-operation-coding-system 'insert-file-contents
123 (let (auto-coding-alist)
125 (funcall (symbol-value 'set-auto-coding-function)
126 nil (- (point-max) (point-min)))
128 ((featurep 'file-coding) ;; XEmacs
129 (let ((case-fold-search t)
133 (and (re-search-forward "-\\*-+[\t ]*" end t)
135 (setq start (match-end 0))
136 (re-search-forward "[\t ]*-+\\*-" end t))
138 (setq end (match-beginning 0))
140 (or (looking-at "coding:[\t ]*\\([^\t ;]+\\)")
142 "[\t ;]+coding:[\t ]*\\([^\t ;]+\\)"
144 (find-coding-system (setq codesys
145 (intern (match-string 1))))
147 (and (re-search-forward "^[\t ]*;+[\t ]*Local[\t ]+Variables:"
150 (setq start (match-end 0))
151 (re-search-forward "^[\t ]*;+[\t ]*End:" nil t))
153 (setq end (match-beginning 0))
156 "^[\t ]*;+[\t ]*coding:[\t ]*\\([^\t\n\r ]+\\)"
158 (find-coding-system (setq codesys
159 (intern (match-string 1))))
162 (goto-char (point-min))
163 (setq case-fold-search nil)
164 (re-search-forward "^;;;coding system: "
165 ;;(+ (point-min) 3000) t))
167 (looking-at "[^\t\n\r ]+")
169 (setq codesys (intern (match-string 0))))
173 (find-file-coding-system-for-read-from-filename
175 (coding-system-name (coding-system-base codesys))))))))
177 (defun elmo-object-load (filename &optional mime-charset no-err)
178 "Load OBJECT from the file specified by FILENAME.
179 File content is decoded with MIME-CHARSET."
180 (if (not (file-readable-p filename))
183 (insert-file-contents-as-binary filename)
184 (let ((coding-system (or (elmo-set-auto-coding)
185 (mime-charset-to-coding-system
188 (decode-coding-region (point-min) (point-max) coding-system)))
189 (goto-char (point-min))
191 (read (current-buffer))
192 (error (unless no-err
193 (message "Warning: Loading object from %s failed."
195 (elmo-object-save filename nil mime-charset))
198 (defsubst elmo-save-buffer (filename &optional mime-charset)
199 "Save current buffer to the file specified by FILENAME.
200 Directory of the file is created if it doesn't exist.
201 File content is encoded with MIME-CHARSET."
202 (let ((dir (directory-file-name (file-name-directory filename))))
203 (if (file-directory-p dir)
205 (unless (file-exists-p dir)
206 (elmo-make-directory dir)))
207 (if (file-writable-p filename)
210 ;;; (set-buffer-multibyte default-enable-multibyte-characters)
211 (encode-mime-charset-region (point-min) (point-max) mime-charset))
212 (as-binary-output-file
213 (write-region (point-min) (point-max) filename nil 'no-msg)))
214 (message "%s is not writable." filename))))
216 (defun elmo-object-save (filename object &optional mime-charset)
217 "Save OBJECT to the file specified by FILENAME.
218 Directory of the file is created if it doesn't exist.
219 File content is encoded with MIME-CHARSET."
221 (let (print-length print-level)
222 (prin1 object (current-buffer)))
224 (let ((coding (mime-charset-to-coding-system
225 (or (detect-mime-charset-region (point-min) (point-max))
227 (goto-char (point-min))
228 (insert ";;; -*- mode: emacs-lisp; coding: "
229 (symbol-name coding) " -*-\n")
230 (encode-coding-region (point-min) (point-max) coding)))
231 (elmo-save-buffer filename)))
235 (defconst elmo-condition-atom-regexp "[^/ \")|&]*")
237 (defsubst elmo-condition-parse-error ()
238 (error "Syntax error in '%s'" (buffer-string)))
240 (defun elmo-parse-search-condition (condition)
242 Return value is a cons cell of (STRUCTURE . REST)"
245 (goto-char (point-min))
246 (cons (elmo-condition-parse) (buffer-substring (point) (point-max)))))
248 ;; condition ::= or-expr
249 (defun elmo-condition-parse ()
250 (or (elmo-condition-parse-or-expr)
251 (elmo-condition-parse-error)))
253 ;; or-expr ::= and-expr /
254 ;; and-expr "|" or-expr
255 (defun elmo-condition-parse-or-expr ()
256 (let ((left (elmo-condition-parse-and-expr)))
257 (if (looking-at "| *")
259 (goto-char (match-end 0))
260 (list 'or left (elmo-condition-parse-or-expr)))
263 ;; and-expr ::= primitive /
264 ;; primitive "&" and-expr
265 (defun elmo-condition-parse-and-expr ()
266 (let ((left (elmo-condition-parse-primitive)))
267 (if (looking-at "& *")
269 (goto-char (match-end 0))
270 (list 'and left (elmo-condition-parse-and-expr)))
273 ;; primitive ::= "(" expr ")" /
274 ;; ["!"] search-key SPACE* ":" SPACE* search-value
275 (defun elmo-condition-parse-primitive ()
278 (goto-char (match-end 0))
279 (prog1 (elmo-condition-parse)
280 (unless (looking-at ") *")
281 (elmo-condition-parse-error))
282 (goto-char (match-end 0))))
283 ;; search-key ::= [A-Za-z-]+
284 ;; ;; "since" / "before" / "last" / "first" /
285 ;; ;; "body" / "flag" / field-name
286 ((looking-at "\\(!\\)? *\\([A-Za-z-]+\\) *: *")
287 (goto-char (match-end 0))
288 (let ((search-key (vector
289 (if (match-beginning 1) 'unmatch 'match)
290 (downcase (elmo-match-buffer 2))
291 (elmo-condition-parse-search-value))))
293 (if (string= (aref search-key 1) "tocc")
294 (if (eq (aref search-key 0) 'match)
296 (vector 'match "to" (aref search-key 2))
297 (vector 'match "cc" (aref search-key 2)))
299 (vector 'unmatch "to" (aref search-key 2))
300 (vector 'unmatch "cc" (aref search-key 2))))
303 ;; search-value ::= quoted / time / number / atom
304 ;; quoted ::= <elisp string expression>
305 ;; time ::= "yesterday" / "lastweek" / "lastmonth" / "lastyear" /
306 ;; number SPACE* "daysago" /
307 ;; number "-" month "-" number ; ex. 10-May-2000
308 ;; number "-" number "-" number ; ex. 2000-05-10
310 ;; month ::= "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
311 ;; "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
312 ;; atom ::= ATOM_CHARS*
313 ;; SPACE ::= <ascii space character, 0x20>
314 ;; ATOM_CHARS ::= <any character except specials>
315 ;; specials ::= SPACE / <"> / </> / <)> / <|> / <&>
316 ;; ;; These characters should be quoted.
317 (defun elmo-condition-parse-search-value ()
320 (read (current-buffer)))
321 ((or (looking-at elmo-condition-atom-regexp)
322 (looking-at "yesterday") (looking-at "lastweek")
323 (looking-at "lastmonth") (looking-at "lastyear")
324 (looking-at "[0-9]+ *daysago")
325 (looking-at "[0-9]+-[A-Za-z]+-[0-9]+")
326 (looking-at "[0-9]+-[0-9]+-[0-9]+")
327 (looking-at "[0-9]+"))
328 (prog1 (elmo-match-buffer 0)
329 (goto-char (match-end 0))))
330 (t (error "Syntax error '%s'" (buffer-string)))))
332 (defmacro elmo-filter-condition-p (filter)
333 `(or (vectorp ,filter) (consp ,filter)))
335 (defmacro elmo-filter-type (filter)
338 (defmacro elmo-filter-key (filter)
341 (defmacro elmo-filter-value (filter)
344 (defun elmo-condition-match (condition match-primitive args)
347 (if (eq (elmo-filter-type condition) 'unmatch)
348 (not (apply match-primitive condition args))
349 (apply match-primitive condition args)))
350 ((eq (car condition) 'and)
351 (let ((lhs (elmo-condition-match (nth 1 condition) match-primitive args)))
353 ((elmo-filter-condition-p lhs)
354 (let ((rhs (elmo-condition-match (nth 2 condition)
355 match-primitive args)))
356 (cond ((elmo-filter-condition-p rhs)
361 (elmo-condition-match (nth 2 condition) match-primitive args)))))
362 ((eq (car condition) 'or)
363 (let ((lhs (elmo-condition-match (nth 1 condition) match-primitive args)))
365 ((elmo-filter-condition-p lhs)
366 (let ((rhs (elmo-condition-match (nth 2 condition)
367 match-primitive args)))
368 (cond ((elmo-filter-condition-p rhs)
377 (elmo-condition-match (nth 2 condition) match-primitive args)))))))
379 (defun elmo-condition-optimize (condition)
382 (let ((key (elmo-filter-key condition)))
383 (cond ((cdr (assoc key '(("first" . 0)
387 ((member key '("since" "before" "from" "subject" "to" "cc"))
389 ((member key elmo-msgdb-extra-fields)
394 (let ((weight-l (elmo-condition-optimize (nth 1 condition)))
395 (weight-r (elmo-condition-optimize (nth 2 condition))))
396 (if (> weight-l weight-r)
397 (let ((lhs (nth 1 condition)))
398 (setcar (nthcdr 1 condition) (nth 2 condition))
399 (setcar (nthcdr 2 condition) lhs)
404 (defsubst elmo-buffer-replace (regexp &optional newtext)
405 (goto-char (point-min))
406 (while (re-search-forward regexp nil t)
407 (replace-match (or newtext ""))))
409 (defsubst elmo-delete-char (char string &optional unibyte)
412 (let ((coding-system-for-read 'no-conversion)
413 (coding-system-for-write 'no-conversion))
414 (if unibyte (set-buffer-multibyte nil))
416 (goto-char (point-min))
417 (while (search-forward (char-to-string char) nil t)
421 (defsubst elmo-delete-cr-buffer ()
422 "Delete CR from buffer."
424 (goto-char (point-min))
425 (while (search-forward "\r\n" nil t)
426 (replace-match "\n")) ))
428 (defsubst elmo-delete-cr-get-content-type ()
430 (goto-char (point-min))
431 (while (search-forward "\r\n" nil t)
432 (replace-match "\n"))
433 (goto-char (point-min))
434 (or (std11-field-body "content-type")
437 (defun elmo-delete-cr (string)
441 (goto-char (point-min))
442 (while (search-forward "\r\n" nil t)
443 (replace-match "\n"))
446 (defun elmo-last (list)
447 (and list (nth (1- (length list)) list)))
449 (defun elmo-set-list (vars vals)
452 (set (car vars) (car vals)))
453 (setq vars (cdr vars)
456 (defun elmo-uniq-list (lst &optional delete-function)
457 "Distractively uniqfy elements of LST."
458 (setq delete-function (or delete-function #'delete))
464 (funcall delete-function
469 (defun elmo-uniq-sorted-list (list &optional equal-function)
470 "Distractively uniqfy elements of sorted LIST."
471 (setq equal-function (or equal-function #'equal))
474 (while (funcall equal-function (car list) (cadr list))
475 (setcdr list (cddr list)))
476 (setq list (cdr list))))
479 (defun elmo-list-insert (list element after)
480 (let* ((match (memq after list))
481 (rest (and match (cdr (memq after list)))))
484 (setcdr match (list element))
486 (nconc list (list element)))))
488 (defun elmo-get-file-string (filename &optional remove-final-newline)
490 (let (insert-file-contents-pre-hook ; To avoid autoconv-xmas...
491 insert-file-contents-post-hook)
492 (when (file-exists-p filename)
494 (as-binary-input-file (insert-file-contents filename)))
495 (when (and remove-final-newline
497 (= (char-after (1- (point-max))) ?\n))
498 (goto-char (point-max))
499 (delete-backward-char 1))
502 (defun elmo-save-string (string filename)
505 (as-binary-output-file
507 (write-region (point-min) (point-max)
508 filename nil 'no-msg))
511 (defun elmo-max-of-list (nlist)
515 (if (< max-num (car l))
516 (setq max-num (car l)))
520 (defun elmo-concat-path (path filename)
521 (if (not (string= path ""))
522 (elmo-replace-in-string
523 (if (string= elmo-path-sep (substring path (- (length path) 1)))
524 (concat path filename)
525 (concat path elmo-path-sep filename))
526 (concat (regexp-quote elmo-path-sep)(regexp-quote elmo-path-sep))
530 (defvar elmo-passwd-alist nil)
532 (defun elmo-passwd-alist-load ()
534 (let ((filename (expand-file-name elmo-passwd-alist-file-name
535 elmo-msgdb-directory))
536 insert-file-contents-pre-hook ; To avoid autoconv-xmas...
537 insert-file-contents-post-hook
539 (if (not (file-readable-p filename))
541 (insert-file-contents filename)
543 (read (current-buffer))
546 (defun elmo-passwd-alist-clear ()
547 "Clear password cache."
549 (dolist (pair elmo-passwd-alist)
550 (when (stringp (cdr-safe pair))
551 (fillarray (cdr pair) 0)))
552 (setq elmo-passwd-alist nil))
554 (defun elmo-passwd-alist-save ()
555 "Save password into file."
558 (let ((filename (expand-file-name elmo-passwd-alist-file-name
559 elmo-msgdb-directory))
560 print-length print-level)
561 (prin1 elmo-passwd-alist (current-buffer))
562 (princ "\n" (current-buffer))
563 ;;; (if (and (file-exists-p filename)
564 ;;; (not (equal 384 (file-modes filename))))
565 ;;; (error "%s is not safe.chmod 600 %s!" filename filename))
566 (if (file-writable-p filename)
568 (write-region (point-min) (point-max)
569 filename nil 'no-msg)
570 (set-file-modes filename 384))
571 (message "%s is not writable." filename)))))
573 (defun elmo-get-passwd (key)
574 "Get password from password pool."
576 (if (not elmo-passwd-alist)
577 (setq elmo-passwd-alist (elmo-passwd-alist-load)))
578 (setq pair (assoc key elmo-passwd-alist))
580 (elmo-base64-decode-string (cdr pair))
581 (setq pass (elmo-read-passwd (format "Password for %s: "
583 (setq elmo-passwd-alist
584 (append elmo-passwd-alist
586 (elmo-base64-encode-string pass)))))
587 (if elmo-passwd-life-time
588 (run-with-timer elmo-passwd-life-time nil
589 (` (lambda () (elmo-remove-passwd (, key))))))
592 (defun elmo-remove-passwd (key)
593 "Remove password from password pool (for failure)."
595 (while (setq pass-cons (assoc key elmo-passwd-alist))
597 (fillarray (cdr pass-cons) 0)
598 (setq elmo-passwd-alist
599 (delete pass-cons elmo-passwd-alist))))))
601 (defmacro elmo-read-char-exclusive ()
602 (cond ((featurep 'xemacs)
603 '(let ((table (quote ((backspace . ?\C-h) (delete . ?\C-?)
608 (key-press-event-p (setq event (next-command-event)))
609 (setq key (or (event-to-character event)
610 (cdr (assq (event-key event) table)))))))
612 ((fboundp 'read-char-exclusive)
613 '(read-char-exclusive))
617 (defun elmo-read-passwd (prompt &optional stars)
618 "Read a single line of text from user without echoing, and return it."
622 (cursor-in-echo-area t)
623 (log-message-max-size 0)
624 message-log-max done msg truncate)
626 (if (or (not stars) (string= "" ans))
628 (setq msg (concat prompt (make-string (length ans) ?.)))
630 (1+ (- (length msg) (window-width (minibuffer-window)))))
632 (setq msg (concat "$" (substring msg (1+ truncate))))))
634 (setq c (elmo-read-char-exclusive))
638 ((or (= c ?\r) (= c ?\n) (= c ?\e))
642 ((and (/= c ?\b) (/= c ?\177))
643 (setq ans (concat ans (char-to-string c))))
645 (setq ans (substring ans 0 -1)))))
654 (defun elmo-string-to-list (string)
657 (goto-char (point-min))
659 (goto-char (point-max))
661 (goto-char (point-min))
662 (read (current-buffer))))
664 (defun elmo-list-to-string (list)
673 (if (symbolp (car tlist))
674 (symbol-name (car tlist))
679 (setq tlist (cdr tlist)))
689 (defun elmo-plug-on-by-servers (alist &optional servers)
690 (let ((server-list (or servers elmo-plug-on-servers)))
693 (if (elmo-plugged-p (car server-list))
695 (setq server-list (cdr server-list))))))
697 (defun elmo-plug-on-by-exclude-servers (alist &optional servers)
698 (let ((server-list (or servers elmo-plug-on-exclude-servers))
699 server other-servers)
701 (when (and (not (member (setq server (caaar alist)) server-list))
702 (not (member server other-servers)))
703 (push server other-servers))
704 (setq alist (cdr alist)))
705 (elmo-plug-on-by-servers alist other-servers)))
707 (defun elmo-plugged-p (&optional server port stream-type alist label-exp)
708 (let ((alist (or alist elmo-plugged-alist))
710 (cond ((and (not port) (not server))
711 (cond ((eq elmo-plugged-condition 'one)
715 (if (nth 2 (car alist))
717 (setq alist (cdr alist))))
719 ((eq elmo-plugged-condition 'all)
723 (if (not (nth 2 (car alist)))
724 (throw 'plugged nil))
725 (setq alist (cdr alist)))
728 ((functionp elmo-plugged-condition)
729 (funcall elmo-plugged-condition alist))
732 ((not port) ;; server
735 (when (string= server (caaar alist))
736 (if (nth 2 (car alist))
738 (setq alist (cdr alist)))))
740 (setq plugged-info (assoc (list server port stream-type) alist))
741 (if (not plugged-info)
742 ;; add elmo-plugged-alist automatically
744 (elmo-set-plugged elmo-plugged server port stream-type
745 nil nil nil label-exp)
747 (if (and elmo-auto-change-plugged
748 (> elmo-auto-change-plugged 0)
749 (nth 3 plugged-info) ;; time
750 (elmo-time-expire (nth 3 plugged-info)
751 elmo-auto-change-plugged))
753 (nth 2 plugged-info)))))))
755 (defun elmo-set-plugged (plugged &optional server port stream-type time
757 (let ((alist (or alist elmo-plugged-alist))
759 (cond ((and (not port) (not server))
760 (setq elmo-plugged plugged)
761 ;; set plugged all element of elmo-plugged-alist.
763 (setcdr (cdar alist) (list plugged time))
764 (setq alist (cdr alist))))
766 ;; set plugged all port of server
768 (when (string= server (caaar alist))
769 (setcdr (cdar alist) (list plugged time)))
770 (setq alist (cdr alist))))
772 ;; set plugged one port of server
773 (setq plugged-info (assoc (list server port stream-type) alist))
774 (setq label (if label-exp
776 (nth 1 plugged-info)))
778 ;; if add is non-nil, don't reset plug state.
780 (setcdr plugged-info (list label plugged time)))
782 (setq elmo-plugged-alist
786 (list (list server port stream-type)
787 label plugged time))))))))
790 (defun elmo-delete-plugged (&optional server port alist)
791 (let* ((alist (or alist elmo-plugged-alist))
793 (cond ((and (not port) (not server))
796 ;; delete plugged all port of server
798 (when (string= server (caaar alist2))
799 (setq alist (delete (car alist2) alist)))
800 (setq alist2 (cdr alist2))))
802 ;; delete plugged one port of server
804 (delete (assoc (cons server port) alist) alist))))
807 (defun elmo-disk-usage (path)
808 "Get disk usage (bytes) in PATH."
810 (condition-case () (file-attributes path) (error nil))))
812 (if (nth 0 file-attr) ; directory
813 (let ((files (condition-case ()
814 (directory-files path t "^[^\\.]")
817 ;; (result (nth 7 file-attr))) ... directory size
819 (setq result (+ result (or (elmo-disk-usage (car files)) 0)))
820 (setq files (cdr files)))
822 (float (nth 7 file-attr)))
825 (defun elmo-get-last-accessed-time (path &optional dir)
826 "Return the last accessed time of PATH."
827 (let ((last-accessed (nth 4 (file-attributes (or (and dir
832 (setq last-accessed (+ (* (nth 0 last-accessed)
833 (float 65536)) (nth 1 last-accessed)))
836 (defun elmo-get-last-modification-time (path &optional dir)
837 "Return the last accessed time of PATH."
838 (let ((last-modified (nth 5 (file-attributes (or (and dir
842 (setq last-modified (+ (* (nth 0 last-modified)
843 (float 65536)) (nth 1 last-modified)))))
845 (defun elmo-make-directory (path &optional mode)
846 "Create directory recursively."
847 (let ((parent (directory-file-name (file-name-directory path))))
848 (if (null (file-directory-p parent))
849 (elmo-make-directory parent))
850 (make-directory path)
851 (set-file-modes path (or mode
852 (+ (* 64 7) (* 8 0) 0))))) ; chmod 0700
854 (defun elmo-delete-directory (path &optional no-hierarchy)
855 "Delete directory recursively."
856 (if (stringp path) ; nil is not permitted.
857 (let ((dirent (directory-files path))
858 relpath abspath hierarchy)
860 (setq relpath (car dirent)
862 abspath (expand-file-name relpath path))
863 (when (not (string-match "^\\.\\.?$" relpath))
864 (if (eq (nth 0 (file-attributes abspath)) t)
867 (elmo-delete-directory abspath no-hierarchy))
868 (delete-file abspath))))
870 (delete-directory path)))))
872 (defun elmo-delete-match-files (path regexp &optional remove-if-empty)
873 "Delete directory files specified by PATH.
874 If optional REMOVE-IF-EMPTY is non-nil, delete directory itself if
875 the directory becomes empty after deletion."
876 (when (stringp path) ; nil is not permitted.
877 (dolist (file (directory-files path t regexp))
881 (delete-directory path) ; should be removed if empty.
884 (defun elmo-list-filter (l1 l2)
885 "Return a list from L2 in which each element is a member of L1."
888 (if (memq element l1)
889 (setq result (cons element result))))
892 (defsubst elmo-list-delete-if-smaller (list number)
893 (let ((ret-val (copy-sequence list)))
895 (if (< (car list) number)
896 (setq ret-val (delq (car list) ret-val)))
897 (setq list (cdr list)))
900 (defun elmo-list-diff (list1 list2)
901 (let ((clist1 (sort (copy-sequence list1) #'<))
902 (clist2 (sort (copy-sequence list2) #'<))
903 list1-only list2-only)
904 (while (or clist1 clist2)
908 (setq list2-only (cons (car clist2) list2-only))
909 (setq clist2 (cdr clist2))))
912 (setq list1-only (cons (car clist1) list1-only))
913 (setq clist1 (cdr clist1))))
914 ((< (car clist1) (car clist2))
915 (while (and clist1 (< (car clist1) (car clist2)))
916 (setq list1-only (cons (car clist1) list1-only))
917 (setq clist1 (cdr clist1))))
918 ((< (car clist2) (car clist1))
919 (while (and clist2 (< (car clist2) (car clist1)))
920 (setq list2-only (cons (car clist2) list2-only))
921 (setq clist2 (cdr clist2))))
922 ((= (car clist1) (car clist2))
923 (setq clist1 (cdr clist1)
924 clist2 (cdr clist2)))))
925 (list list1-only list2-only)))
927 (defun elmo-list-diff-nonsortable (list1 list2)
928 (let ((clist1 (copy-sequence list1))
929 (clist2 (copy-sequence list2)))
931 (setq clist1 (delq (car list2) clist1))
932 (setq list2 (cdr list2)))
934 (setq clist2 (delq (car list1) clist2))
935 (setq list1 (cdr list1)))
936 (list clist1 clist2)))
938 (defun elmo-list-bigger-diff (list1 list2 &optional mes)
939 "Returns a list (- +). + is bigger than max of LIST1, in LIST2."
944 (max-of-l2 (or (nth (max 0 (1- (length l2))) l2) 0))
948 (setq num (+ (length l1)))
950 (if (memq (car l1) l2)
951 (if (eq (car l1) (car l2))
954 (if (> (car l1) max-of-l2)
955 (setq diff1 (nconc diff1 (list (car l1))))))
959 (setq percent (/ (* i 100) num))
960 (if (eq (% percent 5) 0)
961 (elmo-display-progress
962 'elmo-list-bigger-diff "%s%d%%" percent mes))))
964 (cons diff1 (list l2)))))
966 (defmacro elmo-get-hash-val (string hashtable)
967 (static-if (fboundp 'unintern)
968 `(symbol-value (intern-soft ,string ,hashtable))
969 `(let ((sym (intern-soft ,string ,hashtable)))
971 (symbol-value sym)))))
973 (defmacro elmo-set-hash-val (string value hashtable)
974 `(set (intern ,string ,hashtable) ,value))
976 (defmacro elmo-clear-hash-val (string hashtable)
977 (static-if (fboundp 'unintern)
978 (list 'unintern string hashtable)
979 (list 'makunbound (list 'intern string hashtable))))
981 (defmacro elmo-unintern (string)
982 "`unintern' symbol named STRING, When can use `unintern'.
983 Emacs 19.28 or earlier does not have `unintern'."
984 (static-if (fboundp 'unintern)
985 (list 'unintern string)))
987 (defun elmo-make-hash (&optional hashsize)
988 "Make a new hash table which have HASHSIZE size."
992 ;; Prime numbers as lengths tend to result in good
993 ;; hashing; lengths one less than a power of two are
997 (while (< (- i 1) hashsize)
1000 elmo-hash-maximum-size)
1001 elmo-hash-minimum-size)
1002 elmo-hash-minimum-size)
1005 (defsubst elmo-mime-string (string)
1006 "Normalize MIME encoded STRING."
1008 (elmo-with-enable-multibyte
1009 (encode-mime-charset-string
1011 (eword-decode-and-unfold-unstructured-field-body string))
1013 elmo-mime-charset))))
1015 (defsubst elmo-collect-field (beg end downcase-field-name)
1018 (narrow-to-region beg end)
1019 (goto-char (point-min))
1020 (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
1022 (while (re-search-forward regexp nil t)
1023 (setq name (buffer-substring-no-properties
1024 (match-beginning 1)(1- (match-end 1))))
1025 (if downcase-field-name
1026 (setq name (downcase name)))
1027 (setq body (buffer-substring-no-properties
1028 (match-end 0) (std11-field-end)))
1029 (or (assoc name dest)
1030 (setq dest (cons (cons name body) dest))))
1033 (defsubst elmo-collect-field-from-string (string downcase-field-name)
1036 (goto-char (point-min))
1037 (let ((regexp (concat "\\(" std11-field-head-regexp "\\)[ \t]*"))
1039 (while (re-search-forward regexp nil t)
1040 (setq name (buffer-substring-no-properties
1041 (match-beginning 1)(1- (match-end 1))))
1042 (if downcase-field-name
1043 (setq name (downcase name)))
1044 (setq body (buffer-substring-no-properties
1045 (match-end 0) (std11-field-end)))
1046 (or (assoc name dest)
1047 (setq dest (cons (cons name body) dest))))
1050 (defun elmo-safe-filename (filename)
1051 (let* ((replace-alist '(("/" . " ")
1056 (regexp-quote (mapconcat 'car replace-alist ""))
1060 (while (string-match regexp rest)
1061 (setq converted (concat converted
1062 (substring rest 0 (match-beginning 0))
1063 (cdr (assoc (substring rest
1067 rest (substring rest (match-end 0))))
1068 (concat converted rest)))
1070 (defvar elmo-filename-replace-chars nil)
1072 (defsubst elmo-replace-string-as-filename (msgid)
1073 "Replace string as filename."
1074 (setq msgid (elmo-replace-in-string msgid " " " "))
1075 (if (null elmo-filename-replace-chars)
1076 (setq elmo-filename-replace-chars
1077 (regexp-quote (mapconcat
1078 'car elmo-filename-replace-string-alist ""))))
1079 (while (string-match (concat "[" elmo-filename-replace-chars "]")
1082 (substring msgid 0 (match-beginning 0))
1085 (match-beginning 0) (match-end 0))
1086 elmo-filename-replace-string-alist))
1087 (substring msgid (match-end 0)))))
1090 (defsubst elmo-recover-string-from-filename (filename)
1091 "Recover string from FILENAME."
1093 (while (string-match " " filename)
1094 (setq tmp (substring filename
1096 (+ (match-end 0) 1)))
1097 (if (string= tmp " ")
1099 (setq tmp (car (rassoc tmp
1100 elmo-filename-replace-string-alist))))
1103 (substring filename 0 (match-beginning 0))
1105 (setq filename (substring filename (+ (match-end 0) 1))))
1106 (concat result filename)))
1108 (defsubst elmo-copy-file (src dst &optional ok-if-already-exists)
1110 (elmo-add-name-to-file src dst ok-if-already-exists)
1111 (error (copy-file src dst ok-if-already-exists t))))
1113 (defsubst elmo-buffer-exists-p (buffer)
1114 (if (bufferp buffer)
1115 (buffer-live-p buffer)
1116 (get-buffer buffer)))
1118 (defsubst elmo-kill-buffer (buffer)
1119 (when (elmo-buffer-exists-p buffer)
1120 (kill-buffer buffer)))
1122 (defun elmo-delete-if (pred lst)
1123 "Return new list contain items which don't satisfy PRED in LST."
1126 (unless (funcall pred (car lst))
1127 (setq result (cons (car lst) result)))
1128 (setq lst (cdr lst)))
1131 (defun elmo-list-delete (list1 list2 &optional delete-function)
1132 "Delete by side effect any occurrences equal to elements of LIST1 from LIST2.
1133 Return the modified LIST2. Deletion is done with `delete'.
1134 Write `(setq foo (elmo-list-delete bar foo))' to be sure of changing
1136 If optional DELETE-FUNCTION is speficied, it is used as delete procedure."
1137 (setq delete-function (or delete-function 'delete))
1139 (setq list2 (funcall delete-function (car list1) list2))
1140 (setq list1 (cdr list1)))
1143 (defun elmo-list-member (list1 list2)
1144 "If any element of LIST1 is member of LIST2, return t."
1147 (if (member (car list1) list2)
1149 (setq list1 (cdr list1)))))
1151 (defun elmo-count-matches (regexp beg end)
1155 (while (re-search-forward regexp end t)
1156 (setq count (1+ count)))
1159 (if (fboundp 'display-error)
1160 (defalias 'elmo-display-error 'display-error)
1161 (defun elmo-display-error (error-object stream)
1162 "A tiny function to display ERROR-OBJECT to the STREAM."
1164 (errobj error-object)
1167 (setq err-mes (concat err-mes (format
1168 (if (stringp (car errobj))
1172 (setq errobj (cdr errobj))
1173 (if errobj (setq err-mes (concat err-mes (if first ": " ", "))))
1175 (princ err-mes stream))))
1177 (if (fboundp 'define-error)
1178 (defalias 'elmo-define-error 'define-error)
1179 (defun elmo-define-error (error doc &optional parents)
1181 (setq parents 'error))
1182 (let ((conds (get parents 'error-conditions)))
1184 (error "Not an error symbol: %s" error))
1186 (list 'error-message doc
1187 'error-conditions (cons error conds))))))
1189 (cond ((fboundp 'progress-feedback-with-label)
1190 (defalias 'elmo-display-progress 'progress-feedback-with-label))
1191 ((fboundp 'lprogress-display)
1192 (defalias 'elmo-display-progress 'lprogress-display))
1194 (defun elmo-display-progress (label format &optional value &rest args)
1195 "Print a progress message."
1196 (if (and (null format) (null args))
1198 (apply (function message) (concat format " %d%%")
1199 (nconc args (list value)))))))
1201 (defvar elmo-progress-counter-alist nil)
1203 (defmacro elmo-progress-counter-value (counter)
1204 (` (aref (cdr (, counter)) 0)))
1206 (defmacro elmo-progress-counter-all-value (counter)
1207 (` (aref (cdr (, counter)) 1)))
1209 (defmacro elmo-progress-counter-format (counter)
1210 (` (aref (cdr (, counter)) 2)))
1212 (defmacro elmo-progress-counter-set-value (counter value)
1213 (` (aset (cdr (, counter)) 0 (, value))))
1215 (defun elmo-progress-set (label all-value &optional format)
1216 (unless (assq label elmo-progress-counter-alist)
1217 (setq elmo-progress-counter-alist
1218 (cons (cons label (vector 0 all-value (or format "")))
1219 elmo-progress-counter-alist))))
1221 (defun elmo-progress-clear (label)
1222 (let ((counter (assq label elmo-progress-counter-alist)))
1224 (elmo-display-progress label
1225 (elmo-progress-counter-format counter)
1227 (setq elmo-progress-counter-alist
1228 (delq counter elmo-progress-counter-alist)))))
1230 (defun elmo-progress-notify (label &optional value op &rest args)
1231 (let ((counter (assq label elmo-progress-counter-alist)))
1233 (let* ((value (or value 1))
1234 (cur-value (elmo-progress-counter-value counter))
1235 (all-value (elmo-progress-counter-all-value counter))
1236 (new-value (if (eq op 'set) value (+ cur-value value)))
1237 (cur-rate (/ (* cur-value 100) all-value))
1238 (new-rate (/ (* new-value 100) all-value)))
1239 (elmo-progress-counter-set-value counter new-value)
1240 (unless (= cur-rate new-rate)
1241 (apply 'elmo-display-progress
1243 (elmo-progress-counter-format counter)
1246 (when (>= new-rate 100)
1247 (elmo-progress-clear label))))))
1249 (put 'elmo-with-progress-display 'lisp-indent-function '2)
1250 (def-edebug-spec elmo-with-progress-display
1251 (form (symbolp form &optional form) &rest form))
1253 (defmacro elmo-with-progress-display (condition spec &rest body)
1254 "Evaluate BODY with progress gauge if CONDITION is non-nil.
1255 SPEC is a list as followed (LABEL MAX-VALUE [FORMAT])."
1256 (let ((label (car spec))
1257 (max-value (cadr spec))
1262 (elmo-progress-set (quote ,label) ,max-value ,fmt))
1264 (elmo-progress-clear (quote ,label)))))
1266 (defun elmo-time-expire (before-time diff-time)
1267 (let* ((current (current-time))
1268 (rest (when (< (nth 1 current) (nth 1 before-time))
1272 (list (- (+ (car current) (if rest -1 0)) (car before-time))
1273 (- (+ (or rest 0) (nth 1 current)) (nth 1 before-time))))
1274 (and (eq (car diff) 0)
1275 (< diff-time (nth 1 diff)))))
1277 (if (fboundp 'std11-fetch-field)
1278 (defalias 'elmo-field-body 'std11-fetch-field) ;;no narrow-to-region
1279 (defalias 'elmo-field-body 'std11-field-body))
1281 (defun elmo-unfold-field-body (name)
1282 (let ((value (elmo-field-body name)))
1284 (std11-unfold-string value))))
1286 (defun elmo-decoded-field-body (field-name &optional mode)
1287 (let ((field-body (elmo-field-body field-name)))
1290 (elmo-with-enable-multibyte
1291 (mime-decode-field-body field-body field-name mode)))
1294 (defun elmo-address-quote-specials (word)
1295 "Make quoted string of WORD if needed."
1296 (let ((lal (std11-lexical-analyze word)))
1297 (if (or (assq 'specials lal)
1298 (assq 'domain-literal lal))
1299 (prin1-to-string word)
1302 (defmacro elmo-string (string)
1303 "STRING without text property."
1304 (` (let ((obj (copy-sequence (, string))))
1305 (and obj (set-text-properties 0 (length obj) nil obj))
1308 (defun elmo-flatten (list-of-list)
1309 "Flatten LIST-OF-LIST."
1310 (unless (null list-of-list)
1311 (append (if (and (car list-of-list)
1312 (listp (car list-of-list)))
1314 (list (car list-of-list)))
1315 (elmo-flatten (cdr list-of-list)))))
1317 (defun elmo-y-or-n-p (prompt &optional auto default)
1318 "Same as `y-or-n-p'.
1319 But if optional argument AUTO is non-nil, DEFAULT is returned."
1324 (defun elmo-string-member (string slist)
1326 (dolist (element slist)
1327 (cond ((null element))
1329 (when (string= string element)
1332 (when (string= string (symbol-value element))
1333 (throw 'found t)))))))
1335 (static-cond ((fboundp 'member-ignore-case)
1336 (defalias 'elmo-string-member-ignore-case 'member-ignore-case))
1337 ((fboundp 'compare-strings)
1338 (defun elmo-string-member-ignore-case (elt list)
1339 "Like `member', but ignores differences in case and text representation.
1340 ELT must be a string. Upper-case and lower-case letters are treated as equal.
1341 Unibyte strings are converted to multibyte for comparison."
1342 (while (and list (not (eq t (compare-strings elt 0 nil (car list) 0 nil t))))
1343 (setq list (cdr list)))
1346 (defun elmo-string-member-ignore-case (elt list)
1347 "Like `member', but ignores differences in case and text representation.
1348 ELT must be a string. Upper-case and lower-case letters are treated as equal."
1349 (let ((str (downcase elt)))
1350 (while (and list (not (string= str (downcase (car list)))))
1351 (setq list (cdr list)))
1354 (defun elmo-string-match-member (str list &optional case-ignore)
1355 (let ((case-fold-search case-ignore))
1358 (if (string-match (car list) str)
1359 (throw 'member (car list)))
1360 (setq list (cdr list))))))
1362 (defun elmo-string-matched-member (str list &optional case-ignore)
1363 (let ((case-fold-search case-ignore))
1366 (if (string-match str (car list))
1367 (throw 'member (car list)))
1368 (setq list (cdr list))))))
1370 (defsubst elmo-string-delete-match (string pos)
1371 (concat (substring string
1372 0 (match-beginning pos))
1377 (defun elmo-string-match-assoc (key alist &optional case-ignore)
1378 (let ((case-fold-search case-ignore)
1382 (setq a (car alist))
1385 (string-match key (car a)))
1387 (setq alist (cdr alist))))))
1389 (defun elmo-string-matched-assoc (key alist &optional case-ignore)
1390 (let ((case-fold-search case-ignore)
1394 (setq a (car alist))
1397 (string-match (car a) key))
1399 (setq alist (cdr alist))))))
1401 (defun elmo-string-assoc (key alist)
1405 (setq a (car alist))
1408 (string= key (car a)))
1410 (setq alist (cdr alist))))))
1412 (defun elmo-string-assoc-all (key alist)
1415 (if (string= key (car (car alist)))
1419 (setq alist (cdr alist)))
1422 (defun elmo-string-rassoc (key alist)
1426 (setq a (car alist))
1429 (string= key (cdr a)))
1431 (setq alist (cdr alist))))))
1433 (defun elmo-string-rassoc-all (key alist)
1436 (if (string= key (cdr (car alist)))
1440 (setq alist (cdr alist)))
1443 (defun elmo-expand-newtext (newtext original)
1444 (let ((len (length newtext))
1446 c expanded beg N did-expand)
1449 (while (and (< pos len)
1450 (not (= (aref newtext pos) ?\\)))
1451 (setq pos (1+ pos)))
1453 (push (substring newtext beg pos) expanded))
1455 ;; We hit a \; expand it.
1458 c (aref newtext pos))
1459 (if (not (or (= c ?\&)
1462 ;; \ followed by some character we don't expand.
1463 (push (char-to-string c) expanded)
1468 (when (match-beginning N)
1469 (push (substring original (match-beginning N) (match-end N))
1471 (setq pos (1+ pos)))
1473 (apply (function concat) (nreverse expanded))
1476 ;;; Folder parser utils.
1477 (defconst elmo-quoted-specials-list '(?\\ ?\"))
1479 (defun elmo-quoted-token (string)
1481 (std11-wrap-as-quoted-pairs string elmo-quoted-specials-list)
1484 (defun elmo-token-valid-p (token requirement)
1485 (cond ((null requirement))
1486 ((stringp requirement)
1487 (string-match requirement token))
1488 ((functionp requirement)
1489 (funcall requirement token))))
1491 (defun elmo-parse-token (string &optional seps requirement)
1492 "Parse atom from STRING using SEPS as a string of separator char list."
1493 (let ((len (length string))
1494 (seps (and seps (string-to-char-list seps)))
1500 (while (and (< i len) (or in (null sep)))
1501 (setq c (aref string i))
1503 ((and in (eq c ?\\))
1505 content (cons (aref string i) content)
1510 (in (setq content (cons c content)
1514 (t (setq content (cons c content)
1516 (if in (error "Parse error in quoted"))
1517 (let ((atom (if (null content)
1519 (char-list-to-string (nreverse content)))))
1520 (if (elmo-token-valid-p atom requirement)
1521 (cons atom (substring string i))
1522 (cons "" string))))))
1524 (defun elmo-parse-prefixed-element (prefix string &optional seps requirement)
1526 (if (and (not (eq (length string) 0))
1527 (eq (aref string 0) prefix)
1528 (setq parsed (elmo-parse-token (substring string 1) seps))
1529 (elmo-token-valid-p (car parsed) requirement))
1533 (defun elmo-collect-separators (spec)
1535 (let ((result (elmo-collect-separators-internal spec)))
1537 (char-list-to-string (elmo-uniq-list result #'delq))))))
1539 (defun elmo-collect-separators-internal (specs)
1542 (let ((spec (car specs)))
1545 (setq separators (nconc (elmo-collect-separators-internal spec)
1549 (setq separators (cons spec separators)
1552 (setq specs nil)))))
1555 (defun elmo-collect-trail-separators (element specs)
1560 (eq (aref specs 0) element))
1563 (while (setq spec (car specs))
1564 (if (setq result (elmo-collect-trail-separators element spec))
1565 (setq result (concat (if (stringp result) result)
1566 (elmo-collect-separators (cdr specs)))
1568 (setq specs (cdr specs))))
1571 (defun elmo-parse-separated-tokens (string spec)
1572 (let ((result (elmo-parse-separated-tokens-internal string spec)))
1573 (if (eq (car result) t)
1574 (cons nil (cdr result))
1577 (defun elmo-parse-separated-tokens-internal (string spec &optional separators)
1580 (let ((parse (elmo-parse-token string separators)))
1581 (cons (list (cons spec (car parse))) (cdr parse))))
1583 (let ((parse (elmo-parse-token string separators)))
1584 (if (elmo-token-valid-p (car parse) (aref spec 1))
1585 (cons (list (cons (aref spec 0) (car parse))) (cdr parse))
1586 (cons nil string))))
1588 (if (and (> (length string) 0)
1589 (eq (aref string 0) spec))
1590 (cons t (substring string 1))
1597 (setq result (elmo-parse-separated-tokens-internal
1600 (concat (elmo-collect-separators (cdr spec))
1602 (cond ((null (car result))
1603 (throw 'unmatch (cons t string)))
1604 ((eq t (car result)))
1606 (setq tokens (nconc (car result) tokens))))
1607 (setq rest (cdr result)
1609 (cons (or tokens t) rest))))))
1611 (defun elmo-quote-syntactical-element (value element syntax)
1612 (let ((separators (elmo-collect-trail-separators element syntax)))
1614 (string-match (concat "[" separators "]") value))
1615 (elmo-quoted-token value)
1618 ;;; Number set defined by OKAZAKI Tetsurou <okazaki@be.to>
1620 ;; number ::= [0-9]+
1623 ;; number-range ::= "(" beg " . " end ")" ;; cons cell
1624 ;; number-set-elem ::= number / number-range
1625 ;; number-set ::= "(" *number-set-elem ")" ;; list
1627 (defun elmo-number-set-member (number number-set)
1628 "Return non-nil if NUMBER is an element of NUMBER-SET.
1629 The value is actually the tail of NUMBER-RANGE whose car contains NUMBER."
1630 (or (memq number number-set)
1632 (while (and number-set (not found))
1633 (if (and (consp (car number-set))
1634 (and (<= (car (car number-set)) number)
1635 (<= number (cdr (car number-set)))))
1637 (setq number-set (cdr number-set))))
1640 (defun elmo-number-set-append-list (number-set list)
1641 "Append LIST of numbers to the NUMBER-SET.
1642 NUMBER-SET is altered."
1643 (let ((appended number-set))
1645 (setq appended (elmo-number-set-append appended (car list)))
1646 (setq list (cdr list)))
1649 (defun elmo-number-set-append (number-set number)
1650 "Append NUMBER to the NUMBER-SET.
1651 NUMBER-SET is altered."
1652 (let ((number-set-1 number-set)
1654 (while (and number-set (not found))
1655 (setq elem (car number-set))
1658 (eq (+ 1 (cdr elem)) number))
1659 (setcdr elem number)
1661 ((and (integerp elem)
1662 (eq (+ 1 elem) number))
1663 (setcar number-set (cons elem number))
1665 ((or (and (integerp elem) (eq elem number))
1667 (<= (car elem) number)
1668 (<= number (cdr elem))))
1670 (setq number-set (cdr number-set)))
1672 (setq number-set-1 (nconc number-set-1 (list number))))
1675 (defun elmo-number-set-delete-list (number-set list)
1676 "Delete LIST of numbers from the NUMBER-SET.
1677 NUMBER-SET is altered."
1678 (let ((deleted number-set))
1679 (dolist (number list)
1680 (setq deleted (elmo-number-set-delete deleted number)))
1683 (defun elmo-number-set-delete (number-set number)
1684 "Delete NUMBER from the NUMBER-SET.
1685 NUMBER-SET is altered."
1686 (let* ((curr number-set)
1687 (top (cons 'dummy number-set))
1690 (while (and curr (not found))
1691 (setq elem (car curr))
1694 ((eq (car elem) number)
1695 (if (eq (cdr elem) (1+ number))
1696 (setcar curr (cdr elem))
1697 (setcar elem (1+ number)))
1699 ((eq (cdr elem) number)
1700 (if (eq (car elem) (1- number))
1701 (setcar curr (car elem))
1702 (setcdr elem (1- number)))
1704 ((and (> number (car elem))
1705 (< number (cdr elem)))
1710 ;; (beg . (1- number))
1711 (let ((new (cons (car elem) (1- number))))
1712 (if (eq (car new) (cdr new))
1715 ;; ((1+ number) . end)
1716 (let ((new (cons (1+ number) (cdr elem))))
1717 (if (eq (car new) (cdr new))
1721 (when (eq elem number)
1722 (setcdr prev (cdr curr))
1728 (defun elmo-make-number-list (beg end)
1729 (let (number-list i)
1732 (setq number-list (cons i number-list))
1736 (defun elmo-number-set-to-number-list (number-set)
1737 "Return a number list which corresponds to NUMBER-SET."
1738 (let ((number-list (list 'dummy))
1741 (setq elem (car number-set))
1744 (nconc number-list (elmo-make-number-list (car elem) (cdr elem))))
1746 (nconc number-list (list elem))))
1747 (setq number-set (cdr number-set)))
1750 (defcustom elmo-list-subdirectories-ignore-regexp "^\\(\\.\\.?\\|[0-9]+\\)$"
1751 "*Regexp to filter subfolders."
1755 (defun elmo-list-subdirectories-1 (basedir curdir one-level)
1756 (let ((root (zerop (length curdir)))
1757 (w32-get-true-file-link-count t) ; for Meadow
1760 (dolist (file (directory-files (setq dir (expand-file-name curdir basedir))))
1761 (when (and (not (string-match
1762 elmo-list-subdirectories-ignore-regexp
1764 (car (setq attr (file-attributes
1765 (expand-file-name file dir)))))
1766 (when (eq one-level 'check) (throw 'done t))
1768 (concat curdir (and (not root) elmo-path-sep) file))
1770 (setq dirs (nconc dirs
1771 (if (if elmo-have-link-count (< 2 (nth 1 attr))
1773 (elmo-list-subdirectories-1
1776 (if one-level 'check))))
1778 (list (list relpath))
1781 (elmo-list-subdirectories-1
1785 (list relpath)))))))
1788 (defun elmo-list-subdirectories (directory file one-level)
1789 (let ((subdirs (elmo-list-subdirectories-1 directory file one-level)))
1790 (if (zerop (length file))
1792 (cons file subdirs))))
1794 (defun elmo-mapcar-list-of-list (func list-of-list)
1797 (cond ((listp x) (elmo-mapcar-list-of-list func x))
1798 (t (funcall func x))))
1801 (defun elmo-map-recursive (function object)
1803 (let* ((prev (list 'dummy))
1805 (while (consp object)
1806 (setq prev (setcdr prev (list (elmo-map-recursive function
1808 object (cdr object)))
1810 (setcdr prev (funcall function object)))
1812 (funcall function object)))
1814 (defun elmo-map-until-success (function sequence)
1816 (while (and (null result)
1818 (setq result (funcall function (car sequence))
1819 sequence (cdr sequence)))
1822 (defun elmo-string-match-substring (regexp string &optional matchn)
1823 (when (string-match regexp string)
1824 (match-string (or matchn 1) string)))
1826 (defun elmo-parse (string regexp &optional matchn)
1827 (or matchn (setq matchn 1))
1829 (store-match-data nil)
1830 (while (string-match regexp string (match-end 0))
1831 (setq list (cons (substring string (match-beginning matchn)
1832 (match-end matchn)) list)))
1835 (defun elmo-find-list-match-value (specs getter)
1836 (lexical-let ((getter getter))
1837 (elmo-map-until-success
1841 (funcall getter spec))
1843 (lexical-let ((value (funcall getter (car spec))))
1845 (elmo-map-until-success
1849 (elmo-string-match-substring rule value))
1851 (elmo-string-match-substring (car rule) value (cdr rule)))))
1856 (defmacro elmo-make-file-cache (path status)
1857 "PATH is the cache file name.
1858 STATUS is one of 'section, 'entire or nil.
1859 nil means no cache exists.
1860 'section means partial section cache exists.
1861 'entire means entire cache exists.
1862 If the cache is partial file-cache, TYPE is 'partial."
1863 (` (cons (, path) (, status))))
1865 (defmacro elmo-file-cache-path (file-cache)
1866 "Returns the file path of the FILE-CACHE."
1867 (` (car (, file-cache))))
1869 (defmacro elmo-file-cache-status (file-cache)
1870 "Returns the status of the FILE-CACHE."
1871 (` (cdr (, file-cache))))
1873 (defsubst elmo-cache-to-msgid (filename)
1874 (concat "<" (elmo-recover-string-from-filename filename) ">"))
1876 (defsubst elmo-cache-get-path-subr (msgid)
1877 (let ((chars '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?A ?B ?C ?D ?E ?F))
1878 (clist (string-to-char-list msgid))
1881 (setq sum (+ sum (car clist)))
1882 (setq clist (cdr clist)))
1884 (nth (% (/ sum 16) 2) chars)
1885 (nth (% sum 16) chars))))
1888 (defun elmo-file-cache-get-path (msgid &optional section)
1889 "Get cache path for MSGID.
1890 If optional argument SECTION is specified, partial cache path is returned."
1891 (if (setq msgid (elmo-msgid-to-cache msgid))
1894 (format "%s/%s/%s/%s"
1895 elmo-cache-directory
1896 (elmo-cache-get-path-subr msgid)
1900 elmo-cache-directory
1901 (elmo-cache-get-path-subr msgid)
1904 (defmacro elmo-file-cache-expand-path (path section)
1905 "Return file name for the file-cache corresponds to the section.
1906 PATH is the file-cache path.
1907 SECTION is the section string."
1908 (` (expand-file-name (or (, section) "") (, path))))
1910 (defun elmo-file-cache-delete (path)
1911 "Delete a cache on PATH."
1912 (when (file-exists-p path)
1913 (if (file-directory-p path)
1915 (dolist (file (directory-files path t "^[^\\.]"))
1917 (delete-directory path))
1921 (defun elmo-file-cache-exists-p (msgid)
1922 "Returns 'section or 'entire if a cache which corresponds to MSGID exists."
1923 (elmo-file-cache-status (elmo-file-cache-get msgid)))
1925 (defun elmo-file-cache-save (cache-path section)
1926 "Save current buffer as cache on PATH.
1927 Return t if cache is saved successfully."
1929 (let ((path (if section (expand-file-name section cache-path)
1932 (if (and (null section)
1933 (file-directory-p path))
1935 (setq files (directory-files path t "^[^\\.]"))
1937 (delete-file (car files))
1938 (setq files (cdr files)))
1939 (delete-directory path))
1941 (not (file-directory-p cache-path)))
1942 (delete-file cache-path)))
1944 (setq dir (directory-file-name (file-name-directory path)))
1945 (if (not (file-exists-p dir))
1946 (elmo-make-directory dir))
1947 (write-region-as-binary (point-min) (point-max)
1953 (defun elmo-file-cache-load (cache-path section)
1954 "Load cache on PATH into the current buffer.
1955 Return t if cache is loaded successfully."
1958 (when (and cache-path
1959 (if (elmo-cache-path-section-p cache-path)
1962 (setq cache-file (elmo-file-cache-expand-path
1965 (file-exists-p cache-file))
1966 (insert-file-contents-as-binary cache-file)
1971 (defun elmo-cache-path-section-p (path)
1972 "Return non-nil when PATH is `section' cache path."
1973 (file-directory-p path))
1975 (defun elmo-file-cache-get (msgid &optional section)
1976 "Returns the current file-cache object associated with MSGID.
1977 MSGID is the message-id of the message.
1978 If optional argument SECTION is specified, get partial file-cache object
1979 associated with SECTION."
1981 (let ((path (elmo-cache-get-path msgid)))
1982 (if (and path (file-exists-p path))
1983 (if (elmo-cache-path-section-p path)
1985 (if (file-exists-p (setq path (expand-file-name
1987 (cons path 'section))
1988 ;; section is not specified but sectional.
1989 (cons path 'section))
1992 (cons path 'entire)))
1999 (defun elmo-cache-expire ()
2001 (let* ((completion-ignore-case t)
2002 (method (completing-read (format "Expire by (%s): "
2003 elmo-cache-expire-default-method)
2007 (when (string= method "")
2008 (setq method elmo-cache-expire-default-method))
2009 (funcall (intern (concat "elmo-cache-expire-by-" method)))))
2011 (defun elmo-read-float-value-from-minibuffer (prompt &optional initial)
2012 (let ((str (read-from-minibuffer prompt initial)))
2014 ((string-match "[0-9]*\\.[0-9]+" str)
2015 (string-to-number str))
2016 ((string-match "[0-9]+" str)
2017 (string-to-number (concat str ".0")))
2018 (t (error "%s is not number" str)))))
2020 (defun elmo-cache-expire-by-size (&optional kbytes)
2021 "Expire cache file by size.
2022 If KBYTES is kilo bytes (This value must be float)."
2024 (let ((size (or kbytes
2025 (and (interactive-p)
2026 (elmo-read-float-value-from-minibuffer
2027 "Enter cache disk size (Kbytes): "
2029 (if (integerp elmo-cache-expire-default-size)
2030 (float elmo-cache-expire-default-size)
2031 elmo-cache-expire-default-size))))
2032 (if (integerp elmo-cache-expire-default-size)
2033 (float elmo-cache-expire-default-size))))
2037 (message "Checking disk usage...")
2038 (setq total (/ (elmo-disk-usage
2039 elmo-cache-directory) Kbytes))
2040 (setq beginning total)
2041 (message "Checking disk usage...done")
2042 (let ((cfl (elmo-cache-get-sorted-cache-file-list))
2046 (while (and (<= size total)
2047 (setq oldest (elmo-cache-get-oldest-cache-file-entity cfl)))
2048 (setq cur-file (expand-file-name (car (cdr oldest)) (car oldest)))
2049 (setq cur-size (/ (elmo-disk-usage cur-file) Kbytes))
2050 (when (elmo-file-cache-delete cur-file)
2051 (setq count (+ count 1))
2052 (message "%d cache(s) are expired." count))
2053 (setq deleted (+ deleted cur-size))
2054 (setq total (- total cur-size)))
2055 (message "%d cache(s) are expired from disk (%d Kbytes/%d Kbytes)."
2056 count deleted beginning))))
2058 (defun elmo-cache-make-file-entity (filename path)
2059 (cons filename (elmo-get-last-accessed-time filename path)))
2061 (defun elmo-cache-get-oldest-cache-file-entity (cache-file-list)
2062 (let ((cfl cache-file-list)
2063 flist firsts oldest-entity wonlist)
2065 (setq flist (cdr (car cfl)))
2066 (setq firsts (append firsts (list
2067 (cons (car (car cfl))
2069 (setq cfl (cdr cfl)))
2072 (if (and (not oldest-entity)
2073 (cdr (cdr (car firsts))))
2074 (setq oldest-entity (car firsts)))
2075 (if (and (cdr (cdr (car firsts)))
2076 (cdr (cdr oldest-entity))
2077 (> (cdr (cdr oldest-entity)) (cdr (cdr (car firsts)))))
2078 (setq oldest-entity (car firsts)))
2079 (setq firsts (cdr firsts)))
2080 (setq wonlist (assoc (car oldest-entity) cache-file-list))
2082 (setcdr wonlist (delete (car (cdr wonlist)) (cdr wonlist))))
2085 (defun elmo-cache-get-sorted-cache-file-list ()
2086 (let ((dirs (directory-files
2087 elmo-cache-directory
2092 (setq num (length dirs))
2093 (message "Collecting cache info...")
2095 (setq elist (mapcar (lambda (x)
2096 (elmo-cache-make-file-entity x (car dirs)))
2097 (directory-files (car dirs) nil "^[^\\.]")))
2098 (setq ret-val (append ret-val
2106 (when (> num elmo-display-progress-threshold)
2108 (elmo-display-progress
2109 'elmo-cache-get-sorted-cache-file-list "Collecting cache info..."
2111 (setq dirs (cdr dirs)))
2112 (message "Collecting cache info...done")
2115 (defun elmo-cache-expire-by-age (&optional days)
2116 (let ((age (or (and days (int-to-string days))
2117 (and (interactive-p)
2118 (read-from-minibuffer
2119 (format "Enter days (%s): "
2120 elmo-cache-expire-default-age)))
2121 (int-to-string elmo-cache-expire-default-age)))
2122 (dirs (directory-files
2123 elmo-cache-directory
2127 (if (string= age "")
2128 (setq age elmo-cache-expire-default-age)
2129 (setq age (string-to-int age)))
2130 (setq curtime (current-time))
2131 (setq curtime (+ (* (nth 0 curtime)
2132 (float 65536)) (nth 1 curtime)))
2134 (let ((files (directory-files (car dirs) t "^[^\\.]"))
2135 (limit-age (* age 86400)))
2137 (when (> (- curtime (elmo-get-last-accessed-time (car files)))
2139 (when (elmo-file-cache-delete (car files))
2140 (setq count (+ 1 count))
2141 (message "%d cache file(s) are expired." count)))
2142 (setq files (cdr files))))
2143 (setq dirs (cdr dirs)))))
2147 (defun elmo-msgid-to-cache (msgid)
2150 (string-match "<\\(.+\\)>$" msgid))
2151 (elmo-replace-string-as-filename (elmo-match-string 1 msgid)))))
2153 (defun elmo-cache-get-path (msgid &optional folder number)
2154 "Get path for cache file associated with MSGID, FOLDER, and NUMBER."
2155 (if (setq msgid (elmo-msgid-to-cache msgid))
2159 (format "%s/%s/%s@%s"
2160 (elmo-cache-get-path-subr msgid)
2163 (elmo-safe-filename folder))
2165 (elmo-cache-get-path-subr msgid)
2167 elmo-cache-directory))))
2172 (static-if (fboundp 'display-warning)
2173 (defmacro elmo-warning (&rest args)
2174 "Display a warning with `elmo' group."
2175 `(display-warning 'elmo (format ,@args)))
2176 (defconst elmo-warning-buffer-name "*elmo warning*")
2177 (defun elmo-warning (&rest args)
2178 "Display a warning. ARGS are passed to `format'."
2179 (with-current-buffer (get-buffer-create elmo-warning-buffer-name)
2180 (goto-char (point-max))
2181 (funcall 'insert (apply 'format (append args '("\n"))))
2182 (ignore-errors (recenter 1))
2183 (display-buffer elmo-warning-buffer-name))))
2185 (defvar elmo-obsolete-variable-alist nil)
2187 (defcustom elmo-obsolete-variable-show-warnings t
2188 "Show warning window if obsolete variable is treated."
2192 (defun elmo-define-obsolete-variable (obsolete var)
2193 "Define obsolete variable.
2194 OBSOLETE is a symbol for obsolete variable.
2195 VAR is a symbol for new variable.
2196 Definition is stored in `elmo-obsolete-variable-alist'."
2197 (let ((pair (assq var elmo-obsolete-variable-alist)))
2199 (setcdr pair obsolete)
2200 (setq elmo-obsolete-variable-alist
2201 (cons (cons var obsolete)
2202 elmo-obsolete-variable-alist)))))
2204 (defun elmo-resque-obsolete-variable (obsolete var)
2205 "Resque obsolete variable OBSOLETE as VAR.
2206 If `elmo-obsolete-variable-show-warnings' is non-nil, show warning message."
2207 (when (boundp obsolete)
2208 (static-if (and (fboundp 'defvaralias)
2209 (subrp (symbol-function 'defvaralias)))
2210 (defvaralias var obsolete)
2211 (set var (symbol-value obsolete)))
2212 (if elmo-obsolete-variable-show-warnings
2213 (elmo-warning "%s is obsolete. Use %s instead."
2214 (symbol-name obsolete)
2215 (symbol-name var)))))
2217 (defun elmo-resque-obsolete-variables (&optional alist)
2218 "Resque obsolete variables in ALIST.
2219 ALIST is a list of cons cell of
2220 \(OBSOLETE-VARIABLE-SYMBOL . NEW-VARIABLE-SYMBOL\).
2221 If ALIST is nil, `elmo-obsolete-variable-alist' is used."
2222 (dolist (pair elmo-obsolete-variable-alist)
2223 (elmo-resque-obsolete-variable (cdr pair)
2226 (defsubst elmo-msgdb-get-last-message-id (string)
2232 (goto-char (point-max))
2233 (when (search-backward "<" nil t)
2235 (if (search-forward ">" nil t)
2236 (elmo-replace-in-string
2237 (buffer-substring beg (point)) "\n[ \t]*" ""))))))))
2239 (defun elmo-msgdb-get-message-id-from-buffer ()
2240 (let ((msgid (elmo-field-body "message-id")))
2242 (if (string-match "<\\(.+\\)>$" msgid)
2244 (concat "<" msgid ">")) ; Invaild message-id.
2245 ;; no message-id, so put dummy msgid.
2247 (if (elmo-unfold-field-body "date")
2248 (timezone-make-date-sortable (elmo-unfold-field-body "date"))
2249 (md5 (string-as-unibyte (buffer-string))))
2250 (nth 1 (eword-extract-address-components
2251 (or (elmo-field-body "from") "nobody"))) ">"))))
2253 (defun elmo-msgdb-get-references-from-buffer ()
2254 (if elmo-msgdb-prefer-in-reply-to-for-parent
2255 (or (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to"))
2256 (elmo-msgdb-get-last-message-id (elmo-field-body "references")))
2257 (or (elmo-msgdb-get-last-message-id (elmo-field-body "references"))
2258 (elmo-msgdb-get-last-message-id (elmo-field-body "in-reply-to")))))
2260 (defsubst elmo-msgdb-insert-file-header (file)
2261 "Insert the header of the article."
2263 insert-file-contents-pre-hook ; To avoid autoconv-xmas...
2264 insert-file-contents-post-hook
2266 (when (file-exists-p file)
2267 ;; Read until header separator is found.
2268 (while (and (eq elmo-msgdb-file-header-chop-length
2270 (insert-file-contents-as-binary
2272 (incf beg elmo-msgdb-file-header-chop-length))))
2273 (prog1 (not (search-forward "\n\n" nil t))
2274 (goto-char (point-max))))))))
2277 ;; overview handling
2279 (defun elmo-multiple-field-body (name &optional boundary)
2282 (std11-narrow-to-header boundary)
2283 (goto-char (point-min))
2284 (let ((case-fold-search t)
2286 (while (re-search-forward (concat "^" name ":[ \t]*") nil t)
2289 (list (buffer-substring-no-properties
2290 (match-end 0) (std11-field-end))))))
2293 (defun elmo-parse-addresses (string)
2297 (let (list start s char)
2299 (goto-char (point-min))
2300 (skip-chars-forward "\t\f\n\r ")
2301 (setq start (point))
2303 (skip-chars-forward "^\"\\,(")
2304 (setq char (following-char))
2310 (setq s (buffer-substring start (point)))
2311 (if (or (null (string-match "^[\t\f\n\r ]+$" s))
2312 (not (string= s "")))
2313 (setq list (cons s list)))
2314 (skip-chars-forward ",\t\f\n\r ")
2315 (setq start (point)))
2317 (re-search-forward "[^\\]\"" nil 0))
2321 (while (and (not (eobp)) (not (zerop parens)))
2322 (re-search-forward "[()]" nil 0)
2324 (= (char-after (- (point) 2)) ?\\)))
2325 ((= (preceding-char) ?\()
2326 (setq parens (1+ parens)))
2328 (setq parens (1- parens)))))))))
2329 (setq s (buffer-substring start (point)))
2330 (if (and (null (string-match "^[\t\f\n\r ]+$" s))
2331 (not (string= s "")))
2332 (setq list (cons s list)))
2336 (defvar elmo-dop-queue-filename "queue"
2337 "*Disconnected operation queue is saved in this file.")
2339 (defun elmo-dop-queue-load ()
2340 (setq elmo-dop-queue
2342 (expand-file-name elmo-dop-queue-filename
2343 elmo-msgdb-directory))))
2345 (defun elmo-dop-queue-save ()
2347 (expand-file-name elmo-dop-queue-filename
2348 elmo-msgdb-directory)
2351 (if (and (fboundp 'regexp-opt)
2352 (not (featurep 'xemacs)))
2353 (defalias 'elmo-regexp-opt 'regexp-opt)
2354 (defun elmo-regexp-opt (strings &optional paren)
2355 "Return a regexp to match a string in STRINGS.
2356 Each string should be unique in STRINGS and should not contain any regexps,
2357 quoted or not. If optional PAREN is non-nil, ensure that the returned regexp
2358 is enclosed by at least one regexp grouping construct."
2359 (let ((open-paren (if paren "\\(" "")) (close-paren (if paren "\\)" "")))
2360 (concat open-paren (mapconcat 'regexp-quote strings "\\|")
2364 (product-provide (provide 'elmo-util) (require 'elmo-version))
2366 ;;; elmo-util.el ends here