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