Sync up with Pterodactyl Gnus v0.83.
[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 This variable is obsolete; `mail-sources' should be used instead."
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-split-fancy-syntax-table nil
399   "Syntax table used by `nnmail-split-fancy'.")
400 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
401   (setq nnmail-split-fancy-syntax-table
402         (copy-syntax-table (standard-syntax-table)))
403   ;; support the %-hack
404   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
405
406 (defvar nnmail-prepare-save-mail-hook nil
407   "Hook called before saving mail.")
408
409 (defvar nnmail-split-tracing nil)
410 (defvar nnmail-split-trace nil)
411
412 \f
413
414 (defconst nnmail-version "nnmail 1.0"
415   "nnmail version.")
416
417 \f
418
419 (defun nnmail-request-post (&optional server)
420   (mail-send-and-exit nil))
421
422 (defvar nnmail-file-coding-system 'binary
423   "Coding system used in nnmail.")
424
425 (defvar nnmail-file-coding-system-1
426   (if (string-match "nt" system-configuration)
427       'raw-text-dos 'binary)
428   "Another coding system used in nnmail.")
429
430 (defvar nnmail-incoming-coding-system 'raw-text
431   "Coding system used in reading inbox")
432
433 (defun nnmail-find-file (file)
434   "Insert FILE in server buffer safely."
435   (set-buffer nntp-server-buffer)
436   (delete-region (point-min) (point-max))
437   (let ((format-alist nil)
438         (after-insert-file-functions nil))
439     (condition-case ()
440         (let ((auto-mode-alist (nnheader-auto-mode-alist))
441               (pathname-coding-system nnmail-file-coding-system))
442           (insert-file-contents-as-coding-system
443            nnmail-file-coding-system file)
444           t)
445       (file-error nil))))
446
447 (defvar nnmail-pathname-coding-system 'binary
448   "*Coding system for pathname.")
449
450 (defun nnmail-group-pathname (group dir &optional file)
451   "Make pathname for GROUP."
452   (concat
453    (let ((dir (file-name-as-directory (expand-file-name dir))))
454      (setq group (nnheader-translate-file-chars group))
455      ;; If this directory exists, we use it directly.
456      (if (or nnmail-use-long-file-names
457              (file-directory-p (concat dir group)))
458          (concat dir group "/")
459        ;; If not, we translate dots into slashes.
460        (concat dir
461                (encode-coding-string
462                 (nnheader-replace-chars-in-string group ?. ?/)
463                 nnmail-pathname-coding-system)
464                "/")))
465    (or file "")))
466
467 (defun nnmail-get-active ()
468   "Returns an assoc of group names and active ranges.
469 nn*-request-list should have been called before calling this function."
470   (let (group-assoc)
471     ;; Go through all groups from the active list.
472     (save-excursion
473       (set-buffer nntp-server-buffer)
474       (goto-char (point-min))
475       (while (re-search-forward
476               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
477         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
478         (push (list (match-string 1)
479                     (cons (string-to-int (match-string 3))
480                           (string-to-int (match-string 2))))
481               group-assoc)))
482     group-assoc))
483
484 (defvar nnmail-active-file-coding-system 'binary
485   "*Coding system for active file.")
486
487 (defun nnmail-save-active (group-assoc file-name)
488   "Save GROUP-ASSOC in ACTIVE-FILE."
489   (let ((coding-system-for-write nnmail-active-file-coding-system))
490     (when file-name
491       (with-temp-file file-name
492         (nnmail-generate-active group-assoc)))))
493
494 (defun nnmail-generate-active (alist)
495   "Generate an active file from group-alist ALIST."
496   (erase-buffer)
497   (let (group)
498     (while (setq group (pop alist))
499       (insert (format "%s %d %d y\n" (car group) (cdadr group)
500                       (caadr group))))))
501
502 (defun nnmail-get-split-group (file source)
503   "Find out whether this FILE is to be split into GROUP only.
504 If SOURCE is a directory spec, try to return the group name component."
505   (if (eq (car source) 'directory)
506       (let ((file (file-name-nondirectory file)))
507         (mail-source-bind (directory source)
508           (if (string-match (concat (regexp-quote suffix) "$") file)
509               (substring file 0 (match-beginning 0))
510             nil)))
511     nil))
512
513 (defun nnmail-process-babyl-mail-format (func artnum-func)
514   (let ((case-fold-search t)
515         start message-id content-length do-search end)
516     (while (not (eobp))
517       (goto-char (point-min))
518       (re-search-forward
519        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
520       (goto-char (match-end 0))
521       (delete-region (match-beginning 0) (match-end 0))
522       (narrow-to-region
523        (setq start (point))
524        (progn
525          ;; Skip all the headers in case there are more "From "s...
526          (or (search-forward "\n\n" nil t)
527              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
528              (search-forward "\1f\f"))
529          (point)))
530       ;; Unquote the ">From " line, if any.
531       (goto-char (point-min))
532       (when (looking-at ">From ")
533         (replace-match "X-From-Line: ") )
534       (run-hooks 'nnmail-prepare-incoming-header-hook)
535       (goto-char (point-max))
536       ;; Find the Message-ID header.
537       (save-excursion
538         (if (re-search-backward
539              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
540             (setq message-id (buffer-substring (match-beginning 1)
541                                                (match-end 1)))
542           ;; There is no Message-ID here, so we create one.
543           (save-excursion
544             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
545               (beginning-of-line)
546               (insert "Original-")))
547           (forward-line -1)
548           (insert "Message-ID: " (setq message-id (nnmail-message-id))
549                   "\n")))
550       ;; Look for a Content-Length header.
551       (if (not (save-excursion
552                  (and (re-search-backward
553                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
554                       (setq content-length (string-to-int
555                                             (buffer-substring
556                                              (match-beginning 1)
557                                              (match-end 1))))
558                       ;; We destroy the header, since none of
559                       ;; the backends ever use it, and we do not
560                       ;; want to confuse other mailers by having
561                       ;; a (possibly) faulty header.
562                       (progn (insert "X-") t))))
563           (setq do-search t)
564         (widen)
565         (if (or (= (+ (point) content-length) (point-max))
566                 (save-excursion
567                   (goto-char (+ (point) content-length))
568                   (looking-at "\1f")))
569             (progn
570               (goto-char (+ (point) content-length))
571               (setq do-search nil))
572           (setq do-search t)))
573       (widen)
574       ;; Go to the beginning of the next article - or to the end
575       ;; of the buffer.
576       (when do-search
577         (if (re-search-forward "^\1f" nil t)
578             (goto-char (match-beginning 0))
579           (goto-char (1- (point-max)))))
580       (delete-char 1)                   ; delete ^_
581       (save-excursion
582         (save-restriction
583           (narrow-to-region start (point))
584           (goto-char (point-min))
585           (nnmail-check-duplication message-id func artnum-func)
586           (setq end (point-max))))
587       (goto-char end))))
588
589 (defsubst nnmail-search-unix-mail-delim ()
590   "Put point at the beginning of the next Unix mbox message."
591   ;; Algorithm used to find the the next article in the
592   ;; brain-dead Unix mbox format:
593   ;;
594   ;; 1) Search for "^From ".
595   ;; 2) If we find it, then see whether the previous
596   ;;    line is blank and the next line looks like a header.
597   ;; Then it's possible that this is a mail delim, and we use it.
598   (let ((case-fold-search nil)
599         found)
600     (while (not found)
601       (if (not (re-search-forward "^From " nil t))
602           (setq found 'no)
603         (save-excursion
604           (beginning-of-line)
605           (when (and (or (bobp)
606                          (save-excursion
607                            (forward-line -1)
608                            (eq (char-after) ?\n)))
609                      (save-excursion
610                        (forward-line 1)
611                        (while (looking-at ">From \\|From ")
612                          (forward-line 1))
613                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
614             (setq found 'yes)))))
615     (beginning-of-line)
616     (eq found 'yes)))
617
618 (defun nnmail-search-unix-mail-delim-backward ()
619   "Put point at the beginning of the current Unix mbox message."
620   ;; Algorithm used to find the the next article in the
621   ;; brain-dead Unix mbox format:
622   ;;
623   ;; 1) Search for "^From ".
624   ;; 2) If we find it, then see whether the previous
625   ;;    line is blank and the next line looks like a header.
626   ;; Then it's possible that this is a mail delim, and we use it.
627   (let ((case-fold-search nil)
628         found)
629     (while (not found)
630       (if (not (re-search-backward "^From " nil t))
631           (setq found 'no)
632         (save-excursion
633           (beginning-of-line)
634           (when (and (or (bobp)
635                          (save-excursion
636                            (forward-line -1)
637                            (eq (char-after) ?\n)))
638                      (save-excursion
639                        (forward-line 1)
640                        (while (looking-at ">From \\|From ")
641                          (forward-line 1))
642                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
643             (setq found 'yes)))))
644     (beginning-of-line)
645     (eq found 'yes)))
646
647 (defun nnmail-process-unix-mail-format (func artnum-func)
648   (let ((case-fold-search t)
649         start message-id content-length end skip head-end)
650     (goto-char (point-min))
651     (if (not (and (re-search-forward "^From " nil t)
652                   (goto-char (match-beginning 0))))
653         ;; Possibly wrong format?
654         (error "Error, unknown mail format! (Possibly corrupted.)")
655       ;; Carry on until the bitter end.
656       (while (not (eobp))
657         (setq start (point)
658               end nil)
659         ;; Find the end of the head.
660         (narrow-to-region
661          start
662          (if (search-forward "\n\n" nil t)
663              (1- (point))
664            ;; This will never happen, but just to be on the safe side --
665            ;; if there is no head-body delimiter, we search a bit manually.
666            (while (and (looking-at "From \\|[^ \t]+:")
667                        (not (eobp)))
668              (forward-line 1))
669            (point)))
670         ;; Find the Message-ID header.
671         (goto-char (point-min))
672         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
673             (setq message-id (match-string 1))
674           (save-excursion
675             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
676               (beginning-of-line)
677               (insert "Original-")))
678           ;; There is no Message-ID here, so we create one.
679           (forward-line 1)
680           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
681         ;; Look for a Content-Length header.
682         (goto-char (point-min))
683         (if (not (re-search-forward
684                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
685             (setq content-length nil)
686           (setq content-length (string-to-int (match-string 1)))
687           ;; We destroy the header, since none of the backends ever
688           ;; use it, and we do not want to confuse other mailers by
689           ;; having a (possibly) faulty header.
690           (beginning-of-line)
691           (insert "X-"))
692         (run-hooks 'nnmail-prepare-incoming-header-hook)
693         ;; Find the end of this article.
694         (goto-char (point-max))
695         (widen)
696         (setq head-end (point))
697         ;; We try the Content-Length value.  The idea: skip over the header
698         ;; separator, then check what happens content-length bytes into the
699         ;; message body.  This should be either the end ot the buffer, the
700         ;; message separator or a blank line followed by the separator.
701         ;; The blank line should probably be deleted.  If neither of the
702         ;; three is met, the content-length header is probably invalid.
703         (when content-length
704           (forward-line 1)
705           (setq skip (+ (point) content-length))
706           (goto-char skip)
707           (cond ((or (= skip (point-max))
708                      (= (1+ skip) (point-max)))
709                  (setq end (point-max)))
710                 ((looking-at "From ")
711                  (setq end skip))
712                 ((looking-at "[ \t]*\n\\(From \\)")
713                  (setq end (match-beginning 1)))
714                 (t (setq end nil))))
715         (if end
716             (goto-char end)
717           ;; No Content-Length, so we find the beginning of the next
718           ;; article or the end of the buffer.
719           (goto-char head-end)
720           (or (nnmail-search-unix-mail-delim)
721               (goto-char (point-max))))
722         ;; Allow the backend to save the article.
723         (save-excursion
724           (save-restriction
725             (narrow-to-region start (point))
726             (goto-char (point-min))
727             (nnmail-check-duplication message-id func artnum-func)
728             (setq end (point-max))))
729         (goto-char end)))))
730
731 (defun nnmail-process-mmdf-mail-format (func artnum-func)
732   (let ((delim "^\^A\^A\^A\^A$")
733         (case-fold-search t)
734         start message-id end)
735     (goto-char (point-min))
736     (if (not (and (re-search-forward delim nil t)
737                   (forward-line 1)))
738         ;; Possibly wrong format?
739         (error "Error, unknown mail format! (Possibly corrupted.)")
740       ;; Carry on until the bitter end.
741       (while (not (eobp))
742         (setq start (point))
743         ;; Find the end of the head.
744         (narrow-to-region
745          start
746          (if (search-forward "\n\n" nil t)
747              (1- (point))
748            ;; This will never happen, but just to be on the safe side --
749            ;; if there is no head-body delimiter, we search a bit manually.
750            (while (and (looking-at "From \\|[^ \t]+:")
751                        (not (eobp)))
752              (forward-line 1))
753            (point)))
754         ;; Find the Message-ID header.
755         (goto-char (point-min))
756         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
757             (setq message-id (match-string 1))
758           ;; There is no Message-ID here, so we create one.
759           (save-excursion
760             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
761               (beginning-of-line)
762               (insert "Original-")))
763           (forward-line 1)
764           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
765         (run-hooks 'nnmail-prepare-incoming-header-hook)
766         ;; Find the end of this article.
767         (goto-char (point-max))
768         (widen)
769         (if (re-search-forward delim nil t)
770             (beginning-of-line)
771           (goto-char (point-max)))
772         ;; Allow the backend to save the article.
773         (save-excursion
774           (save-restriction
775             (narrow-to-region start (point))
776             (goto-char (point-min))
777             (nnmail-check-duplication message-id func artnum-func)
778             (setq end (point-max))))
779         (goto-char end)
780         (forward-line 2)))))
781
782 (defun nnmail-process-maildir-mail-format (func artnum-func)
783 ; In a maildir, every file contains exactly one mail
784   (let ((case-fold-search t)
785         message-id)
786     (goto-char (point-min))
787     ;; Find the end of the head.
788     (narrow-to-region
789      (point-min)
790      (if (search-forward "\n\n" nil t)
791          (1- (point))
792        ;; This will never happen, but just to be on the safe side --
793        ;; if there is no head-body delimiter, we search a bit manually.
794        (while (and (looking-at "From \\|[^ \t]+:")
795                    (not (eobp)))
796          (forward-line 1)
797          (point))))
798     ;; Find the Message-ID header.
799     (goto-char (point-min))
800     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
801         (setq message-id (match-string 1))
802       ;; There is no Message-ID here, so we create one.
803       (save-excursion
804             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
805           (beginning-of-line)
806           (insert "Original-")))
807       (forward-line 1)
808       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
809     (run-hooks 'nnmail-prepare-incoming-header-hook)
810     ;; Allow the backend to save the article.
811     (widen)
812     (save-excursion
813         (goto-char (point-min))
814         (nnmail-check-duplication message-id func artnum-func))))
815
816 (defun nnmail-split-incoming (incoming func &optional exit-func
817                                        group artnum-func)
818   "Go through the entire INCOMING file and pick out each individual mail.
819 FUNC will be called with the buffer narrowed to each mail."
820   (let (;; If this is a group-specific split, we bind the split
821         ;; methods to just this group.
822         (nnmail-split-methods (if (and group
823                                        (not nnmail-resplit-incoming))
824                                   (list (list group ""))
825                                 nnmail-split-methods)))
826     (save-excursion
827       ;; Insert the incoming file.
828       (set-buffer (get-buffer-create " *nnmail incoming*"))
829       (erase-buffer)
830       (let ((nnheader-file-coding-system nnmail-incoming-coding-system))
831         (nnheader-insert-file-contents incoming))
832       (unless (zerop (buffer-size))
833         (goto-char (point-min))
834         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
835         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
836         ;; use the former when fetching from a mailbox, the latter when
837         ;; fetching from a file.
838         (cond ((or (looking-at "\^L")
839                    (looking-at "BABYL OPTIONS:"))
840                (nnmail-process-babyl-mail-format func artnum-func))
841               ((looking-at "\^A\^A\^A\^A")
842                (nnmail-process-mmdf-mail-format func artnum-func))
843               ((looking-at "Return-Path:")
844                (nnmail-process-maildir-mail-format func artnum-func))
845               (t
846                (nnmail-process-unix-mail-format func artnum-func))))
847       (when exit-func
848         (funcall exit-func))
849       (kill-buffer (current-buffer)))))
850
851 (defun nnmail-article-group (func &optional trace)
852   "Look at the headers and return an alist of groups that match.
853 FUNC will be called with the group name to determine the article number."
854   (let ((methods nnmail-split-methods)
855         (obuf (current-buffer))
856         (beg (point-min))
857         end group-art method grp)
858     (if (and (sequencep methods)
859              (= (length methods) 1))
860         ;; If there is only just one group to put everything in, we
861         ;; just return a list with just this one method in.
862         (setq group-art
863               (list (cons (caar methods) (funcall func (caar methods)))))
864       ;; We do actual comparison.
865       (save-excursion
866         ;; Find headers.
867         (goto-char beg)
868         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
869         (set-buffer nntp-server-buffer)
870         (erase-buffer)
871         ;; Copy the headers into the work buffer.
872         (insert-buffer-substring obuf beg end)
873         ;; Fold continuation lines.
874         (goto-char (point-min))
875         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
876           (replace-match " " t t))
877         ;; Nuke pathologically long headers.  Since Gnus applies
878         ;; pathologically complex regexps to the buffer, lines
879         ;; that are looong will take longer than the Universe's
880         ;; existence to process.
881         (goto-char (point-min))
882         (while (not (eobp))
883           (unless (< (move-to-column nnmail-split-header-length-limit)
884                      nnmail-split-header-length-limit)
885             (delete-region (point) (progn (end-of-line) (point))))
886           (forward-line 1))
887         ;; Allow washing.
888         (goto-char (point-min))
889         (run-hooks 'nnmail-split-hook)
890         (when (setq nnmail-split-tracing trace)
891           (setq nnmail-split-trace nil))
892         (if (and (symbolp nnmail-split-methods)
893                  (fboundp nnmail-split-methods))
894             (let ((split
895                    (condition-case nil
896                        ;; `nnmail-split-methods' is a function, so we
897                        ;; just call this function here and use the
898                        ;; result.
899                        (or (funcall nnmail-split-methods)
900                            '("bogus"))
901                      (error
902                       (nnheader-message 5
903                        "Error in `nnmail-split-methods'; using `bogus' mail group")
904                       (sit-for 1)
905                       '("bogus")))))
906               (setq split (gnus-remove-duplicates split))
907               ;; The article may be "cross-posted" to `junk'.  What
908               ;; to do?  Just remove the `junk' spec.  Don't really
909               ;; see anything else to do...
910               (let (elem)
911                 (while (setq elem (car (memq 'junk split)))
912                   (setq split (delq elem split))))
913               (when split
914                 (setq group-art
915                       (mapcar
916                        (lambda (group) (cons group (funcall func group)))
917                        split))))
918           ;; Go through the split methods to find a match.
919           (while (and methods
920                       (or nnmail-crosspost
921                           (not group-art)))
922             (goto-char (point-max))
923             (setq method (pop methods)
924                   grp (car method))
925             (if (or methods
926                     (not (equal "" (nth 1 method))))
927                 (when (and
928                        (ignore-errors
929                          (if (stringp (nth 1 method))
930                              (let ((expand (string-match "\\\\[0-9&]" grp))
931                                    (pos (re-search-backward (cadr method)
932                                                             nil t)))
933                                (and expand
934                                     (setq grp (nnmail-expand-newtext grp)))
935                                pos)
936                            ;; Function to say whether this is a match.
937                            (funcall (nth 1 method) grp)))
938                        ;; Don't enter the article into the same
939                        ;; group twice.
940                        (not (assoc grp group-art)))
941                   (push (cons grp (funcall func grp))
942                         group-art))
943               ;; This is the final group, which is used as a
944               ;; catch-all.
945               (unless group-art
946                 (setq group-art
947                       (list (cons (car method)
948                                   (funcall func (car method)))))))))
949         ;; Produce a trace if non-empty.
950         (when (and trace nnmail-split-trace)
951           (let ((trace (nreverse nnmail-split-trace))
952                 (restore (current-buffer)))
953             (nnheader-set-temp-buffer "*Split Trace*")
954             (gnus-add-buffer)
955             (while trace
956               (insert (car trace) "\n")
957               (setq trace (cdr trace)))
958             (goto-char (point-min))
959             (gnus-configure-windows 'split-trace)
960             (set-buffer restore)))
961         ;; See whether the split methods returned `junk'.
962         (if (equal group-art '(junk))
963             nil
964           ;; The article may be "cross-posted" to `junk'.  What
965           ;; to do?  Just remove the `junk' spec.  Don't really
966           ;; see anything else to do...
967           (let (elem)
968             (while (setq elem (car (memq 'junk group-art)))
969               (setq group-art (delq elem group-art)))
970             (nreverse group-art)))))))
971
972 (defun nnmail-insert-lines ()
973   "Insert how many lines there are in the body of the mail.
974 Return the number of characters in the body."
975   (let (lines chars)
976     (save-excursion
977       (goto-char (point-min))
978       (when (search-forward "\n\n" nil t)
979         (setq chars (- (point-max) (point)))
980         (setq lines (count-lines (point) (point-max)))
981         (forward-char -1)
982         (save-excursion
983           (when (re-search-backward "^Lines: " nil t)
984             (delete-region (point) (progn (forward-line 1) (point)))))
985         (beginning-of-line)
986         (insert (format "Lines: %d\n" (max lines 0)))
987         chars))))
988
989 (defun nnmail-insert-xref (group-alist)
990   "Insert an Xref line based on the (group . article) alist."
991   (save-excursion
992     (goto-char (point-min))
993     (when (search-forward "\n\n" nil t)
994       (forward-char -1)
995       (when (re-search-backward "^Xref: " nil t)
996         (delete-region (match-beginning 0)
997                        (progn (forward-line 1) (point))))
998       (insert (format "Xref: %s" (system-name)))
999       (while group-alist
1000         (insert (format " %s:%d"
1001                         (encode-coding-string
1002                          (caar group-alist)
1003                          nnmail-pathname-coding-system)
1004                         (cdar group-alist)))
1005         (setq group-alist (cdr group-alist)))
1006       (insert "\n"))))
1007
1008 ;;; Message washing functions
1009
1010 (defun nnmail-remove-leading-whitespace ()
1011   "Remove excessive whitespace from all headers."
1012   (goto-char (point-min))
1013   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1014     (replace-match "\\1" t)))
1015
1016 (defun nnmail-remove-list-identifiers ()
1017   "Remove list identifiers from Subject headers."
1018   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1019                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1020     (when regexp
1021       (goto-char (point-min))
1022       (when (re-search-forward
1023              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1024              nil t)
1025         (delete-region (match-beginning 2) (match-end 0))))))
1026
1027 (defun nnmail-remove-tabs ()
1028   "Translate TAB characters into SPACE characters."
1029   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1030
1031 (defun nnmail-fix-eudora-headers ()
1032   "Eudora has a broken References line, but an OK In-Reply-To."
1033   (goto-char (point-min))
1034   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1035     (goto-char (point-min))
1036     (when (re-search-forward "^References:" nil t)
1037       (beginning-of-line)
1038       (insert "X-Gnus-Broken-Eudora-"))))
1039
1040 (custom-add-option 'nnmail-prepare-incoming-header-hook
1041                    'nnmail-fix-eudora-headers)
1042
1043 ;;; Utility functions
1044
1045 (defun nnmail-split-fancy ()
1046   "Fancy splitting method.
1047 See the documentation for the variable `nnmail-split-fancy' for documentation."
1048   (let ((syntab (syntax-table)))
1049     (unwind-protect
1050         (progn
1051           (set-syntax-table nnmail-split-fancy-syntax-table)
1052           (nnmail-split-it nnmail-split-fancy))
1053       (set-syntax-table syntab))))
1054
1055 (defvar nnmail-split-cache nil)
1056 ;; Alist of split expressions their equivalent regexps.
1057
1058 (defun nnmail-split-it (split)
1059   ;; Return a list of groups matching SPLIT.
1060   (let (cached-pair)
1061     (cond
1062      ;; nil split
1063      ((null split)
1064       nil)
1065
1066      ;; A group name.  Do the \& and \N subs into the string.
1067      ((stringp split)
1068       (when nnmail-split-tracing
1069         (push (format "\"%s\"" split) nnmail-split-trace))
1070       (list (nnmail-expand-newtext split)))
1071
1072      ;; Junk the message.
1073      ((eq split 'junk)
1074       (when nnmail-split-tracing
1075         (push "junk" nnmail-split-trace))
1076       (list 'junk))
1077
1078      ;; Builtin & operation.
1079      ((eq (car split) '&)
1080       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1081
1082      ;; Builtin | operation.
1083      ((eq (car split) '|)
1084       (let (done)
1085         (while (and (not done) (cdr split))
1086           (setq split (cdr split)
1087                 done (nnmail-split-it (car split))))
1088         done))
1089
1090      ;; Builtin : operation.
1091      ((eq (car split) ':)
1092       (nnmail-split-it (save-excursion (eval (cdr split)))))
1093
1094      ;; Builtin ! operation.
1095      ((eq (car split) '!)
1096       (funcall (cadr split) (nnmail-split-it (caddr split))))
1097
1098      ;; Check the cache for the regexp for this split.
1099      ((setq cached-pair (assq split nnmail-split-cache))
1100       (goto-char (point-max))
1101       ;; FIX FIX FIX problem with re-search-backward is that if you have
1102       ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1103       ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1104       ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1105       ;; if the cc line is a later header, even though the other choice
1106       ;; is probably better.  Also, this routine won't do a crosspost
1107       ;; when there are two different matches.
1108       ;; I guess you could just make this more determined, and it could
1109       ;; look for still more matches prior to this one, and recurse
1110       ;; on each of the multiple matches hit.  Of course, then you'd
1111       ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1112       ;; removed duplicates, since there might be more of those.
1113       ;; I guess we could also remove duplicates in the & split case, since
1114       ;; that's the only thing that can introduce them.
1115       (when (re-search-backward (cdr cached-pair) nil t)
1116         (when nnmail-split-tracing
1117           (push (cdr cached-pair) nnmail-split-trace))
1118         ;; Someone might want to do a \N sub on this match, so get the
1119         ;; correct match positions.
1120         (goto-char (match-end 0))
1121         (let ((value (nth 1 split)))
1122           (re-search-backward (if (symbolp value)
1123                                   (cdr (assq value nnmail-split-abbrev-alist))
1124                                 value)
1125                               (match-end 1)))
1126         (nnmail-split-it (nth 2 split))))
1127
1128      ;; Not in cache, compute a regexp for the field/value pair.
1129      (t
1130       (let* ((field (nth 0 split))
1131              (value (nth 1 split))
1132              (regexp (concat "^\\(\\("
1133                              (if (symbolp field)
1134                                  (cdr (assq field nnmail-split-abbrev-alist))
1135                                field)
1136                              "\\):.*\\)\\<\\("
1137                              (if (symbolp value)
1138                                  (cdr (assq value nnmail-split-abbrev-alist))
1139                                value)
1140                              "\\)\\>")))
1141         (push (cons split regexp) nnmail-split-cache)
1142         ;; Now that it's in the cache, just call nnmail-split-it again
1143         ;; on the same split, which will find it immediately in the cache.
1144         (nnmail-split-it split))))))
1145
1146 (defun nnmail-expand-newtext (newtext)
1147   (let ((len (length newtext))
1148         (pos 0)
1149         c expanded beg N did-expand)
1150     (while (< pos len)
1151       (setq beg pos)
1152       (while (and (< pos len)
1153                   (not (= (aref newtext pos) ?\\)))
1154         (setq pos (1+ pos)))
1155       (unless (= beg pos)
1156         (push (substring newtext beg pos) expanded))
1157       (when (< pos len)
1158         ;; We hit a \; expand it.
1159         (setq did-expand t
1160               pos (1+ pos)
1161               c (aref newtext pos))
1162         (if (not (or (= c ?\&)
1163                      (and (>= c ?1)
1164                           (<= c ?9))))
1165             ;; \ followed by some character we don't expand.
1166             (push (char-to-string c) expanded)
1167           ;; \& or \N
1168           (if (= c ?\&)
1169               (setq N 0)
1170             (setq N (- c ?0)))
1171           (when (match-beginning N)
1172             (push (buffer-substring (match-beginning N) (match-end N))
1173                   expanded))))
1174       (setq pos (1+ pos)))
1175     (if did-expand
1176         (apply 'concat (nreverse expanded))
1177       newtext)))
1178
1179 ;; Activate a backend only if it isn't already activated.
1180 ;; If FORCE, re-read the active file even if the backend is
1181 ;; already activated.
1182 (defun nnmail-activate (backend &optional force)
1183   (nnheader-init-server-buffer)
1184   (let (file timestamp file-time)
1185     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1186             force
1187             (and (setq file (ignore-errors
1188                               (symbol-value (intern (format "%s-active-file"
1189                                                             backend)))))
1190                  (setq file-time (nth 5 (file-attributes file)))
1191                  (or (not
1192                       (setq timestamp
1193                             (condition-case ()
1194                                 (symbol-value (intern
1195                                                (format "%s-active-timestamp"
1196                                                        backend)))
1197                               (error 'none))))
1198                      (not (consp timestamp))
1199                      (equal timestamp '(0 0))
1200                      (> (nth 0 file-time) (nth 0 timestamp))
1201                      (and (= (nth 0 file-time) (nth 0 timestamp))
1202                           (> (nth 1 file-time) (nth 1 timestamp))))))
1203         (save-excursion
1204           (or (eq timestamp 'none)
1205               (set (intern (format "%s-active-timestamp" backend))
1206                    file-time))
1207           (funcall (intern (format "%s-request-list" backend)))))
1208     t))
1209
1210 (defun nnmail-message-id ()
1211   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1212
1213 ;;;
1214 ;;; nnmail duplicate handling
1215 ;;;
1216
1217 (defvar nnmail-cache-buffer nil)
1218
1219 (defun nnmail-cache-open ()
1220   (if (or (not nnmail-treat-duplicates)
1221           (and nnmail-cache-buffer
1222                (buffer-name nnmail-cache-buffer)))
1223       ()                                ; The buffer is open.
1224     (save-excursion
1225       (set-buffer
1226        (setq nnmail-cache-buffer
1227              (get-buffer-create " *nnmail message-id cache*")))
1228       (when (file-exists-p nnmail-message-id-cache-file)
1229         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1230       (set-buffer-modified-p nil)
1231       (current-buffer))))
1232
1233 (defun nnmail-cache-close ()
1234   (when (and nnmail-cache-buffer
1235              nnmail-treat-duplicates
1236              (buffer-name nnmail-cache-buffer)
1237              (buffer-modified-p nnmail-cache-buffer))
1238     (save-excursion
1239       (set-buffer nnmail-cache-buffer)
1240       ;; Weed out the excess number of Message-IDs.
1241       (goto-char (point-max))
1242       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1243         (progn
1244           (beginning-of-line)
1245           (delete-region (point-min) (point))))
1246       ;; Save the buffer.
1247       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1248           (make-directory (file-name-directory nnmail-message-id-cache-file)
1249                           t))
1250       (nnmail-write-region (point-min) (point-max)
1251                            nnmail-message-id-cache-file nil 'silent)
1252       (set-buffer-modified-p nil)
1253       (setq nnmail-cache-buffer nil)
1254       (kill-buffer (current-buffer)))))
1255
1256 (defun nnmail-cache-insert (id)
1257   (when nnmail-treat-duplicates
1258     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1259       (nnmail-cache-open))
1260     (save-excursion
1261       (set-buffer nnmail-cache-buffer)
1262       (goto-char (point-max))
1263       (insert id "\n"))))
1264
1265 (defun nnmail-cache-id-exists-p (id)
1266   (when nnmail-treat-duplicates
1267     (save-excursion
1268       (set-buffer nnmail-cache-buffer)
1269       (goto-char (point-max))
1270       (search-backward id nil t))))
1271
1272 (defun nnmail-fetch-field (header)
1273   (save-excursion
1274     (save-restriction
1275       (message-narrow-to-head)
1276       (message-fetch-field header))))
1277
1278 (defun nnmail-check-duplication (message-id func artnum-func)
1279   (run-hooks 'nnmail-prepare-incoming-message-hook)
1280   ;; If this is a duplicate message, then we do not save it.
1281   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1282          (case-fold-search t)
1283          (action (when duplication
1284                    (cond
1285                     ((memq nnmail-treat-duplicates '(warn delete))
1286                      nnmail-treat-duplicates)
1287                     ((nnheader-functionp nnmail-treat-duplicates)
1288                      (funcall nnmail-treat-duplicates message-id))
1289                     (t
1290                      nnmail-treat-duplicates))))
1291          group-art)
1292     ;; We insert a line that says what the mail source is.
1293     (let ((case-fold-search t))
1294       (goto-char (point-min))
1295       (re-search-forward "^message-id[ \t]*:" nil t)
1296       (beginning-of-line)
1297       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1298
1299     ;; Let the backend save the article (or not).
1300     (cond
1301      ((not duplication)
1302       (funcall func (setq group-art
1303                           (nreverse (nnmail-article-group artnum-func))))
1304       (nnmail-cache-insert message-id))
1305      ((eq action 'delete)
1306       (setq group-art nil))
1307      ((eq action 'warn)
1308       ;; We insert a warning.
1309       (let ((case-fold-search t))
1310         (goto-char (point-min))
1311         (re-search-forward "^message-id[ \t]*:" nil t)
1312         (beginning-of-line)
1313         (insert
1314          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1315         (funcall func (setq group-art
1316                             (nreverse (nnmail-article-group artnum-func))))))
1317      (t
1318       (funcall func (setq group-art
1319                           (nreverse (nnmail-article-group artnum-func))))))
1320     ;; Add the group-art list to the history list.
1321     (if group-art
1322         (push group-art nnmail-split-history)
1323       (delete-region (point-min) (point-max)))))
1324
1325 ;;; Get new mail.
1326
1327 (defvar nnmail-fetched-sources nil)
1328
1329 (defun nnmail-get-value (&rest args)
1330   (let ((sym (intern (apply 'format args))))
1331     (when (boundp sym)
1332       (symbol-value sym))))
1333
1334 (defun nnmail-get-new-mail (method exit-func temp
1335                                    &optional group spool-func)
1336   "Read new incoming mail."
1337   (let* ((sources (or mail-sources
1338                       (if (listp nnmail-spool-file) nnmail-spool-file
1339                         (list nnmail-spool-file))))
1340          (group-in group)
1341          (i 0)
1342          (new 0)
1343          (total 0)
1344          incoming incomings source)
1345     (when (and (nnmail-get-value "%s-get-new-mail" method)
1346                nnmail-spool-file)
1347       ;; We first activate all the groups.
1348       (nnmail-activate method)
1349       ;; Allow the user to hook.
1350       (run-hooks 'nnmail-pre-get-new-mail-hook)
1351       ;; Open the message-id cache.
1352       (nnmail-cache-open)
1353       ;; The we go through all the existing mail source specification
1354       ;; and fetch the mail from each.
1355       (while (setq source (pop sources))
1356         ;; Be compatible with old values.
1357         (cond
1358          ((stringp source)
1359           (setq source
1360                 (cond
1361                  ((string-match "^po:" source)
1362                   (list 'pop :user (substring source (match-end 0))))
1363                  ((file-directory-p source)
1364                   (list 'directory :path source))
1365                  (t
1366                   (list 'file :path source)))))
1367          ((eq source 'procmail)
1368           (message "Invalid value for nnmail-spool-file: `procmail'")
1369           nil))
1370         ;; Hack to only fetch the contents of a single group's spool file.
1371         (when (and (eq (car source) 'directory)
1372                    group)
1373           (mail-source-bind (directory source)
1374             (setq source (append source
1375                                  (list
1376                                   :predicate
1377                                   `(lambda (file)
1378                                      (string-match
1379                                       ,(concat
1380                                         (regexp-quote (concat group suffix))
1381                                         "$")
1382                                       file)))))))
1383         (when nnmail-fetched-sources
1384           (if (member source nnmail-fetched-sources)
1385               (setq source nil)
1386             (push source nnmail-fetched-sources)))
1387         (when source
1388           (nnheader-message 4 "%s: Reading incoming mail from %s..."
1389                             method (car source))
1390           (when (setq new
1391                       (mail-source-fetch
1392                        source
1393                        `(lambda (file orig-file)
1394                           (nnmail-split-incoming
1395                            file ',(intern (format "%s-save-mail" method))
1396                            ',spool-func
1397                            (nnmail-get-split-group orig-file source)
1398                            ',(intern (format "%s-active-number" method))))))
1399             (incf total new)
1400             (incf i))))
1401       ;; If we did indeed read any incoming spools, we save all info.
1402       (unless (zerop i)
1403         (nnmail-save-active
1404          (nnmail-get-value "%s-group-alist" method)
1405          (nnmail-get-value "%s-active-file" method))
1406         (when exit-func
1407           (funcall exit-func))
1408         (run-hooks 'nnmail-read-incoming-hook)
1409         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1410                           total))
1411       ;; Close the message-id cache.
1412       (nnmail-cache-close)
1413       ;; Allow the user to hook.
1414       (run-hooks 'nnmail-post-get-new-mail-hook))))
1415
1416 (defun nnmail-expired-article-p (group time force &optional inhibit)
1417   "Say whether an article that is TIME old in GROUP should be expired."
1418   (if force
1419       t
1420     (let ((days (or (and nnmail-expiry-wait-function
1421                          (funcall nnmail-expiry-wait-function group))
1422                     nnmail-expiry-wait)))
1423       (cond ((or (eq days 'never)
1424                  (and (not force)
1425                       inhibit))
1426              ;; This isn't an expirable group.
1427              nil)
1428             ((eq days 'immediate)
1429              ;; We expire all articles on sight.
1430              t)
1431             ((equal time '(0 0))
1432              ;; This is an ange-ftp group, and we don't have any dates.
1433              nil)
1434             ((numberp days)
1435              (setq days (days-to-time days))
1436              ;; Compare the time with the current time.
1437              (ignore-errors (time-less-p days (time-since time))))))))
1438
1439 (defun nnmail-check-syntax ()
1440   "Check (and modify) the syntax of the message in the current buffer."
1441   (save-restriction
1442     (message-narrow-to-head)
1443     (let ((case-fold-search t))
1444       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1445         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1446
1447 (defun nnmail-write-region (start end filename &optional append visit lockname)
1448   "Do a `write-region', and then set the file modes."
1449   (let ((pathname-coding-system 'binary))
1450     (write-region-as-coding-system
1451      nnmail-file-coding-system start end filename append visit lockname)
1452     (set-file-modes filename nnmail-default-file-modes)))
1453
1454 ;;;
1455 ;;; Status functions
1456 ;;;
1457
1458 (defun nnmail-replace-status (name value)
1459   "Make status NAME and VALUE part of the current status line."
1460   (save-restriction
1461     (message-narrow-to-head)
1462     (let ((status (nnmail-decode-status)))
1463       (setq status (delq (member name status) status))
1464       (when value
1465         (push (cons name value) status))
1466       (message-remove-header "status")
1467       (goto-char (point-max))
1468       (insert "Status: " (nnmail-encode-status status) "\n"))))
1469
1470 (defun nnmail-decode-status ()
1471   "Return a status-value alist from STATUS."
1472   (goto-char (point-min))
1473   (when (re-search-forward "^Status: " nil t)
1474     (let (name value status)
1475       (save-restriction
1476         ;; Narrow to the status.
1477         (narrow-to-region
1478          (point)
1479          (if (re-search-forward "^[^ \t]" nil t)
1480              (1- (point))
1481            (point-max)))
1482         ;; Go through all elements and add them to the list.
1483         (goto-char (point-min))
1484         (while (re-search-forward "[^ \t=]+" nil t)
1485           (setq name (match-string 0))
1486           (if (not (eq (char-after) ?=))
1487               ;; Implied "yes".
1488               (setq value "yes")
1489             (forward-char 1)
1490             (if (not (eq (char-after) ?\"))
1491                 (if (not (looking-at "[^ \t]"))
1492                     ;; Implied "no".
1493                     (setq value "no")
1494                   ;; Unquoted value.
1495                   (setq value (match-string 0))
1496                   (goto-char (match-end 0)))
1497               ;; Quoted value.
1498               (setq value (read (current-buffer)))))
1499           (push (cons name value) status)))
1500       status)))
1501
1502 (defun nnmail-encode-status (status)
1503   "Return a status string from STATUS."
1504   (mapconcat
1505    (lambda (elem)
1506      (concat
1507       (car elem) "="
1508       (if (string-match "[ \t]" (cdr elem))
1509           (prin1-to-string (cdr elem))
1510         (cdr elem))))
1511    status " "))
1512
1513 (defun nnmail-split-history ()
1514   "Generate an overview of where the last mail split put articles."
1515   (interactive)
1516   (unless nnmail-split-history
1517     (error "No current split history"))
1518   (with-output-to-temp-buffer "*nnmail split history*"
1519     (let ((history nnmail-split-history)
1520           elem)
1521       (while (setq elem (pop history))
1522         (princ (mapconcat (lambda (ga)
1523                             (concat (car ga) ":" (int-to-string (cdr ga))))
1524                           elem
1525                           ", "))
1526         (princ "\n")))))
1527
1528 (defun nnmail-purge-split-history (group)
1529   "Remove all instances of GROUP from `nnmail-split-history'."
1530   (let ((history nnmail-split-history))
1531     (while history
1532       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1533                                       (car history)))
1534       (pop history))
1535     (setq nnmail-split-history (delq nil nnmail-split-history))))
1536
1537 (defun nnmail-new-mail-p (group)
1538   "Say whether GROUP has new mail."
1539   (let ((his nnmail-split-history)
1540         found)
1541     (while his
1542       (when (assoc group (pop his))
1543         (setq found t
1544               his nil)))
1545     found))
1546
1547 (defun nnmail-within-headers-p ()
1548   "Check to see if point is within the headers of a unix mail message.
1549 Doesn't change point."
1550   (let ((pos (point)))
1551     (save-excursion
1552       (and (nnmail-search-unix-mail-delim-backward)
1553            (not (search-forward "\n\n" pos t))))))
1554
1555 (run-hooks 'nnmail-load-hook)
1556
1557 (provide 'nnmail)
1558
1559 ;;; nnmail.el ends here