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