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