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