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