Synch to No Gnus 200401122258.
[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) (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) (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   (with-syntax-table nnmail-split-fancy-syntax-table
1314     (nnmail-split-it nnmail-split-fancy)))
1315
1316 (defvar nnmail-split-cache nil)
1317 ;; Alist of split expressions their equivalent regexps.
1318
1319 (defun nnmail-split-it (split)
1320   ;; Return a list of groups matching SPLIT.
1321   (let (cached-pair)
1322     (cond
1323      ;; nil split
1324      ((null split)
1325       nil)
1326
1327      ;; A group name.  Do the \& and \N subs into the string.
1328      ((stringp split)
1329       (when nnmail-split-tracing
1330         (push split nnmail-split-trace))
1331       (list (nnmail-expand-newtext split)))
1332
1333      ;; Junk the message.
1334      ((eq split 'junk)
1335       (when nnmail-split-tracing
1336         (push "junk" nnmail-split-trace))
1337       (list 'junk))
1338
1339      ;; Builtin & operation.
1340      ((eq (car split) '&)
1341       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1342
1343      ;; Builtin | operation.
1344      ((eq (car split) '|)
1345       (let (done)
1346         (while (and (not done) (cdr split))
1347           (setq split (cdr split)
1348                 done (nnmail-split-it (car split))))
1349         done))
1350
1351      ;; Builtin : operation.
1352      ((eq (car split) ':)
1353       (when nnmail-split-tracing
1354         (push split nnmail-split-trace))
1355       (nnmail-split-it (save-excursion (eval (cdr split)))))
1356
1357      ;; Builtin ! operation.
1358      ((eq (car split) '!)
1359       (funcall (cadr split) (nnmail-split-it (caddr split))))
1360
1361      ;; Check the cache for the regexp for this split.
1362      ((setq cached-pair (assq split nnmail-split-cache))
1363       (let (split-result
1364             (end-point (point-max))
1365             (value (nth 1 split)))
1366         (if (symbolp value)
1367             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1368         (while (and (goto-char end-point)
1369                     (re-search-backward (cdr cached-pair) nil t))
1370           (when nnmail-split-tracing
1371             (push split nnmail-split-trace))
1372           (let ((split-rest (cddr split))
1373                 (end (match-end 0))
1374                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).  So,
1375                 ;; start-of-value is the the point just before the
1376                 ;; beginning of the value, whereas after-header-name is
1377                 ;; the point just after the field name.
1378                 (start-of-value (match-end 1))
1379                 (after-header-name (match-end 2)))
1380             ;; Start the next search just before the beginning of the
1381             ;; VALUE match.
1382             (setq end-point (1- start-of-value))
1383             ;; Handle - RESTRICTs
1384             (while (eq (car split-rest) '-)
1385               ;; RESTRICT must start after-header-name and
1386               ;; end after start-of-value, so that, for
1387               ;; (any "foo" - "x-foo" "foo.list")
1388               ;; we do not exclude foo.list just because
1389               ;; the header is: ``To: x-foo, foo''
1390               (goto-char end)
1391               (if (and (re-search-backward (cadr split-rest)
1392                                            after-header-name t)
1393                        (> (match-end 0) start-of-value))
1394                   (setq split-rest nil)
1395                 (setq split-rest (cddr split-rest))))
1396             (when split-rest
1397               (goto-char end)
1398               (let ((value (nth 1 split)))
1399                 (if (symbolp value)
1400                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1401                 ;; Someone might want to do a \N sub on this match, so get the
1402                 ;; correct match positions.
1403                 (re-search-backward value start-of-value))
1404               (dolist (sp (nnmail-split-it (car split-rest)))
1405                 (unless (member sp split-result)
1406                   (push sp split-result))))))
1407         split-result))
1408
1409      ;; Not in cache, compute a regexp for the field/value pair.
1410      (t
1411       (let* ((field (nth 0 split))
1412              (value (nth 1 split))
1413              partial-front
1414              partial-rear
1415              regexp)
1416         (if (symbolp value)
1417             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1418         (if (and (>= (length value) 2)
1419                  (string= ".*" (substring value 0 2)))
1420             (setq value (substring value 2)
1421                   partial-front ""))
1422         ;; Same trick for the rear of the regexp
1423         (if (and (>= (length value) 2)
1424                  (string= ".*" (substring value -2)))
1425             (setq value (substring value 0 -2)
1426                   partial-rear ""))
1427         (when nnmail-split-fancy-match-partial-words
1428           (setq partial-front ""
1429                 partial-rear ""))
1430         (setq regexp (concat "^\\(\\("
1431                              (if (symbolp field)
1432                                  (cdr (assq field nnmail-split-abbrev-alist))
1433                                field)
1434                              "\\):.*\\)"
1435                              (or partial-front "\\<")
1436                              "\\("
1437                              value
1438                              "\\)"
1439                              (or partial-rear "\\>")))
1440         (push (cons split regexp) nnmail-split-cache)
1441         ;; Now that it's in the cache, just call nnmail-split-it again
1442         ;; on the same split, which will find it immediately in the cache.
1443         (nnmail-split-it split))))))
1444
1445 (defun nnmail-expand-newtext (newtext)
1446   (let ((len (length newtext))
1447         (pos 0)
1448         c expanded beg N did-expand)
1449     (while (< pos len)
1450       (setq beg pos)
1451       (while (and (< pos len)
1452                   (not (= (aref newtext pos) ?\\)))
1453         (setq pos (1+ pos)))
1454       (unless (= beg pos)
1455         (push (substring newtext beg pos) expanded))
1456       (when (< pos len)
1457         ;; We hit a \; expand it.
1458         (setq did-expand t
1459               pos (1+ pos)
1460               c (aref newtext pos))
1461         (if (not (or (= c ?\&)
1462                      (and (>= c ?1)
1463                           (<= c ?9))))
1464             ;; \ followed by some character we don't expand.
1465             (push (char-to-string c) expanded)
1466           ;; \& or \N
1467           (if (= c ?\&)
1468               (setq N 0)
1469             (setq N (- c ?0)))
1470           (when (match-beginning N)
1471             (push (buffer-substring (match-beginning N) (match-end N))
1472                   expanded))))
1473       (setq pos (1+ pos)))
1474     (if did-expand
1475         (apply 'concat (nreverse expanded))
1476       newtext)))
1477
1478 ;; Activate a backend only if it isn't already activated.
1479 ;; If FORCE, re-read the active file even if the backend is
1480 ;; already activated.
1481 (defun nnmail-activate (backend &optional force)
1482   (nnheader-init-server-buffer)
1483   (let (file timestamp file-time)
1484     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1485             force
1486             (and (setq file (ignore-errors
1487                               (symbol-value (intern (format "%s-active-file"
1488                                                             backend)))))
1489                  (setq file-time (nth 5 (file-attributes file)))
1490                  (or (not
1491                       (setq timestamp
1492                             (condition-case ()
1493                                 (symbol-value (intern
1494                                                (format "%s-active-timestamp"
1495                                                        backend)))
1496                               (error 'none))))
1497                      (not (consp timestamp))
1498                      (equal timestamp '(0 0))
1499                      (> (nth 0 file-time) (nth 0 timestamp))
1500                      (and (= (nth 0 file-time) (nth 0 timestamp))
1501                           (> (nth 1 file-time) (nth 1 timestamp))))))
1502         (save-excursion
1503           (or (eq timestamp 'none)
1504               (set (intern (format "%s-active-timestamp" backend))
1505                    file-time))
1506           (funcall (intern (format "%s-request-list" backend)))))
1507     t))
1508
1509 (defun nnmail-message-id ()
1510   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1511
1512 ;;;
1513 ;;; nnmail duplicate handling
1514 ;;;
1515
1516 (defvar nnmail-cache-buffer nil)
1517
1518 (defun nnmail-cache-open ()
1519   (if (or (not nnmail-treat-duplicates)
1520           (and nnmail-cache-buffer
1521                (buffer-name nnmail-cache-buffer)))
1522       ()                                ; The buffer is open.
1523     (save-excursion
1524       (set-buffer
1525        (setq nnmail-cache-buffer
1526              (get-buffer-create " *nnmail message-id cache*")))
1527       (gnus-add-buffer)
1528       (when (file-exists-p nnmail-message-id-cache-file)
1529         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1530       (set-buffer-modified-p nil)
1531       (current-buffer))))
1532
1533 (defun nnmail-cache-close ()
1534   (when (and nnmail-cache-buffer
1535              nnmail-treat-duplicates
1536              (buffer-name nnmail-cache-buffer)
1537              (buffer-modified-p nnmail-cache-buffer))
1538     (save-excursion
1539       (set-buffer nnmail-cache-buffer)
1540       ;; Weed out the excess number of Message-IDs.
1541       (goto-char (point-max))
1542       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1543         (progn
1544           (beginning-of-line)
1545           (delete-region (point-min) (point))))
1546       ;; Save the buffer.
1547       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1548           (make-directory (file-name-directory nnmail-message-id-cache-file)
1549                           t))
1550       (nnmail-write-region (point-min) (point-max)
1551                            nnmail-message-id-cache-file nil 'silent)
1552       (set-buffer-modified-p nil)
1553       (setq nnmail-cache-buffer nil)
1554       (gnus-kill-buffer (current-buffer)))))
1555
1556 ;; Compiler directives.
1557 (defvar group)
1558 (defvar group-art-list)
1559 (defvar group-art)
1560 (defun nnmail-cache-insert (id grp &optional subject sender)
1561   (when (stringp id)
1562     ;; this will handle cases like `B r' where the group is nil
1563     (let ((grp (or grp gnus-newsgroup-name "UNKNOWN")))
1564       (run-hook-with-args 'nnmail-spool-hook 
1565                           id grp subject sender))
1566     (when nnmail-treat-duplicates
1567       ;; Store some information about the group this message is written
1568       ;; to.  This is passed in as the grp argument -- all locations this
1569       ;; has been called from have been checked and the group is available.
1570       ;; The only ambiguous case is nnmail-check-duplication which will only
1571       ;; pass the first (of possibly >1) group which matches. -Josh
1572       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1573         (nnmail-cache-open))
1574       (save-excursion
1575         (set-buffer nnmail-cache-buffer)
1576         (goto-char (point-max))
1577         (if (and grp (not (string= "" grp))
1578                  (gnus-methods-equal-p gnus-command-method
1579                                        (nnmail-cache-primary-mail-backend)))
1580             (let ((regexp (if (consp nnmail-cache-ignore-groups)
1581                               (mapconcat 'identity nnmail-cache-ignore-groups
1582                                          "\\|")
1583                             nnmail-cache-ignore-groups)))
1584               (unless (and regexp (string-match regexp grp))
1585                 (insert id "\t" grp "\n")))
1586           (insert id "\n"))))))
1587   
1588 (defun nnmail-cache-primary-mail-backend ()
1589   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1590         (be nil)
1591         (res nil)
1592         (get-new-mail nil))
1593     (while (and (null res) be-list)
1594       (setq be (car be-list))
1595       (setq be-list (cdr be-list))
1596       (when (and (gnus-method-option-p be 'respool)
1597                  (setq get-new-mail
1598                        (intern (format "%s-get-new-mail" (car be))))
1599                  (boundp get-new-mail)
1600                  (symbol-value get-new-mail))
1601         (setq res be)))
1602     res))
1603
1604 ;; Fetch the group name corresponding to the message id stored in the
1605 ;; cache.
1606 (defun nnmail-cache-fetch-group (id)
1607   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1608     (save-excursion
1609       (set-buffer nnmail-cache-buffer)
1610       (goto-char (point-max))
1611       (when (search-backward id nil t)
1612         (beginning-of-line)
1613         (skip-chars-forward "^\n\r\t")
1614         (unless (looking-at "[\r\n]")
1615           (forward-char 1)
1616           (buffer-substring (point) (point-at-eol)))))))
1617
1618 ;; Function for nnmail-split-fancy: look up all references in the
1619 ;; cache and if a match is found, return that group.
1620 (defun nnmail-split-fancy-with-parent ()
1621   "Split this message into the same group as its parent.
1622 This function can be used as an entry in `nnmail-split-fancy', for
1623 example like this: (: nnmail-split-fancy-with-parent)
1624 For a message to be split, it looks for the parent message in the
1625 References or In-Reply-To header and then looks in the message id
1626 cache file (given by the variable `nnmail-message-id-cache-file') to
1627 see which group that message was put in.  This group is returned.
1628
1629 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1630   (let* ((refstr (or (message-fetch-field "references")
1631                      (message-fetch-field "in-reply-to")))
1632          (references nil)
1633          (res nil)
1634          (regexp (if (consp nnmail-split-fancy-with-parent-ignore-groups)
1635                      (mapconcat
1636                       (lambda (x) (format "\\(%s\\)" x))
1637                       nnmail-split-fancy-with-parent-ignore-groups
1638                       "\\|")
1639                    nnmail-split-fancy-with-parent-ignore-groups)))
1640     (when refstr
1641       (setq references (nreverse (gnus-split-references refstr)))
1642       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1643         (nnmail-cache-open))
1644       (mapcar (lambda (x)
1645                 (setq res (or (nnmail-cache-fetch-group x) res))
1646                 (when (or (member res '("delayed" "drafts" "queue"))
1647                           (and regexp res (string-match regexp res)))
1648                   (setq res nil)))
1649               references)
1650       res)))
1651
1652 (defun nnmail-cache-id-exists-p (id)
1653   (when nnmail-treat-duplicates
1654     (save-excursion
1655       (set-buffer nnmail-cache-buffer)
1656       (goto-char (point-max))
1657       (search-backward id nil t))))
1658
1659 (defun nnmail-fetch-field (header)
1660   (save-excursion
1661     (save-restriction
1662       (message-narrow-to-head)
1663       (message-fetch-field header))))
1664
1665 (defun nnmail-check-duplication (message-id func artnum-func)
1666   (run-hooks 'nnmail-prepare-incoming-message-hook)
1667   ;; If this is a duplicate message, then we do not save it.
1668   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1669          (case-fold-search t)
1670          (action (when duplication
1671                    (cond
1672                     ((memq nnmail-treat-duplicates '(warn delete))
1673                      nnmail-treat-duplicates)
1674                     ((functionp nnmail-treat-duplicates)
1675                      (funcall nnmail-treat-duplicates message-id))
1676                     (t
1677                      nnmail-treat-duplicates))))
1678          group-art)
1679     ;; We insert a line that says what the mail source is.
1680     (let ((case-fold-search t))
1681       (goto-char (point-min))
1682       (re-search-forward "^message-id[ \t]*:" nil t)
1683       (beginning-of-line)
1684       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1685
1686     ;; Let the backend save the article (or not).
1687     (cond
1688      ((not duplication)
1689       (funcall func (setq group-art
1690                           (nreverse (nnmail-article-group artnum-func))))
1691       (nnmail-cache-insert message-id (caar group-art)))
1692      ((eq action 'delete)
1693       (setq group-art nil))
1694      ((eq action 'warn)
1695       ;; We insert a warning.
1696       (let ((case-fold-search t))
1697         (goto-char (point-min))
1698         (re-search-forward "^message-id[ \t]*:" nil t)
1699         (beginning-of-line)
1700         (insert
1701          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1702         (funcall func (setq group-art
1703                             (nreverse (nnmail-article-group artnum-func))))))
1704      (t
1705       (funcall func (setq group-art
1706                           (nreverse (nnmail-article-group artnum-func))))))
1707     ;; Add the group-art list to the history list.
1708     (if group-art
1709         (push group-art nnmail-split-history)
1710       (delete-region (point-min) (point-max)))))
1711
1712 ;;; Get new mail.
1713
1714 (defvar nnmail-fetched-sources nil)
1715
1716 (defun nnmail-get-value (&rest args)
1717   (let ((sym (intern (apply 'format args))))
1718     (when (boundp sym)
1719       (symbol-value sym))))
1720
1721 (defun nnmail-get-new-mail (method exit-func temp
1722                                    &optional group spool-func)
1723   "Read new incoming mail."
1724   (let* ((sources (or mail-sources
1725                       (if (listp nnmail-spool-file) nnmail-spool-file
1726                         (list nnmail-spool-file))))
1727          fetching-sources
1728          (group-in group)
1729          (i 0)
1730          (new 0)
1731          (total 0)
1732          incoming incomings source)
1733     (when (and (nnmail-get-value "%s-get-new-mail" method)
1734                sources)
1735       (while (setq source (pop sources))
1736         ;; Be compatible with old values.
1737         (cond
1738          ((stringp source)
1739           (setq source
1740                 (cond
1741                  ((string-match "^po:" source)
1742                   (list 'pop :user (substring source (match-end 0))))
1743                  ((file-directory-p source)
1744                   (list 'directory :path source))
1745                  (t
1746                   (list 'file :path source)))))
1747          ((eq source 'procmail)
1748           (message "Invalid value for nnmail-spool-file: `procmail'")
1749           nil))
1750         ;; Hack to only fetch the contents of a single group's spool file.
1751         (when (and (eq (car source) 'directory)
1752                    (null nnmail-scan-directory-mail-source-once)
1753                    group)
1754           (mail-source-bind (directory source)
1755             (setq source (append source
1756                                  (list
1757                                   :predicate
1758                                   (gnus-byte-compile
1759                                    `(lambda (file)
1760                                       (string-equal
1761                                        ,(concat group suffix)
1762                                        (file-name-nondirectory file)))))))))
1763         (when nnmail-fetched-sources
1764           (if (member source nnmail-fetched-sources)
1765               (setq source nil)
1766             (push source nnmail-fetched-sources)
1767             (push source fetching-sources)))))
1768     (when fetching-sources
1769       ;; We first activate all the groups.
1770       (nnmail-activate method)
1771       ;; Allow the user to hook.
1772       (run-hooks 'nnmail-pre-get-new-mail-hook)
1773       ;; Open the message-id cache.
1774       (nnmail-cache-open)
1775       ;; The we go through all the existing mail source specification
1776       ;; and fetch the mail from each.
1777       (while (setq source (pop fetching-sources))
1778         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1779                           method (car source))
1780         (when (setq new
1781                     (mail-source-fetch
1782                      source
1783                      (gnus-byte-compile
1784                       `(lambda (file orig-file)
1785                          (nnmail-split-incoming
1786                           file ',(intern (format "%s-save-mail" method))
1787                           ',spool-func
1788                           (if (equal file orig-file)
1789                               nil
1790                             (nnmail-get-split-group orig-file ',source))
1791                           ',(intern (format "%s-active-number" method)))))))
1792           (incf total new)
1793           (incf i)))
1794       ;; If we did indeed read any incoming spools, we save all info.
1795       (if (zerop total)
1796           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1797                             method (car source))
1798         (nnmail-save-active
1799          (nnmail-get-value "%s-group-alist" method)
1800          (nnmail-get-value "%s-active-file" method))
1801         (when exit-func
1802           (funcall exit-func))
1803         (run-hooks 'nnmail-read-incoming-hook)
1804         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1805                           total))
1806       ;; Close the message-id cache.
1807       (nnmail-cache-close)
1808       ;; Allow the user to hook.
1809       (run-hooks 'nnmail-post-get-new-mail-hook))))
1810
1811 (defun nnmail-expired-article-p (group time force &optional inhibit)
1812   "Say whether an article that is TIME old in GROUP should be expired."
1813   (if force
1814       t
1815     (let ((days (or (and nnmail-expiry-wait-function
1816                          (funcall nnmail-expiry-wait-function group))
1817                     nnmail-expiry-wait)))
1818       (cond ((or (eq days 'never)
1819                  (and (not force)
1820                       inhibit))
1821              ;; This isn't an expirable group.
1822              nil)
1823             ((eq days 'immediate)
1824              ;; We expire all articles on sight.
1825              t)
1826             ((equal time '(0 0))
1827              ;; This is an ange-ftp group, and we don't have any dates.
1828              nil)
1829             ((numberp days)
1830              (setq days (days-to-time days))
1831              ;; Compare the time with the current time.
1832              (ignore-errors (time-less-p days (time-since time))))))))
1833
1834 (defun nnmail-expiry-target-group (target group)
1835   ;; Do not invoke this from nntp-server-buffer!  At least nnfolder clears
1836   ;; that buffer if the nnfolder group isn't selected.
1837   (let (nnmail-cache-accepted-message-ids)
1838     ;; Don't enter Message-IDs into cache.
1839     ;; Let users hack it in TARGET function.
1840     (when (functionp target)
1841       (setq target (funcall target group)))
1842     (unless (eq target 'delete)
1843       (when (or (gnus-request-group target)
1844                 (gnus-request-create-group target))
1845         (let ((group-art (gnus-request-accept-article target nil nil t)))
1846           (when (consp group-art)
1847             (gnus-group-mark-article-read target (cdr group-art))))))))
1848
1849 (defun nnmail-fancy-expiry-target (group)
1850   "Returns a target expiry group determined by `nnmail-fancy-expiry-targets'."
1851   (let* (header
1852          (case-fold-search nil)
1853          (from (or (message-fetch-field "from") ""))
1854          (to (or (message-fetch-field "to") ""))
1855          (date (date-to-time
1856                 (or (message-fetch-field "date") (current-time-string))))
1857          (target 'delete))
1858     (dolist (regexp-target-pair (reverse nnmail-fancy-expiry-targets) target)
1859       (setq header (car regexp-target-pair))
1860       (cond
1861        ;; If the header is to-from then match against the
1862        ;; To or From header
1863        ((and (equal header 'to-from)
1864              (or (string-match (cadr regexp-target-pair) from)
1865                  (and (string-match message-dont-reply-to-names from)
1866                       (string-match (cadr regexp-target-pair) to))))
1867         (setq target (format-time-string (caddr regexp-target-pair) date)))
1868        ((and (not (equal header 'to-from))
1869              (string-match (cadr regexp-target-pair)
1870                            (or
1871                             (message-fetch-field header)
1872                             "")))
1873         (setq target
1874               (format-time-string (caddr regexp-target-pair) date)))))))
1875
1876 (defun nnmail-check-syntax ()
1877   "Check (and modify) the syntax of the message in the current buffer."
1878   (save-restriction
1879     (message-narrow-to-head)
1880     (let ((case-fold-search t))
1881       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1882         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1883
1884 (defun nnmail-write-region (start end filename &optional append visit lockname)
1885   "Do a `write-region', and then set the file modes."
1886   (let ((file-name-coding-system nnmail-pathname-coding-system))
1887     (write-region-as-coding-system
1888      nnmail-file-coding-system start end filename append visit lockname)
1889     (set-file-modes filename nnmail-default-file-modes)))
1890
1891 ;;;
1892 ;;; Status functions
1893 ;;;
1894
1895 (defun nnmail-replace-status (name value)
1896   "Make status NAME and VALUE part of the current status line."
1897   (save-restriction
1898     (message-narrow-to-head)
1899     (let ((status (nnmail-decode-status)))
1900       (setq status (delq (member name status) status))
1901       (when value
1902         (push (cons name value) status))
1903       (message-remove-header "status")
1904       (goto-char (point-max))
1905       (insert "Status: " (nnmail-encode-status status) "\n"))))
1906
1907 (defun nnmail-decode-status ()
1908   "Return a status-value alist from STATUS."
1909   (goto-char (point-min))
1910   (when (re-search-forward "^Status: " nil t)
1911     (let (name value status)
1912       (save-restriction
1913         ;; Narrow to the status.
1914         (narrow-to-region
1915          (point)
1916          (if (re-search-forward "^[^ \t]" nil t)
1917              (1- (point))
1918            (point-max)))
1919         ;; Go through all elements and add them to the list.
1920         (goto-char (point-min))
1921         (while (re-search-forward "[^ \t=]+" nil t)
1922           (setq name (match-string 0))
1923           (if (not (eq (char-after) ?=))
1924               ;; Implied "yes".
1925               (setq value "yes")
1926             (forward-char 1)
1927             (if (not (eq (char-after) ?\"))
1928                 (if (not (looking-at "[^ \t]"))
1929                     ;; Implied "no".
1930                     (setq value "no")
1931                   ;; Unquoted value.
1932                   (setq value (match-string 0))
1933                   (goto-char (match-end 0)))
1934               ;; Quoted value.
1935               (setq value (read (current-buffer)))))
1936           (push (cons name value) status)))
1937       status)))
1938
1939 (defun nnmail-encode-status (status)
1940   "Return a status string from STATUS."
1941   (mapconcat
1942    (lambda (elem)
1943      (concat
1944       (car elem) "="
1945       (if (string-match "[ \t]" (cdr elem))
1946           (prin1-to-string (cdr elem))
1947         (cdr elem))))
1948    status " "))
1949
1950 (defun nnmail-split-history ()
1951   "Generate an overview of where the last mail split put articles."
1952   (interactive)
1953   (unless nnmail-split-history
1954     (error "No current split history"))
1955   (with-output-to-temp-buffer "*nnmail split history*"
1956     (with-current-buffer standard-output
1957       (fundamental-mode))               ; for Emacs 20.4+
1958     (let ((history nnmail-split-history)
1959           elem)
1960       (while (setq elem (pop history))
1961         (princ (mapconcat (lambda (ga)
1962                             (concat (car ga) ":" (int-to-string (cdr ga))))
1963                           elem
1964                           ", "))
1965         (princ "\n")))))
1966
1967 (defun nnmail-purge-split-history (group)
1968   "Remove all instances of GROUP from `nnmail-split-history'."
1969   (let ((history nnmail-split-history))
1970     (while history
1971       (setcar history (gnus-remove-if (lambda (e) (string= (car e) group))
1972                                       (car history)))
1973       (pop history))
1974     (setq nnmail-split-history (delq nil nnmail-split-history))))
1975
1976 (defun nnmail-new-mail-p (group)
1977   "Say whether GROUP has new mail."
1978   (let ((his nnmail-split-history)
1979         found)
1980     (while his
1981       (when (assoc group (pop his))
1982         (setq found t
1983               his nil)))
1984     found))
1985
1986 (defun nnmail-new-mail-numbers (group)
1987   "Say how many articles has been incorporated to GROUP."
1988   (let ((his (apply 'append nnmail-split-history))
1989         numbers)
1990     (while his
1991       (when (string= group (caar his))
1992         (push (cdar his) numbers))
1993       (setq his (cdr his)))
1994     numbers))
1995
1996 (defun nnmail-within-headers-p ()
1997   "Check to see if point is within the headers of a unix mail message.
1998 Doesn't change point."
1999   (let ((pos (point)))
2000     (save-excursion
2001       (and (nnmail-search-unix-mail-delim-backward)
2002            (not (search-forward "\n\n" pos t))))))
2003
2004 (run-hooks 'nnmail-load-hook)
2005
2006 (provide 'nnmail)
2007
2008 ;;; nnmail.el ends here