lisp/ChangeLog (2014-10-24): Add bug#
[gnus] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2
3 ;; Copyright (C) 1995-2014 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (eval-when-compile (require 'cl))
28
29 (require 'gnus)                         ; for macro gnus-kill-buffer, at least
30 (require 'nnheader)
31 (require 'message)
32 (require 'gnus-util)
33 (require 'mail-source)
34 (require 'mm-util)
35 (require 'gnus-int)
36
37 (autoload 'gnus-add-buffer "gnus")
38 (autoload 'gnus-kill-buffer "gnus")
39 (eval-when-compile
40   (autoload 'mail-send-and-exit "sendmail" nil t))
41
42 (defgroup nnmail nil
43   "Reading mail with Gnus."
44   :group 'gnus)
45
46 (defgroup nnmail-retrieve nil
47   "Retrieving new mail."
48   :group 'nnmail)
49
50 (defgroup nnmail-prepare nil
51   "Preparing (or mangling) new mail after retrieval."
52   :group 'nnmail)
53
54 (defgroup nnmail-duplicate nil
55   "Handling of duplicate mail messages."
56   :group 'nnmail)
57
58 (defgroup nnmail-split nil
59   "Organizing the incoming mail in folders."
60   :group 'nnmail)
61
62 (defgroup nnmail-files nil
63   "Mail files."
64   :group 'gnus-files
65   :group 'nnmail)
66
67 (defgroup nnmail-expire nil
68   "Expiring old mail."
69   :group 'nnmail)
70
71 (defgroup nnmail-procmail nil
72   "Interfacing with procmail and other mail agents."
73   :group 'nnmail)
74
75 (defgroup nnmail-various nil
76   "Various mail options."
77   :group 'nnmail)
78
79 (defcustom nnmail-split-methods '(("mail.misc" ""))
80   "*Incoming mail will be split according to this variable.
81
82 If you'd like, for instance, one mail group for mail from the
83 \"4ad-l\" mailing list, one group for junk mail and one for everything
84 else, you could do something like this:
85
86  (setq nnmail-split-methods
87        '((\"mail.4ad\" \"From:.*4ad\")
88          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
89          (\"mail.misc\" \"\")))
90
91 As you can see, this variable is a list of lists, where the first
92 element in each \"rule\" is the name of the group (which, by the way,
93 does not have to be called anything beginning with \"mail\",
94 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
95 nnmail will try to match on the header to find a fit.
96
97 The second element can also be a function.  In that case, it will be
98 called narrowed to the headers with the first element of the rule as
99 the argument.  It should return a non-nil value if it thinks that the
100 mail belongs in that group.
101
102 The last element should always have \"\" as the regexp.
103
104 This variable can also have a function as its value, and it can
105 also have a fancy split method as its value.  See
106 `nnmail-split-fancy' for an explanation of that syntax."
107   :group 'nnmail-split
108   :type '(choice (repeat :tag "Alist" (group (string :tag "Name")
109                                              (choice regexp function)))
110                  (function-item nnmail-split-fancy)
111                  (function :tag "Other")))
112
113 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
114 (defcustom nnmail-crosspost t
115   "If non-nil, do crossposting if several split methods match the mail.
116 If nil, the first match found will be used."
117   :group 'nnmail-split
118   :type 'boolean)
119
120 (defcustom nnmail-split-fancy-with-parent-ignore-groups nil
121   "Regexp that matches group names to be ignored when applying `nnmail-split-fancy-with-parent'.
122 This can also be a list of regexps."
123   :version "22.1"
124   :group 'nnmail-split
125   :type '(choice (const :tag "none" nil)
126                  (regexp :value ".*")
127                  (repeat :value (".*") regexp)))
128
129 (defcustom nnmail-cache-ignore-groups nil
130   "Regexp that matches group names to be ignored when inserting message ids into the cache (`nnmail-cache-insert').
131 This can also be a list of regexps."
132   :version "22.1"
133   :group 'nnmail-split
134   :type '(choice (const :tag "none" nil)
135                  (regexp :value ".*")
136                  (repeat :value (".*") regexp)))
137
138 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
139 (defcustom nnmail-keep-last-article nil
140   "If non-nil, nnmail will never delete/move a group's last article.
141 It can be marked expirable, so it will be deleted when it is no longer last.
142
143 You may need to set this variable if other programs are putting
144 new mail into folder numbers that Gnus has marked as expired."
145   :group 'nnmail-procmail
146   :group 'nnmail-various
147   :type 'boolean)
148
149 (defcustom nnmail-use-long-file-names nil
150   "If non-nil the mail backends will use long file and directory names.
151 If nil, groups like \"mail.misc\" will end up in directories like
152 \"mail/misc/\"."
153   :group 'nnmail-files
154   :type 'boolean)
155
156 (defcustom nnmail-default-file-modes 384
157   "Set the mode bits of all new mail files to this integer."
158   :group 'nnmail-files
159   :type 'integer)
160
161 (defcustom nnmail-expiry-wait 7
162   "*Expirable articles that are older than this will be expired.
163 This variable can either be a number (which will be interpreted as a
164 number of days) -- this doesn't have to be an integer.  This variable
165 can also be `immediate' and `never'."
166   :group 'nnmail-expire
167   :type '(choice (const immediate)
168                  (number :tag "days")
169                  (const never)))
170
171 (defcustom nnmail-expiry-wait-function nil
172   "Variable that holds function to specify how old articles should be before they are expired.
173 The function will be called with the name of the group that the expiry
174 is to be performed in, and it should return an integer that says how
175 many days an article can be stored before it is considered \"old\".
176 It can also return the values `never' and `immediate'.
177
178 E.g.:
179
180 \(setq nnmail-expiry-wait-function
181       (lambda (newsgroup)
182         (cond ((string-match \"private\" newsgroup) 31)
183               ((string-match \"junk\" newsgroup) 1)
184               ((string-match \"important\" newsgroup) 'never)
185               (t 7))))"
186   :group 'nnmail-expire
187   :type '(choice (const :tag "nnmail-expiry-wait" nil)
188                  (function :format "%v" nnmail-)))
189
190 (defcustom nnmail-expiry-target 'delete
191   "*Variable that says where expired messages should end up.
192 The default value is `delete' (which says to delete the messages),
193 but it can also be a string or a function.  If it is a string, expired
194 messages end up in that group.  If it is a function, the function is
195 called in a buffer narrowed to the message in question.  The function
196 receives one argument, the name of the group the message comes from.
197 The return value should be `delete' or a group name (a string)."
198   :version "21.1"
199   :group 'nnmail-expire
200   :type '(choice (const delete)
201                  function
202                  string))
203
204 (defcustom nnmail-fancy-expiry-targets nil
205   "Determine expiry target based on articles using fancy techniques.
206
207 This is a list of (\"HEADER\" \"REGEXP\" \"TARGET\") entries.  If
208 `nnmail-expiry-target' is set to the function
209 `nnmail-fancy-expiry-target' and HEADER of the article matches REGEXP,
210 the message will be expired to a group determined by invoking
211 `format-time-string' with TARGET used as the format string and the
212 time extracted from the articles' Date header (if missing the current
213 time is used).
214
215 In the special cases that HEADER is the symbol `to-from', the regexp
216 will try to match against both the From and the To header.
217
218 Example:
219
220 \(setq nnmail-fancy-expiry-targets
221       '((to-from \"boss\" \"nnfolder:Work\")
222         (\"Subject\" \"IMPORTANT\" \"nnfolder:IMPORTANT.%Y.%b\")
223         (\"from\" \".*\" \"nnfolder:Archive-%Y\")))
224
225 In this case, articles containing the string \"boss\" in the To or the
226 From header will be expired to the group \"nnfolder:Work\";
227 articles containing the string \"IMPORTANT\" in the Subject header will
228 be expired to the group \"nnfolder:IMPORTANT.YYYY.MMM\"; and
229 everything else will be expired to \"nnfolder:Archive-YYYY\"."
230   :version "22.1"
231   :group 'nnmail-expire
232   :type '(repeat (list (choice :tag "Match against"
233                                (string :tag "Header")
234                                (const to-from))
235                        regexp
236                        (string :tag "Target group format string"))))
237
238 (defcustom nnmail-cache-accepted-message-ids nil
239   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache.
240 If non-nil, also update the cache when copy or move articles."
241   :group 'nnmail
242   :type 'boolean)
243
244 (make-obsolete-variable 'nnmail-spool-file 'mail-sources
245                         "Gnus 5.9 (Emacs 22.1)")
246 ;; revision 5.29 / p0-85 / Gnus 5.9
247 ;; Variable removed in No Gnus v0.7
248
249 (defcustom nnmail-resplit-incoming nil
250   "*If non-nil, re-split incoming procmail sorted mail."
251   :group 'nnmail-procmail
252   :type 'boolean)
253
254 (defcustom nnmail-scan-directory-mail-source-once nil
255   "*If non-nil, scan all incoming procmail sorted mails once.
256 It scans low-level sorted spools even when not required."
257   :version "21.1"
258   :group 'nnmail-procmail
259   :type 'boolean)
260
261 (defcustom nnmail-delete-file-function 'delete-file
262   "Function called to delete files in some mail backends."
263   :group 'nnmail-files
264   :type 'function)
265
266 (defcustom nnmail-crosspost-link-function
267   (if (string-match "windows-nt" (symbol-name system-type))
268       'copy-file
269     'add-name-to-file)
270   "*Function called to create a copy of a file.
271 This is `add-name-to-file' by default, which means that crossposts
272 will use hard links.  If your file system doesn't allow hard
273 links, you could set this variable to `copy-file' instead."
274   :group 'nnmail-files
275   :type '(radio (function-item add-name-to-file)
276                 (function-item copy-file)
277                 (function :tag "Other")))
278
279 (defcustom nnmail-read-incoming-hook
280   (if (eq system-type 'windows-nt)
281       '(nnheader-ms-strip-cr)
282     nil)
283   "*Hook that will be run after the incoming mail has been transferred.
284 The incoming mail is moved from the specified spool file (which normally is
285 something like \"/usr/spool/mail/$user\") to the user's home
286 directory.  This hook is called after the incoming mail box has been
287 emptied, and can be used to call any mail box programs you have
288 running (\"xwatch\", etc.)
289
290 E.g.:
291
292 \(add-hook 'nnmail-read-incoming-hook
293           (lambda ()
294             (call-process \"/local/bin/mailsend\" nil nil nil
295                           \"read\"
296                           ;; The incoming mail box file.
297                           (expand-file-name (user-login-name)
298                                             rmail-spool-directory))))
299
300 If you have xwatch running, this will alert it that mail has been
301 read.
302
303 If you use `display-time', you could use something like this:
304
305 \(add-hook 'nnmail-read-incoming-hook
306           (lambda ()
307             ;; Update the displayed time, since that will clear out
308             ;; the flag that says you have mail.
309             (when (eq (process-status \"display-time\") 'run)
310               (display-time-filter display-time-process \"\"))))"
311   :group 'nnmail-prepare
312   :type 'hook)
313
314 (defcustom nnmail-prepare-incoming-hook nil
315   "Hook called before treating incoming mail.
316 The hook is run in a buffer with all the new, incoming mail."
317   :group 'nnmail-prepare
318   :type 'hook)
319
320 (defcustom nnmail-prepare-incoming-header-hook nil
321   "Hook called narrowed to the headers of each message.
322 This can be used to remove excessive spaces (and stuff like
323 that) from the headers before splitting and saving the messages."
324   :group 'nnmail-prepare
325   :type 'hook)
326
327 (defcustom nnmail-prepare-incoming-message-hook nil
328   "Hook called narrowed to each message."
329   :group 'nnmail-prepare
330   :type 'hook)
331
332 (defcustom nnmail-list-identifiers nil
333   "Regexp that matches list identifiers to be removed.
334 This can also be a list of regexps."
335   :group 'nnmail-prepare
336   :type '(choice (const :tag "none" nil)
337                  (regexp :value ".*")
338                  (repeat :value (".*") regexp)))
339
340 (defcustom nnmail-pre-get-new-mail-hook nil
341   "Hook called just before starting to handle new incoming mail."
342   :group 'nnmail-retrieve
343   :type 'hook)
344
345 (defcustom nnmail-post-get-new-mail-hook nil
346   "Hook called just after finishing handling new incoming mail."
347   :group 'nnmail-retrieve
348   :type 'hook)
349
350 (defcustom nnmail-split-hook nil
351   "Hook called before deciding where to split an article.
352 The functions in this hook are free to modify the buffer
353 contents in any way they choose -- the buffer contents are
354 discarded after running the split process."
355   :group 'nnmail-split
356   :type 'hook)
357
358 (defcustom nnmail-spool-hook nil
359   "*A hook called when a new article is spooled."
360   :version "22.1"
361   :group 'nnmail
362   :type 'hook)
363
364 (defcustom nnmail-large-newsgroup 50
365   "*The number of articles which indicates a large newsgroup or nil.
366 If the number of articles is greater than the value, verbose
367 messages will be shown to indicate the current status."
368   :group 'nnmail-various
369   :type '(choice (const :tag "infinite" nil)
370                  (number :tag "count")))
371
372 (define-widget 'nnmail-lazy 'default
373   "Base widget for recursive data structures.
374
375 This is copy of the `lazy' widget in Emacs 22.1 provided for compatibility."
376   :format "%{%t%}: %v"
377   :convert-widget 'widget-value-convert-widget
378   :value-create (lambda (widget)
379                   (let ((value (widget-get widget :value))
380                         (type (widget-get widget :type)))
381                     (widget-put widget :children
382                                 (list (widget-create-child-value
383                                        widget (widget-convert type) value)))))
384   :value-delete 'widget-children-value-delete
385   :value-get (lambda (widget)
386                (widget-value (car (widget-get widget :children))))
387   :value-inline (lambda (widget)
388                   (widget-apply (car (widget-get widget :children))
389                                 :value-inline))
390   :default-get (lambda (widget)
391                  (widget-default-get
392                   (widget-convert (widget-get widget :type))))
393   :match (lambda (widget value)
394            (widget-apply (widget-convert (widget-get widget :type))
395                          :match value))
396   :validate (lambda (widget)
397               (widget-apply (car (widget-get widget :children)) :validate)))
398
399 (define-widget 'nnmail-split-fancy 'nnmail-lazy
400   "Widget for customizing splits in the variable of the same name."
401   :tag "Split"
402   :type '(menu-choice :value (any ".*value.*" "misc")
403                       :tag "Type"
404                       (string :tag "Destination")
405                       (list :tag "Use first match (|)" :value (|)
406                             (const :format "" |)
407                             (editable-list :inline t nnmail-split-fancy))
408                       (list :tag "Use all matches (&)" :value (&)
409                             (const :format "" &)
410                             (editable-list :inline t nnmail-split-fancy))
411                       (list :tag "Function with fixed arguments (:)"
412                             :value (:)
413                             (const :format "" :value :)
414                             function
415                             (editable-list :inline t (sexp :tag "Arg"))
416                             )
417                       (list :tag "Function with split arguments (!)"
418                             :value (!)
419                             (const :format "" !)
420                             function
421                             (editable-list :inline t nnmail-split-fancy))
422                       (list :tag "Field match"
423                             (choice :tag "Field"
424                                     regexp symbol)
425                             (choice :tag "Match"
426                                     regexp
427                                     (symbol :value mail))
428                             (repeat :inline t
429                                     :tag "Restrictions"
430                                     (group :inline t
431                                            (const :format "" -)
432                                            regexp))
433                             nnmail-split-fancy)
434                       (const :tag "Junk (delete mail)" junk)))
435
436 (defcustom nnmail-split-fancy "mail.misc"
437   "Incoming mail can be split according to this fancy variable.
438 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
439
440 The format of this variable is SPLIT, where SPLIT can be one of
441 the following:
442
443 GROUP: Mail will be stored in GROUP (a string).
444
445 \(FIELD VALUE [- RESTRICT [- RESTRICT [...]]] SPLIT): If the message
446   field FIELD (a regexp) contains VALUE (a regexp), store the messages
447   as specified by SPLIT.  If RESTRICT (a regexp) matches some string
448   after FIELD and before the end of the matched VALUE, return nil,
449   otherwise process SPLIT.  Multiple RESTRICTs add up, further
450   restricting the possibility of processing SPLIT.
451
452 \(| SPLIT...): Process each SPLIT expression until one of them matches.
453   A SPLIT expression is said to match if it will cause the mail
454   message to be stored in one or more groups.
455
456 \(& SPLIT...): Process each SPLIT expression.
457
458 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
459   the buffer containing the message headers.  The return value FUNCTION
460   should be a split, which is then recursively processed.
461
462 \(! FUNCTION SPLIT): Call FUNCTION with the result of SPLIT.  The
463   return value FUNCTION should be a split, which is then recursively
464   processed.
465
466 junk: Mail will be deleted.  Use with care!  Do not submerge in water!
467   Example:
468   (setq nnmail-split-fancy
469         '(| (\"Subject\" \"MAKE MONEY FAST\" junk)
470             ...other.rules.omitted...))
471
472 FIELD must match a complete field name.  VALUE must match a complete
473 word according to the `nnmail-split-fancy-syntax-table' syntax table.
474 You can use \".*\" in the regexps to match partial field names or words.
475
476 FIELD and VALUE can also be Lisp symbols, in that case they are expanded
477 as specified in `nnmail-split-abbrev-alist'.
478
479 GROUP can contain \\& and \\N which will substitute from matching
480 \\(\\) patterns in the previous VALUE.
481
482 Example:
483
484 \(setq nnmail-split-methods 'nnmail-split-fancy
485       nnmail-split-fancy
486       ;; Messages from the mailer daemon are not crossposted to any of
487       ;; the ordinary groups.  Warnings are put in a separate group
488       ;; from real errors.
489       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
490                           \"mail.misc\"))
491           ;; Non-error messages are crossposted to all relevant
492           ;; groups, but we don't crosspost between the group for the
493           ;; (ding) list and the group for other (ding) related mail.
494           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
495                 (\"subject\" \"ding\" \"ding.misc\"))
496              ;; Other mailing lists...
497              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
498              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
499              ;; Both lists below have the same suffix, so prevent
500              ;; cross-posting to mkpkg.list of messages posted only to
501              ;; the bugs- list, but allow cross-posting when the
502              ;; message was really cross-posted.
503              (any \"bugs-mypackage@somewhere\" \"mypkg.bugs\")
504              (any \"mypackage@somewhere\" - \"bugs-mypackage\" \"mypkg.list\")
505              ;;
506              ;; People...
507              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
508           ;; Unmatched mail goes to the catch all group.
509           \"misc.misc\"))"
510   :group 'nnmail-split
511   :type 'nnmail-split-fancy)
512
513 (defcustom nnmail-split-abbrev-alist
514   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
515     (mail . "mailer-daemon\\|postmaster\\|uucp")
516     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
517     (from . "from\\|sender\\|resent-from")
518     (nato . "to\\|cc\\|resent-to\\|resent-cc")
519     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
520   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
521   :group 'nnmail-split
522   :type '(repeat (cons :format "%v" symbol regexp)))
523
524 (defcustom nnmail-message-id-cache-length 1000
525   "*The approximate number of Message-IDs nnmail will keep in its cache.
526 If this variable is nil, no checking on duplicate messages will be
527 performed."
528   :group 'nnmail-duplicate
529   :type '(choice (const :tag "disable" nil)
530                  (integer :format "%v")))
531
532 (defcustom nnmail-message-id-cache-file
533   (nnheader-concat gnus-home-directory ".nnmail-cache")
534   "The file name of the nnmail Message-ID cache."
535   :group 'nnmail-duplicate
536   :group 'nnmail-files
537   :type 'file)
538
539 (defcustom nnmail-treat-duplicates 'warn
540   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
541 Three values are valid: nil, which means that nnmail is not to keep a
542 Message-ID cache; `warn', which means that nnmail should insert extra
543 headers to warn the user about the duplication (this is the default);
544 and `delete', which means that nnmail will delete duplicated mails.
545
546 This variable can also be a function.  It will be called from a buffer
547 narrowed to the article in question with the Message-ID as a
548 parameter.  It should return nil, `warn' or `delete'."
549   :group 'nnmail-duplicate
550   :type '(choice (const :tag "off" nil)
551                  (const warn)
552                  (const delete)))
553
554 (defcustom nnmail-extra-headers '(To Newsgroups Cc)
555   "Extra headers to parse.
556 In addition to the standard headers, these extra headers will be
557 included in NOV headers (and the like) when backends parse headers."
558   :version "24.3"
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                 (not (consp (car-safe nnmail-split-methods)))
1152                 (and (listp nnmail-split-methods)
1153                      ;; Not a regular split method, so it has to be a
1154                      ;; fancy one.
1155                      (not (let ((top-element (car-safe nnmail-split-methods)))
1156                             (and (= 2 (length top-element))
1157                                  (stringp (nth 0 top-element))
1158                                  (stringp (nth 1 top-element)))))))
1159             (let* ((method-function
1160                     (if (and (symbolp nnmail-split-methods)
1161                              (fboundp nnmail-split-methods))
1162                         nnmail-split-methods
1163                       'nnmail-split-fancy))
1164                    (split
1165                     (condition-case error-info
1166                         ;; `nnmail-split-methods' is a function, so we
1167                         ;; just call this function here and use the
1168                         ;; result.
1169                         (or (funcall method-function)
1170                             (and (not nnmail-inhibit-default-split-group)
1171                                  '("bogus")))
1172                       (error
1173                        (nnheader-message
1174                         5 "Error in `nnmail-split-methods'; using `bogus' mail group: %S" error-info)
1175                        (sit-for 1)
1176                        '("bogus")))))
1177               (setq split (mm-delete-duplicates split))
1178               ;; The article may be "cross-posted" to `junk'.  What
1179               ;; to do?  Just remove the `junk' spec.  Don't really
1180               ;; see anything else to do...
1181               (when (and (memq 'junk split)
1182                          junk-func)
1183                 (funcall junk-func 'junk))
1184               (setq split (delq 'junk split))
1185               (when split
1186                 (setq group-art
1187                       (mapcar
1188                        (lambda (group) (cons group (funcall func group)))
1189                        split))))
1190           ;; Go through the split methods to find a match.
1191           (while (and methods
1192                       (or nnmail-crosspost
1193                           (not group-art)))
1194             (goto-char (point-max))
1195             (setq method (pop methods)
1196                   grp (car method))
1197             (if (or methods
1198                     (not (equal "" (nth 1 method))))
1199                 (when (and
1200                        (ignore-errors
1201                          (if (stringp (nth 1 method))
1202                              (let ((expand (string-match "\\\\[0-9&]" grp))
1203                                    (pos (re-search-backward (cadr method)
1204                                                             nil t)))
1205                                (and expand
1206                                     (setq grp (nnmail-expand-newtext grp)))
1207                                pos)
1208                            ;; Function to say whether this is a match.
1209                            (funcall (nth 1 method) grp)))
1210                        ;; Don't enter the article into the same
1211                        ;; group twice.
1212                        (not (assoc grp group-art)))
1213                   (push (cons grp (funcall func grp))
1214                         group-art))
1215               ;; This is the final group, which is used as a
1216               ;; catch-all.
1217               (when (and (not group-art)
1218                          (or (equal "" (nth 1 method))
1219                              (not nnmail-inhibit-default-split-group)))
1220                 (setq group-art
1221                       (list (cons (car method)
1222                                   (funcall func (car method))))))))
1223           ;; Fall back on "bogus" if all else fails.
1224           (when (and (not group-art)
1225                      (not nnmail-inhibit-default-split-group))
1226             (setq group-art (list (cons "bogus" (funcall func "bogus"))))))
1227         ;; Produce a trace if non-empty.
1228         (when (and trace nnmail-split-trace)
1229           (let ((restore (current-buffer)))
1230             (nnheader-set-temp-buffer "*Split Trace*")
1231             (gnus-add-buffer)
1232             (dolist (trace (nreverse nnmail-split-trace))
1233               (prin1 trace (current-buffer))
1234               (insert "\n"))
1235             (goto-char (point-min))
1236             (gnus-configure-windows 'split-trace)
1237             (set-buffer restore)))
1238         (widen)
1239         ;; See whether the split methods returned `junk'.
1240         (if (equal group-art '(junk))
1241             nil
1242           ;; The article may be "cross-posted" to `junk'.  What
1243           ;; to do?  Just remove the `junk' spec.  Don't really
1244           ;; see anything else to do...
1245           (let (elem)
1246             (while (setq elem (car (memq 'junk group-art)))
1247               (setq group-art (delq elem group-art)))
1248             (nreverse group-art)))))))
1249
1250 (defun nnmail-insert-lines ()
1251   "Insert how many lines there are in the body of the mail.
1252 Return the number of characters in the body."
1253   (let (lines chars)
1254     (save-excursion
1255       (goto-char (point-min))
1256       (unless (search-forward "\n\n" nil t)
1257         (goto-char (point-max))
1258         (insert "\n"))
1259       (setq chars (- (point-max) (point)))
1260       (setq lines (count-lines (point) (point-max)))
1261       (forward-char -1)
1262       (save-excursion
1263         (when (re-search-backward "^Lines: " nil t)
1264           (delete-region (point) (progn (forward-line 1) (point)))))
1265       (beginning-of-line)
1266       (insert (format "Lines: %d\n" (max lines 0)))
1267       chars)))
1268
1269 (defun nnmail-insert-xref (group-alist)
1270   "Insert an Xref line based on the (group . article) alist."
1271   (save-excursion
1272     (goto-char (point-min))
1273     (unless (search-forward "\n\n" nil t)
1274       (goto-char (point-max))
1275       (insert "\n"))
1276     (forward-char -1)
1277     (when (re-search-backward "^Xref: " nil t)
1278       (delete-region (match-beginning 0)
1279                      (progn (forward-line 1) (point))))
1280     (insert (format "Xref: %s" (system-name)))
1281     (while group-alist
1282       (insert (if (mm-multibyte-p)
1283                   (mm-string-as-multibyte
1284                    (format " %s:%d" (caar group-alist) (cdar group-alist)))
1285                 (mm-string-as-unibyte
1286                  (format " %s:%d" (caar group-alist) (cdar group-alist)))))
1287       (setq group-alist (cdr group-alist)))
1288     (insert "\n")))
1289
1290 ;;; Message washing functions
1291
1292 (defun nnmail-remove-leading-whitespace ()
1293   "Remove excessive whitespace from all headers."
1294   (goto-char (point-min))
1295   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1296     (replace-match "\\1" t)))
1297
1298 (defun nnmail-remove-list-identifiers ()
1299   "Remove list identifiers from Subject headers."
1300   (let ((regexp
1301          (if (consp nnmail-list-identifiers)
1302              (mapconcat 'identity nnmail-list-identifiers " *\\|")
1303            nnmail-list-identifiers)))
1304     (when regexp
1305       (goto-char (point-min))
1306       (while (re-search-forward
1307               (concat "^Subject: +\\(R[Ee]: +\\)*\\(" regexp " *\\)")
1308               nil t)
1309         (delete-region (match-beginning 2) (match-end 0))
1310         (beginning-of-line))
1311       (when (re-search-forward "^Subject: +\\(\\(R[Ee]: +\\)+\\)R[Ee]: +"
1312                                nil t)
1313         (delete-region (match-beginning 1) (match-end 1))
1314         (beginning-of-line)))))
1315
1316 (defun nnmail-remove-tabs ()
1317   "Translate TAB characters into SPACE characters."
1318   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1319
1320 (defcustom nnmail-broken-references-mailers
1321   "^X-Mailer:.*\\(Eudora\\|Pegasus\\)"
1322   "Header line matching mailer producing bogus References lines.
1323 See `nnmail-ignore-broken-references'."
1324   :group 'nnmail-prepare
1325   :version "23.1" ;; No Gnus
1326   :type 'regexp)
1327
1328 (defun nnmail-ignore-broken-references ()
1329   "Ignore the References line and use In-Reply-To
1330
1331 Eudora has a broken References line, but an OK In-Reply-To."
1332   (goto-char (point-min))
1333   (when (re-search-forward nnmail-broken-references-mailers nil t)
1334     (goto-char (point-min))
1335     (when (re-search-forward "^References:" nil t)
1336       (beginning-of-line)
1337       (insert "X-Gnus-Broken-Eudora-"))
1338     (goto-char (point-min))
1339     (when (re-search-forward "^\\(In-Reply-To:[^\n]+\\)\n[ \t]+" nil t)
1340       (replace-match "\\1" t))))
1341
1342 (defalias 'nnmail-fix-eudora-headers 'nnmail-ignore-broken-references)
1343 (make-obsolete 'nnmail-fix-eudora-headers 'nnmail-ignore-broken-references "Emacs 23.1")
1344
1345 (custom-add-option 'nnmail-prepare-incoming-header-hook
1346                    'nnmail-ignore-broken-references)
1347
1348 ;;; Utility functions
1349
1350 (declare-function gnus-activate-group "gnus-start"
1351                   (group &optional scan dont-check method dont-sub-check))
1352
1353 (defun nnmail-do-request-post (accept-func &optional server)
1354   "Utility function to directly post a message to an nnmail-derived group.
1355 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
1356 to actually put the message in the right group."
1357   (let ((success t))
1358     (dolist (mbx (message-unquote-tokens
1359                   (message-tokenize-header
1360                    (message-fetch-field "Newsgroups") ", ")) success)
1361       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1362         (or (gnus-active to-newsgroup)
1363             (gnus-activate-group to-newsgroup)
1364             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1365                                        to-newsgroup))
1366                 (or (and (gnus-request-create-group
1367                           to-newsgroup gnus-command-method)
1368                          (gnus-activate-group to-newsgroup nil nil
1369                                               gnus-command-method))
1370                     (error "Couldn't create group %s" to-newsgroup)))
1371             (error "No such group: %s" to-newsgroup))
1372         (unless (funcall accept-func mbx (nth 1 gnus-command-method))
1373           (setq success nil))))))
1374
1375 (defun nnmail-split-fancy ()
1376   "Fancy splitting method.
1377 See the documentation for the variable `nnmail-split-fancy' for details."
1378   (with-syntax-table nnmail-split-fancy-syntax-table
1379     (nnmail-split-it nnmail-split-fancy)))
1380
1381 (defvar nnmail-split-cache nil)
1382 ;; Alist of split expressions their equivalent regexps.
1383
1384 (defun nnmail-split-it (split)
1385   ;; Return a list of groups matching SPLIT.
1386   (let (cached-pair)
1387     (cond
1388      ;; nil split
1389      ((null split)
1390       nil)
1391
1392      ;; A group name.  Do the \& and \N subs into the string.
1393      ((stringp split)
1394       (when nnmail-split-tracing
1395         (push split nnmail-split-trace))
1396       (list (nnmail-expand-newtext split t)))
1397
1398      ;; Junk the message.
1399      ((eq split 'junk)
1400       (when nnmail-split-tracing
1401         (push "junk" nnmail-split-trace))
1402       (list 'junk))
1403
1404      ;; Builtin & operation.
1405      ((eq (car split) '&)
1406       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1407
1408      ;; Builtin | operation.
1409      ((eq (car split) '|)
1410       (let (done)
1411         (while (and (not done) (cdr split))
1412           (setq split (cdr split)
1413                 done (nnmail-split-it (car split))))
1414         done))
1415
1416      ;; Builtin : operation.
1417      ((eq (car split) ':)
1418       (when nnmail-split-tracing
1419         (push split nnmail-split-trace))
1420       (nnmail-split-it (save-excursion (eval (cdr split)))))
1421
1422      ;; Builtin ! operation.
1423      ((eq (car split) '!)
1424       (funcall (cadr split) (nnmail-split-it (caddr split))))
1425
1426      ;; Check the cache for the regexp for this split.
1427      ((setq cached-pair (assq split nnmail-split-cache))
1428       (let (split-result
1429             match-data
1430             (end-point (point-max))
1431             (value (nth 1 split)))
1432         (if (symbolp value)
1433             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1434         (while (and (goto-char end-point)
1435                     (re-search-backward (cdr cached-pair) nil t))
1436           (setq match-data (match-data))
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               ;; Someone might want to do a \N sub on this match, so
1466               ;; restore the match data.
1467               (set-match-data match-data)
1468               (dolist (sp (nnmail-split-it (car split-rest)))
1469                 (unless (member sp split-result)
1470                   (push sp split-result))))))
1471         split-result))
1472
1473      ;; Not in cache, compute a regexp for the field/value pair.
1474      (t
1475       (let ((field (nth 0 split))
1476             (value (nth 1 split))
1477             (split-rest (cddr split))
1478             partial-front
1479             partial-rear
1480             regexp)
1481         (if (symbolp value)
1482             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1483         (if (and (>= (length value) 2)
1484                  (string= ".*" (substring value 0 2)))
1485             (setq value (substring value 2)
1486                   partial-front ""))
1487         ;; Same trick for the rear of the regexp
1488         (if (and (>= (length value) 2)
1489                  (string= ".*" (substring value -2)))
1490             (setq value (substring value 0 -2)
1491                   partial-rear ""))
1492         ;; Invert the match-partial-words behavior if the optional
1493         ;; last element is specified.
1494         (while (eq (car split-rest) '-)
1495           (setq split-rest (cddr split-rest)))
1496         (when (if (cadr split-rest)
1497                   (not nnmail-split-fancy-match-partial-words)
1498                 nnmail-split-fancy-match-partial-words)
1499           (setq partial-front ""
1500                 partial-rear ""))
1501         (setq regexp (concat "^\\(\\("
1502                              (if (symbolp field)
1503                                  (cdr (assq field nnmail-split-abbrev-alist))
1504                                field)
1505                              "\\):.*\\)"
1506                              (or partial-front "\\<")
1507                              "\\("
1508                              value
1509                              "\\)"
1510                              (or partial-rear "\\>")))
1511         (push (cons split regexp) nnmail-split-cache)
1512         ;; Now that it's in the cache, just call nnmail-split-it again
1513         ;; on the same split, which will find it immediately in the cache.
1514         (nnmail-split-it split))))))
1515
1516 (defun nnmail-expand-newtext (newtext &optional fancyp)
1517   (let ((len (length newtext))
1518         (pos 0)
1519         c expanded beg N did-expand)
1520     (while (< pos len)
1521       (setq beg pos)
1522       (while (and (< pos len)
1523                   (not (= (aref newtext pos) ?\\)))
1524         (setq pos (1+ pos)))
1525       (unless (= beg pos)
1526         (push (substring newtext beg pos) expanded))
1527       (when (< pos len)
1528         ;; We hit a \; expand it.
1529         (setq did-expand t
1530               pos (1+ pos)
1531               c (aref newtext pos))
1532         (if (not (or (= c ?\&)
1533                      (and (>= c ?1)
1534                           (<= c ?9))))
1535             ;; \ followed by some character we don't expand.
1536             (push (char-to-string c) expanded)
1537           ;; \& or \N
1538           (if (= c ?\&)
1539               (setq N 0)
1540             (setq N (- c ?0)))
1541           ;; We wrapped the searches in parentheses, so we have to
1542           ;; add some parentheses here...
1543           (when fancyp
1544             (setq N (+ N 3)))
1545           (when (match-beginning N)
1546             (push (if nnmail-split-lowercase-expanded
1547                       (downcase (buffer-substring (match-beginning N)
1548                                                   (match-end N)))
1549                     (buffer-substring (match-beginning N) (match-end N)))
1550                   expanded))))
1551       (setq pos (1+ pos)))
1552     (if did-expand
1553         (apply 'concat (nreverse expanded))
1554       newtext)))
1555
1556 ;; Activate a backend only if it isn't already activated.
1557 ;; If FORCE, re-read the active file even if the backend is
1558 ;; already activated.
1559 (defun nnmail-activate (backend &optional force)
1560   (nnheader-init-server-buffer)
1561   (let (file timestamp file-time)
1562     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1563             force
1564             (and (setq file (ignore-errors
1565                               (symbol-value (intern (format "%s-active-file"
1566                                                             backend)))))
1567                  (setq file-time (nth 5 (file-attributes file)))
1568                  (or (not
1569                       (setq timestamp
1570                             (condition-case ()
1571                                 (symbol-value (intern
1572                                                (format "%s-active-timestamp"
1573                                                        backend)))
1574                               (error 'none))))
1575                      (not (consp timestamp))
1576                      (equal timestamp '(0 0))
1577                      (> (nth 0 file-time) (nth 0 timestamp))
1578                      (and (= (nth 0 file-time) (nth 0 timestamp))
1579                           (> (nth 1 file-time) (nth 1 timestamp))))))
1580         (save-excursion
1581           (or (eq timestamp 'none)
1582               (set (intern (format "%s-active-timestamp" backend))
1583                    file-time))
1584           (funcall (intern (format "%s-request-list" backend)))))
1585     t))
1586
1587 (defun nnmail-message-id ()
1588   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1589
1590 ;;;
1591 ;;; nnmail duplicate handling
1592 ;;;
1593
1594 (defvar nnmail-cache-buffer nil)
1595
1596 (defun nnmail-cache-open ()
1597   (if (or (not nnmail-treat-duplicates)
1598           (and nnmail-cache-buffer
1599                (buffer-name nnmail-cache-buffer)))
1600       ()                                ; The buffer is open.
1601     (with-current-buffer
1602        (setq nnmail-cache-buffer
1603              (get-buffer-create " *nnmail message-id cache*"))
1604       (gnus-add-buffer)
1605       (when (file-exists-p nnmail-message-id-cache-file)
1606         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1607       (set-buffer-modified-p nil)
1608       (current-buffer))))
1609
1610 (defun nnmail-cache-close ()
1611   (when (and nnmail-cache-buffer
1612              nnmail-treat-duplicates
1613              (buffer-name nnmail-cache-buffer)
1614              (buffer-modified-p nnmail-cache-buffer))
1615     (with-current-buffer nnmail-cache-buffer
1616       ;; Weed out the excess number of Message-IDs.
1617       (goto-char (point-max))
1618       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1619         (progn
1620           (beginning-of-line)
1621           (delete-region (point-min) (point))))
1622       ;; Save the buffer.
1623       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1624           (make-directory (file-name-directory nnmail-message-id-cache-file)
1625                           t))
1626       (nnmail-write-region (point-min) (point-max)
1627                            nnmail-message-id-cache-file nil 'silent)
1628       (set-buffer-modified-p nil)
1629       (setq nnmail-cache-buffer nil)
1630       (gnus-kill-buffer (current-buffer)))))
1631
1632 (defun nnmail-cache-insert (id grp &optional subject sender)
1633   (when (stringp id)
1634     ;; this will handle cases like `B r' where the group is nil
1635     (let ((grp (or grp gnus-newsgroup-name "UNKNOWN")))
1636       (run-hook-with-args 'nnmail-spool-hook
1637                           id grp subject sender))
1638     (when nnmail-treat-duplicates
1639       ;; Store some information about the group this message is written
1640       ;; to.  This is passed in as the grp argument -- all locations this
1641       ;; has been called from have been checked and the group is available.
1642       ;; The only ambiguous case is nnmail-check-duplication which will only
1643       ;; pass the first (of possibly >1) group which matches. -Josh
1644       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1645         (nnmail-cache-open))
1646       (with-current-buffer nnmail-cache-buffer
1647         (goto-char (point-max))
1648         (if (and grp (not (string= "" grp))
1649                  (gnus-methods-equal-p gnus-command-method
1650                                        (nnmail-cache-primary-mail-backend)))
1651             (let ((regexp (if (consp nnmail-cache-ignore-groups)
1652                               (mapconcat 'identity nnmail-cache-ignore-groups
1653                                          "\\|")
1654                             nnmail-cache-ignore-groups)))
1655               (unless (and regexp (string-match regexp grp))
1656                 (insert id "\t" grp "\n")))
1657           (insert id "\n"))))))
1658
1659 (defun nnmail-cache-primary-mail-backend ()
1660   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1661         (be nil)
1662         (res nil)
1663         (get-new-mail nil))
1664     (while (and (null res) be-list)
1665       (setq be (car be-list))
1666       (setq be-list (cdr be-list))
1667       (when (and (gnus-method-option-p be 'respool)
1668                  (setq get-new-mail
1669                        (intern (format "%s-get-new-mail" (car be))))
1670                  (boundp get-new-mail)
1671                  (symbol-value get-new-mail))
1672         (setq res be)))
1673     res))
1674
1675 ;; Fetch the group name corresponding to the message id stored in the
1676 ;; cache.
1677 (defun nnmail-cache-fetch-group (id)
1678   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1679     (with-current-buffer nnmail-cache-buffer
1680       (goto-char (point-max))
1681       (when (search-backward id nil t)
1682         (beginning-of-line)
1683         (skip-chars-forward "^\n\r\t")
1684         (unless (looking-at "[\r\n]")
1685           (forward-char 1)
1686           (buffer-substring (point) (point-at-eol)))))))
1687
1688 ;; Function for nnmail-split-fancy: look up all references in the
1689 ;; cache and if a match is found, return that group.
1690 (defun nnmail-split-fancy-with-parent ()
1691   "Split this message into the same group as its parent.
1692 This function can be used as an entry in `nnmail-split-fancy', for
1693 example like this: (: nnmail-split-fancy-with-parent)
1694 For a message to be split, it looks for the parent message in the
1695 References or In-Reply-To header and then looks in the message id
1696 cache file (given by the variable `nnmail-message-id-cache-file') to
1697 see which group that message was put in.  This group is returned.
1698
1699 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1700   (let* ((refstr (or (message-fetch-field "references")
1701                      (message-fetch-field "in-reply-to")))
1702          (references nil)
1703          (res nil)
1704          (regexp (if (consp nnmail-split-fancy-with-parent-ignore-groups)
1705                      (mapconcat
1706                       (lambda (x) (format "\\(%s\\)" x))
1707                       nnmail-split-fancy-with-parent-ignore-groups
1708                       "\\|")
1709                    nnmail-split-fancy-with-parent-ignore-groups)))
1710     (when refstr
1711       (setq references (nreverse (gnus-split-references refstr)))
1712       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1713         (nnmail-cache-open))
1714       (dolist (x references)
1715         (setq res (or (nnmail-cache-fetch-group x) res))
1716         (when (or (member res '("delayed" "drafts" "queue"))
1717                   (and regexp res (string-match regexp res)))
1718           (setq res nil)))
1719       res)))
1720
1721 (defun nnmail-cache-id-exists-p (id)
1722   (when nnmail-treat-duplicates
1723     (with-current-buffer nnmail-cache-buffer
1724       (goto-char (point-max))
1725       (search-backward id nil t))))
1726
1727 (defun nnmail-fetch-field (header)
1728   (save-excursion
1729     (save-restriction
1730       (message-narrow-to-head)
1731       (message-fetch-field header))))
1732
1733 (defun nnmail-check-duplication (message-id func artnum-func
1734                                             &optional junk-func)
1735   (run-hooks 'nnmail-prepare-incoming-message-hook)
1736   ;; If this is a duplicate message, then we do not save it.
1737   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1738          (case-fold-search t)
1739          (action (when duplication
1740                    (cond
1741                     ((memq nnmail-treat-duplicates '(warn delete))
1742                      nnmail-treat-duplicates)
1743                     ((functionp nnmail-treat-duplicates)
1744                      (funcall nnmail-treat-duplicates message-id))
1745                     (t
1746                      nnmail-treat-duplicates))))
1747          group-art)
1748     ;; We insert a line that says what the mail source is.
1749     (let ((case-fold-search t))
1750       (goto-char (point-min))
1751       (re-search-forward "^message-id[ \t]*:" nil t)
1752       (beginning-of-line)
1753       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1754
1755     ;; Let the backend save the article (or not).
1756     (cond
1757      ((not duplication)
1758       (funcall func (setq group-art
1759                           (nreverse (nnmail-article-group
1760                                      artnum-func nil junk-func))))
1761       (nnmail-cache-insert message-id (caar group-art)))
1762      ((eq action 'delete)
1763       (setq group-art nil))
1764      ((eq action 'warn)
1765       ;; We insert a warning.
1766       (let ((case-fold-search t))
1767         (goto-char (point-min))
1768         (re-search-forward "^message-id[ \t]*:" nil t)
1769         (beginning-of-line)
1770         (insert
1771          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1772         (funcall func (setq group-art
1773                             (nreverse (nnmail-article-group artnum-func))))))
1774      (t
1775       (funcall func (setq group-art
1776                           (nreverse (nnmail-article-group artnum-func))))))
1777     ;; Add the group-art list to the history list.
1778     (if group-art
1779         (push group-art nnmail-split-history)
1780       (delete-region (point-min) (point-max)))))
1781
1782 ;;; Get new mail.
1783
1784 (defvar nnmail-fetched-sources nil)
1785
1786 (defun nnmail-get-value (&rest args)
1787   (let ((sym (intern (apply 'format args))))
1788     (when (boundp sym)
1789       (symbol-value sym))))
1790
1791 (defun nnmail-get-new-mail (method exit-func temp
1792                             &optional group spool-func)
1793   "Read new incoming mail."
1794   (nnmail-get-new-mail-1 method exit-func temp group nil spool-func))
1795
1796 (defun nnmail-get-new-mail-1 (method exit-func temp
1797                               group in-group spool-func)
1798   (let* ((sources mail-sources)
1799          fetching-sources
1800          (i 0)
1801          (new 0)
1802          (total 0)
1803          source)
1804     (when (and (nnmail-get-value "%s-get-new-mail" method)
1805                sources)
1806       (while (setq source (pop sources))
1807         ;; Use group's parameter
1808         (when (eq (car source) 'group)
1809           (let ((mail-sources
1810                  (list
1811                   (gnus-group-find-parameter
1812                    (concat (symbol-name method) ":" group)
1813                    'mail-source t))))
1814             (nnmail-get-new-mail-1 method exit-func temp
1815                                    group group spool-func))
1816           (setq source nil))
1817         ;; Hack to only fetch the contents of a single group's spool file.
1818         (when (and (eq (car source) 'directory)
1819                    (null nnmail-scan-directory-mail-source-once)
1820                    group)
1821           (mail-source-bind (directory source)
1822             (setq source (append source
1823                                  (list
1824                                   :predicate
1825                                   (gnus-byte-compile
1826                                    `(lambda (file)
1827                                       (string-equal
1828                                        ,(concat group suffix)
1829                                        (file-name-nondirectory file)))))))))
1830         (when nnmail-fetched-sources
1831           (if (member source nnmail-fetched-sources)
1832               (setq source nil)
1833             (push source nnmail-fetched-sources)
1834             (push source fetching-sources)))))
1835     (when fetching-sources
1836       ;; We first activate all the groups.
1837       (nnmail-activate method)
1838       ;; Allow the user to hook.
1839       (run-hooks 'nnmail-pre-get-new-mail-hook)
1840       ;; Open the message-id cache.
1841       (nnmail-cache-open)
1842       ;; The we go through all the existing mail source specification
1843       ;; and fetch the mail from each.
1844       (while (setq source (pop fetching-sources))
1845         (when (setq new
1846                     (condition-case cond
1847                         (mail-source-fetch
1848                          source
1849                          (gnus-byte-compile
1850                           `(lambda (file orig-file)
1851                              (nnmail-split-incoming
1852                               file ',(intern (format "%s-save-mail" method))
1853                               ',spool-func
1854                               (or in-group
1855                                   (if (equal file orig-file)
1856                                       nil
1857                                     (nnmail-get-split-group orig-file
1858                                                             ',source)))
1859                               ',(intern (format "%s-active-number" method))))))
1860                       ((error quit)
1861                        (message "Mail source %s failed: %s" source cond)
1862                        0)))
1863           (incf total new)
1864           (incf i)))
1865       ;; If we did indeed read any incoming spools, we save all info.
1866       (if (zerop total)
1867           (when mail-source-plugged
1868             (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1869                               method (car source)))
1870         (nnmail-save-active
1871          (nnmail-get-value "%s-group-alist" method)
1872          (nnmail-get-value "%s-active-file" method))
1873         (when exit-func
1874           (funcall exit-func))
1875         (run-hooks 'nnmail-read-incoming-hook)
1876         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1877                           total))
1878       ;; Close the message-id cache.
1879       (nnmail-cache-close)
1880       ;; Allow the user to hook.
1881       (run-hooks 'nnmail-post-get-new-mail-hook))))
1882
1883 (defun nnmail-expired-article-p (group time force &optional inhibit)
1884   "Say whether an article that is TIME old in GROUP should be expired.
1885 If TIME is nil, then return the cutoff time for oldness instead."
1886   (if force
1887       (if (null time)
1888           (current-time)
1889         t)
1890     (let ((days (or (and nnmail-expiry-wait-function
1891                          (funcall nnmail-expiry-wait-function group))
1892                     nnmail-expiry-wait)))
1893       (cond ((or (eq days 'never)
1894                  (and (not force)
1895                       inhibit))
1896              ;; This isn't an expirable group.
1897              nil)
1898             ((eq days 'immediate)
1899              ;; We expire all articles on sight.
1900              (if (null time)
1901                  (current-time)
1902                t))
1903             ((equal time '(0 0))
1904             ;; This is an ange-ftp group, and we don't have any dates.
1905              nil)
1906             ((numberp days)
1907              (setq days (days-to-time days))
1908              ;; Compare the time with the current time.
1909              (if (null time)
1910                  (time-subtract (current-time) days)
1911                (ignore-errors (time-less-p days (time-since time)))))))))
1912
1913 (declare-function gnus-group-mark-article-read "gnus-group" (group article))
1914
1915 (defun nnmail-expiry-target-group (target group)
1916   ;; Do not invoke this from nntp-server-buffer!  At least nnfolder clears
1917   ;; that buffer if the nnfolder group isn't selected.
1918   (let (nnmail-cache-accepted-message-ids)
1919     ;; Don't enter Message-IDs into cache.
1920     ;; Let users hack it in TARGET function.
1921     (when (functionp target)
1922       (setq target (funcall target group)))
1923     (unless (eq target 'delete)
1924       (when (or (gnus-request-group target)
1925                 (gnus-request-create-group target))
1926         (let ((group-art (gnus-request-accept-article target nil nil t)))
1927           (when (and (consp group-art)
1928                      (cdr group-art))
1929             (gnus-group-mark-article-read target (cdr group-art))))))))
1930
1931 (defun nnmail-fancy-expiry-target (group)
1932   "Returns a target expiry group determined by `nnmail-fancy-expiry-targets'."
1933   (let* (header
1934          (case-fold-search nil)
1935          (from (or (message-fetch-field "from") ""))
1936          (to (or (message-fetch-field "to") ""))
1937          (date (message-fetch-field "date"))
1938          (target 'delete))
1939     (setq date (if date
1940                    (condition-case err
1941                        (date-to-time date)
1942                      (error
1943                       (message "%s" (error-message-string err))
1944                       (current-time)))
1945                  (current-time)))
1946     (dolist (regexp-target-pair (reverse nnmail-fancy-expiry-targets) target)
1947       (setq header (car regexp-target-pair))
1948       (cond
1949        ;; If the header is to-from then match against the
1950        ;; To or From header
1951        ((and (equal header 'to-from)
1952              (or (string-match (cadr regexp-target-pair) from)
1953                  (and (string-match (cadr regexp-target-pair) to)
1954                       (let* ((mail-dont-reply-to-names
1955                               (message-dont-reply-to-names))
1956                              (rmail-dont-reply-to-names ; obsolete since 24.1
1957                               mail-dont-reply-to-names))
1958                         (equal (if (fboundp 'rmail-dont-reply-to)
1959                                    (rmail-dont-reply-to from)
1960                                  (mail-dont-reply-to from)) "")))))
1961         (setq target (format-time-string (caddr regexp-target-pair) date)))
1962        ((and (not (equal header 'to-from))
1963              (string-match (cadr regexp-target-pair)
1964                            (or
1965                             (message-fetch-field header)
1966                             "")))
1967         (setq target
1968               (format-time-string (caddr regexp-target-pair) date)))))))
1969
1970 (defun nnmail-check-syntax ()
1971   "Check (and modify) the syntax of the message in the current buffer."
1972   (save-restriction
1973     (message-narrow-to-head)
1974     (let ((case-fold-search t))
1975       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1976         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1977
1978 (defun nnmail-write-region (start end filename &optional append visit lockname)
1979   "Do a `write-region', and then set the file modes."
1980   (let ((coding-system-for-write nnmail-file-coding-system)
1981         (file-name-coding-system nnmail-pathname-coding-system))
1982     (write-region start end filename append visit lockname)
1983     (set-file-modes filename nnmail-default-file-modes)))
1984
1985 ;;;
1986 ;;; Status functions
1987 ;;;
1988
1989 (defun nnmail-replace-status (name value)
1990   "Make status NAME and VALUE part of the current status line."
1991   (save-restriction
1992     (message-narrow-to-head)
1993     (let ((status (nnmail-decode-status)))
1994       (setq status (delq (member name status) status))
1995       (when value
1996         (push (cons name value) status))
1997       (message-remove-header "status")
1998       (goto-char (point-max))
1999       (insert "Status: " (nnmail-encode-status status) "\n"))))
2000
2001 (defun nnmail-decode-status ()
2002   "Return a status-value alist from STATUS."
2003   (goto-char (point-min))
2004   (when (re-search-forward "^Status: " nil t)
2005     (let (name value status)
2006       (save-restriction
2007         ;; Narrow to the status.
2008         (narrow-to-region
2009          (point)
2010          (if (re-search-forward "^[^ \t]" nil t)
2011              (1- (point))
2012            (point-max)))
2013         ;; Go through all elements and add them to the list.
2014         (goto-char (point-min))
2015         (while (re-search-forward "[^ \t=]+" nil t)
2016           (setq name (match-string 0))
2017           (if (not (eq (char-after) ?=))
2018               ;; Implied "yes".
2019               (setq value "yes")
2020             (forward-char 1)
2021             (if (not (eq (char-after) ?\"))
2022                 (if (not (looking-at "[^ \t]"))
2023                     ;; Implied "no".
2024                     (setq value "no")
2025                   ;; Unquoted value.
2026                   (setq value (match-string 0))
2027                   (goto-char (match-end 0)))
2028               ;; Quoted value.
2029               (setq value (read (current-buffer)))))
2030           (push (cons name value) status)))
2031       status)))
2032
2033 (defun nnmail-encode-status (status)
2034   "Return a status string from STATUS."
2035   (mapconcat
2036    (lambda (elem)
2037      (concat
2038       (car elem) "="
2039       (if (string-match "[ \t]" (cdr elem))
2040           (prin1-to-string (cdr elem))
2041         (cdr elem))))
2042    status " "))
2043
2044 (defun nnmail-split-history ()
2045   "Generate an overview of where the last mail split put articles."
2046   (interactive)
2047   (unless nnmail-split-history
2048     (error "No current split history"))
2049   (with-output-to-temp-buffer "*nnmail split history*"
2050     (with-current-buffer standard-output
2051       (fundamental-mode))               ; for Emacs 20.4+
2052       (dolist (elem nnmail-split-history)
2053         (princ (mapconcat (lambda (ga)
2054                             (concat (car ga) ":" (int-to-string (cdr ga))))
2055                           elem
2056                           ", "))
2057         (princ "\n"))))
2058
2059 (defun nnmail-purge-split-history (group)
2060   "Remove all instances of GROUP from `nnmail-split-history'."
2061   (let ((history nnmail-split-history))
2062     (while history
2063       (setcar history (gnus-remove-if (lambda (e) (string= (car e) group))
2064                                       (car history)))
2065       (pop history))
2066     (setq nnmail-split-history (delq nil nnmail-split-history))))
2067
2068 (defun nnmail-new-mail-p (group)
2069   "Say whether GROUP has new mail."
2070   (let ((his nnmail-split-history)
2071         found)
2072     (while his
2073       (when (assoc group (pop his))
2074         (setq found t
2075               his nil)))
2076     found))
2077
2078 (defun nnmail-within-headers-p ()
2079   "Check to see if point is within the headers of a unix mail message.
2080 Doesn't change point."
2081   (let ((pos (point)))
2082     (save-excursion
2083       (and (nnmail-search-unix-mail-delim-backward)
2084            (not (search-forward "\n\n" pos t))))))
2085
2086 (run-hooks 'nnmail-load-hook)
2087
2088 (provide 'nnmail)
2089
2090 ;;; nnmail.el ends here