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