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