Importing pgnus-0.79
[elisp/gnus.git-] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2 ;; Copyright (C) 1995,96,97,98,99 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
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 (eval-when-compile (require 'cl))
29
30 (require 'nnheader)
31 (require 'message)
32 (require 'custom)
33 (require 'gnus-util)
34 (require 'mail-source)
35 (require 'mm-util)
36
37 (eval-and-compile
38   (autoload 'gnus-error "gnus-util")
39   (autoload 'gnus-buffer-live-p "gnus-util"))
40
41 (defgroup nnmail nil
42   "Reading mail with Gnus."
43   :group 'gnus)
44
45 (defgroup nnmail-retrieve nil
46   "Retrieving new mail."
47   :group 'nnmail)
48
49 (defgroup nnmail-prepare nil
50   "Preparing (or mangling) new mail after retrival."
51   :group 'nnmail)
52
53 (defgroup nnmail-duplicate nil
54   "Handling of duplicate mail messages."
55   :group 'nnmail)
56
57 (defgroup nnmail-split nil
58   "Organizing the incomming mail in folders."
59   :group 'nnmail)
60
61 (defgroup nnmail-files nil
62   "Mail files."
63   :group 'gnus-files
64   :group 'nnmail)
65
66 (defgroup nnmail-expire nil
67   "Expiring old mail."
68   :group 'nnmail)
69
70 (defgroup nnmail-procmail nil
71   "Interfacing with procmail and other mail agents."
72   :group 'nnmail)
73
74 (defgroup nnmail-various nil
75   "Various mail options."
76   :group 'nnmail)
77
78 (defcustom nnmail-split-methods
79   '(("mail.misc" ""))
80   "*Incoming mail will be split according to this variable.
81
82 If you'd like, for instance, one mail group for mail from the
83 \"4ad-l\" mailing list, one group for junk mail and one for everything
84 else, you could do something like this:
85
86  (setq nnmail-split-methods
87        '((\"mail.4ad\" \"From:.*4ad\")
88          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
89          (\"mail.misc\" \"\")))
90
91 As you can see, this variable is a list of lists, where the first
92 element in each \"rule\" is the name of the group (which, by the way,
93 does not have to be called anything beginning with \"mail\",
94 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
95 nnmail will try to match on the header to find a fit.
96
97 The second element can also be a function.  In that case, it will be
98 called narrowed to the headers with the first element of the rule as
99 the argument.  It should return a non-nil value if it thinks that the
100 mail belongs in that group.
101
102 The last element should always have \"\" as the regexp.
103
104 This variable can also have a function as its value."
105   :group 'nnmail-split
106   :type '(choice (repeat :tag "Alist" (group (string :tag "Name") regexp))
107                  (function-item nnmail-split-fancy)
108                  (function :tag "Other")))
109
110 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
111 (defcustom nnmail-crosspost t
112   "If non-nil, do crossposting if several split methods match the mail.
113 If nil, the first match found will be used."
114   :group 'nnmail-split
115   :type 'boolean)
116
117 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
118 (defcustom nnmail-keep-last-article nil
119   "If non-nil, nnmail will never delete/move a group's last article.
120 It can be marked expirable, so it will be deleted when it is no longer last.
121
122 You may need to set this variable if other programs are putting
123 new mail into folder numbers that Gnus has marked as expired."
124   :group 'nnmail-procmail
125   :group 'nnmail-various
126   :type 'boolean)
127
128 (defcustom nnmail-use-long-file-names nil
129   "If non-nil the mail backends will use long file and directory names.
130 If nil, groups like \"mail.misc\" will end up in directories like
131 \"mail/misc/\"."
132   :group 'nnmail-files
133   :type 'boolean)
134
135 (defcustom nnmail-default-file-modes 384
136   "Set the mode bits of all new mail files to this integer."
137   :group 'nnmail-files
138   :type 'integer)
139
140 (defcustom nnmail-expiry-wait 7
141   "*Expirable articles that are older than this will be expired.
142 This variable can either be a number (which will be interpreted as a
143 number of days) -- this doesn't have to be an integer.  This variable
144 can also be `immediate' and `never'."
145   :group 'nnmail-expire
146   :type '(choice (const immediate)
147                  (integer :tag "days")
148                  (const never)))
149
150 (defcustom nnmail-expiry-wait-function nil
151   "Variable that holds function to specify how old articles should be before they are expired.
152   The function will be called with the name of the group that the
153 expiry is to be performed in, and it should return an integer that
154 says how many days an article can be stored before it is considered
155 \"old\".  It can also return the values `never' and `immediate'.
156
157 Eg.:
158
159 \(setq nnmail-expiry-wait-function
160       (lambda (newsgroup)
161         (cond ((string-match \"private\" newsgroup) 31)
162               ((string-match \"junk\" newsgroup) 1)
163               ((string-match \"important\" newsgroup) 'never)
164               (t 7))))"
165   :group 'nnmail-expire
166   :type '(choice (const :tag "nnmail-expiry-wait" nil)
167                  (function :format "%v" nnmail-)))
168
169 (defcustom nnmail-cache-accepted-message-ids nil
170   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache."
171   :group 'nnmail
172   :type 'boolean)
173
174 (defcustom nnmail-spool-file '((file))
175   "*Where the mail backends will look for incoming mail.
176 This variable is a list of mail source specifiers.
177 If this variable is nil, no mail backends will read incoming mail."
178   :group 'nnmail-files
179   :type 'sexp)
180
181 (defcustom nnmail-resplit-incoming nil
182   "*If non-nil, re-split incoming procmail sorted mail."
183   :group 'nnmail-procmail
184   :type 'boolean)
185
186 (defcustom nnmail-delete-file-function 'delete-file
187   "Function called to delete files in some mail backends."
188   :group 'nnmail-files
189   :type 'function)
190
191 (defcustom nnmail-crosspost-link-function
192   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
193       'copy-file
194     'add-name-to-file)
195   "*Function called to create a copy of a file.
196 This is `add-name-to-file' by default, which means that crossposts
197 will use hard links.  If your file system doesn't allow hard
198 links, you could set this variable to `copy-file' instead."
199   :group 'nnmail-files
200   :type '(radio (function-item add-name-to-file)
201                 (function-item copy-file)
202                 (function :tag "Other")))
203
204 (defcustom nnmail-read-incoming-hook
205   (if (eq system-type 'windows-nt)
206       '(nnheader-ms-strip-cr)
207     nil)
208   "*Hook that will be run after the incoming mail has been transferred.
209 The incoming mail is moved from `nnmail-spool-file' (which normally is
210 something like \"/usr/spool/mail/$user\") to the user's home
211 directory.  This hook is called after the incoming mail box has been
212 emptied, and can be used to call any mail box programs you have
213 running (\"xwatch\", etc.)
214
215 Eg.
216
217 \(add-hook 'nnmail-read-incoming-hook
218            (lambda ()
219              (start-process \"mailsend\" nil
220                             \"/local/bin/mailsend\" \"read\" \"mbox\")))
221
222 If you have xwatch running, this will alert it that mail has been
223 read.
224
225 If you use `display-time', you could use something like this:
226
227 \(add-hook 'nnmail-read-incoming-hook
228           (lambda ()
229             ;; Update the displayed time, since that will clear out
230             ;; the flag that says you have mail.
231             (when (eq (process-status \"display-time\") 'run)
232               (display-time-filter display-time-process \"\"))))"
233   :group 'nnmail-prepare
234   :type 'hook)
235
236 (defcustom nnmail-prepare-incoming-hook nil
237   "Hook called before treating incoming mail.
238 The hook is run in a buffer with all the new, incoming mail."
239   :group 'nnmail-prepare
240   :type 'hook)
241
242 (defcustom nnmail-prepare-incoming-header-hook nil
243   "Hook called narrowed to the headers of each message.
244 This can be used to remove excessive spaces (and stuff like
245 that) from the headers before splitting and saving the messages."
246   :group 'nnmail-prepare
247   :type 'hook)
248
249 (defcustom nnmail-prepare-incoming-message-hook nil
250   "Hook called narrowed to each message."
251   :group 'nnmail-prepare
252   :type 'hook)
253
254 (defcustom nnmail-list-identifiers nil
255   "Regexp that matches list identifiers to be removed.
256 This can also be a list of regexps."
257   :group 'nnmail-prepare
258   :type '(choice (const :tag "none" nil)
259                  (regexp :value ".*")
260                  (repeat :value (".*") regexp)))
261
262 (defcustom nnmail-pre-get-new-mail-hook nil
263   "Hook called just before starting to handle new incoming mail."
264   :group 'nnmail-retrieve
265   :type 'hook)
266
267 (defcustom nnmail-post-get-new-mail-hook nil
268   "Hook called just after finishing handling new incoming mail."
269   :group 'nnmail-retrieve
270   :type 'hook)
271
272 (defcustom nnmail-split-hook nil
273   "Hook called before deciding where to split an article.
274 The functions in this hook are free to modify the buffer
275 contents in any way they choose -- the buffer contents are
276 discarded after running the split process."
277   :group 'nnmail-split
278   :type 'hook)
279
280 (defcustom nnmail-large-newsgroup 50
281   "*The number of the articles which indicates a large newsgroup.
282 If the number of the articles is greater than the value, verbose
283 messages will be shown to indicate the current status."
284   :group 'nnmail-various
285   :type 'integer)
286
287 (defcustom nnmail-split-fancy "mail.misc"
288   "Incoming mail can be split according to this fancy variable.
289 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
290
291 The format of this variable is SPLIT, where SPLIT can be one of
292 the following:
293
294 GROUP: Mail will be stored in GROUP (a string).
295
296 \(FIELD VALUE SPLIT): If the message field FIELD (a regexp) contains
297   VALUE (a regexp), store the messages as specified by SPLIT.
298
299 \(| SPLIT...): Process each SPLIT expression until one of them matches.
300   A SPLIT expression is said to match if it will cause the mail
301   message to be stored in one or more groups.
302
303 \(& SPLIT...): Process each SPLIT expression.
304
305 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
306   the buffer containing the message headers.  The return value FUNCTION
307   should be a split, which is then recursively processed.
308
309 FIELD must match a complete field name.  VALUE must match a complete
310 word according to the `nnmail-split-fancy-syntax-table' syntax table.
311 You can use \".*\" in the regexps to match partial field names or words.
312
313 FIELD and VALUE can also be lisp symbols, in that case they are expanded
314 as specified in `nnmail-split-abbrev-alist'.
315
316 GROUP can contain \\& and \\N which will substitute from matching
317 \\(\\) patterns in the previous VALUE.
318
319 Example:
320
321 \(setq nnmail-split-methods 'nnmail-split-fancy
322       nnmail-split-fancy
323       ;; Messages from the mailer daemon are not crossposted to any of
324       ;; the ordinary groups.  Warnings are put in a separate group
325       ;; from real errors.
326       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
327                           \"mail.misc\"))
328           ;; Non-error messages are crossposted to all relevant
329           ;; groups, but we don't crosspost between the group for the
330           ;; (ding) list and the group for other (ding) related mail.
331           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
332                 (\"subject\" \"ding\" \"ding.misc\"))
333              ;; Other mailing lists...
334              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
335              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
336              ;; People...
337              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
338           ;; Unmatched mail goes to the catch all group.
339           \"misc.misc\"))"
340   :group 'nnmail-split
341   ;; Sigh!
342   :type 'sexp)
343
344 (defcustom nnmail-split-abbrev-alist
345   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
346     (mail . "mailer-daemon\\|postmaster\\|uucp")
347     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
348     (from . "from\\|sender\\|resent-from")
349     (nato . "to\\|cc\\|resent-to\\|resent-cc")
350     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
351   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
352   :group 'nnmail-split
353   :type '(repeat (cons :format "%v" symbol regexp)))
354
355 (defcustom nnmail-message-id-cache-length 1000
356   "*The approximate number of Message-IDs nnmail will keep in its cache.
357 If this variable is nil, no checking on duplicate messages will be
358 performed."
359   :group 'nnmail-duplicate
360   :type '(choice (const :tag "disable" nil)
361                  (integer :format "%v")))
362
363 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
364   "*The file name of the nnmail Message-ID cache."
365   :group 'nnmail-duplicate
366   :group 'nnmail-files
367   :type 'file)
368
369 (defcustom nnmail-treat-duplicates 'warn
370   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
371 Three values are valid: nil, which means that nnmail is not to keep a
372 Message-ID cache; `warn', which means that nnmail should insert extra
373 headers to warn the user about the duplication (this is the default);
374 and `delete', which means that nnmail will delete duplicated mails.
375
376 This variable can also be a function.  It will be called from a buffer
377 narrowed to the article in question with the Message-ID as a
378 parameter.  It should return nil, `warn' or `delete'."
379   :group 'nnmail-duplicate
380   :type '(choice (const :tag "off" nil)
381                  (const warn)
382                  (const delete)))
383
384 (defcustom nnmail-extra-headers nil
385   "*Extra headers to parse."
386   :group 'nnmail
387   :type '(repeat symbol))
388
389 (defcustom nnmail-split-header-length-limit 512
390   "Header lines longer than this limit are excluded from the split function."
391   :group 'nnmail
392   :type 'integer)
393
394 ;;; Internal variables.
395
396 (defvar nnmail-split-history nil
397   "List of group/article elements that say where the previous split put messages.")
398
399 (defvar nnmail-current-spool nil)
400
401 (defvar nnmail-split-fancy-syntax-table nil
402   "Syntax table used by `nnmail-split-fancy'.")
403 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
404   (setq nnmail-split-fancy-syntax-table
405         (copy-syntax-table (standard-syntax-table)))
406   ;; support the %-hack
407   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
408
409 (defvar nnmail-prepare-save-mail-hook nil
410   "Hook called before saving mail.")
411
412 (defvar nnmail-split-tracing nil)
413 (defvar nnmail-split-trace nil)
414
415 \f
416
417 (defconst nnmail-version "nnmail 1.0"
418   "nnmail version.")
419
420 \f
421
422 (defun nnmail-request-post (&optional server)
423   (mail-send-and-exit nil))
424
425 (defvar nnmail-file-coding-system 'binary
426   "Coding system used in nnmail.")
427
428 (defvar nnmail-file-coding-system-1
429   (if (string-match "nt" system-configuration)
430       'raw-text-dos 'binary)
431   "Another coding system used in nnmail.")
432
433 (defvar nnmail-incoming-coding-system
434   mm-text-coding-system
435   "Coding system used in reading inbox")
436
437 (defun nnmail-find-file (file)
438   "Insert FILE in server buffer safely."
439   (set-buffer nntp-server-buffer)
440   (delete-region (point-min) (point-max))
441   (let ((format-alist nil)
442         (after-insert-file-functions nil))
443     (condition-case ()
444         (let ((coding-system-for-read nnmail-file-coding-system)
445               (auto-mode-alist (nnheader-auto-mode-alist))
446               (pathname-coding-system nnmail-file-coding-system))
447           (insert-file-contents file)
448           t)
449       (file-error nil))))
450
451 (defvar nnmail-pathname-coding-system 'binary
452   "*Coding system for pathname.")
453
454 (defun nnmail-group-pathname (group dir &optional file)
455   "Make pathname for GROUP."
456   (concat
457    (let ((dir (file-name-as-directory (expand-file-name dir))))
458      (setq group (nnheader-translate-file-chars group))
459      ;; If this directory exists, we use it directly.
460      (if (or nnmail-use-long-file-names
461              (file-directory-p (concat dir group)))
462          (concat dir group "/")
463        ;; If not, we translate dots into slashes.
464        (concat dir
465                (mm-encode-coding-string
466                 (nnheader-replace-chars-in-string group ?. ?/)
467                 nnmail-pathname-coding-system)
468                "/")))
469    (or file "")))
470
471 (defun nnmail-get-active ()
472   "Returns an assoc of group names and active ranges.
473 nn*-request-list should have been called before calling this function."
474   (let (group-assoc)
475     ;; Go through all groups from the active list.
476     (save-excursion
477       (set-buffer nntp-server-buffer)
478       (goto-char (point-min))
479       (while (re-search-forward
480               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
481         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
482         (push (list (match-string 1)
483                     (cons (string-to-int (match-string 3))
484                           (string-to-int (match-string 2))))
485               group-assoc)))
486     group-assoc))
487
488 (defvar nnmail-active-file-coding-system 'binary
489   "*Coding system for active file.")
490
491 (defun nnmail-save-active (group-assoc file-name)
492   "Save GROUP-ASSOC in ACTIVE-FILE."
493   (let ((coding-system-for-write nnmail-active-file-coding-system))
494     (when file-name
495       (with-temp-file file-name
496         (nnmail-generate-active group-assoc)))))
497
498 (defun nnmail-generate-active (alist)
499   "Generate an active file from group-alist ALIST."
500   (erase-buffer)
501   (let (group)
502     (while (setq group (pop alist))
503       (insert (format "%s %d %d y\n" (car group) (cdadr group)
504                       (caadr group))))))
505
506 (defun nnmail-get-split-group (file source)
507   "Find out whether this FILE is to be split into GROUP only.
508 If SOURCE is a directory spec, try to return the group name component."
509   (if (eq (car source) 'directory)
510       (let ((file (file-name-nondirectory file)))
511         (mail-source-bind (directory source)
512           (if (string-match (concat (regexp-quote suffix) "$") file)
513               (substring file 0 (match-beginning 0))
514             nil)))
515     nil))
516
517 (defun nnmail-process-babyl-mail-format (func artnum-func)
518   (let ((case-fold-search t)
519         start message-id content-length do-search end)
520     (while (not (eobp))
521       (goto-char (point-min))
522       (re-search-forward
523        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
524       (goto-char (match-end 0))
525       (delete-region (match-beginning 0) (match-end 0))
526       (narrow-to-region
527        (setq start (point))
528        (progn
529          ;; Skip all the headers in case there are more "From "s...
530          (or (search-forward "\n\n" nil t)
531              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
532              (search-forward "\1f\f"))
533          (point)))
534       ;; Unquote the ">From " line, if any.
535       (goto-char (point-min))
536       (when (looking-at ">From ")
537         (replace-match "X-From-Line: ") )
538       (run-hooks 'nnmail-prepare-incoming-header-hook)
539       (goto-char (point-max))
540       ;; Find the Message-ID header.
541       (save-excursion
542         (if (re-search-backward
543              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
544             (setq message-id (buffer-substring (match-beginning 1)
545                                                (match-end 1)))
546           ;; There is no Message-ID here, so we create one.
547           (save-excursion
548             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
549               (beginning-of-line)
550               (insert "Original-")))
551           (forward-line -1)
552           (insert "Message-ID: " (setq message-id (nnmail-message-id))
553                   "\n")))
554       ;; Look for a Content-Length header.
555       (if (not (save-excursion
556                  (and (re-search-backward
557                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
558                       (setq content-length (string-to-int
559                                             (buffer-substring
560                                              (match-beginning 1)
561                                              (match-end 1))))
562                       ;; We destroy the header, since none of
563                       ;; the backends ever use it, and we do not
564                       ;; want to confuse other mailers by having
565                       ;; a (possibly) faulty header.
566                       (progn (insert "X-") t))))
567           (setq do-search t)
568         (widen)
569         (if (or (= (+ (point) content-length) (point-max))
570                 (save-excursion
571                   (goto-char (+ (point) content-length))
572                   (looking-at "\1f")))
573             (progn
574               (goto-char (+ (point) content-length))
575               (setq do-search nil))
576           (setq do-search t)))
577       (widen)
578       ;; Go to the beginning of the next article - or to the end
579       ;; of the buffer.
580       (when do-search
581         (if (re-search-forward "^\1f" nil t)
582             (goto-char (match-beginning 0))
583           (goto-char (1- (point-max)))))
584       (delete-char 1)                   ; delete ^_
585       (save-excursion
586         (save-restriction
587           (narrow-to-region start (point))
588           (goto-char (point-min))
589           (nnmail-check-duplication message-id func artnum-func)
590           (setq end (point-max))))
591       (goto-char end))))
592
593 (defsubst nnmail-search-unix-mail-delim ()
594   "Put point at the beginning of the next Unix mbox message."
595   ;; Algorithm used to find the the next article in the
596   ;; brain-dead Unix mbox format:
597   ;;
598   ;; 1) Search for "^From ".
599   ;; 2) If we find it, then see whether the previous
600   ;;    line is blank and the next line looks like a header.
601   ;; Then it's possible that this is a mail delim, and we use it.
602   (let ((case-fold-search nil)
603         found)
604     (while (not found)
605       (if (not (re-search-forward "^From " nil t))
606           (setq found 'no)
607         (save-excursion
608           (beginning-of-line)
609           (when (and (or (bobp)
610                          (save-excursion
611                            (forward-line -1)
612                            (eq (char-after) ?\n)))
613                      (save-excursion
614                        (forward-line 1)
615                        (while (looking-at ">From \\|From ")
616                          (forward-line 1))
617                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
618             (setq found 'yes)))))
619     (beginning-of-line)
620     (eq found 'yes)))
621
622 (defun nnmail-search-unix-mail-delim-backward ()
623   "Put point at the beginning of the current Unix mbox message."
624   ;; Algorithm used to find the the next article in the
625   ;; brain-dead Unix mbox format:
626   ;;
627   ;; 1) Search for "^From ".
628   ;; 2) If we find it, then see whether the previous
629   ;;    line is blank and the next line looks like a header.
630   ;; Then it's possible that this is a mail delim, and we use it.
631   (let ((case-fold-search nil)
632         found)
633     (while (not found)
634       (if (not (re-search-backward "^From " nil t))
635           (setq found 'no)
636         (save-excursion
637           (beginning-of-line)
638           (when (and (or (bobp)
639                          (save-excursion
640                            (forward-line -1)
641                            (eq (char-after) ?\n)))
642                      (save-excursion
643                        (forward-line 1)
644                        (while (looking-at ">From \\|From ")
645                          (forward-line 1))
646                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
647             (setq found 'yes)))))
648     (beginning-of-line)
649     (eq found 'yes)))
650
651 (defun nnmail-process-unix-mail-format (func artnum-func)
652   (let ((case-fold-search t)
653         start message-id content-length end skip head-end)
654     (goto-char (point-min))
655     (if (not (and (re-search-forward "^From " nil t)
656                   (goto-char (match-beginning 0))))
657         ;; Possibly wrong format?
658         (progn
659           (pop-to-buffer (nnheader-find-file-noselect nnmail-current-spool))
660           (error "Error, unknown mail format! (Possibly corrupted.)"))
661       ;; Carry on until the bitter end.
662       (while (not (eobp))
663         (setq start (point)
664               end nil)
665         ;; Find the end of the head.
666         (narrow-to-region
667          start
668          (if (search-forward "\n\n" nil t)
669              (1- (point))
670            ;; This will never happen, but just to be on the safe side --
671            ;; if there is no head-body delimiter, we search a bit manually.
672            (while (and (looking-at "From \\|[^ \t]+:")
673                        (not (eobp)))
674              (forward-line 1))
675            (point)))
676         ;; Find the Message-ID header.
677         (goto-char (point-min))
678         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
679             (setq message-id (match-string 1))
680           (save-excursion
681             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
682               (beginning-of-line)
683               (insert "Original-")))
684           ;; There is no Message-ID here, so we create one.
685           (forward-line 1)
686           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
687         ;; Look for a Content-Length header.
688         (goto-char (point-min))
689         (if (not (re-search-forward
690                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
691             (setq content-length nil)
692           (setq content-length (string-to-int (match-string 1)))
693           ;; We destroy the header, since none of the backends ever
694           ;; use it, and we do not want to confuse other mailers by
695           ;; having a (possibly) faulty header.
696           (beginning-of-line)
697           (insert "X-"))
698         (run-hooks 'nnmail-prepare-incoming-header-hook)
699         ;; Find the end of this article.
700         (goto-char (point-max))
701         (widen)
702         (setq head-end (point))
703         ;; We try the Content-Length value.  The idea: skip over the header
704         ;; separator, then check what happens content-length bytes into the
705         ;; message body.  This should be either the end ot the buffer, the
706         ;; message separator or a blank line followed by the separator.
707         ;; The blank line should probably be deleted.  If neither of the
708         ;; three is met, the content-length header is probably invalid.
709         (when content-length
710           (forward-line 1)
711           (setq skip (+ (point) content-length))
712           (goto-char skip)
713           (cond ((or (= skip (point-max))
714                      (= (1+ skip) (point-max)))
715                  (setq end (point-max)))
716                 ((looking-at "From ")
717                  (setq end skip))
718                 ((looking-at "[ \t]*\n\\(From \\)")
719                  (setq end (match-beginning 1)))
720                 (t (setq end nil))))
721         (if end
722             (goto-char end)
723           ;; No Content-Length, so we find the beginning of the next
724           ;; article or the end of the buffer.
725           (goto-char head-end)
726           (or (nnmail-search-unix-mail-delim)
727               (goto-char (point-max))))
728         ;; Allow the backend to save the article.
729         (save-excursion
730           (save-restriction
731             (narrow-to-region start (point))
732             (goto-char (point-min))
733             (nnmail-check-duplication message-id func artnum-func)
734             (setq end (point-max))))
735         (goto-char end)))))
736
737 (defun nnmail-process-mmdf-mail-format (func artnum-func)
738   (let ((delim "^\^A\^A\^A\^A$")
739         (case-fold-search t)
740         start message-id end)
741     (goto-char (point-min))
742     (if (not (and (re-search-forward delim nil t)
743                   (forward-line 1)))
744         ;; Possibly wrong format?
745         (progn
746           (pop-to-buffer (nnheader-find-file-noselect nnmail-current-spool))
747           (error "Error, unknown mail format! (Possibly corrupted.)"))
748       ;; Carry on until the bitter end.
749       (while (not (eobp))
750         (setq start (point))
751         ;; Find the end of the head.
752         (narrow-to-region
753          start
754          (if (search-forward "\n\n" nil t)
755              (1- (point))
756            ;; This will never happen, but just to be on the safe side --
757            ;; if there is no head-body delimiter, we search a bit manually.
758            (while (and (looking-at "From \\|[^ \t]+:")
759                        (not (eobp)))
760              (forward-line 1))
761            (point)))
762         ;; Find the Message-ID header.
763         (goto-char (point-min))
764         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
765             (setq message-id (match-string 1))
766           ;; There is no Message-ID here, so we create one.
767           (save-excursion
768             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
769               (beginning-of-line)
770               (insert "Original-")))
771           (forward-line 1)
772           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
773         (run-hooks 'nnmail-prepare-incoming-header-hook)
774         ;; Find the end of this article.
775         (goto-char (point-max))
776         (widen)
777         (if (re-search-forward delim nil t)
778             (beginning-of-line)
779           (goto-char (point-max)))
780         ;; Allow the backend to save the article.
781         (save-excursion
782           (save-restriction
783             (narrow-to-region start (point))
784             (goto-char (point-min))
785             (nnmail-check-duplication message-id func artnum-func)
786             (setq end (point-max))))
787         (goto-char end)
788         (forward-line 2)))))
789
790 (defun nnmail-process-maildir-mail-format (func artnum-func)
791 ; In a maildir, every file contains exactly one mail
792   (let ((case-fold-search t)
793         message-id)
794     (goto-char (point-min))
795     ;; Find the end of the head.
796     (narrow-to-region
797      (point-min)
798      (if (search-forward "\n\n" nil t)
799          (1- (point))
800        ;; This will never happen, but just to be on the safe side --
801        ;; if there is no head-body delimiter, we search a bit manually.
802        (while (and (looking-at "From \\|[^ \t]+:")
803                    (not (eobp)))
804          (forward-line 1)
805          (point))))
806     ;; Find the Message-ID header.
807     (goto-char (point-min))
808     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
809         (setq message-id (match-string 1))
810       ;; There is no Message-ID here, so we create one.
811       (save-excursion
812             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
813           (beginning-of-line)
814           (insert "Original-")))
815       (forward-line 1)
816       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
817     (run-hooks 'nnmail-prepare-incoming-header-hook)
818     ;; Allow the backend to save the article.
819     (widen)
820     (save-excursion
821         (goto-char (point-min))
822         (nnmail-check-duplication message-id func artnum-func))))
823
824 (defun nnmail-split-incoming (incoming func &optional exit-func
825                                        group artnum-func)
826   "Go through the entire INCOMING file and pick out each individual mail.
827 FUNC will be called with the buffer narrowed to each mail."
828   (let (;; If this is a group-specific split, we bind the split
829         ;; methods to just this group.
830         (nnmail-split-methods (if (and group
831                                        (not nnmail-resplit-incoming))
832                                   (list (list group ""))
833                                 nnmail-split-methods)))
834     (save-excursion
835       ;; Insert the incoming file.
836       (set-buffer (get-buffer-create " *nnmail incoming*"))
837       (erase-buffer)
838       (let ((nnheader-file-coding-system nnmail-incoming-coding-system))
839         (nnheader-insert-file-contents incoming))
840       (unless (zerop (buffer-size))
841         (goto-char (point-min))
842         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
843         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
844         ;; use the former when fetching from a mailbox, the latter when
845         ;; fetching from a file.
846         (cond ((or (looking-at "\^L")
847                    (looking-at "BABYL OPTIONS:"))
848                (nnmail-process-babyl-mail-format func artnum-func))
849               ((looking-at "\^A\^A\^A\^A")
850                (nnmail-process-mmdf-mail-format func artnum-func))
851               ((looking-at "Return-Path:")
852                (nnmail-process-maildir-mail-format func artnum-func))
853               (t
854                (nnmail-process-unix-mail-format func artnum-func))))
855       (when exit-func
856         (funcall exit-func))
857       (kill-buffer (current-buffer)))))
858
859 (defun nnmail-article-group (func &optional trace)
860   "Look at the headers and return an alist of groups that match.
861 FUNC will be called with the group name to determine the article number."
862   (let ((methods nnmail-split-methods)
863         (obuf (current-buffer))
864         (beg (point-min))
865         end group-art method regrepp)
866     (if (and (sequencep methods)
867              (= (length methods) 1))
868         ;; If there is only just one group to put everything in, we
869         ;; just return a list with just this one method in.
870         (setq group-art
871               (list (cons (caar methods) (funcall func (caar methods)))))
872       ;; We do actual comparison.
873       (save-excursion
874         ;; Find headers.
875         (goto-char beg)
876         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
877         (set-buffer nntp-server-buffer)
878         (erase-buffer)
879         ;; Copy the headers into the work buffer.
880         (insert-buffer-substring obuf beg end)
881         ;; Fold continuation lines.
882         (goto-char (point-min))
883         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
884           (replace-match " " t t))
885         ;; Nuke pathologically long headers.  Since Gnus applies
886         ;; pathologically complex regexps to the buffer, lines
887         ;; that are looong will take longer than the Universe's
888         ;; existence to process.
889         (goto-char (point-min))
890         (while (not (eobp))
891           (unless (< (move-to-column nnmail-split-header-length-limit)
892                      nnmail-split-header-length-limit)
893             (delete-region (point) (progn (end-of-line) (point))))
894           (forward-line 1))
895         ;; Allow washing.
896         (goto-char (point-min))
897         (run-hooks 'nnmail-split-hook)
898         (when (setq nnmail-split-tracing trace)
899           (setq nnmail-split-trace nil))
900         (if (and (symbolp nnmail-split-methods)
901                  (fboundp nnmail-split-methods))
902             (let ((split
903                    (condition-case nil
904                        ;; `nnmail-split-methods' is a function, so we
905                        ;; just call this function here and use the
906                        ;; result.
907                        (or (funcall nnmail-split-methods)
908                            '("bogus"))
909                      (error
910                       (nnheader-message 5
911                        "Error in `nnmail-split-methods'; using `bogus' mail group")
912                       (sit-for 1)
913                       '("bogus")))))
914               (setq split (gnus-remove-duplicates split))
915               ;; The article may be "cross-posted" to `junk'.  What
916               ;; to do?  Just remove the `junk' spec.  Don't really
917               ;; see anything else to do...
918               (let (elem)
919                 (while (setq elem (car (memq 'junk split)))
920                   (setq split (delq elem split))))
921               (when split
922                 (setq group-art
923                       (mapcar
924                        (lambda (group) (cons group (funcall func group)))
925                        split))))
926           ;; Go through the split methods to find a match.
927           (while (and methods
928                       (or nnmail-crosspost
929                           (not group-art)))
930             (goto-char (point-max))
931             (setq method (pop methods)
932                   regrepp nil)
933             (if (or methods
934                     (not (equal "" (nth 1 method))))
935                 (when (and
936                        (ignore-errors
937                          (if (stringp (nth 1 method))
938                              (progn
939                                (setq regrepp
940                                      (string-match "\\\\[0-9&]" (car method)))
941                                (re-search-backward (cadr method) nil t))
942                            ;; Function to say whether this is a match.
943                            (funcall (nth 1 method) (car method))))
944                        ;; Don't enter the article into the same
945                        ;; group twice.
946                        (not (assoc (car method) group-art)))
947                   (push (cons (if regrepp
948                                   (nnmail-expand-newtext (car method))
949                                 (car method))
950                               (funcall func (car method)))
951                         group-art))
952               ;; This is the final group, which is used as a
953               ;; catch-all.
954               (unless group-art
955                 (setq group-art
956                       (list (cons (car method)
957                                   (funcall func (car method)))))))))
958         ;; Produce a trace if non-empty.
959         (when (and trace nnmail-split-trace)
960           (let ((trace (nreverse nnmail-split-trace))
961                 (restore (current-buffer)))
962             (nnheader-set-temp-buffer "*Split Trace*")
963             (gnus-add-buffer)
964             (while trace
965               (insert (car trace) "\n")
966               (setq trace (cdr trace)))
967             (goto-char (point-min))
968             (gnus-configure-windows 'split-trace)
969             (set-buffer restore)))
970         ;; See whether the split methods returned `junk'.
971         (if (equal group-art '(junk))
972             nil
973           ;; The article may be "cross-posted" to `junk'.  What
974           ;; to do?  Just remove the `junk' spec.  Don't really
975           ;; see anything else to do...
976           (let (elem)
977             (while (setq elem (car (memq 'junk group-art)))
978               (setq group-art (delq elem group-art)))
979             (nreverse group-art)))))))
980
981 (defun nnmail-insert-lines ()
982   "Insert how many lines there are in the body of the mail.
983 Return the number of characters in the body."
984   (let (lines chars)
985     (save-excursion
986       (goto-char (point-min))
987       (when (search-forward "\n\n" nil t)
988         (setq chars (- (point-max) (point)))
989         (setq lines (count-lines (point) (point-max)))
990         (forward-char -1)
991         (save-excursion
992           (when (re-search-backward "^Lines: " nil t)
993             (delete-region (point) (progn (forward-line 1) (point)))))
994         (beginning-of-line)
995         (insert (format "Lines: %d\n" (max lines 0)))
996         chars))))
997
998 (defun nnmail-insert-xref (group-alist)
999   "Insert an Xref line based on the (group . article) alist."
1000   (save-excursion
1001     (goto-char (point-min))
1002     (when (search-forward "\n\n" nil t)
1003       (forward-char -1)
1004       (when (re-search-backward "^Xref: " nil t)
1005         (delete-region (match-beginning 0)
1006                        (progn (forward-line 1) (point))))
1007       (insert (format "Xref: %s" (system-name)))
1008       (while group-alist
1009         (insert (format " %s:%d"
1010                         (mm-encode-coding-string
1011                          (caar group-alist)
1012                          nnmail-pathname-coding-system)
1013                         (cdar group-alist)))
1014         (setq group-alist (cdr group-alist)))
1015       (insert "\n"))))
1016
1017 ;;; Message washing functions
1018
1019 (defun nnmail-remove-leading-whitespace ()
1020   "Remove excessive whitespace from all headers."
1021   (goto-char (point-min))
1022   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1023     (replace-match "\\1" t)))
1024
1025 (defun nnmail-remove-list-identifiers ()
1026   "Remove list identifiers from Subject headers."
1027   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1028                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1029     (when regexp
1030       (goto-char (point-min))
1031       (when (re-search-forward
1032              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1033              nil t)
1034         (delete-region (match-beginning 2) (match-end 0))))))
1035
1036 (defun nnmail-remove-tabs ()
1037   "Translate TAB characters into SPACE characters."
1038   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1039
1040 (defun nnmail-fix-eudora-headers ()
1041   "Eudora has a broken References line, but an OK In-Reply-To."
1042   (goto-char (point-min))
1043   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1044     (goto-char (point-min))
1045     (when (re-search-forward "^References:" nil t)
1046       (beginning-of-line)
1047       (insert "X-Gnus-Broken-Eudora-"))))
1048
1049 (custom-add-option 'nnmail-prepare-incoming-header-hook
1050                    'nnmail-fix-eudora-headers)
1051
1052 ;;; Utility functions
1053
1054 (defun nnmail-split-fancy ()
1055   "Fancy splitting method.
1056 See the documentation for the variable `nnmail-split-fancy' for documentation."
1057   (let ((syntab (syntax-table)))
1058     (unwind-protect
1059         (progn
1060           (set-syntax-table nnmail-split-fancy-syntax-table)
1061           (nnmail-split-it nnmail-split-fancy))
1062       (set-syntax-table syntab))))
1063
1064 (defvar nnmail-split-cache nil)
1065 ;; Alist of split expressions their equivalent regexps.
1066
1067 (defun nnmail-split-it (split)
1068   ;; Return a list of groups matching SPLIT.
1069   (let (cached-pair)
1070     (cond
1071      ;; nil split
1072      ((null split)
1073       nil)
1074
1075      ;; A group name.  Do the \& and \N subs into the string.
1076      ((stringp split)
1077       (when nnmail-split-tracing
1078         (push (format "\"%s\"" split) nnmail-split-trace))
1079       (list (nnmail-expand-newtext split)))
1080
1081      ;; Junk the message.
1082      ((eq split 'junk)
1083       (when nnmail-split-tracing
1084         (push "junk" nnmail-split-trace))
1085       (list 'junk))
1086
1087      ;; Builtin & operation.
1088      ((eq (car split) '&)
1089       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1090
1091      ;; Builtin | operation.
1092      ((eq (car split) '|)
1093       (let (done)
1094         (while (and (not done) (cdr split))
1095           (setq split (cdr split)
1096                 done (nnmail-split-it (car split))))
1097         done))
1098
1099      ;; Builtin : operation.
1100      ((eq (car split) ':)
1101       (nnmail-split-it (save-excursion (eval (cdr split)))))
1102
1103      ;; Builtin ! operation.
1104      ((eq (car split) '!)
1105       (funcall (cadr split) (nnmail-split-it (caddr split))))
1106
1107      ;; Check the cache for the regexp for this split.
1108      ((setq cached-pair (assq split nnmail-split-cache))
1109       (goto-char (point-max))
1110       ;; FIX FIX FIX problem with re-search-backward is that if you have
1111       ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1112       ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1113       ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1114       ;; if the cc line is a later header, even though the other choice
1115       ;; is probably better.  Also, this routine won't do a crosspost
1116       ;; when there are two different matches.
1117       ;; I guess you could just make this more determined, and it could
1118       ;; look for still more matches prior to this one, and recurse
1119       ;; on each of the multiple matches hit.  Of course, then you'd
1120       ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1121       ;; removed duplicates, since there might be more of those.
1122       ;; I guess we could also remove duplicates in the & split case, since
1123       ;; that's the only thing that can introduce them.
1124       (when (re-search-backward (cdr cached-pair) nil t)
1125         (when nnmail-split-tracing
1126           (push (cdr cached-pair) nnmail-split-trace))
1127         ;; Someone might want to do a \N sub on this match, so get the
1128         ;; correct match positions.
1129         (goto-char (match-end 0))
1130         (let ((value (nth 1 split)))
1131           (re-search-backward (if (symbolp value)
1132                                   (cdr (assq value nnmail-split-abbrev-alist))
1133                                 value)
1134                               (match-end 1)))
1135         (nnmail-split-it (nth 2 split))))
1136
1137      ;; Not in cache, compute a regexp for the field/value pair.
1138      (t
1139       (let* ((field (nth 0 split))
1140              (value (nth 1 split))
1141              (regexp (concat "^\\(\\("
1142                              (if (symbolp field)
1143                                  (cdr (assq field nnmail-split-abbrev-alist))
1144                                field)
1145                              "\\):.*\\)\\<\\("
1146                              (if (symbolp value)
1147                                  (cdr (assq value nnmail-split-abbrev-alist))
1148                                value)
1149                              "\\)\\>")))
1150         (push (cons split regexp) nnmail-split-cache)
1151         ;; Now that it's in the cache, just call nnmail-split-it again
1152         ;; on the same split, which will find it immediately in the cache.
1153         (nnmail-split-it split))))))
1154
1155 (defun nnmail-expand-newtext (newtext)
1156   (let ((len (length newtext))
1157         (pos 0)
1158         c expanded beg N did-expand)
1159     (while (< pos len)
1160       (setq beg pos)
1161       (while (and (< pos len)
1162                   (not (= (aref newtext pos) ?\\)))
1163         (setq pos (1+ pos)))
1164       (unless (= beg pos)
1165         (push (substring newtext beg pos) expanded))
1166       (when (< pos len)
1167         ;; We hit a \; expand it.
1168         (setq did-expand t
1169               pos (1+ pos)
1170               c (aref newtext pos))
1171         (if (not (or (= c ?\&)
1172                      (and (>= c ?1)
1173                           (<= c ?9))))
1174             ;; \ followed by some character we don't expand.
1175             (push (char-to-string c) expanded)
1176           ;; \& or \N
1177           (if (= c ?\&)
1178               (setq N 0)
1179             (setq N (- c ?0)))
1180           (when (match-beginning N)
1181             (push (buffer-substring (match-beginning N) (match-end N))
1182                   expanded))))
1183       (setq pos (1+ pos)))
1184     (if did-expand
1185         (apply 'concat (nreverse expanded))
1186       newtext)))
1187
1188 ;; Activate a backend only if it isn't already activated.
1189 ;; If FORCE, re-read the active file even if the backend is
1190 ;; already activated.
1191 (defun nnmail-activate (backend &optional force)
1192   (nnheader-init-server-buffer)
1193   (let (file timestamp file-time)
1194     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1195             force
1196             (and (setq file (ignore-errors
1197                               (symbol-value (intern (format "%s-active-file"
1198                                                             backend)))))
1199                  (setq file-time (nth 5 (file-attributes file)))
1200                  (or (not
1201                       (setq timestamp
1202                             (condition-case ()
1203                                 (symbol-value (intern
1204                                                (format "%s-active-timestamp"
1205                                                        backend)))
1206                               (error 'none))))
1207                      (not (consp timestamp))
1208                      (equal timestamp '(0 0))
1209                      (> (nth 0 file-time) (nth 0 timestamp))
1210                      (and (= (nth 0 file-time) (nth 0 timestamp))
1211                           (> (nth 1 file-time) (nth 1 timestamp))))))
1212         (save-excursion
1213           (or (eq timestamp 'none)
1214               (set (intern (format "%s-active-timestamp" backend))
1215                    file-time))
1216           (funcall (intern (format "%s-request-list" backend)))))
1217     t))
1218
1219 (defun nnmail-message-id ()
1220   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1221
1222 ;;;
1223 ;;; nnmail duplicate handling
1224 ;;;
1225
1226 (defvar nnmail-cache-buffer nil)
1227
1228 (defun nnmail-cache-open ()
1229   (if (or (not nnmail-treat-duplicates)
1230           (and nnmail-cache-buffer
1231                (buffer-name nnmail-cache-buffer)))
1232       ()                                ; The buffer is open.
1233     (save-excursion
1234       (set-buffer
1235        (setq nnmail-cache-buffer
1236              (get-buffer-create " *nnmail message-id cache*")))
1237       (when (file-exists-p nnmail-message-id-cache-file)
1238         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1239       (set-buffer-modified-p nil)
1240       (current-buffer))))
1241
1242 (defun nnmail-cache-close ()
1243   (when (and nnmail-cache-buffer
1244              nnmail-treat-duplicates
1245              (buffer-name nnmail-cache-buffer)
1246              (buffer-modified-p nnmail-cache-buffer))
1247     (save-excursion
1248       (set-buffer nnmail-cache-buffer)
1249       ;; Weed out the excess number of Message-IDs.
1250       (goto-char (point-max))
1251       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1252         (progn
1253           (beginning-of-line)
1254           (delete-region (point-min) (point))))
1255       ;; Save the buffer.
1256       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1257           (make-directory (file-name-directory nnmail-message-id-cache-file)
1258                           t))
1259       (nnmail-write-region (point-min) (point-max)
1260                            nnmail-message-id-cache-file nil 'silent)
1261       (set-buffer-modified-p nil)
1262       (setq nnmail-cache-buffer nil)
1263       (kill-buffer (current-buffer)))))
1264
1265 (defun nnmail-cache-insert (id)
1266   (when nnmail-treat-duplicates
1267     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1268       (nnmail-cache-open))
1269     (save-excursion
1270       (set-buffer nnmail-cache-buffer)
1271       (goto-char (point-max))
1272       (insert id "\n"))))
1273
1274 (defun nnmail-cache-id-exists-p (id)
1275   (when nnmail-treat-duplicates
1276     (save-excursion
1277       (set-buffer nnmail-cache-buffer)
1278       (goto-char (point-max))
1279       (search-backward id nil t))))
1280
1281 (defun nnmail-fetch-field (header)
1282   (save-excursion
1283     (save-restriction
1284       (message-narrow-to-head)
1285       (message-fetch-field header))))
1286
1287 (defun nnmail-check-duplication (message-id func artnum-func)
1288   (run-hooks 'nnmail-prepare-incoming-message-hook)
1289   ;; If this is a duplicate message, then we do not save it.
1290   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1291          (case-fold-search t)
1292          (action (when duplication
1293                    (cond
1294                     ((memq nnmail-treat-duplicates '(warn delete))
1295                      nnmail-treat-duplicates)
1296                     ((nnheader-functionp nnmail-treat-duplicates)
1297                      (funcall nnmail-treat-duplicates message-id))
1298                     (t
1299                      nnmail-treat-duplicates))))
1300          group-art)
1301     ;; We insert a line that says what the mail source is.
1302     (let ((case-fold-search t))
1303       (goto-char (point-min))
1304       (re-search-forward "^message-id[ \t]*:" nil t)
1305       (beginning-of-line)
1306       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1307
1308     ;; Let the backend save the article (or not).
1309     (cond
1310      ((not duplication)
1311       (funcall func (setq group-art
1312                           (nreverse (nnmail-article-group artnum-func))))
1313       (nnmail-cache-insert message-id))
1314      ((eq action 'delete)
1315       (setq group-art nil))
1316      ((eq action 'warn)
1317       ;; We insert a warning.
1318       (let ((case-fold-search t))
1319         (goto-char (point-min))
1320         (re-search-forward "^message-id[ \t]*:" nil t)
1321         (beginning-of-line)
1322         (insert
1323          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1324         (funcall func (setq group-art
1325                             (nreverse (nnmail-article-group artnum-func))))))
1326      (t
1327       (funcall func (setq group-art
1328                           (nreverse (nnmail-article-group artnum-func))))))
1329     ;; Add the group-art list to the history list.
1330     (if group-art
1331         (push group-art nnmail-split-history)
1332       (delete-region (point-min) (point-max)))))
1333
1334 ;;; Get new mail.
1335
1336 (defvar nnmail-fetched-sources nil)
1337
1338 (defun nnmail-get-value (&rest args)
1339   (let ((sym (intern (apply 'format args))))
1340     (when (boundp sym)
1341       (symbol-value sym))))
1342
1343 (defun nnmail-get-new-mail (method exit-func temp
1344                                    &optional group spool-func)
1345   "Read new incoming mail."
1346   (let* ((sources (if (listp nnmail-spool-file) nnmail-spool-file
1347                     (list nnmail-spool-file)))
1348          (group-in group)
1349          (i 0)
1350          nnmail-current-spool incoming incomings source)
1351     (when (and (nnmail-get-value "%s-get-new-mail" method)
1352                nnmail-spool-file)
1353       ;; We first activate all the groups.
1354       (nnmail-activate method)
1355       ;; Allow the user to hook.
1356       (run-hooks 'nnmail-pre-get-new-mail-hook)
1357       ;; Open the message-id cache.
1358       (nnmail-cache-open)
1359       ;; The we go through all the existing mail source specification
1360       ;; and fetch the mail from each.
1361       (while (setq source (pop sources))
1362         ;; Be compatible with old values.
1363         (cond
1364          ((stringp source)
1365           (setq source
1366                 (cond
1367                  ((string-match "^po:" source)
1368                   (list 'pop :user (substring source (match-end 0))))
1369                  ((file-directory-p source)
1370                   (list 'directory :path source))
1371                  (t
1372                   (list 'file :path source)))))
1373          ((eq source 'procmail)
1374           (message "Invalid value for nnmail-spool-file: `procmail'")
1375           nil))
1376         ;; Hack to only fetch the contents of a single group's spool file.
1377         (when (and (eq (car source) 'directory)
1378                    group)
1379           (setq source (append source
1380                                (list :predicate
1381                                      `(lambda (file)
1382                                         (string-match 
1383                                          ,(concat (regexp-quote group) "$")
1384                                          file))))))
1385         (when nnmail-fetched-sources
1386           (if (member source nnmail-fetched-sources)
1387               (setq source nil)
1388             (push source nnmail-fetched-sources)))
1389         (when source
1390           (nnheader-message 4 "%s: Reading incoming mail from %s..."
1391                             method (car source))
1392           (when (mail-source-fetch
1393                  source
1394                  `(lambda (file orig-file)
1395                     (nnmail-split-incoming
1396                      file ',(intern (format "%s-save-mail" method))
1397                      ',spool-func (nnmail-get-split-group orig-file source)
1398                      ',(intern (format "%s-active-number" method)))))
1399             (incf i))))
1400       ;; If we did indeed read any incoming spools, we save all info.
1401       (unless (zerop i)
1402         (nnmail-save-active
1403          (nnmail-get-value "%s-group-alist" method)
1404          (nnmail-get-value "%s-active-file" method))
1405         (when exit-func
1406           (funcall exit-func))
1407         (run-hooks 'nnmail-read-incoming-hook)
1408         (nnheader-message 4 "%s: Reading incoming mail...done" method))
1409       ;; Close the message-id cache.
1410       (nnmail-cache-close)
1411       ;; Allow the user to hook.
1412       (run-hooks 'nnmail-post-get-new-mail-hook))))
1413
1414 (defun nnmail-expired-article-p (group time force &optional inhibit)
1415   "Say whether an article that is TIME old in GROUP should be expired."
1416   (if force
1417       t
1418     (let ((days (or (and nnmail-expiry-wait-function
1419                          (funcall nnmail-expiry-wait-function group))
1420                     nnmail-expiry-wait)))
1421       (cond ((or (eq days 'never)
1422                  (and (not force)
1423                       inhibit))
1424              ;; This isn't an expirable group.
1425              nil)
1426             ((eq days 'immediate)
1427              ;; We expire all articles on sight.
1428              t)
1429             ((equal time '(0 0))
1430              ;; This is an ange-ftp group, and we don't have any dates.
1431              nil)
1432             ((numberp days)
1433              (setq days (days-to-time days))
1434              ;; Compare the time with the current time.
1435              (ignore-errors (time-less-p days (time-since time))))))))
1436
1437 (defun nnmail-check-syntax ()
1438   "Check (and modify) the syntax of the message in the current buffer."
1439   (save-restriction
1440     (message-narrow-to-head)
1441     (let ((case-fold-search t))
1442       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1443         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1444
1445 (defun nnmail-write-region (start end filename &optional append visit lockname)
1446   "Do a `write-region', and then set the file modes."
1447   (let ((coding-system-for-write nnmail-file-coding-system)
1448         (pathname-coding-system 'binary))
1449     (write-region start end filename append visit lockname)
1450     (set-file-modes filename nnmail-default-file-modes)))
1451
1452 ;;;
1453 ;;; Status functions
1454 ;;;
1455
1456 (defun nnmail-replace-status (name value)
1457   "Make status NAME and VALUE part of the current status line."
1458   (save-restriction
1459     (message-narrow-to-head)
1460     (let ((status (nnmail-decode-status)))
1461       (setq status (delq (member name status) status))
1462       (when value
1463         (push (cons name value) status))
1464       (message-remove-header "status")
1465       (goto-char (point-max))
1466       (insert "Status: " (nnmail-encode-status status) "\n"))))
1467
1468 (defun nnmail-decode-status ()
1469   "Return a status-value alist from STATUS."
1470   (goto-char (point-min))
1471   (when (re-search-forward "^Status: " nil t)
1472     (let (name value status)
1473       (save-restriction
1474         ;; Narrow to the status.
1475         (narrow-to-region
1476          (point)
1477          (if (re-search-forward "^[^ \t]" nil t)
1478              (1- (point))
1479            (point-max)))
1480         ;; Go through all elements and add them to the list.
1481         (goto-char (point-min))
1482         (while (re-search-forward "[^ \t=]+" nil t)
1483           (setq name (match-string 0))
1484           (if (not (eq (char-after) ?=))
1485               ;; Implied "yes".
1486               (setq value "yes")
1487             (forward-char 1)
1488             (if (not (eq (char-after) ?\"))
1489                 (if (not (looking-at "[^ \t]"))
1490                     ;; Implied "no".
1491                     (setq value "no")
1492                   ;; Unquoted value.
1493                   (setq value (match-string 0))
1494                   (goto-char (match-end 0)))
1495               ;; Quoted value.
1496               (setq value (read (current-buffer)))))
1497           (push (cons name value) status)))
1498       status)))
1499
1500 (defun nnmail-encode-status (status)
1501   "Return a status string from STATUS."
1502   (mapconcat
1503    (lambda (elem)
1504      (concat
1505       (car elem) "="
1506       (if (string-match "[ \t]" (cdr elem))
1507           (prin1-to-string (cdr elem))
1508         (cdr elem))))
1509    status " "))
1510
1511 (defun nnmail-split-history ()
1512   "Generate an overview of where the last mail split put articles."
1513   (interactive)
1514   (unless nnmail-split-history
1515     (error "No current split history"))
1516   (with-output-to-temp-buffer "*nnmail split history*"
1517     (let ((history nnmail-split-history)
1518           elem)
1519       (while (setq elem (pop history))
1520         (princ (mapconcat (lambda (ga)
1521                             (concat (car ga) ":" (int-to-string (cdr ga))))
1522                           elem
1523                           ", "))
1524         (princ "\n")))))
1525
1526 (defun nnmail-purge-split-history (group)
1527   "Remove all instances of GROUP from `nnmail-split-history'."
1528   (let ((history nnmail-split-history))
1529     (while history
1530       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1531                                       (car history)))
1532       (pop history))
1533     (setq nnmail-split-history (delq nil nnmail-split-history))))
1534
1535 (defun nnmail-new-mail-p (group)
1536   "Say whether GROUP has new mail."
1537   (let ((his nnmail-split-history)
1538         found)
1539     (while his
1540       (when (assoc group (pop his))
1541         (setq found t
1542               his nil)))
1543     found))
1544
1545 (defun nnmail-within-headers-p ()
1546   "Check to see if point is within the headers of a unix mail message.
1547 Doesn't change point."
1548   (let ((pos (point)))
1549     (save-excursion
1550       (and (nnmail-search-unix-mail-delim-backward)
1551            (not (search-forward "\n\n" pos t))))))
1552
1553 (run-hooks 'nnmail-load-hook)
1554
1555 (provide 'nnmail)
1556
1557 ;;; nnmail.el ends here