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