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