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