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