Synch with Oort Gnus.
[elisp/gnus.git-] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (require 'nnheader)
32 (require 'message)
33 (require 'custom)
34 (require 'gnus-util)
35 (require 'mail-source)
36
37 (eval-and-compile
38   (autoload 'gnus-error "gnus-util")
39   (autoload 'gnus-buffer-live-p "gnus-util"))
40
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-article-buffer " *nnmail incoming*"
436   "The buffer used for splitting incoming mails.")
437
438 (defvar nnmail-split-history nil
439   "List of group/article elements that say where the previous split put messages.")
440
441 (defvar nnmail-split-fancy-syntax-table nil
442   "Syntax table used by `nnmail-split-fancy'.")
443 (unless (syntax-table-p nnmail-split-fancy-syntax-table)
444   (setq nnmail-split-fancy-syntax-table
445         (copy-syntax-table (standard-syntax-table)))
446   ;; support the %-hack
447   (modify-syntax-entry ?\% "." nnmail-split-fancy-syntax-table))
448
449 (defvar nnmail-prepare-save-mail-hook nil
450   "Hook called before saving mail.")
451
452 (defvar nnmail-split-tracing nil)
453 (defvar nnmail-split-trace nil)
454
455 \f
456
457 (defconst nnmail-version "nnmail 1.0"
458   "nnmail version.")
459
460 \f
461
462 (defun nnmail-request-post (&optional server)
463   (mail-send-and-exit nil))
464
465 (defvar nnmail-file-coding-system 'raw-text
466   "Coding system used in nnmail.")
467
468 (defvar nnmail-incoming-coding-system
469   nnheader-text-coding-system
470   "Coding system used in reading inbox")
471
472 (defvar nnmail-pathname-coding-system 'binary
473   "*Coding system for pathname.")
474
475 (defun nnmail-find-file (file)
476   "Insert FILE in server buffer safely."
477   (set-buffer nntp-server-buffer)
478   (delete-region (point-min) (point-max))
479   (let ((format-alist nil)
480         (after-insert-file-functions nil))
481     (condition-case ()
482         (let ((auto-mode-alist (nnheader-auto-mode-alist))
483               (file-name-coding-system nnmail-pathname-coding-system)
484               (pathname-coding-system nnmail-pathname-coding-system))
485           (insert-file-contents-as-coding-system
486            nnmail-file-coding-system file)
487           t)
488       (file-error nil))))
489
490 (defun nnmail-group-pathname (group dir &optional file)
491   "Make pathname for GROUP."
492   (concat
493    (let ((dir (file-name-as-directory (expand-file-name dir))))
494      (setq group (nnheader-replace-duplicate-chars-in-string
495                   (nnheader-replace-chars-in-string group ?/ ?_)
496                   ?. ?_))
497      (setq group (nnheader-translate-file-chars group))
498      ;; If this directory exists, we use it directly.
499      (file-name-as-directory
500       (if (or nnmail-use-long-file-names
501               (file-directory-p (concat dir group)))
502           (expand-file-name group dir)
503         ;; If not, we translate dots into slashes.
504         (expand-file-name
505          (encode-coding-string
506           (nnheader-replace-chars-in-string group ?. ?/)
507           nnmail-pathname-coding-system)
508          dir))))
509    (or file "")))
510
511 (defun nnmail-get-active ()
512   "Returns an assoc of group names and active ranges.
513 nn*-request-list should have been called before calling this function."
514   ;; Go through all groups from the active list.
515   (save-excursion
516     (set-buffer nntp-server-buffer)
517     (nnmail-parse-active)))
518
519 (defun nnmail-parse-active ()
520   "Parse the active file in the current buffer and return an alist."
521   (goto-char (point-min))
522   (unless (re-search-forward "[\\\"]" nil t)
523     (goto-char (point-max))
524     (while (re-search-backward "[][';?()#]" nil t)
525       (insert ?\\)))
526   (goto-char (point-min))
527   (let ((buffer (current-buffer))
528         group-assoc group max min)
529     (while (not (eobp))
530       (condition-case err
531           (progn
532             (narrow-to-region (point) (gnus-point-at-eol))
533             (setq group (read buffer))
534             (unless (stringp group)
535               (setq group (symbol-name group)))
536             (if (and (numberp (setq max (read nntp-server-buffer)))
537                      (numberp (setq min (read nntp-server-buffer))))
538                 (push (list group (cons min max))
539                       group-assoc)))
540         (error nil))
541       (widen)
542       (forward-line 1))
543     group-assoc))
544
545 (defvar nnmail-active-file-coding-system 'raw-text
546   "*Coding system for active file.")
547
548 (defun nnmail-save-active (group-assoc file-name)
549   "Save GROUP-ASSOC in ACTIVE-FILE."
550   (let ((coding-system-for-write nnmail-active-file-coding-system)
551         (output-coding-system nnmail-active-file-coding-system))
552     (when file-name
553       (with-temp-file file-name
554         (nnmail-generate-active group-assoc)))))
555
556 (defun nnmail-generate-active (alist)
557   "Generate an active file from group-alist ALIST."
558   (erase-buffer)
559   (let (group)
560     (while (setq group (pop alist))
561       (insert (format "%S %d %d y\n" (intern (car group)) (cdadr group)
562                       (caadr group))))
563     (goto-char (point-max))
564     (while (search-backward "\\." nil t)
565       (delete-char 1))))
566
567 (defun nnmail-get-split-group (file source)
568   "Find out whether this FILE is to be split into GROUP only.
569 If SOURCE is a directory spec, try to return the group name component."
570   (if (eq (car source) 'directory)
571       (let ((file (file-name-nondirectory file)))
572         (mail-source-bind (directory source)
573           (if (string-match (concat (regexp-quote suffix) "$") file)
574               (substring file 0 (match-beginning 0))
575             nil)))
576     nil))
577
578 (defun nnmail-process-babyl-mail-format (func artnum-func)
579   (let ((case-fold-search t)
580         (count 0)
581         start message-id content-length do-search end)
582     (while (not (eobp))
583       (goto-char (point-min))
584       (re-search-forward
585        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
586       (goto-char (match-end 0))
587       (delete-region (match-beginning 0) (match-end 0))
588       (narrow-to-region
589        (setq start (point))
590        (progn
591          ;; Skip all the headers in case there are more "From "s...
592          (or (search-forward "\n\n" nil t)
593              (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
594              (search-forward "\1f\f"))
595          (point)))
596       ;; Unquote the ">From " line, if any.
597       (goto-char (point-min))
598       (when (looking-at ">From ")
599         (replace-match "X-From-Line: ") )
600       (run-hooks 'nnmail-prepare-incoming-header-hook)
601       (goto-char (point-max))
602       ;; Find the Message-ID header.
603       (save-excursion
604         (if (re-search-backward
605              "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]*>\\)" nil t)
606             (setq message-id (buffer-substring (match-beginning 1)
607                                                (match-end 1)))
608           ;; There is no Message-ID here, so we create one.
609           (save-excursion
610             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
611               (beginning-of-line)
612               (insert "Original-")))
613           (forward-line -1)
614           (insert "Message-ID: " (setq message-id (nnmail-message-id))
615                   "\n")))
616       ;; Look for a Content-Length header.
617       (if (not (save-excursion
618                  (and (re-search-backward
619                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
620                       (setq content-length (string-to-int
621                                             (buffer-substring
622                                              (match-beginning 1)
623                                              (match-end 1))))
624                       ;; We destroy the header, since none of
625                       ;; the backends ever use it, and we do not
626                       ;; want to confuse other mailers by having
627                       ;; a (possibly) faulty header.
628                       (progn (insert "X-") t))))
629           (setq do-search t)
630         (widen)
631         (if (or (= (+ (point) content-length) (point-max))
632                 (save-excursion
633                   (goto-char (+ (point) content-length))
634                   (looking-at "\1f")))
635             (progn
636               (goto-char (+ (point) content-length))
637               (setq do-search nil))
638           (setq do-search t)))
639       (widen)
640       ;; Go to the beginning of the next article - or to the end
641       ;; of the buffer.
642       (when do-search
643         (if (re-search-forward "^\1f" nil t)
644             (goto-char (match-beginning 0))
645           (goto-char (1- (point-max)))))
646       (delete-char 1)                   ; delete ^_
647       (save-excursion
648         (save-restriction
649           (narrow-to-region start (point))
650           (goto-char (point-min))
651           (nnmail-check-duplication message-id func artnum-func)
652           (incf count)
653           (setq end (point-max))))
654       (goto-char end))
655     count))
656
657 (defsubst nnmail-search-unix-mail-delim ()
658   "Put point at the beginning of the next Unix mbox message."
659   ;; Algorithm used to find the the next article in the
660   ;; brain-dead Unix mbox format:
661   ;;
662   ;; 1) Search for "^From ".
663   ;; 2) If we find it, then see whether the previous
664   ;;    line is blank and the next line looks like a header.
665   ;; Then it's possible that this is a mail delim, and we use it.
666   (let ((case-fold-search nil)
667         found)
668     (while (not found)
669       (if (not (re-search-forward "^From " nil t))
670           (setq found 'no)
671         (save-excursion
672           (beginning-of-line)
673           (when (and (or (bobp)
674                          (save-excursion
675                            (forward-line -1)
676                            (eq (char-after) ?\n)))
677                      (save-excursion
678                        (forward-line 1)
679                        (while (looking-at ">From \\|From ")
680                          (forward-line 1))
681                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
682             (setq found 'yes)))))
683     (beginning-of-line)
684     (eq found 'yes)))
685
686 (defun nnmail-search-unix-mail-delim-backward ()
687   "Put point at the beginning of the current Unix mbox message."
688   ;; Algorithm used to find the the next article in the
689   ;; brain-dead Unix mbox format:
690   ;;
691   ;; 1) Search for "^From ".
692   ;; 2) If we find it, then see whether the previous
693   ;;    line is blank and the next line looks like a header.
694   ;; Then it's possible that this is a mail delim, and we use it.
695   (let ((case-fold-search nil)
696         found)
697     (while (not found)
698       (if (not (re-search-backward "^From " nil t))
699           (setq found 'no)
700         (save-excursion
701           (beginning-of-line)
702           (when (and (or (bobp)
703                          (save-excursion
704                            (forward-line -1)
705                            (eq (char-after) ?\n)))
706                      (save-excursion
707                        (forward-line 1)
708                        (while (looking-at ">From \\|From ")
709                          (forward-line 1))
710                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
711             (setq found 'yes)))))
712     (beginning-of-line)
713     (eq found 'yes)))
714
715 (defun nnmail-process-unix-mail-format (func artnum-func)
716   (let ((case-fold-search t)
717         (count 0)
718         start message-id content-length end skip head-end)
719     (goto-char (point-min))
720     (if (not (and (re-search-forward "^From " nil t)
721                   (goto-char (match-beginning 0))))
722         ;; Possibly wrong format?
723         (error "Error, unknown mail format! (Possibly corrupted.)")
724       ;; Carry on until the bitter end.
725       (while (not (eobp))
726         (setq start (point)
727               end nil)
728         ;; Find the end of the head.
729         (narrow-to-region
730          start
731          (if (search-forward "\n\n" nil t)
732              (1- (point))
733            ;; This will never happen, but just to be on the safe side --
734            ;; if there is no head-body delimiter, we search a bit manually.
735            (while (and (looking-at "From \\|[^ \t]+:")
736                        (not (eobp)))
737              (forward-line 1))
738            (point)))
739         ;; Find the Message-ID header.
740         (goto-char (point-min))
741         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
742             (setq message-id (match-string 1))
743           (save-excursion
744             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
745               (beginning-of-line)
746               (insert "Original-")))
747           ;; There is no Message-ID here, so we create one.
748           (forward-line 1)
749           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
750         ;; Look for a Content-Length header.
751         (goto-char (point-min))
752         (if (not (re-search-forward
753                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
754             (setq content-length nil)
755           (setq content-length (string-to-int (match-string 1)))
756           ;; We destroy the header, since none of the backends ever
757           ;; use it, and we do not want to confuse other mailers by
758           ;; having a (possibly) faulty header.
759           (beginning-of-line)
760           (insert "X-"))
761         (run-hooks 'nnmail-prepare-incoming-header-hook)
762         ;; Find the end of this article.
763         (goto-char (point-max))
764         (widen)
765         (setq head-end (point))
766         ;; We try the Content-Length value.  The idea: skip over the header
767         ;; separator, then check what happens content-length bytes into the
768         ;; message body.  This should be either the end ot the buffer, the
769         ;; message separator or a blank line followed by the separator.
770         ;; The blank line should probably be deleted.  If neither of the
771         ;; three is met, the content-length header is probably invalid.
772         (when content-length
773           (forward-line 1)
774           (setq skip (+ (point) content-length))
775           (goto-char skip)
776           (cond ((or (= skip (point-max))
777                      (= (1+ skip) (point-max)))
778                  (setq end (point-max)))
779                 ((looking-at "From ")
780                  (setq end skip))
781                 ((looking-at "[ \t]*\n\\(From \\)")
782                  (setq end (match-beginning 1)))
783                 (t (setq end nil))))
784         (if end
785             (goto-char end)
786           ;; No Content-Length, so we find the beginning of the next
787           ;; article or the end of the buffer.
788           (goto-char head-end)
789           (or (nnmail-search-unix-mail-delim)
790               (goto-char (point-max))))
791         ;; Allow the backend to save the article.
792         (save-excursion
793           (save-restriction
794             (narrow-to-region start (point))
795             (goto-char (point-min))
796             (incf count)
797             (nnmail-check-duplication message-id func artnum-func)
798             (setq end (point-max))))
799         (goto-char end)))
800     count))
801
802 (defun nnmail-process-mmdf-mail-format (func artnum-func)
803   (let ((delim "^\^A\^A\^A\^A$")
804         (case-fold-search t)
805         (count 0)
806         start message-id end)
807     (goto-char (point-min))
808     (if (not (and (re-search-forward delim nil t)
809                   (forward-line 1)))
810         ;; Possibly wrong format?
811         (error "Error, unknown mail format! (Possibly corrupted.)")
812       ;; Carry on until the bitter end.
813       (while (not (eobp))
814         (setq start (point))
815         ;; Find the end of the head.
816         (narrow-to-region
817          start
818          (if (search-forward "\n\n" nil t)
819              (1- (point))
820            ;; This will never happen, but just to be on the safe side --
821            ;; if there is no head-body delimiter, we search a bit manually.
822            (while (and (looking-at "From \\|[^ \t]+:")
823                        (not (eobp)))
824              (forward-line 1))
825            (point)))
826         ;; Find the Message-ID header.
827         (goto-char (point-min))
828         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
829             (setq message-id (match-string 1))
830           ;; There is no Message-ID here, so we create one.
831           (save-excursion
832             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
833               (beginning-of-line)
834               (insert "Original-")))
835           (forward-line 1)
836           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
837         (run-hooks 'nnmail-prepare-incoming-header-hook)
838         ;; Find the end of this article.
839         (goto-char (point-max))
840         (widen)
841         (if (re-search-forward delim nil t)
842             (beginning-of-line)
843           (goto-char (point-max)))
844         ;; Allow the backend to save the article.
845         (save-excursion
846           (save-restriction
847             (narrow-to-region start (point))
848             (goto-char (point-min))
849             (incf count)
850             (nnmail-check-duplication message-id func artnum-func)
851             (setq end (point-max))))
852         (goto-char end)
853         (forward-line 2)))
854     count))
855
856 (defun nnmail-process-maildir-mail-format (func artnum-func)
857   ;; In a maildir, every file contains exactly one mail.
858   (let ((case-fold-search t)
859         message-id)
860     (goto-char (point-min))
861     ;; Find the end of the head.
862     (narrow-to-region
863      (point-min)
864      (if (search-forward "\n\n" nil t)
865          (1- (point))
866        ;; This will never happen, but just to be on the safe side --
867        ;; if there is no head-body delimiter, we search a bit manually.
868        (while (and (looking-at "From \\|[^ \t]+:")
869                    (not (eobp)))
870          (forward-line 1))
871        (point)))
872     ;; Find the Message-ID header.
873     (goto-char (point-min))
874     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
875         (setq message-id (match-string 1))
876       ;; There is no Message-ID here, so we create one.
877       (save-excursion
878         (when (re-search-backward "^Message-ID[ \t]*:" nil t)
879           (beginning-of-line)
880           (insert "Original-")))
881       (forward-line 1)
882       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
883     (run-hooks 'nnmail-prepare-incoming-header-hook)
884     ;; Allow the backend to save the article.
885     (widen)
886     (save-excursion
887       (goto-char (point-min))
888       (nnmail-check-duplication message-id func artnum-func))
889     1))
890
891 (defun nnmail-split-incoming (incoming func &optional exit-func
892                                        group artnum-func)
893   "Go through the entire INCOMING file and pick out each individual mail.
894 FUNC will be called with the buffer narrowed to each mail."
895   (let (;; If this is a group-specific split, we bind the split
896         ;; methods to just this group.
897         (nnmail-split-methods (if (and group
898                                        (not nnmail-resplit-incoming))
899                                   (list (list group ""))
900                                 nnmail-split-methods)))
901     (save-excursion
902       ;; Insert the incoming file.
903       (set-buffer (get-buffer-create nnmail-article-buffer))
904       (erase-buffer)
905       (let ((nnheader-file-coding-system nnmail-incoming-coding-system))
906         (nnheader-insert-file-contents incoming))
907       (prog1
908           (if (zerop (buffer-size))
909               0
910             (goto-char (point-min))
911             (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
912             ;; Handle both babyl, MMDF and unix mail formats, since
913             ;; movemail will use the former when fetching from a
914             ;; mailbox, the latter when fetching from a file.
915             (cond ((or (looking-at "\^L")
916                        (looking-at "BABYL OPTIONS:"))
917                    (nnmail-process-babyl-mail-format func artnum-func))
918                   ((looking-at "\^A\^A\^A\^A")
919                    (nnmail-process-mmdf-mail-format func artnum-func))
920                   ((looking-at "Return-Path:")
921                    (nnmail-process-maildir-mail-format func artnum-func))
922                   (t
923                    (nnmail-process-unix-mail-format func artnum-func))))
924         (when exit-func
925           (funcall exit-func))
926         (kill-buffer (current-buffer))))))
927
928 (defun nnmail-article-group (func &optional trace)
929   "Look at the headers and return an alist of groups that match.
930 FUNC will be called with the group name to determine the article number."
931   (let ((methods nnmail-split-methods)
932         (obuf (current-buffer))
933         (beg (point-min))
934         end group-art method grp)
935     (if (and (sequencep methods)
936              (= (length methods) 1))
937         ;; If there is only just one group to put everything in, we
938         ;; just return a list with just this one method in.
939         (setq group-art
940               (list (cons (caar methods) (funcall func (caar methods)))))
941       ;; We do actual comparison.
942       (save-excursion
943         ;; Find headers.
944         (goto-char beg)
945         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
946         (set-buffer nntp-server-buffer)
947         (erase-buffer)
948         ;; Copy the headers into the work buffer.
949         (insert-buffer-substring obuf beg end)
950         ;; Fold continuation lines.
951         (goto-char (point-min))
952         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
953           (replace-match " " t t))
954         ;; Nuke pathologically long headers.  Since Gnus applies
955         ;; pathologically complex regexps to the buffer, lines
956         ;; that are looong will take longer than the Universe's
957         ;; existence to process.
958         (goto-char (point-min))
959         (while (not (eobp))
960           (unless (< (move-to-column nnmail-split-header-length-limit)
961                      nnmail-split-header-length-limit)
962             (delete-region (point) (progn (end-of-line) (point))))
963           (forward-line 1))
964         ;; Allow washing.
965         (goto-char (point-min))
966         (run-hooks 'nnmail-split-hook)
967         (when (setq nnmail-split-tracing trace)
968           (setq nnmail-split-trace nil))
969         (if (and (symbolp nnmail-split-methods)
970                  (fboundp nnmail-split-methods))
971             (let ((split
972                    (condition-case nil
973                        ;; `nnmail-split-methods' is a function, so we
974                        ;; just call this function here and use the
975                        ;; result.
976                        (or (funcall nnmail-split-methods)
977                            '("bogus"))
978                      (error
979                       (nnheader-message 5
980                                         "Error in `nnmail-split-methods'; using `bogus' mail group")
981                       (sit-for 1)
982                       '("bogus")))))
983               (setq split (gnus-remove-duplicates split))
984               ;; The article may be "cross-posted" to `junk'.  What
985               ;; to do?  Just remove the `junk' spec.  Don't really
986               ;; see anything else to do...
987               (let (elem)
988                 (while (setq elem (car (memq 'junk split)))
989                   (setq split (delq elem split))))
990               (when split
991                 (setq group-art
992                       (mapcar
993                        (lambda (group) (cons group (funcall func group)))
994                        split))))
995           ;; Go through the split methods to find a match.
996           (while (and methods
997                       (or nnmail-crosspost
998                           (not group-art)))
999             (goto-char (point-max))
1000             (setq method (pop methods)
1001                   grp (car method))
1002             (if (or methods
1003                     (not (equal "" (nth 1 method))))
1004                 (when (and
1005                        (ignore-errors
1006                          (if (stringp (nth 1 method))
1007                              (let ((expand (string-match "\\\\[0-9&]" grp))
1008                                    (pos (re-search-backward (cadr method)
1009                                                             nil t)))
1010                                (and expand
1011                                     (setq grp (nnmail-expand-newtext grp)))
1012                                pos)
1013                            ;; Function to say whether this is a match.
1014                            (funcall (nth 1 method) grp)))
1015                        ;; Don't enter the article into the same
1016                        ;; group twice.
1017                        (not (assoc grp group-art)))
1018                   (push (cons grp (funcall func grp))
1019                         group-art))
1020               ;; This is the final group, which is used as a
1021               ;; catch-all.
1022               (unless group-art
1023                 (setq group-art
1024                       (list (cons (car method)
1025                                   (funcall func (car method)))))))))
1026         ;; Produce a trace if non-empty.
1027         (when (and trace nnmail-split-trace)
1028           (let ((trace (nreverse nnmail-split-trace))
1029                 (restore (current-buffer)))
1030             (nnheader-set-temp-buffer "*Split Trace*")
1031             (gnus-add-buffer)
1032             (while trace
1033               (insert (car trace) "\n")
1034               (setq trace (cdr trace)))
1035             (goto-char (point-min))
1036             (gnus-configure-windows 'split-trace)
1037             (set-buffer restore)))
1038         ;; See whether the split methods returned `junk'.
1039         (if (equal group-art '(junk))
1040             nil
1041           ;; The article may be "cross-posted" to `junk'.  What
1042           ;; to do?  Just remove the `junk' spec.  Don't really
1043           ;; see anything else to do...
1044           (let (elem)
1045             (while (setq elem (car (memq 'junk group-art)))
1046               (setq group-art (delq elem group-art)))
1047             (nreverse group-art)))))))
1048
1049 (defun nnmail-insert-lines ()
1050   "Insert how many lines there are in the body of the mail.
1051 Return the number of characters in the body."
1052   (let (lines chars)
1053     (save-excursion
1054       (goto-char (point-min))
1055       (unless (search-forward "\n\n" nil t)
1056         (goto-char (point-max))
1057         (insert "\n"))
1058       (setq chars (- (point-max) (point)))
1059       (setq lines (count-lines (point) (point-max)))
1060       (forward-char -1)
1061       (save-excursion
1062         (when (re-search-backward "^Lines: " nil t)
1063           (delete-region (point) (progn (forward-line 1) (point)))))
1064       (beginning-of-line)
1065       (insert (format "Lines: %d\n" (max lines 0)))
1066       chars)))
1067
1068 (defun nnmail-insert-xref (group-alist)
1069   "Insert an Xref line based on the (group . article) alist."
1070   (save-excursion
1071     (goto-char (point-min))
1072     (unless (search-forward "\n\n" nil t)
1073       (goto-char (point-max))
1074       (insert "\n"))
1075     (forward-char -1)
1076     (when (re-search-backward "^Xref: " nil t)
1077       (delete-region (match-beginning 0)
1078                      (progn (forward-line 1) (point))))
1079     (insert (format "Xref: %s" (system-name)))
1080     (while group-alist
1081       (insert (format " %s:%d"
1082                       (encode-coding-string
1083                        (caar group-alist)
1084                        nnmail-pathname-coding-system)
1085                       (cdar group-alist)))
1086       (setq group-alist (cdr group-alist)))
1087     (insert "\n")))
1088
1089 ;;; Message washing functions
1090
1091 (defun nnmail-remove-leading-whitespace ()
1092   "Remove excessive whitespace from all headers."
1093   (goto-char (point-min))
1094   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1095     (replace-match "\\1" t)))
1096
1097 (defun nnmail-remove-list-identifiers ()
1098   "Remove list identifiers from Subject headers."
1099   (let ((regexp 
1100          (if (consp nnmail-list-identifiers) 
1101              (mapconcat 'identity nnmail-list-identifiers " *\\|")
1102            nnmail-list-identifiers)))
1103     (when regexp
1104       (goto-char (point-min))
1105       (while (re-search-forward
1106               (concat "^Subject: +\\(R[Ee]: +\\)*\\(" regexp " *\\)")
1107               nil t)
1108         (delete-region (match-beginning 2) (match-end 0))
1109         (beginning-of-line))
1110       (when (re-search-forward "^Subject: +\\(\\(R[Ee]: +\\)+\\)R[Ee]: +" nil t)
1111         (delete-region (match-beginning 1) (match-end 1))
1112         (beginning-of-line)))))
1113
1114 (defun nnmail-remove-tabs ()
1115   "Translate TAB characters into SPACE characters."
1116   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1117
1118 (defun nnmail-fix-eudora-headers ()
1119   "Eudora has a broken References line, but an OK In-Reply-To."
1120   (goto-char (point-min))
1121   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1122     (goto-char (point-min))
1123     (when (re-search-forward "^References:" nil t)
1124       (beginning-of-line)
1125       (insert "X-Gnus-Broken-Eudora-"))
1126     (goto-char (point-min))
1127     (when (re-search-forward "^\\(In-Reply-To:[^\n]+\\)\n[ \t]+" nil t)
1128       (replace-match "\\1" t))))
1129
1130 (custom-add-option 'nnmail-prepare-incoming-header-hook
1131                    'nnmail-fix-eudora-headers)
1132
1133 ;;; Utility functions
1134
1135 (defun nnmail-split-fancy ()
1136   "Fancy splitting method.
1137 See the documentation for the variable `nnmail-split-fancy' for documentation."
1138   (let ((syntab (syntax-table)))
1139     (unwind-protect
1140         (progn
1141           (set-syntax-table nnmail-split-fancy-syntax-table)
1142           (nnmail-split-it nnmail-split-fancy))
1143       (set-syntax-table syntab))))
1144
1145 (defvar nnmail-split-cache nil)
1146 ;; Alist of split expressions their equivalent regexps.
1147
1148 (defun nnmail-split-it (split)
1149   ;; Return a list of groups matching SPLIT.
1150   (let (cached-pair)
1151     (cond
1152      ;; nil split
1153      ((null split)
1154       nil)
1155
1156      ;; A group name.  Do the \& and \N subs into the string.
1157      ((stringp split)
1158       (when nnmail-split-tracing
1159         (push (format "\"%s\"" split) nnmail-split-trace))
1160       (list (nnmail-expand-newtext split)))
1161
1162      ;; Junk the message.
1163      ((eq split 'junk)
1164       (when nnmail-split-tracing
1165         (push "junk" nnmail-split-trace))
1166       (list 'junk))
1167
1168      ;; Builtin & operation.
1169      ((eq (car split) '&)
1170       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1171
1172      ;; Builtin | operation.
1173      ((eq (car split) '|)
1174       (let (done)
1175         (while (and (not done) (cdr split))
1176           (setq split (cdr split)
1177                 done (nnmail-split-it (car split))))
1178         done))
1179
1180      ;; Builtin : operation.
1181      ((eq (car split) ':)
1182       (nnmail-split-it (save-excursion (eval (cdr split)))))
1183
1184      ;; Builtin ! operation.
1185      ((eq (car split) '!)
1186       (funcall (cadr split) (nnmail-split-it (caddr split))))
1187
1188      ;; Check the cache for the regexp for this split.
1189      ((setq cached-pair (assq split nnmail-split-cache))
1190       (let (split-result
1191             (end-point (point-max))
1192             (value (nth 1 split)))
1193         (if (symbolp value)
1194             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1195         (while (and (goto-char end-point)
1196                     (re-search-backward (cdr cached-pair) nil t))
1197           (when nnmail-split-tracing
1198             (push (cdr cached-pair) nnmail-split-trace))
1199           (let ((split-rest (cddr split))
1200                 (end (match-end 0))
1201                 ;; The searched regexp is \(\(FIELD\).*\)\(VALUE\).  So,
1202                 ;; start-of-value is the the point just before the
1203                 ;; beginning of the value, whereas after-header-name is
1204                 ;; the point just after the field name.
1205                 (start-of-value (match-end 1))
1206                 (after-header-name (match-end 2)))
1207             ;; Start the next search just before the beginning of the
1208             ;; VALUE match.
1209             (setq end-point (1- start-of-value))
1210             ;; Handle - RESTRICTs
1211             (while (eq (car split-rest) '-)
1212               ;; RESTRICT must start after-header-name and
1213               ;; end after start-of-value, so that, for
1214               ;; (any "foo" - "x-foo" "foo.list")
1215               ;; we do not exclude foo.list just because
1216               ;; the header is: ``To: x-foo, foo''
1217               (goto-char end)
1218               (if (and (re-search-backward (cadr split-rest)
1219                                            after-header-name t)
1220                        (> (match-end 0) start-of-value))
1221                   (setq split-rest nil)
1222                 (setq split-rest (cddr split-rest))))
1223             (when split-rest
1224               (goto-char end)
1225               (let ((value (nth 1 split)))
1226                 (if (symbolp value)
1227                     (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1228                 ;; Someone might want to do a \N sub on this match, so get the
1229                 ;; correct match positions.
1230                 (re-search-backward (concat "\\<" value "\\>") start-of-value))
1231               (dolist (sp (nnmail-split-it (car split-rest)))
1232                 (unless (memq sp split-result)
1233                   (push sp split-result))))))
1234         split-result))
1235
1236      ;; Not in cache, compute a regexp for the field/value pair.
1237      (t
1238       (let* ((field (nth 0 split))
1239              (value (nth 1 split))
1240              partial-front regexp
1241              partial-rear  regexp)
1242         (if (symbolp value)
1243             (setq value (cdr (assq value nnmail-split-abbrev-alist))))
1244         (if (and (>= (length value) 2)
1245                  (string= ".*" (substring value 0 2)))
1246             (setq value (substring value 2)
1247                   partial-front ""))
1248         ;; Same trick for the rear of the regexp
1249         (if (and (>= (length value) 2)
1250                  (string= ".*" (substring value -2)))
1251             (setq value (substring value 0 -2)
1252                   partial-rear ""))
1253         (setq regexp (concat "^\\(\\("
1254                              (if (symbolp field)
1255                                  (cdr (assq field nnmail-split-abbrev-alist))
1256                                field)
1257                              "\\):.*\\)"
1258                              (or partial-front "\\<")
1259                              "\\("
1260                              value
1261                              "\\)"
1262                              (or partial-rear "\\>")))
1263         (push (cons split regexp) nnmail-split-cache)
1264         ;; Now that it's in the cache, just call nnmail-split-it again
1265         ;; on the same split, which will find it immediately in the cache.
1266         (nnmail-split-it split))))))
1267
1268 (defun nnmail-expand-newtext (newtext)
1269   (let ((len (length newtext))
1270         (pos 0)
1271         c expanded beg N did-expand)
1272     (while (< pos len)
1273       (setq beg pos)
1274       (while (and (< pos len)
1275                   (not (= (aref newtext pos) ?\\)))
1276         (setq pos (1+ pos)))
1277       (unless (= beg pos)
1278         (push (substring newtext beg pos) expanded))
1279       (when (< pos len)
1280         ;; We hit a \; expand it.
1281         (setq did-expand t
1282               pos (1+ pos)
1283               c (aref newtext pos))
1284         (if (not (or (= c ?\&)
1285                      (and (>= c ?1)
1286                           (<= c ?9))))
1287             ;; \ followed by some character we don't expand.
1288             (push (char-to-string c) expanded)
1289           ;; \& or \N
1290           (if (= c ?\&)
1291               (setq N 0)
1292             (setq N (- c ?0)))
1293           (when (match-beginning N)
1294             (push (buffer-substring (match-beginning N) (match-end N))
1295                   expanded))))
1296       (setq pos (1+ pos)))
1297     (if did-expand
1298         (apply 'concat (nreverse expanded))
1299       newtext)))
1300
1301 ;; Activate a backend only if it isn't already activated.
1302 ;; If FORCE, re-read the active file even if the backend is
1303 ;; already activated.
1304 (defun nnmail-activate (backend &optional force)
1305   (nnheader-init-server-buffer)
1306   (let (file timestamp file-time)
1307     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1308             force
1309             (and (setq file (ignore-errors
1310                               (symbol-value (intern (format "%s-active-file"
1311                                                             backend)))))
1312                  (setq file-time (nth 5 (file-attributes file)))
1313                  (or (not
1314                       (setq timestamp
1315                             (condition-case ()
1316                                 (symbol-value (intern
1317                                                (format "%s-active-timestamp"
1318                                                        backend)))
1319                               (error 'none))))
1320                      (not (consp timestamp))
1321                      (equal timestamp '(0 0))
1322                      (> (nth 0 file-time) (nth 0 timestamp))
1323                      (and (= (nth 0 file-time) (nth 0 timestamp))
1324                           (> (nth 1 file-time) (nth 1 timestamp))))))
1325         (save-excursion
1326           (or (eq timestamp 'none)
1327               (set (intern (format "%s-active-timestamp" backend))
1328                    file-time))
1329           (funcall (intern (format "%s-request-list" backend)))))
1330     t))
1331
1332 (defun nnmail-message-id ()
1333   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1334
1335 ;;;
1336 ;;; nnmail duplicate handling
1337 ;;;
1338
1339 (defvar nnmail-cache-buffer nil)
1340
1341 (defun nnmail-cache-open ()
1342   (if (or (not nnmail-treat-duplicates)
1343           (and nnmail-cache-buffer
1344                (buffer-name nnmail-cache-buffer)))
1345       ()                                ; The buffer is open.
1346     (save-excursion
1347       (set-buffer
1348        (setq nnmail-cache-buffer
1349              (get-buffer-create " *nnmail message-id cache*")))
1350       (when (file-exists-p nnmail-message-id-cache-file)
1351         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1352       (set-buffer-modified-p nil)
1353       (current-buffer))))
1354
1355 (defun nnmail-cache-close ()
1356   (when (and nnmail-cache-buffer
1357              nnmail-treat-duplicates
1358              (buffer-name nnmail-cache-buffer)
1359              (buffer-modified-p nnmail-cache-buffer))
1360     (save-excursion
1361       (set-buffer nnmail-cache-buffer)
1362       ;; Weed out the excess number of Message-IDs.
1363       (goto-char (point-max))
1364       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1365         (progn
1366           (beginning-of-line)
1367           (delete-region (point-min) (point))))
1368       ;; Save the buffer.
1369       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1370           (make-directory (file-name-directory nnmail-message-id-cache-file)
1371                           t))
1372       (nnmail-write-region (point-min) (point-max)
1373                            nnmail-message-id-cache-file nil 'silent)
1374       (set-buffer-modified-p nil)
1375       (setq nnmail-cache-buffer nil)
1376       (kill-buffer (current-buffer)))))
1377
1378 ;; Compiler directives.
1379 (defvar group)
1380 (defvar group-art-list)
1381 (defvar group-art)
1382 (defun nnmail-cache-insert (id)
1383   (when nnmail-treat-duplicates
1384     ;; Store some information about the group this message is written
1385     ;; to.  This function might have been called from various places.
1386     ;; Sometimes, a function up in the calling sequence has an
1387     ;; argument GROUP which is bound to a string, the group name.  At
1388     ;; other times, there is a function up in the calling sequence
1389     ;; which has an argument GROUP-ART which is a list of pairs, and
1390     ;; the car of a pair is a group name.  Should we check that the
1391     ;; length of the list is equal to 1? -- kai
1392     (let ((g nil))
1393       (cond ((and (boundp 'group) group)
1394              (setq g group))
1395             ((and (boundp 'group-art-list) group-art-list
1396                   (listp group-art-list))
1397              (setq g (caar group-art-list)))
1398             ((and (boundp 'group-art) group-art (listp group-art))
1399              (setq g (caar group-art)))
1400             (t (setq g "")))
1401       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1402         (nnmail-cache-open))
1403       (save-excursion
1404         (set-buffer nnmail-cache-buffer)
1405         (goto-char (point-max))
1406         (if (and g (not (string= "" g))
1407                  (gnus-methods-equal-p gnus-command-method
1408                                        (nnmail-cache-primary-mail-backend)))
1409             (insert id "\t" g "\n")
1410           (insert id "\n"))))))
1411
1412 (defun nnmail-cache-primary-mail-backend ()
1413   (let ((be-list (cons gnus-select-method gnus-secondary-select-methods))
1414         (be nil)
1415         (res nil))
1416     (while (and (null res) be-list)
1417       (setq be (car be-list))
1418       (setq be-list (cdr be-list))
1419       (when (and (gnus-method-option-p be 'respool)
1420                  (eval (intern (format "%s-get-new-mail" (car be)))))
1421         (setq res be)))
1422     res))
1423
1424 ;; Fetch the group name corresponding to the message id stored in the
1425 ;; cache.
1426 (defun nnmail-cache-fetch-group (id)
1427   (when (and nnmail-treat-duplicates nnmail-cache-buffer)
1428     (save-excursion
1429       (set-buffer nnmail-cache-buffer)
1430       (goto-char (point-max))
1431       (when (search-backward id nil t)
1432         (beginning-of-line)
1433         (skip-chars-forward "^\n\r\t")
1434         (unless (eolp)
1435           (forward-char 1)
1436           (buffer-substring (point)
1437                             (progn (end-of-line) (point))))))))
1438
1439 ;; Function for nnmail-split-fancy: look up all references in the
1440 ;; cache and if a match is found, return that group.
1441 (defun nnmail-split-fancy-with-parent ()
1442   "Split this message into the same group as its parent.
1443 This function can be used as an entry in `nnmail-split-fancy', for
1444 example like this: (: nnmail-split-fancy)
1445 For a message to be split, it looks for the parent message in the
1446 References or In-Reply-To header and then looks in the message id
1447 cache file (given by the variable `nnmail-message-id-cache-file') to
1448 see which group that message was put in.  This group is returned.
1449
1450 See the Info node `(gnus)Fancy Mail Splitting' for more details."
1451   (let* ((refstr (or (message-fetch-field "references")
1452                      (message-fetch-field "in-reply-to")))
1453          (references nil)
1454          (res nil))
1455     (when refstr
1456       (setq references (nreverse (gnus-split-references refstr)))
1457       (unless (gnus-buffer-live-p nnmail-cache-buffer)
1458         (nnmail-cache-open))
1459       (mapcar (lambda (x)
1460                 (setq res (or (nnmail-cache-fetch-group x) res))
1461                 (when (string= "drafts" res)
1462                   (setq res nil)))
1463               references)
1464       res)))
1465
1466 (defun nnmail-cache-id-exists-p (id)
1467   (when nnmail-treat-duplicates
1468     (save-excursion
1469       (set-buffer nnmail-cache-buffer)
1470       (goto-char (point-max))
1471       (search-backward id nil t))))
1472
1473 (defun nnmail-fetch-field (header)
1474   (save-excursion
1475     (save-restriction
1476       (message-narrow-to-head)
1477       (message-fetch-field header))))
1478
1479 (defun nnmail-check-duplication (message-id func artnum-func)
1480   (run-hooks 'nnmail-prepare-incoming-message-hook)
1481   ;; If this is a duplicate message, then we do not save it.
1482   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1483          (case-fold-search t)
1484          (action (when duplication
1485                    (cond
1486                     ((memq nnmail-treat-duplicates '(warn delete))
1487                      nnmail-treat-duplicates)
1488                     ((nnheader-functionp nnmail-treat-duplicates)
1489                      (funcall nnmail-treat-duplicates message-id))
1490                     (t
1491                      nnmail-treat-duplicates))))
1492          group-art)
1493     ;; We insert a line that says what the mail source is.
1494     (let ((case-fold-search t))
1495       (goto-char (point-min))
1496       (re-search-forward "^message-id[ \t]*:" nil t)
1497       (beginning-of-line)
1498       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1499
1500     ;; Let the backend save the article (or not).
1501     (cond
1502      ((not duplication)
1503       (funcall func (setq group-art
1504                           (nreverse (nnmail-article-group artnum-func))))
1505       (nnmail-cache-insert message-id))
1506      ((eq action 'delete)
1507       (setq group-art nil))
1508      ((eq action 'warn)
1509       ;; We insert a warning.
1510       (let ((case-fold-search t))
1511         (goto-char (point-min))
1512         (re-search-forward "^message-id[ \t]*:" nil t)
1513         (beginning-of-line)
1514         (insert
1515          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1516         (funcall func (setq group-art
1517                             (nreverse (nnmail-article-group artnum-func))))))
1518      (t
1519       (funcall func (setq group-art
1520                           (nreverse (nnmail-article-group artnum-func))))))
1521     ;; Add the group-art list to the history list.
1522     (if group-art
1523         (push group-art nnmail-split-history)
1524       (delete-region (point-min) (point-max)))))
1525
1526 ;;; Get new mail.
1527
1528 (defvar nnmail-fetched-sources nil)
1529
1530 (defun nnmail-get-value (&rest args)
1531   (let ((sym (intern (apply 'format args))))
1532     (when (boundp sym)
1533       (symbol-value sym))))
1534
1535 (defun nnmail-get-new-mail (method exit-func temp
1536                                    &optional group spool-func)
1537   "Read new incoming mail."
1538   (let* ((sources (or mail-sources
1539                       (if (listp nnmail-spool-file) nnmail-spool-file
1540                         (list nnmail-spool-file))))
1541          fetching-sources
1542          (group-in group)
1543          (i 0)
1544          (new 0)
1545          (total 0)
1546          incoming incomings source)
1547     (when (and (nnmail-get-value "%s-get-new-mail" method)
1548                sources)
1549       (while (setq source (pop sources))
1550         ;; Be compatible with old values.
1551         (cond
1552          ((stringp source)
1553           (setq source
1554                 (cond
1555                  ((string-match "^po:" source)
1556                   (list 'pop :user (substring source (match-end 0))))
1557                  ((file-directory-p source)
1558                   (list 'directory :path source))
1559                  (t
1560                   (list 'file :path source)))))
1561          ((eq source 'procmail)
1562           (message "Invalid value for nnmail-spool-file: `procmail'")
1563           nil))
1564         ;; Hack to only fetch the contents of a single group's spool file.
1565         (when (and (eq (car source) 'directory)
1566                    (null nnmail-scan-directory-mail-source-once)
1567                    group)
1568           (mail-source-bind (directory source)
1569             (setq source (append source
1570                                  (list
1571                                   :predicate
1572                                   `(lambda (file)
1573                                      (string-equal
1574                                       ,(concat group suffix)
1575                                       (file-name-nondirectory file))))))))
1576         (when nnmail-fetched-sources
1577           (if (member source nnmail-fetched-sources)
1578               (setq source nil)
1579             (push source nnmail-fetched-sources)
1580             (push source fetching-sources)))))
1581     (when fetching-sources
1582       ;; We first activate all the groups.
1583       (nnmail-activate method)
1584       ;; Allow the user to hook.
1585       (run-hooks 'nnmail-pre-get-new-mail-hook)
1586       ;; Open the message-id cache.
1587       (nnmail-cache-open)
1588       ;; The we go through all the existing mail source specification
1589       ;; and fetch the mail from each.
1590       (while (setq source (pop fetching-sources))
1591         (nnheader-message 4 "%s: Reading incoming mail from %s..."
1592                           method (car source))
1593         (when (setq new
1594                     (mail-source-fetch
1595                      source
1596                      `(lambda (file orig-file)
1597                         (nnmail-split-incoming
1598                          file ',(intern (format "%s-save-mail" method))
1599                          ',spool-func
1600                          (if (equal file orig-file)
1601                              nil
1602                            (nnmail-get-split-group orig-file ',source))
1603                          ',(intern (format "%s-active-number" method))))))
1604           (incf total new)
1605           (incf i)))
1606       ;; If we did indeed read any incoming spools, we save all info.
1607       (if (zerop total)
1608           (nnheader-message 4 "%s: Reading incoming mail (no new mail)...done"
1609                             method (car source))
1610         (nnmail-save-active
1611          (nnmail-get-value "%s-group-alist" method)
1612          (nnmail-get-value "%s-active-file" method))
1613         (when exit-func
1614           (funcall exit-func))
1615         (run-hooks 'nnmail-read-incoming-hook)
1616         (nnheader-message 4 "%s: Reading incoming mail (%d new)...done" method
1617                           total))
1618       ;; Close the message-id cache.
1619       (nnmail-cache-close)
1620       ;; Allow the user to hook.
1621       (run-hooks 'nnmail-post-get-new-mail-hook))))
1622
1623 (defun nnmail-expired-article-p (group time force &optional inhibit)
1624   "Say whether an article that is TIME old in GROUP should be expired."
1625   (if force
1626       t
1627     (let ((days (or (and nnmail-expiry-wait-function
1628                          (funcall nnmail-expiry-wait-function group))
1629                     nnmail-expiry-wait)))
1630       (cond ((or (eq days 'never)
1631                  (and (not force)
1632                       inhibit))
1633              ;; This isn't an expirable group.
1634              nil)
1635             ((eq days 'immediate)
1636              ;; We expire all articles on sight.
1637              t)
1638             ((equal time '(0 0))
1639              ;; This is an ange-ftp group, and we don't have any dates.
1640              nil)
1641             ((numberp days)
1642              (setq days (days-to-time days))
1643              ;; Compare the time with the current time.
1644              (ignore-errors (time-less-p days (time-since time))))))))
1645
1646 (defun nnmail-expiry-target-group (target group)
1647   (let (nnmail-cache-accepted-message-ids)
1648     ;; Don't enter Message-IDs into cache.
1649     ;; Let users hack it in TARGET function.
1650     (when (nnheader-functionp target)
1651       (setq target (funcall target group)))
1652     (unless (eq target 'delete)
1653       (gnus-request-accept-article target nil nil t))))
1654
1655 (defun nnmail-check-syntax ()
1656   "Check (and modify) the syntax of the message in the current buffer."
1657   (save-restriction
1658     (message-narrow-to-head)
1659     (let ((case-fold-search t))
1660       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1661         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1662
1663 (defun nnmail-write-region (start end filename &optional append visit lockname)
1664   "Do a `write-region', and then set the file modes."
1665   (let ((file-name-coding-system nnmail-pathname-coding-system)
1666         (pathname-coding-system nnmail-pathname-coding-system))
1667     (write-region-as-coding-system
1668      nnmail-file-coding-system start end filename append visit lockname)
1669     (set-file-modes filename nnmail-default-file-modes)))
1670
1671 ;;;
1672 ;;; Status functions
1673 ;;;
1674
1675 (defun nnmail-replace-status (name value)
1676   "Make status NAME and VALUE part of the current status line."
1677   (save-restriction
1678     (message-narrow-to-head)
1679     (let ((status (nnmail-decode-status)))
1680       (setq status (delq (member name status) status))
1681       (when value
1682         (push (cons name value) status))
1683       (message-remove-header "status")
1684       (goto-char (point-max))
1685       (insert "Status: " (nnmail-encode-status status) "\n"))))
1686
1687 (defun nnmail-decode-status ()
1688   "Return a status-value alist from STATUS."
1689   (goto-char (point-min))
1690   (when (re-search-forward "^Status: " nil t)
1691     (let (name value status)
1692       (save-restriction
1693         ;; Narrow to the status.
1694         (narrow-to-region
1695          (point)
1696          (if (re-search-forward "^[^ \t]" nil t)
1697              (1- (point))
1698            (point-max)))
1699         ;; Go through all elements and add them to the list.
1700         (goto-char (point-min))
1701         (while (re-search-forward "[^ \t=]+" nil t)
1702           (setq name (match-string 0))
1703           (if (not (eq (char-after) ?=))
1704               ;; Implied "yes".
1705               (setq value "yes")
1706             (forward-char 1)
1707             (if (not (eq (char-after) ?\"))
1708                 (if (not (looking-at "[^ \t]"))
1709                     ;; Implied "no".
1710                     (setq value "no")
1711                   ;; Unquoted value.
1712                   (setq value (match-string 0))
1713                   (goto-char (match-end 0)))
1714               ;; Quoted value.
1715               (setq value (read (current-buffer)))))
1716           (push (cons name value) status)))
1717       status)))
1718
1719 (defun nnmail-encode-status (status)
1720   "Return a status string from STATUS."
1721   (mapconcat
1722    (lambda (elem)
1723      (concat
1724       (car elem) "="
1725       (if (string-match "[ \t]" (cdr elem))
1726           (prin1-to-string (cdr elem))
1727         (cdr elem))))
1728    status " "))
1729
1730 (defun nnmail-split-history ()
1731   "Generate an overview of where the last mail split put articles."
1732   (interactive)
1733   (unless nnmail-split-history
1734     (error "No current split history"))
1735   (with-output-to-temp-buffer "*nnmail split history*"
1736     (with-current-buffer standard-output
1737       (fundamental-mode))               ; for Emacs 20.4+
1738     (let ((history nnmail-split-history)
1739           elem)
1740       (while (setq elem (pop history))
1741         (princ (mapconcat (lambda (ga)
1742                             (concat (car ga) ":" (int-to-string (cdr ga))))
1743                           elem
1744                           ", "))
1745         (princ "\n")))))
1746
1747 (defun nnmail-purge-split-history (group)
1748   "Remove all instances of GROUP from `nnmail-split-history'."
1749   (let ((history nnmail-split-history))
1750     (while history
1751       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1752                                       (car history)))
1753       (pop history))
1754     (setq nnmail-split-history (delq nil nnmail-split-history))))
1755
1756 (defun nnmail-new-mail-p (group)
1757   "Say whether GROUP has new mail."
1758   (let ((his nnmail-split-history)
1759         found)
1760     (while his
1761       (when (assoc group (pop his))
1762         (setq found t
1763               his nil)))
1764     found))
1765
1766 (defun nnmail-new-mail-numbers (group)
1767   "Say how many articles has been incorporated to GROUP."
1768   (let ((his (apply 'append nnmail-split-history))
1769         numbers)
1770     (while his
1771       (when (string= group (caar his))
1772         (push (cdar his) numbers))
1773       (setq his (cdr his)))
1774     numbers))
1775
1776 (defun nnmail-within-headers-p ()
1777   "Check to see if point is within the headers of a unix mail message.
1778 Doesn't change point."
1779   (let ((pos (point)))
1780     (save-excursion
1781       (and (nnmail-search-unix-mail-delim-backward)
1782            (not (search-forward "\n\n" pos t))))))
1783
1784 (run-hooks 'nnmail-load-hook)
1785
1786 (provide 'nnmail)
1787
1788 ;;; nnmail.el ends here