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