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