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