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