*** 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             (if (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 deamon 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 (if (< (nth 1 current) (nth 1 time)) (expt 2 16))))
382     (list (- (+ (car current) (if rest -1 0)) (car time))
383           (- (+ (or rest 0) (nth 1 current)) (nth 1 time)))))
384
385 ;; Function rewritten from rmail.el.
386 (defun nnmail-move-inbox (inbox)
387   "Move INBOX to `nnmail-crash-box'."
388   (if (not (file-writable-p nnmail-crash-box))
389       (gnus-error 1 "Can't write to crash box %s.  Not moving mail."
390                   nnmail-crash-box)
391     (let ((inbox (file-truename (expand-file-name inbox)))
392           (tofile (file-truename (expand-file-name nnmail-crash-box)))
393           movemail popmail errors)
394       ;; If getting from mail spool directory,
395       ;; use movemail to move rather than just renaming,
396       ;; so as to interlock with the mailer.
397       (unless (setq popmail (string-match "^po:" (file-name-nondirectory inbox)))
398         (setq movemail t))
399       (when popmail 
400         (setq inbox (file-name-nondirectory inbox)))
401       (when (and movemail
402                  ;; On some systems, /usr/spool/mail/foo is a directory
403                  ;; and the actual inbox is /usr/spool/mail/foo/foo.
404                  (file-directory-p inbox))
405         (setq inbox (expand-file-name (user-login-name) inbox)))
406       (if (member inbox nnmail-moved-inboxes)
407           nil
408         (if popmail
409             (progn
410               (setq nnmail-internal-password nnmail-pop-password)
411               (when (and nnmail-pop-password-required (not nnmail-pop-password))
412                 (setq nnmail-internal-password
413                       (nnmail-read-passwd
414                        (format "Password for %s: "
415                                (substring inbox (+ popmail 3))))))
416               (message "Getting mail from post office ..."))
417           (when (or (and (file-exists-p tofile)
418                          (/= 0 (nnheader-file-size tofile)))
419                     (and (file-exists-p inbox)
420                          (/= 0 (nnheader-file-size inbox))))
421             (message "Getting mail from %s..." inbox)))
422         ;; Set TOFILE if have not already done so, and
423         ;; rename or copy the file INBOX to TOFILE if and as appropriate.
424         (cond 
425          ((file-exists-p tofile)
426           ;; The crash box exists already.
427           t)
428          ((and (not popmail)
429                (not (file-exists-p inbox)))
430           ;; There is no inbox.
431           (setq tofile nil))
432          ((and (not movemail) (not popmail))
433           ;; Try copying.  If that fails (perhaps no space),
434           ;; rename instead.
435           (condition-case nil
436               (copy-file inbox tofile nil)
437             (error
438              ;; Third arg is t so we can replace existing file TOFILE.
439              (rename-file inbox tofile t)))
440           (push inbox nnmail-moved-inboxes)
441           ;; Make the real inbox file empty.
442           ;; Leaving it deleted could cause lossage
443           ;; because mailers often won't create the file.
444           (condition-case ()
445               (write-region (point) (point) inbox)
446             (file-error nil)))
447          (t
448           ;; Use movemail.
449           (unwind-protect
450               (save-excursion
451                 (setq errors (generate-new-buffer " *nnmail loss*"))
452                 (buffer-disable-undo errors)
453                 (let ((default-directory "/"))
454                   (if (nnheader-functionp nnmail-movemail-program)
455                       (funcall nnmail-movemail-program inbox tofile)
456                     (apply 
457                      'call-process
458                      (append
459                       (list
460                        (expand-file-name nnmail-movemail-program exec-directory)
461                        nil errors nil inbox tofile)
462                       (when nnmail-internal-password
463                         (list nnmail-internal-password))))))
464                 (if (not (buffer-modified-p errors))
465                     ;; No output => movemail won
466                     (progn
467                       (or popmail
468                           (set-file-modes tofile nnmail-default-file-modes))
469                       (push inbox nnmail-moved-inboxes))
470                   (set-buffer errors)
471                   ;; There may be a warning about older revisions.  We
472                   ;; ignore those.
473                   (goto-char (point-min))
474                   (if (search-forward "older revision" nil t)
475                       (progn
476                         (or popmail
477                             (set-file-modes tofile nnmail-default-file-modes))
478                         (push inbox nnmail-moved-inboxes))
479                     ;; Probably a real error.
480                     (subst-char-in-region (point-min) (point-max) ?\n ?\  )
481                     (goto-char (point-max))
482                     (skip-chars-backward " \t")
483                     (delete-region (point) (point-max))
484                     (goto-char (point-min))
485                     (when (looking-at "movemail: ")
486                       (delete-region (point-min) (match-end 0)))
487                     (unless (yes-or-no-p
488                              (format "movemail: %s.  Continue? "
489                                      (buffer-string)))
490                       (error "%s" (buffer-string)))
491                     (setq tofile nil)))))))
492         (and errors
493              (buffer-name errors)
494              (kill-buffer errors))
495         tofile))))
496
497 (defun nnmail-get-active ()
498   "Returns an assoc of group names and active ranges.
499 nn*-request-list should have been called before calling this function."
500   (let (group-assoc)
501     ;; Go through all groups from the active list.
502     (save-excursion
503       (set-buffer nntp-server-buffer)
504       (goto-char (point-min))
505       (while (re-search-forward 
506               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
507         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
508         (push (list (match-string 1)
509                     (cons (string-to-int (match-string 3))
510                           (string-to-int (match-string 2))))
511               group-assoc)))
512     group-assoc))
513
514 (defun nnmail-save-active (group-assoc file-name)
515   "Save GROUP-ASSOC in ACTIVE-FILE."
516   (when file-name
517     (let (group)
518       (save-excursion
519         (set-buffer (get-buffer-create " *nnmail active*"))
520         (buffer-disable-undo (current-buffer))
521         (erase-buffer)
522         (while group-assoc
523           (setq group (pop group-assoc))
524           (insert (format "%s %d %d y\n" (car group) (cdadr group) 
525                           (caadr group))))
526         (unless (file-exists-p (file-name-directory file-name))
527           (make-directory (file-name-directory file-name) t))
528         (nnmail-write-region
529          1 (point-max) (expand-file-name file-name) nil 'nomesg)
530         (kill-buffer (current-buffer))))))
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       (if exit-func (funcall exit-func))
809       (kill-buffer (current-buffer)))))
810
811 ;; Mail crossposts suggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
812 (defun nnmail-article-group (func)
813   "Look at the headers and return an alist of groups that match.
814 FUNC will be called with the group name to determine the article number."
815   (let ((methods nnmail-split-methods)
816         (obuf (current-buffer))
817         (beg (point-min))
818         end group-art method)
819     (if (and (sequencep methods) (= (length methods) 1))
820         ;; If there is only just one group to put everything in, we
821         ;; just return a list with just this one method in.
822         (setq group-art
823               (list (cons (caar methods) (funcall func (caar methods)))))
824       ;; We do actual comparison.
825       (save-excursion
826         ;; Find headers.
827         (goto-char beg)
828         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
829         (set-buffer nntp-server-buffer)
830         (erase-buffer)
831         ;; Copy the headers into the work buffer.
832         (insert-buffer-substring obuf beg end)
833         ;; Fold continuation lines.
834         (goto-char (point-min))
835         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
836           (replace-match " " t t))
837         ;; Allow washing.
838         (run-hooks 'nnmail-split-hook)
839         (if (and (symbolp nnmail-split-methods)
840                  (fboundp nnmail-split-methods))
841             ;; `nnmail-split-methods' is a function, so we just call 
842             ;; this function here and use the result.
843             (setq group-art
844                   (mapcar
845                    (lambda (group) (cons group (funcall func group)))
846                    (condition-case nil
847                        (or (funcall nnmail-split-methods)
848                            '("bogus"))
849                      (error
850                       (message 
851                        "Error in `nnmail-split-methods'; using `bogus' mail group")
852                       (sit-for 1)
853                       '("bogus")))))
854           ;; Go through the split methods to find a match.
855           (while (and methods (or nnmail-crosspost (not group-art)))
856             (goto-char (point-max))
857             (setq method (pop methods))
858             (if (or methods
859                     (not (equal "" (nth 1 method))))
860                 (when (and
861                        (condition-case () 
862                            (if (stringp (nth 1 method))
863                                (re-search-backward (cadr method) nil t)
864                              ;; Function to say whether this is a match.
865                              (funcall (nth 1 method) (car method)))
866                          (error nil))
867                        ;; Don't enter the article into the same 
868                        ;; group twice.
869                        (not (assoc (car method) group-art)))
870                   (push (cons (car method) (funcall func (car method))) 
871                         group-art))
872               ;; This is the final group, which is used as a 
873               ;; catch-all.
874               (unless group-art
875                 (setq group-art 
876                       (list (cons (car method) 
877                                   (funcall func (car method)))))))))
878         ;; See whether the split methods returned `junk'.
879         (if (equal group-art '(junk))
880             nil
881           (nreverse (delq 'junk group-art)))))))
882
883 (defun nnmail-insert-lines ()
884   "Insert how many lines there are in the body of the mail.
885 Return the number of characters in the body."
886   (let (lines chars)
887     (save-excursion
888       (goto-char (point-min))
889       (when (search-forward "\n\n" nil t) 
890         (setq chars (- (point-max) (point)))
891         (setq lines (count-lines (point) (point-max)))
892         (forward-char -1)
893         (save-excursion
894           (when (re-search-backward "^Lines: " nil t)
895             (delete-region (point) (progn (forward-line 1) (point)))))
896         (beginning-of-line)
897         (insert (format "Lines: %d\n" (max lines 0)))
898         chars))))
899
900 (defun nnmail-insert-xref (group-alist)
901   "Insert an Xref line based on the (group . article) alist."
902   (save-excursion
903     (goto-char (point-min))
904     (when (search-forward "\n\n" nil t) 
905       (forward-char -1)
906       (when (re-search-backward "^Xref: " nil t)
907         (delete-region (match-beginning 0) 
908                        (progn (forward-line 1) (point))))
909       (insert (format "Xref: %s" (system-name)))
910       (while group-alist
911         (insert (format " %s:%d" (caar group-alist) (cdar group-alist)))
912         (setq group-alist (cdr group-alist)))
913       (insert "\n"))))
914
915 ;;; Message washing functions
916
917 (defun nnmail-remove-leading-whitespace ()
918   "Remove excessive whitespace from all headers."
919   (goto-char (point-min))
920   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
921     (replace-match "\\1" t t)))
922
923 (defun nnmail-remove-list-identifiers ()
924   "Remove list identifiers from Subject headers."
925   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
926                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
927     (when regexp
928       (goto-char (point-min))
929       (when (re-search-forward
930              (concat "Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
931              nil t)
932         (delete-region (match-beginning 2) (match-end 0))))))
933
934 (defun nnmail-remove-tabs ()
935   "Translate TAB characters into SPACE characters."
936   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
937
938 ;;; Utility functions
939
940 ;; Written by byer@mv.us.adobe.com (Scott Byer).
941 (defun nnmail-make-complex-temp-name (prefix)
942   (let ((newname (make-temp-name prefix))
943         (newprefix prefix))
944     (while (file-exists-p newname)
945       (setq newprefix (concat newprefix "x"))
946       (setq newname (make-temp-name newprefix)))
947     newname))
948
949 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
950
951 (defun nnmail-split-fancy ()
952   "Fancy splitting method.
953 See the documentation for the variable `nnmail-split-fancy' for documentation."
954   (let ((syntab (syntax-table)))
955     (unwind-protect
956         (progn
957           (set-syntax-table nnmail-split-fancy-syntax-table)
958           (nnmail-split-it nnmail-split-fancy))
959       (set-syntax-table syntab))))
960
961 (defvar nnmail-split-cache nil)
962 ;; Alist of split expressions their equivalent regexps.
963
964 (defun nnmail-split-it (split)
965   ;; Return a list of groups matching SPLIT.
966   (cond
967    ((stringp split)
968     ;; A group.
969     (list split))
970    ((eq split 'junk)
971     ;; Junk this.
972     (list 'junk))
973    ((eq (car split) '&)
974     (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
975    ((eq (car split) '|)
976     (let (done)
977       (while (and (not done) (cdr split))
978         (setq split (cdr split)
979               done (nnmail-split-it (car split))))
980       done))
981    ((assq split nnmail-split-cache)
982     ;; A compiled match expression.
983     (goto-char (point-max))
984     (if (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
985         (nnmail-split-it (nth 2 split))))
986    (t
987     ;; An uncompiled match.
988     (let* ((field (nth 0 split))
989            (value (nth 1 split))
990            (regexp (concat "^\\(" 
991                            (if (symbolp field)
992                                (cdr (assq field nnmail-split-abbrev-alist))
993                              field)
994                            "\\):.*\\<\\("
995                            (if (symbolp value)
996                                (cdr (assq value nnmail-split-abbrev-alist))
997                              value)
998                            "\\)\\>")))
999       (setq nnmail-split-cache 
1000             (cons (cons split regexp) nnmail-split-cache))
1001       (goto-char (point-max))
1002       (if (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)) 0))
1024                     (list nnmail-crash-box))))
1025       ;; Remove any directories that inadvertantly match the procmail
1026       ;; suffix, which might happen if the suffix is "". 
1027       (while p
1028         (when (file-directory-p (car p))
1029           (setq procmails (delete (car p) procmails)))
1030         (setq p (cdr p)))
1031       ;; Return the list of spools.
1032       (append 
1033        crash
1034        (cond ((and group
1035                    (or (eq nnmail-spool-file 'procmail)
1036                        nnmail-use-procmail)
1037                    procmails)
1038               procmails)
1039              ((and group
1040                    (eq nnmail-spool-file 'procmail))
1041               nil)
1042              ((listp nnmail-spool-file)
1043               (append nnmail-spool-file procmails))
1044              ((stringp nnmail-spool-file)
1045               (cons nnmail-spool-file procmails))
1046              ((eq nnmail-spool-file 'pop)
1047               (cons (format "po:%s" (user-login-name)) procmails))
1048              (t
1049               procmails))))))
1050
1051 ;; Activate a backend only if it isn't already activated. 
1052 ;; If FORCE, re-read the active file even if the backend is 
1053 ;; already activated.
1054 (defun nnmail-activate (backend &optional force)
1055   (let (file timestamp file-time)
1056     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1057             force
1058             (and (setq file (condition-case ()
1059                                 (symbol-value (intern (format "%s-active-file" 
1060                                                               backend)))
1061                               (error nil)))
1062                  (setq file-time (nth 5 (file-attributes file)))
1063                  (or (not
1064                       (setq timestamp
1065                             (condition-case ()
1066                                 (symbol-value (intern
1067                                                (format "%s-active-timestamp" 
1068                                                        backend)))
1069                               (error 'none))))
1070                      (not (consp timestamp))
1071                      (equal timestamp '(0 0))
1072                      (> (nth 0 file-time) (nth 0 timestamp))
1073                      (and (= (nth 0 file-time) (nth 0 timestamp))
1074                           (> (nth 1 file-time) (nth 1 timestamp))))))
1075         (save-excursion
1076           (or (eq timestamp 'none)
1077               (set (intern (format "%s-active-timestamp" backend)) 
1078                    (current-time)))
1079           (funcall (intern (format "%s-request-list" backend)))
1080           (set (intern (format "%s-group-alist" backend)) 
1081                (nnmail-get-active))))
1082     t))
1083
1084 (defun nnmail-message-id ()
1085   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1086
1087 ;;;
1088 ;;; nnmail duplicate handling
1089 ;;;
1090
1091 (defvar nnmail-cache-buffer nil)
1092
1093 (defun nnmail-cache-open ()
1094   (if (or (not nnmail-treat-duplicates)
1095           (and nnmail-cache-buffer
1096                (buffer-name nnmail-cache-buffer)))
1097       ()                                ; The buffer is open.
1098     (save-excursion
1099       (set-buffer 
1100        (setq nnmail-cache-buffer 
1101              (get-buffer-create " *nnmail message-id cache*")))
1102       (buffer-disable-undo (current-buffer))
1103       (and (file-exists-p nnmail-message-id-cache-file)
1104            (insert-file-contents nnmail-message-id-cache-file))
1105       (set-buffer-modified-p nil)
1106       (current-buffer))))
1107
1108 (defun nnmail-cache-close ()
1109   (when (and nnmail-cache-buffer
1110              nnmail-treat-duplicates
1111              (buffer-name nnmail-cache-buffer)
1112              (buffer-modified-p nnmail-cache-buffer))
1113     (save-excursion
1114       (set-buffer nnmail-cache-buffer)
1115       ;; Weed out the excess number of Message-IDs.
1116       (goto-char (point-max))
1117       (and (search-backward "\n" nil t nnmail-message-id-cache-length)
1118            (progn
1119              (beginning-of-line)
1120              (delete-region (point-min) (point))))
1121       ;; Save the buffer.
1122       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1123           (make-directory (file-name-directory nnmail-message-id-cache-file)
1124                           t))
1125       (nnmail-write-region (point-min) (point-max)
1126                            nnmail-message-id-cache-file nil 'silent)
1127       (set-buffer-modified-p nil)
1128       (setq nnmail-cache-buffer nil)
1129       ;;(kill-buffer (current-buffer))
1130       )))
1131
1132 (defun nnmail-cache-insert (id)
1133   (when nnmail-treat-duplicates
1134     (save-excursion
1135       (set-buffer nnmail-cache-buffer)
1136       (goto-char (point-max))
1137       (insert id "\n"))))
1138
1139 (defun nnmail-cache-id-exists-p (id)
1140   (when nnmail-treat-duplicates
1141     (save-excursion
1142       (set-buffer nnmail-cache-buffer)
1143       (goto-char (point-max))
1144       (search-backward id nil t))))
1145
1146 (defun nnmail-check-duplication (message-id func artnum-func)
1147   (run-hooks 'nnmail-prepare-incoming-message-hook)
1148   ;; If this is a duplicate message, then we do not save it.
1149   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1150          (action (when duplication
1151                    (cond
1152                     ((memq nnmail-treat-duplicates '(warn delete))
1153                      nnmail-treat-duplicates)
1154                     ((nnheader-functionp nnmail-treat-duplicates)
1155                      (funcall nnmail-treat-duplicates message-id))
1156                     (t
1157                      nnmail-treat-duplicates))))
1158          (group-art (nreverse (nnmail-article-group artnum-func))))
1159     ;; Let the backend save the article (or not).
1160     (cond
1161      ((null group-art)
1162       (delete-region (point-min) (point-max)))
1163      ((not duplication)
1164       (nnmail-cache-insert message-id)
1165       (funcall func group-art))
1166      ((eq action 'delete)
1167       (delete-region (point-min) (point-max))
1168       (setq group-art nil))
1169      ((eq action 'warn)
1170       ;; We insert a warning.
1171       (let ((case-fold-search t)
1172             (newid (nnmail-message-id)))
1173         (goto-char (point-min))
1174         (when (re-search-forward "^message-id:" nil t)
1175           (beginning-of-line)
1176           (insert "Original-"))
1177         (beginning-of-line)
1178         (insert 
1179          "Message-ID: " newid "\n"
1180          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1181         (nnmail-cache-insert newid)
1182         (funcall func group-art)))
1183      (t
1184       (funcall func group-art)))
1185     ;; Add the group-art list to the history list.
1186     (push group-art nnmail-split-history)))
1187
1188 ;;; Get new mail.
1189
1190 (defun nnmail-get-value (&rest args)
1191   (let ((sym (intern (apply 'format args))))
1192     (when (boundp sym)
1193       (symbol-value sym))))
1194
1195 (defun nnmail-get-new-mail (method exit-func temp
1196                                    &optional group spool-func)
1197   "Read new incoming mail."
1198   ;; Nix out the previous split history.
1199   (setq nnmail-split-history nil)
1200   (let* ((spools (nnmail-get-spool-files group))
1201          (group-in group)
1202          incoming incomings spool)
1203     (when (and (nnmail-get-value "%s-get-new-mail" method)
1204                nnmail-spool-file)
1205       ;; We first activate all the groups.
1206       (nnmail-activate method)
1207       ;; Allow the user to hook.
1208       (run-hooks 'nnmail-pre-get-new-mail-hook)
1209       ;; Open the message-id cache.
1210       (nnmail-cache-open)
1211       ;; The we go through all the existing spool files and split the
1212       ;; mail from each.
1213       (while spools
1214         (setq spool (pop spools))
1215         ;; We read each spool file if either the spool is a POP-mail
1216         ;; spool, or the file exists.  We can't check for the
1217         ;; existance of POPped mail.
1218         (when (or (string-match "^po:" spool)
1219                   (and (file-exists-p spool)
1220                        (> (nnheader-file-size (file-truename spool)) 0)))
1221           (nnheader-message 3 "%s: Reading incoming mail..." method)
1222           (when (and (nnmail-move-inbox spool)
1223                      (file-exists-p nnmail-crash-box))
1224             ;; There is new mail.  We first find out if all this mail
1225             ;; is supposed to go to some specific group.
1226             (setq group (nnmail-get-split-group spool group-in))
1227             ;; We split the mail
1228             (nnmail-split-incoming 
1229              nnmail-crash-box (intern (format "%s-save-mail" method)) 
1230              spool-func group (intern (format "%s-active-number" method)))
1231             ;; Check whether the inbox is to be moved to the special tmp dir. 
1232             (setq incoming
1233                   (nnmail-make-complex-temp-name 
1234                    (expand-file-name 
1235                     (if nnmail-tmp-directory
1236                         (concat 
1237                          (file-name-as-directory nnmail-tmp-directory)
1238                          (file-name-nondirectory (concat temp "Incoming")))
1239                       (concat temp "Incoming")))))
1240             (rename-file nnmail-crash-box incoming t)
1241             (push incoming incomings))))
1242       ;; If we did indeed read any incoming spools, we save all info. 
1243       (when incomings
1244         (nnmail-save-active 
1245          (nnmail-get-value "%s-group-alist" method)
1246          (nnmail-get-value "%s-active-file" method))
1247         (when exit-func
1248           (funcall exit-func))
1249         (run-hooks 'nnmail-read-incoming-hook)
1250         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1251       ;; Close the message-id cache.
1252       (nnmail-cache-close)
1253       ;; Allow the user to hook.
1254       (run-hooks 'nnmail-post-get-new-mail-hook)
1255       ;; Delete all the temporary files.
1256       (while incomings
1257         (setq incoming (pop incomings))
1258         (and nnmail-delete-incoming
1259              (file-exists-p incoming)
1260              (file-writable-p incoming)
1261              (delete-file incoming))))))
1262
1263 (defun nnmail-expired-article-p (group time force &optional inhibit)
1264   "Say whether an article that is TIME old in GROUP should be expired."
1265   (if force
1266       t
1267     (let ((days (or (and nnmail-expiry-wait-function
1268                          (funcall nnmail-expiry-wait-function group))
1269                     nnmail-expiry-wait)))
1270       (cond ((or (eq days 'never)
1271                  (and (not force)
1272                       inhibit))
1273              ;; This isn't an expirable group.
1274              nil)
1275             ((eq days 'immediate)
1276              ;; We expire all articles on sight.
1277              t)
1278             ((equal time '(0 0))
1279              ;; This is an ange-ftp group, and we don't have any dates.
1280              nil)
1281             ((numberp days)
1282              (setq days (nnmail-days-to-time days))
1283              ;; Compare the time with the current time.
1284              (nnmail-time-less days (nnmail-time-since time)))))))
1285
1286 (defvar nnmail-read-passwd nil)
1287 (defun nnmail-read-passwd (prompt)
1288   (unless nnmail-read-passwd
1289     (if (load "passwd" t)
1290         (setq nnmail-read-passwd 'read-passwd)
1291       (autoload 'ange-ftp-read-passwd "ange-ftp")
1292       (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1293   (funcall nnmail-read-passwd prompt))
1294
1295 (defun nnmail-check-syntax ()
1296   "Check (and modify) the syntax of the message in the current buffer."
1297   (save-restriction
1298     (message-narrow-to-head)
1299     (let ((case-fold-search t))
1300       (unless (re-search-forward "^Message-Id:" nil t)
1301         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1302
1303 (defun nnmail-write-region (start end filename &optional append visit lockname)
1304   "Do a `write-region', and then set the file modes."
1305   (write-region start end filename append visit lockname)
1306   (set-file-modes filename nnmail-default-file-modes))
1307
1308 ;;;
1309 ;;; Status functions
1310 ;;;
1311
1312 (defun nnmail-replace-status (name value)
1313   "Make status NAME and VALUE part of the current status line."
1314   (save-restriction
1315     (message-narrow-to-head)
1316     (let ((status (nnmail-decode-status)))
1317       (setq status (delq (member name status) status))
1318       (when value
1319         (push (cons name value) status))
1320       (message-remove-header "status")
1321       (goto-char (point-max))
1322       (insert "Status: " (nnmail-encode-status status) "\n"))))
1323
1324 (defun nnmail-decode-status ()
1325   "Return a status-value alist from STATUS."
1326   (goto-char (point-min))
1327   (when (re-search-forward "^Status: " nil t)
1328     (let (name value status)
1329       (save-restriction
1330         ;; Narrow to the status.
1331         (narrow-to-region
1332          (point)
1333          (if (re-search-forward "^[^ \t]" nil t)
1334              (1- (point))
1335            (point-max)))
1336         ;; Go through all elements and add them to the list.
1337         (goto-char (point-min))
1338         (while (re-search-forward "[^ \t=]+" nil t)
1339           (setq name (match-string 0))
1340           (if (not (= (following-char) ?=))
1341               ;; Implied "yes".
1342               (setq value "yes")
1343             (forward-char 1)
1344             (if (not (= (following-char) ?\"))
1345                 (if (not (looking-at "[^ \t]"))
1346                     ;; Implied "no".
1347                     (setq value "no")
1348                   ;; Unquoted value.
1349                   (setq value (match-string 0))
1350                   (goto-char (match-end 0)))
1351               ;; Quoted value.
1352               (setq value (read (current-buffer)))))
1353           (push (cons name value) status)))
1354       status)))
1355
1356 (defun nnmail-encode-status (status)
1357   "Return a status string from STATUS."
1358   (mapconcat
1359    (lambda (elem)
1360      (concat
1361       (car elem) "="
1362       (if (string-match "[ \t]" (cdr elem))
1363           (prin1-to-string (cdr elem))
1364         (cdr elem))))
1365    status " "))
1366
1367 (defun nnmail-split-history ()
1368   "Generate an overview of where the last mail split put articles."
1369   (interactive)
1370   (unless nnmail-split-history
1371     (error "No current split history"))
1372   (pop-to-buffer "*nnmail split history*")
1373   (buffer-disable-undo (current-buffer))
1374   (erase-buffer)
1375   (let ((history nnmail-split-history)
1376         elem ga)
1377     (while (setq elem (pop history))
1378       (insert (mapcar (lambda (ga)
1379                         (concat (car ga) ":" (int-to-string (cdr ga))))
1380                       elem
1381                       ", ")
1382               "\n"))
1383     (goto-char (point-min))))
1384         
1385 (run-hooks 'nnmail-load-hook)
1386             
1387 (provide 'nnmail)
1388
1389 ;;; nnmail.el ends here