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