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