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