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