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