Refill some long/short copyright headers.
[gnus] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2
3 ;; Copyright (C) 1995-2011  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)
557   "*Extra headers to parse."
558   :version "21.1"
559   :group 'nnmail
560   :type '(repeat symbol))
561
562 (defcustom nnmail-split-header-length-limit 2048
563   "Header lines longer than this limit are excluded from the split function."
564   :version "21.1"
565   :group 'nnmail
566   :type 'integer)
567
568 (defcustom nnmail-mail-splitting-charset nil
569   "Default charset to be used when splitting incoming mail."
570   :version "22.1"
571   :group 'nnmail
572   :type 'symbol)
573
574 (defcustom nnmail-mail-splitting-decodes nil
575   "Whether the nnmail splitting functionality should MIME decode headers."
576   :version "22.1"
577   :group 'nnmail
578   :type 'boolean)
579
580 (defcustom nnmail-split-fancy-match-partial-words nil
581   "Whether to match partial words when fancy splitting.
582 Normally, regexes given in `nnmail-split-fancy' are implicitly surrounded
583 by \"\\=\\<...\\>\".  If this variable is true, they are not implicitly\
584  surrounded
585 by anything."
586   :version "22.1"
587   :group 'nnmail
588   :type 'boolean)
589
590 (defcustom nnmail-split-lowercase-expanded t
591   "Whether to lowercase expanded entries (i.e. \\N) when splitting mails.
592 This avoids the creation of multiple groups when users send to an address
593 using different case (i.e. mailing-list@domain vs Mailing-List@Domain)."
594   :version "22.1"
595   :group 'nnmail
596   :type 'boolean)
597
598 ;;; Internal variables.
599
600 (defvar nnmail-article-buffer " *nnmail incoming*"
601   "The buffer used for splitting incoming mails.")
602
603 (defvar nnmail-split-history nil
604   "List of group/article elements that say where the previous split put messages.")
605
606 (defvar nnmail-split-fancy-syntax-table
607   (let ((table (make-syntax-table)))
608     ;; support the %-hack
609     (modify-syntax-entry ?\% "." table)
610     table)
611   "Syntax table used by `nnmail-split-fancy'.")
612
613 (defvar nnmail-prepare-save-mail-hook nil
614   "Hook called before saving mail.")
615
616 (defvar nnmail-split-tracing nil)
617 (defvar nnmail-split-trace nil)
618 (defvar nnmail-inhibit-default-split-group nil)
619
620 \f
621
622 (defun nnmail-request-post (&optional server)
623   (mail-send-and-exit nil))
624
625 (defvar nnmail-file-coding-system 'raw-text
626   "Coding system used in nnmail.")
627
628 (defvar nnmail-incoming-coding-system
629   mm-text-coding-system
630   "Coding system used in reading inbox")
631
632 (defvar nnmail-pathname-coding-system
633   ;; This causes Emacs 22.2 and 22.3 to issue a useless warning.
634   ;;(if (and (featurep 'xemacs) (featurep 'file-coding))
635   (if (featurep 'xemacs)
636       (if (featurep 'file-coding)
637           ;; Work around a bug in many XEmacs 21.5 betas.
638           ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/68134
639           (setq file-name-coding-system (coding-system-aliasee 'file-name))))
640   "*Coding system for file name.")
641
642 (defun nnmail-find-file (file)
643   "Insert FILE in server buffer safely."
644   (set-buffer nntp-server-buffer)
645   (delete-region (point-min) (point-max))
646   (let ((format-alist nil)
647         (after-insert-file-functions nil))
648     (condition-case ()
649         (let ((coding-system-for-read nnmail-file-coding-system)
650               (auto-mode-alist (mm-auto-mode-alist))
651               (file-name-coding-system nnmail-pathname-coding-system))
652           (insert-file-contents file)
653           t)
654       (file-error nil))))
655
656 (defun nnmail-group-pathname (group dir &optional file)
657   "Make file name for GROUP."
658   (concat
659    (let ((dir (file-name-as-directory (expand-file-name dir))))
660      (setq group (nnheader-replace-duplicate-chars-in-string
661                   (nnheader-replace-chars-in-string group ?/ ?_)
662                   ?. ?_))
663      (setq group (nnheader-translate-file-chars group))
664      ;; If this directory exists, we use it directly.
665      (file-name-as-directory
666       (if (or nnmail-use-long-file-names
667               (file-directory-p (concat dir group)))
668           (expand-file-name group dir)
669         ;; If not, we translate dots into slashes.
670         (expand-file-name
671          (nnheader-replace-chars-in-string group ?. ?/)
672          dir))))
673    (or file "")))
674
675 (defun nnmail-get-active ()
676   "Returns an assoc of group names and active ranges.
677 nn*-request-list should have been called before calling this function."
678   ;; Go through all groups from the active list.
679   (with-current-buffer nntp-server-buffer
680     (nnmail-parse-active)))
681
682 (defun nnmail-parse-active ()
683   "Parse the active file in the current buffer and return an alist."
684   (goto-char (point-min))
685   (unless (re-search-forward "[\\\"]" nil t)
686     (goto-char (point-max))
687     (while (re-search-backward "[][';?()#]" nil t)
688       (insert ?\\)))
689   (goto-char (point-min))
690   (let ((buffer (current-buffer))
691         group-assoc group max min)
692     (while (not (eobp))
693       (condition-case err
694           (progn
695             (narrow-to-region (point) (point-at-eol))
696             (setq group (read buffer))
697             (unless (stringp group)
698               (setq group (symbol-name group)))
699             (if (and (numberp (setq max (read buffer)))
700                      (numberp (setq min (read buffer))))
701                 (push (list (mm-string-as-unibyte group) (cons min max))
702                       group-assoc)))
703         (error nil))
704       (widen)
705       (forward-line 1))
706     group-assoc))
707
708 (defvar nnmail-active-file-coding-system 'raw-text
709   "*Coding system for active file.")
710
711 (defun nnmail-save-active (group-assoc file-name)
712   "Save GROUP-ASSOC in ACTIVE-FILE."
713   (let ((coding-system-for-write nnmail-active-file-coding-system))
714     (when file-name
715       (with-temp-file file-name
716         (mm-disable-multibyte)
717         (nnmail-generate-active group-assoc)))))
718
719 (defun nnmail-generate-active (alist)
720   "Generate an active file from group-alist ALIST."
721   (erase-buffer)
722   (let (group)
723     (while (setq group (pop alist))
724       (insert (format "%S %d %d y\n" (intern (car group)) (cdadr group)
725                       (caadr group))))
726     (goto-char (point-max))
727     (while (search-backward "\\." nil t)
728       (delete-char 1))))
729
730 (defun nnmail-get-split-group (file source)
731   "Find out whether this FILE is to be split into GROUP only.
732 If SOURCE is a directory spec, try to return the group name component."
733   (if (eq (car source) 'directory)
734       (let ((file (file-name-nondirectory file)))
735         (mail-source-bind (directory source)
736           (if (string-match (concat (regexp-quote suffix) "$") file)
737               (substring file 0 (match-beginning 0))
738             nil)))
739     nil))
740
741 (defun nnmail-process-babyl-mail-format (func artnum-func)
742   (let ((case-fold-search t)
743         (count 0)
744         start message-id content-length do-search end)
745     (while (not (eobp))
746       (goto-char (point-min))
747       (re-search-forward
748        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
749       (goto-char (match-end 0))
750       (delete-region (match-beginning 0) (match-end 0))
751       (narrow-to-region
752        (setq start (point))
753        (progn
754          ;; Skip all the headers in case there are more "From "s...
755          (or (search-forward "\n\n" nil t)
756              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
757              (search-forward "\1f\f"))
758          (point)))
759       ;; Unquote the ">From " line, if any.
760       (goto-char (point-min))
761       (when (looking-at ">From ")
762         (replace-match "X-From-Line: ") )
763       (run-hooks 'nnmail-prepare-incoming-header-hook)
764       (goto-char (point-max))
765       ;; Find the Message-ID header.
766       (save-excursion
767         (if (re-search-backward
768              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
769             (setq message-id (buffer-substring (match-beginning 1)
770                                                (match-end 1)))
771           ;; There is no Message-ID here, so we create one.
772           (save-excursion
773             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
774               (beginning-of-line)
775               (insert "Original-")))
776           (forward-line -1)
777           (insert "Message-ID: " (setq message-id (nnmail-message-id))
778                   "\n")))
779       ;; Look for a Content-Length header.
780       (if (not (save-excursion
781                  (and (re-search-backward
782                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
783                       (setq content-length (string-to-number
784                                             (buffer-substring
785                                              (match-beginning 1)
786                                              (match-end 1))))
787                       ;; We destroy the header, since none of
788                       ;; the backends ever use it, and we do not
789                       ;; want to confuse other mailers by having
790                       ;; a (possibly) faulty header.
791                       (progn (insert "X-") t))))
792           (setq do-search t)
793         (widen)
794         (if (or (= (+ (point) content-length) (point-max))
795                 (save-excursion
796                   (goto-char (+ (point) content-length))
797                   (looking-at "\1f")))
798             (progn
799               (goto-char (+ (point) content-length))
800               (setq do-search nil))
801           (setq do-search t)))
802       (widen)
803       ;; Go to the beginning of the next article - or to the end
804       ;; of the buffer.
805       (when do-search
806         (if (re-search-forward "^\1f" nil t)
807             (goto-char (match-beginning 0))
808           (goto-char (1- (point-max)))))
809       (delete-char 1)                   ; delete ^_
810       (save-excursion
811         (save-restriction
812           (narrow-to-region start (point))
813           (goto-char (point-min))
814           (nnmail-check-duplication message-id func artnum-func)
815           (incf count)
816           (setq end (point-max))))
817       (goto-char end))
818     count))
819
820 (defsubst nnmail-search-unix-mail-delim ()
821   "Put point at the beginning of the next Unix mbox message."
822   ;; Algorithm used to find the next article in the
823   ;; brain-dead Unix mbox format:
824   ;;
825   ;; 1) Search for "^From ".
826   ;; 2) If we find it, then see whether the previous
827   ;;    line is blank and the next line looks like a header.
828   ;; Then it's possible that this is a mail delim, and we use it.
829   (let ((case-fold-search nil)
830         found)
831     (while (not found)
832       (if (not (re-search-forward "^From " nil t))
833           (setq found 'no)
834         (save-excursion
835           (beginning-of-line)
836           (when (and (or (bobp)
837                          (save-excursion
838                            (forward-line -1)
839                            (eq (char-after) ?\n)))
840                      (save-excursion
841                        (forward-line 1)
842                        (while (looking-at ">From \\|From ")
843                          (forward-line 1))
844                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
845             (setq found 'yes)))))
846     (beginning-of-line)
847     (eq found 'yes)))
848
849 (defun nnmail-search-unix-mail-delim-backward ()
850   "Put point at the beginning of the current Unix mbox message."
851   ;; Algorithm used to find the next article in the
852   ;; brain-dead Unix mbox format:
853   ;;
854   ;; 1) Search for "^From ".
855   ;; 2) If we find it, then see whether the previous
856   ;;    line is blank and the next line looks like a header.
857   ;; Then it's possible that this is a mail delim, and we use it.
858   (let ((case-fold-search nil)
859         found)
860     (while (not found)
861       (if (not (re-search-backward "^From " nil t))
862           (setq found 'no)
863         (save-excursion
864           (beginning-of-line)
865           (when (and (or (bobp)
866                          (save-excursion
867                            (forward-line -1)
868                            (eq (char-after) ?\n)))
869                      (save-excursion
870                        (forward-line 1)
871                        (while (looking-at ">From \\|From ")
872                          (forward-line 1))
873                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
874             (setq found 'yes)))))
875     (beginning-of-line)
876     (eq found 'yes)))
877
878 (defun nnmail-process-unix-mail-format (func artnum-func)
879   (let ((case-fold-search t)
880         (count 0)
881         start message-id content-length end skip head-end)
882     (goto-char (point-min))
883     (if (not (and (re-search-forward "^From " nil t)
884                   (goto-char (match-beginning 0))))
885         ;; Possibly wrong format?
886         (error "Error, unknown mail format! (Possibly corrupted %s `%s'.)"
887                (if (buffer-file-name) "file" "buffer")
888                (or (buffer-file-name) (buffer-name)))
889       ;; Carry on until the bitter end.
890       (while (not (eobp))
891         (setq start (point)
892               end nil)
893         ;; Find the end of the head.
894         (narrow-to-region
895          start
896          (if (search-forward "\n\n" nil t)
897              (1- (point))
898            ;; This will never happen, but just to be on the safe side --
899            ;; if there is no head-body delimiter, we search a bit manually.
900            (while (and (looking-at "From \\|[^ \t]+:")
901                        (not (eobp)))
902              (forward-line 1))
903            (point)))
904         ;; Find the Message-ID header.
905         (goto-char (point-min))
906         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
907             (setq message-id (match-string 1))
908           (save-excursion
909             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
910               (beginning-of-line)
911               (insert "Original-")))
912           ;; There is no Message-ID here, so we create one.
913           (forward-line 1)
914           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
915         ;; Look for a Content-Length header.
916         (goto-char (point-min))
917         (if (not (re-search-forward
918                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
919             (setq content-length nil)
920           (setq content-length (string-to-number (match-string 1)))
921           ;; We destroy the header, since none of the backends ever
922           ;; use it, and we do not want to confuse other mailers by
923           ;; having a (possibly) faulty header.
924           (beginning-of-line)
925           (insert "X-"))
926         (run-hooks 'nnmail-prepare-incoming-header-hook)
927         ;; Find the end of this article.
928         (goto-char (point-max))
929         (widen)
930         (setq head-end (point))
931         ;; We try the Content-Length value.  The idea: skip over the header
932         ;; separator, then check what happens content-length bytes into the
933         ;; message body.  This should be either the end of the buffer, the
934         ;; message separator or a blank line followed by the separator.
935         ;; The blank line should probably be deleted.  If neither of the
936         ;; three is met, the content-length header is probably invalid.
937         (when content-length
938           (forward-line 1)
939           (setq skip (+ (point) content-length))
940           (goto-char skip)
941           (cond ((or (= skip (point-max))
942                      (= (1+ skip) (point-max)))
943                  (setq end (point-max)))
944                 ((looking-at "From ")
945                  (setq end skip))
946                 ((looking-at "[ \t]*\n\\(From \\)")
947                  (setq end (match-beginning 1)))
948                 (t (setq end nil))))
949         (if end
950             (goto-char end)
951           ;; No Content-Length, so we find the beginning of the next
952           ;; article or the end of the buffer.
953           (goto-char head-end)
954           (or (nnmail-search-unix-mail-delim)
955               (goto-char (point-max))))
956         ;; Allow the backend to save the article.
957         (save-excursion
958           (save-restriction
959             (narrow-to-region start (point))
960             (goto-char (point-min))
961             (incf count)
962             (nnmail-check-duplication message-id func artnum-func)
963             (setq end (point-max))))
964         (goto-char end)))
965     count))
966
967 (defun nnmail-process-mmdf-mail-format (func artnum-func &optional junk-func)
968   (let ((delim "^\^A\^A\^A\^A$")
969         (case-fold-search t)
970         (count 0)
971         start message-id end)
972     (goto-char (point-min))
973     (if (not (and (re-search-forward delim nil t)
974                   (forward-line 1)))
975         ;; Possibly wrong format?
976         (error "Error, unknown mail format! (Possibly corrupted.)")
977       ;; Carry on until the bitter end.
978       (while (not (eobp))
979         (setq start (point))
980         ;; Find the end of the head.
981         (narrow-to-region
982          start
983          (if (search-forward "\n\n" nil t)
984              (1- (point))
985            ;; This will never happen, but just to be on the safe side --
986            ;; if there is no head-body delimiter, we search a bit manually.
987            (while (and (looking-at "From \\|[^ \t]+:")
988                        (not (eobp)))
989              (forward-line 1))
990            (point)))
991         ;; Find the Message-ID header.
992         (goto-char (point-min))
993         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
994             (setq message-id (match-string 1))
995           ;; There is no Message-ID here, so we create one.
996           (save-excursion
997             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
998               (beginning-of-line)
999               (insert "Original-")))
1000           (forward-line 1)
1001           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
1002         (run-hooks 'nnmail-prepare-incoming-header-hook)
1003         ;; Find the end of this article.
1004         (goto-char (point-max))
1005         (widen)
1006         (if (re-search-forward delim nil t)
1007             (beginning-of-line)
1008           (goto-char (point-max)))
1009         ;; Allow the backend to save the article.
1010         (save-excursion
1011           (save-restriction
1012             (narrow-to-region start (point))
1013             (goto-char (point-min))
1014             (incf count)
1015             (nnmail-check-duplication message-id func artnum-func junk-func)
1016             (setq end (point-max))))
1017         (goto-char end)
1018         (forward-line 2)))
1019     count))
1020
1021 (defun nnmail-process-maildir-mail-format (func artnum-func)
1022   ;; In a maildir, every file contains exactly one mail.
1023   (let ((case-fold-search t)
1024         message-id)
1025     (goto-char (point-min))
1026     ;; Find the end of the head.
1027     (narrow-to-region
1028      (point-min)
1029      (if (search-forward "\n\n" nil t)
1030          (1- (point))
1031        ;; This will never happen, but just to be on the safe side --
1032        ;; if there is no head-body delimiter, we search a bit manually.
1033        (while (and (looking-at "From \\|[^ \t]+:")
1034                    (not (eobp)))
1035          (forward-line 1))
1036        (point)))
1037     ;; Find the Message-ID header.
1038     (goto-char (point-min))
1039     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
1040         (setq message-id (match-string 1))
1041       ;; There is no Message-ID here, so we create one.
1042       (save-excursion
1043         (when (re-search-backward "^Message-ID[ \t]*:" nil t)
1044           (beginning-of-line)
1045           (insert "Original-")))
1046       (forward-line 1)
1047       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
1048     (run-hooks 'nnmail-prepare-incoming-header-hook)
1049     ;; Allow the backend to save the article.
1050     (widen)
1051     (save-excursion
1052       (goto-char (point-min))
1053       (nnmail-check-duplication message-id func artnum-func))
1054     1))
1055
1056 (defvar nnmail-group-names-not-encoded-p nil
1057   "Non-nil means group names are not encoded.")
1058
1059 (defun nnmail-split-incoming (incoming func &optional exit-func
1060                                        group artnum-func junk-func)
1061   "Go through the entire INCOMING file and pick out each individual mail.
1062 FUNC will be called with the buffer narrowed to each mail.
1063 INCOMING can also be a buffer object.  In that case, the mail
1064 will be copied over from that buffer."
1065   (let ( ;; If this is a group-specific split, we bind the split
1066         ;; methods to just this group.
1067         (nnmail-split-methods (if (and group
1068                                        (not nnmail-resplit-incoming))
1069                                   (list (list group ""))
1070                                 nnmail-split-methods))
1071         (nnmail-group-names-not-encoded-p t))
1072     ;; Insert the incoming file.
1073     (with-current-buffer (get-buffer-create nnmail-article-buffer)
1074       (erase-buffer)
1075       (if (bufferp incoming)
1076           (insert-buffer-substring incoming)
1077         (let ((coding-system-for-read nnmail-incoming-coding-system))
1078           (mm-insert-file-contents incoming)))
1079       (prog1
1080           (if (zerop (buffer-size))
1081               0
1082             (goto-char (point-min))
1083             (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
1084             ;; Handle both babyl, MMDF and unix mail formats, since
1085             ;; movemail will use the former when fetching from a
1086             ;; mailbox, the latter when fetching from a file.
1087             (cond ((or (looking-at "\^L")
1088                        (looking-at "BABYL OPTIONS:"))
1089                    (nnmail-process-babyl-mail-format func artnum-func))
1090                   ((looking-at "\^A\^A\^A\^A")
1091                    (nnmail-process-mmdf-mail-format
1092                     func artnum-func junk-func))
1093                   ((looking-at "Return-Path:")
1094                    (nnmail-process-maildir-mail-format func artnum-func))
1095                   (t
1096                    (nnmail-process-unix-mail-format func artnum-func))))
1097         (when exit-func
1098           (funcall exit-func))
1099         (kill-buffer (current-buffer))))))
1100
1101 (defun nnmail-article-group (func &optional trace junk-func)
1102   "Look at the headers and return an alist of groups that match.
1103 FUNC will be called with the group name to determine the article number."
1104   (let ((methods (or nnmail-split-methods '(("bogus" ""))))
1105         (obuf (current-buffer))
1106         group-art method grp)
1107     (if (and (sequencep methods)
1108              (= (length methods) 1)
1109              (not nnmail-inhibit-default-split-group))
1110         ;; If there is only just one group to put everything in, we
1111         ;; just return a list with just this one method in.
1112         (setq group-art
1113               (list (cons (caar methods) (funcall func (caar methods)))))
1114       ;; We do actual comparison.
1115       ;; Copy the article into the work buffer.
1116       (with-current-buffer nntp-server-buffer
1117         (erase-buffer)
1118         (insert-buffer-substring obuf)
1119         ;; Narrow to headers.
1120         (narrow-to-region
1121          (goto-char (point-min))
1122          (if (search-forward "\n\n" nil t)
1123              (point)
1124            (point-max)))
1125         (goto-char (point-min))
1126         ;; Decode MIME headers and charsets.
1127         (when nnmail-mail-splitting-decodes
1128           (let ((mail-parse-charset nnmail-mail-splitting-charset))
1129             (mail-decode-encoded-word-region (point-min) (point-max))))
1130         ;; Fold continuation lines.
1131         (goto-char (point-min))
1132         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1133           (replace-match " " t t))
1134         ;; Nuke pathologically long headers.  Since Gnus applies
1135         ;; pathologically complex regexps to the buffer, lines
1136         ;; that are looong will take longer than the Universe's
1137         ;; existence to process.
1138         (goto-char (point-min))
1139         (while (not (eobp))
1140           (unless (< (move-to-column nnmail-split-header-length-limit)
1141                      nnmail-split-header-length-limit)
1142             (delete-region (point) (point-at-eol)))
1143           (forward-line 1))
1144         ;; Allow washing.
1145         (goto-char (point-min))
1146         (run-hooks 'nnmail-split-hook)
1147         (when (setq nnmail-split-tracing trace)
1148           (setq nnmail-split-trace nil))
1149         (if (or (and (symbolp nnmail-split-methods)
1150                      (fboundp nnmail-split-methods))
1151                 (and (listp nnmail-split-methods)
1152                      ;; Not a regular split method, so it has to be a
1153                      ;; fancy one.
1154                      (not (let ((top-element (car-safe nnmail-split-methods)))
1155                             (and (= 2 (length top-element))
1156                                  (stringp (nth 0 top-element))
1157                                  (stringp (nth 1 top-element)))))))
1158             (let* ((method-function
1159                     (if (and (symbolp nnmail-split-methods)
1160                              (fboundp nnmail-split-methods))
1161                         nnmail-split-methods
1162                       'nnmail-split-fancy))
1163                    (split
1164                     (condition-case error-info
1165                         ;; `nnmail-split-methods' is a function, so we
1166                         ;; just call this function here and use the
1167                         ;; result.
1168                         (or (funcall method-function)
1169                             (and (not nnmail-inhibit-default-split-group)
1170                                  '("bogus")))
1171                       (error
1172                        (nnheader-message
1173                         5 "Error in `nnmail-split-methods'; using `bogus' mail group: %S" error-info)
1174                        (sit-for 1)
1175                        '("bogus")))))
1176               (setq split (mm-delete-duplicates split))
1177               ;; The article may be "cross-posted" to `junk'.  What
1178               ;; to do?  Just remove the `junk' spec.  Don't really
1179               ;; see anything else to do...
1180               (when (and (memq 'junk split)
1181                          junk-func)
1182                 (funcall junk-func 'junk))
1183               (setq split (delq 'junk split))
1184               (when split
1185                 (setq group-art
1186                       (mapcar
1187                        (lambda (group) (cons group (funcall func group)))
1188                        split))))
1189           ;; Go through the split methods to find a match.
1190           (while (and methods
1191                       (or nnmail-crosspost
1192                           (not group-art)))
1193             (goto-char (point-max))
1194             (setq method (pop methods)
1195                   grp (car method))
1196             (if (or methods
1197                     (not (equal "" (nth 1 method))))
1198                 (when (and
1199                        (ignore-errors
1200                          (if (stringp (nth 1 method))
1201                              (let ((expand (string-match "\\\\[0-9&]" grp))
1202                                    (pos (re-search-backward (cadr method)
1203                                                             nil t)))
1204                                (and expand
1205                                     (setq grp (nnmail-expand-newtext grp)))
1206                                pos)
1207                            ;; Function to say whether this is a match.
1208                            (funcall (nth 1 method) grp)))
1209                        ;; Don't enter the article into the same
1210                        ;; group twice.
1211                        (not (assoc grp group-art)))
1212                   (push (cons grp (funcall func grp))
1213                         group-art))
1214               ;; This is the final group, which is used as a
1215               ;; catch-all.
1216               (when (and (not group-art)
1217                          (not nnmail-inhibit-default-split-group))
1218                 (setq group-art
1219                       (list (cons (car method)
1220                                   (funcall func (car method))))))))
1221           ;; Fall back on "bogus" if all else fails.
1222           (when (and (not group-art)
1223                      (not nnmail-inhibit-default-split-group))
1224             (setq group-art (list (cons "bogus" (funcall func "bogus"))))))
1225         ;; Produce a trace if non-empty.
1226         (when (and trace nnmail-split-trace)
1227           (let ((restore (current-buffer)))
1228             (nnheader-set-temp-buffer "*Split Trace*")
1229             (gnus-add-buffer)
1230             (dolist (trace (nreverse nnmail-split-trace))
1231               (prin1 trace (current-buffer))
1232               (insert "\n"))
1233             (goto-char (point-min))
1234             (gnus-configure-windows 'split-trace)
1235             (set-buffer restore)))
1236         (widen)
1237         ;; See whether the split methods returned `junk'.
1238         (if (equal group-art '(junk))
1239             nil
1240           ;; The article may be "cross-posted" to `junk'.  What
1241           ;; to do?  Just remove the `junk' spec.  Don't really
1242           ;; see anything else to do...
1243           (let (elem)
1244             (while (setq elem (car (memq 'junk group-art)))
1245               (setq group-art (delq elem group-art)))
1246             (nreverse group-art)))))))
1247
1248 (defun nnmail-insert-lines ()
1249   "Insert how many lines there are in the body of the mail.
1250 Return the number of characters in the body."
1251   (let (lines chars)
1252     (save-excursion
1253       (goto-char (point-min))
1254       (unless (search-forward "\n\n" nil t)
1255         (goto-char (point-max))
1256         (insert "\n"))
1257       (setq chars (- (point-max) (point)))
1258       (setq lines (count-lines (point) (point-max)))
1259       (forward-char -1)
1260       (save-excursion
1261         (when (re-search-backward "^Lines: " nil t)
1262           (delete-region (point) (progn (forward-line 1) (point)))))
1263       (beginning-of-line)
1264       (insert (format "Lines: %d\n" (max lines 0)))
1265       chars)))
1266
1267 (defun nnmail-insert-xref (group-alist)
1268   "Insert an Xref line based on the (group . article) alist."
1269   (save-excursion
1270     (goto-char (point-min))
1271     (unless (search-forward "\n\n" nil t)
1272       (goto-char (point-max))
1273       (insert "\n"))
1274     (forward-char -1)
1275     (when (re-search-backward "^Xref: " nil t)
1276       (delete-region (match-beginning 0)
1277                      (progn (forward-line 1) (point))))
1278     (insert (format "Xref: %s" (system-name)))
1279     (while group-alist
1280       (insert (if (mm-multibyte-p)
1281                   (mm-string-as-multibyte
1282                    (format " %s:%d" (caar group-alist) (cdar group-alist)))
1283                 (mm-string-as-unibyte
1284                  (format " %s:%d" (caar group-alist) (cdar group-alist)))))
1285       (setq group-alist (cdr group-alist)))
1286     (insert "\n")))
1287
1288 ;;; Message washing functions
1289
1290 (defun nnmail-remove-leading-whitespace ()
1291   "Remove excessive whitespace from all headers."
1292   (goto-char (point-min))
1293   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1294     (replace-match "\\1" t)))
1295
1296 (defun nnmail-remove-list-identifiers ()
1297   "Remove list identifiers from Subject headers."
1298   (let ((regexp
1299          (if (consp nnmail-list-identifiers)
1300              (mapconcat 'identity nnmail-list-identifiers " *\\|")
1301            nnmail-list-identifiers)))
1302     (when regexp
1303       (goto-char (point-min))
1304       (while (re-search-forward
1305               (concat "^Subject: +\\(R[Ee]: +\\)*\\(" regexp " *\\)")
1306               nil t)
1307         (delete-region (match-beginning 2) (match-end 0))
1308         (beginning-of-line))
1309       (when (re-search-forward "^Subject: +\\(\\(R[Ee]: +\\)+\\)R[Ee]: +"
1310                                nil t)
1311         (delete-region (match-beginning 1) (match-end 1))
1312         (beginning-of-line)))))
1313
1314 (defun nnmail-remove-tabs ()
1315   "Translate TAB characters into SPACE characters."
1316   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1317
1318 (defcustom nnmail-broken-references-mailers
1319   "^X-Mailer:.*\\(Eudora\\|Pegasus\\)"
1320   "Header line matching mailer producing bogus References lines.
1321 See `nnmail-ignore-broken-references'."
1322   :group 'nnmail-prepare
1323   :version "23.1" ;; No Gnus
1324   :type 'regexp)
1325
1326 (defun nnmail-ignore-broken-references ()
1327   "Ignore the References line and use In-Reply-To
1328
1329 Eudora has a broken References line, but an OK In-Reply-To."
1330   (goto-char (point-min))
1331   (when (re-search-forward nnmail-broken-references-mailers nil t)
1332     (goto-char (point-min))
1333     (when (re-search-forward "^References:" nil t)
1334       (beginning-of-line)
1335       (insert "X-Gnus-Broken-Eudora-"))
1336     (goto-char (point-min))
1337     (when (re-search-forward "^\\(In-Reply-To:[^\n]+\\)\n[ \t]+" nil t)
1338       (replace-match "\\1" t))))
1339
1340 (defalias 'nnmail-fix-eudora-headers 'nnmail-ignore-broken-references)
1341 (make-obsolete 'nnmail-fix-eudora-headers 'nnmail-ignore-broken-references "Emacs 23.1")
1342
1343 (custom-add-option 'nnmail-prepare-incoming-header-hook
1344                    'nnmail-ignore-broken-references)
1345
1346 ;;; Utility functions
1347
1348 (declare-function gnus-activate-group "gnus-start"
1349                   (group &optional scan dont-check method dont-sub-check))
1350
1351 (defun nnmail-do-request-post (accept-func &optional server)
1352   "Utility function to directly post a message to an nnmail-derived group.
1353 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
1354 to actually put the message in the right group."
1355   (let ((success t))
1356     (dolist (mbx (message-unquote-tokens
1357                   (message-tokenize-header
1358                    (message-fetch-field "Newsgroups") ", ")) success)
1359       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1360         (or (gnus-active to-newsgroup)
1361             (gnus-activate-group to-newsgroup)
1362             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1363                                        to-newsgroup))
1364                 (or (and (gnus-request-create-group
1365                           to-newsgroup gnus-command-method)
1366                          (gnus-activate-group to-newsgroup nil nil
1367                                               gnus-command-method))
1368                     (error "Couldn't create group %s" to-newsgroup)))
1369             (error "No such group: %s" to-newsgroup))
1370         (unless (funcall accept-func mbx (nth 1 gnus-command-method))
1371           (setq success nil))))))
1372
1373 (defun nnmail-split-fancy ()
1374   "Fancy splitting method.
1375 See the documentation for the variable `nnmail-split-fancy' for details."
1376   (with-syntax-table nnmail-split-fancy-syntax-table
1377     (nnmail-split-it nnmail-split-fancy)))
1378
1379 (defvar nnmail-split-cache nil)
1380 ;; Alist of split expressions their equivalent regexps.
1381
1382 (defun nnmail-split-it (split)
1383   ;; Return a list of groups matching SPLIT.
1384   (let (cached-pair)
1385     (cond
1386      ;; nil split
1387      ((null split)
1388       nil)
1389
1390      ;; A group name.  Do the \& and \N subs into the string.
1391      ((stringp split)
1392       (when nnmail-split-tracing
1393         (push split nnmail-split-trace))
1394       (list (nnmail-expand-newtext split)))
1395
1396      ;; Junk the message.
1397      ((eq split 'junk)
1398       (when nnmail-split-tracing
1399         (push "junk" nnmail-split-trace))
1400       (list 'junk))
1401
1402      ;; Builtin & operation.
1403      ((eq (car split) '&)
1404       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1405
1406      ;; Builtin | operation.
1407      ((eq (car split) '|)
1408       (let (done)
1409         (while (and (not done) (cdr split))
1410           (setq split (cdr split)
1411                 done (nnmail-split-it (car split))))
1412         done))
1413
1414      ;; Builtin : operation.
1415      ((eq (car split) ':)
1416       (when nnmail-split-tracing
1417         (push split nnmail-split-trace))
1418       (nnmail-split-it (save-excursion (eval (cdr split)))))
1419
1420      ;; Builtin ! operation.
1421      ((eq (car split) '!)
1422       (funcall (cadr split) (nnmail-split-it (caddr split))))
1423
1424      ;; Check the cache for the regexp for this split.
1425      ((setq cached-pair (assq split nnmail-split-cache))
1426       (let (split-result
1427             (end-point (point-max))
1428             (value (nth 1 split)))
1429         (if (symbolp value)
1430             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1431         (while (and (goto-char end-point)
1432                     (re-search-backward (cdr cached-pair) nil t))
1433           (when nnmail-split-tracing
1434             (push split nnmail-split-trace))
1435           (let ((split-rest (cddr split))
1436                 (end (match-end 0))
1437                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).
1438                 ;; So, start-of-value is the point just before the
1439                 ;; beginning of the value, whereas after-header-name
1440                 ;; is the point just after the field name.
1441                 (start-of-value (match-end 1))
1442                 (after-header-name (match-end 2)))
1443             ;; Start the next search just before the beginning of the
1444             ;; VALUE match.
1445             (setq end-point (1- start-of-value))
1446             ;; Handle - RESTRICTs
1447             (while (eq (car split-rest) '-)
1448               ;; RESTRICT must start after-header-name and
1449               ;; end after start-of-value, so that, for
1450               ;; (any "foo" - "x-foo" "foo.list")
1451               ;; we do not exclude foo.list just because
1452               ;; the header is: ``To: x-foo, foo''
1453               (goto-char end)
1454               (if (and (re-search-backward (cadr split-rest)
1455                                            after-header-name t)
1456                        (> (match-end 0) start-of-value))
1457                   (setq split-rest nil)
1458                 (setq split-rest (cddr split-rest))))
1459             (when split-rest
1460               (goto-char end)
1461               (let ((value (nth 1 split)))
1462                 (if (symbolp value)
1463                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1464                 ;; Someone might want to do a \N sub on this match, so get the
1465                 ;; correct match positions.
1466                 (re-search-backward value start-of-value))
1467               (dolist (sp (nnmail-split-it (car split-rest)))
1468                 (unless (member sp split-result)
1469                   (push sp split-result))))))
1470         split-result))
1471
1472      ;; Not in cache, compute a regexp for the field/value pair.
1473      (t
1474       (let ((field (nth 0 split))
1475             (value (nth 1 split))
1476             (split-rest (cddr split))
1477             partial-front
1478             partial-rear
1479             regexp)
1480         (if (symbolp value)
1481             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1482         (if (and (>= (length value) 2)
1483                  (string= ".*" (substring value 0 2)))
1484             (setq value (substring value 2)
1485                   partial-front ""))
1486         ;; Same trick for the rear of the regexp
1487         (if (and (>= (length value) 2)
1488                  (string= ".*" (substring value -2)))
1489             (setq value (substring value 0 -2)
1490                   partial-rear ""))
1491         ;; Invert the match-partial-words behavior if the optional
1492         ;; last element is specified.
1493         (while (eq (car split-rest) '-)
1494           (setq split-rest (cddr split-rest)))
1495         (when (if (cadr split-rest)
1496                   (not nnmail-split-fancy-match-partial-words)
1497                 nnmail-split-fancy-match-partial-words)
1498           (setq partial-front ""
1499                 partial-rear ""))
1500         (setq regexp (concat "^\\(\\("
1501                              (if (symbolp field)
1502                                  (cdr (assq field nnmail-split-abbrev-alist))
1503                                field)
1504                              "\\):.*\\)"
1505                              (or partial-front "\\<")
1506                              "\\("
1507                              value
1508                              "\\)"
1509                              (or partial-rear "\\>")))
1510         (push (cons split regexp) nnmail-split-cache)
1511         ;; Now that it's in the cache, just call nnmail-split-it again
1512         ;; on the same split, which will find it immediately in the cache.
1513         (nnmail-split-it split))))))
1514
1515 (defun nnmail-expand-newtext (newtext)
1516   (let ((len (length newtext))
1517         (pos 0)
1518         c expanded beg N did-expand)
1519     (while (< pos len)
1520       (setq beg pos)
1521       (while (and (< pos len)
1522                   (not (= (aref newtext pos) ?\\)))
1523         (setq pos (1+ pos)))
1524       (unless (= beg pos)
1525         (push (substring newtext beg pos) expanded))
1526       (when (< pos len)
1527         ;; We hit a \; expand it.
1528         (setq did-expand t
1529               pos (1+ pos)
1530               c (aref newtext pos))
1531         (if (not (or (= c ?\&)
1532                      (and (>= c ?1)
1533                           (<= c ?9))))
1534             ;; \ followed by some character we don't expand.
1535             (push (char-to-string c) expanded)
1536           ;; \& or \N
1537           (if (= c ?\&)
1538               (setq N 0)
1539             (setq N (- c ?0)))
1540           (when (match-beginning N)
1541             (push (if nnmail-split-lowercase-expanded
1542                       (downcase (buffer-substring (match-beginning N)
1543                                                   (match-end N)))
1544                     (buffer-substring (match-beginning N) (match-end N)))
1545                   expanded))))
1546       (setq pos (1+ pos)))
1547     (if did-expand
1548         (apply 'concat (nreverse expanded))
1549       newtext)))
1550
1551 ;; Activate a backend only if it isn't already activated.
1552 ;; If FORCE, re-read the active file even if the backend is
1553 ;; already activated.
1554 (defun nnmail-activate (backend &optional force)
1555   (nnheader-init-server-buffer)
1556   (let (file timestamp file-time)
1557     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1558             force
1559             (and (setq file (ignore-errors
1560                               (symbol-value (intern (format "%s-active-file"
1561                                                             backend)))))
1562                  (setq file-time (nth 5 (file-attributes file)))
1563                  (or (not
1564                       (setq timestamp
1565                             (condition-case ()
1566                                 (symbol-value (intern
1567                                                (format "%s-active-timestamp"
1568                                                        backend)))
1569                               (error 'none))))
1570                      (not (consp timestamp))
1571                      (equal timestamp '(0 0))
1572                      (> (nth 0 file-time) (nth 0 timestamp))
1573                      (and (= (nth 0 file-time) (nth 0 timestamp))
1574                           (> (nth 1 file-time) (nth 1 timestamp))))))
1575         (save-excursion
1576           (or (eq timestamp 'none)
1577               (set (intern (format "%s-active-timestamp" backend))
1578                    file-time))
1579           (funcall (intern (format "%s-request-list" backend)))))
1580     t))
1581
1582 (defun nnmail-message-id ()
1583   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1584
1585 ;;;
1586 ;;; nnmail duplicate handling
1587 ;;;
1588
1589 (defvar nnmail-cache-buffer nil)
1590
1591 (defun nnmail-cache-open ()
1592   (if (or (not nnmail-treat-duplicates)
1593           (and nnmail-cache-buffer
1594                (buffer-name nnmail-cache-buffer)))
1595       ()                                ; The buffer is open.
1596     (with-current-buffer
1597        (setq nnmail-cache-buffer
1598              (get-buffer-create " *nnmail message-id cache*"))
1599       (gnus-add-buffer)
1600       (when (file-exists-p nnmail-message-id-cache-file)
1601         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1602       (set-buffer-modified-p nil)
1603       (current-buffer))))
1604
1605 (defun nnmail-cache-close ()
1606   (when (and nnmail-cache-buffer
1607              nnmail-treat-duplicates
1608              (buffer-name nnmail-cache-buffer)
1609              (buffer-modified-p nnmail-cache-buffer))
1610     (with-current-buffer nnmail-cache-buffer
1611       ;; Weed out the excess number of Message-IDs.
1612       (goto-char (point-max))
1613       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1614         (progn
1615           (beginning-of-line)
1616           (delete-region (point-min) (point))))
1617       ;; Save the buffer.
1618       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1619           (make-directory (file-name-directory nnmail-message-id-cache-file)
1620                           t))
1621       (nnmail-write-region (point-min) (point-max)
1622                            nnmail-message-id-cache-file nil 'silent)
1623       (set-buffer-modified-p nil)
1624       (setq nnmail-cache-buffer nil)
1625       (gnus-kill-buffer (current-buffer)))))
1626
1627 (defun nnmail-cache-insert (id grp &optional subject sender)
1628   (when (stringp id)
1629     ;; this will handle cases like `B r' where the group is nil
1630     (let ((grp (or grp gnus-newsgroup-name "UNKNOWN")))
1631       (run-hook-with-args 'nnmail-spool-hook
1632                           id grp subject sender))
1633     (when nnmail-treat-duplicates
1634       ;; Store some information about the group this message is written
1635       ;; to.  This is passed in as the grp argument -- all locations this
1636       ;; has been called from have been checked and the group is available.
1637       ;; The only ambiguous case is nnmail-check-duplication which will only
1638       ;; pass the first (of possibly >1) group which matches. -Josh
1639       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1640         (nnmail-cache-open))
1641       (with-current-buffer nnmail-cache-buffer
1642         (goto-char (point-max))
1643         (if (and grp (not (string= "" grp))
1644                  (gnus-methods-equal-p gnus-command-method
1645                                        (nnmail-cache-primary-mail-backend)))
1646             (let ((regexp (if (consp nnmail-cache-ignore-groups)
1647                               (mapconcat 'identity nnmail-cache-ignore-groups
1648                                          "\\|")
1649                             nnmail-cache-ignore-groups)))
1650               (unless (and regexp (string-match regexp grp))
1651                 (insert id "\t" grp "\n")))
1652           (insert id "\n"))))))
1653
1654 (defun nnmail-cache-primary-mail-backend ()
1655   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1656         (be nil)
1657         (res nil)
1658         (get-new-mail nil))
1659     (while (and (null res) be-list)
1660       (setq be (car be-list))
1661       (setq be-list (cdr be-list))
1662       (when (and (gnus-method-option-p be 'respool)
1663                  (setq get-new-mail
1664                        (intern (format "%s-get-new-mail" (car be))))
1665                  (boundp get-new-mail)
1666                  (symbol-value get-new-mail))
1667         (setq res be)))
1668     res))
1669
1670 ;; Fetch the group name corresponding to the message id stored in the
1671 ;; cache.
1672 (defun nnmail-cache-fetch-group (id)
1673   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1674     (with-current-buffer nnmail-cache-buffer
1675       (goto-char (point-max))
1676       (when (search-backward id nil t)
1677         (beginning-of-line)
1678         (skip-chars-forward "^\n\r\t")
1679         (unless (looking-at "[\r\n]")
1680           (forward-char 1)
1681           (buffer-substring (point) (point-at-eol)))))))
1682
1683 ;; Function for nnmail-split-fancy: look up all references in the
1684 ;; cache and if a match is found, return that group.
1685 (defun nnmail-split-fancy-with-parent ()
1686   "Split this message into the same group as its parent.
1687 This function can be used as an entry in `nnmail-split-fancy', for
1688 example like this: (: nnmail-split-fancy-with-parent)
1689 For a message to be split, it looks for the parent message in the
1690 References or In-Reply-To header and then looks in the message id
1691 cache file (given by the variable `nnmail-message-id-cache-file') to
1692 see which group that message was put in.  This group is returned.
1693
1694 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1695   (let* ((refstr (or (message-fetch-field "references")
1696                      (message-fetch-field "in-reply-to")))
1697          (references nil)
1698          (res nil)
1699          (regexp (if (consp nnmail-split-fancy-with-parent-ignore-groups)
1700                      (mapconcat
1701                       (lambda (x) (format "\\(%s\\)" x))
1702                       nnmail-split-fancy-with-parent-ignore-groups
1703                       "\\|")
1704                    nnmail-split-fancy-with-parent-ignore-groups)))
1705     (when refstr
1706       (setq references (nreverse (gnus-split-references refstr)))
1707       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1708         (nnmail-cache-open))
1709       (dolist (x references)
1710         (setq res (or (nnmail-cache-fetch-group x) res))
1711         (when (or (member res '("delayed" "drafts" "queue"))
1712                   (and regexp res (string-match regexp res)))
1713           (setq res nil)))
1714       res)))
1715
1716 (defun nnmail-cache-id-exists-p (id)
1717   (when nnmail-treat-duplicates
1718     (with-current-buffer nnmail-cache-buffer
1719       (goto-char (point-max))
1720       (search-backward id nil t))))
1721
1722 (defun nnmail-fetch-field (header)
1723   (save-excursion
1724     (save-restriction
1725       (message-narrow-to-head)
1726       (message-fetch-field header))))
1727
1728 (defun nnmail-check-duplication (message-id func artnum-func
1729                                             &optional junk-func)
1730   (run-hooks 'nnmail-prepare-incoming-message-hook)
1731   ;; If this is a duplicate message, then we do not save it.
1732   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1733          (case-fold-search t)
1734          (action (when duplication
1735                    (cond
1736                     ((memq nnmail-treat-duplicates '(warn delete))
1737                      nnmail-treat-duplicates)
1738                     ((functionp nnmail-treat-duplicates)
1739                      (funcall nnmail-treat-duplicates message-id))
1740                     (t
1741                      nnmail-treat-duplicates))))
1742          group-art)
1743     ;; We insert a line that says what the mail source is.
1744     (let ((case-fold-search t))
1745       (goto-char (point-min))
1746       (re-search-forward "^message-id[ \t]*:" nil t)
1747       (beginning-of-line)
1748       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1749
1750     ;; Let the backend save the article (or not).
1751     (cond
1752      ((not duplication)
1753       (funcall func (setq group-art
1754                           (nreverse (nnmail-article-group
1755                                      artnum-func nil junk-func))))
1756       (nnmail-cache-insert message-id (caar group-art)))
1757      ((eq action 'delete)
1758       (setq group-art nil))
1759      ((eq action 'warn)
1760       ;; We insert a warning.
1761       (let ((case-fold-search t))
1762         (goto-char (point-min))
1763         (re-search-forward "^message-id[ \t]*:" nil t)
1764         (beginning-of-line)
1765         (insert
1766          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1767         (funcall func (setq group-art
1768                             (nreverse (nnmail-article-group artnum-func))))))
1769      (t
1770       (funcall func (setq group-art
1771                           (nreverse (nnmail-article-group artnum-func))))))
1772     ;; Add the group-art list to the history list.
1773     (if group-art
1774         (push group-art nnmail-split-history)
1775       (delete-region (point-min) (point-max)))))
1776
1777 ;;; Get new mail.
1778
1779 (defvar nnmail-fetched-sources nil)
1780
1781 (defun nnmail-get-value (&rest args)
1782   (let ((sym (intern (apply 'format args))))
1783     (when (boundp sym)
1784       (symbol-value sym))))
1785
1786 (defun nnmail-get-new-mail (method exit-func temp
1787                             &optional group spool-func)
1788   "Read new incoming mail."
1789   (nnmail-get-new-mail-1 method exit-func temp group nil spool-func))
1790
1791 (defun nnmail-get-new-mail-1 (method exit-func temp
1792                               group in-group spool-func)
1793   (let* ((sources mail-sources)
1794          fetching-sources
1795          (i 0)
1796          (new 0)
1797          (total 0)
1798          incoming incomings source)
1799     (when (and (nnmail-get-value "%s-get-new-mail" method)
1800                sources)
1801       (while (setq source (pop sources))
1802         ;; Use group's parameter
1803         (when (eq (car source) 'group)
1804           (let ((mail-sources
1805                  (list
1806                   (gnus-group-find-parameter
1807                    (concat (symbol-name method) ":" group)
1808                    'mail-source t))))
1809             (nnmail-get-new-mail-1 method exit-func temp
1810                                    group group spool-func))
1811           (setq source nil))
1812         ;; Hack to only fetch the contents of a single group's spool file.
1813         (when (and (eq (car source) 'directory)
1814                    (null nnmail-scan-directory-mail-source-once)
1815                    group)
1816           (mail-source-bind (directory source)
1817             (setq source (append source
1818                                  (list
1819                                   :predicate
1820                                   (gnus-byte-compile
1821                                    `(lambda (file)
1822                                       (string-equal
1823                                        ,(concat group suffix)
1824                                        (file-name-nondirectory file)))))))))
1825         (when nnmail-fetched-sources
1826           (if (member source nnmail-fetched-sources)
1827               (setq source nil)
1828             (push source nnmail-fetched-sources)
1829             (push source fetching-sources)))))
1830     (when fetching-sources
1831       ;; We first activate all the groups.
1832       (nnmail-activate method)
1833       ;; Allow the user to hook.
1834       (run-hooks 'nnmail-pre-get-new-mail-hook)
1835       ;; Open the message-id cache.
1836       (nnmail-cache-open)
1837       ;; The we go through all the existing mail source specification
1838       ;; and fetch the mail from each.
1839       (while (setq source (pop fetching-sources))
1840         (when (setq new
1841                     (mail-source-fetch
1842                      source
1843                      (gnus-byte-compile
1844                       `(lambda (file orig-file)
1845                          (nnmail-split-incoming
1846                           file ',(intern (format "%s-save-mail" method))
1847                           ',spool-func
1848                           (or in-group
1849                               (if (equal file orig-file)
1850                                   nil
1851                                 (nnmail-get-split-group orig-file ',source)))
1852                           ',(intern (format "%s-active-number" method)))))))
1853           (incf total new)
1854           (incf i)))
1855       ;; If we did indeed read any incoming spools, we save all info.
1856       (if (zerop total)
1857           (when mail-source-plugged
1858             (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1859                               method (car source)))
1860         (nnmail-save-active
1861          (nnmail-get-value "%s-group-alist" method)
1862          (nnmail-get-value "%s-active-file" method))
1863         (when exit-func
1864           (funcall exit-func))
1865         (run-hooks 'nnmail-read-incoming-hook)
1866         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1867                           total))
1868       ;; Close the message-id cache.
1869       (nnmail-cache-close)
1870       ;; Allow the user to hook.
1871       (run-hooks 'nnmail-post-get-new-mail-hook))))
1872
1873 (defun nnmail-expired-article-p (group time force &optional inhibit)
1874   "Say whether an article that is TIME old in GROUP should be expired.
1875 If TIME is nil, then return the cutoff time for oldness instead."
1876   (if force
1877       (if (null time)
1878           (current-time)
1879         t)
1880     (let ((days (or (and nnmail-expiry-wait-function
1881                          (funcall nnmail-expiry-wait-function group))
1882                     nnmail-expiry-wait)))
1883       (cond ((or (eq days 'never)
1884                  (and (not force)
1885                       inhibit))
1886              ;; This isn't an expirable group.
1887              nil)
1888             ((eq days 'immediate)
1889              ;; We expire all articles on sight.
1890              (if (null time)
1891                  (current-time)
1892                t))
1893             ((equal time '(0 0))
1894             ;; This is an ange-ftp group, and we don't have any dates.
1895              nil)
1896             ((numberp days)
1897              (setq days (days-to-time days))
1898              ;; Compare the time with the current time.
1899              (if (null time)
1900                  (time-subtract (current-time) days)
1901                (ignore-errors (time-less-p days (time-since time)))))))))
1902
1903 (declare-function gnus-group-mark-article-read "gnus-group" (group article))
1904
1905 (defun nnmail-expiry-target-group (target group)
1906   ;; Do not invoke this from nntp-server-buffer!  At least nnfolder clears
1907   ;; that buffer if the nnfolder group isn't selected.
1908   (let (nnmail-cache-accepted-message-ids)
1909     ;; Don't enter Message-IDs into cache.
1910     ;; Let users hack it in TARGET function.
1911     (when (functionp target)
1912       (setq target (funcall target group)))
1913     (unless (eq target 'delete)
1914       (when (or (gnus-request-group target)
1915                 (gnus-request-create-group target))
1916         (let ((group-art (gnus-request-accept-article target nil nil t)))
1917           (when (and (consp group-art)
1918                      (cdr group-art))
1919             (gnus-group-mark-article-read target (cdr group-art))))))))
1920
1921 (defun nnmail-fancy-expiry-target (group)
1922   "Returns a target expiry group determined by `nnmail-fancy-expiry-targets'."
1923   (let* (header
1924          (case-fold-search nil)
1925          (from (or (message-fetch-field "from") ""))
1926          (to (or (message-fetch-field "to") ""))
1927          (date (message-fetch-field "date"))
1928          (target 'delete))
1929     (setq date (if date
1930                    (condition-case err
1931                        (date-to-time date)
1932                      (error
1933                       (message "%s" (error-message-string err))
1934                       (current-time)))
1935                  (current-time)))
1936     (dolist (regexp-target-pair (reverse nnmail-fancy-expiry-targets) target)
1937       (setq header (car regexp-target-pair))
1938       (cond
1939        ;; If the header is to-from then match against the
1940        ;; To or From header
1941        ((and (equal header 'to-from)
1942              (or (string-match (cadr regexp-target-pair) from)
1943                  (and (string-match (cadr regexp-target-pair) to)
1944                       (let ((rmail-dont-reply-to-names
1945                              (message-dont-reply-to-names)))
1946                         (equal (rmail-dont-reply-to from) "")))))
1947         (setq target (format-time-string (caddr regexp-target-pair) date)))
1948        ((and (not (equal header 'to-from))
1949              (string-match (cadr regexp-target-pair)
1950                            (or
1951                             (message-fetch-field header)
1952                             "")))
1953         (setq target
1954               (format-time-string (caddr regexp-target-pair) date)))))))
1955
1956 (defun nnmail-check-syntax ()
1957   "Check (and modify) the syntax of the message in the current buffer."
1958   (save-restriction
1959     (message-narrow-to-head)
1960     (let ((case-fold-search t))
1961       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1962         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1963
1964 (defun nnmail-write-region (start end filename &optional append visit lockname)
1965   "Do a `write-region', and then set the file modes."
1966   (let ((coding-system-for-write nnmail-file-coding-system)
1967         (file-name-coding-system nnmail-pathname-coding-system))
1968     (write-region start end filename append visit lockname)
1969     (set-file-modes filename nnmail-default-file-modes)))
1970
1971 ;;;
1972 ;;; Status functions
1973 ;;;
1974
1975 (defun nnmail-replace-status (name value)
1976   "Make status NAME and VALUE part of the current status line."
1977   (save-restriction
1978     (message-narrow-to-head)
1979     (let ((status (nnmail-decode-status)))
1980       (setq status (delq (member name status) status))
1981       (when value
1982         (push (cons name value) status))
1983       (message-remove-header "status")
1984       (goto-char (point-max))
1985       (insert "Status: " (nnmail-encode-status status) "\n"))))
1986
1987 (defun nnmail-decode-status ()
1988   "Return a status-value alist from STATUS."
1989   (goto-char (point-min))
1990   (when (re-search-forward "^Status: " nil t)
1991     (let (name value status)
1992       (save-restriction
1993         ;; Narrow to the status.
1994         (narrow-to-region
1995          (point)
1996          (if (re-search-forward "^[^ \t]" nil t)
1997              (1- (point))
1998            (point-max)))
1999         ;; Go through all elements and add them to the list.
2000         (goto-char (point-min))
2001         (while (re-search-forward "[^ \t=]+" nil t)
2002           (setq name (match-string 0))
2003           (if (not (eq (char-after) ?=))
2004               ;; Implied "yes".
2005               (setq value "yes")
2006             (forward-char 1)
2007             (if (not (eq (char-after) ?\"))
2008                 (if (not (looking-at "[^ \t]"))
2009                     ;; Implied "no".
2010                     (setq value "no")
2011                   ;; Unquoted value.
2012                   (setq value (match-string 0))
2013                   (goto-char (match-end 0)))
2014               ;; Quoted value.
2015               (setq value (read (current-buffer)))))
2016           (push (cons name value) status)))
2017       status)))
2018
2019 (defun nnmail-encode-status (status)
2020   "Return a status string from STATUS."
2021   (mapconcat
2022    (lambda (elem)
2023      (concat
2024       (car elem) "="
2025       (if (string-match "[ \t]" (cdr elem))
2026           (prin1-to-string (cdr elem))
2027         (cdr elem))))
2028    status " "))
2029
2030 (defun nnmail-split-history ()
2031   "Generate an overview of where the last mail split put articles."
2032   (interactive)
2033   (unless nnmail-split-history
2034     (error "No current split history"))
2035   (with-output-to-temp-buffer "*nnmail split history*"
2036     (with-current-buffer standard-output
2037       (fundamental-mode))               ; for Emacs 20.4+
2038       (dolist (elem nnmail-split-history)
2039         (princ (mapconcat (lambda (ga)
2040                             (concat (car ga) ":" (int-to-string (cdr ga))))
2041                           elem
2042                           ", "))
2043         (princ "\n"))))
2044
2045 (defun nnmail-purge-split-history (group)
2046   "Remove all instances of GROUP from `nnmail-split-history'."
2047   (let ((history nnmail-split-history))
2048     (while history
2049       (setcar history (gnus-remove-if (lambda (e) (string= (car e) group))
2050                                       (car history)))
2051       (pop history))
2052     (setq nnmail-split-history (delq nil nnmail-split-history))))
2053
2054 (defun nnmail-new-mail-p (group)
2055   "Say whether GROUP has new mail."
2056   (let ((his nnmail-split-history)
2057         found)
2058     (while his
2059       (when (assoc group (pop his))
2060         (setq found t
2061               his nil)))
2062     found))
2063
2064 (defun nnmail-within-headers-p ()
2065   "Check to see if point is within the headers of a unix mail message.
2066 Doesn't change point."
2067   (let ((pos (point)))
2068     (save-excursion
2069       (and (nnmail-search-unix-mail-delim-backward)
2070            (not (search-forward "\n\n" pos t))))))
2071
2072 (run-hooks 'nnmail-load-hook)
2073
2074 (provide 'nnmail)
2075
2076 ;;; nnmail.el ends here