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