Fix my last change.
[gnus] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (eval-and-compile
30   (autoload 'pop3-movemail "pop3")
31   (autoload 'pop3-get-message-count "pop3"))
32 (require 'format-spec)
33
34 (defgroup mail-source nil
35   "The mail-fetching library."
36   :group 'gnus)
37
38 (defcustom mail-sources nil
39   "*Where the mail backends will look for incoming mail.
40 This variable is a list of mail source specifiers.
41 See Info node `(gnus)Mail Source Specifiers'."
42   :group 'mail-source
43   ;; This specification should be tidied up, particularly to avoid
44   ;; constant items appearing.  (Perhaps there's scope for improvment
45   ;; in the widget code.)
46   :type `(repeat
47           (choice (const :tag "Default spool file" (file))
48                   (list :tag "Specified spool file"
49                         (const file)
50                         (const :value :path)
51                         file)
52                   (cons :tag "Several files in a directory"
53                         (const directory)
54                         (choice
55                          :tag "Options"
56                          (const :tag "None" nil)
57                          (repeat
58                           (choice
59                            (list :inline t :tag "path"
60                                  (const :value :path) directory)
61                            (list :inline t :tag "suffix"
62                                  (const :value :suffix) string)
63                            (list :inline t :tag "predicate"
64                                  (const :value :predicate) function)
65                            (list :inline t :tag "prescript"
66                                  (const :value :prescript) string)
67                            (list :inline t :tag "postscript"
68                                  (const :value :postscript) string)
69                            (list :inline t :tag "plugged"
70                                  (const :value :plugged) boolean)))))
71                   (cons :tag "POP3 server"
72                         (const pop)
73                         (choice
74                          :tag "Options"
75                          (const :tag "None" nil)
76                          (repeat
77                           (choice
78                            (list :inline t :tag "server"
79                                  (const :value :server) string)
80                            (list :inline t :tag "port"
81                                  (const :value :port) (choice number string))
82                            (list :inline t :tag "user"
83                                  (const :value :user) string)
84                            (list :inline t :tag "password"
85                                  (const :value :password) string)
86                            (list :inline t :tag "program"
87                                  (const :value :program) string)
88                            (list :inline t :tag "prescript"
89                                  (const :value :prescript) string)
90                            (list :inline t :tag "postscript"
91                                  (const :value :postscript) string)
92                            (list :inline t :tag "function"
93                                  (const :value :function) function)
94                            (list :inline t :tag "authentication"
95                                  (const :value :authentication)
96                                  (choice (const password)
97                                          (const apop)))
98                            (list :inline t :tag "plugged"
99                                  (const :value :plugged) boolean)))))
100                   (cons :tag "Maildir (qmail, postfix...)"
101                         (const maildir)
102                         (choice
103                          :tag "Options"
104                          (const :tag "None" nil)
105                          (repeat
106                           (choice
107                            (list :inline t :tag "path"
108                                  (const :value :path) directory)
109                            (list :inline t :tag "plugged"
110                                  (const :value :plugged) boolean)))))
111                   (cons :tag "IMAP server"
112                         (const imap)
113                         (choice
114                          :tag "Options"
115                          (const :tag "None" nil)
116                          (repeat
117                           (choice
118                            (list :inline t :tag "server"
119                                  (const :value :server) string)
120                            (list :inline t :tag "port"
121                                  (const :value :port)
122                                  (choice number string))
123                            (list :inline t :tag "user"
124                                  (const :value :user) string)
125                            (list :inline t :tag "password"
126                                  (const :value :password) string)
127                            (list :inline t :tag "stream"
128                                  (const :value :stream)
129                                  (choice ,@(progn (require 'imap)
130                                                   (mapcar
131                                                    (lambda (a)
132                                                      (list 'const (car a)))
133                                                    imap-stream-alist))))
134                            (list :inline t :tag "authenticator"
135                                  (const :value :authenticator)
136                                  (choice ,@(progn (require 'imap)
137                                                   (mapcar
138                                                    (lambda (a)
139                                                      (list 'const (car a)))
140                                                    imap-authenticator-alist))))
141                            (list :inline t :tag "mailbox"
142                                  (const :value :mailbox) string)
143                            (list :inline t :tag "predicate"
144                                  (const :value :predicate) function)
145                            (list :inline t :tag "fetchflag"
146                                  (const :value :fetchflag) string)
147                            (list :inline t :tag "dontexpunge"
148                                  (const :value :dontexpunge) boolean)
149                            (list :inline t :tag "plugged"
150                                  (const :value :plugged) )))))
151                   (cons :tag "Webmail server"
152                         (const webmail)
153                         (choice
154                          :tag "Options"
155                          (const :tag "None" nil)
156                          (repeat
157                           (choice
158                            (list :inline t :tag "subtype"
159                                  (const :value :subtype)
160                                  ;; Should be generated from
161                                  ;; `webmail-type-definition', but we
162                                  ;; can't require webmail without W3.
163                                  (choice (const hotmail) (const yahoo)
164                                          (const netaddress) (const netscape)
165                                          (const my-deja)))
166                            (list :inline t :tag "user"
167                                  (const :value :user) string)
168                            (list :inline t :tag "password"
169                                  (const :value :password) string)
170                            (list :inline t :tag "dontexpunge"
171                                  (const :value :dontexpunge) boolean)
172                            (list :inline t :tag "plugged"
173                                  (const :value :plugged) boolean))))))))
174
175 (defcustom mail-source-primary-source nil
176   "*Primary source for incoming mail.
177 If non-nil, this maildrop will be checked periodically for new mail."
178   :group 'mail-source
179   :type 'sexp)
180
181 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
182   "File where mail will be stored while processing it."
183   :group 'mail-source
184   :type 'file)
185
186 (defcustom mail-source-directory "~/Mail/"
187   "Directory where files (if any) will be stored."
188   :group 'mail-source
189   :type 'directory)
190
191 (defcustom mail-source-default-file-modes 384
192   "Set the mode bits of all new mail files to this integer."
193   :group 'mail-source
194   :type 'integer)
195
196 (defcustom mail-source-delete-incoming nil
197   "*If non-nil, delete incoming files after handling."
198   :group 'mail-source
199   :type 'boolean)
200
201 (defcustom mail-source-incoming-file-prefix "Incoming"
202   "Prefix for file name for storing incoming mail"
203   :group 'mail-source
204   :type 'string)
205
206 (defcustom mail-source-report-new-mail-interval 5
207   "Interval in minutes between checks for new mail."
208   :group 'mail-source
209   :type 'number)
210
211 (defcustom mail-source-idle-time-delay 5
212   "Number of idle seconds to wait before checking for new mail."
213   :group 'mail-source
214   :type 'number)
215
216 ;;; Internal variables.
217
218 (defvar mail-source-string ""
219   "A dynamically bound string that says what the current mail source is.")
220
221 (defvar mail-source-new-mail-available nil
222   "Flag indicating when new mail is available.")
223
224 (eval-and-compile
225   (defvar mail-source-common-keyword-map
226     '((:plugged))
227     "Mapping from keywords to default values.
228 Common keywords should be listed here.")
229
230   (defvar mail-source-keyword-map
231     '((file
232        (:prescript)
233        (:prescript-delay)
234        (:postscript)
235        (:path (or (getenv "MAIL")
236                   (concat "/usr/spool/mail/" (user-login-name)))))
237       (directory
238        (:path)
239        (:suffix ".spool")
240        (:predicate identity))
241       (pop
242        (:prescript)
243        (:prescript-delay)
244        (:postscript)
245        (:server (getenv "MAILHOST"))
246        (:port 110)
247        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
248        (:program)
249        (:function)
250        (:password)
251        (:authentication password))
252       (maildir
253        (:path (or (getenv "MAILDIR") "~/Maildir/"))
254        (:subdirs ("new" "cur"))
255        (:function))
256       (imap
257        (:server (getenv "MAILHOST"))
258        (:port)
259        (:stream)
260        (:authentication)
261        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
262        (:password)
263        (:mailbox "INBOX")
264        (:predicate "UNSEEN UNDELETED")
265        (:fetchflag "\\Deleted")
266        (:dontexpunge))
267       (webmail
268        (:subtype hotmail)
269        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
270        (:password)
271        (:dontexpunge)
272        (:authentication password)))
273     "Mapping from keywords to default values.
274 All keywords that can be used must be listed here."))
275
276 (defvar mail-source-fetcher-alist
277   '((file mail-source-fetch-file)
278     (directory mail-source-fetch-directory)
279     (pop mail-source-fetch-pop)
280     (maildir mail-source-fetch-maildir)
281     (imap mail-source-fetch-imap)
282     (webmail mail-source-fetch-webmail))
283   "A mapping from source type to fetcher function.")
284
285 (defvar mail-source-password-cache nil)
286
287 (defvar mail-source-plugged t)
288
289 ;;; Functions
290
291 (eval-and-compile
292   (defun mail-source-strip-keyword (keyword)
293     "Strip the leading colon off the KEYWORD."
294     (intern (substring (symbol-name keyword) 1))))
295
296 (eval-and-compile
297   (defun mail-source-bind-1 (type)
298     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
299            default bind)
300       (while (setq default (pop defaults))
301         (push (list (mail-source-strip-keyword (car default))
302                     nil)
303               bind))
304       bind)))
305
306 (defmacro mail-source-bind (type-source &rest body)
307   "Return a `let' form that binds all variables in source TYPE.
308 TYPE-SOURCE is a list where the first element is the TYPE, and
309 the second variable is the SOURCE.
310 At run time, the mail source specifier SOURCE will be inspected,
311 and the variables will be set according to it.  Variables not
312 specified will be given default values.
313
314 After this is done, BODY will be executed in the scope
315 of the `let' form.
316
317 The variables bound and their default values are described by
318 the `mail-source-keyword-map' variable."
319   `(let ,(mail-source-bind-1 (car type-source))
320      (mail-source-set-1 ,(cadr type-source))
321      ,@body))
322
323 (put 'mail-source-bind 'lisp-indent-function 1)
324 (put 'mail-source-bind 'edebug-form-spec '(form body))
325
326 (defun mail-source-set-1 (source)
327   (let* ((type (pop source))
328          (defaults (cdr (assq type mail-source-keyword-map)))
329          default value keyword)
330     (while (setq default (pop defaults))
331       (set (mail-source-strip-keyword (setq keyword (car default)))
332            (if (setq value (plist-get source keyword))
333                (mail-source-value value)
334              (mail-source-value (cadr default)))))))
335
336 (eval-and-compile
337   (defun mail-source-bind-common-1 ()
338     (let* ((defaults mail-source-common-keyword-map)
339            default bind)
340       (while (setq default (pop defaults))
341         (push (list (mail-source-strip-keyword (car default))
342                     nil)
343               bind))
344       bind)))
345
346 (defun mail-source-set-common-1 (source)
347   (let* ((type (pop source))
348          (defaults mail-source-common-keyword-map)
349          (defaults-1 (cdr (assq type mail-source-keyword-map)))
350          default value keyword)
351     (while (setq default (pop defaults))
352       (set (mail-source-strip-keyword (setq keyword (car default)))
353            (if (setq value (plist-get source keyword))
354                (mail-source-value value)
355              (if (setq value (assq  keyword defaults-1))
356                  (mail-source-value (cadr value))
357                (mail-source-value (cadr default))))))))
358
359 (defmacro mail-source-bind-common (source &rest body)
360   "Return a `let' form that binds all common variables.
361 See `mail-source-bind'."
362   `(let ,(mail-source-bind-common-1)
363      (mail-source-set-common-1 source)
364      ,@body))
365
366 (put 'mail-source-bind-common 'lisp-indent-function 1)
367 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
368
369 (defun mail-source-value (value)
370   "Return the value of VALUE."
371   (cond
372    ;; String
373    ((stringp value)
374     value)
375    ;; Function
376    ((and (listp value)
377          (functionp (car value)))
378     (eval value))
379    ;; Just return the value.
380    (t
381     value)))
382
383 (defun mail-source-fetch (source callback)
384   "Fetch mail from SOURCE and call CALLBACK zero or more times.
385 CALLBACK will be called with the name of the file where (some of)
386 the mail from SOURCE is put.
387 Return the number of files that were found."
388   (mail-source-bind-common source
389     (if (or mail-source-plugged plugged)
390         (save-excursion
391           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
392                 (found 0))
393             (unless function
394               (error "%S is an invalid mail source specification" source))
395             ;; If there's anything in the crash box, we do it first.
396             (when (file-exists-p mail-source-crash-box)
397               (message "Processing mail from %s..." mail-source-crash-box)
398               (setq found (mail-source-callback
399                            callback mail-source-crash-box)))
400             (+ found
401                (condition-case err
402                    (funcall function source callback)
403                  (error
404                   (unless (yes-or-no-p
405                            (format "Mail source error (%s).  Continue? " err))
406                     (error "Cannot get new mail."))
407                   0))))))))
408
409 (defun mail-source-make-complex-temp-name (prefix)
410   (let ((newname (make-temp-name prefix))
411         (newprefix prefix))
412     (while (file-exists-p newname)
413       (setq newprefix (concat newprefix "x"))
414       (setq newname (make-temp-name newprefix)))
415     newname))
416
417 (defun mail-source-callback (callback info)
418   "Call CALLBACK on the mail file, and then remove the mail file.
419 Pass INFO on to CALLBACK."
420   (if (or (not (file-exists-p mail-source-crash-box))
421           (zerop (nth 7 (file-attributes mail-source-crash-box))))
422       (progn
423         (when (file-exists-p mail-source-crash-box)
424           (delete-file mail-source-crash-box))
425         0)
426     (prog1
427         (funcall callback mail-source-crash-box info)
428       (when (file-exists-p mail-source-crash-box)
429         ;; Delete or move the incoming mail out of the way.
430         (if mail-source-delete-incoming
431             (delete-file mail-source-crash-box)
432           (let ((incoming
433                  (mail-source-make-complex-temp-name
434                   (expand-file-name
435                    mail-source-incoming-file-prefix
436                    mail-source-directory))))
437             (unless (file-exists-p (file-name-directory incoming))
438               (make-directory (file-name-directory incoming) t))
439             (rename-file mail-source-crash-box incoming t)))))))
440
441 (defun mail-source-movemail (from to)
442   "Move FROM to TO using movemail."
443   (if (not (file-writable-p to))
444       (error "Can't write to crash box %s.  Not moving mail" to)
445     (let ((to (file-truename (expand-file-name to)))
446           errors result)
447       (setq to (file-truename to)
448             from (file-truename from))
449       ;; Set TO if have not already done so, and rename or copy
450       ;; the file FROM to TO if and as appropriate.
451       (cond
452        ((file-exists-p to)
453         ;; The crash box exists already.
454         t)
455        ((not (file-exists-p from))
456         ;; There is no inbox.
457         (setq to nil))
458        ((zerop (nth 7 (file-attributes from)))
459         ;; Empty file.
460         (setq to nil))
461        (t
462         ;; If getting from mail spool directory, use movemail to move
463         ;; rather than just renaming, so as to interlock with the
464         ;; mailer.
465         (unwind-protect
466             (save-excursion
467               (setq errors (generate-new-buffer " *mail source loss*"))
468               (let ((default-directory "/"))
469                 (setq result
470                       (apply
471                        'call-process
472                        (append
473                         (list
474                          (expand-file-name "movemail" exec-directory)
475                          nil errors nil from to)))))
476               (when (file-exists-p to)
477                 (set-file-modes to mail-source-default-file-modes))
478               (if (and (not (buffer-modified-p errors))
479                        (zerop result))
480                   ;; No output => movemail won.
481                   t
482                 (set-buffer errors)
483                 ;; There may be a warning about older revisions.  We
484                 ;; ignore that.
485                 (goto-char (point-min))
486                 (if (search-forward "older revision" nil t)
487                     t
488                   ;; Probably a real error.
489                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
490                   (goto-char (point-max))
491                   (skip-chars-backward " \t")
492                   (delete-region (point) (point-max))
493                   (goto-char (point-min))
494                   (when (looking-at "movemail: ")
495                     (delete-region (point-min) (match-end 0)))
496                   (unless (yes-or-no-p
497                            (format "movemail: %s (%d return).  Continue? "
498                                    (buffer-string) result))
499                     (error "%s" (buffer-string)))
500                   (setq to nil)))))))
501       (when (and errors
502                  (buffer-name errors))
503         (kill-buffer errors))
504       ;; Return whether we moved successfully or not.
505       to)))
506
507 (defun mail-source-movemail-and-remove (from to)
508   "Move FROM to TO using movemail, then remove FROM if empty."
509   (or (not (mail-source-movemail from to))
510       (not (zerop (nth 7 (file-attributes from))))
511       (delete-file from)))
512
513 (defvar mail-source-read-passwd nil)
514 (defun mail-source-read-passwd (prompt &rest args)
515   "Read a password using PROMPT.
516 If ARGS, PROMPT is used as an argument to `format'."
517   (let ((prompt
518          (if args
519              (apply 'format prompt args)
520            prompt)))
521     (unless mail-source-read-passwd
522       (if (or (fboundp 'read-passwd) (load "passwd" t))
523           (setq mail-source-read-passwd 'read-passwd)
524         (unless (fboundp 'ange-ftp-read-passwd)
525           (autoload 'ange-ftp-read-passwd "ange-ftp"))
526         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
527     (funcall mail-source-read-passwd prompt)))
528
529 (defun mail-source-fetch-with-program (program)
530   (zerop (call-process shell-file-name nil nil nil
531                        shell-command-switch program)))
532
533 (defun mail-source-run-script (script spec &optional delay)
534   (when script
535     (if (and (symbolp script) (fboundp script))
536         (funcall script)
537       (mail-source-call-script
538        (format-spec script spec))))
539   (when delay
540     (sleep-for delay)))
541
542 (defun mail-source-call-script (script)
543   (let ((background nil))
544     (when (string-match "& *$" script)
545       (setq script (substring script 0 (match-beginning 0))
546             background 0))
547     (call-process shell-file-name nil background nil
548                   shell-command-switch script)))
549
550 ;;;
551 ;;; Different fetchers
552 ;;;
553
554 (defun mail-source-fetch-file (source callback)
555   "Fetcher for single-file sources."
556   (mail-source-bind (file source)
557     (mail-source-run-script
558      prescript (format-spec-make ?t mail-source-crash-box)
559      prescript-delay)
560     (let ((mail-source-string (format "file:%s" path)))
561       (if (mail-source-movemail path mail-source-crash-box)
562           (prog1
563               (mail-source-callback callback path)
564             (mail-source-run-script
565              postscript (format-spec-make ?t mail-source-crash-box)))
566         0))))
567
568 (defun mail-source-fetch-directory (source callback)
569   "Fetcher for directory sources."
570   (mail-source-bind (directory source)
571     (let ((found 0)
572           (mail-source-string (format "directory:%s" path)))
573       (dolist (file (directory-files
574                      path t (concat (regexp-quote suffix) "$")))
575         (when (and (file-regular-p file)
576                    (funcall predicate file)
577                    (mail-source-movemail file mail-source-crash-box))
578           (incf found (mail-source-callback callback file))))
579       found)))
580
581 (defun mail-source-fetch-pop (source callback)
582   "Fetcher for single-file sources."
583   (mail-source-bind (pop source)
584     (mail-source-run-script
585      prescript
586      (format-spec-make ?p password ?t mail-source-crash-box
587                        ?s server ?P port ?u user)
588      prescript-delay)
589     (let ((from (format "%s:%s:%s" server user port))
590           (mail-source-string (format "pop:%s@%s" user server))
591           result)
592       (when (eq authentication 'password)
593         (setq password
594               (or password
595                   (cdr (assoc from mail-source-password-cache))
596                   (mail-source-read-passwd
597                    (format "Password for %s at %s: " user server)))))
598       (when server
599         (setenv "MAILHOST" server))
600       (setq result
601             (cond
602              (program
603               (mail-source-fetch-with-program
604                (format-spec
605                 program
606                 (format-spec-make ?p password ?t mail-source-crash-box
607                                   ?s server ?P port ?u user))))
608              (function
609               (funcall function mail-source-crash-box))
610              ;; The default is to use pop3.el.
611              (t
612               (let ((pop3-password password)
613                     (pop3-maildrop user)
614                     (pop3-mailhost server)
615                     (pop3-port port)
616                     (pop3-authentication-scheme
617                      (if (eq authentication 'apop) 'apop 'pass)))
618                 (save-excursion (pop3-movemail mail-source-crash-box))))))
619       (if result
620           (progn
621             (when (eq authentication 'password)
622               (unless (assoc from mail-source-password-cache)
623                 (push (cons from password) mail-source-password-cache)))
624             (prog1
625                 (mail-source-callback callback server)
626               ;; Update display-time's mail flag, if relevant.
627               (if (equal source mail-source-primary-source)
628                   (setq mail-source-new-mail-available nil))
629               (mail-source-run-script
630                postscript
631                (format-spec-make ?p password ?t mail-source-crash-box
632                                  ?s server ?P port ?u user))))
633         ;; We nix out the password in case the error
634         ;; was because of a wrong password being given.
635         (setq mail-source-password-cache
636               (delq (assoc from mail-source-password-cache)
637                     mail-source-password-cache))
638         0))))
639
640 (defun mail-source-check-pop (source)
641   "Check whether there is new mail."
642   (mail-source-bind (pop source)
643     (let ((from (format "%s:%s:%s" server user port))
644           (mail-source-string (format "pop:%s@%s" user server))
645           result)
646       (when (eq authentication 'password)
647         (setq password
648               (or password
649                   (cdr (assoc from mail-source-password-cache))
650                   (mail-source-read-passwd
651                    (format "Password for %s at %s: " user server))))
652         (unless (assoc from mail-source-password-cache)
653           (push (cons from password) mail-source-password-cache)))
654       (when server
655         (setenv "MAILHOST" server))
656       (setq result
657             (cond
658              ;; No easy way to check whether mail is waiting for these.
659              (program)
660              (function)
661              ;; The default is to use pop3.el.
662              (t
663               (let ((pop3-password password)
664                     (pop3-maildrop user)
665                     (pop3-mailhost server)
666                     (pop3-port port)
667                     (pop3-authentication-scheme
668                      (if (eq authentication 'apop) 'apop 'pass)))
669                 (save-excursion (pop3-get-message-count))))))
670       (if result
671           ;; Inform display-time that we have new mail.
672           (setq mail-source-new-mail-available (> result 0))
673         ;; We nix out the password in case the error
674         ;; was because of a wrong password being given.
675         (setq mail-source-password-cache
676               (delq (assoc from mail-source-password-cache)
677                     mail-source-password-cache)))
678       result)))
679
680 (defun mail-source-new-mail-p ()
681   "Handler for `display-time' to indicate when new mail is available."
682   ;; Only report flag setting; flag is updated on a different schedule.
683   mail-source-new-mail-available)
684
685
686 (defvar mail-source-report-new-mail nil)
687 (defvar mail-source-report-new-mail-timer nil)
688 (defvar mail-source-report-new-mail-idle-timer nil)
689
690 (eval-when-compile 
691   (if (featurep 'xemacs)
692       (require 'itimer)
693     (require 'timer)))
694
695 (defun mail-source-start-idle-timer ()
696   ;; Start our idle timer if necessary, so we delay the check until the
697   ;; user isn't typing.
698   (unless mail-source-report-new-mail-idle-timer
699     (setq mail-source-report-new-mail-idle-timer
700           (run-with-idle-timer
701            mail-source-idle-time-delay
702            nil
703            (lambda ()
704              (setq mail-source-report-new-mail-idle-timer nil)
705              (mail-source-check-pop mail-source-primary-source))))
706     ;; Since idle timers created when Emacs is already in the idle
707     ;; state don't get activated until Emacs _next_ becomes idle, we
708     ;; need to force our timer to be considered active now.  We do
709     ;; this by being naughty and poking the timer internals directly
710     ;; (element 0 of the vector is nil if the timer is active).
711     (aset mail-source-report-new-mail-idle-timer 0 nil)))
712
713 (defun mail-source-report-new-mail (arg)
714   "Toggle whether to report when new mail is available.
715 This only works when `display-time' is enabled."
716   (interactive "P")
717   (if (not mail-source-primary-source)
718       (error "Need to set `mail-source-primary-source' to check for new mail."))
719   (let ((on (if (null arg)
720                 (not mail-source-report-new-mail)
721               (> (prefix-numeric-value arg) 0))))
722     (setq mail-source-report-new-mail on)
723     (and mail-source-report-new-mail-timer
724          (nnheader-cancel-timer mail-source-report-new-mail-timer))
725     (and mail-source-report-new-mail-idle-timer
726          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
727     (setq mail-source-report-new-mail-timer nil)
728     (setq mail-source-report-new-mail-idle-timer nil)
729     (if on
730         (progn
731           (require 'time)
732           ;; display-time-mail-function is an Emacs 21 feature.
733           (setq display-time-mail-function #'mail-source-new-mail-p)
734           ;; Set up the main timer.
735           (setq mail-source-report-new-mail-timer
736                 (run-at-time t (* 60 mail-source-report-new-mail-interval)
737                              #'mail-source-start-idle-timer))
738           ;; When you get new mail, clear "Mail" from the mode line.
739           (add-hook 'nnmail-post-get-new-mail-hook
740                     'display-time-event-handler)
741           (message "Mail check enabled"))
742       (setq display-time-mail-function nil)
743       (remove-hook 'nnmail-post-get-new-mail-hook
744                    'display-time-event-handler)
745       (message "Mail check disabled"))))
746
747 (defun mail-source-fetch-maildir (source callback)
748   "Fetcher for maildir sources."
749   (mail-source-bind (maildir source)
750     (let ((found 0)
751           mail-source-string)
752       (unless (string-match "/$" path)
753         (setq path (concat path "/")))
754       (dolist (subdir subdirs)
755         (when (file-directory-p (concat path subdir))
756           (setq mail-source-string (format "maildir:%s%s" path subdir))
757           (dolist (file (directory-files (concat path subdir) t))
758             (when (and (not (file-directory-p file))
759                        (not (if function
760                                 (funcall function file mail-source-crash-box)
761                               (let ((coding-system-for-write 
762                                      mm-text-coding-system)
763                                     (coding-system-for-read 
764                                      mm-text-coding-system))
765                                 (with-temp-file mail-source-crash-box
766                                   (insert-file-contents file)
767                                   (goto-char (point-min))
768 ;;;                               ;; Unix mail format
769 ;;;                               (unless (looking-at "\n*From ")
770 ;;;                                 (insert "From maildir " 
771 ;;;                                         (current-time-string) "\n"))
772 ;;;                               (while (re-search-forward "^From " nil t)
773 ;;;                                 (replace-match ">From "))
774 ;;;                               (goto-char (point-max))
775 ;;;                               (insert "\n\n")
776                                   ;; MMDF mail format
777                                   (insert "\001\001\001\001\n"))
778                                 (delete-file file)))))
779               (incf found (mail-source-callback callback file))))))
780       found)))
781
782 (eval-and-compile
783   (autoload 'imap-open "imap")
784   (autoload 'imap-authenticate "imap")
785   (autoload 'imap-mailbox-select "imap")
786   (autoload 'imap-mailbox-unselect "imap")
787   (autoload 'imap-mailbox-close "imap")
788   (autoload 'imap-search "imap")
789   (autoload 'imap-fetch "imap")
790   (autoload 'imap-close "imap")
791   (autoload 'imap-error-text "imap")
792   (autoload 'imap-message-flags-add "imap")
793   (autoload 'imap-list-to-message-set "imap")
794   (autoload 'imap-range-to-message-set "imap")
795   (autoload 'nnheader-ms-strip-cr "nnheader"))
796
797 (defvar mail-source-imap-file-coding-system 'binary
798   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
799
800 (defun mail-source-fetch-imap (source callback)
801   "Fetcher for imap sources."
802   (mail-source-bind (imap source)
803     (let ((from (format "%s:%s:%s" server user port))
804           (found 0)
805           (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
806           (mail-source-string (format "imap:%s:%s" server mailbox))
807           remove)
808       (if (and (imap-open server port stream authentication buf)
809                (imap-authenticate
810                 user (or (cdr (assoc from mail-source-password-cache))
811                          password) buf)
812                (imap-mailbox-select mailbox nil buf))
813           (let (str (coding-system-for-write mail-source-imap-file-coding-system))
814             (with-temp-file mail-source-crash-box
815               ;; In some versions of FSF Emacs, inserting unibyte
816               ;; string into multibyte buffer may convert 8-bit chars
817               ;; into latin-iso8859-1 chars, which results \201's.
818               (mm-disable-multibyte)
819               ;; remember password
820               (with-current-buffer buf
821                 (when (or imap-password
822                           (assoc from mail-source-password-cache))
823                   (push (cons from imap-password) mail-source-password-cache)))
824               ;; if predicate is nil, use all uids
825               (dolist (uid (imap-search (or predicate "1:*") buf))
826                 (when (setq str (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf))
827                   (push uid remove)
828                   (insert "From imap " (current-time-string) "\n")
829                   (save-excursion
830                     (insert str "\n\n"))
831                   (while (re-search-forward "^From " nil t)
832                     (replace-match ">From "))
833                   (goto-char (point-max))))
834               (nnheader-ms-strip-cr))
835             (incf found (mail-source-callback callback server))
836             (when (and remove fetchflag)
837               (imap-message-flags-add
838                (imap-range-to-message-set (gnus-compress-sequence remove))
839                fetchflag nil buf))
840             (if dontexpunge
841                 (imap-mailbox-unselect buf)
842               (imap-mailbox-close buf))
843             (imap-close buf))
844         (imap-close buf)
845         ;; We nix out the password in case the error
846         ;; was because of a wrong password being given.
847         (setq mail-source-password-cache
848               (delq (assoc from mail-source-password-cache)
849                     mail-source-password-cache))
850         (error (imap-error-text buf)))
851       (kill-buffer buf)
852       found)))
853
854 (eval-and-compile
855   (autoload 'webmail-fetch "webmail"))
856
857 (defun mail-source-fetch-webmail (source callback)
858   "Fetch for webmail source."
859   (mail-source-bind (webmail source)
860     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
861           (webmail-newmail-only dontexpunge)
862           (webmail-move-to-trash-can (not dontexpunge)))
863       (when (eq authentication 'password)
864         (setq password
865               (or password
866                   (cdr (assoc (format "webmail:%s:%s" subtype user) 
867                               mail-source-password-cache))
868                   (mail-source-read-passwd
869                    (format "Password for %s at %s: " user subtype))))
870         (when (and password
871                    (not (assoc (format "webmail:%s:%s" subtype user) 
872                                mail-source-password-cache)))
873           (push (cons (format "webmail:%s:%s" subtype user) password) 
874                 mail-source-password-cache)))
875       (webmail-fetch mail-source-crash-box subtype user password)
876       (mail-source-callback callback (symbol-name subtype)))))
877
878 (provide 'mail-source)
879
880 ;;; mail-source.el ends here