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