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