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