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