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