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