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