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