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