Better tags for nnmail-split-fancy widget
[gnus] / 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 'custom)
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 retrival."
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   :group 'nnmail-split
123   :type '(choice (const :tag "none" nil)
124                  (regexp :value ".*")
125                  (repeat :value (".*") regexp)))
126
127 (defcustom nnmail-cache-ignore-groups nil
128   "Regexp that matches group names to be ignored when inserting message ids into the cache (`nnmail-cache-insert').
129 This can also be a list of regexps."
130   :group 'nnmail-split
131   :type '(choice (const :tag "none" nil)
132                  (regexp :value ".*")
133                  (repeat :value (".*") regexp)))
134
135 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
136 (defcustom nnmail-keep-last-article nil
137   "If non-nil, nnmail will never delete/move a group's last article.
138 It can be marked expirable, so it will be deleted when it is no longer last.
139
140 You may need to set this variable if other programs are putting
141 new mail into folder numbers that Gnus has marked as expired."
142   :group 'nnmail-procmail
143   :group 'nnmail-various
144   :type 'boolean)
145
146 (defcustom nnmail-use-long-file-names nil
147   "If non-nil the mail backends will use long file and directory names.
148 If nil, groups like \"mail.misc\" will end up in directories like
149 \"mail/misc/\"."
150   :group 'nnmail-files
151   :type 'boolean)
152
153 (defcustom nnmail-default-file-modes 384
154   "Set the mode bits of all new mail files to this integer."
155   :group 'nnmail-files
156   :type 'integer)
157
158 (defcustom nnmail-expiry-wait 7
159   "*Expirable articles that are older than this will be expired.
160 This variable can either be a number (which will be interpreted as a
161 number of days) -- this doesn't have to be an integer.  This variable
162 can also be `immediate' and `never'."
163   :group 'nnmail-expire
164   :type '(choice (const immediate)
165                  (number :tag "days")
166                  (const never)))
167
168 (defcustom nnmail-expiry-wait-function nil
169   "Variable that holds function to specify how old articles should be before they are expired.
170 The function will be called with the name of the group that the expiry
171 is to be performed in, and it should return an integer that says how
172 many days an article can be stored before it is considered \"old\".
173 It can also return the values `never' and `immediate'.
174
175 Eg.:
176
177 \(setq nnmail-expiry-wait-function
178       (lambda (newsgroup)
179         (cond ((string-match \"private\" newsgroup) 31)
180               ((string-match \"junk\" newsgroup) 1)
181               ((string-match \"important\" newsgroup) 'never)
182               (t 7))))"
183   :group 'nnmail-expire
184   :type '(choice (const :tag "nnmail-expiry-wait" nil)
185                  (function :format "%v" nnmail-)))
186
187 (defcustom nnmail-expiry-target 'delete
188   "*Variable that says where expired messages should end up.
189 The default value is `delete' (which says to delete the messages),
190 but it can also be a string or a function.  If it is a string, expired
191 messages end up in that group.  If it is a function, the function is
192 called in a buffer narrowed to the message in question.  The function
193 receives one argument, the name of the group the message comes from.
194 The return value should be `delete' or a group name (a string)."
195   :version "21.1"
196   :group 'nnmail-expire
197   :type '(choice (const delete)
198                  (function :format "%v" nnmail-)
199                  string))
200
201 (defcustom nnmail-fancy-expiry-targets nil
202   "Determine expiry target based on articles using fancy techniques.
203
204 This is a list of (\"HEADER\" \"REGEXP\" \"TARGET\") entries.  If
205 `nnmail-expiry-target' is set to the function
206 `nnmail-fancy-expiry-target' and HEADER of the article matches REGEXP,
207 the message will be expired to a group determined by invoking
208 `format-time-string' with TARGET used as the format string and the
209 time extracted from the articles' Date header (if missing the current
210 time is used).
211
212 In the special cases that HEADER is the symbol `to-from', the regexp
213 will try to match against both the From and the To header.
214
215 Example:
216
217 \(setq nnmail-fancy-expiry-targets
218       '((to-from \"boss\" \"nnfolder:Work\")
219         (\"Subject\" \"IMPORTANT\" \"nnfolder:IMPORTANT.%Y.%b\")
220         (\"from\" \".*\" \"nnfolder:Archive-%Y\")))
221
222 In this case, articles containing the string \"boss\" in the To or the
223 From header will be expired to the group \"nnfolder:Work\";
224 articles containing the sting \"IMPORTANT\" in the Subject header will
225 be expired to the group \"nnfolder:IMPORTANT.YYYY.MMM\"; and
226 everything else will be expired to \"nnfolder:Archive-YYYY\"."
227   :group 'nnmail-expire
228   :type '(repeat (list (choice :tag "Match against"
229                                (string :tag "Header")
230                                (const to-from))
231                        regexp
232                        (string :tag "Target group format string"))))
233
234 (defcustom nnmail-cache-accepted-message-ids nil
235   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache.
236 If non-nil, also update the cache when copy or move articles."
237   :group 'nnmail
238   :type 'boolean)
239
240 (defcustom nnmail-spool-file '((file))
241   "*Where the mail backends will look for incoming mail.
242 This variable is a list of mail source specifiers.
243 This variable is obsolete; `mail-sources' should be used instead."
244   :group 'nnmail-files
245   :type 'sexp)
246
247 (defcustom nnmail-resplit-incoming nil
248   "*If non-nil, re-split incoming procmail sorted mail."
249   :group 'nnmail-procmail
250   :type 'boolean)
251
252 (defcustom nnmail-scan-directory-mail-source-once nil
253   "*If non-nil, scan all incoming procmail sorted mails once.
254 It scans low-level sorted spools even when not required."
255   :version "21.1"
256   :group 'nnmail-procmail
257   :type 'boolean)
258
259 (defcustom nnmail-delete-file-function 'delete-file
260   "Function called to delete files in some mail backends."
261   :group 'nnmail-files
262   :type 'function)
263
264 (defcustom nnmail-crosspost-link-function
265   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
266       'copy-file
267     'add-name-to-file)
268   "*Function called to create a copy of a file.
269 This is `add-name-to-file' by default, which means that crossposts
270 will use hard links.  If your file system doesn't allow hard
271 links, you could set this variable to `copy-file' instead."
272   :group 'nnmail-files
273   :type '(radio (function-item add-name-to-file)
274                 (function-item copy-file)
275                 (function :tag "Other")))
276
277 (defcustom nnmail-read-incoming-hook
278   (if (eq system-type 'windows-nt)
279       '(nnheader-ms-strip-cr)
280     nil)
281   "*Hook that will be run after the incoming mail has been transferred.
282 The incoming mail is moved from the specified spool file (which normally is
283 something like \"/usr/spool/mail/$user\") to the user's home
284 directory.  This hook is called after the incoming mail box has been
285 emptied, and can be used to call any mail box programs you have
286 running (\"xwatch\", etc.)
287
288 Eg.
289
290 \(add-hook 'nnmail-read-incoming-hook
291           (lambda ()
292             (call-process \"/local/bin/mailsend\" nil nil nil
293                           \"read\" nnmail-spool-file)))
294
295 If you have xwatch running, this will alert it that mail has been
296 read.
297
298 If you use `display-time', you could use something like this:
299
300 \(add-hook 'nnmail-read-incoming-hook
301           (lambda ()
302             ;; Update the displayed time, since that will clear out
303             ;; the flag that says you have mail.
304             (when (eq (process-status \"display-time\") 'run)
305               (display-time-filter display-time-process \"\"))))"
306   :group 'nnmail-prepare
307   :type 'hook)
308
309 (defcustom nnmail-prepare-incoming-hook nil
310   "Hook called before treating incoming mail.
311 The hook is run in a buffer with all the new, incoming mail."
312   :group 'nnmail-prepare
313   :type 'hook)
314
315 (defcustom nnmail-prepare-incoming-header-hook nil
316   "Hook called narrowed to the headers of each message.
317 This can be used to remove excessive spaces (and stuff like
318 that) from the headers before splitting and saving the messages."
319   :group 'nnmail-prepare
320   :type 'hook)
321
322 (defcustom nnmail-prepare-incoming-message-hook nil
323   "Hook called narrowed to each message."
324   :group 'nnmail-prepare
325   :type 'hook)
326
327 (defcustom nnmail-list-identifiers nil
328   "Regexp that matches list identifiers to be removed.
329 This can also be a list of regexps."
330   :group 'nnmail-prepare
331   :type '(choice (const :tag "none" nil)
332                  (regexp :value ".*")
333                  (repeat :value (".*") regexp)))
334
335 (defcustom nnmail-pre-get-new-mail-hook nil
336   "Hook called just before starting to handle new incoming mail."
337   :group 'nnmail-retrieve
338   :type 'hook)
339
340 (defcustom nnmail-post-get-new-mail-hook nil
341   "Hook called just after finishing handling new incoming mail."
342   :group 'nnmail-retrieve
343   :type 'hook)
344
345 (defcustom nnmail-split-hook nil
346   "Hook called before deciding where to split an article.
347 The functions in this hook are free to modify the buffer
348 contents in any way they choose -- the buffer contents are
349 discarded after running the split process."
350   :group 'nnmail-split
351   :type 'hook)
352
353 (defcustom nnmail-spool-hook nil
354   "*A hook called when a new article is spooled."
355   :group 'nnmail
356   :type 'hook)
357
358 (defcustom nnmail-large-newsgroup 50
359   "*The number of articles which indicates a large newsgroup or nil.
360 If the number of articles is greater than the value, verbose
361 messages will be shown to indicate the current status."
362   :group 'nnmail-various
363   :type '(choice (const :tag "infinite" nil)
364                  (number :tag "count")))
365
366 (define-widget 'nnmail-lazy 'default
367   "Base widget for recursive datastructures.
368
369 This is copy of the `lazy' widget in Emacs 21.4 provided for compatibility."
370   :format "%{%t%}: %v"
371   :convert-widget 'widget-value-convert-widget
372   :value-create (lambda (widget)
373                   (let ((value (widget-get widget :value))
374                         (type (widget-get widget :type)))
375                     (widget-put widget :children 
376                                 (list (widget-create-child-value 
377                                        widget (widget-convert type) value)))))
378   :value-delete 'widget-children-value-delete
379   :value-get (lambda (widget)
380                (widget-value (car (widget-get widget :children))))
381   :value-inline (lambda (widget)
382                   (widget-apply (car (widget-get widget :children))
383                                 :value-inline))
384   :default-get (lambda (widget)
385                  (widget-default-get
386                   (widget-convert (widget-get widget :type))))
387   :match (lambda (widget value)
388            (widget-apply (widget-convert (widget-get widget :type))
389                          :match value))
390   :validate (lambda (widget)
391               (widget-apply (car (widget-get widget :children)) :validate)))
392
393 (define-widget 'nnmail-split-fancy 'nnmail-lazy
394   "Widget for customizing splits in the variable of the same name."
395   :tag "Split"
396   :type '(menu-choice :value (any ".*value.*" "misc")
397                       :tag "Type"
398                       (string :tag "Destination")
399                       (list :tag "Use first match (|)" :value (|)
400                             (const :format "" |)
401                             (editable-list :inline t nnmail-split-fancy))
402                       (list :tag "Use all matches (&)" :value (&)
403                             (const :format "" &)
404                             (editable-list :inline t nnmail-split-fancy))
405                       (list :tag "Function with fixed arguments (:)"
406                             :value (:)
407                             (const :format "" :value :)
408                             function 
409                             (editable-list :inline t (sexp :tag "Arg"))
410                             )
411                       (list :tag "Function with split arguments (!)" :value (!)
412                             (const :format "" !)
413                             function
414                             (editable-list :inline t nnmail-split-fancy))
415                       (list :tag "Field match" 
416                             (choice :tag "Field" 
417                                     regexp symbol)
418                             (choice :tag "Match"
419                                     regexp 
420                                     (symbol :value mail))
421                             nnmail-split-fancy)
422                       (const :tag "Junk (delete mail)" junk)))
423
424 (defcustom nnmail-split-fancy "mail.misc"
425   "Incoming mail can be split according to this fancy variable.
426 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
427
428 The format of this variable is SPLIT, where SPLIT can be one of
429 the following:
430
431 GROUP: Mail will be stored in GROUP (a string).
432
433 \(FIELD VALUE [- RESTRICT [- RESTRICT [...]]] SPLIT): If the message
434   field FIELD (a regexp) contains VALUE (a regexp), store the messages
435   as specified by SPLIT.  If RESTRICT (a regexp) matches some string
436   after FIELD and before the end of the matched VALUE, return nil,
437   otherwise process SPLIT.  Multiple RESTRICTs add up, further
438   restricting the possibility of processing SPLIT.
439
440 \(| SPLIT...): Process each SPLIT expression until one of them matches.
441   A SPLIT expression is said to match if it will cause the mail
442   message to be stored in one or more groups.
443
444 \(& SPLIT...): Process each SPLIT expression.
445
446 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
447   the buffer containing the message headers.  The return value FUNCTION
448   should be a split, which is then recursively processed.
449
450 \(! FUNCTION SPLIT): Call FUNCTION with the result of SPLIT.  The
451   return value FUNCTION should be a split, which is then recursively
452   processed.
453
454 junk: Mail will be deleted.  Use with care!  Do not submerge in water!
455   Example:
456   (setq nnmail-split-fancy
457         '(| (\"Subject\" \"MAKE MONEY FAST\" junk)
458             ...other.rules.omitted...))
459
460 FIELD must match a complete field name.  VALUE must match a complete
461 word according to the `nnmail-split-fancy-syntax-table' syntax table.
462 You can use \".*\" in the regexps to match partial field names or words.
463
464 FIELD and VALUE can also be lisp symbols, in that case they are expanded
465 as specified in `nnmail-split-abbrev-alist'.
466
467 GROUP can contain \\& and \\N which will substitute from matching
468 \\(\\) patterns in the previous VALUE.
469
470 Example:
471
472 \(setq nnmail-split-methods 'nnmail-split-fancy
473       nnmail-split-fancy
474       ;; Messages from the mailer daemon are not crossposted to any of
475       ;; the ordinary groups.  Warnings are put in a separate group
476       ;; from real errors.
477       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
478                           \"mail.misc\"))
479           ;; Non-error messages are crossposted to all relevant
480           ;; groups, but we don't crosspost between the group for the
481           ;; (ding) list and the group for other (ding) related mail.
482           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
483                 (\"subject\" \"ding\" \"ding.misc\"))
484              ;; Other mailing lists...
485              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
486              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
487              ;; Both lists below have the same suffix, so prevent
488              ;; cross-posting to mkpkg.list of messages posted only to
489              ;; the bugs- list, but allow cross-posting when the
490              ;; message was really cross-posted.
491              (any \"bugs-mypackage@somewhere\" \"mypkg.bugs\")
492              (any \"mypackage@somewhere\" - \"bugs-mypackage\" \"mypkg.list\")
493              ;;
494              ;; People...
495              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
496           ;; Unmatched mail goes to the catch all group.
497           \"misc.misc\"))"
498   :group 'nnmail-split
499   :type 'nnmail-split-fancy)
500
501 (defcustom nnmail-split-abbrev-alist
502   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
503     (mail . "mailer-daemon\\|postmaster\\|uucp")
504     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
505     (from . "from\\|sender\\|resent-from")
506     (nato . "to\\|cc\\|resent-to\\|resent-cc")
507     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
508   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
509   :group 'nnmail-split
510   :type '(repeat (cons :format "%v" symbol regexp)))
511
512 (defcustom nnmail-message-id-cache-length 1000
513   "*The approximate number of Message-IDs nnmail will keep in its cache.
514 If this variable is nil, no checking on duplicate messages will be
515 performed."
516   :group 'nnmail-duplicate
517   :type '(choice (const :tag "disable" nil)
518                  (integer :format "%v")))
519
520 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
521   "*The file name of the nnmail Message-ID cache."
522   :group 'nnmail-duplicate
523   :group 'nnmail-files
524   :type 'file)
525
526 (defcustom nnmail-treat-duplicates 'warn
527   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
528 Three values are valid: nil, which means that nnmail is not to keep a
529 Message-ID cache; `warn', which means that nnmail should insert extra
530 headers to warn the user about the duplication (this is the default);
531 and `delete', which means that nnmail will delete duplicated mails.
532
533 This variable can also be a function.  It will be called from a buffer
534 narrowed to the article in question with the Message-ID as a
535 parameter.  It should return nil, `warn' or `delete'."
536   :group 'nnmail-duplicate
537   :type '(choice (const :tag "off" nil)
538                  (const warn)
539                  (const delete)))
540
541 (defcustom nnmail-extra-headers '(To Newsgroups)
542   "*Extra headers to parse."
543   :version "21.1"
544   :group 'nnmail
545   :type '(repeat symbol))
546
547 (defcustom nnmail-split-header-length-limit 512
548   "Header lines longer than this limit are excluded from the split function."
549   :version "21.1"
550   :group 'nnmail
551   :type 'integer)
552
553 (defcustom nnmail-mail-splitting-charset nil
554   "Default charset to be used when splitting incoming mail."
555   :group 'nnmail
556   :type 'symbol)
557
558 (defcustom nnmail-mail-splitting-decodes nil
559   "Whether the nnmail splitting functionality should MIME decode headers."
560   :group 'nnmail
561   :type 'boolean)
562
563 (defcustom nnmail-split-fancy-match-partial-words nil
564   "Whether to match partial words when fancy splitting.
565 Normally, regexes given in `nnmail-split-fancy' are implicitly surrounded
566 by \"\\=\\<...\\>\".  If this variable is true, they are not implicitly\
567  surrounded
568 by anything."
569   :group 'nnmail
570   :type 'boolean)
571
572 ;;; Internal variables.
573
574 (defvar nnmail-article-buffer " *nnmail incoming*"
575   "The buffer used for splitting incoming mails.")
576
577 (defvar nnmail-split-history nil
578   "List of group/article elements that say where the previous split put messages.")
579
580 (defvar nnmail-split-fancy-syntax-table
581   (let ((table (make-syntax-table)))
582     ;; support the %-hack
583     (modify-syntax-entry ?\% "." table)
584     table)
585   "Syntax table used by `nnmail-split-fancy'.")
586
587 (defvar nnmail-prepare-save-mail-hook nil
588   "Hook called before saving mail.")
589
590 (defvar nnmail-split-tracing nil)
591 (defvar nnmail-split-trace nil)
592
593 \f
594
595 (defun nnmail-request-post (&optional server)
596   (mail-send-and-exit nil))
597
598 (defvar nnmail-file-coding-system 'raw-text
599   "Coding system used in nnmail.")
600
601 (defvar nnmail-incoming-coding-system
602   mm-text-coding-system
603   "Coding system used in reading inbox")
604
605 (defvar nnmail-pathname-coding-system nil
606   "*Coding system for file name.")
607
608 (defun nnmail-find-file (file)
609   "Insert FILE in server buffer safely."
610   (set-buffer nntp-server-buffer)
611   (delete-region (point-min) (point-max))
612   (let ((format-alist nil)
613         (after-insert-file-functions nil))
614     (condition-case ()
615         (let ((coding-system-for-read nnmail-file-coding-system)
616               (auto-mode-alist (mm-auto-mode-alist))
617               (file-name-coding-system nnmail-pathname-coding-system))
618           (insert-file-contents file)
619           t)
620       (file-error nil))))
621
622 (defun nnmail-group-pathname (group dir &optional file)
623   "Make file name for GROUP."
624   (concat
625    (let ((dir (file-name-as-directory (expand-file-name dir))))
626      (setq group (nnheader-replace-duplicate-chars-in-string
627                   (nnheader-replace-chars-in-string group ?/ ?_)
628                   ?. ?_))
629      (setq group (nnheader-translate-file-chars group))
630      ;; If this directory exists, we use it directly.
631      (file-name-as-directory
632       (if (or nnmail-use-long-file-names
633               (file-directory-p (concat dir group)))
634           (expand-file-name group dir)
635         ;; If not, we translate dots into slashes.
636         (expand-file-name
637          (mm-encode-coding-string
638           (nnheader-replace-chars-in-string group ?. ?/)
639           nnmail-pathname-coding-system)
640          dir))))
641    (or file "")))
642
643 (defun nnmail-get-active ()
644   "Returns an assoc of group names and active ranges.
645 nn*-request-list should have been called before calling this function."
646   ;; Go through all groups from the active list.
647   (save-excursion
648     (set-buffer nntp-server-buffer)
649     (nnmail-parse-active)))
650
651 (defun nnmail-parse-active ()
652   "Parse the active file in the current buffer and return an alist."
653   (goto-char (point-min))
654   (unless (re-search-forward "[\\\"]" nil t)
655     (goto-char (point-max))
656     (while (re-search-backward "[][';?()#]" nil t)
657       (insert ?\\)))
658   (goto-char (point-min))
659   (let ((buffer (current-buffer))
660         group-assoc group max min)
661     (while (not (eobp))
662       (condition-case err
663           (progn
664             (narrow-to-region (point) (gnus-point-at-eol))
665             (setq group (read buffer))
666             (unless (stringp group)
667               (setq group (symbol-name group)))
668             (if (and (numberp (setq max (read buffer)))
669                      (numberp (setq min (read buffer))))
670                 (push (list group (cons min max))
671                       group-assoc)))
672         (error nil))
673       (widen)
674       (forward-line 1))
675     group-assoc))
676
677 (defvar nnmail-active-file-coding-system 'raw-text
678   "*Coding system for active file.")
679
680 (defun nnmail-save-active (group-assoc file-name)
681   "Save GROUP-ASSOC in ACTIVE-FILE."
682   (let ((coding-system-for-write nnmail-active-file-coding-system))
683     (when file-name
684       (with-temp-file file-name
685         (nnmail-generate-active group-assoc)))))
686
687 (defun nnmail-generate-active (alist)
688   "Generate an active file from group-alist ALIST."
689   (erase-buffer)
690   (let (group)
691     (while (setq group (pop alist))
692       (insert (format "%S %d %d y\n" (intern (car group)) (cdadr group)
693                       (caadr group))))
694     (goto-char (point-max))
695     (while (search-backward "\\." nil t)
696       (delete-char 1))))
697
698 (defun nnmail-get-split-group (file source)
699   "Find out whether this FILE is to be split into GROUP only.
700 If SOURCE is a directory spec, try to return the group name component."
701   (if (eq (car source) 'directory)
702       (let ((file (file-name-nondirectory file)))
703         (mail-source-bind (directory source)
704           (if (string-match (concat (regexp-quote suffix) "$") file)
705               (substring file 0 (match-beginning 0))
706             nil)))
707     nil))
708
709 (defun nnmail-process-babyl-mail-format (func artnum-func)
710   (let ((case-fold-search t)
711         (count 0)
712         start message-id content-length do-search end)
713     (while (not (eobp))
714       (goto-char (point-min))
715       (re-search-forward
716        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
717       (goto-char (match-end 0))
718       (delete-region (match-beginning 0) (match-end 0))
719       (narrow-to-region
720        (setq start (point))
721        (progn
722          ;; Skip all the headers in case there are more "From "s...
723          (or (search-forward "\n\n" nil t)
724              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
725              (search-forward "\1f\f"))
726          (point)))
727       ;; Unquote the ">From " line, if any.
728       (goto-char (point-min))
729       (when (looking-at ">From ")
730         (replace-match "X-From-Line: ") )
731       (run-hooks 'nnmail-prepare-incoming-header-hook)
732       (goto-char (point-max))
733       ;; Find the Message-ID header.
734       (save-excursion
735         (if (re-search-backward
736              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
737             (setq message-id (buffer-substring (match-beginning 1)
738                                                (match-end 1)))
739           ;; There is no Message-ID here, so we create one.
740           (save-excursion
741             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
742               (beginning-of-line)
743               (insert "Original-")))
744           (forward-line -1)
745           (insert "Message-ID: " (setq message-id (nnmail-message-id))
746                   "\n")))
747       ;; Look for a Content-Length header.
748       (if (not (save-excursion
749                  (and (re-search-backward
750                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
751                       (setq content-length (string-to-int
752                                             (buffer-substring
753                                              (match-beginning 1)
754                                              (match-end 1))))
755                       ;; We destroy the header, since none of
756                       ;; the backends ever use it, and we do not
757                       ;; want to confuse other mailers by having
758                       ;; a (possibly) faulty header.
759                       (progn (insert "X-") t))))
760           (setq do-search t)
761         (widen)
762         (if (or (= (+ (point) content-length) (point-max))
763                 (save-excursion
764                   (goto-char (+ (point) content-length))
765                   (looking-at "\1f")))
766             (progn
767               (goto-char (+ (point) content-length))
768               (setq do-search nil))
769           (setq do-search t)))
770       (widen)
771       ;; Go to the beginning of the next article - or to the end
772       ;; of the buffer.
773       (when do-search
774         (if (re-search-forward "^\1f" nil t)
775             (goto-char (match-beginning 0))
776           (goto-char (1- (point-max)))))
777       (delete-char 1)                   ; delete ^_
778       (save-excursion
779         (save-restriction
780           (narrow-to-region start (point))
781           (goto-char (point-min))
782           (nnmail-check-duplication message-id func artnum-func)
783           (incf count)
784           (setq end (point-max))))
785       (goto-char end))
786     count))
787
788 (defsubst nnmail-search-unix-mail-delim ()
789   "Put point at the beginning of the next Unix mbox message."
790   ;; Algorithm used to find the next article in the
791   ;; brain-dead Unix mbox format:
792   ;;
793   ;; 1) Search for "^From ".
794   ;; 2) If we find it, then see whether the previous
795   ;;    line is blank and the next line looks like a header.
796   ;; Then it's possible that this is a mail delim, and we use it.
797   (let ((case-fold-search nil)
798         found)
799     (while (not found)
800       (if (not (re-search-forward "^From " nil t))
801           (setq found 'no)
802         (save-excursion
803           (beginning-of-line)
804           (when (and (or (bobp)
805                          (save-excursion
806                            (forward-line -1)
807                            (eq (char-after) ?\n)))
808                      (save-excursion
809                        (forward-line 1)
810                        (while (looking-at ">From \\|From ")
811                          (forward-line 1))
812                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
813             (setq found 'yes)))))
814     (beginning-of-line)
815     (eq found 'yes)))
816
817 (defun nnmail-search-unix-mail-delim-backward ()
818   "Put point at the beginning of the current Unix mbox message."
819   ;; Algorithm used to find the next article in the
820   ;; brain-dead Unix mbox format:
821   ;;
822   ;; 1) Search for "^From ".
823   ;; 2) If we find it, then see whether the previous
824   ;;    line is blank and the next line looks like a header.
825   ;; Then it's possible that this is a mail delim, and we use it.
826   (let ((case-fold-search nil)
827         found)
828     (while (not found)
829       (if (not (re-search-backward "^From " nil t))
830           (setq found 'no)
831         (save-excursion
832           (beginning-of-line)
833           (when (and (or (bobp)
834                          (save-excursion
835                            (forward-line -1)
836                            (eq (char-after) ?\n)))
837                      (save-excursion
838                        (forward-line 1)
839                        (while (looking-at ">From \\|From ")
840                          (forward-line 1))
841                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
842             (setq found 'yes)))))
843     (beginning-of-line)
844     (eq found 'yes)))
845
846 (defun nnmail-process-unix-mail-format (func artnum-func)
847   (let ((case-fold-search t)
848         (count 0)
849         start message-id content-length end skip head-end)
850     (goto-char (point-min))
851     (if (not (and (re-search-forward "^From " nil t)
852                   (goto-char (match-beginning 0))))
853         ;; Possibly wrong format?
854         (error "Error, unknown mail format! (Possibly corrupted %s `%s'.)"
855                (if (buffer-file-name) "file" "buffer")
856                (or (buffer-file-name) (buffer-name)))
857       ;; Carry on until the bitter end.
858       (while (not (eobp))
859         (setq start (point)
860               end nil)
861         ;; Find the end of the head.
862         (narrow-to-region
863          start
864          (if (search-forward "\n\n" nil t)
865              (1- (point))
866            ;; This will never happen, but just to be on the safe side --
867            ;; if there is no head-body delimiter, we search a bit manually.
868            (while (and (looking-at "From \\|[^ \t]+:")
869                        (not (eobp)))
870              (forward-line 1))
871            (point)))
872         ;; Find the Message-ID header.
873         (goto-char (point-min))
874         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
875             (setq message-id (match-string 1))
876           (save-excursion
877             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
878               (beginning-of-line)
879               (insert "Original-")))
880           ;; There is no Message-ID here, so we create one.
881           (forward-line 1)
882           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
883         ;; Look for a Content-Length header.
884         (goto-char (point-min))
885         (if (not (re-search-forward
886                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
887             (setq content-length nil)
888           (setq content-length (string-to-int (match-string 1)))
889           ;; We destroy the header, since none of the backends ever
890           ;; use it, and we do not want to confuse other mailers by
891           ;; having a (possibly) faulty header.
892           (beginning-of-line)
893           (insert "X-"))
894         (run-hooks 'nnmail-prepare-incoming-header-hook)
895         ;; Find the end of this article.
896         (goto-char (point-max))
897         (widen)
898         (setq head-end (point))
899         ;; We try the Content-Length value.  The idea: skip over the header
900         ;; separator, then check what happens content-length bytes into the
901         ;; message body.  This should be either the end of the buffer, the
902         ;; message separator or a blank line followed by the separator.
903         ;; The blank line should probably be deleted.  If neither of the
904         ;; three is met, the content-length header is probably invalid.
905         (when content-length
906           (forward-line 1)
907           (setq skip (+ (point) content-length))
908           (goto-char skip)
909           (cond ((or (= skip (point-max))
910                      (= (1+ skip) (point-max)))
911                  (setq end (point-max)))
912                 ((looking-at "From ")
913                  (setq end skip))
914                 ((looking-at "[ \t]*\n\\(From \\)")
915                  (setq end (match-beginning 1)))
916                 (t (setq end nil))))
917         (if end
918             (goto-char end)
919           ;; No Content-Length, so we find the beginning of the next
920           ;; article or the end of the buffer.
921           (goto-char head-end)
922           (or (nnmail-search-unix-mail-delim)
923               (goto-char (point-max))))
924         ;; Allow the backend to save the article.
925         (save-excursion
926           (save-restriction
927             (narrow-to-region start (point))
928             (goto-char (point-min))
929             (incf count)
930             (nnmail-check-duplication message-id func artnum-func)
931             (setq end (point-max))))
932         (goto-char end)))
933     count))
934
935 (defun nnmail-process-mmdf-mail-format (func artnum-func)
936   (let ((delim "^\^A\^A\^A\^A$")
937         (case-fold-search t)
938         (count 0)
939         start message-id end)
940     (goto-char (point-min))
941     (if (not (and (re-search-forward delim nil t)
942                   (forward-line 1)))
943         ;; Possibly wrong format?
944         (error "Error, unknown mail format! (Possibly corrupted.)")
945       ;; Carry on until the bitter end.
946       (while (not (eobp))
947         (setq start (point))
948         ;; Find the end of the head.
949         (narrow-to-region
950          start
951          (if (search-forward "\n\n" nil t)
952              (1- (point))
953            ;; This will never happen, but just to be on the safe side --
954            ;; if there is no head-body delimiter, we search a bit manually.
955            (while (and (looking-at "From \\|[^ \t]+:")
956                        (not (eobp)))
957              (forward-line 1))
958            (point)))
959         ;; Find the Message-ID header.
960         (goto-char (point-min))
961         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
962             (setq message-id (match-string 1))
963           ;; There is no Message-ID here, so we create one.
964           (save-excursion
965             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
966               (beginning-of-line)
967               (insert "Original-")))
968           (forward-line 1)
969           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
970         (run-hooks 'nnmail-prepare-incoming-header-hook)
971         ;; Find the end of this article.
972         (goto-char (point-max))
973         (widen)
974         (if (re-search-forward delim nil t)
975             (beginning-of-line)
976           (goto-char (point-max)))
977         ;; Allow the backend to save the article.
978         (save-excursion
979           (save-restriction
980             (narrow-to-region start (point))
981             (goto-char (point-min))
982             (incf count)
983             (nnmail-check-duplication message-id func artnum-func)
984             (setq end (point-max))))
985         (goto-char end)
986         (forward-line 2)))
987     count))
988
989 (defun nnmail-process-maildir-mail-format (func artnum-func)
990   ;; In a maildir, every file contains exactly one mail.
991   (let ((case-fold-search t)
992         message-id)
993     (goto-char (point-min))
994     ;; Find the end of the head.
995     (narrow-to-region
996      (point-min)
997      (if (search-forward "\n\n" nil t)
998          (1- (point))
999        ;; This will never happen, but just to be on the safe side --
1000        ;; if there is no head-body delimiter, we search a bit manually.
1001        (while (and (looking-at "From \\|[^ \t]+:")
1002                    (not (eobp)))
1003          (forward-line 1))
1004        (point)))
1005     ;; Find the Message-ID header.
1006     (goto-char (point-min))
1007     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
1008         (setq message-id (match-string 1))
1009       ;; There is no Message-ID here, so we create one.
1010       (save-excursion
1011         (when (re-search-backward "^Message-ID[ \t]*:" nil t)
1012           (beginning-of-line)
1013           (insert "Original-")))
1014       (forward-line 1)
1015       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
1016     (run-hooks 'nnmail-prepare-incoming-header-hook)
1017     ;; Allow the backend to save the article.
1018     (widen)
1019     (save-excursion
1020       (goto-char (point-min))
1021       (nnmail-check-duplication message-id func artnum-func))
1022     1))
1023
1024 (defun nnmail-split-incoming (incoming func &optional exit-func
1025                                        group artnum-func)
1026   "Go through the entire INCOMING file and pick out each individual mail.
1027 FUNC will be called with the buffer narrowed to each mail."
1028   (let ( ;; If this is a group-specific split, we bind the split
1029         ;; methods to just this group.
1030         (nnmail-split-methods (if (and group
1031                                        (not nnmail-resplit-incoming))
1032                                   (list (list group ""))
1033                                 nnmail-split-methods)))
1034     (save-excursion
1035       ;; Insert the incoming file.
1036       (set-buffer (get-buffer-create nnmail-article-buffer))
1037       (erase-buffer)
1038       (let ((coding-system-for-read nnmail-incoming-coding-system))
1039         (mm-insert-file-contents incoming))
1040       (prog1
1041           (if (zerop (buffer-size))
1042               0
1043             (goto-char (point-min))
1044             (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
1045             ;; Handle both babyl, MMDF and unix mail formats, since
1046             ;; movemail will use the former when fetching from a
1047             ;; mailbox, the latter when fetching from a file.
1048             (cond ((or (looking-at "\^L")
1049                        (looking-at "BABYL OPTIONS:"))
1050                    (nnmail-process-babyl-mail-format func artnum-func))
1051                   ((looking-at "\^A\^A\^A\^A")
1052                    (nnmail-process-mmdf-mail-format func artnum-func))
1053                   ((looking-at "Return-Path:")
1054                    (nnmail-process-maildir-mail-format func artnum-func))
1055                   (t
1056                    (nnmail-process-unix-mail-format func artnum-func))))
1057         (when exit-func
1058           (funcall exit-func))
1059         (kill-buffer (current-buffer))))))
1060
1061 (defun nnmail-article-group (func &optional trace)
1062   "Look at the headers and return an alist of groups that match.
1063 FUNC will be called with the group name to determine the article number."
1064   (let ((methods (or nnmail-split-methods '(("bogus" ""))))
1065         (obuf (current-buffer))
1066         group-art method grp)
1067     (if (and (sequencep methods)
1068              (= (length methods) 1))
1069         ;; If there is only just one group to put everything in, we
1070         ;; just return a list with just this one method in.
1071         (setq group-art
1072               (list (cons (caar methods) (funcall func (caar methods)))))
1073       ;; We do actual comparison.
1074       (save-excursion
1075         ;; Copy the article into the work buffer.
1076         (set-buffer nntp-server-buffer)
1077         (erase-buffer)
1078         (insert-buffer-substring obuf)
1079         ;; Narrow to headers.
1080         (narrow-to-region
1081          (goto-char (point-min))
1082          (if (search-forward "\n\n" nil t)
1083              (point)
1084            (point-max)))
1085         (goto-char (point-min))
1086         ;; Decode MIME headers and charsets.
1087         (when nnmail-mail-splitting-decodes
1088           (let ((mail-parse-charset nnmail-mail-splitting-charset))
1089             (mail-decode-encoded-word-region (point-min) (point-max))))
1090         ;; Fold continuation lines.
1091         (goto-char (point-min))
1092         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1093           (replace-match " " t t))
1094         ;; Nuke pathologically long headers.  Since Gnus applies
1095         ;; pathologically complex regexps to the buffer, lines
1096         ;; that are looong will take longer than the Universe's
1097         ;; existence to process.
1098         (goto-char (point-min))
1099         (while (not (eobp))
1100           (unless (< (move-to-column nnmail-split-header-length-limit)
1101                      nnmail-split-header-length-limit)
1102             (delete-region (point) (gnus-point-at-eol)))
1103           (forward-line 1))
1104         ;; Allow washing.
1105         (goto-char (point-min))
1106         (run-hooks 'nnmail-split-hook)
1107         (when (setq nnmail-split-tracing trace)
1108           (setq nnmail-split-trace nil))
1109         (if (and (symbolp nnmail-split-methods)
1110                  (fboundp nnmail-split-methods))
1111             (let ((split
1112                    (condition-case nil
1113                        ;; `nnmail-split-methods' is a function, so we
1114                        ;; just call this function here and use the
1115                        ;; result.
1116                        (or (funcall nnmail-split-methods)
1117                            '("bogus"))
1118                      (error
1119                       (nnheader-message
1120                        5 "Error in `nnmail-split-methods'; using `bogus' mail group")
1121                       (sit-for 1)
1122                       '("bogus")))))
1123               (setq split (gnus-remove-duplicates split))
1124               ;; The article may be "cross-posted" to `junk'.  What
1125               ;; to do?  Just remove the `junk' spec.  Don't really
1126               ;; see anything else to do...
1127               (let (elem)
1128                 (while (setq elem (car (memq 'junk split)))
1129                   (setq split (delq elem split))))
1130               (when split
1131                 (setq group-art
1132                       (mapcar
1133                        (lambda (group) (cons group (funcall func group)))
1134                        split))))
1135           ;; Go through the split methods to find a match.
1136           (while (and methods
1137                       (or nnmail-crosspost
1138                           (not group-art)))
1139             (goto-char (point-max))
1140             (setq method (pop methods)
1141                   grp (car method))
1142             (if (or methods
1143                     (not (equal "" (nth 1 method))))
1144                 (when (and
1145                        (ignore-errors
1146                          (if (stringp (nth 1 method))
1147                              (let ((expand (string-match "\\\\[0-9&]" grp))
1148                                    (pos (re-search-backward (cadr method)
1149                                                             nil t)))
1150                                (and expand
1151                                     (setq grp (nnmail-expand-newtext grp)))
1152                                pos)
1153                            ;; Function to say whether this is a match.
1154                            (funcall (nth 1 method) grp)))
1155                        ;; Don't enter the article into the same
1156                        ;; group twice.
1157                        (not (assoc grp group-art)))
1158                   (push (cons grp (funcall func grp))
1159                         group-art))
1160               ;; This is the final group, which is used as a
1161               ;; catch-all.
1162               (unless group-art
1163                 (setq group-art
1164                       (list (cons (car method)
1165                                   (funcall func (car method))))))))
1166           ;; Fall back on "bogus" if all else fails.
1167           (unless group-art
1168             (setq group-art (list (cons "bogus" (funcall func "bogus"))))))
1169         ;; Produce a trace if non-empty.
1170         (when (and trace nnmail-split-trace)
1171           (let ((restore (current-buffer)))
1172             (nnheader-set-temp-buffer "*Split Trace*")
1173             (gnus-add-buffer)
1174             (dolist (trace (nreverse nnmail-split-trace))
1175               (prin1 trace (current-buffer))
1176               (insert "\n"))
1177             (goto-char (point-min))
1178             (gnus-configure-windows 'split-trace)
1179             (set-buffer restore)))
1180         (widen)
1181         ;; See whether the split methods returned `junk'.
1182         (if (equal group-art '(junk))
1183             nil
1184           ;; The article may be "cross-posted" to `junk'.  What
1185           ;; to do?  Just remove the `junk' spec.  Don't really
1186           ;; see anything else to do...
1187           (let (elem)
1188             (while (setq elem (car (memq 'junk group-art)))
1189               (setq group-art (delq elem group-art)))
1190             (nreverse group-art)))))))
1191
1192 (defun nnmail-insert-lines ()
1193   "Insert how many lines there are in the body of the mail.
1194 Return the number of characters in the body."
1195   (let (lines chars)
1196     (save-excursion
1197       (goto-char (point-min))
1198       (unless (search-forward "\n\n" nil t)
1199         (goto-char (point-max))
1200         (insert "\n"))
1201       (setq chars (- (point-max) (point)))
1202       (setq lines (count-lines (point) (point-max)))
1203       (forward-char -1)
1204       (save-excursion
1205         (when (re-search-backward "^Lines: " nil t)
1206           (delete-region (point) (progn (forward-line 1) (point)))))
1207       (beginning-of-line)
1208       (insert (format "Lines: %d\n" (max lines 0)))
1209       chars)))
1210
1211 (defun nnmail-insert-xref (group-alist)
1212   "Insert an Xref line based on the (group . article) alist."
1213   (save-excursion
1214     (goto-char (point-min))
1215     (unless (search-forward "\n\n" nil t)
1216       (goto-char (point-max))
1217       (insert "\n"))
1218     (forward-char -1)
1219     (when (re-search-backward "^Xref: " nil t)
1220       (delete-region (match-beginning 0)
1221                      (progn (forward-line 1) (point))))
1222     (insert (format "Xref: %s" (system-name)))
1223     (while group-alist
1224       (insert (format " %s:%d"
1225                       (mm-encode-coding-string
1226                        (caar group-alist)
1227                        nnmail-pathname-coding-system)
1228                       (cdar group-alist)))
1229       (setq group-alist (cdr group-alist)))
1230     (insert "\n")))
1231
1232 ;;; Message washing functions
1233
1234 (defun nnmail-remove-leading-whitespace ()
1235   "Remove excessive whitespace from all headers."
1236   (goto-char (point-min))
1237   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1238     (replace-match "\\1" t)))
1239
1240 (defun nnmail-remove-list-identifiers ()
1241   "Remove list identifiers from Subject headers."
1242   (let ((regexp
1243          (if (consp nnmail-list-identifiers)
1244              (mapconcat 'identity nnmail-list-identifiers " *\\|")
1245            nnmail-list-identifiers)))
1246     (when regexp
1247       (goto-char (point-min))
1248       (while (re-search-forward
1249               (concat "^Subject: +\\(R[Ee]: +\\)*\\(" regexp " *\\)")
1250               nil t)
1251         (delete-region (match-beginning 2) (match-end 0))
1252         (beginning-of-line))
1253       (when (re-search-forward "^Subject: +\\(\\(R[Ee]: +\\)+\\)R[Ee]: +"
1254                                nil t)
1255         (delete-region (match-beginning 1) (match-end 1))
1256         (beginning-of-line)))))
1257
1258 (defun nnmail-remove-tabs ()
1259   "Translate TAB characters into SPACE characters."
1260   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1261
1262 (defun nnmail-fix-eudora-headers ()
1263   "Eudora has a broken References line, but an OK In-Reply-To."
1264   (goto-char (point-min))
1265   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1266     (goto-char (point-min))
1267     (when (re-search-forward "^References:" nil t)
1268       (beginning-of-line)
1269       (insert "X-Gnus-Broken-Eudora-"))
1270     (goto-char (point-min))
1271     (when (re-search-forward "^\\(In-Reply-To:[^\n]+\\)\n[ \t]+" nil t)
1272       (replace-match "\\1" t))))
1273
1274 (custom-add-option 'nnmail-prepare-incoming-header-hook
1275                    'nnmail-fix-eudora-headers)
1276
1277 ;;; Utility functions
1278
1279 (defun nnmail-do-request-post (accept-func &optional server)
1280   "Utility function to directly post a message to an nnmail-derived group.
1281 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
1282 to actually put the message in the right group."
1283   (let ((success t))
1284     (dolist (mbx (message-unquote-tokens
1285                   (message-tokenize-header
1286                    (message-fetch-field "Newsgroups") ", ")) success)
1287       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1288         (or (gnus-active to-newsgroup)
1289             (gnus-activate-group to-newsgroup)
1290             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1291                                        to-newsgroup))
1292                 (or (and (gnus-request-create-group
1293                           to-newsgroup gnus-command-method)
1294                          (gnus-activate-group to-newsgroup nil nil
1295                                               gnus-command-method))
1296                     (error "Couldn't create group %s" to-newsgroup)))
1297             (error "No such group: %s" to-newsgroup))
1298         (unless (funcall accept-func mbx (nth 1 gnus-command-method))
1299           (setq success nil))))))
1300
1301 (defun nnmail-split-fancy ()
1302   "Fancy splitting method.
1303 See the documentation for the variable `nnmail-split-fancy' for details."
1304   (let ((syntab (syntax-table)))
1305     (unwind-protect
1306         (progn
1307           (set-syntax-table nnmail-split-fancy-syntax-table)
1308           (nnmail-split-it nnmail-split-fancy))
1309       (set-syntax-table syntab))))
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\).
1370                 ;; So, start-of-value is the point just before the
1371                 ;; beginning of the value, whereas after-header-name
1372                 ;; is 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) (gnus-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 ((coding-system-for-write nnmail-file-coding-system)
1882         (file-name-coding-system nnmail-pathname-coding-system))
1883     (write-region 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-within-headers-p ()
1982   "Check to see if point is within the headers of a unix mail message.
1983 Doesn't change point."
1984   (let ((pos (point)))
1985     (save-excursion
1986       (and (nnmail-search-unix-mail-delim-backward)
1987            (not (search-forward "\n\n" pos t))))))
1988
1989 (run-hooks 'nnmail-load-hook)
1990
1991 (provide 'nnmail)
1992
1993 ;;; nnmail.el ends here