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