*** 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-pop-password nil
295   "*Password to use when reading mail from a POP server, if required.")
296
297 (defvar nnmail-split-fancy-syntax-table nil
298   "Syntax table used by `nnmail-split-fancy'.")
299 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
300   (setq nnmail-split-fancy-syntax-table
301         (copy-syntax-table (standard-syntax-table)))
302   ;; support the %-hack
303   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
304
305 (defvar nnmail-prepare-save-mail-hook nil
306   "Hook called before saving mail.")
307
308 (defvar nnmail-moved-inboxes nil
309   "List of inboxes that have been moved.")
310
311 (defvar nnmail-internal-password nil)
312
313 \f
314
315 (defconst nnmail-version "nnmail 1.0"
316   "nnmail version.")
317
318 \f
319
320 (defun nnmail-request-post (&optional server)
321   (mail-send-and-exit nil))
322
323 (defun nnmail-find-file (file)
324   "Insert FILE in server buffer safely."
325   (set-buffer nntp-server-buffer)
326   (erase-buffer)
327   (let ((format-alist nil)
328         (after-insert-file-functions nil))
329     (condition-case ()
330         (progn (insert-file-contents file) t)
331       (file-error nil))))
332
333 (defun nnmail-group-pathname (group dir &optional file)
334   "Make pathname for GROUP."
335   (concat
336    (let ((dir (file-name-as-directory (expand-file-name dir))))
337      ;; If this directory exists, we use it directly.
338      (if (or nnmail-use-long-file-names 
339              (file-directory-p (concat dir group)))
340          (concat dir group "/")
341        ;; If not, we translate dots into slashes.
342        (concat dir (nnheader-replace-chars-in-string group ?. ?/) "/")))
343    (or file "")))
344   
345 (defun nnmail-date-to-time (date)
346   "Convert DATE into time."
347   (let* ((d1 (timezone-parse-date date))
348          (t1 (timezone-parse-time (aref d1 3))))
349     (apply 'encode-time
350            (mapcar (lambda (el)
351                      (and el (string-to-number el)))
352                    (list
353                     (aref t1 2) (aref t1 1) (aref t1 0)
354                     (aref d1 2) (aref d1 1) (aref d1 0)
355                     (aref d1 4))))))
356
357 (defun nnmail-time-less (t1 t2)
358   "Say whether time T1 is less than time T2."
359   (or (< (car t1) (car t2))
360       (and (= (car t1) (car t2))
361            (< (nth 1 t1) (nth 1 t2)))))
362
363 (defun nnmail-days-to-time (days)
364   "Convert DAYS into time."
365   (let* ((seconds (* 1.0 days 60 60 24))
366          (rest (expt 2 16))
367          (ms (condition-case nil (round (/ seconds rest)) 
368                (range-error (expt 2 16)))))
369     (list ms (condition-case nil (round (- seconds (* ms rest)))
370                (range-error (expt 2 16))))))
371
372 (defun nnmail-time-since (time)
373   "Return the time since TIME, which is either an internal time or a date."
374   (when (stringp time)
375     ;; Convert date strings to internal time.
376     (setq time (nnmail-date-to-time time)))
377   (let* ((current (current-time))
378          (rest (if (< (nth 1 current) (nth 1 time)) (expt 2 16))))
379     (list (- (+ (car current) (if rest -1 0)) (car time))
380           (- (+ (or rest 0) (nth 1 current)) (nth 1 time)))))
381
382 ;; Function rewritten from rmail.el.
383 (defun nnmail-move-inbox (inbox)
384   "Move INBOX to `nnmail-crash-box'."
385   (let ((inbox (file-truename (expand-file-name inbox)))
386         (tofile (file-truename (expand-file-name nnmail-crash-box)))
387         movemail popmail errors)
388     ;; If getting from mail spool directory,
389     ;; use movemail to move rather than just renaming,
390     ;; so as to interlock with the mailer.
391     (unless (setq popmail (string-match "^po:" (file-name-nondirectory inbox)))
392       (setq movemail t))
393     (when popmail 
394       (setq inbox (file-name-nondirectory inbox)))
395     (when (and movemail
396                ;; On some systems, /usr/spool/mail/foo is a directory
397                ;; and the actual inbox is /usr/spool/mail/foo/foo.
398                (file-directory-p inbox))
399       (setq inbox (expand-file-name (user-login-name) inbox)))
400     (if (member inbox nnmail-moved-inboxes)
401         nil
402       (if popmail
403           (progn
404             (setq nnmail-internal-password nnmail-pop-password)
405             (when (and nnmail-pop-password-required (not nnmail-pop-password))
406               (setq nnmail-internal-password
407                     (nnmail-read-passwd
408                      (format "Password for %s: "
409                              (substring inbox (+ popmail 3))))))
410             (message "Getting mail from post office ..."))
411         (when (or (and (file-exists-p tofile)
412                        (/= 0 (nnheader-file-size tofile)))
413                   (and (file-exists-p inbox)
414                        (/= 0 (nnheader-file-size inbox))))
415           (message "Getting mail from %s..." inbox)))
416       ;; Set TOFILE if have not already done so, and
417       ;; rename or copy the file INBOX to TOFILE if and as appropriate.
418       (cond 
419        ((file-exists-p tofile)
420         ;; The crash box exists already.
421         t)
422        ((and (not popmail)
423              (not (file-exists-p inbox)))
424         ;; There is no inbox.
425         (setq tofile nil))
426        ((and (not movemail) (not popmail))
427         ;; Try copying.  If that fails (perhaps no space),
428         ;; rename instead.
429         (condition-case nil
430             (copy-file inbox tofile nil)
431           (error
432            ;; Third arg is t so we can replace existing file TOFILE.
433            (rename-file inbox tofile t)))
434         (push inbox nnmail-moved-inboxes)
435         ;; Make the real inbox file empty.
436         ;; Leaving it deleted could cause lossage
437         ;; because mailers often won't create the file.
438         (condition-case ()
439             (write-region (point) (point) inbox)
440           (file-error nil)))
441        (t
442         ;; Use movemail.
443         (unwind-protect
444             (save-excursion
445               (setq errors (generate-new-buffer " *nnmail loss*"))
446               (buffer-disable-undo errors)
447               (let ((default-directory "/"))
448                 (if (nnheader-functionp nnmail-movemail-program)
449                     (funcall nnmail-movemail-program inbox tofile)
450                   (apply 
451                    'call-process
452                    (append
453                     (list
454                      (expand-file-name nnmail-movemail-program exec-directory)
455                      nil errors nil inbox tofile)
456                     (when nnmail-internal-password
457                       (list nnmail-internal-password))))))
458               (if (not (buffer-modified-p errors))
459                   ;; No output => movemail won
460                   (progn
461                     (or popmail
462                         (set-file-modes inbox nnmail-default-file-modes))
463                     (push inbox nnmail-moved-inboxes))
464                 (set-buffer errors)
465                 ;; There may be a warning about older revisions.  We
466                 ;; ignore those.
467                 (goto-char (point-min))
468                 (if (search-forward "older revision" nil t)
469                     (progn
470                       (or popmail
471                           (set-file-modes inbox nnmail-default-file-modes))
472                       (push inbox nnmail-moved-inboxes))
473                   ;; Probably a real error.
474                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
475                   (goto-char (point-max))
476                   (skip-chars-backward " \t")
477                   (delete-region (point) (point-max))
478                   (goto-char (point-min))
479                   (when (looking-at "movemail: ")
480                     (delete-region (point-min) (match-end 0)))
481                   (unless (yes-or-no-p
482                            (format "movemail: %s.  Continue? "
483                                    (buffer-string)))
484                     (error "%s" (buffer-string)))
485                   (setq tofile nil)))))))
486       (and errors
487            (buffer-name errors)
488            (kill-buffer errors))
489       tofile)))
490
491 (defun nnmail-get-active ()
492   "Returns an assoc of group names and active ranges.
493 nn*-request-list should have been called before calling this function."
494   (let (group-assoc)
495     ;; Go through all groups from the active list.
496     (save-excursion
497       (set-buffer nntp-server-buffer)
498       (goto-char (point-min))
499       (while (re-search-forward 
500               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
501         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
502         (push (list (match-string 1)
503                     (cons (string-to-int (match-string 3))
504                           (string-to-int (match-string 2))))
505               group-assoc)))
506     group-assoc))
507
508 (defun nnmail-save-active (group-assoc file-name)
509   "Save GROUP-ASSOC in ACTIVE-FILE."
510   (when file-name
511     (let (group)
512       (save-excursion
513         (set-buffer (get-buffer-create " *nnmail active*"))
514         (buffer-disable-undo (current-buffer))
515         (erase-buffer)
516         (while group-assoc
517           (setq group (pop group-assoc))
518           (insert (format "%s %d %d y\n" (car group) (cdadr group) 
519                           (caadr group))))
520         (unless (file-exists-p (file-name-directory file-name))
521           (make-directory (file-name-directory file-name) t))
522         (nnmail-write-region
523          1 (point-max) (expand-file-name file-name) nil 'nomesg)
524         (kill-buffer (current-buffer))))))
525
526 (defun nnmail-get-split-group (file group)
527   "Find out whether this FILE is to be split into GROUP only.
528 If GROUP is non-nil and we are using procmail, return the group name
529 only when the file is the correct procmail file.  When GROUP is nil,
530 return nil if FILE is a spool file or the procmail group for which it
531 is a spool.  If not using procmail, return GROUP."
532   (if (or (eq nnmail-spool-file 'procmail)
533           nnmail-use-procmail)
534       (if (string-match (concat "^" (expand-file-name
535                                      (file-name-as-directory
536                                       nnmail-procmail-directory))
537                                 "\\([^/]*\\)" nnmail-procmail-suffix "$")
538                         (expand-file-name file))
539           (let ((procmail-group (substring (expand-file-name file)
540                                            (match-beginning 1)
541                                            (match-end 1))))
542             (if group 
543                 (if (string-equal group procmail-group)
544                     group
545                   nil)
546               procmail-group))
547         nil)
548     group))
549
550 (defun nnmail-process-babyl-mail-format (func artnum-func)
551   (let ((case-fold-search t)
552         start message-id content-length do-search end)
553     (while (not (eobp))
554       (goto-char (point-min))
555       (re-search-forward
556        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
557       (goto-char (match-end 0))
558       (delete-region (match-beginning 0) (match-end 0))
559       (narrow-to-region
560        (setq start (point))
561        (progn
562          ;; Skip all the headers in case there are more "From "s...
563          (or (search-forward "\n\n" nil t)
564              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
565              (search-forward "\1f\f"))
566          (point)))
567       (run-hooks 'nnmail-prepare-incoming-header-hook)
568       (widen)
569       ;; Find the Message-ID header.
570       (save-excursion
571         (if (re-search-backward "^Message-ID:[ \t]*\\(<[^>]*>\\)" nil t)
572             (setq message-id (buffer-substring (match-beginning 1)
573                                                (match-end 1)))
574           ;; There is no Message-ID here, so we create one.
575           (save-excursion
576             (when (re-search-backward "^Message-ID:" nil t)
577               (beginning-of-line)
578               (insert "Original-")))
579           (forward-line -1)
580           (insert "Message-ID: " (setq message-id (nnmail-message-id))
581                   "\n")))
582       ;; Look for a Content-Length header.
583       (if (not (save-excursion
584                  (and (re-search-backward 
585                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
586                       (setq content-length (string-to-int
587                                             (buffer-substring 
588                                              (match-beginning 1)
589                                              (match-end 1))))
590                       ;; We destroy the header, since none of
591                       ;; the backends ever use it, and we do not
592                       ;; want to confuse other mailers by having
593                       ;; a (possibly) faulty header.
594                       (progn (insert "X-") t))))
595           (setq do-search t)
596         (if (or (= (+ (point) content-length) (point-max))
597                 (save-excursion
598                   (goto-char (+ (point) content-length))
599                   (looking-at "\1f")))
600             (progn
601               (goto-char (+ (point) content-length))
602               (setq do-search nil))
603           (setq do-search t)))
604       ;; Go to the beginning of the next article - or to the end
605       ;; of the buffer.  
606       (when do-search
607         (if (re-search-forward "^\1f" nil t)
608             (goto-char (match-beginning 0))
609           (goto-char (1- (point-max)))))
610       (delete-char 1)                   ; delete ^_
611       (save-excursion
612         (save-restriction
613           (narrow-to-region start (point))
614           (goto-char (point-min))
615           (nnmail-check-duplication message-id func artnum-func)
616           (setq end (point-max))))
617       (goto-char end))))
618
619 (defun nnmail-search-unix-mail-delim ()
620   "Put point at the beginning of the next message."
621   (let ((case-fold-search t)
622         (delim (concat "^" message-unix-mail-delimiter))
623         found)
624     (while (not found)
625       (if (re-search-forward delim nil t)
626           (when (or (looking-at "[^\n :]+ *:")
627                     (looking-at delim)
628                     (looking-at (concat ">" message-unix-mail-delimiter)))
629             (forward-line -1)
630             (setq found 'yes))
631         (setq found 'no)))
632     (eq found 'yes)))
633
634 (defun nnmail-process-unix-mail-format (func artnum-func)
635   (let ((case-fold-search t)
636         (delim (concat "^" message-unix-mail-delimiter))
637         start message-id content-length end skip head-end)
638     (goto-char (point-min))
639     (if (not (and (re-search-forward delim nil t)
640                   (goto-char (match-beginning 0))))
641         ;; Possibly wrong format?
642         (error "Error, unknown mail format! (Possibly corrupted.)")
643       ;; Carry on until the bitter end.
644       (while (not (eobp))
645         (setq start (point)
646               end nil)
647         ;; Find the end of the head.
648         (narrow-to-region
649          start 
650          (if (search-forward "\n\n" nil t)
651              (1- (point))
652            ;; This will never happen, but just to be on the safe side --
653            ;; if there is no head-body delimiter, we search a bit manually.
654            (while (and (looking-at "From \\|[^ \t]+:")
655                        (not (eobp)))
656              (forward-line 1)
657              (point))))
658         ;; Find the Message-ID header.
659         (goto-char (point-min))
660         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
661             (setq message-id (match-string 1))
662           (save-excursion
663             (when (re-search-forward "^Message-ID:" nil t)
664               (beginning-of-line)
665               (insert "Original-")))
666           ;; There is no Message-ID here, so we create one.
667           (forward-line 1)
668           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
669         ;; Look for a Content-Length header.
670         (goto-char (point-min))
671         (if (not (re-search-forward
672                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
673             (setq content-length nil)
674           (setq content-length (string-to-int (match-string 1)))
675           ;; We destroy the header, since none of the backends ever 
676           ;; use it, and we do not want to confuse other mailers by
677           ;; having a (possibly) faulty header.
678           (beginning-of-line)
679           (insert "X-"))
680         (run-hooks 'nnmail-prepare-incoming-header-hook)
681         ;; Find the end of this article.
682         (goto-char (point-max))
683         (widen)
684         (setq head-end (point))
685         ;; We try the Content-Length value.  The idea: skip over the header
686         ;; separator, then check what happens content-length bytes into the
687         ;; message body.  This should be either the end ot the buffer, the
688         ;; message separator or a blank line followed by the separator.
689         ;; The blank line should probably be deleted.  If neither of the
690         ;; three is met, the content-length header is probably invalid.
691         (when content-length
692           (forward-line 1)
693           (setq skip (+ (point) content-length))
694           (goto-char skip)
695           (cond ((or (= skip (point-max))
696                      (= (1+ skip) (point-max)))
697                  (setq end (point-max)))
698                 ((looking-at delim)
699                  (setq end skip))
700                 ((looking-at
701                   (concat "[ \t]*\n\\(" delim "\\)"))
702                  (setq end (match-beginning 1)))
703                 (t (setq end nil))))
704         (if end
705             (goto-char end)
706           ;; No Content-Length, so we find the beginning of the next 
707           ;; article or the end of the buffer.
708           (goto-char head-end)
709           (or (nnmail-search-unix-mail-delim)
710               (goto-char (point-max))))
711         ;; Allow the backend to save the article.
712         (save-excursion
713           (save-restriction
714             (narrow-to-region start (point))
715             (goto-char (point-min))
716             (nnmail-check-duplication message-id func artnum-func)
717             (setq end (point-max))))
718         (goto-char end)))))
719
720 (defun nnmail-process-mmdf-mail-format (func artnum-func)
721   (let ((delim "^\^A\^A\^A\^A$")
722         (case-fold-search t)
723         start message-id end)
724     (goto-char (point-min))
725     (if (not (and (re-search-forward delim nil t)
726                   (forward-line 1)))
727         ;; Possibly wrong format?
728         (error "Error, unknown mail format! (Possibly corrupted.)")
729       ;; Carry on until the bitter end.
730       (while (not (eobp))
731         (setq start (point))
732         ;; Find the end of the head.
733         (narrow-to-region
734          start 
735          (if (search-forward "\n\n" nil t)
736              (1- (point))
737            ;; This will never happen, but just to be on the safe side --
738            ;; if there is no head-body delimiter, we search a bit manually.
739            (while (and (looking-at "From \\|[^ \t]+:")
740                        (not (eobp)))
741              (forward-line 1)
742              (point))))
743         ;; Find the Message-ID header.
744         (goto-char (point-min))
745         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
746             (setq message-id (match-string 1))
747           ;; There is no Message-ID here, so we create one.
748           (save-excursion
749             (when (re-search-backward "^Message-ID:" nil t)
750               (beginning-of-line)
751               (insert "Original-")))
752           (forward-line 1)
753           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
754         (run-hooks 'nnmail-prepare-incoming-header-hook)
755         ;; Find the end of this article.
756         (goto-char (point-max))
757         (widen)
758         (if (re-search-forward delim nil t)
759             (beginning-of-line)
760           (goto-char (point-max)))
761         ;; Allow the backend to save the article.
762         (save-excursion
763           (save-restriction
764             (narrow-to-region start (point))
765             (goto-char (point-min))
766             (nnmail-check-duplication message-id func artnum-func)
767             (setq end (point-max))))
768         (goto-char end)
769         (forward-line 2)))))
770
771 (defun nnmail-split-incoming (incoming func &optional exit-func
772                                        group artnum-func)
773   "Go through the entire INCOMING file and pick out each individual mail.
774 FUNC will be called with the buffer narrowed to each mail."
775   (let (;; If this is a group-specific split, we bind the split
776         ;; methods to just this group.
777         (nnmail-split-methods (if (and group
778                                        (or (eq nnmail-spool-file 'procmail)
779                                            nnmail-use-procmail)
780                                        (not nnmail-resplit-incoming))
781                                   (list (list group ""))
782                                 nnmail-split-methods)))
783     (save-excursion
784       ;; Insert the incoming file.
785       (set-buffer (get-buffer-create " *nnmail incoming*"))
786       (buffer-disable-undo (current-buffer))
787       (erase-buffer)
788       (nnheader-insert-file-contents-literally incoming)
789       (unless (zerop (buffer-size))
790         (goto-char (point-min))
791         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
792         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
793         ;; use the former when fetching from a mailbox, the latter when
794         ;; fetches from a file.
795         (cond ((or (looking-at "\^L")
796                    (looking-at "BABYL OPTIONS:"))
797                (nnmail-process-babyl-mail-format func artnum-func))
798               ((looking-at "\^A\^A\^A\^A")
799                (nnmail-process-mmdf-mail-format func artnum-func))
800               (t
801                (nnmail-process-unix-mail-format func artnum-func))))
802       (if exit-func (funcall exit-func))
803       (kill-buffer (current-buffer)))))
804
805 ;; Mail crossposts suggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
806 (defun nnmail-article-group (func)
807   "Look at the headers and return an alist of groups that match.
808 FUNC will be called with the group name to determine the article number."
809   (let ((methods nnmail-split-methods)
810         (obuf (current-buffer))
811         (beg (point-min))
812         end group-art method)
813     (if (and (sequencep methods) (= (length methods) 1))
814         ;; If there is only just one group to put everything in, we
815         ;; just return a list with just this one method in.
816         (setq group-art
817               (list (cons (caar methods) (funcall func (caar methods)))))
818       ;; We do actual comparison.
819       (save-excursion
820         ;; Find headers.
821         (goto-char beg)
822         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
823         (set-buffer nntp-server-buffer)
824         (erase-buffer)
825         ;; Copy the headers into the work buffer.
826         (insert-buffer-substring obuf beg end)
827         ;; Fold continuation lines.
828         (goto-char (point-min))
829         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
830           (replace-match " " t t))
831         ;; Allow washing.
832         (run-hooks 'nnmail-split-hook)
833         (if (and (symbolp nnmail-split-methods)
834                  (fboundp nnmail-split-methods))
835             ;; `nnmail-split-methods' is a function, so we just call 
836             ;; this function here and use the result.
837             (setq group-art
838                   (mapcar
839                    (lambda (group) (cons group (funcall func group)))
840                    (condition-case nil
841                        (or (funcall nnmail-split-methods)
842                            '("bogus"))
843                      (error
844                       (message 
845                        "Error in `nnmail-split-methods'; using `bogus' mail group")
846                       (sit-for 1)
847                       '("bogus")))))
848           ;; Go through the split methods to find a match.
849           (while (and methods (or nnmail-crosspost (not group-art)))
850             (goto-char (point-max))
851             (setq method (pop methods))
852             (if (or methods
853                     (not (equal "" (nth 1 method))))
854                 (when (and
855                        (condition-case () 
856                            (if (stringp (nth 1 method))
857                                (re-search-backward (cadr method) nil t)
858                              ;; Function to say whether this is a match.
859                              (funcall (nth 1 method) (car method)))
860                          (error nil))
861                        ;; Don't enter the article into the same 
862                        ;; group twice.
863                        (not (assoc (car method) group-art)))
864                   (push (cons (car method) (funcall func (car method))) 
865                         group-art))
866               ;; This is the final group, which is used as a 
867               ;; catch-all.
868               (unless group-art
869                 (setq group-art 
870                       (list (cons (car method) 
871                                   (funcall func (car method)))))))))
872         ;; See whether the split methods returned `junk'.
873         (if (equal group-art '(junk))
874             nil
875           (nreverse (delq 'junk group-art)))))))
876
877 (defun nnmail-insert-lines ()
878   "Insert how many lines there are in the body of the mail.
879 Return the number of characters in the body."
880   (let (lines chars)
881     (save-excursion
882       (goto-char (point-min))
883       (when (search-forward "\n\n" nil t) 
884         (setq chars (- (point-max) (point)))
885         (setq lines (count-lines (point) (point-max)))
886         (forward-char -1)
887         (save-excursion
888           (when (re-search-backward "^Lines: " nil t)
889             (delete-region (point) (progn (forward-line 1) (point)))))
890         (beginning-of-line)
891         (insert (format "Lines: %d\n" (max lines 0)))
892         chars))))
893
894 (defun nnmail-insert-xref (group-alist)
895   "Insert an Xref line based on the (group . article) alist."
896   (save-excursion
897     (goto-char (point-min))
898     (when (search-forward "\n\n" nil t) 
899       (forward-char -1)
900       (when (re-search-backward "^Xref: " nil t)
901         (delete-region (match-beginning 0) 
902                        (progn (forward-line 1) (point))))
903       (insert (format "Xref: %s" (system-name)))
904       (while group-alist
905         (insert (format " %s:%d" (caar group-alist) (cdar group-alist)))
906         (setq group-alist (cdr group-alist)))
907       (insert "\n"))))
908
909 ;;; Message washing functions
910
911 (defun nnmail-remove-leading-whitespace ()
912   "Remove excessive whitespace from all headers."
913   (goto-char (point-min))
914   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
915     (replace-match "\\1" t t)))
916
917 (defun nnmail-remove-list-identifiers ()
918   "Remove list identifiers from Subject headers."
919   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
920                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
921     (when regexp
922       (goto-char (point-min))
923       (when (re-search-forward
924              (concat "Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
925              nil t)
926         (delete-region (match-beginning 2) (match-end 0))))))
927
928 (defun nnmail-remove-tabs ()
929   "Translate TAB characters into SPACE characters."
930   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
931
932 ;;; Utility functions
933
934 ;; Written by byer@mv.us.adobe.com (Scott Byer).
935 (defun nnmail-make-complex-temp-name (prefix)
936   (let ((newname (make-temp-name prefix))
937         (newprefix prefix))
938     (while (file-exists-p newname)
939       (setq newprefix (concat newprefix "x"))
940       (setq newname (make-temp-name newprefix)))
941     newname))
942
943 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
944
945 (defun nnmail-split-fancy ()
946   "Fancy splitting method.
947 See the documentation for the variable `nnmail-split-fancy' for documentation."
948   (let ((syntab (syntax-table)))
949     (unwind-protect
950         (progn
951           (set-syntax-table nnmail-split-fancy-syntax-table)
952           (nnmail-split-it nnmail-split-fancy))
953       (set-syntax-table syntab))))
954
955 (defvar nnmail-split-cache nil)
956 ;; Alist of split expressions their equivalent regexps.
957
958 (defun nnmail-split-it (split)
959   ;; Return a list of groups matching SPLIT.
960   (cond
961    ((stringp split)
962     ;; A group.
963     (list split))
964    ((eq split 'junk)
965     ;; Junk this.
966     (list 'junk))
967    ((eq (car split) '&)
968     (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
969    ((eq (car split) '|)
970     (let (done)
971       (while (and (not done) (cdr split))
972         (setq split (cdr split)
973               done (nnmail-split-it (car split))))
974       done))
975    ((assq split nnmail-split-cache)
976     ;; A compiled match expression.
977     (goto-char (point-max))
978     (if (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
979         (nnmail-split-it (nth 2 split))))
980    (t
981     ;; An uncompiled match.
982     (let* ((field (nth 0 split))
983            (value (nth 1 split))
984            (regexp (concat "^\\(" 
985                            (if (symbolp field)
986                                (cdr (assq field nnmail-split-abbrev-alist))
987                              field)
988                            "\\):.*\\<\\("
989                            (if (symbolp value)
990                                (cdr (assq value nnmail-split-abbrev-alist))
991                              value)
992                            "\\)\\>")))
993       (setq nnmail-split-cache 
994             (cons (cons split regexp) nnmail-split-cache))
995       (goto-char (point-max))
996       (if (re-search-backward regexp nil t)
997           (nnmail-split-it (nth 2 split)))))))
998
999 ;; Get a list of spool files to read.
1000 (defun nnmail-get-spool-files (&optional group)
1001   (if (null nnmail-spool-file)
1002       ;; No spool file whatsoever.
1003       nil
1004     (let* ((procmails 
1005             ;; If procmail is used to get incoming mail, the files
1006             ;; are stored in this directory.
1007             (and (file-exists-p nnmail-procmail-directory)
1008                  (or (eq nnmail-spool-file 'procmail)
1009                      nnmail-use-procmail)
1010                  (directory-files 
1011                   nnmail-procmail-directory 
1012                   t (concat (if group (concat "^" group) "")
1013                             nnmail-procmail-suffix "$"))))
1014            (p procmails)
1015            (crash (when (and (file-exists-p nnmail-crash-box)
1016                              (> (nnheader-file-size
1017                                  (file-truename nnmail-crash-box)) 0))
1018                     (list nnmail-crash-box))))
1019       ;; Remove any directories that inadvertantly match the procmail
1020       ;; suffix, which might happen if the suffix is "". 
1021       (while p
1022         (when (file-directory-p (car p))
1023           (setq procmails (delete (car p) procmails)))
1024         (setq p (cdr p)))
1025       ;; Return the list of spools.
1026       (append 
1027        crash
1028        (cond ((and group
1029                    (or (eq nnmail-spool-file 'procmail)
1030                        nnmail-use-procmail)
1031                    procmails)
1032               procmails)
1033              ((and group
1034                    (eq nnmail-spool-file 'procmail))
1035               nil)
1036              ((listp nnmail-spool-file)
1037               (append nnmail-spool-file procmails))
1038              ((stringp nnmail-spool-file)
1039               (cons nnmail-spool-file procmails))
1040              ((eq nnmail-spool-file 'pop)
1041               (cons (format "po:%s" (user-login-name)) procmails))
1042              (t
1043               procmails))))))
1044
1045 ;; Activate a backend only if it isn't already activated. 
1046 ;; If FORCE, re-read the active file even if the backend is 
1047 ;; already activated.
1048 (defun nnmail-activate (backend &optional force)
1049   (let (file timestamp file-time)
1050     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1051             force
1052             (and (setq file (condition-case ()
1053                                 (symbol-value (intern (format "%s-active-file" 
1054                                                               backend)))
1055                               (error nil)))
1056                  (setq file-time (nth 5 (file-attributes file)))
1057                  (or (not
1058                       (setq timestamp
1059                             (condition-case ()
1060                                 (symbol-value (intern
1061                                                (format "%s-active-timestamp" 
1062                                                        backend)))
1063                               (error 'none))))
1064                      (not (consp timestamp))
1065                      (equal timestamp '(0 0))
1066                      (> (nth 0 file-time) (nth 0 timestamp))
1067                      (and (= (nth 0 file-time) (nth 0 timestamp))
1068                           (> (nth 1 file-time) (nth 1 timestamp))))))
1069         (save-excursion
1070           (or (eq timestamp 'none)
1071               (set (intern (format "%s-active-timestamp" backend)) 
1072                    (current-time)))
1073           (funcall (intern (format "%s-request-list" backend)))
1074           (set (intern (format "%s-group-alist" backend)) 
1075                (nnmail-get-active))))
1076     t))
1077
1078 (defun nnmail-message-id ()
1079   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1080
1081 ;;;
1082 ;;; nnmail duplicate handling
1083 ;;;
1084
1085 (defvar nnmail-cache-buffer nil)
1086
1087 (defun nnmail-cache-open ()
1088   (if (or (not nnmail-treat-duplicates)
1089           (and nnmail-cache-buffer
1090                (buffer-name nnmail-cache-buffer)))
1091       ()                                ; The buffer is open.
1092     (save-excursion
1093       (set-buffer 
1094        (setq nnmail-cache-buffer 
1095              (get-buffer-create " *nnmail message-id cache*")))
1096       (buffer-disable-undo (current-buffer))
1097       (and (file-exists-p nnmail-message-id-cache-file)
1098            (insert-file-contents nnmail-message-id-cache-file))
1099       (set-buffer-modified-p nil)
1100       (current-buffer))))
1101
1102 (defun nnmail-cache-close ()
1103   (when (and nnmail-cache-buffer
1104              nnmail-treat-duplicates
1105              (buffer-name nnmail-cache-buffer)
1106              (buffer-modified-p nnmail-cache-buffer))
1107     (save-excursion
1108       (set-buffer nnmail-cache-buffer)
1109       ;; Weed out the excess number of Message-IDs.
1110       (goto-char (point-max))
1111       (and (search-backward "\n" nil t nnmail-message-id-cache-length)
1112            (progn
1113              (beginning-of-line)
1114              (delete-region (point-min) (point))))
1115       ;; Save the buffer.
1116       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1117           (make-directory (file-name-directory nnmail-message-id-cache-file)
1118                           t))
1119       (nnmail-write-region (point-min) (point-max)
1120                            nnmail-message-id-cache-file nil 'silent)
1121       (set-buffer-modified-p nil)
1122       (setq nnmail-cache-buffer nil)
1123       ;;(kill-buffer (current-buffer))
1124       )))
1125
1126 (defun nnmail-cache-insert (id)
1127   (when nnmail-treat-duplicates
1128     (save-excursion
1129       (set-buffer nnmail-cache-buffer)
1130       (goto-char (point-max))
1131       (insert id "\n"))))
1132
1133 (defun nnmail-cache-id-exists-p (id)
1134   (when nnmail-treat-duplicates
1135     (save-excursion
1136       (set-buffer nnmail-cache-buffer)
1137       (goto-char (point-max))
1138       (search-backward id nil t))))
1139
1140 (defun nnmail-check-duplication (message-id func artnum-func)
1141   (run-hooks 'nnmail-prepare-incoming-message-hook)
1142   ;; If this is a duplicate message, then we do not save it.
1143   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1144          (action (when duplication
1145                    (cond
1146                     ((memq nnmail-treat-duplicates '(warn delete))
1147                      nnmail-treat-duplicates)
1148                     ((nnheader-functionp nnmail-treat-duplicates)
1149                      (funcall nnmail-treat-duplicates message-id))
1150                     (t
1151                      nnmail-treat-duplicates))))
1152          (group-art (nreverse (nnmail-article-group artnum-func))))
1153     (cond
1154      ((null group-art)
1155       (delete-region (point-min) (point-max)))
1156      ((not duplication)
1157       (nnmail-cache-insert message-id)
1158       (funcall func group-art))
1159      ((eq action 'delete)
1160       (delete-region (point-min) (point-max)))
1161      ((eq action 'warn)
1162       ;; We insert a warning.
1163       (let ((case-fold-search t)
1164             (newid (nnmail-message-id)))
1165         (goto-char (point-min))
1166         (when (re-search-forward "^message-id:" nil t)
1167           (beginning-of-line)
1168           (insert "Original-"))
1169         (beginning-of-line)
1170         (insert 
1171          "Message-ID: " newid "\n"
1172          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1173         (nnmail-cache-insert newid)
1174         (funcall func group-art)))
1175      (t
1176       (funcall func group-art)))))
1177
1178 ;;; Get new mail.
1179
1180 (defun nnmail-get-value (&rest args)
1181   (let ((sym (intern (apply 'format args))))
1182     (when (boundp sym)
1183       (symbol-value sym))))
1184
1185 (defun nnmail-get-new-mail (method exit-func temp
1186                                    &optional group spool-func)
1187   "Read new incoming mail."
1188   (let* ((spools (nnmail-get-spool-files group))
1189          (group-in group)
1190          incoming incomings spool)
1191     (when (and (nnmail-get-value "%s-get-new-mail" method)
1192                nnmail-spool-file)
1193       ;; We first activate all the groups.
1194       (nnmail-activate method)
1195       ;; Allow the user to hook.
1196       (run-hooks 'nnmail-pre-get-new-mail-hook)
1197       ;; Open the message-id cache.
1198       (nnmail-cache-open)
1199       ;; The we go through all the existing spool files and split the
1200       ;; mail from each.
1201       (while spools
1202         (setq spool (pop spools))
1203         ;; We read each spool file if either the spool is a POP-mail
1204         ;; spool, or the file exists.  We can't check for the
1205         ;; existance of POPped mail.
1206         (when (or (string-match "^po:" spool)
1207                   (and (file-exists-p spool)
1208                        (> (nnheader-file-size (file-truename spool)) 0)))
1209           (nnheader-message 3 "%s: Reading incoming mail..." method)
1210           (when (and (nnmail-move-inbox spool)
1211                      (file-exists-p nnmail-crash-box))
1212             ;; There is new mail.  We first find out if all this mail
1213             ;; is supposed to go to some specific group.
1214             (setq group (nnmail-get-split-group spool group-in))
1215             ;; We split the mail
1216             (nnmail-split-incoming 
1217              nnmail-crash-box (intern (format "%s-save-mail" method)) 
1218              spool-func group (intern (format "%s-active-number" method)))
1219             ;; Check whether the inbox is to be moved to the special tmp dir. 
1220             (setq incoming
1221                   (nnmail-make-complex-temp-name 
1222                    (expand-file-name 
1223                     (if nnmail-tmp-directory
1224                         (concat 
1225                          (file-name-as-directory nnmail-tmp-directory)
1226                          (file-name-nondirectory (concat temp "Incoming")))
1227                       (concat temp "Incoming")))))
1228             (rename-file nnmail-crash-box incoming t)
1229             (push incoming incomings))))
1230       ;; If we did indeed read any incoming spools, we save all info. 
1231       (when incomings
1232         (nnmail-save-active 
1233          (nnmail-get-value "%s-group-alist" method)
1234          (nnmail-get-value "%s-active-file" method))
1235         (when exit-func
1236           (funcall exit-func))
1237         (run-hooks 'nnmail-read-incoming-hook)
1238         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1239       ;; Close the message-id cache.
1240       (nnmail-cache-close)
1241       ;; Allow the user to hook.
1242       (run-hooks 'nnmail-post-get-new-mail-hook)
1243       ;; Delete all the temporary files.
1244       (while incomings
1245         (setq incoming (pop incomings))
1246         (and nnmail-delete-incoming
1247              (file-exists-p incoming)
1248              (file-writable-p incoming)
1249              (delete-file incoming))))))
1250
1251 (defun nnmail-expired-article-p (group time force &optional inhibit)
1252   "Say whether an article that is TIME old in GROUP should be expired."
1253   (if force
1254       t
1255     (let ((days (or (and nnmail-expiry-wait-function
1256                          (funcall nnmail-expiry-wait-function group))
1257                     nnmail-expiry-wait)))
1258       (cond ((or (eq days 'never)
1259                  (and (not force)
1260                       inhibit))
1261              ;; This isn't an expirable group.
1262              nil)
1263             ((eq days 'immediate)
1264              ;; We expire all articles on sight.
1265              t)
1266             ((equal time '(0 0))
1267              ;; This is an ange-ftp group, and we don't have any dates.
1268              nil)
1269             ((numberp days)
1270              (setq days (nnmail-days-to-time days))
1271              ;; Compare the time with the current time.
1272              (nnmail-time-less days (nnmail-time-since time)))))))
1273
1274 (defvar nnmail-read-passwd nil)
1275 (defun nnmail-read-passwd (prompt)
1276   (unless nnmail-read-passwd
1277     (if (load "passwd" t)
1278         (setq nnmail-read-passwd 'read-passwd)
1279       (autoload 'ange-ftp-read-passwd "ange-ftp")
1280       (setq nnmail-read-passwd 'ange-ftp-read-passwd)))
1281   (funcall nnmail-read-passwd prompt))
1282
1283 (defun nnmail-check-syntax ()
1284   "Check (and modify) the syntax of the message in the current buffer."
1285   (save-restriction
1286     (message-narrow-to-head)
1287     (let ((case-fold-search t))
1288       (unless (re-search-forward "^Message-Id:" nil t)
1289         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1290
1291 (defun nnmail-write-region (start end filename &optional append visit lockname)
1292   "Do a `write-region', and then set the file modes."
1293   (write-region start end filename append visit lockname)
1294   (set-file-modes filename nnmail-default-file-modes))
1295
1296 ;;;
1297 ;;; Status functions
1298 ;;;
1299
1300 (defun nnmail-replace-status (name value)
1301   "Make status NAME and VALUE part of the current status line."
1302   (save-restriction
1303     (message-narrow-to-head)
1304     (let ((status (nnmail-decode-status)))
1305       (setq status (delq (member name status) status))
1306       (when value
1307         (push (cons name value) status))
1308       (message-remove-header "status")
1309       (goto-char (point-max))
1310       (insert "Status: " (nnmail-encode-status status) "\n"))))
1311
1312 (defun nnmail-decode-status ()
1313   "Return a status-value alist from STATUS."
1314   (goto-char (point-min))
1315   (when (re-search-forward "^Status: " nil t)
1316     (let (name value status)
1317       (save-restriction
1318         ;; Narrow to the status.
1319         (narrow-to-region
1320          (point)
1321          (if (re-search-forward "^[^ \t]" nil t)
1322              (1- (point))
1323            (point-max)))
1324         ;; Go through all elements and add them to the list.
1325         (goto-char (point-min))
1326         (while (re-search-forward "[^ \t=]+" nil t)
1327           (setq name (match-string 0))
1328           (if (not (= (following-char) ?=))
1329               ;; Implied "yes".
1330               (setq value "yes")
1331             (forward-char 1)
1332             (if (not (= (following-char) ?\"))
1333                 (if (not (looking-at "[^ \t]"))
1334                     ;; Implied "no".
1335                     (setq value "no")
1336                   ;; Unquoted value.
1337                   (setq value (match-string 0))
1338                   (goto-char (match-end 0)))
1339               ;; Quoted value.
1340               (setq value (read (current-buffer)))))
1341           (push (cons name value) status)))
1342       status)))
1343
1344 (defun nnmail-encode-status (status)
1345   "Return a status string from STATUS."
1346   (mapconcat
1347    (lambda (elem)
1348      (concat
1349       (car elem) "="
1350       (if (string-match "[ \t]" (cdr elem))
1351           (prin1-to-string (cdr elem))
1352         (cdr elem))))
1353    status " "))
1354
1355 (run-hooks 'nnmail-load-hook)
1356             
1357 (provide 'nnmail)
1358
1359 ;;; nnmail.el ends here