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