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