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