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