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