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