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