66e656dc56566a51cae142faf4840f5676a0e70e
[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 'nnheader)
32 (require 'message)
33 (require 'custom)
34 (require 'gnus-util)
35 (require 'mail-source)
36
37 (eval-and-compile
38   (autoload 'gnus-add-buffer "gnus")
39   (autoload 'gnus-kill-buffer "gnus"))
40
41 (defgroup nnmail nil
42   "Reading mail with Gnus."
43   :group 'gnus)
44
45 (defgroup nnmail-retrieve nil
46   "Retrieving new mail."
47   :group 'nnmail)
48
49 (defgroup nnmail-prepare nil
50   "Preparing (or mangling) new mail after retrival."
51   :group 'nnmail)
52
53 (defgroup nnmail-duplicate nil
54   "Handling of duplicate mail messages."
55   :group 'nnmail)
56
57 (defgroup nnmail-split nil
58   "Organizing the incoming mail in folders."
59   :group 'nnmail)
60
61 (defgroup nnmail-files nil
62   "Mail files."
63   :group 'gnus-files
64   :group 'nnmail)
65
66 (defgroup nnmail-expire nil
67   "Expiring old mail."
68   :group 'nnmail)
69
70 (defgroup nnmail-procmail nil
71   "Interfacing with procmail and other mail agents."
72   :group 'nnmail)
73
74 (defgroup nnmail-various nil
75   "Various mail options."
76   :group 'nnmail)
77
78 (defcustom nnmail-split-methods '(("mail.misc" ""))
79   "*Incoming mail will be split according to this variable.
80
81 If you'd like, for instance, one mail group for mail from the
82 \"4ad-l\" mailing list, one group for junk mail and one for everything
83 else, you could do something like this:
84
85  (setq nnmail-split-methods
86        '((\"mail.4ad\" \"From:.*4ad\")
87          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
88          (\"mail.misc\" \"\")))
89
90 As you can see, this variable is a list of lists, where the first
91 element in each \"rule\" is the name of the group (which, by the way,
92 does not have to be called anything beginning with \"mail\",
93 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
94 nnmail will try to match on the header to find a fit.
95
96 The second element can also be a function.  In that case, it will be
97 called narrowed to the headers with the first element of the rule as
98 the argument.  It should return a non-nil value if it thinks that the
99 mail belongs in that group.
100
101 The last element should always have \"\" as the regexp.
102
103 This variable can also have a function as its value."
104   :group 'nnmail-split
105   :type '(choice (repeat :tag "Alist" (group (string :tag "Name")
106                                              (choice regexp function)))
107                  (function-item nnmail-split-fancy)
108                  (function :tag "Other")))
109
110 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
111 (defcustom nnmail-crosspost t
112   "If non-nil, do crossposting if several split methods match the mail.
113 If nil, the first match found will be used."
114   :group 'nnmail-split
115   :type 'boolean)
116
117 (defcustom nnmail-split-fancy-with-parent-ignore-groups nil
118   "Regexp that matches group names to be ignored when applying `nnmail-split-fancy-with-parent'.
119 This can also be a list of regexps."
120   :group 'nnmail-split
121   :type '(choice (const :tag "none" nil)
122                  (regexp :value ".*")
123                  (repeat :value (".*") regexp)))
124
125 (defcustom nnmail-cache-ignore-groups nil
126   "Regexp that matches group names to be ignored when inserting message ids into the cache (`nnmail-cache-insert').
127 This can also be a list of regexps."
128   :group 'nnmail-split
129   :type '(choice (const :tag "none" nil)
130                  (regexp :value ".*")
131                  (repeat :value (".*") regexp)))
132
133 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
134 (defcustom nnmail-keep-last-article nil
135   "If non-nil, nnmail will never delete/move a group's last article.
136 It can be marked expirable, so it will be deleted when it is no longer last.
137
138 You may need to set this variable if other programs are putting
139 new mail into folder numbers that Gnus has marked as expired."
140   :group 'nnmail-procmail
141   :group 'nnmail-various
142   :type 'boolean)
143
144 (defcustom nnmail-use-long-file-names nil
145   "If non-nil the mail backends will use long file and directory names.
146 If nil, groups like \"mail.misc\" will end up in directories like
147 \"mail/misc/\"."
148   :group 'nnmail-files
149   :type 'boolean)
150
151 (defcustom nnmail-default-file-modes 384
152   "Set the mode bits of all new mail files to this integer."
153   :group 'nnmail-files
154   :type 'integer)
155
156 (defcustom nnmail-expiry-wait 7
157   "*Expirable articles that are older than this will be expired.
158 This variable can either be a number (which will be interpreted as a
159 number of days) -- this doesn't have to be an integer.  This variable
160 can also be `immediate' and `never'."
161   :group 'nnmail-expire
162   :type '(choice (const immediate)
163                  (number :tag "days")
164                  (const never)))
165
166 (defcustom nnmail-expiry-wait-function nil
167   "Variable that holds function to specify how old articles should be before they are expired.
168 The function will be called with the name of the group that the expiry
169 is to be performed in, and it should return an integer that says how
170 many days an article can be stored before it is considered \"old\".
171 It can also return the values `never' and `immediate'.
172
173 Eg.:
174
175 \(setq nnmail-expiry-wait-function
176       (lambda (newsgroup)
177         (cond ((string-match \"private\" newsgroup) 31)
178               ((string-match \"junk\" newsgroup) 1)
179               ((string-match \"important\" newsgroup) 'never)
180               (t 7))))"
181   :group 'nnmail-expire
182   :type '(choice (const :tag "nnmail-expiry-wait" nil)
183                  (function :format "%v" nnmail-)))
184
185 (defcustom nnmail-expiry-target 'delete
186   "*Variable that says where expired messages should end up.
187 The default value is `delete' (which says to delete the messages),
188 but it can also be a string or a function.  If it is a string, expired
189 messages end up in that group.  If it is a function, the function is
190 called in a buffer narrowed to the message in question.  The function
191 receives one argument, the name of the group the message comes from.
192 The return value should be `delete' or a group name (a string)."
193   :version "21.1"
194   :group 'nnmail-expire
195   :type '(choice (const delete)
196                  (function :format "%v" nnmail-)
197                  string))
198
199 (defcustom nnmail-fancy-expiry-targets nil
200   "Determine expiry target based on articles using fancy techniques.
201
202 This is a list of (\"HEADER\" \"REGEXP\" \"TARGET\") entries.  If
203 `nnmail-expiry-target' is set to the function
204 `nnmail-fancy-expiry-target' and HEADER of the article matches REGEXP,
205 the message will be expired to a group determined by invoking
206 `format-time-string' with TARGET used as the format string and the
207 time extracted from the articles' Date header (if missing the current
208 time is used).
209
210 In the special cases that HEADER is the symbol `to-from', the regexp
211 will try to match against both the From and the To header.
212
213 Example:
214
215 \(setq nnmail-fancy-expiry-targets
216       '((to-from \"boss\" \"nnfolder:Work\")
217         (\"Subject\" \"IMPORTANT\" \"nnfolder:IMPORTANT.%Y.%b\")
218         (\"from\" \".*\" \"nnfolder:Archive-%Y\")))
219
220 In this case, articles containing the string \"boss\" in the To or the
221 From header will be expired to the group \"nnfolder:Work\";
222 articles containing the sting \"IMPORTANT\" in the Subject header will
223 be expired to the group \"nnfolder:IMPORTANT.YYYY.MMM\"; and
224 everything else will be expired to \"nnfolder:Archive-YYYY\"."
225   :group 'nnmail-expire
226   :type '(repeat (list (choice :tag "Match against"
227                                (string :tag "Header")
228                                (const to-from))
229                        regexp
230                        (string :tag "Target group format string"))))
231
232 (defcustom nnmail-cache-accepted-message-ids nil
233   "If non-nil, put Message-IDs of Gcc'd articles into the duplicate cache.
234 If non-nil, also update the cache when copy or move articles."
235   :group 'nnmail
236   :type 'boolean)
237
238 (defcustom nnmail-spool-file '((file))
239   "*Where the mail backends will look for incoming mail.
240 This variable is a list of mail source specifiers.
241 This variable is obsolete; `mail-sources' should be used instead."
242   :group 'nnmail-files
243   :type 'sexp)
244
245 (defcustom nnmail-resplit-incoming nil
246   "*If non-nil, re-split incoming procmail sorted mail."
247   :group 'nnmail-procmail
248   :type 'boolean)
249
250 (defcustom nnmail-scan-directory-mail-source-once nil
251   "*If non-nil, scan all incoming procmail sorted mails once.
252 It scans low-level sorted spools even when not required."
253   :version "21.1"
254   :group 'nnmail-procmail
255   :type 'boolean)
256
257 (defcustom nnmail-delete-file-function 'delete-file
258   "Function called to delete files in some mail backends."
259   :group 'nnmail-files
260   :type 'function)
261
262 (defcustom nnmail-crosspost-link-function
263   (if (string-match "windows-nt\\|emx" (symbol-name system-type))
264       'copy-file
265     'add-name-to-file)
266   "*Function called to create a copy of a file.
267 This is `add-name-to-file' by default, which means that crossposts
268 will use hard links.  If your file system doesn't allow hard
269 links, you could set this variable to `copy-file' instead."
270   :group 'nnmail-files
271   :type '(radio (function-item add-name-to-file)
272                 (function-item copy-file)
273                 (function :tag "Other")))
274
275 (defcustom nnmail-read-incoming-hook
276   (if (eq system-type 'windows-nt)
277       '(nnheader-ms-strip-cr)
278     nil)
279   "*Hook that will be run after the incoming mail has been transferred.
280 The incoming mail is moved from the specified spool file (which normally is
281 something like \"/usr/spool/mail/$user\") to the user's home
282 directory.  This hook is called after the incoming mail box has been
283 emptied, and can be used to call any mail box programs you have
284 running (\"xwatch\", etc.)
285
286 Eg.
287
288 \(add-hook 'nnmail-read-incoming-hook
289           (lambda ()
290             (call-process \"/local/bin/mailsend\" nil nil nil
291                           \"read\" nnmail-spool-file)))
292
293 If you have xwatch running, this will alert it that mail has been
294 read.
295
296 If you use `display-time', you could use something like this:
297
298 \(add-hook 'nnmail-read-incoming-hook
299           (lambda ()
300             ;; Update the displayed time, since that will clear out
301             ;; the flag that says you have mail.
302             (when (eq (process-status \"display-time\") 'run)
303               (display-time-filter display-time-process \"\"))))"
304   :group 'nnmail-prepare
305   :type 'hook)
306
307 (defcustom nnmail-prepare-incoming-hook nil
308   "Hook called before treating incoming mail.
309 The hook is run in a buffer with all the new, incoming mail."
310   :group 'nnmail-prepare
311   :type 'hook)
312
313 (defcustom nnmail-prepare-incoming-header-hook nil
314   "Hook called narrowed to the headers of each message.
315 This can be used to remove excessive spaces (and stuff like
316 that) from the headers before splitting and saving the messages."
317   :group 'nnmail-prepare
318   :type 'hook)
319
320 (defcustom nnmail-prepare-incoming-message-hook nil
321   "Hook called narrowed to each message."
322   :group 'nnmail-prepare
323   :type 'hook)
324
325 (defcustom nnmail-list-identifiers nil
326   "Regexp that matches list identifiers to be removed.
327 This can also be a list of regexps."
328   :group 'nnmail-prepare
329   :type '(choice (const :tag "none" nil)
330                  (regexp :value ".*")
331                  (repeat :value (".*") regexp)))
332
333 (defcustom nnmail-pre-get-new-mail-hook nil
334   "Hook called just before starting to handle new incoming mail."
335   :group 'nnmail-retrieve
336   :type 'hook)
337
338 (defcustom nnmail-post-get-new-mail-hook nil
339   "Hook called just after finishing handling new incoming mail."
340   :group 'nnmail-retrieve
341   :type 'hook)
342
343 (defcustom nnmail-split-hook nil
344   "Hook called before deciding where to split an article.
345 The functions in this hook are free to modify the buffer
346 contents in any way they choose -- the buffer contents are
347 discarded after running the split process."
348   :group 'nnmail-split
349   :type 'hook)
350
351 (defcustom nnmail-spool-hook nil
352   "*A hook called when a new article is spooled."
353   :group 'nnmail
354   :type 'hook)
355
356 (defcustom nnmail-large-newsgroup 50
357   "*The number of the articles which indicates a large newsgroup or nil.
358 If the number of the articles is greater than the value, verbose
359 messages will be shown to indicate the current status."
360   :group 'nnmail-various
361   :type '(choice (const :tag "infinite" nil)
362                  (number :tag "count")))
363
364 (defcustom nnmail-split-fancy "mail.misc"
365   "Incoming mail can be split according to this fancy variable.
366 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
367
368 The format of this variable is SPLIT, where SPLIT can be one of
369 the following:
370
371 GROUP: Mail will be stored in GROUP (a string).
372
373 \(FIELD VALUE [- RESTRICT [- RESTRICT [...]]] SPLIT): If the message
374   field FIELD (a regexp) contains VALUE (a regexp), store the messages
375   as specified by SPLIT.  If RESTRICT (a regexp) matches some string
376   after FIELD and before the end of the matched VALUE, return nil,
377   otherwise process SPLIT.  Multiple RESTRICTs add up, further
378   restricting the possibility of processing SPLIT.
379
380 \(| SPLIT...): Process each SPLIT expression until one of them matches.
381   A SPLIT expression is said to match if it will cause the mail
382   message to be stored in one or more groups.
383
384 \(& SPLIT...): Process each SPLIT expression.
385
386 \(: FUNCTION optional args): Call FUNCTION with the optional args, in
387   the buffer containing the message headers.  The return value FUNCTION
388   should be a split, which is then recursively processed.
389
390 \(! FUNCTION SPLIT): Call FUNCTION with the result of SPLIT.  The
391   return value FUNCTION should be a split, which is then recursively
392   processed.
393
394 junk: Mail will be deleted.  Use with care!  Do not submerge in water!
395   Example:
396   (setq nnmail-split-fancy
397         '(| (\"Subject\" \"MAKE MONEY FAST\" junk)
398             ...other.rules.omitted...))
399
400 FIELD must match a complete field name.  VALUE must match a complete
401 word according to the `nnmail-split-fancy-syntax-table' syntax table.
402 You can use \".*\" in the regexps to match partial field names or words.
403
404 FIELD and VALUE can also be lisp symbols, in that case they are expanded
405 as specified in `nnmail-split-abbrev-alist'.
406
407 GROUP can contain \\& and \\N which will substitute from matching
408 \\(\\) patterns in the previous VALUE.
409
410 Example:
411
412 \(setq nnmail-split-methods 'nnmail-split-fancy
413       nnmail-split-fancy
414       ;; Messages from the mailer daemon are not crossposted to any of
415       ;; the ordinary groups.  Warnings are put in a separate group
416       ;; from real errors.
417       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
418                           \"mail.misc\"))
419           ;; Non-error messages are crossposted to all relevant
420           ;; groups, but we don't crosspost between the group for the
421           ;; (ding) list and the group for other (ding) related mail.
422           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
423                 (\"subject\" \"ding\" \"ding.misc\"))
424              ;; Other mailing lists...
425              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
426              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
427              ;; Both lists below have the same suffix, so prevent
428              ;; cross-posting to mkpkg.list of messages posted only to
429              ;; the bugs- list, but allow cross-posting when the
430              ;; message was really cross-posted.
431              (any \"bugs-mypackage@somewhere\" \"mypkg.bugs\")
432              (any \"mypackage@somewhere\" - \"bugs-mypackage\" \"mypkg.list\")
433              ;;
434              ;; People...
435              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
436           ;; Unmatched mail goes to the catch all group.
437           \"misc.misc\"))"
438   :group 'nnmail-split
439   ;; Sigh!
440   :type 'sexp)
441
442 (defcustom nnmail-split-abbrev-alist
443   '((any . "from\\|to\\|cc\\|sender\\|apparently-to\\|resent-from\\|resent-to\\|resent-cc")
444     (mail . "mailer-daemon\\|postmaster\\|uucp")
445     (to . "to\\|cc\\|apparently-to\\|resent-to\\|resent-cc")
446     (from . "from\\|sender\\|resent-from")
447     (nato . "to\\|cc\\|resent-to\\|resent-cc")
448     (naany . "from\\|to\\|cc\\|sender\\|resent-from\\|resent-to\\|resent-cc"))
449   "*Alist of abbreviations allowed in `nnmail-split-fancy'."
450   :group 'nnmail-split
451   :type '(repeat (cons :format "%v" symbol regexp)))
452
453 (defcustom nnmail-message-id-cache-length 1000
454   "*The approximate number of Message-IDs nnmail will keep in its cache.
455 If this variable is nil, no checking on duplicate messages will be
456 performed."
457   :group 'nnmail-duplicate
458   :type '(choice (const :tag "disable" nil)
459                  (integer :format "%v")))
460
461 (defcustom nnmail-message-id-cache-file "~/.nnmail-cache"
462   "*The file name of the nnmail Message-ID cache."
463   :group 'nnmail-duplicate
464   :group 'nnmail-files
465   :type 'file)
466
467 (defcustom nnmail-treat-duplicates 'warn
468   "*If non-nil, nnmail keep a cache of Message-IDs to discover mail duplicates.
469 Three values are valid: nil, which means that nnmail is not to keep a
470 Message-ID cache; `warn', which means that nnmail should insert extra
471 headers to warn the user about the duplication (this is the default);
472 and `delete', which means that nnmail will delete duplicated mails.
473
474 This variable can also be a function.  It will be called from a buffer
475 narrowed to the article in question with the Message-ID as a
476 parameter.  It should return nil, `warn' or `delete'."
477   :group 'nnmail-duplicate
478   :type '(choice (const :tag "off" nil)
479                  (const warn)
480                  (const delete)))
481
482 (defcustom nnmail-extra-headers '(To Newsgroups)
483   "*Extra headers to parse."
484   :version "21.1"
485   :group 'nnmail
486   :type '(repeat symbol))
487
488 (defcustom nnmail-split-header-length-limit 512
489   "Header lines longer than this limit are excluded from the split function."
490   :version "21.1"
491   :group 'nnmail
492   :type 'integer)
493
494 (defcustom nnmail-mail-splitting-charset nil
495   "Default charset to be used when splitting incoming mail."
496   :group 'nnmail
497   :type 'symbol)
498
499 (defcustom nnmail-mail-splitting-decodes t
500   "Whether the nnmail splitting functionality should MIME decode headers."
501   :group 'nnmail
502   :type 'boolean)
503
504 ;;; Internal variables.
505
506 (defvar nnmail-article-buffer " *nnmail incoming*"
507   "The buffer used for splitting incoming mails.")
508
509 (defvar nnmail-split-history nil
510   "List of group/article elements that say where the previous split put messages.")
511
512 (defvar nnmail-split-fancy-syntax-table nil
513   "Syntax table used by `nnmail-split-fancy'.")
514 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
515   (setq nnmail-split-fancy-syntax-table
516         (copy-syntax-table (standard-syntax-table)))
517   ;; support the %-hack
518   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
519
520 (defvar nnmail-prepare-save-mail-hook nil
521   "Hook called before saving mail.")
522
523 (defvar nnmail-split-tracing nil)
524 (defvar nnmail-split-trace nil)
525
526 \f
527
528 (defconst nnmail-version "nnmail 1.0"
529   "nnmail version.")
530
531 \f
532
533 (defun nnmail-request-post (&optional server)
534   (mail-send-and-exit nil))
535
536 (defvar nnmail-file-coding-system 'raw-text
537   "Coding system used in nnmail.")
538
539 (defvar nnmail-incoming-coding-system
540   nnheader-text-coding-system
541   "Coding system used in reading inbox")
542
543 (defvar nnmail-pathname-coding-system nil
544   "*Coding system for file name.")
545
546 (defun nnmail-find-file (file)
547   "Insert FILE in server buffer safely."
548   (set-buffer nntp-server-buffer)
549   (delete-region (point-min) (point-max))
550   (let ((format-alist nil)
551         (after-insert-file-functions nil))
552     (condition-case ()
553         (let ((auto-mode-alist (nnheader-auto-mode-alist))
554               (file-name-coding-system nnmail-pathname-coding-system)
555               (pathname-coding-system nnmail-pathname-coding-system))
556           (insert-file-contents-as-coding-system
557            nnmail-file-coding-system file)
558           t)
559       (file-error nil))))
560
561 (defun nnmail-group-pathname (group dir &optional file)
562   "Make file name for GROUP."
563   (concat
564    (let ((dir (file-name-as-directory (expand-file-name dir))))
565      (setq group (nnheader-replace-duplicate-chars-in-string
566                   (nnheader-replace-chars-in-string group ?/ ?_)
567                   ?. ?_))
568      (setq group (nnheader-translate-file-chars group))
569      ;; If this directory exists, we use it directly.
570      (file-name-as-directory
571       (if (or nnmail-use-long-file-names
572               (file-directory-p (concat dir group)))
573           (expand-file-name group dir)
574         ;; If not, we translate dots into slashes.
575         (expand-file-name
576          (encode-coding-string
577           (nnheader-replace-chars-in-string group ?. ?/)
578           nnmail-pathname-coding-system)
579          dir))))
580    (or file "")))
581
582 (defun nnmail-get-active ()
583   "Returns an assoc of group names and active ranges.
584 nn*-request-list should have been called before calling this function."
585   ;; Go through all groups from the active list.
586   (save-excursion
587     (set-buffer nntp-server-buffer)
588     (nnmail-parse-active)))
589
590 (defun nnmail-parse-active ()
591   "Parse the active file in the current buffer and return an alist."
592   (goto-char (point-min))
593   (unless (re-search-forward "[\\\"]" nil t)
594     (goto-char (point-max))
595     (while (re-search-backward "[][';?()#]" nil t)
596       (insert ?\\)))
597   (goto-char (point-min))
598   (let ((buffer (current-buffer))
599         group-assoc group max min)
600     (while (not (eobp))
601       (condition-case err
602           (progn
603             (narrow-to-region (point) (gnus-point-at-eol))
604             (setq group (read buffer))
605             (unless (stringp group)
606               (setq group (symbol-name group)))
607             (if (and (numberp (setq max (read buffer)))
608                      (numberp (setq min (read buffer))))
609                 (push (list group (cons min max))
610                       group-assoc)))
611         (error nil))
612       (widen)
613       (forward-line 1))
614     group-assoc))
615
616 (defvar nnmail-active-file-coding-system 'raw-text
617   "*Coding system for active file.")
618
619 (defun nnmail-save-active (group-assoc file-name)
620   "Save GROUP-ASSOC in ACTIVE-FILE."
621   (let ((coding-system-for-write nnmail-active-file-coding-system)
622         (output-coding-system 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 ((nnheader-file-coding-system nnmail-incoming-coding-system))
979         (nnheader-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           (mime-decode-header-in-region (point-min) (point-max)
1029                                         nnmail-mail-splitting-charset))
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                       (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]: +" nil t)
1191         (delete-region (match-beginning 1) (match-end 1))
1192         (beginning-of-line)))))
1193
1194 (defun nnmail-remove-tabs ()
1195   "Translate TAB characters into SPACE characters."
1196   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1197
1198 (defun nnmail-fix-eudora-headers ()
1199   "Eudora has a broken References line, but an OK In-Reply-To."
1200   (goto-char (point-min))
1201   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1202     (goto-char (point-min))
1203     (when (re-search-forward "^References:" nil t)
1204       (beginning-of-line)
1205       (insert "X-Gnus-Broken-Eudora-"))
1206     (goto-char (point-min))
1207     (when (re-search-forward "^\\(In-Reply-To:[^\n]+\\)\n[ \t]+" nil t)
1208       (replace-match "\\1" t))))
1209
1210 (custom-add-option 'nnmail-prepare-incoming-header-hook
1211                    'nnmail-fix-eudora-headers)
1212
1213 ;;; Utility functions
1214
1215 (defun nnmail-do-request-post (accept-func &optional server)
1216   "Utility function to directly post a message to an nnmail-derived group.
1217 Calls ACCEPT-FUNC (which should be `nnchoke-request-accept-article')
1218 to actually put the message in the right group."
1219   (let ((success t))
1220     (dolist (mbx (message-unquote-tokens
1221                   (message-tokenize-header
1222                    (message-fetch-field "Newsgroups") ", ")) success)
1223       (let ((to-newsgroup (gnus-group-prefixed-name mbx gnus-command-method)))
1224         (or (gnus-active to-newsgroup)
1225             (gnus-activate-group to-newsgroup)
1226             (if (gnus-y-or-n-p (format "No such group: %s.  Create it? "
1227                                        to-newsgroup))
1228                 (or (and (gnus-request-create-group
1229                           to-newsgroup gnus-command-method)
1230                          (gnus-activate-group to-newsgroup nil nil
1231                                               gnus-command-method))
1232                     (error "Couldn't create group %s" to-newsgroup)))
1233             (error "No such group: %s" to-newsgroup))
1234         (unless (funcall accept-func mbx (nth 1 gnus-command-method))
1235           (setq success nil))))))
1236
1237 (defun nnmail-split-fancy ()
1238   "Fancy splitting method.
1239 See the documentation for the variable `nnmail-split-fancy' for details."
1240   (let ((syntab (syntax-table)))
1241     (unwind-protect
1242         (progn
1243           (set-syntax-table nnmail-split-fancy-syntax-table)
1244           (nnmail-split-it nnmail-split-fancy))
1245       (set-syntax-table syntab))))
1246
1247 (defvar nnmail-split-cache nil)
1248 ;; Alist of split expressions their equivalent regexps.
1249
1250 (defun nnmail-split-it (split)
1251   ;; Return a list of groups matching SPLIT.
1252   (let (cached-pair)
1253     (cond
1254      ;; nil split
1255      ((null split)
1256       nil)
1257
1258      ;; A group name.  Do the \& and \N subs into the string.
1259      ((stringp split)
1260       (when nnmail-split-tracing
1261         (push split nnmail-split-trace))
1262       (list (nnmail-expand-newtext split)))
1263
1264      ;; Junk the message.
1265      ((eq split 'junk)
1266       (when nnmail-split-tracing
1267         (push "junk" nnmail-split-trace))
1268       (list 'junk))
1269
1270      ;; Builtin & operation.
1271      ((eq (car split) '&)
1272       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1273
1274      ;; Builtin | operation.
1275      ((eq (car split) '|)
1276       (let (done)
1277         (while (and (not done) (cdr split))
1278           (setq split (cdr split)
1279                 done (nnmail-split-it (car split))))
1280         done))
1281
1282      ;; Builtin : operation.
1283      ((eq (car split) ':)
1284       (when nnmail-split-tracing
1285         (push split nnmail-split-trace))
1286       (nnmail-split-it (save-excursion (eval (cdr split)))))
1287
1288      ;; Builtin ! operation.
1289      ((eq (car split) '!)
1290       (funcall (cadr split) (nnmail-split-it (caddr split))))
1291
1292      ;; Check the cache for the regexp for this split.
1293      ((setq cached-pair (assq split nnmail-split-cache))
1294       (let (split-result
1295             (end-point (point-max))
1296             (value (nth 1 split)))
1297         (if (symbolp value)
1298             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1299         (while (and (goto-char end-point)
1300                     (re-search-backward (cdr cached-pair) nil t))
1301           (when nnmail-split-tracing
1302             (push split nnmail-split-trace))
1303           (let ((split-rest (cddr split))
1304                 (end (match-end 0))
1305                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).  So,
1306                 ;; start-of-value is the the point just before the
1307                 ;; beginning of the value, whereas after-header-name is
1308                 ;; the point just after the field name.
1309                 (start-of-value (match-end 1))
1310                 (after-header-name (match-end 2)))
1311             ;; Start the next search just before the beginning of the
1312             ;; VALUE match.
1313             (setq end-point (1- start-of-value))
1314             ;; Handle - RESTRICTs
1315             (while (eq (car split-rest) '-)
1316               ;; RESTRICT must start after-header-name and
1317               ;; end after start-of-value, so that, for
1318               ;; (any "foo" - "x-foo" "foo.list")
1319               ;; we do not exclude foo.list just because
1320               ;; the header is: ``To: x-foo, foo''
1321               (goto-char end)
1322               (if (and (re-search-backward (cadr split-rest)
1323                                            after-header-name t)
1324                        (> (match-end 0) start-of-value))
1325                   (setq split-rest nil)
1326                 (setq split-rest (cddr split-rest))))
1327             (when split-rest
1328               (goto-char end)
1329               (let ((value (nth 1 split)))
1330                 (if (symbolp value)
1331                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1332                 ;; Someone might want to do a \N sub on this match, so get the
1333                 ;; correct match positions.
1334                 (re-search-backward value start-of-value))
1335               (dolist (sp (nnmail-split-it (car split-rest)))
1336                 (unless (member sp split-result)
1337                   (push sp split-result))))))
1338         split-result))
1339
1340      ;; Not in cache, compute a regexp for the field/value pair.
1341      (t
1342       (let* ((field (nth 0 split))
1343              (value (nth 1 split))
1344              partial-front regexp
1345              partial-rear  regexp)
1346         (if (symbolp value)
1347             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1348         (if (and (>= (length value) 2)
1349                  (string= ".*" (substring value 0 2)))
1350             (setq value (substring value 2)
1351                   partial-front ""))
1352         ;; Same trick for the rear of the regexp
1353         (if (and (>= (length value) 2)
1354                  (string= ".*" (substring value -2)))
1355             (setq value (substring value 0 -2)
1356                   partial-rear ""))
1357         (setq regexp (concat "^\\(\\("
1358                              (if (symbolp field)
1359                                  (cdr (assq field nnmail-split-abbrev-alist))
1360                                field)
1361                              "\\):.*\\)"
1362                              (or partial-front "\\<")
1363                              "\\("
1364                              value
1365                              "\\)"
1366                              (or partial-rear "\\>")))
1367         (push (cons split regexp) nnmail-split-cache)
1368         ;; Now that it's in the cache, just call nnmail-split-it again
1369         ;; on the same split, which will find it immediately in the cache.
1370         (nnmail-split-it split))))))
1371
1372 (defun nnmail-expand-newtext (newtext)
1373   (let ((len (length newtext))
1374         (pos 0)
1375         c expanded beg N did-expand)
1376     (while (< pos len)
1377       (setq beg pos)
1378       (while (and (< pos len)
1379                   (not (= (aref newtext pos) ?\\)))
1380         (setq pos (1+ pos)))
1381       (unless (= beg pos)
1382         (push (substring newtext beg pos) expanded))
1383       (when (< pos len)
1384         ;; We hit a \; expand it.
1385         (setq did-expand t
1386               pos (1+ pos)
1387               c (aref newtext pos))
1388         (if (not (or (= c ?\&)
1389                      (and (>= c ?1)
1390                           (<= c ?9))))
1391             ;; \ followed by some character we don't expand.
1392             (push (char-to-string c) expanded)
1393           ;; \& or \N
1394           (if (= c ?\&)
1395               (setq N 0)
1396             (setq N (- c ?0)))
1397           (when (match-beginning N)
1398             (push (buffer-substring (match-beginning N) (match-end N))
1399                   expanded))))
1400       (setq pos (1+ pos)))
1401     (if did-expand
1402         (apply 'concat (nreverse expanded))
1403       newtext)))
1404
1405 ;; Activate a backend only if it isn't already activated.
1406 ;; If FORCE, re-read the active file even if the backend is
1407 ;; already activated.
1408 (defun nnmail-activate (backend &optional force)
1409   (nnheader-init-server-buffer)
1410   (let (file timestamp file-time)
1411     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1412             force
1413             (and (setq file (ignore-errors
1414                               (symbol-value (intern (format "%s-active-file"
1415                                                             backend)))))
1416                  (setq file-time (nth 5 (file-attributes file)))
1417                  (or (not
1418                       (setq timestamp
1419                             (condition-case ()
1420                                 (symbol-value (intern
1421                                                (format "%s-active-timestamp"
1422                                                        backend)))
1423                               (error 'none))))
1424                      (not (consp timestamp))
1425                      (equal timestamp '(0 0))
1426                      (> (nth 0 file-time) (nth 0 timestamp))
1427                      (and (= (nth 0 file-time) (nth 0 timestamp))
1428                           (> (nth 1 file-time) (nth 1 timestamp))))))
1429         (save-excursion
1430           (or (eq timestamp 'none)
1431               (set (intern (format "%s-active-timestamp" backend))
1432                    file-time))
1433           (funcall (intern (format "%s-request-list" backend)))))
1434     t))
1435
1436 (defun nnmail-message-id ()
1437   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1438
1439 ;;;
1440 ;;; nnmail duplicate handling
1441 ;;;
1442
1443 (defvar nnmail-cache-buffer nil)
1444
1445 (defun nnmail-cache-open ()
1446   (if (or (not nnmail-treat-duplicates)
1447           (and nnmail-cache-buffer
1448                (buffer-name nnmail-cache-buffer)))
1449       ()                                ; The buffer is open.
1450     (save-excursion
1451       (set-buffer
1452        (setq nnmail-cache-buffer
1453              (get-buffer-create " *nnmail message-id cache*")))
1454       (gnus-add-buffer)
1455       (when (file-exists-p nnmail-message-id-cache-file)
1456         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1457       (set-buffer-modified-p nil)
1458       (current-buffer))))
1459
1460 (defun nnmail-cache-close ()
1461   (when (and nnmail-cache-buffer
1462              nnmail-treat-duplicates
1463              (buffer-name nnmail-cache-buffer)
1464              (buffer-modified-p nnmail-cache-buffer))
1465     (save-excursion
1466       (set-buffer nnmail-cache-buffer)
1467       ;; Weed out the excess number of Message-IDs.
1468       (goto-char (point-max))
1469       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1470         (progn
1471           (beginning-of-line)
1472           (delete-region (point-min) (point))))
1473       ;; Save the buffer.
1474       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1475           (make-directory (file-name-directory nnmail-message-id-cache-file)
1476                           t))
1477       (nnmail-write-region (point-min) (point-max)
1478                            nnmail-message-id-cache-file nil 'silent)
1479       (set-buffer-modified-p nil)
1480       (setq nnmail-cache-buffer nil)
1481       (gnus-kill-buffer (current-buffer)))))
1482
1483 ;; Compiler directives.
1484 (defvar group)
1485 (defvar group-art-list)
1486 (defvar group-art)
1487 (defun nnmail-cache-insert (id grp)
1488   (run-hook-with-args 'nnmail-spool-hook 
1489                       id grp)
1490   (when nnmail-treat-duplicates
1491     ;; Store some information about the group this message is written
1492     ;; to.  This is passed in as the grp argument -- all locations this
1493     ;; has been called from have been checked and the group is available.
1494     ;; The only ambiguous case is nnmail-check-duplication which will only
1495     ;; pass the first (of possibly >1) group which matches. -Josh
1496     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1497       (nnmail-cache-open))
1498     (save-excursion
1499       (set-buffer nnmail-cache-buffer)
1500       (goto-char (point-max))
1501       (if (and grp (not (string= "" grp))
1502                (gnus-methods-equal-p gnus-command-method
1503                                      (nnmail-cache-primary-mail-backend)))
1504           (let ((regexp (if (consp nnmail-cache-ignore-groups)
1505                             (mapconcat 'identity nnmail-cache-ignore-groups
1506                                        "\\|")
1507                           nnmail-cache-ignore-groups)))
1508             (unless (and regexp (string-match regexp grp))
1509               (insert id "\t" grp "\n")))
1510         (insert id "\n")))))
1511
1512 (defun nnmail-cache-primary-mail-backend ()
1513   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1514         (be nil)
1515         (res nil)
1516         (get-new-mail nil))
1517     (while (and (null res) be-list)
1518       (setq be (car be-list))
1519       (setq be-list (cdr be-list))
1520       (when (and (gnus-method-option-p be 'respool)
1521                  (setq get-new-mail
1522                        (intern (format "%s-get-new-mail" (car be))))
1523                  (boundp get-new-mail)
1524                  (symbol-value get-new-mail))
1525         (setq res be)))
1526     res))
1527
1528 ;; Fetch the group name corresponding to the message id stored in the
1529 ;; cache.
1530 (defun nnmail-cache-fetch-group (id)
1531   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1532     (save-excursion
1533       (set-buffer nnmail-cache-buffer)
1534       (goto-char (point-max))
1535       (when (search-backward id nil t)
1536         (beginning-of-line)
1537         (skip-chars-forward "^\n\r\t")
1538         (unless (looking-at "[\r\n]")
1539           (forward-char 1)
1540           (buffer-substring (point) (gnus-point-at-eol)))))))
1541
1542 ;; Function for nnmail-split-fancy: look up all references in the
1543 ;; cache and if a match is found, return that group.
1544 (defun nnmail-split-fancy-with-parent ()
1545   "Split this message into the same group as its parent.
1546 This function can be used as an entry in `nnmail-split-fancy', for
1547 example like this: (: nnmail-split-fancy)
1548 For a message to be split, it looks for the parent message in the
1549 References or In-Reply-To header and then looks in the message id
1550 cache file (given by the variable `nnmail-message-id-cache-file') to
1551 see which group that message was put in.  This group is returned.
1552
1553 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1554   (let* ((refstr (or (message-fetch-field "references")
1555                      (message-fetch-field "in-reply-to")))
1556          (references nil)
1557          (res nil)
1558          (regexp (if (consp nnmail-split-fancy-with-parent-ignore-groups)
1559                      (mapconcat
1560                       (lambda (x) (format "\\(%s\\)" x))
1561                       nnmail-split-fancy-with-parent-ignore-groups
1562                       "\\|")
1563                    nnmail-split-fancy-with-parent-ignore-groups)))
1564     (when refstr
1565       (setq references (nreverse (gnus-split-references refstr)))
1566       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1567         (nnmail-cache-open))
1568       (mapcar (lambda (x)
1569                 (setq res (or (nnmail-cache-fetch-group x) res))
1570                 (when (or (member res '("delayed" "drafts" "queue"))
1571                           (and regexp res (string-match regexp res)))
1572                   (setq res nil)))
1573               references)
1574       res)))
1575
1576 (defun nnmail-cache-id-exists-p (id)
1577   (when nnmail-treat-duplicates
1578     (save-excursion
1579       (set-buffer nnmail-cache-buffer)
1580       (goto-char (point-max))
1581       (search-backward id nil t))))
1582
1583 (defun nnmail-fetch-field (header)
1584   (save-excursion
1585     (save-restriction
1586       (message-narrow-to-head)
1587       (message-fetch-field header))))
1588
1589 (defun nnmail-check-duplication (message-id func artnum-func)
1590   (run-hooks 'nnmail-prepare-incoming-message-hook)
1591   ;; If this is a duplicate message, then we do not save it.
1592   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1593          (case-fold-search t)
1594          (action (when duplication
1595                    (cond
1596                     ((memq nnmail-treat-duplicates '(warn delete))
1597                      nnmail-treat-duplicates)
1598                     ((nnheader-functionp nnmail-treat-duplicates)
1599                      (funcall nnmail-treat-duplicates message-id))
1600                     (t
1601                      nnmail-treat-duplicates))))
1602          group-art)
1603     ;; We insert a line that says what the mail source is.
1604     (let ((case-fold-search t))
1605       (goto-char (point-min))
1606       (re-search-forward "^message-id[ \t]*:" nil t)
1607       (beginning-of-line)
1608       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1609
1610     ;; Let the backend save the article (or not).
1611     (cond
1612      ((not duplication)
1613       (funcall func (setq group-art
1614                           (nreverse (nnmail-article-group artnum-func))))
1615       (nnmail-cache-insert message-id (caar group-art)))
1616      ((eq action 'delete)
1617       (setq group-art nil))
1618      ((eq action 'warn)
1619       ;; We insert a warning.
1620       (let ((case-fold-search t))
1621         (goto-char (point-min))
1622         (re-search-forward "^message-id[ \t]*:" nil t)
1623         (beginning-of-line)
1624         (insert
1625          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1626         (funcall func (setq group-art
1627                             (nreverse (nnmail-article-group artnum-func))))))
1628      (t
1629       (funcall func (setq group-art
1630                           (nreverse (nnmail-article-group artnum-func))))))
1631     ;; Add the group-art list to the history list.
1632     (if group-art
1633         (push group-art nnmail-split-history)
1634       (delete-region (point-min) (point-max)))))
1635
1636 ;;; Get new mail.
1637
1638 (defvar nnmail-fetched-sources nil)
1639
1640 (defun nnmail-get-value (&rest args)
1641   (let ((sym (intern (apply 'format args))))
1642     (when (boundp sym)
1643       (symbol-value sym))))
1644
1645 (defun nnmail-get-new-mail (method exit-func temp
1646                                    &optional group spool-func)
1647   "Read new incoming mail."
1648   (let* ((sources (or mail-sources
1649                       (if (listp nnmail-spool-file) nnmail-spool-file
1650                         (list nnmail-spool-file))))
1651          fetching-sources
1652          (group-in group)
1653          (i 0)
1654          (new 0)
1655          (total 0)
1656          incoming incomings source)
1657     (when (and (nnmail-get-value "%s-get-new-mail" method)
1658                sources)
1659       (while (setq source (pop sources))
1660         ;; Be compatible with old values.
1661         (cond
1662          ((stringp source)
1663           (setq source
1664                 (cond
1665                  ((string-match "^po:" source)
1666                   (list 'pop :user (substring source (match-end 0))))
1667                  ((file-directory-p source)
1668                   (list 'directory :path source))
1669                  (t
1670                   (list 'file :path source)))))
1671          ((eq source 'procmail)
1672           (message "Invalid value for nnmail-spool-file: `procmail'")
1673           nil))
1674         ;; Hack to only fetch the contents of a single group's spool file.
1675         (when (and (eq (car source) 'directory)
1676                    (null nnmail-scan-directory-mail-source-once)
1677                    group)
1678           (mail-source-bind (directory source)
1679             (setq source (append source
1680                                  (list
1681                                   :predicate
1682                                   (gnus-byte-compile
1683                                    `(lambda (file)
1684                                       (string-equal
1685                                        ,(concat group suffix)
1686                                        (file-name-nondirectory file)))))))))
1687         (when nnmail-fetched-sources
1688           (if (member source nnmail-fetched-sources)
1689               (setq source nil)
1690             (push source nnmail-fetched-sources)
1691             (push source fetching-sources)))))
1692     (when fetching-sources
1693       ;; We first activate all the groups.
1694       (nnmail-activate method)
1695       ;; Allow the user to hook.
1696       (run-hooks 'nnmail-pre-get-new-mail-hook)
1697       ;; Open the message-id cache.
1698       (nnmail-cache-open)
1699       ;; The we go through all the existing mail source specification
1700       ;; and fetch the mail from each.
1701       (while (setq source (pop fetching-sources))
1702         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1703                           method (car source))
1704         (when (setq new
1705                     (mail-source-fetch
1706                      source
1707                      (gnus-byte-compile
1708                       `(lambda (file orig-file)
1709                          (nnmail-split-incoming
1710                           file ',(intern (format "%s-save-mail" method))
1711                           ',spool-func
1712                           (if (equal file orig-file)
1713                               nil
1714                             (nnmail-get-split-group orig-file ',source))
1715                           ',(intern (format "%s-active-number" method)))))))
1716           (incf total new)
1717           (incf i)))
1718       ;; If we did indeed read any incoming spools, we save all info.
1719       (if (zerop total)
1720           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1721                             method (car source))
1722         (nnmail-save-active
1723          (nnmail-get-value "%s-group-alist" method)
1724          (nnmail-get-value "%s-active-file" method))
1725         (when exit-func
1726           (funcall exit-func))
1727         (run-hooks 'nnmail-read-incoming-hook)
1728         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1729                           total))
1730       ;; Close the message-id cache.
1731       (nnmail-cache-close)
1732       ;; Allow the user to hook.
1733       (run-hooks 'nnmail-post-get-new-mail-hook))))
1734
1735 (defun nnmail-expired-article-p (group time force &optional inhibit)
1736   "Say whether an article that is TIME old in GROUP should be expired."
1737   (if force
1738       t
1739     (let ((days (or (and nnmail-expiry-wait-function
1740                          (funcall nnmail-expiry-wait-function group))
1741                     nnmail-expiry-wait)))
1742       (cond ((or (eq days 'never)
1743                  (and (not force)
1744                       inhibit))
1745              ;; This isn't an expirable group.
1746              nil)
1747             ((eq days 'immediate)
1748              ;; We expire all articles on sight.
1749              t)
1750             ((equal time '(0 0))
1751              ;; This is an ange-ftp group, and we don't have any dates.
1752              nil)
1753             ((numberp days)
1754              (setq days (days-to-time days))
1755              ;; Compare the time with the current time.
1756              (ignore-errors (time-less-p days (time-since time))))))))
1757
1758 (defun nnmail-expiry-target-group (target group)
1759   ;; Do not invoke this from nntp-server-buffer!  At least nnfolder clears
1760   ;; that buffer if the nnfolder group isn't selected.
1761   (let (nnmail-cache-accepted-message-ids)
1762     ;; Don't enter Message-IDs into cache.
1763     ;; Let users hack it in TARGET function.
1764     (when (nnheader-functionp target)
1765       (setq target (funcall target group)))
1766     (unless (eq target 'delete)
1767       (when (or (gnus-request-group target)
1768                 (gnus-request-create-group target))
1769         (let ((group-art (gnus-request-accept-article target nil nil t)))
1770           (when (consp group-art)
1771             (gnus-group-mark-article-read target (cdr group-art))))))))
1772
1773 (defun nnmail-fancy-expiry-target (group)
1774   "Returns a target expiry group determined by `nnmail-fancy-expiry-targets'."
1775   (let* (header
1776          (case-fold-search nil)
1777          (from (or (message-fetch-field "from") ""))
1778          (to (or (message-fetch-field "to") ""))
1779          (date (date-to-time
1780                 (or (message-fetch-field "date") (current-time-string))))
1781          (target 'delete))
1782     (dolist (regexp-target-pair (reverse nnmail-fancy-expiry-targets) target)
1783       (setq header (car regexp-target-pair))
1784       (cond
1785        ;; If the header is to-from then match against the
1786        ;; To or From header
1787        ((and (equal header 'to-from)
1788              (or (string-match (cadr regexp-target-pair) from)
1789                  (and (string-match message-dont-reply-to-names from)
1790                       (string-match (cadr regexp-target-pair) to))))
1791         (setq target (format-time-string (caddr regexp-target-pair) date)))
1792        ((and (not (equal header 'to-from))
1793              (string-match (cadr regexp-target-pair)
1794                            (or
1795                             (message-fetch-field header)
1796                             "")))
1797         (setq target
1798               (format-time-string (caddr regexp-target-pair) date)))))))
1799
1800 (defun nnmail-check-syntax ()
1801   "Check (and modify) the syntax of the message in the current buffer."
1802   (save-restriction
1803     (message-narrow-to-head)
1804     (let ((case-fold-search t))
1805       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1806         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1807
1808 (defun nnmail-write-region (start end filename &optional append visit lockname)
1809   "Do a `write-region', and then set the file modes."
1810   (let ((file-name-coding-system nnmail-pathname-coding-system)
1811         (pathname-coding-system nnmail-pathname-coding-system))
1812     (write-region-as-coding-system
1813      nnmail-file-coding-system 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-new-mail-numbers (group)
1912   "Say how many articles has been incorporated to GROUP."
1913   (let ((his (apply 'append nnmail-split-history))
1914         numbers)
1915     (while his
1916       (when (string= group (caar his))
1917         (push (cdar his) numbers))
1918       (setq his (cdr his)))
1919     numbers))
1920
1921 (defun nnmail-within-headers-p ()
1922   "Check to see if point is within the headers of a unix mail message.
1923 Doesn't change point."
1924   (let ((pos (point)))
1925     (save-excursion
1926       (and (nnmail-search-unix-mail-delim-backward)
1927            (not (search-forward "\n\n" pos t))))))
1928
1929 (run-hooks 'nnmail-load-hook)
1930
1931 (provide 'nnmail)
1932
1933 ;;; nnmail.el ends here