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