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