(nnmail-split-fancy): Make it customizable with Emacs 20 as well.
[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 'custom)
35 (require 'gnus-util)
36 (require 'mail-source)
37 (require 'mm-util)
38
39 (eval-and-compile
40   (autoload 'gnus-add-buffer "gnus")
41   (autoload 'gnus-kill-buffer "gnus"))
42
43 (defgroup nnmail nil
44   "Reading mail with Gnus."
45   :group 'gnus)
46
47 (defgroup nnmail-retrieve nil
48   "Retrieving new mail."
49   :group 'nnmail)
50
51 (defgroup nnmail-prepare nil
52   "Preparing (or mangling) new mail after retrival."
53   :group 'nnmail)
54
55 (defgroup nnmail-duplicate nil
56   "Handling of duplicate mail messages."
57   :group 'nnmail)
58
59 (defgroup nnmail-split nil
60   "Organizing the incoming mail in folders."
61   :group 'nnmail)
62
63 (defgroup nnmail-files nil
64   "Mail files."
65   :group 'gnus-files
66   :group 'nnmail)
67
68 (defgroup nnmail-expire nil
69   "Expiring old mail."
70   :group 'nnmail)
71
72 (defgroup nnmail-procmail nil
73   "Interfacing with procmail and other mail agents."
74   :group 'nnmail)
75
76 (defgroup nnmail-various nil
77   "Various mail options."
78   :group 'nnmail)
79
80 (defcustom nnmail-split-methods '(("mail.misc" ""))
81   "*Incoming mail will be split according to this variable.
82
83 If you'd like, for instance, one mail group for mail from the
84 \"4ad-l\" mailing list, one group for junk mail and one for everything
85 else, you could do something like this:
86
87  (setq nnmail-split-methods
88        '((\"mail.4ad\" \"From:.*4ad\")
89          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
90          (\"mail.misc\" \"\")))
91
92 As you can see, this variable is a list of lists, where the first
93 element in each \"rule\" is the name of the group (which, by the way,
94 does not have to be called anything beginning with \"mail\",
95 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
96 nnmail will try to match on the header to find a fit.
97
98 The second element can also be a function.  In that case, it will be
99 called narrowed to the headers with the first element of the rule as
100 the argument.  It should return a non-nil value if it thinks that the
101 mail belongs in that group.
102
103 The last element should always have \"\" as the regexp.
104
105 This variable can also have a function as its value."
106   :group 'nnmail-split
107   :type '(choice (repeat :tag "Alist" (group (string :tag "Name")
108                                              (choice regexp function)))
109                  (function-item nnmail-split-fancy)
110                  (function :tag "Other")))
111
112 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
113 (defcustom nnmail-crosspost t
114   "If non-nil, do crossposting if several split methods match the mail.
115 If nil, the first match found will be used."
116   :group 'nnmail-split
117   :type 'boolean)
118
119 (defcustom nnmail-split-fancy-with-parent-ignore-groups nil
120   "Regexp that matches group names to be ignored when applying `nnmail-split-fancy-with-parent'.
121 This can also be a list of regexps."
122   :group 'nnmail-split
123   :type '(choice (const :tag "none" nil)
124                  (regexp :value ".*")
125                  (repeat :value (".*") regexp)))
126
127 (defcustom nnmail-cache-ignore-groups nil
128   "Regexp that matches group names to be ignored when inserting message ids into the cache (`nnmail-cache-insert').
129 This can also be a list of regexps."
130   :group 'nnmail-split
131   :type '(choice (const :tag "none" nil)
132                  (regexp :value ".*")
133                  (repeat :value (".*") regexp)))
134
135 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
136 (defcustom nnmail-keep-last-article nil
137   "If non-nil, nnmail will never delete/move a group's last article.
138 It can be marked expirable, so it will be deleted when it is no longer last.
139
140 You may need to set this variable if other programs are putting
141 new mail into folder numbers that Gnus has marked as expired."
142   :group 'nnmail-procmail
143   :group 'nnmail-various
144   :type 'boolean)
145
146 (defcustom nnmail-use-long-file-names nil
147   "If non-nil the mail backends will use long file and directory names.
148 If nil, groups like \"mail.misc\" will end up in directories like
149 \"mail/misc/\"."
150   :group 'nnmail-files
151   :type 'boolean)
152
153 (defcustom nnmail-default-file-modes 384
154   "Set the mode bits of all new mail files to this integer."
155   :group 'nnmail-files
156   :type 'integer)
157
158 (defcustom nnmail-expiry-wait 7
159   "*Expirable articles that are older than this will be expired.
160 This variable can either be a number (which will be interpreted as a
161 number of days) -- this doesn't have to be an integer.  This variable
162 can also be `immediate' and `never'."
163   :group 'nnmail-expire
164   :type '(choice (const immediate)
165                  (number :tag "days")
166                  (const never)))
167
168 (defcustom nnmail-expiry-wait-function nil
169   "Variable that holds function to specify how old articles should be before they are expired.
170 The function will be called with the name of the group that the expiry
171 is to be performed in, and it should return an integer that says how
172 many days an article can be stored before it is considered \"old\".
173 It can also return the values `never' and `immediate'.
174
175 Eg.:
176
177 \(setq nnmail-expiry-wait-function
178       (lambda (newsgroup)
179         (cond ((string-match \"private\" newsgroup) 31)
180               ((string-match \"junk\" newsgroup) 1)
181               ((string-match \"important\" newsgroup) 'never)
182               (t 7))))"
183   :group 'nnmail-expire
184   :type '(choice (const :tag "nnmail-expiry-wait" nil)
185                  (function :format "%v" nnmail-)))
186
187 (defcustom nnmail-expiry-target 'delete
188   "*Variable that says where expired messages should end up.
189 The default value is `delete' (which says to delete the messages),
190 but it can also be a string or a function.  If it is a string, expired
191 messages end up in that group.  If it is a function, the function is
192 called in a buffer narrowed to the message in question.  The function
193 receives one argument, the name of the group the message comes from.
194 The return value should be `delete' or a group name (a string)."
195   :version "21.1"
196   :group 'nnmail-expire
197   :type '(choice (const delete)
198                  (function :format "%v" nnmail-)
199                  string))
200
201 (defcustom nnmail-fancy-expiry-targets nil
202   "Determine expiry target based on articles using fancy techniques.
203
204 This is a list of (\"HEADER\" \"REGEXP\" \"TARGET\") entries.  If
205 `nnmail-expiry-target' is set to the function
206 `nnmail-fancy-expiry-target' and HEADER of the article matches REGEXP,
207 the message will be expired to a group determined by invoking
208 `format-time-string' with TARGET used as the format string and the
209 time extracted from the articles' Date header (if missing the current
210 time is used).
211
212 In the special cases that HEADER is the symbol `to-from', the regexp
213 will try to match against both the From and the To header.
214
215 Example:
216
217 \(setq nnmail-fancy-expiry-targets
218       '((to-from \"boss\" \"nnfolder:Work\")
219         (\"Subject\" \"IMPORTANT\" \"nnfolder:IMPORTANT.%Y.%b\")
220         (\"from\" \".*\" \"nnfolder:Archive-%Y\")))
221
222 In this case, articles containing the string \"boss\" in the To or the
223 From header will be expired to the group \"nnfolder:Work\";
224 articles containing the sting \"IMPORTANT\" in the Subject header will
225 be expired to the group \"nnfolder:IMPORTANT.YYYY.MMM\"; and
226 everything else will be expired to \"nnfolder:Archive-YYYY\"."
227   :group 'nnmail-expire
228   :type '(repeat (list (choice :tag "Match against"
229                                (string :tag "Header")
230                                (const to-from))
231                        regexp
232                        (string :tag "Target group format string"))))
233
234 (defcustom nnmail-cache-accepted-message-ids nil
235   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache.
236 If non-nil, also update the cache when copy or move articles."
237   :group 'nnmail
238   :type 'boolean)
239
240 (defcustom nnmail-spool-file '((file))
241   "*Where the mail backends will look for incoming mail.
242 This variable is a list of mail source specifiers.
243 This variable is obsolete; `mail-sources' should be used instead."
244   :group 'nnmail-files
245   :type 'sexp)
246
247 (defcustom nnmail-resplit-incoming nil
248   "*If non-nil, re-split incoming procmail sorted mail."
249   :group 'nnmail-procmail
250   :type 'boolean)
251
252 (defcustom nnmail-scan-directory-mail-source-once nil
253   "*If non-nil, scan all incoming procmail sorted mails once.
254 It scans low-level sorted spools even when not required."
255   :version "21.1"
256   :group 'nnmail-procmail
257   :type 'boolean)
258
259 (defcustom nnmail-delete-file-function 'delete-file
260   "Function called to delete files in some mail backends."
261   :group 'nnmail-files
262   :type 'function)
263
264 (defcustom nnmail-crosspost-link-function
265   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
266       'copy-file
267     'add-name-to-file)
268   "*Function called to create a copy of a file.
269 This is `add-name-to-file' by default, which means that crossposts
270 will use hard links.  If your file system doesn't allow hard
271 links, you could set this variable to `copy-file' instead."
272   :group 'nnmail-files
273   :type '(radio (function-item add-name-to-file)
274                 (function-item copy-file)
275                 (function :tag "Other")))
276
277 (defcustom nnmail-read-incoming-hook
278   (if (eq system-type 'windows-nt)
279       '(nnheader-ms-strip-cr)
280     nil)
281   "*Hook that will be run after the incoming mail has been transferred.
282 The incoming mail is moved from the specified spool file (which normally is
283 something like \"/usr/spool/mail/$user\") to the user's home
284 directory.  This hook is called after the incoming mail box has been
285 emptied, and can be used to call any mail box programs you have
286 running (\"xwatch\", etc.)
287
288 Eg.
289
290 \(add-hook 'nnmail-read-incoming-hook
291           (lambda ()
292             (call-process \"/local/bin/mailsend\" nil nil nil
293                           \"read\" nnmail-spool-file)))
294
295 If you have xwatch running, this will alert it that mail has been
296 read.
297
298 If you use `display-time', you could use something like this:
299
300 \(add-hook 'nnmail-read-incoming-hook
301           (lambda ()
302             ;; Update the displayed time, since that will clear out
303             ;; the flag that says you have mail.
304             (when (eq (process-status \"display-time\") 'run)
305               (display-time-filter display-time-process \"\"))))"
306   :group 'nnmail-prepare
307   :type 'hook)
308
309 (defcustom nnmail-prepare-incoming-hook nil
310   "Hook called before treating incoming mail.
311 The hook is run in a buffer with all the new, incoming mail."
312   :group 'nnmail-prepare
313   :type 'hook)
314
315 (defcustom nnmail-prepare-incoming-header-hook nil
316   "Hook called narrowed to the headers of each message.
317 This can be used to remove excessive spaces (and stuff like
318 that) from the headers before splitting and saving the messages."
319   :group 'nnmail-prepare
320   :type 'hook)
321
322 (defcustom nnmail-prepare-incoming-message-hook nil
323   "Hook called narrowed to each message."
324   :group 'nnmail-prepare
325   :type 'hook)
326
327 (defcustom nnmail-list-identifiers nil
328   "Regexp that matches list identifiers to be removed.
329 This can also be a list of regexps."
330   :group 'nnmail-prepare
331   :type '(choice (const :tag "none" nil)
332                  (regexp :value ".*")
333                  (repeat :value (".*") regexp)))
334
335 (defcustom nnmail-pre-get-new-mail-hook nil
336   "Hook called just before starting to handle new incoming mail."
337   :group 'nnmail-retrieve
338   :type 'hook)
339
340 (defcustom nnmail-post-get-new-mail-hook nil
341   "Hook called just after finishing handling new incoming mail."
342   :group 'nnmail-retrieve
343   :type 'hook)
344
345 (defcustom nnmail-split-hook nil
346   "Hook called before deciding where to split an article.
347 The functions in this hook are free to modify the buffer
348 contents in any way they choose -- the buffer contents are
349 discarded after running the split process."
350   :group 'nnmail-split
351   :type 'hook)
352
353 (defcustom nnmail-spool-hook nil
354   "*A hook called when a new article is spooled."
355   :group 'nnmail
356   :type 'hook)
357
358 (defcustom nnmail-large-newsgroup 50
359   "*The number of articles which indicates a large newsgroup or nil.
360 If the number of articles is greater than the value, verbose
361 messages will be shown to indicate the current status."
362   :group 'nnmail-various
363   :type '(choice (const :tag "infinite" nil)
364                  (number :tag "count")))
365
366 (define-widget 'nnmail-lazy 'default
367   "Base widget for recursive datastructures.
368
369 This is copy of the `lazy' widget in Emacs 21.4 provided for compatibility."
370   :format "%{%t%}: %v"
371   :convert-widget 'widget-value-convert-widget
372   :value-create (lambda (widget)
373                   (let ((value (widget-get widget :value))
374                         (type (widget-get widget :type)))
375                     (widget-put widget :children 
376                                 (list (widget-create-child-value 
377                                        widget (widget-convert type) value)))))
378   :value-delete 'widget-children-value-delete
379   :value-get (lambda (widget)
380                (widget-value (car (widget-get widget :children))))
381   :value-inline (lambda (widget)
382                   (widget-apply (car (widget-get widget :children))
383                                 :value-inline))
384   :default-get (lambda (widget)
385                  (widget-default-get
386                   (widget-convert (widget-get widget :type))))
387   :match (lambda (widget value)
388            (widget-apply (widget-convert (widget-get widget :type))
389                          :match value))
390   :validate (lambda (widget)
391               (widget-apply (car (widget-get widget :children)) :validate)))
392
393 (define-widget 'nnmail-split-fancy 'nnmail-lazy
394   "Widget for customizing splits in the variable of the same name."
395   :tag "Split"
396   :type '(menu-choice :value (any ".*value.*" "misc")
397                       :tag "Type"
398                       (string :tag "Destination")
399                       (list :tag "Use first match (|)" :value (|)
400                             (const :format "" |)
401                             (editable-list :inline t nnmail-split-fancy))
402                       (list :tag "Use all matches (&)" :value (&)
403                             (const :format "" &)
404                             (editable-list :inline t nnmail-split-fancy))
405                       (list :tag "Function with fixed arguments (:)"
406                             :value (: nil)
407                             (const :format "" :value :)
408                             function 
409                             (editable-list :inline t (sexp :tag "Arg"))
410                             )
411                       (list :tag "Function with split arguments (!)"
412                             :value (! nil)
413                             (const :format "" !)
414                             function
415                             (editable-list :inline t nnmail-split-fancy))
416                       (list :tag "Field match" 
417                             (choice :tag "Field" 
418                                     regexp symbol)
419                             (choice :tag "Match"
420                                     regexp 
421                                     (symbol :value mail))
422                             nnmail-split-fancy)
423                       (const :tag "Junk (delete mail)" junk)))
424
425 (defcustom nnmail-split-fancy "mail.misc"
426   "Incoming mail can be split according to this fancy variable.
427 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
428
429 The format of this variable is SPLIT, where SPLIT can be one of
430 the following:
431
432 GROUP: Mail will be stored in GROUP (a string).
433
434 \(FIELD VALUE [- RESTRICT [- RESTRICT [...]]] SPLIT): If the message
435   field FIELD (a regexp) contains VALUE (a regexp), store the messages
436   as specified by SPLIT.  If RESTRICT (a regexp) matches some string
437   after FIELD and before the end of the matched VALUE, return nil,
438   otherwise process SPLIT.  Multiple RESTRICTs add up, further
439   restricting the possibility of processing SPLIT.
440
441 \(| SPLIT...): Process each SPLIT expression until one of them matches.
442   A SPLIT expression is said to match if it will cause the mail
443   message to be stored in one or more groups.
444
445 \(& SPLIT...): Process each SPLIT expression.
446
447 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
448   the buffer containing the message headers.  The return value FUNCTION
449   should be a split, which is then recursively processed.
450
451 \(! FUNCTION SPLIT): Call FUNCTION with the result of SPLIT.  The
452   return value FUNCTION should be a split, which is then recursively
453   processed.
454
455 junk: Mail will be deleted.  Use with care!  Do not submerge in water!
456   Example:
457   (setq nnmail-split-fancy
458         '(| (\"Subject\" \"MAKE MONEY FAST\" junk)
459             ...other.rules.omitted...))
460
461 FIELD must match a complete field name.  VALUE must match a complete
462 word according to the `nnmail-split-fancy-syntax-table' syntax table.
463 You can use \".*\" in the regexps to match partial field names or words.
464
465 FIELD and VALUE can also be lisp symbols, in that case they are expanded
466 as specified in `nnmail-split-abbrev-alist'.
467
468 GROUP can contain \\& and \\N which will substitute from matching
469 \\(\\) patterns in the previous VALUE.
470
471 Example:
472
473 \(setq nnmail-split-methods 'nnmail-split-fancy
474       nnmail-split-fancy
475       ;; Messages from the mailer daemon are not crossposted to any of
476       ;; the ordinary groups.  Warnings are put in a separate group
477       ;; from real errors.
478       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
479                           \"mail.misc\"))
480           ;; Non-error messages are crossposted to all relevant
481           ;; groups, but we don't crosspost between the group for the
482           ;; (ding) list and the group for other (ding) related mail.
483           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
484                 (\"subject\" \"ding\" \"ding.misc\"))
485              ;; Other mailing lists...
486              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
487              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
488              ;; Both lists below have the same suffix, so prevent
489              ;; cross-posting to mkpkg.list of messages posted only to
490              ;; the bugs- list, but allow cross-posting when the
491              ;; message was really cross-posted.
492              (any \"bugs-mypackage@somewhere\" \"mypkg.bugs\")
493              (any \"mypackage@somewhere\" - \"bugs-mypackage\" \"mypkg.list\")
494              ;;
495              ;; People...
496              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
497           ;; Unmatched mail goes to the catch all group.
498           \"misc.misc\"))"
499   :group 'nnmail-split
500   :type 'nnmail-split-fancy)
501
502 (defcustom nnmail-split-abbrev-alist
503   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
504     (mail . "mailer-daemon\\|postmaster\\|uucp")
505     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
506     (from . "from\\|sender\\|resent-from")
507     (nato . "to\\|cc\\|resent-to\\|resent-cc")
508     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
509   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
510   :group 'nnmail-split
511   :type '(repeat (cons :format "%v" symbol regexp)))
512
513 (defcustom nnmail-message-id-cache-length 1000
514   "*The approximate number of Message-IDs nnmail will keep in its cache.
515 If this variable is nil, no checking on duplicate messages will be
516 performed."
517   :group 'nnmail-duplicate
518   :type '(choice (const :tag "disable" nil)
519                  (integer :format "%v")))
520
521 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
522   "*The file name of the nnmail Message-ID cache."
523   :group 'nnmail-duplicate
524   :group 'nnmail-files
525   :type 'file)
526
527 (defcustom nnmail-treat-duplicates 'warn
528   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
529 Three values are valid: nil, which means that nnmail is not to keep a
530 Message-ID cache; `warn', which means that nnmail should insert extra
531 headers to warn the user about the duplication (this is the default);
532 and `delete', which means that nnmail will delete duplicated mails.
533
534 This variable can also be a function.  It will be called from a buffer
535 narrowed to the article in question with the Message-ID as a
536 parameter.  It should return nil, `warn' or `delete'."
537   :group 'nnmail-duplicate
538   :type '(choice (const :tag "off" nil)
539                  (const warn)
540                  (const delete)))
541
542 (defcustom nnmail-extra-headers '(To Newsgroups)
543   "*Extra headers to parse."
544   :version "21.1"
545   :group 'nnmail
546   :type '(repeat symbol))
547
548 (defcustom nnmail-split-header-length-limit 512
549   "Header lines longer than this limit are excluded from the split function."
550   :version "21.1"
551   :group 'nnmail
552   :type 'integer)
553
554 (defcustom nnmail-mail-splitting-charset nil
555   "Default charset to be used when splitting incoming mail."
556   :group 'nnmail
557   :type 'symbol)
558
559 (defcustom nnmail-mail-splitting-decodes nil
560   "Whether the nnmail splitting functionality should MIME decode headers."
561   :group 'nnmail
562   :type 'boolean)
563
564 (defcustom nnmail-split-fancy-match-partial-words nil
565   "Whether to match partial words when fancy splitting.
566 Normally, regexes given in `nnmail-split-fancy' are implicitly surrounded
567 by \"\\=\\<...\\>\".  If this variable is true, they are not implicitly\
568  surrounded
569 by anything."
570   :group 'nnmail
571   :type 'boolean)
572
573 ;;; Internal variables.
574
575 (defvar nnmail-article-buffer " *nnmail incoming*"
576   "The buffer used for splitting incoming mails.")
577
578 (defvar nnmail-split-history nil
579   "List of group/article elements that say where the previous split put messages.")
580
581 (defvar nnmail-split-fancy-syntax-table
582   (let ((table (make-syntax-table)))
583     ;; support the %-hack
584     (modify-syntax-entry ?\% "." table)
585     table)
586   "Syntax table used by `nnmail-split-fancy'.")
587
588 (defvar nnmail-prepare-save-mail-hook nil
589   "Hook called before saving mail.")
590
591 (defvar nnmail-split-tracing nil)
592 (defvar nnmail-split-trace nil)
593
594 \f
595
596 (defun nnmail-request-post (&optional server)
597   (mail-send-and-exit nil))
598
599 (defvar nnmail-file-coding-system 'raw-text
600   "Coding system used in nnmail.")
601
602 (defvar nnmail-incoming-coding-system
603   mm-text-coding-system
604   "Coding system used in reading inbox")
605
606 (defvar nnmail-pathname-coding-system nil
607   "*Coding system for file name.")
608
609 (defun nnmail-find-file (file)
610   "Insert FILE in server buffer safely."
611   (set-buffer nntp-server-buffer)
612   (delete-region (point-min) (point-max))
613   (let ((format-alist nil)
614         (after-insert-file-functions nil))
615     (condition-case ()
616         (let ((coding-system-for-read nnmail-file-coding-system)
617               (auto-mode-alist (mm-auto-mode-alist))
618               (file-name-coding-system nnmail-pathname-coding-system))
619           (insert-file-contents file)
620           t)
621       (file-error nil))))
622
623 (defun nnmail-group-pathname (group dir &optional file)
624   "Make file name for GROUP."
625   (concat
626    (let ((dir (file-name-as-directory (expand-file-name dir))))
627      (setq group (nnheader-replace-duplicate-chars-in-string
628                   (nnheader-replace-chars-in-string group ?/ ?_)
629                   ?. ?_))
630      (setq group (nnheader-translate-file-chars group))
631      ;; If this directory exists, we use it directly.
632      (file-name-as-directory
633       (if (or nnmail-use-long-file-names
634               (file-directory-p (concat dir group)))
635           (expand-file-name group dir)
636         ;; If not, we translate dots into slashes.
637         (expand-file-name
638          (mm-encode-coding-string
639           (nnheader-replace-chars-in-string group ?. ?/)
640           nnmail-pathname-coding-system)
641          dir))))
642    (or file "")))
643
644 (defun nnmail-get-active ()
645   "Returns an assoc of group names and active ranges.
646 nn*-request-list should have been called before calling this function."
647   ;; Go through all groups from the active list.
648   (save-excursion
649     (set-buffer nntp-server-buffer)
650     (nnmail-parse-active)))
651
652 (defun nnmail-parse-active ()
653   "Parse the active file in the current buffer and return an alist."
654   (goto-char (point-min))
655   (unless (re-search-forward "[\\\"]" nil t)
656     (goto-char (point-max))
657     (while (re-search-backward "[][';?()#]" nil t)
658       (insert ?\\)))
659   (goto-char (point-min))
660   (let ((buffer (current-buffer))
661         group-assoc group max min)
662     (while (not (eobp))
663       (condition-case err
664           (progn
665             (narrow-to-region (point) (gnus-point-at-eol))
666             (setq group (read buffer))
667             (unless (stringp group)
668               (setq group (symbol-name group)))
669             (if (and (numberp (setq max (read buffer)))
670                      (numberp (setq min (read buffer))))
671                 (push (list group (cons min max))
672                       group-assoc)))
673         (error nil))
674       (widen)
675       (forward-line 1))
676     group-assoc))
677
678 (defvar nnmail-active-file-coding-system 'raw-text
679   "*Coding system for active file.")
680
681 (defun nnmail-save-active (group-assoc file-name)
682   "Save GROUP-ASSOC in ACTIVE-FILE."
683   (let ((coding-system-for-write nnmail-active-file-coding-system))
684     (when file-name
685       (with-temp-file file-name
686         (nnmail-generate-active group-assoc)))))
687
688 (defun nnmail-generate-active (alist)
689   "Generate an active file from group-alist ALIST."
690   (erase-buffer)
691   (let (group)
692     (while (setq group (pop alist))
693       (insert (format "%S %d %d y\n" (intern (car group)) (cdadr group)
694                       (caadr group))))
695     (goto-char (point-max))
696     (while (search-backward "\\." nil t)
697       (delete-char 1))))
698
699 (defun nnmail-get-split-group (file source)
700   "Find out whether this FILE is to be split into GROUP only.
701 If SOURCE is a directory spec, try to return the group name component."
702   (if (eq (car source) 'directory)
703       (let ((file (file-name-nondirectory file)))
704         (mail-source-bind (directory source)
705           (if (string-match (concat (regexp-quote suffix) "$") file)
706               (substring file 0 (match-beginning 0))
707             nil)))
708     nil))
709
710 (defun nnmail-process-babyl-mail-format (func artnum-func)
711   (let ((case-fold-search t)
712         (count 0)
713         start message-id content-length do-search end)
714     (while (not (eobp))
715       (goto-char (point-min))
716       (re-search-forward
717        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
718       (goto-char (match-end 0))
719       (delete-region (match-beginning 0) (match-end 0))
720       (narrow-to-region
721        (setq start (point))
722        (progn
723          ;; Skip all the headers in case there are more "From "s...
724          (or (search-forward "\n\n" nil t)
725              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
726              (search-forward "\1f\f"))
727          (point)))
728       ;; Unquote the ">From " line, if any.
729       (goto-char (point-min))
730       (when (looking-at ">From ")
731         (replace-match "X-From-Line: ") )
732       (run-hooks 'nnmail-prepare-incoming-header-hook)
733       (goto-char (point-max))
734       ;; Find the Message-ID header.
735       (save-excursion
736         (if (re-search-backward
737              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
738             (setq message-id (buffer-substring (match-beginning 1)
739                                                (match-end 1)))
740           ;; There is no Message-ID here, so we create one.
741           (save-excursion
742             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
743               (beginning-of-line)
744               (insert "Original-")))
745           (forward-line -1)
746           (insert "Message-ID: " (setq message-id (nnmail-message-id))
747                   "\n")))
748       ;; Look for a Content-Length header.
749       (if (not (save-excursion
750                  (and (re-search-backward
751                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
752                       (setq content-length (string-to-int
753                                             (buffer-substring
754                                              (match-beginning 1)
755                                              (match-end 1))))
756                       ;; We destroy the header, since none of
757                       ;; the backends ever use it, and we do not
758                       ;; want to confuse other mailers by having
759                       ;; a (possibly) faulty header.
760                       (progn (insert "X-") t))))
761           (setq do-search t)
762         (widen)
763         (if (or (= (+ (point) content-length) (point-max))
764                 (save-excursion
765                   (goto-char (+ (point) content-length))
766                   (looking-at "\1f")))
767             (progn
768               (goto-char (+ (point) content-length))
769               (setq do-search nil))
770           (setq do-search t)))
771       (widen)
772       ;; Go to the beginning of the next article - or to the end
773       ;; of the buffer.
774       (when do-search
775         (if (re-search-forward "^\1f" nil t)
776             (goto-char (match-beginning 0))
777           (goto-char (1- (point-max)))))
778       (delete-char 1)                   ; delete ^_
779       (save-excursion
780         (save-restriction
781           (narrow-to-region start (point))
782           (goto-char (point-min))
783           (nnmail-check-duplication message-id func artnum-func)
784           (incf count)
785           (setq end (point-max))))
786       (goto-char end))
787     count))
788
789 (defsubst nnmail-search-unix-mail-delim ()
790   "Put point at the beginning of the next Unix mbox message."
791   ;; Algorithm used to find the next article in the
792   ;; brain-dead Unix mbox format:
793   ;;
794   ;; 1) Search for "^From ".
795   ;; 2) If we find it, then see whether the previous
796   ;;    line is blank and the next line looks like a header.
797   ;; Then it's possible that this is a mail delim, and we use it.
798   (let ((case-fold-search nil)
799         found)
800     (while (not found)
801       (if (not (re-search-forward "^From " nil t))
802           (setq found 'no)
803         (save-excursion
804           (beginning-of-line)
805           (when (and (or (bobp)
806                          (save-excursion
807                            (forward-line -1)
808                            (eq (char-after) ?\n)))
809                      (save-excursion
810                        (forward-line 1)
811                        (while (looking-at ">From \\|From ")
812                          (forward-line 1))
813                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
814             (setq found 'yes)))))
815     (beginning-of-line)
816     (eq found 'yes)))
817
818 (defun nnmail-search-unix-mail-delim-backward ()
819   "Put point at the beginning of the current Unix mbox message."
820   ;; Algorithm used to find the next article in the
821   ;; brain-dead Unix mbox format:
822   ;;
823   ;; 1) Search for "^From ".
824   ;; 2) If we find it, then see whether the previous
825   ;;    line is blank and the next line looks like a header.
826   ;; Then it's possible that this is a mail delim, and we use it.
827   (let ((case-fold-search nil)
828         found)
829     (while (not found)
830       (if (not (re-search-backward "^From " nil t))
831           (setq found 'no)
832         (save-excursion
833           (beginning-of-line)
834           (when (and (or (bobp)
835                          (save-excursion
836                            (forward-line -1)
837                            (eq (char-after) ?\n)))
838                      (save-excursion
839                        (forward-line 1)
840                        (while (looking-at ">From \\|From ")
841                          (forward-line 1))
842                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
843             (setq found 'yes)))))
844     (beginning-of-line)
845     (eq found 'yes)))
846
847 (defun nnmail-process-unix-mail-format (func artnum-func)
848   (let ((case-fold-search t)
849         (count 0)
850         start message-id content-length end skip head-end)
851     (goto-char (point-min))
852     (if (not (and (re-search-forward "^From " nil t)
853                   (goto-char (match-beginning 0))))
854         ;; Possibly wrong format?
855         (error "Error, unknown mail format! (Possibly corrupted %s `%s'.)"
856                (if (buffer-file-name) "file" "buffer")
857                (or (buffer-file-name) (buffer-name)))
858       ;; Carry on until the bitter end.
859       (while (not (eobp))
860         (setq start (point)
861               end nil)
862         ;; Find the end of the head.
863         (narrow-to-region
864          start
865          (if (search-forward "\n\n" nil t)
866              (1- (point))
867            ;; This will never happen, but just to be on the safe side --
868            ;; if there is no head-body delimiter, we search a bit manually.
869            (while (and (looking-at "From \\|[^ \t]+:")
870                        (not (eobp)))
871              (forward-line 1))
872            (point)))
873         ;; Find the Message-ID header.
874         (goto-char (point-min))
875         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
876             (setq message-id (match-string 1))
877           (save-excursion
878             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
879               (beginning-of-line)
880               (insert "Original-")))
881           ;; There is no Message-ID here, so we create one.
882           (forward-line 1)
883           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
884         ;; Look for a Content-Length header.
885         (goto-char (point-min))
886         (if (not (re-search-forward
887                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
888             (setq content-length nil)
889           (setq content-length (string-to-int (match-string 1)))
890           ;; We destroy the header, since none of the backends ever
891           ;; use it, and we do not want to confuse other mailers by
892           ;; having a (possibly) faulty header.
893           (beginning-of-line)
894           (insert "X-"))
895         (run-hooks 'nnmail-prepare-incoming-header-hook)
896         ;; Find the end of this article.
897         (goto-char (point-max))
898         (widen)
899         (setq head-end (point))
900         ;; We try the Content-Length value.  The idea: skip over the header
901         ;; separator, then check what happens content-length bytes into the
902         ;; message body.  This should be either the end of the buffer, the
903         ;; message separator or a blank line followed by the separator.
904         ;; The blank line should probably be deleted.  If neither of the
905         ;; three is met, the content-length header is probably invalid.
906         (when content-length
907           (forward-line 1)
908           (setq skip (+ (point) content-length))
909           (goto-char skip)
910           (cond ((or (= skip (point-max))
911                      (= (1+ skip) (point-max)))
912                  (setq end (point-max)))
913                 ((looking-at "From ")
914                  (setq end skip))
915                 ((looking-at "[ \t]*\n\\(From \\)")
916                  (setq end (match-beginning 1)))
917                 (t (setq end nil))))
918         (if end
919             (goto-char end)
920           ;; No Content-Length, so we find the beginning of the next
921           ;; article or the end of the buffer.
922           (goto-char head-end)
923           (or (nnmail-search-unix-mail-delim)
924               (goto-char (point-max))))
925         ;; Allow the backend to save the article.
926         (save-excursion
927           (save-restriction
928             (narrow-to-region start (point))
929             (goto-char (point-min))
930             (incf count)
931             (nnmail-check-duplication message-id func artnum-func)
932             (setq end (point-max))))
933         (goto-char end)))
934     count))
935
936 (defun nnmail-process-mmdf-mail-format (func artnum-func)
937   (let ((delim "^\^A\^A\^A\^A$")
938         (case-fold-search t)
939         (count 0)
940         start message-id end)
941     (goto-char (point-min))
942     (if (not (and (re-search-forward delim nil t)
943                   (forward-line 1)))
944         ;; Possibly wrong format?
945         (error "Error, unknown mail format! (Possibly corrupted.)")
946       ;; Carry on until the bitter end.
947       (while (not (eobp))
948         (setq start (point))
949         ;; Find the end of the head.
950         (narrow-to-region
951          start
952          (if (search-forward "\n\n" nil t)
953              (1- (point))
954            ;; This will never happen, but just to be on the safe side --
955            ;; if there is no head-body delimiter, we search a bit manually.
956            (while (and (looking-at "From \\|[^ \t]+:")
957                        (not (eobp)))
958              (forward-line 1))
959            (point)))
960         ;; Find the Message-ID header.
961         (goto-char (point-min))
962         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
963             (setq message-id (match-string 1))
964           ;; There is no Message-ID here, so we create one.
965           (save-excursion
966             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
967               (beginning-of-line)
968               (insert "Original-")))
969           (forward-line 1)
970           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
971         (run-hooks 'nnmail-prepare-incoming-header-hook)
972         ;; Find the end of this article.
973         (goto-char (point-max))
974         (widen)
975         (if (re-search-forward delim nil t)
976             (beginning-of-line)
977           (goto-char (point-max)))
978         ;; Allow the backend to save the article.
979         (save-excursion
980           (save-restriction
981             (narrow-to-region start (point))
982             (goto-char (point-min))
983             (incf count)
984             (nnmail-check-duplication message-id func artnum-func)
985             (setq end (point-max))))
986         (goto-char end)
987         (forward-line 2)))
988     count))
989
990 (defun nnmail-process-maildir-mail-format (func artnum-func)
991   ;; In a maildir, every file contains exactly one mail.
992   (let ((case-fold-search t)
993         message-id)
994     (goto-char (point-min))
995     ;; Find the end of the head.
996     (narrow-to-region
997      (point-min)
998      (if (search-forward "\n\n" nil t)
999          (1- (point))
1000        ;; This will never happen, but just to be on the safe side --
1001        ;; if there is no head-body delimiter, we search a bit manually.
1002        (while (and (looking-at "From \\|[^ \t]+:")
1003                    (not (eobp)))
1004          (forward-line 1))
1005        (point)))
1006     ;; Find the Message-ID header.
1007     (goto-char (point-min))
1008     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
1009         (setq message-id (match-string 1))
1010       ;; There is no Message-ID here, so we create one.
1011       (save-excursion
1012         (when (re-search-backward "^Message-ID[ \t]*:" nil t)
1013           (beginning-of-line)
1014           (insert "Original-")))
1015       (forward-line 1)
1016       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
1017     (run-hooks 'nnmail-prepare-incoming-header-hook)
1018     ;; Allow the backend to save the article.
1019     (widen)
1020     (save-excursion
1021       (goto-char (point-min))
1022       (nnmail-check-duplication message-id func artnum-func))
1023     1))
1024
1025 (defun nnmail-split-incoming (incoming func &optional exit-func
1026                                        group artnum-func)
1027   "Go through the entire INCOMING file and pick out each individual mail.
1028 FUNC will be called with the buffer narrowed to each mail."
1029   (let ( ;; If this is a group-specific split, we bind the split
1030         ;; methods to just this group.
1031         (nnmail-split-methods (if (and group
1032                                        (not nnmail-resplit-incoming))
1033                                   (list (list group ""))
1034                                 nnmail-split-methods)))
1035     (save-excursion
1036       ;; Insert the incoming file.
1037       (set-buffer (get-buffer-create nnmail-article-buffer))
1038       (erase-buffer)
1039       (let ((coding-system-for-read nnmail-incoming-coding-system))
1040         (mm-insert-file-contents incoming))
1041       (prog1
1042           (if (zerop (buffer-size))
1043               0
1044             (goto-char (point-min))
1045             (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
1046             ;; Handle both babyl, MMDF and unix mail formats, since
1047             ;; movemail will use the former when fetching from a
1048             ;; mailbox, the latter when fetching from a file.
1049             (cond ((or (looking-at "\^L")
1050                        (looking-at "BABYL OPTIONS:"))
1051                    (nnmail-process-babyl-mail-format func artnum-func))
1052                   ((looking-at "\^A\^A\^A\^A")
1053                    (nnmail-process-mmdf-mail-format func artnum-func))
1054                   ((looking-at "Return-Path:")
1055                    (nnmail-process-maildir-mail-format func artnum-func))
1056                   (t
1057                    (nnmail-process-unix-mail-format func artnum-func))))
1058         (when exit-func
1059           (funcall exit-func))
1060         (kill-buffer (current-buffer))))))
1061
1062 (defun nnmail-article-group (func &optional trace)
1063   "Look at the headers and return an alist of groups that match.
1064 FUNC will be called with the group name to determine the article number."
1065   (let ((methods (or nnmail-split-methods '(("bogus" ""))))
1066         (obuf (current-buffer))
1067         group-art method grp)
1068     (if (and (sequencep methods)
1069              (= (length methods) 1))
1070         ;; If there is only just one group to put everything in, we
1071         ;; just return a list with just this one method in.
1072         (setq group-art
1073               (list (cons (caar methods) (funcall func (caar methods)))))
1074       ;; We do actual comparison.
1075       (save-excursion
1076         ;; Copy the article into the work buffer.
1077         (set-buffer nntp-server-buffer)
1078         (erase-buffer)
1079         (insert-buffer-substring obuf)
1080         ;; Narrow to headers.
1081         (narrow-to-region
1082          (goto-char (point-min))
1083          (if (search-forward "\n\n" nil t)
1084              (point)
1085            (point-max)))
1086         (goto-char (point-min))
1087         ;; Decode MIME headers and charsets.
1088         (when nnmail-mail-splitting-decodes
1089           (let ((mail-parse-charset nnmail-mail-splitting-charset))
1090             (mail-decode-encoded-word-region (point-min) (point-max))))
1091         ;; Fold continuation lines.
1092         (goto-char (point-min))
1093         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
1094           (replace-match " " t t))
1095         ;; Nuke pathologically long headers.  Since Gnus applies
1096         ;; pathologically complex regexps to the buffer, lines
1097         ;; that are looong will take longer than the Universe's
1098         ;; existence to process.
1099         (goto-char (point-min))
1100         (while (not (eobp))
1101           (unless (< (move-to-column nnmail-split-header-length-limit)
1102                      nnmail-split-header-length-limit)
1103             (delete-region (point) (gnus-point-at-eol)))
1104           (forward-line 1))
1105         ;; Allow washing.
1106         (goto-char (point-min))
1107         (run-hooks 'nnmail-split-hook)
1108         (when (setq nnmail-split-tracing trace)
1109           (setq nnmail-split-trace nil))
1110         (if (and (symbolp nnmail-split-methods)
1111                  (fboundp nnmail-split-methods))
1112             (let ((split
1113                    (condition-case nil
1114                        ;; `nnmail-split-methods' is a function, so we
1115                        ;; just call this function here and use the
1116                        ;; result.
1117                        (or (funcall nnmail-split-methods)
1118                            '("bogus"))
1119                      (error
1120                       (nnheader-message
1121                        5 "Error in `nnmail-split-methods'; using `bogus' mail group")
1122                       (sit-for 1)
1123                       '("bogus")))))
1124               (setq split (gnus-remove-duplicates split))
1125               ;; The article may be "cross-posted" to `junk'.  What
1126               ;; to do?  Just remove the `junk' spec.  Don't really
1127               ;; see anything else to do...
1128               (let (elem)
1129                 (while (setq elem (car (memq 'junk split)))
1130                   (setq split (delq elem split))))
1131               (when split
1132                 (setq group-art
1133                       (mapcar
1134                        (lambda (group) (cons group (funcall func group)))
1135                        split))))
1136           ;; Go through the split methods to find a match.
1137           (while (and methods
1138                       (or nnmail-crosspost
1139                           (not group-art)))
1140             (goto-char (point-max))
1141             (setq method (pop methods)
1142                   grp (car method))
1143             (if (or methods
1144                     (not (equal "" (nth 1 method))))
1145                 (when (and
1146                        (ignore-errors
1147                          (if (stringp (nth 1 method))
1148                              (let ((expand (string-match "\\\\[0-9&]" grp))
1149                                    (pos (re-search-backward (cadr method)
1150                                                             nil t)))
1151                                (and expand
1152                                     (setq grp (nnmail-expand-newtext grp)))
1153                                pos)
1154                            ;; Function to say whether this is a match.
1155                            (funcall (nth 1 method) grp)))
1156                        ;; Don't enter the article into the same
1157                        ;; group twice.
1158                        (not (assoc grp group-art)))
1159                   (push (cons grp (funcall func grp))
1160                         group-art))
1161               ;; This is the final group, which is used as a
1162               ;; catch-all.
1163               (unless group-art
1164                 (setq group-art
1165                       (list (cons (car method)
1166                                   (funcall func (car method))))))))
1167           ;; Fall back on "bogus" if all else fails.
1168           (unless group-art
1169             (setq group-art (list (cons "bogus" (funcall func "bogus"))))))
1170         ;; Produce a trace if non-empty.
1171         (when (and trace nnmail-split-trace)
1172           (let ((restore (current-buffer)))
1173             (nnheader-set-temp-buffer "*Split Trace*")
1174             (gnus-add-buffer)
1175             (dolist (trace (nreverse nnmail-split-trace))
1176               (prin1 trace (current-buffer))
1177               (insert "\n"))
1178             (goto-char (point-min))
1179             (gnus-configure-windows 'split-trace)
1180             (set-buffer restore)))
1181         (widen)
1182         ;; See whether the split methods returned `junk'.
1183         (if (equal group-art '(junk))
1184             nil
1185           ;; The article may be "cross-posted" to `junk'.  What
1186           ;; to do?  Just remove the `junk' spec.  Don't really
1187           ;; see anything else to do...
1188           (let (elem)
1189             (while (setq elem (car (memq 'junk group-art)))
1190               (setq group-art (delq elem group-art)))
1191             (nreverse group-art)))))))
1192
1193 (defun nnmail-insert-lines ()
1194   "Insert how many lines there are in the body of the mail.
1195 Return the number of characters in the body."
1196   (let (lines chars)
1197     (save-excursion
1198       (goto-char (point-min))
1199       (unless (search-forward "\n\n" nil t)
1200         (goto-char (point-max))
1201         (insert "\n"))
1202       (setq chars (- (point-max) (point)))
1203       (setq lines (count-lines (point) (point-max)))
1204       (forward-char -1)
1205       (save-excursion
1206         (when (re-search-backward "^Lines: " nil t)
1207           (delete-region (point) (progn (forward-line 1) (point)))))
1208       (beginning-of-line)
1209       (insert (format "Lines: %d\n" (max lines 0)))
1210       chars)))
1211
1212 (defun nnmail-insert-xref (group-alist)
1213   "Insert an Xref line based on the (group . article) alist."
1214   (save-excursion
1215     (goto-char (point-min))
1216     (unless (search-forward "\n\n" nil t)
1217       (goto-char (point-max))
1218       (insert "\n"))
1219     (forward-char -1)
1220     (when (re-search-backward "^Xref: " nil t)
1221       (delete-region (match-beginning 0)
1222                      (progn (forward-line 1) (point))))
1223     (insert (format "Xref: %s" (system-name)))
1224     (while group-alist
1225       (insert (format " %s:%d"
1226                       (mm-encode-coding-string
1227                        (caar group-alist)
1228                        nnmail-pathname-coding-system)
1229                       (cdar group-alist)))
1230       (setq group-alist (cdr group-alist)))
1231     (insert "\n")))
1232
1233 ;;; Message washing functions
1234
1235 (defun nnmail-remove-leading-whitespace ()
1236   "Remove excessive whitespace from all headers."
1237   (goto-char (point-min))
1238   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1239     (replace-match "\\1" t)))
1240
1241 (defun nnmail-remove-list-identifiers ()
1242   "Remove list identifiers from Subject headers."
1243   (let ((regexp
1244          (if (consp nnmail-list-identifiers)
1245              (mapconcat 'identity nnmail-list-identifiers " *\\|")
1246            nnmail-list-identifiers)))
1247     (when regexp
1248       (goto-char (point-min))
1249       (while (re-search-forward
1250               (concat "^Subject: +\\(R[Ee]: +\\)*\\(" regexp " *\\)")
1251               nil t)
1252         (delete-region (match-beginning 2) (match-end 0))
1253         (beginning-of-line))
1254       (when (re-search-forward "^Subject: +\\(\\(R[Ee]: +\\)+\\)R[Ee]: +"
1255                                nil t)
1256         (delete-region (match-beginning 1) (match-end 1))
1257         (beginning-of-line)))))
1258
1259 (defun nnmail-remove-tabs ()
1260   "Translate TAB characters into SPACE characters."
1261   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1262
1263 (defun nnmail-fix-eudora-headers ()
1264   "Eudora has a broken References line, but an OK In-Reply-To."
1265   (goto-char (point-min))
1266   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1267     (goto-char (point-min))
1268     (when (re-search-forward "^References:" nil t)
1269       (beginning-of-line)
1270       (insert "X-Gnus-Broken-Eudora-"))
1271     (goto-char (point-min))
1272     (when (re-search-forward "^\\(In-Reply-To:[^\n]+\\)\n[ \t]+" nil t)
1273       (replace-match "\\1" t))))
1274
1275 (custom-add-option 'nnmail-prepare-incoming-header-hook
1276                    'nnmail-fix-eudora-headers)
1277
1278 ;;; Utility functions
1279
1280 (defun nnmail-do-request-post (accept-func &optional server)
1281   "Utility function to directly post a message to an nnmail-derived group.
1282 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
1283 to actually put the message in the right group."
1284   (let ((success t))
1285     (dolist (mbx (message-unquote-tokens
1286                   (message-tokenize-header
1287                    (message-fetch-field "Newsgroups") ", ")) success)
1288       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1289         (or (gnus-active to-newsgroup)
1290             (gnus-activate-group to-newsgroup)
1291             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1292                                        to-newsgroup))
1293                 (or (and (gnus-request-create-group
1294                           to-newsgroup gnus-command-method)
1295                          (gnus-activate-group to-newsgroup nil nil
1296                                               gnus-command-method))
1297                     (error "Couldn't create group %s" to-newsgroup)))
1298             (error "No such group: %s" to-newsgroup))
1299         (unless (funcall accept-func mbx (nth 1 gnus-command-method))
1300           (setq success nil))))))
1301
1302 (defun nnmail-split-fancy ()
1303   "Fancy splitting method.
1304 See the documentation for the variable `nnmail-split-fancy' for details."
1305   (let ((syntab (syntax-table)))
1306     (unwind-protect
1307         (progn
1308           (set-syntax-table nnmail-split-fancy-syntax-table)
1309           (nnmail-split-it nnmail-split-fancy))
1310       (set-syntax-table syntab))))
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) (gnus-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 ;;; nnmail.el ends here