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