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