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