*** empty log message ***
[gnus] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2 ;; Copyright (C) 1995,96 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
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 (require 'nnheader)
29 (require 'timezone)
30 (require 'message)
31 (eval-when-compile (require 'cl))
32
33 (defvar nnmail-split-methods
34   '(("mail.misc" ""))
35   "*Incoming mail will be split according to this variable.
36
37 If you'd like, for instance, one mail group for mail from the
38 \"4ad-l\" mailing list, one group for junk mail and one for everything
39 else, you could do something like this:
40
41  (setq nnmail-split-methods
42        '((\"mail.4ad\" \"From:.*4ad\")
43          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
44          (\"mail.misc\" \"\")))
45
46 As you can see, this variable is a list of lists, where the first
47 element in each \"rule\" is the name of the group (which, by the way,
48 does not have to be called anything beginning with \"mail\",
49 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
50 nnmail will try to match on the header to find a fit.
51
52 The second element can also be a function.  In that case, it will be
53 called narrowed to the headers with the first element of the rule as
54 the argument.  It should return a non-nil value if it thinks that the
55 mail belongs in that group.
56
57 The last element should always have \"\" as the regexp.
58
59 This variable can also have a function as its value.")
60
61 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
62 (defvar nnmail-crosspost t
63   "*If non-nil, do crossposting if several split methods match the mail.
64 If nil, the first match found will be used.")
65
66 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
67 (defvar nnmail-keep-last-article nil
68   "*If non-nil, nnmail will never delete the last expired article in a directory.  
69 You may need to set this variable if other programs are putting
70 new mail into folder numbers that Gnus has marked as expired.")
71
72 (defvar nnmail-use-long-file-names nil
73   "*If non-nil the mail backends will use long file and directory names.
74 If nil, groups like \"mail.misc\" will end up in directories like
75 \"mail/misc/\".")
76
77 (defvar nnmail-default-file-modes 384
78   "Set the mode bits of all new mail files to this integer.")
79
80 (defvar nnmail-expiry-wait 7
81   "*Expirable articles that are older than this will be expired.
82 This variable can either be a number (which will be interpreted as a
83 number of days) -- this doesn't have to be an integer.  This variable
84 can also be `immediate' and `never'.")
85
86 (defvar nnmail-expiry-wait-function nil
87   "*Variable that holds function to specify how old articles should be before they are expired.
88   The function will be called with the name of the group that the
89 expiry is to be performed in, and it should return an integer that
90 says how many days an article can be stored before it is considered
91 \"old\".  It can also return the values `never' and `immediate'.
92
93 Eg.:
94
95 (setq nnmail-expiry-wait-function
96       (lambda (newsgroup)
97         (cond ((string-match \"private\" newsgroup) 31)
98               ((string-match \"junk\" newsgroup) 1)
99               ((string-match \"important\" newsgroup) 'never)
100               (t 7))))")
101
102 (defvar nnmail-spool-file 
103   (or (getenv "MAIL")
104       (concat "/usr/spool/mail/" (user-login-name)))
105   "Where the mail backends will look for incoming mail.
106 This variable is \"/usr/spool/mail/$user\" by default.
107 If this variable is nil, no mail backends will read incoming mail.
108 If this variable is a list, all files mentioned in this list will be
109 used as incoming mailboxes.")
110
111 (defvar nnmail-crash-box "~/.gnus-crash-box"
112   "*File where Gnus will store mail while processing it.")
113
114 (defvar nnmail-use-procmail nil
115   "*If non-nil, the mail backends will look in `nnmail-procmail-directory' for spool files.
116 The file(s) in `nnmail-spool-file' will also be read.")
117
118 (defvar nnmail-procmail-directory "~/incoming/"
119   "*When using procmail (and the like), incoming mail is put in this directory.
120 The Gnus mail backends will read the mail from this directory.")
121
122 (defvar nnmail-procmail-suffix "\\.spool"
123   "*Suffix of files created by procmail (and the like).
124 This variable might be a suffix-regexp to match the suffixes of
125 several files - eg. \".spool[0-9]*\".")
126
127 (defvar nnmail-resplit-incoming nil
128   "*If non-nil, re-split incoming procmail sorted mail.")
129
130 (defvar nnmail-delete-file-function 'delete-file
131   "Function called to delete files in some mail backends.")
132
133 (defvar nnmail-crosspost-link-function 'add-name-to-file
134   "Function called to create a copy of a file.
135 This is `add-name-to-file' by default, which means that crossposts
136 will use hard links.  If your file system doesn't allow hard
137 links, you could set this variable to `copy-file' instead.")
138
139 (defvar nnmail-movemail-program "movemail"
140   "*A command to be executed to move mail from the inbox.
141 The default is \"movemail\".
142
143 This can also be a function.  In that case, the function will be
144 called with two parameters -- the name of the INBOX file, and the file
145 to be moved to.")
146
147 (defvar nnmail-pop-password-required nil
148   "*Non-nil if a password is required when reading mail using POP.")
149
150 (defvar nnmail-read-incoming-hook nil
151   "*Hook that will be run after the incoming mail has been transferred.
152 The incoming mail is moved from `nnmail-spool-file' (which normally is
153 something like \"/usr/spool/mail/$user\") to the user's home
154 directory.  This hook is called after the incoming mail box has been
155 emptied, and can be used to call any mail box programs you have
156 running (\"xwatch\", etc.)
157
158 Eg.
159
160 \(add-hook 'nnmail-read-incoming-hook 
161            (lambda ()
162              (start-process \"mailsend\" nil 
163                             \"/local/bin/mailsend\" \"read\" \"mbox\")))
164
165 If you have xwatch running, this will alert it that mail has been
166 read.  
167
168 If you use `display-time', you could use something like this:
169
170 \(add-hook 'nnmail-read-incoming-hook
171           (lambda ()
172             ;; Update the displayed time, since that will clear out
173             ;; the flag that says you have mail.
174             (when (eq (process-status \"display-time\") 'run)
175               (display-time-filter display-time-process \"\"))))")
176
177 (when (eq system-type 'windows-nt)
178   (add-hook 'nnmail-prepare-incoming-hook 'nnheader-ms-strip-cr))
179
180 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
181 (defvar nnmail-prepare-incoming-hook nil
182   "*Hook called before treating incoming mail.
183 The hook is run in a buffer with all the new, incoming mail.")
184
185 (defvar nnmail-prepare-incoming-header-hook nil
186   "*Hook called narrowed to the headers of each message.
187 This can be used to remove excessive spaces (and stuff like
188 that) from the headers before splitting and saving the messages.")
189
190 (defvar nnmail-prepare-incoming-message-hook nil
191   "*Hook called narrowed to each message.")
192
193 (defvar nnmail-list-identifiers nil
194   "Regexp that match list identifiers to be removed.
195 This can also be a list of regexps.")
196
197 (defvar nnmail-pre-get-new-mail-hook nil
198   "Hook called just before starting to handle new incoming mail.")
199
200 (defvar nnmail-post-get-new-mail-hook nil
201   "Hook called just after finishing handling new incoming mail.")
202
203 (defvar nnmail-split-hook nil
204   "Hook called before deciding where to split an article.
205 The functions in this hook are free to modify the buffer
206 contents in any way they choose -- the buffer contents are
207 discarded after running the split process.")
208
209 ;; Suggested by Mejia Pablo J <pjm9806@usl.edu>.
210 (defvar nnmail-tmp-directory nil
211   "*If non-nil, use this directory for temporary storage when reading incoming mail.")
212
213 (defvar nnmail-large-newsgroup 50
214   "*The number of the articles which indicates a large newsgroup.
215 If the number of the articles is greater than the value, verbose
216 messages will be shown to indicate the current status.")
217
218 (defvar nnmail-split-fancy "mail.misc"
219   "*Incoming mail can be split according to this fancy variable.
220 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
221
222 The format is this variable is SPLIT, where SPLIT can be one of
223 the following:
224
225 GROUP: Mail will be stored in GROUP (a string).
226
227 \(FIELD VALUE SPLIT): If the message field FIELD (a regexp) contains
228   VALUE (a regexp), store the messages as specified by SPLIT.
229
230 \(| SPLIT...): Process each SPLIT expression until one of them matches.
231   A SPLIT expression is said to match if it will cause the mail
232   message to be stored in one or more groups.  
233
234 \(& SPLIT...): Process each SPLIT expression.
235
236 FIELD must match a complete field name.  VALUE must match a complete
237 word according to the `nnmail-split-fancy-syntax-table' syntax table.
238 You can use .* in the regexps to match partial field names or words.
239
240 FIELD and VALUE can also be lisp symbols, in that case they are expanded
241 as specified in `nnmail-split-abbrev-alist'.
242
243 Example:
244
245 \(setq nnmail-split-methods 'nnmail-split-fancy
246       nnmail-split-fancy
247       ;; Messages from the mailer daemon are not crossposted to any of
248       ;; the ordinary groups.  Warnings are put in a separate group
249       ;; from real errors.
250       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
251                           \"mail.misc\"))
252           ;; Non-error messages are crossposted to all relevant
253           ;; groups, but we don't crosspost between the group for the
254           ;; (ding) list and the group for other (ding) related mail.
255           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
256                 (\"subject\" \"ding\" \"ding.misc\"))
257              ;; Other mailing lists...
258              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
259              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
260              ;; People...
261              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
262           ;; Unmatched mail goes to the catch all group.
263           \"misc.misc\"))")
264
265 (defvar nnmail-split-abbrev-alist
266   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
267     (mail . "mailer-daemon\\|postmaster"))
268   "*Alist of abbreviations allowed in `nnmail-split-fancy'.")
269
270 (defvar nnmail-delete-incoming nil
271   "*If non-nil, the mail backends will delete incoming files after splitting.")
272
273 (defvar nnmail-message-id-cache-length 1000
274   "*The approximate number of Message-IDs nnmail will keep in its cache.
275 If this variable is nil, no checking on duplicate messages will be
276 performed.")
277
278 (defvar nnmail-message-id-cache-file "~/.nnmail-cache"
279   "*The file name of the nnmail Message-ID cache.")
280
281 (defvar nnmail-treat-duplicates 'warn
282   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
283 Three values are legal: nil, which means that nnmail is not to keep a
284 Message-ID cache; `warn', which means that nnmail should insert extra
285 headers to warn the user about the duplication (this is the default);
286 and `delete', which means that nnmail will delete duplicated mails.
287
288 This variable can also be a function.  It will be called from a buffer
289 narrowed to the article in question with the Message-ID as a
290 parameter.  It should return nil, `warn' or `delete'.")
291
292 ;;; Internal variables.
293
294 (defvar nnmail-split-history nil
295   "List of group/article elements that say where the previous split put messages.")
296
297 (defvar nnmail-pop-password nil
298   "*Password to use when reading mail from a POP server, if required.")
299
300 (defvar nnmail-split-fancy-syntax-table nil
301   "Syntax table used by `nnmail-split-fancy'.")
302 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
303   (setq nnmail-split-fancy-syntax-table
304         (copy-syntax-table (standard-syntax-table)))
305   ;; support the %-hack
306   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
307
308 (defvar nnmail-prepare-save-mail-hook nil
309   "Hook called before saving mail.")
310
311 (defvar nnmail-moved-inboxes nil
312   "List of inboxes that have been moved.")
313
314 (defvar nnmail-internal-password nil)
315
316 \f
317
318 (defconst nnmail-version "nnmail 1.0"
319   "nnmail version.")
320
321 \f
322
323 (defun nnmail-request-post (&optional server)
324   (mail-send-and-exit nil))
325
326 (defun nnmail-find-file (file)
327   "Insert FILE in server buffer safely."
328   (set-buffer nntp-server-buffer)
329   (erase-buffer)
330   (let ((format-alist nil)
331         (after-insert-file-functions nil))
332     (condition-case ()
333         (progn (insert-file-contents file) t)
334       (file-error nil))))
335
336 (defun nnmail-group-pathname (group dir &optional file)
337   "Make pathname for GROUP."
338   (concat
339    (let ((dir (file-name-as-directory (expand-file-name dir))))
340      ;; If this directory exists, we use it directly.
341      (if (or nnmail-use-long-file-names 
342              (file-directory-p (concat dir group)))
343          (concat dir group "/")
344        ;; If not, we translate dots into slashes.
345        (concat dir (nnheader-replace-chars-in-string group ?. ?/) "/")))
346    (or file "")))
347   
348 (defun nnmail-date-to-time (date)
349   "Convert DATE into time."
350   (let* ((d1 (timezone-parse-date date))
351          (t1 (timezone-parse-time (aref d1 3))))
352     (apply 'encode-time
353            (mapcar (lambda (el)
354                      (and el (string-to-number el)))
355                    (list
356                     (aref t1 2) (aref t1 1) (aref t1 0)
357                     (aref d1 2) (aref d1 1) (aref d1 0)
358                     (aref d1 4))))))
359
360 (defun nnmail-time-less (t1 t2)
361   "Say whether time T1 is less than time T2."
362   (or (< (car t1) (car t2))
363       (and (= (car t1) (car t2))
364            (< (nth 1 t1) (nth 1 t2)))))
365
366 (defun nnmail-days-to-time (days)
367   "Convert DAYS into time."
368   (let* ((seconds (* 1.0 days 60 60 24))
369          (rest (expt 2 16))
370          (ms (condition-case nil (round (/ seconds rest))
371                (range-error (expt 2 16)))))
372     (list ms (condition-case nil (round (- seconds (* ms rest)))
373                (range-error (expt 2 16))))))
374
375 (defun nnmail-time-since (time)
376   "Return the time since TIME, which is either an internal time or a date."
377   (when (stringp time)
378     ;; Convert date strings to internal time.
379     (setq time (nnmail-date-to-time time)))
380   (let* ((current (current-time))
381          (rest (when (< (nth 1 current) (nth 1 time))
382                  (expt 2 16))))
383     (list (- (+ (car current) (if rest -1 0)) (car time))
384           (- (+ (or rest 0) (nth 1 current)) (nth 1 time)))))
385
386 ;; Function rewritten from rmail.el.
387 (defun nnmail-move-inbox (inbox)
388   "Move INBOX to `nnmail-crash-box'."
389   (if (not (file-writable-p nnmail-crash-box))
390       (gnus-error 1 "Can't write to crash box %s.  Not moving mail."
391                   nnmail-crash-box)
392     (let ((inbox (file-truename (expand-file-name inbox)))
393           (tofile (file-truename (expand-file-name nnmail-crash-box)))
394           movemail popmail errors)
395       ;; If getting from mail spool directory,
396       ;; use movemail to move rather than just renaming,
397       ;; so as to interlock with the mailer.
398       (unless (setq popmail (string-match
399                              "^po:" (file-name-nondirectory inbox)))
400         (setq movemail t))
401       (when popmail 
402         (setq inbox (file-name-nondirectory inbox)))
403       (when (and movemail
404                  ;; On some systems, /usr/spool/mail/foo is a directory
405                  ;; and the actual inbox is /usr/spool/mail/foo/foo.
406                  (file-directory-p inbox))
407         (setq inbox (expand-file-name (user-login-name) inbox)))
408       (if (member inbox nnmail-moved-inboxes)
409           nil
410         (if popmail
411             (progn
412               (setq nnmail-internal-password nnmail-pop-password)
413               (when (and nnmail-pop-password-required
414                          (not nnmail-pop-password))
415                 (setq nnmail-internal-password
416                       (nnmail-read-passwd
417                        (format "Password for %s: "
418                                (substring inbox (+ popmail 3))))))
419               (message "Getting mail from post office ..."))
420           (when (or (and (file-exists-p tofile)
421                          (/= 0 (nnheader-file-size tofile)))
422                     (and (file-exists-p inbox)
423                          (/= 0 (nnheader-file-size inbox))))
424             (message "Getting mail from %s..." inbox)))
425         ;; Set TOFILE if have not already done so, and
426         ;; rename or copy the file INBOX to TOFILE if and as appropriate.
427         (cond 
428          ((file-exists-p tofile)
429           ;; The crash box exists already.
430           t)
431          ((and (not popmail)
432                (not (file-exists-p inbox)))
433           ;; There is no inbox.
434           (setq tofile nil))
435          ((and (not movemail) (not popmail))
436           ;; Try copying.  If that fails (perhaps no space),
437           ;; rename instead.
438           (condition-case nil
439               (copy-file inbox tofile nil)
440             (error
441              ;; Third arg is t so we can replace existing file TOFILE.
442              (rename-file inbox tofile t)))
443           (push inbox nnmail-moved-inboxes)
444           ;; Make the real inbox file empty.
445           ;; Leaving it deleted could cause lossage
446           ;; because mailers often won't create the file.
447           (condition-case ()
448               (write-region (point) (point) inbox)
449             (file-error nil)))
450          (t
451           ;; Use movemail.
452           (unwind-protect
453               (save-excursion
454                 (setq errors (generate-new-buffer " *nnmail loss*"))
455                 (buffer-disable-undo errors)
456                 (let ((default-directory "/"))
457                   (if (nnheader-functionp nnmail-movemail-program)
458                       (funcall nnmail-movemail-program inbox tofile)
459                     (apply 
460                      'call-process
461                      (append
462                       (list
463                        (expand-file-name nnmail-movemail-program
464                                          exec-directory)
465                        nil errors nil inbox tofile)
466                       (when nnmail-internal-password
467                         (list nnmail-internal-password))))))
468                 (if (not (buffer-modified-p errors))
469                     ;; No output => movemail won
470                     (progn
471                       (or popmail
472                           (set-file-modes tofile nnmail-default-file-modes))
473                       (push inbox nnmail-moved-inboxes))
474                   (set-buffer errors)
475                   ;; There may be a warning about older revisions.  We
476                   ;; ignore those.
477                   (goto-char (point-min))
478                   (if (search-forward "older revision" nil t)
479                       (progn
480                         (or popmail
481                             (set-file-modes tofile nnmail-default-file-modes))
482                         (push inbox nnmail-moved-inboxes))
483                     ;; Probably a real error.
484                     (subst-char-in-region (point-min) (point-max) ?\n ?\  )
485                     (goto-char (point-max))
486                     (skip-chars-backward " \t")
487                     (delete-region (point) (point-max))
488                     (goto-char (point-min))
489                     (when (looking-at "movemail: ")
490                       (delete-region (point-min) (match-end 0)))
491                     (unless (yes-or-no-p
492                              (format "movemail: %s.  Continue? "
493                                      (buffer-string)))
494                       (error "%s" (buffer-string)))
495                     (setq tofile nil)))))))
496         (and errors
497              (buffer-name errors)
498              (kill-buffer errors))
499         tofile))))
500
501 (defun nnmail-get-active ()
502   "Returns an assoc of group names and active ranges.
503 nn*-request-list should have been called before calling this function."
504   (let (group-assoc)
505     ;; Go through all groups from the active list.
506     (save-excursion
507       (set-buffer nntp-server-buffer)
508       (goto-char (point-min))
509       (while (re-search-forward 
510               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
511         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
512         (push (list (match-string 1)
513                     (cons (string-to-int (match-string 3))
514                           (string-to-int (match-string 2))))
515               group-assoc)))
516     group-assoc))
517
518 (defun nnmail-save-active (group-assoc file-name)
519   "Save GROUP-ASSOC in ACTIVE-FILE."
520   (when file-name
521     (nnheader-temp-write file-name
522       (nnmail-generate-active group-assoc))))
523
524 (defun nnmail-generate-active (alist)
525   "Generate an active file from group-alist ALIST."
526   (erase-buffer)
527   (let (group)
528     (while (setq group (pop alist))
529       (insert (format "%s %d %d y\n" (car group) (cdadr group)
530                       (caadr group))))))
531
532 (defun nnmail-get-split-group (file group)
533   "Find out whether this FILE is to be split into GROUP only.
534 If GROUP is non-nil and we are using procmail, return the group name
535 only when the file is the correct procmail file.  When GROUP is nil,
536 return nil if FILE is a spool file or the procmail group for which it
537 is a spool.  If not using procmail, return GROUP."
538   (if (or (eq nnmail-spool-file 'procmail)
539           nnmail-use-procmail)
540       (if (string-match (concat "^" (expand-file-name
541                                      (file-name-as-directory
542                                       nnmail-procmail-directory))
543                                 "\\([^/]*\\)" nnmail-procmail-suffix "$")
544                         (expand-file-name file))
545           (let ((procmail-group (substring (expand-file-name file)
546                                            (match-beginning 1)
547                                            (match-end 1))))
548             (if group 
549                 (if (string-equal group procmail-group)
550                     group
551                   nil)
552               procmail-group))
553         nil)
554     group))
555
556 (defun nnmail-process-babyl-mail-format (func artnum-func)
557   (let ((case-fold-search t)
558         start message-id content-length do-search end)
559     (while (not (eobp))
560       (goto-char (point-min))
561       (re-search-forward
562        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
563       (goto-char (match-end 0))
564       (delete-region (match-beginning 0) (match-end 0))
565       (narrow-to-region
566        (setq start (point))
567        (progn
568          ;; Skip all the headers in case there are more "From "s...
569          (or (search-forward "\n\n" nil t)
570              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
571              (search-forward "\1f\f"))
572          (point)))
573       (run-hooks 'nnmail-prepare-incoming-header-hook)
574       (widen)
575       ;; Find the Message-ID header.
576       (save-excursion
577         (if (re-search-backward "^Message-ID:[ \t]*\\(<[^>]*>\\)" nil t)
578             (setq message-id (buffer-substring (match-beginning 1)
579                                                (match-end 1)))
580           ;; There is no Message-ID here, so we create one.
581           (save-excursion
582             (when (re-search-backward "^Message-ID:" nil t)
583               (beginning-of-line)
584               (insert "Original-")))
585           (forward-line -1)
586           (insert "Message-ID: " (setq message-id (nnmail-message-id))
587                   "\n")))
588       ;; Look for a Content-Length header.
589       (if (not (save-excursion
590                  (and (re-search-backward 
591                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
592                       (setq content-length (string-to-int
593                                             (buffer-substring 
594                                              (match-beginning 1)
595                                              (match-end 1))))
596                       ;; We destroy the header, since none of
597                       ;; the backends ever use it, and we do not
598                       ;; want to confuse other mailers by having
599                       ;; a (possibly) faulty header.
600                       (progn (insert "X-") t))))
601           (setq do-search t)
602         (if (or (= (+ (point) content-length) (point-max))
603                 (save-excursion
604                   (goto-char (+ (point) content-length))
605                   (looking-at "\1f")))
606             (progn
607               (goto-char (+ (point) content-length))
608               (setq do-search nil))
609           (setq do-search t)))
610       ;; Go to the beginning of the next article - or to the end
611       ;; of the buffer.  
612       (when do-search
613         (if (re-search-forward "^\1f" nil t)
614             (goto-char (match-beginning 0))
615           (goto-char (1- (point-max)))))
616       (delete-char 1)                   ; delete ^_
617       (save-excursion
618         (save-restriction
619           (narrow-to-region start (point))
620           (goto-char (point-min))
621           (nnmail-check-duplication message-id func artnum-func)
622           (setq end (point-max))))
623       (goto-char end))))
624
625 (defun nnmail-search-unix-mail-delim ()
626   "Put point at the beginning of the next message."
627   (let ((case-fold-search t)
628         (delim (concat "^" message-unix-mail-delimiter))
629         found)
630     (while (not found)
631       (if (re-search-forward delim nil t)
632           (when (or (looking-at "[^\n :]+ *:")
633                     (looking-at delim)
634                     (looking-at (concat ">" message-unix-mail-delimiter)))
635             (forward-line -1)
636             (setq found 'yes))
637         (setq found 'no)))
638     (eq found 'yes)))
639
640 (defun nnmail-process-unix-mail-format (func artnum-func)
641   (let ((case-fold-search t)
642         (delim (concat "^" message-unix-mail-delimiter))
643         start message-id content-length end skip head-end)
644     (goto-char (point-min))
645     (if (not (and (re-search-forward delim nil t)
646                   (goto-char (match-beginning 0))))
647         ;; Possibly wrong format?
648         (error "Error, unknown mail format! (Possibly corrupted.)")
649       ;; Carry on until the bitter end.
650       (while (not (eobp))
651         (setq start (point)
652               end nil)
653         ;; Find the end of the head.
654         (narrow-to-region
655          start 
656          (if (search-forward "\n\n" nil t)
657              (1- (point))
658            ;; This will never happen, but just to be on the safe side --
659            ;; if there is no head-body delimiter, we search a bit manually.
660            (while (and (looking-at "From \\|[^ \t]+:")
661                        (not (eobp)))
662              (forward-line 1)
663              (point))))
664         ;; Find the Message-ID header.
665         (goto-char (point-min))
666         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
667             (setq message-id (match-string 1))
668           (save-excursion
669             (when (re-search-forward "^Message-ID:" nil t)
670               (beginning-of-line)
671               (insert "Original-")))
672           ;; There is no Message-ID here, so we create one.
673           (forward-line 1)
674           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
675         ;; Look for a Content-Length header.
676         (goto-char (point-min))
677         (if (not (re-search-forward
678                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
679             (setq content-length nil)
680           (setq content-length (string-to-int (match-string 1)))
681           ;; We destroy the header, since none of the backends ever 
682           ;; use it, and we do not want to confuse other mailers by
683           ;; having a (possibly) faulty header.
684           (beginning-of-line)
685           (insert "X-"))
686         (run-hooks 'nnmail-prepare-incoming-header-hook)
687         ;; Find the end of this article.
688         (goto-char (point-max))
689         (widen)
690         (setq head-end (point))
691         ;; We try the Content-Length value.  The idea: skip over the header
692         ;; separator, then check what happens content-length bytes into the
693         ;; message body.  This should be either the end ot the buffer, the
694         ;; message separator or a blank line followed by the separator.
695         ;; The blank line should probably be deleted.  If neither of the
696         ;; three is met, the content-length header is probably invalid.
697         (when content-length
698           (forward-line 1)
699           (setq skip (+ (point) content-length))
700           (goto-char skip)
701           (cond ((or (= skip (point-max))
702                      (= (1+ skip) (point-max)))
703                  (setq end (point-max)))
704                 ((looking-at delim)
705                  (setq end skip))
706                 ((looking-at
707                   (concat "[ \t]*\n\\(" delim "\\)"))
708                  (setq end (match-beginning 1)))
709                 (t (setq end nil))))
710         (if end
711             (goto-char end)
712           ;; No Content-Length, so we find the beginning of the next 
713           ;; article or the end of the buffer.
714           (goto-char head-end)
715           (or (nnmail-search-unix-mail-delim)
716               (goto-char (point-max))))
717         ;; Allow the backend to save the article.
718         (save-excursion
719           (save-restriction
720             (narrow-to-region start (point))
721             (goto-char (point-min))
722             (nnmail-check-duplication message-id func artnum-func)
723             (setq end (point-max))))
724         (goto-char end)))))
725
726 (defun nnmail-process-mmdf-mail-format (func artnum-func)
727   (let ((delim "^\^A\^A\^A\^A$")
728         (case-fold-search t)
729         start message-id end)
730     (goto-char (point-min))
731     (if (not (and (re-search-forward delim nil t)
732                   (forward-line 1)))
733         ;; Possibly wrong format?
734         (error "Error, unknown mail format! (Possibly corrupted.)")
735       ;; Carry on until the bitter end.
736       (while (not (eobp))
737         (setq start (point))
738         ;; Find the end of the head.
739         (narrow-to-region
740          start 
741          (if (search-forward "\n\n" nil t)
742              (1- (point))
743            ;; This will never happen, but just to be on the safe side --
744            ;; if there is no head-body delimiter, we search a bit manually.
745            (while (and (looking-at "From \\|[^ \t]+:")
746                        (not (eobp)))
747              (forward-line 1)
748              (point))))
749         ;; Find the Message-ID header.
750         (goto-char (point-min))
751         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
752             (setq message-id (match-string 1))
753           ;; There is no Message-ID here, so we create one.
754           (save-excursion
755             (when (re-search-backward "^Message-ID:" nil t)
756               (beginning-of-line)
757               (insert "Original-")))
758           (forward-line 1)
759           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
760         (run-hooks 'nnmail-prepare-incoming-header-hook)
761         ;; Find the end of this article.
762         (goto-char (point-max))
763         (widen)
764         (if (re-search-forward delim nil t)
765             (beginning-of-line)
766           (goto-char (point-max)))
767         ;; Allow the backend to save the article.
768         (save-excursion
769           (save-restriction
770             (narrow-to-region start (point))
771             (goto-char (point-min))
772             (nnmail-check-duplication message-id func artnum-func)
773             (setq end (point-max))))
774         (goto-char end)
775         (forward-line 2)))))
776
777 (defun nnmail-split-incoming (incoming func &optional exit-func
778                                        group artnum-func)
779   "Go through the entire INCOMING file and pick out each individual mail.
780 FUNC will be called with the buffer narrowed to each mail."
781   (let (;; If this is a group-specific split, we bind the split
782         ;; methods to just this group.
783         (nnmail-split-methods (if (and group
784                                        (or (eq nnmail-spool-file 'procmail)
785                                            nnmail-use-procmail)
786                                        (not nnmail-resplit-incoming))
787                                   (list (list group ""))
788                                 nnmail-split-methods)))
789     (save-excursion
790       ;; Insert the incoming file.
791       (set-buffer (get-buffer-create " *nnmail incoming*"))
792       (buffer-disable-undo (current-buffer))
793       (erase-buffer)
794       (nnheader-insert-file-contents-literally incoming)
795       (unless (zerop (buffer-size))
796         (goto-char (point-min))
797         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
798         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
799         ;; use the former when fetching from a mailbox, the latter when
800         ;; fetches from a file.
801         (cond ((or (looking-at "\^L")
802                    (looking-at "BABYL OPTIONS:"))
803                (nnmail-process-babyl-mail-format func artnum-func))
804               ((looking-at "\^A\^A\^A\^A")
805                (nnmail-process-mmdf-mail-format func artnum-func))
806               (t
807                (nnmail-process-unix-mail-format func artnum-func))))
808       (when exit-func
809         (funcall exit-func))
810       (kill-buffer (current-buffer)))))
811
812 ;; Mail crossposts suggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
813 (defun nnmail-article-group (func)
814   "Look at the headers and return an alist of groups that match.
815 FUNC will be called with the group name to determine the article number."
816   (let ((methods nnmail-split-methods)
817         (obuf (current-buffer))
818         (beg (point-min))
819         end group-art method)
820     (if (and (sequencep methods) (= (length methods) 1))
821         ;; If there is only just one group to put everything in, we
822         ;; just return a list with just this one method in.
823         (setq group-art
824               (list (cons (caar methods) (funcall func (caar methods)))))
825       ;; We do actual comparison.
826       (save-excursion
827         ;; Find headers.
828         (goto-char beg)
829         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
830         (set-buffer nntp-server-buffer)
831         (erase-buffer)
832         ;; Copy the headers into the work buffer.
833         (insert-buffer-substring obuf beg end)
834         ;; Fold continuation lines.
835         (goto-char (point-min))
836         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
837           (replace-match " " t t))
838         ;; Allow washing.
839         (run-hooks 'nnmail-split-hook)
840         (if (and (symbolp nnmail-split-methods)
841                  (fboundp nnmail-split-methods))
842             ;; `nnmail-split-methods' is a function, so we just call 
843             ;; this function here and use the result.
844             (setq group-art
845                   (mapcar
846                    (lambda (group) (cons group (funcall func group)))
847                    (condition-case nil
848                        (or (funcall nnmail-split-methods)
849                            '("bogus"))
850                      (error
851                       (message 
852                        "Error in `nnmail-split-methods'; using `bogus' mail group")
853                       (sit-for 1)
854                       '("bogus")))))
855           ;; Go through the split methods to find a match.
856           (while (and methods (or nnmail-crosspost (not group-art)))
857             (goto-char (point-max))
858             (setq method (pop methods))
859             (if (or methods
860                     (not (equal "" (nth 1 method))))
861                 (when (and
862                        (condition-case ()
863                            (if (stringp (nth 1 method))
864                                (re-search-backward (cadr method) nil t)
865                              ;; Function to say whether this is a match.
866                              (funcall (nth 1 method) (car method)))
867                          (error nil))
868                        ;; Don't enter the article into the same 
869                        ;; group twice.
870                        (not (assoc (car method) group-art)))
871                   (push (cons (car method) (funcall func (car method)))
872                         group-art))
873               ;; This is the final group, which is used as a 
874               ;; catch-all.
875               (unless group-art
876                 (setq group-art 
877                       (list (cons (car method)
878                                   (funcall func (car method)))))))))
879         ;; See whether the split methods returned `junk'.
880         (if (equal group-art '(junk))
881             nil
882           (nreverse (delq 'junk group-art)))))))
883
884 (defun nnmail-insert-lines ()
885   "Insert how many lines there are in the body of the mail.
886 Return the number of characters in the body."
887   (let (lines chars)
888     (save-excursion
889       (goto-char (point-min))
890       (when (search-forward "\n\n" nil t)
891         (setq chars (- (point-max) (point)))
892         (setq lines (count-lines (point) (point-max)))
893         (forward-char -1)
894         (save-excursion
895           (when (re-search-backward "^Lines: " nil t)
896             (delete-region (point) (progn (forward-line 1) (point)))))
897         (beginning-of-line)
898         (insert (format "Lines: %d\n" (max lines 0)))
899         chars))))
900
901 (defun nnmail-insert-xref (group-alist)
902   "Insert an Xref line based on the (group . article) alist."
903   (save-excursion
904     (goto-char (point-min))
905     (when (search-forward "\n\n" nil t)
906       (forward-char -1)
907       (when (re-search-backward "^Xref: " nil t)
908         (delete-region (match-beginning 0)
909                        (progn (forward-line 1) (point))))
910       (insert (format "Xref: %s" (system-name)))
911       (while group-alist
912         (insert (format " %s:%d" (caar group-alist) (cdar group-alist)))
913         (setq group-alist (cdr group-alist)))
914       (insert "\n"))))
915
916 ;;; Message washing functions
917
918 (defun nnmail-remove-leading-whitespace ()
919   "Remove excessive whitespace from all headers."
920   (goto-char (point-min))
921   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
922     (replace-match "\\1" t t)))
923
924 (defun nnmail-remove-list-identifiers ()
925   "Remove list identifiers from Subject headers."
926   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
927                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
928     (when regexp
929       (goto-char (point-min))
930       (when (re-search-forward
931              (concat "Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
932              nil t)
933         (delete-region (match-beginning 2) (match-end 0))))))
934
935 (defun nnmail-remove-tabs ()
936   "Translate TAB characters into SPACE characters."
937   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
938
939 ;;; Utility functions
940
941 ;; Written by byer@mv.us.adobe.com (Scott Byer).
942 (defun nnmail-make-complex-temp-name (prefix)
943   (let ((newname (make-temp-name prefix))
944         (newprefix prefix))
945     (while (file-exists-p newname)
946       (setq newprefix (concat newprefix "x"))
947       (setq newname (make-temp-name newprefix)))
948     newname))
949
950 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
951
952 (defun nnmail-split-fancy ()
953   "Fancy splitting method.
954 See the documentation for the variable `nnmail-split-fancy' for documentation."
955   (let ((syntab (syntax-table)))
956     (unwind-protect
957         (progn
958           (set-syntax-table nnmail-split-fancy-syntax-table)
959           (nnmail-split-it nnmail-split-fancy))
960       (set-syntax-table syntab))))
961
962 (defvar nnmail-split-cache nil)
963 ;; Alist of split expressions their equivalent regexps.
964
965 (defun nnmail-split-it (split)
966   ;; Return a list of groups matching SPLIT.
967   (cond
968    ((stringp split)
969     ;; A group.
970     (list split))
971    ((eq split 'junk)
972     ;; Junk this.
973     (list 'junk))
974    ((eq (car split) '&)
975     (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
976    ((eq (car split) '|)
977     (let (done)
978       (while (and (not done) (cdr split))
979         (setq split (cdr split)
980               done (nnmail-split-it (car split))))
981       done))
982    ((assq split nnmail-split-cache)
983     ;; A compiled match expression.
984     (goto-char (point-max))
985     (when (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
986       (nnmail-split-it (nth 2 split))))
987    (t
988     ;; An uncompiled match.
989     (let* ((field (nth 0 split))
990            (value (nth 1 split))
991            (regexp (concat "^\\(" 
992                            (if (symbolp field)
993                                (cdr (assq field nnmail-split-abbrev-alist))
994                              field)
995                            "\\):.*\\<\\("
996                            (if (symbolp value)
997                                (cdr (assq value nnmail-split-abbrev-alist))
998                              value)
999                            "\\)\\>")))
1000       (push (cons split regexp) nnmail-split-cache)
1001       (goto-char (point-max))
1002       (when (re-search-backward regexp nil t)
1003         (nnmail-split-it (nth 2 split)))))))
1004
1005 ;; Get a list of spool files to read.
1006 (defun nnmail-get-spool-files (&optional group)
1007   (if (null nnmail-spool-file)
1008       ;; No spool file whatsoever.
1009       nil
1010     (let* ((procmails 
1011             ;; If procmail is used to get incoming mail, the files
1012             ;; are stored in this directory.
1013             (and (file-exists-p nnmail-procmail-directory)
1014                  (or (eq nnmail-spool-file 'procmail)
1015                      nnmail-use-procmail)
1016                  (directory-files 
1017                   nnmail-procmail-directory 
1018                   t (concat (if group (concat "^" group) "")
1019                             nnmail-procmail-suffix "$"))))
1020            (p procmails)
1021            (crash (when (and (file-exists-p nnmail-crash-box)
1022                              (> (nnheader-file-size
1023                                  (file-truename nnmail-crash-box))
1024                                 0))
1025                     (list nnmail-crash-box))))
1026       ;; Remove any directories that inadvertently match the procmail
1027       ;; suffix, which might happen if the suffix is "". 
1028       (while p
1029         (when (file-directory-p (car p))
1030           (setq procmails (delete (car p) procmails)))
1031         (setq p (cdr p)))
1032       ;; Return the list of spools.
1033       (append 
1034        crash
1035        (cond ((and group
1036                    (or (eq nnmail-spool-file 'procmail)
1037                        nnmail-use-procmail)
1038                    procmails)
1039               procmails)
1040              ((and group
1041                    (eq nnmail-spool-file 'procmail))
1042               nil)
1043              ((listp nnmail-spool-file)
1044               (append nnmail-spool-file procmails))
1045              ((stringp nnmail-spool-file)
1046               (cons nnmail-spool-file procmails))
1047              ((eq nnmail-spool-file 'pop)
1048               (cons (format "po:%s" (user-login-name)) procmails))
1049              (t
1050               procmails))))))
1051
1052 ;; Activate a backend only if it isn't already activated. 
1053 ;; If FORCE, re-read the active file even if the backend is 
1054 ;; already activated.
1055 (defun nnmail-activate (backend &optional force)
1056   (let (file timestamp file-time)
1057     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1058             force
1059             (and (setq file (condition-case ()
1060                                 (symbol-value (intern (format "%s-active-file" 
1061                                                               backend)))
1062                               (error nil)))
1063                  (setq file-time (nth 5 (file-attributes file)))
1064                  (or (not
1065                       (setq timestamp
1066                             (condition-case ()
1067                                 (symbol-value (intern
1068                                                (format "%s-active-timestamp" 
1069                                                        backend)))
1070                               (error 'none))))
1071                      (not (consp timestamp))
1072                      (equal timestamp '(0 0))
1073                      (> (nth 0 file-time) (nth 0 timestamp))
1074                      (and (= (nth 0 file-time) (nth 0 timestamp))
1075                           (> (nth 1 file-time) (nth 1 timestamp))))))
1076         (save-excursion
1077           (or (eq timestamp 'none)
1078               (set (intern (format "%s-active-timestamp" backend)) 
1079 ;;; dmoore@ucsd.edu 25.10.96
1080 ;;; it's not always the case that current-time
1081 ;;; does correspond to changes in the file's time.  So just compare
1082 ;;; the file's new time against its own previous time.
1083 ;;;                (current-time)
1084                    file-time
1085                    ))
1086           (funcall (intern (format "%s-request-list" backend)))
1087 ;;; dmoore@ucsd.edu 25.10.96
1088 ;;; BACKEND-request-list already does this itself!
1089 ;;;       (set (intern (format "%s-group-alist" backend)) 
1090 ;;;            (nnmail-get-active))
1091           ))
1092     t))
1093
1094 (defun nnmail-message-id ()
1095   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1096
1097 ;;;
1098 ;;; nnmail duplicate handling
1099 ;;;
1100
1101 (defvar nnmail-cache-buffer nil)
1102
1103 (defun nnmail-cache-open ()
1104   (if (or (not nnmail-treat-duplicates)
1105           (and nnmail-cache-buffer
1106                (buffer-name nnmail-cache-buffer)))
1107       ()                                ; The buffer is open.
1108     (save-excursion
1109       (set-buffer 
1110        (setq nnmail-cache-buffer 
1111              (get-buffer-create " *nnmail message-id cache*")))
1112       (buffer-disable-undo (current-buffer))
1113       (when (file-exists-p nnmail-message-id-cache-file)
1114         (insert-file-contents nnmail-message-id-cache-file))
1115       (set-buffer-modified-p nil)
1116       (current-buffer))))
1117
1118 (defun nnmail-cache-close ()
1119   (when (and nnmail-cache-buffer
1120              nnmail-treat-duplicates
1121              (buffer-name nnmail-cache-buffer)
1122              (buffer-modified-p nnmail-cache-buffer))
1123     (save-excursion
1124       (set-buffer nnmail-cache-buffer)
1125       ;; Weed out the excess number of Message-IDs.
1126       (goto-char (point-max))
1127       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1128         (progn
1129           (beginning-of-line)
1130           (delete-region (point-min) (point))))
1131       ;; Save the buffer.
1132       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1133           (make-directory (file-name-directory nnmail-message-id-cache-file)
1134                           t))
1135       (nnmail-write-region (point-min) (point-max)
1136                            nnmail-message-id-cache-file nil 'silent)
1137       (set-buffer-modified-p nil)
1138       (setq nnmail-cache-buffer nil)
1139       ;;(kill-buffer (current-buffer))
1140       )))
1141
1142 (defun nnmail-cache-insert (id)
1143   (when nnmail-treat-duplicates
1144     (save-excursion
1145       (set-buffer nnmail-cache-buffer)
1146       (goto-char (point-max))
1147       (insert id "\n"))))
1148
1149 (defun nnmail-cache-id-exists-p (id)
1150   (when nnmail-treat-duplicates
1151     (save-excursion
1152       (set-buffer nnmail-cache-buffer)
1153       (goto-char (point-max))
1154       (search-backward id nil t))))
1155
1156 (defun nnmail-check-duplication (message-id func artnum-func)
1157   (run-hooks 'nnmail-prepare-incoming-message-hook)
1158   ;; If this is a duplicate message, then we do not save it.
1159   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1160          (case-fold-search t)
1161          (action (when duplication
1162                    (cond
1163                     ((memq nnmail-treat-duplicates '(warn delete))
1164                      nnmail-treat-duplicates)
1165                     ((nnheader-functionp nnmail-treat-duplicates)
1166                      (funcall nnmail-treat-duplicates message-id))
1167                     (t
1168                      nnmail-treat-duplicates))))
1169          group-art)
1170     ;; Let the backend save the article (or not).
1171     (cond
1172      ((not duplication)
1173       (nnmail-cache-insert message-id)
1174       (funcall func (setq group-art
1175                           (nreverse (nnmail-article-group artnum-func)))))
1176      ((eq action 'delete)
1177       (setq group-art nil))
1178      ((eq action 'warn)
1179       ;; We insert a warning.
1180       (let ((case-fold-search t)
1181             (newid (nnmail-message-id)))
1182         (goto-char (point-min))
1183         (when (re-search-forward "^message-id:" nil t)
1184           (beginning-of-line)
1185           (insert "Original-"))
1186         (beginning-of-line)
1187         (insert 
1188          "Message-ID: " newid "\n"
1189          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1190         (nnmail-cache-insert newid)
1191         (funcall func (setq group-art
1192                             (nreverse (nnmail-article-group artnum-func))))))
1193      (t
1194       (funcall func (setq group-art
1195                           (nreverse (nnmail-article-group artnum-func))))))
1196     ;; Add the group-art list to the history list.
1197     (if group-art
1198         (push group-art nnmail-split-history)
1199       (delete-region (point-min) (point-max)))))
1200
1201 ;;; Get new mail.
1202
1203 (defun nnmail-get-value (&rest args)
1204   (let ((sym (intern (apply 'format args))))
1205     (when (boundp sym)
1206       (symbol-value sym))))
1207
1208 (defun nnmail-get-new-mail (method exit-func temp
1209                                    &optional group spool-func)
1210   "Read new incoming mail."
1211   ;; Nix out the previous split history.
1212   (unless group
1213     (setq nnmail-split-history nil))
1214   (let* ((spools (nnmail-get-spool-files group))
1215          (group-in group)
1216          incoming incomings spool)
1217     (when (and (nnmail-get-value "%s-get-new-mail" method)
1218                nnmail-spool-file)
1219       ;; We first activate all the groups.
1220       (nnmail-activate method)
1221       ;; Allow the user to hook.
1222       (run-hooks 'nnmail-pre-get-new-mail-hook)
1223       ;; Open the message-id cache.
1224       (nnmail-cache-open)
1225       ;; The we go through all the existing spool files and split the
1226       ;; mail from each.
1227       (while spools
1228         (setq spool (pop spools))
1229         ;; We read each spool file if either the spool is a POP-mail
1230         ;; spool, or the file exists.  We can't check for the
1231         ;; existence of POPped mail.
1232         (when (or (string-match "^po:" spool)
1233                   (and (file-exists-p spool)
1234                        (> (nnheader-file-size (file-truename spool)) 0)))
1235           (nnheader-message 3 "%s: Reading incoming mail..." method)
1236           (when (and (nnmail-move-inbox spool)
1237                      (file-exists-p nnmail-crash-box))
1238             ;; There is new mail.  We first find out if all this mail
1239             ;; is supposed to go to some specific group.
1240             (setq group (nnmail-get-split-group spool group-in))
1241             ;; We split the mail
1242             (nnmail-split-incoming 
1243              nnmail-crash-box (intern (format "%s-save-mail" method))
1244              spool-func group (intern (format "%s-active-number" method)))
1245             ;; Check whether the inbox is to be moved to the special tmp dir. 
1246             (setq incoming
1247                   (nnmail-make-complex-temp-name 
1248                    (expand-file-name 
1249                     (if nnmail-tmp-directory
1250                         (concat 
1251                          (file-name-as-directory nnmail-tmp-directory)
1252                          (file-name-nondirectory (concat temp "Incoming")))
1253                       (concat temp "Incoming")))))
1254             (rename-file nnmail-crash-box incoming t)
1255             (push incoming incomings))))
1256       ;; If we did indeed read any incoming spools, we save all info. 
1257       (when incomings
1258         (nnmail-save-active 
1259          (nnmail-get-value "%s-group-alist" method)
1260          (nnmail-get-value "%s-active-file" method))
1261         (when exit-func
1262           (funcall exit-func))
1263         (run-hooks 'nnmail-read-incoming-hook)
1264         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1265       ;; Close the message-id cache.
1266       (nnmail-cache-close)
1267       ;; Allow the user to hook.
1268       (run-hooks 'nnmail-post-get-new-mail-hook)
1269       ;; Delete all the temporary files.
1270       (while incomings
1271         (setq incoming (pop incomings))
1272         (and nnmail-delete-incoming
1273              (file-exists-p incoming)
1274              (file-writable-p incoming)
1275              (delete-file incoming))))))
1276
1277 (defun nnmail-expired-article-p (group time force &optional inhibit)
1278   "Say whether an article that is TIME old in GROUP should be expired."
1279   (if force
1280       t
1281     (let ((days (or (and nnmail-expiry-wait-function
1282                          (funcall nnmail-expiry-wait-function group))
1283                     nnmail-expiry-wait)))
1284       (cond ((or (eq days 'never)
1285                  (and (not force)
1286                       inhibit))
1287              ;; This isn't an expirable group.
1288              nil)
1289             ((eq days 'immediate)
1290              ;; We expire all articles on sight.
1291              t)
1292             ((equal time '(0 0))
1293              ;; This is an ange-ftp group, and we don't have any dates.
1294              nil)
1295             ((numberp days)
1296              (setq days (nnmail-days-to-time days))
1297              ;; Compare the time with the current time.
1298              (nnmail-time-less days (nnmail-time-since time)))))))
1299
1300 (defvar nnmail-read-passwd nil)
1301 (defun nnmail-read-passwd (prompt)
1302   (unless nnmail-read-passwd
1303     (if (load "passwd" t)
1304         (setq nnmail-read-passwd 'read-passwd)
1305       (autoload 'ange-ftp-read-passwd "ange-ftp")
1306       (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1307   (funcall nnmail-read-passwd prompt))
1308
1309 (defun nnmail-check-syntax ()
1310   "Check (and modify) the syntax of the message in the current buffer."
1311   (save-restriction
1312     (message-narrow-to-head)
1313     (let ((case-fold-search t))
1314       (unless (re-search-forward "^Message-ID:" nil t)
1315         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1316
1317 (defun nnmail-write-region (start end filename &optional append visit lockname)
1318   "Do a `write-region', and then set the file modes."
1319   (write-region start end filename append visit lockname)
1320   (set-file-modes filename nnmail-default-file-modes))
1321
1322 ;;;
1323 ;;; Status functions
1324 ;;;
1325
1326 (defun nnmail-replace-status (name value)
1327   "Make status NAME and VALUE part of the current status line."
1328   (save-restriction
1329     (message-narrow-to-head)
1330     (let ((status (nnmail-decode-status)))
1331       (setq status (delq (member name status) status))
1332       (when value
1333         (push (cons name value) status))
1334       (message-remove-header "status")
1335       (goto-char (point-max))
1336       (insert "Status: " (nnmail-encode-status status) "\n"))))
1337
1338 (defun nnmail-decode-status ()
1339   "Return a status-value alist from STATUS."
1340   (goto-char (point-min))
1341   (when (re-search-forward "^Status: " nil t)
1342     (let (name value status)
1343       (save-restriction
1344         ;; Narrow to the status.
1345         (narrow-to-region
1346          (point)
1347          (if (re-search-forward "^[^ \t]" nil t)
1348              (1- (point))
1349            (point-max)))
1350         ;; Go through all elements and add them to the list.
1351         (goto-char (point-min))
1352         (while (re-search-forward "[^ \t=]+" nil t)
1353           (setq name (match-string 0))
1354           (if (not (= (following-char) ?=))
1355               ;; Implied "yes".
1356               (setq value "yes")
1357             (forward-char 1)
1358             (if (not (= (following-char) ?\"))
1359                 (if (not (looking-at "[^ \t]"))
1360                     ;; Implied "no".
1361                     (setq value "no")
1362                   ;; Unquoted value.
1363                   (setq value (match-string 0))
1364                   (goto-char (match-end 0)))
1365               ;; Quoted value.
1366               (setq value (read (current-buffer)))))
1367           (push (cons name value) status)))
1368       status)))
1369
1370 (defun nnmail-encode-status (status)
1371   "Return a status string from STATUS."
1372   (mapconcat
1373    (lambda (elem)
1374      (concat
1375       (car elem) "="
1376       (if (string-match "[ \t]" (cdr elem))
1377           (prin1-to-string (cdr elem))
1378         (cdr elem))))
1379    status " "))
1380
1381 (defun nnmail-split-history ()
1382   "Generate an overview of where the last mail split put articles."
1383   (interactive)
1384   (unless nnmail-split-history
1385     (error "No current split history"))
1386   (pop-to-buffer "*nnmail split history*")
1387   (buffer-disable-undo (current-buffer))
1388   (erase-buffer)
1389   (let ((history nnmail-split-history)
1390         elem ga)
1391     (while (setq elem (pop history))
1392       (insert (mapconcat (lambda (ga)
1393                            (concat (car ga) ":" (int-to-string (cdr ga))))
1394                          elem
1395                          ", ")
1396               "\n"))
1397     (goto-char (point-min))))
1398
1399 (defun nnmail-new-mail-p (group)
1400   "Say whether GROUP has new mail."
1401   (let ((his nnmail-split-history)
1402         found)
1403     (while his
1404       (when (assoc group (pop his))
1405         (setq found t
1406               his nil)))
1407     found))
1408         
1409 (run-hooks 'nnmail-load-hook)
1410             
1411 (provide 'nnmail)
1412
1413 ;;; nnmail.el ends here