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