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