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