70c9531dc18d668f153d537c227234e5d5697ee8
[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 ;;; Utility functions
1048
1049 (defun nnmail-split-fancy ()
1050   "Fancy splitting method.
1051 See the documentation for the variable `nnmail-split-fancy' for documentation."
1052   (let ((syntab (syntax-table)))
1053     (unwind-protect
1054         (progn
1055           (set-syntax-table nnmail-split-fancy-syntax-table)
1056           (nnmail-split-it nnmail-split-fancy))
1057       (set-syntax-table syntab))))
1058
1059 (defvar nnmail-split-cache nil)
1060 ;; Alist of split expressions their equivalent regexps.
1061
1062 (defun nnmail-split-it (split)
1063   ;; Return a list of groups matching SPLIT.
1064   (let (cached-pair)
1065     (cond
1066      ;; nil split
1067      ((null split)
1068       nil)
1069
1070      ;; A group name.  Do the \& and \N subs into the string.
1071      ((stringp split)
1072       (when nnmail-split-tracing
1073         (push (format "\"%s\"" split) nnmail-split-trace))
1074       (list (nnmail-expand-newtext split)))
1075
1076      ;; Junk the message.
1077      ((eq split 'junk)
1078       (when nnmail-split-tracing
1079         (push "junk" nnmail-split-trace))
1080       (list 'junk))
1081
1082      ;; Builtin & operation.
1083      ((eq (car split) '&)
1084       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1085
1086      ;; Builtin | operation.
1087      ((eq (car split) '|)
1088       (let (done)
1089         (while (and (not done) (cdr split))
1090           (setq split (cdr split)
1091                 done (nnmail-split-it (car split))))
1092         done))
1093
1094      ;; Builtin : operation.
1095      ((eq (car split) ':)
1096       (nnmail-split-it (save-excursion (eval (cdr split)))))
1097
1098      ;; Check the cache for the regexp for this split.
1099      ((setq cached-pair (assq split nnmail-split-cache))
1100       (goto-char (point-max))
1101       ;; FIX FIX FIX problem with re-search-backward is that if you have
1102       ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1103       ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1104       ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1105       ;; if the cc line is a later header, even though the other choice
1106       ;; is probably better.  Also, this routine won't do a crosspost
1107       ;; when there are two different matches.
1108       ;; I guess you could just make this more determined, and it could
1109       ;; look for still more matches prior to this one, and recurse
1110       ;; on each of the multiple matches hit.  Of course, then you'd
1111       ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1112       ;; removed duplicates, since there might be more of those.
1113       ;; I guess we could also remove duplicates in the & split case, since
1114       ;; that's the only thing that can introduce them.
1115       (when (re-search-backward (cdr cached-pair) nil t)
1116         (when nnmail-split-tracing
1117           (push (cdr cached-pair) nnmail-split-trace))
1118         ;; Someone might want to do a \N sub on this match, so get the
1119         ;; correct match positions.
1120         (goto-char (match-end 0))
1121         (let ((value (nth 1 split)))
1122           (re-search-backward (if (symbolp value)
1123                                   (cdr (assq value nnmail-split-abbrev-alist))
1124                                 value)
1125                               (match-end 1)))
1126         (nnmail-split-it (nth 2 split))))
1127
1128      ;; Not in cache, compute a regexp for the field/value pair.
1129      (t
1130       (let* ((field (nth 0 split))
1131              (value (nth 1 split))
1132              (regexp (concat "^\\(\\("
1133                              (if (symbolp field)
1134                                  (cdr (assq field nnmail-split-abbrev-alist))
1135                                field)
1136                              "\\):.*\\)\\<\\("
1137                              (if (symbolp value)
1138                                  (cdr (assq value nnmail-split-abbrev-alist))
1139                                value)
1140                              "\\)\\>")))
1141         (push (cons split regexp) nnmail-split-cache)
1142         ;; Now that it's in the cache, just call nnmail-split-it again
1143         ;; on the same split, which will find it immediately in the cache.
1144         (nnmail-split-it split))))))
1145
1146 (defun nnmail-expand-newtext (newtext)
1147   (let ((len (length newtext))
1148         (pos 0)
1149         c expanded beg N did-expand)
1150     (while (< pos len)
1151       (setq beg pos)
1152       (while (and (< pos len)
1153                   (not (= (aref newtext pos) ?\\)))
1154         (setq pos (1+ pos)))
1155       (unless (= beg pos)
1156         (push (substring newtext beg pos) expanded))
1157       (when (< pos len)
1158         ;; We hit a \; expand it.
1159         (setq did-expand t
1160               pos (1+ pos)
1161               c (aref newtext pos))
1162         (if (not (or (= c ?\&)
1163                      (and (>= c ?1)
1164                           (<= c ?9))))
1165             ;; \ followed by some character we don't expand.
1166             (push (char-to-string c) expanded)
1167           ;; \& or \N
1168           (if (= c ?\&)
1169               (setq N 0)
1170             (setq N (- c ?0)))
1171           (when (match-beginning N)
1172             (push (buffer-substring (match-beginning N) (match-end N))
1173                   expanded))))
1174       (setq pos (1+ pos)))
1175     (if did-expand
1176         (apply 'concat (nreverse expanded))
1177       newtext)))
1178
1179 ;; Activate a backend only if it isn't already activated.
1180 ;; If FORCE, re-read the active file even if the backend is
1181 ;; already activated.
1182 (defun nnmail-activate (backend &optional force)
1183   (nnheader-init-server-buffer)
1184   (let (file timestamp file-time)
1185     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1186             force
1187             (and (setq file (ignore-errors
1188                               (symbol-value (intern (format "%s-active-file"
1189                                                             backend)))))
1190                  (setq file-time (nth 5 (file-attributes file)))
1191                  (or (not
1192                       (setq timestamp
1193                             (condition-case ()
1194                                 (symbol-value (intern
1195                                                (format "%s-active-timestamp"
1196                                                        backend)))
1197                               (error 'none))))
1198                      (not (consp timestamp))
1199                      (equal timestamp '(0 0))
1200                      (> (nth 0 file-time) (nth 0 timestamp))
1201                      (and (= (nth 0 file-time) (nth 0 timestamp))
1202                           (> (nth 1 file-time) (nth 1 timestamp))))))
1203         (save-excursion
1204           (or (eq timestamp 'none)
1205               (set (intern (format "%s-active-timestamp" backend))
1206                    file-time))
1207           (funcall (intern (format "%s-request-list" backend)))))
1208     t))
1209
1210 (defun nnmail-message-id ()
1211   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1212
1213 ;;;
1214 ;;; nnmail duplicate handling
1215 ;;;
1216
1217 (defvar nnmail-cache-buffer nil)
1218
1219 (defun nnmail-cache-open ()
1220   (if (or (not nnmail-treat-duplicates)
1221           (and nnmail-cache-buffer
1222                (buffer-name nnmail-cache-buffer)))
1223       ()                                ; The buffer is open.
1224     (save-excursion
1225       (set-buffer
1226        (setq nnmail-cache-buffer
1227              (get-buffer-create " *nnmail message-id cache*")))
1228       (when (file-exists-p nnmail-message-id-cache-file)
1229         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1230       (set-buffer-modified-p nil)
1231       (current-buffer))))
1232
1233 (defun nnmail-cache-close ()
1234   (when (and nnmail-cache-buffer
1235              nnmail-treat-duplicates
1236              (buffer-name nnmail-cache-buffer)
1237              (buffer-modified-p nnmail-cache-buffer))
1238     (save-excursion
1239       (set-buffer nnmail-cache-buffer)
1240       ;; Weed out the excess number of Message-IDs.
1241       (goto-char (point-max))
1242       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1243         (progn
1244           (beginning-of-line)
1245           (delete-region (point-min) (point))))
1246       ;; Save the buffer.
1247       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1248           (make-directory (file-name-directory nnmail-message-id-cache-file)
1249                           t))
1250       (nnmail-write-region (point-min) (point-max)
1251                            nnmail-message-id-cache-file nil 'silent)
1252       (set-buffer-modified-p nil)
1253       (setq nnmail-cache-buffer nil)
1254       (kill-buffer (current-buffer)))))
1255
1256 (defun nnmail-cache-insert (id)
1257   (when nnmail-treat-duplicates
1258     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1259       (nnmail-cache-open))
1260     (save-excursion
1261       (set-buffer nnmail-cache-buffer)
1262       (goto-char (point-max))
1263       (insert id "\n"))))
1264
1265 (defun nnmail-cache-id-exists-p (id)
1266   (when nnmail-treat-duplicates
1267     (save-excursion
1268       (set-buffer nnmail-cache-buffer)
1269       (goto-char (point-max))
1270       (search-backward id nil t))))
1271
1272 (defun nnmail-fetch-field (header)
1273   (save-excursion
1274     (save-restriction
1275       (message-narrow-to-head)
1276       (message-fetch-field header))))
1277
1278 (defun nnmail-check-duplication (message-id func artnum-func)
1279   (run-hooks 'nnmail-prepare-incoming-message-hook)
1280   ;; If this is a duplicate message, then we do not save it.
1281   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1282          (case-fold-search t)
1283          (action (when duplication
1284                    (cond
1285                     ((memq nnmail-treat-duplicates '(warn delete))
1286                      nnmail-treat-duplicates)
1287                     ((nnheader-functionp nnmail-treat-duplicates)
1288                      (funcall nnmail-treat-duplicates message-id))
1289                     (t
1290                      nnmail-treat-duplicates))))
1291          group-art)
1292     ;; We insert a line that says what the mail source is.
1293     (let ((case-fold-search t))
1294       (goto-char (point-min))
1295       (re-search-forward "^message-id[ \t]*:" nil t)
1296       (beginning-of-line)
1297       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1298
1299     ;; Let the backend save the article (or not).
1300     (cond
1301      ((not duplication)
1302       (funcall func (setq group-art
1303                           (nreverse (nnmail-article-group artnum-func))))
1304       (nnmail-cache-insert message-id))
1305      ((eq action 'delete)
1306       (setq group-art nil))
1307      ((eq action 'warn)
1308       ;; We insert a warning.
1309       (let ((case-fold-search t))
1310         (goto-char (point-min))
1311         (re-search-forward "^message-id[ \t]*:" nil t)
1312         (beginning-of-line)
1313         (insert
1314          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1315         (funcall func (setq group-art
1316                             (nreverse (nnmail-article-group artnum-func))))))
1317      (t
1318       (funcall func (setq group-art
1319                           (nreverse (nnmail-article-group artnum-func))))))
1320     ;; Add the group-art list to the history list.
1321     (if group-art
1322         (push group-art nnmail-split-history)
1323       (delete-region (point-min) (point-max)))))
1324
1325 ;;; Get new mail.
1326
1327 (defvar nnmail-fetched-sources nil)
1328
1329 (defun nnmail-get-value (&rest args)
1330   (let ((sym (intern (apply 'format args))))
1331     (when (boundp sym)
1332       (symbol-value sym))))
1333
1334 (defun nnmail-get-new-mail (method exit-func temp
1335                                    &optional group spool-func)
1336   "Read new incoming mail."
1337   (let* ((sources (if (listp nnmail-spool-file) nnmail-spool-file
1338                     (list nnmail-spool-file)))
1339          (group-in group)
1340          (i 0)
1341          nnmail-current-spool incoming incomings source)
1342     (when (and (nnmail-get-value "%s-get-new-mail" method)
1343                nnmail-spool-file)
1344       ;; We first activate all the groups.
1345       (nnmail-activate method)
1346       ;; Allow the user to hook.
1347       (run-hooks 'nnmail-pre-get-new-mail-hook)
1348       ;; Open the message-id cache.
1349       (nnmail-cache-open)
1350       ;; The we go through all the existing mail source specification
1351       ;; and fetch the mail from each.
1352       (while (setq source (pop sources))
1353         ;; Be compatible with old values.
1354         (cond
1355          ((stringp source)
1356           (setq source
1357                 (cond
1358                  ((string-match "^po:" source)
1359                   (list 'pop :user (substring source (match-end 0))))
1360                  ((file-directory-p source)
1361                   (list 'directory :path source))
1362                  (t
1363                   (list 'file :path source)))))
1364          ((eq source 'procmail)
1365           (message "Invalid value for nnmail-spool-file: `procmail'")
1366           nil))
1367         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1368                           method (car source))
1369         ;; Hack to only fetch the contents of a single group's spool file.
1370         (when (and (eq (car source) 'directory)
1371                    group)
1372           (setq source (append source
1373                                (list :predicate
1374                                      `(lambda (file)
1375                                         (string-match ,(regexp-quote group)
1376                                                       file))))))
1377         (when nnmail-fetched-sources
1378           (if (member source nnmail-fetched-sources)
1379               (setq source nil)
1380             (push source nnmail-fetched-sources)))
1381         (when (and source
1382                    (mail-source-fetch
1383                     source
1384                     `(lambda (file orig-file)
1385                        (nnmail-split-incoming
1386                         file ',(intern (format "%s-save-mail" method))
1387                         ',spool-func (nnmail-get-split-group orig-file source)
1388                         ',(intern (format "%s-active-number" method))))))
1389           (incf i)))
1390       ;; If we did indeed read any incoming spools, we save all info.
1391       (unless (zerop i)
1392         (nnmail-save-active
1393          (nnmail-get-value "%s-group-alist" method)
1394          (nnmail-get-value "%s-active-file" method))
1395         (when exit-func
1396           (funcall exit-func))
1397         (run-hooks 'nnmail-read-incoming-hook)
1398         (nnheader-message 4 "%s: Reading incoming mail...done" method))
1399       ;; Close the message-id cache.
1400       (nnmail-cache-close)
1401       ;; Allow the user to hook.
1402       (run-hooks 'nnmail-post-get-new-mail-hook))))
1403
1404 (defun nnmail-expired-article-p (group time force &optional inhibit)
1405   "Say whether an article that is TIME old in GROUP should be expired."
1406   (if force
1407       t
1408     (let ((days (or (and nnmail-expiry-wait-function
1409                          (funcall nnmail-expiry-wait-function group))
1410                     nnmail-expiry-wait)))
1411       (cond ((or (eq days 'never)
1412                  (and (not force)
1413                       inhibit))
1414              ;; This isn't an expirable group.
1415              nil)
1416             ((eq days 'immediate)
1417              ;; We expire all articles on sight.
1418              t)
1419             ((equal time '(0 0))
1420              ;; This is an ange-ftp group, and we don't have any dates.
1421              nil)
1422             ((numberp days)
1423              (setq days (days-to-time days))
1424              ;; Compare the time with the current time.
1425              (ignore-errors (time-less-p days (time-since time))))))))
1426
1427 (defun nnmail-check-syntax ()
1428   "Check (and modify) the syntax of the message in the current buffer."
1429   (save-restriction
1430     (message-narrow-to-head)
1431     (let ((case-fold-search t))
1432       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1433         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1434
1435 (defun nnmail-write-region (start end filename &optional append visit lockname)
1436   "Do a `write-region', and then set the file modes."
1437   (let ((pathname-coding-system 'binary))
1438     (write-region-as-coding-system
1439      nnmail-file-coding-system start end filename append visit lockname)
1440     (set-file-modes filename nnmail-default-file-modes)))
1441
1442 ;;;
1443 ;;; Status functions
1444 ;;;
1445
1446 (defun nnmail-replace-status (name value)
1447   "Make status NAME and VALUE part of the current status line."
1448   (save-restriction
1449     (message-narrow-to-head)
1450     (let ((status (nnmail-decode-status)))
1451       (setq status (delq (member name status) status))
1452       (when value
1453         (push (cons name value) status))
1454       (message-remove-header "status")
1455       (goto-char (point-max))
1456       (insert "Status: " (nnmail-encode-status status) "\n"))))
1457
1458 (defun nnmail-decode-status ()
1459   "Return a status-value alist from STATUS."
1460   (goto-char (point-min))
1461   (when (re-search-forward "^Status: " nil t)
1462     (let (name value status)
1463       (save-restriction
1464         ;; Narrow to the status.
1465         (narrow-to-region
1466          (point)
1467          (if (re-search-forward "^[^ \t]" nil t)
1468              (1- (point))
1469            (point-max)))
1470         ;; Go through all elements and add them to the list.
1471         (goto-char (point-min))
1472         (while (re-search-forward "[^ \t=]+" nil t)
1473           (setq name (match-string 0))
1474           (if (not (eq (char-after) ?=))
1475               ;; Implied "yes".
1476               (setq value "yes")
1477             (forward-char 1)
1478             (if (not (eq (char-after) ?\"))
1479                 (if (not (looking-at "[^ \t]"))
1480                     ;; Implied "no".
1481                     (setq value "no")
1482                   ;; Unquoted value.
1483                   (setq value (match-string 0))
1484                   (goto-char (match-end 0)))
1485               ;; Quoted value.
1486               (setq value (read (current-buffer)))))
1487           (push (cons name value) status)))
1488       status)))
1489
1490 (defun nnmail-encode-status (status)
1491   "Return a status string from STATUS."
1492   (mapconcat
1493    (lambda (elem)
1494      (concat
1495       (car elem) "="
1496       (if (string-match "[ \t]" (cdr elem))
1497           (prin1-to-string (cdr elem))
1498         (cdr elem))))
1499    status " "))
1500
1501 (defun nnmail-split-history ()
1502   "Generate an overview of where the last mail split put articles."
1503   (interactive)
1504   (unless nnmail-split-history
1505     (error "No current split history"))
1506   (with-output-to-temp-buffer "*nnmail split history*"
1507     (let ((history nnmail-split-history)
1508           elem)
1509       (while (setq elem (pop history))
1510         (princ (mapconcat (lambda (ga)
1511                             (concat (car ga) ":" (int-to-string (cdr ga))))
1512                           elem
1513                           ", "))
1514         (princ "\n")))))
1515
1516 (defun nnmail-purge-split-history (group)
1517   "Remove all instances of GROUP from `nnmail-split-history'."
1518   (let ((history nnmail-split-history))
1519     (while history
1520       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1521                                       (car history)))
1522       (pop history))
1523     (setq nnmail-split-history (delq nil nnmail-split-history))))
1524
1525 (defun nnmail-new-mail-p (group)
1526   "Say whether GROUP has new mail."
1527   (let ((his nnmail-split-history)
1528         found)
1529     (while his
1530       (when (assoc group (pop his))
1531         (setq found t
1532               his nil)))
1533     found))
1534
1535 (defun nnmail-within-headers-p ()
1536   "Check to see if point is within the headers of a unix mail message.
1537 Doesn't change point."
1538   (let ((pos (point)))
1539     (save-excursion
1540       (and (nnmail-search-unix-mail-delim-backward)
1541            (not (search-forward "\n\n" pos t))))))
1542
1543 (run-hooks 'nnmail-load-hook)
1544
1545 (provide 'nnmail)
1546
1547 ;;; nnmail.el ends here