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