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