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