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