Importing Pterodactyl Gnus v0.80.
[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 (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 If this variable is nil, no mail backends will read incoming mail."
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         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           (setq end (point-max))))
589       (goto-char end))))
590
591 (defsubst nnmail-search-unix-mail-delim ()
592   "Put point at the beginning of the next Unix mbox message."
593   ;; Algorithm used to find the the next article in the
594   ;; brain-dead Unix mbox format:
595   ;;
596   ;; 1) Search for "^From ".
597   ;; 2) If we find it, then see whether the previous
598   ;;    line is blank and the next line looks like a header.
599   ;; Then it's possible that this is a mail delim, and we use it.
600   (let ((case-fold-search nil)
601         found)
602     (while (not found)
603       (if (not (re-search-forward "^From " nil t))
604           (setq found 'no)
605         (save-excursion
606           (beginning-of-line)
607           (when (and (or (bobp)
608                          (save-excursion
609                            (forward-line -1)
610                            (eq (char-after) ?\n)))
611                      (save-excursion
612                        (forward-line 1)
613                        (while (looking-at ">From \\|From ")
614                          (forward-line 1))
615                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
616             (setq found 'yes)))))
617     (beginning-of-line)
618     (eq found 'yes)))
619
620 (defun nnmail-search-unix-mail-delim-backward ()
621   "Put point at the beginning of the current Unix mbox message."
622   ;; Algorithm used to find the the next article in the
623   ;; brain-dead Unix mbox format:
624   ;;
625   ;; 1) Search for "^From ".
626   ;; 2) If we find it, then see whether the previous
627   ;;    line is blank and the next line looks like a header.
628   ;; Then it's possible that this is a mail delim, and we use it.
629   (let ((case-fold-search nil)
630         found)
631     (while (not found)
632       (if (not (re-search-backward "^From " nil t))
633           (setq found 'no)
634         (save-excursion
635           (beginning-of-line)
636           (when (and (or (bobp)
637                          (save-excursion
638                            (forward-line -1)
639                            (eq (char-after) ?\n)))
640                      (save-excursion
641                        (forward-line 1)
642                        (while (looking-at ">From \\|From ")
643                          (forward-line 1))
644                        (looking-at "[^ \n\t:]+[ \n\t]*:")))
645             (setq found 'yes)))))
646     (beginning-of-line)
647     (eq found 'yes)))
648
649 (defun nnmail-process-unix-mail-format (func artnum-func)
650   (let ((case-fold-search t)
651         start message-id content-length end skip head-end)
652     (goto-char (point-min))
653     (if (not (and (re-search-forward "^From " nil t)
654                   (goto-char (match-beginning 0))))
655         ;; Possibly wrong format?
656         (error "Error, unknown mail format! (Possibly corrupted.)")
657       ;; Carry on until the bitter end.
658       (while (not (eobp))
659         (setq start (point)
660               end nil)
661         ;; Find the end of the head.
662         (narrow-to-region
663          start
664          (if (search-forward "\n\n" nil t)
665              (1- (point))
666            ;; This will never happen, but just to be on the safe side --
667            ;; if there is no head-body delimiter, we search a bit manually.
668            (while (and (looking-at "From \\|[^ \t]+:")
669                        (not (eobp)))
670              (forward-line 1))
671            (point)))
672         ;; Find the Message-ID header.
673         (goto-char (point-min))
674         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
675             (setq message-id (match-string 1))
676           (save-excursion
677             (when (re-search-forward "^Message-ID[ \t]*:" nil t)
678               (beginning-of-line)
679               (insert "Original-")))
680           ;; There is no Message-ID here, so we create one.
681           (forward-line 1)
682           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
683         ;; Look for a Content-Length header.
684         (goto-char (point-min))
685         (if (not (re-search-forward
686                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
687             (setq content-length nil)
688           (setq content-length (string-to-int (match-string 1)))
689           ;; We destroy the header, since none of the backends ever
690           ;; use it, and we do not want to confuse other mailers by
691           ;; having a (possibly) faulty header.
692           (beginning-of-line)
693           (insert "X-"))
694         (run-hooks 'nnmail-prepare-incoming-header-hook)
695         ;; Find the end of this article.
696         (goto-char (point-max))
697         (widen)
698         (setq head-end (point))
699         ;; We try the Content-Length value.  The idea: skip over the header
700         ;; separator, then check what happens content-length bytes into the
701         ;; message body.  This should be either the end ot the buffer, the
702         ;; message separator or a blank line followed by the separator.
703         ;; The blank line should probably be deleted.  If neither of the
704         ;; three is met, the content-length header is probably invalid.
705         (when content-length
706           (forward-line 1)
707           (setq skip (+ (point) content-length))
708           (goto-char skip)
709           (cond ((or (= skip (point-max))
710                      (= (1+ skip) (point-max)))
711                  (setq end (point-max)))
712                 ((looking-at "From ")
713                  (setq end skip))
714                 ((looking-at "[ \t]*\n\\(From \\)")
715                  (setq end (match-beginning 1)))
716                 (t (setq end nil))))
717         (if end
718             (goto-char end)
719           ;; No Content-Length, so we find the beginning of the next
720           ;; article or the end of the buffer.
721           (goto-char head-end)
722           (or (nnmail-search-unix-mail-delim)
723               (goto-char (point-max))))
724         ;; Allow the backend to save the article.
725         (save-excursion
726           (save-restriction
727             (narrow-to-region start (point))
728             (goto-char (point-min))
729             (nnmail-check-duplication message-id func artnum-func)
730             (setq end (point-max))))
731         (goto-char end)))))
732
733 (defun nnmail-process-mmdf-mail-format (func artnum-func)
734   (let ((delim "^\^A\^A\^A\^A$")
735         (case-fold-search t)
736         start message-id end)
737     (goto-char (point-min))
738     (if (not (and (re-search-forward delim nil t)
739                   (forward-line 1)))
740         ;; Possibly wrong format?
741         (error "Error, unknown mail format! (Possibly corrupted.)")
742       ;; Carry on until the bitter end.
743       (while (not (eobp))
744         (setq start (point))
745         ;; Find the end of the head.
746         (narrow-to-region
747          start
748          (if (search-forward "\n\n" nil t)
749              (1- (point))
750            ;; This will never happen, but just to be on the safe side --
751            ;; if there is no head-body delimiter, we search a bit manually.
752            (while (and (looking-at "From \\|[^ \t]+:")
753                        (not (eobp)))
754              (forward-line 1))
755            (point)))
756         ;; Find the Message-ID header.
757         (goto-char (point-min))
758         (if (re-search-forward "^Message-ID[ \t]*:[ \n\t]*\\(<[^>]+>\\)" nil t)
759             (setq message-id (match-string 1))
760           ;; There is no Message-ID here, so we create one.
761           (save-excursion
762             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
763               (beginning-of-line)
764               (insert "Original-")))
765           (forward-line 1)
766           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
767         (run-hooks 'nnmail-prepare-incoming-header-hook)
768         ;; Find the end of this article.
769         (goto-char (point-max))
770         (widen)
771         (if (re-search-forward delim nil t)
772             (beginning-of-line)
773           (goto-char (point-max)))
774         ;; Allow the backend to save the article.
775         (save-excursion
776           (save-restriction
777             (narrow-to-region start (point))
778             (goto-char (point-min))
779             (nnmail-check-duplication message-id func artnum-func)
780             (setq end (point-max))))
781         (goto-char end)
782         (forward-line 2)))))
783
784 (defun nnmail-process-maildir-mail-format (func artnum-func)
785 ; In a maildir, every file contains exactly one mail
786   (let ((case-fold-search t)
787         message-id)
788     (goto-char (point-min))
789     ;; Find the end of the head.
790     (narrow-to-region
791      (point-min)
792      (if (search-forward "\n\n" nil t)
793          (1- (point))
794        ;; This will never happen, but just to be on the safe side --
795        ;; if there is no head-body delimiter, we search a bit manually.
796        (while (and (looking-at "From \\|[^ \t]+:")
797                    (not (eobp)))
798          (forward-line 1)
799          (point))))
800     ;; Find the Message-ID header.
801     (goto-char (point-min))
802     (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
803         (setq message-id (match-string 1))
804       ;; There is no Message-ID here, so we create one.
805       (save-excursion
806             (when (re-search-backward "^Message-ID[ \t]*:" nil t)
807           (beginning-of-line)
808           (insert "Original-")))
809       (forward-line 1)
810       (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
811     (run-hooks 'nnmail-prepare-incoming-header-hook)
812     ;; Allow the backend to save the article.
813     (widen)
814     (save-excursion
815         (goto-char (point-min))
816         (nnmail-check-duplication message-id func artnum-func))))
817
818 (defun nnmail-split-incoming (incoming func &optional exit-func
819                                        group artnum-func)
820   "Go through the entire INCOMING file and pick out each individual mail.
821 FUNC will be called with the buffer narrowed to each mail."
822   (let (;; If this is a group-specific split, we bind the split
823         ;; methods to just this group.
824         (nnmail-split-methods (if (and group
825                                        (not nnmail-resplit-incoming))
826                                   (list (list group ""))
827                                 nnmail-split-methods)))
828     (save-excursion
829       ;; Insert the incoming file.
830       (set-buffer (get-buffer-create " *nnmail incoming*"))
831       (erase-buffer)
832       (let ((nnheader-file-coding-system nnmail-incoming-coding-system))
833         (nnheader-insert-file-contents incoming))
834       (unless (zerop (buffer-size))
835         (goto-char (point-min))
836         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
837         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
838         ;; use the former when fetching from a mailbox, the latter when
839         ;; fetching from a file.
840         (cond ((or (looking-at "\^L")
841                    (looking-at "BABYL OPTIONS:"))
842                (nnmail-process-babyl-mail-format func artnum-func))
843               ((looking-at "\^A\^A\^A\^A")
844                (nnmail-process-mmdf-mail-format func artnum-func))
845               ((looking-at "Return-Path:")
846                (nnmail-process-maildir-mail-format func artnum-func))
847               (t
848                (nnmail-process-unix-mail-format func artnum-func))))
849       (when exit-func
850         (funcall exit-func))
851       (kill-buffer (current-buffer)))))
852
853 (defun nnmail-article-group (func &optional trace)
854   "Look at the headers and return an alist of groups that match.
855 FUNC will be called with the group name to determine the article number."
856   (let ((methods nnmail-split-methods)
857         (obuf (current-buffer))
858         (beg (point-min))
859         end group-art method regrepp)
860     (if (and (sequencep methods)
861              (= (length methods) 1))
862         ;; If there is only just one group to put everything in, we
863         ;; just return a list with just this one method in.
864         (setq group-art
865               (list (cons (caar methods) (funcall func (caar methods)))))
866       ;; We do actual comparison.
867       (save-excursion
868         ;; Find headers.
869         (goto-char beg)
870         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
871         (set-buffer nntp-server-buffer)
872         (erase-buffer)
873         ;; Copy the headers into the work buffer.
874         (insert-buffer-substring obuf beg end)
875         ;; Fold continuation lines.
876         (goto-char (point-min))
877         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
878           (replace-match " " t t))
879         ;; Nuke pathologically long headers.  Since Gnus applies
880         ;; pathologically complex regexps to the buffer, lines
881         ;; that are looong will take longer than the Universe's
882         ;; existence to process.
883         (goto-char (point-min))
884         (while (not (eobp))
885           (unless (< (move-to-column nnmail-split-header-length-limit)
886                      nnmail-split-header-length-limit)
887             (delete-region (point) (progn (end-of-line) (point))))
888           (forward-line 1))
889         ;; Allow washing.
890         (goto-char (point-min))
891         (run-hooks 'nnmail-split-hook)
892         (when (setq nnmail-split-tracing trace)
893           (setq nnmail-split-trace nil))
894         (if (and (symbolp nnmail-split-methods)
895                  (fboundp nnmail-split-methods))
896             (let ((split
897                    (condition-case nil
898                        ;; `nnmail-split-methods' is a function, so we
899                        ;; just call this function here and use the
900                        ;; result.
901                        (or (funcall nnmail-split-methods)
902                            '("bogus"))
903                      (error
904                       (nnheader-message 5
905                        "Error in `nnmail-split-methods'; using `bogus' mail group")
906                       (sit-for 1)
907                       '("bogus")))))
908               (setq split (gnus-remove-duplicates split))
909               ;; The article may be "cross-posted" to `junk'.  What
910               ;; to do?  Just remove the `junk' spec.  Don't really
911               ;; see anything else to do...
912               (let (elem)
913                 (while (setq elem (car (memq 'junk split)))
914                   (setq split (delq elem split))))
915               (when split
916                 (setq group-art
917                       (mapcar
918                        (lambda (group) (cons group (funcall func group)))
919                        split))))
920           ;; Go through the split methods to find a match.
921           (while (and methods
922                       (or nnmail-crosspost
923                           (not group-art)))
924             (goto-char (point-max))
925             (setq method (pop methods)
926                   regrepp nil)
927             (if (or methods
928                     (not (equal "" (nth 1 method))))
929                 (when (and
930                        (ignore-errors
931                          (if (stringp (nth 1 method))
932                              (progn
933                                (setq regrepp
934                                      (string-match "\\\\[0-9&]" (car method)))
935                                (re-search-backward (cadr method) nil t))
936                            ;; Function to say whether this is a match.
937                            (funcall (nth 1 method) (car method))))
938                        ;; Don't enter the article into the same
939                        ;; group twice.
940                        (not (assoc (car method) group-art)))
941                   (push (cons (if regrepp
942                                   (nnmail-expand-newtext (car method))
943                                 (car method))
944                               (funcall func (car method)))
945                         group-art))
946               ;; This is the final group, which is used as a
947               ;; catch-all.
948               (unless group-art
949                 (setq group-art
950                       (list (cons (car method)
951                                   (funcall func (car method)))))))))
952         ;; Produce a trace if non-empty.
953         (when (and trace nnmail-split-trace)
954           (let ((trace (nreverse nnmail-split-trace))
955                 (restore (current-buffer)))
956             (nnheader-set-temp-buffer "*Split Trace*")
957             (gnus-add-buffer)
958             (while trace
959               (insert (car trace) "\n")
960               (setq trace (cdr trace)))
961             (goto-char (point-min))
962             (gnus-configure-windows 'split-trace)
963             (set-buffer restore)))
964         ;; See whether the split methods returned `junk'.
965         (if (equal group-art '(junk))
966             nil
967           ;; The article may be "cross-posted" to `junk'.  What
968           ;; to do?  Just remove the `junk' spec.  Don't really
969           ;; see anything else to do...
970           (let (elem)
971             (while (setq elem (car (memq 'junk group-art)))
972               (setq group-art (delq elem group-art)))
973             (nreverse group-art)))))))
974
975 (defun nnmail-insert-lines ()
976   "Insert how many lines there are in the body of the mail.
977 Return the number of characters in the body."
978   (let (lines chars)
979     (save-excursion
980       (goto-char (point-min))
981       (when (search-forward "\n\n" nil t)
982         (setq chars (- (point-max) (point)))
983         (setq lines (count-lines (point) (point-max)))
984         (forward-char -1)
985         (save-excursion
986           (when (re-search-backward "^Lines: " nil t)
987             (delete-region (point) (progn (forward-line 1) (point)))))
988         (beginning-of-line)
989         (insert (format "Lines: %d\n" (max lines 0)))
990         chars))))
991
992 (defun nnmail-insert-xref (group-alist)
993   "Insert an Xref line based on the (group . article) alist."
994   (save-excursion
995     (goto-char (point-min))
996     (when (search-forward "\n\n" nil t)
997       (forward-char -1)
998       (when (re-search-backward "^Xref: " nil t)
999         (delete-region (match-beginning 0)
1000                        (progn (forward-line 1) (point))))
1001       (insert (format "Xref: %s" (system-name)))
1002       (while group-alist
1003         (insert (format " %s:%d"
1004                         (mm-encode-coding-string
1005                          (caar group-alist)
1006                          nnmail-pathname-coding-system)
1007                         (cdar group-alist)))
1008         (setq group-alist (cdr group-alist)))
1009       (insert "\n"))))
1010
1011 ;;; Message washing functions
1012
1013 (defun nnmail-remove-leading-whitespace ()
1014   "Remove excessive whitespace from all headers."
1015   (goto-char (point-min))
1016   (while (re-search-forward "^\\([^ :]+: \\) +" nil t)
1017     (replace-match "\\1" t)))
1018
1019 (defun nnmail-remove-list-identifiers ()
1020   "Remove list identifiers from Subject headers."
1021   (let ((regexp (if (stringp nnmail-list-identifiers) nnmail-list-identifiers
1022                   (mapconcat 'identity nnmail-list-identifiers "\\|"))))
1023     (when regexp
1024       (goto-char (point-min))
1025       (when (re-search-forward
1026              (concat "^Subject: +\\(Re: +\\)?\\(" regexp "\\) *")
1027              nil t)
1028         (delete-region (match-beginning 2) (match-end 0))))))
1029
1030 (defun nnmail-remove-tabs ()
1031   "Translate TAB characters into SPACE characters."
1032   (subst-char-in-region (point-min) (point-max) ?\t ?  t))
1033
1034 (defun nnmail-fix-eudora-headers ()
1035   "Eudora has a broken References line, but an OK In-Reply-To."
1036   (goto-char (point-min))
1037   (when (re-search-forward "^X-Mailer:.*Eudora" nil t)
1038     (goto-char (point-min))
1039     (when (re-search-forward "^References:" nil t)
1040       (beginning-of-line)
1041       (insert "X-Gnus-Broken-Eudora-"))))
1042
1043 (custom-add-option 'nnmail-prepare-incoming-header-hook
1044                    'nnmail-fix-eudora-headers)
1045
1046 ;;; Utility functions
1047
1048 (defun nnmail-split-fancy ()
1049   "Fancy splitting method.
1050 See the documentation for the variable `nnmail-split-fancy' for documentation."
1051   (let ((syntab (syntax-table)))
1052     (unwind-protect
1053         (progn
1054           (set-syntax-table nnmail-split-fancy-syntax-table)
1055           (nnmail-split-it nnmail-split-fancy))
1056       (set-syntax-table syntab))))
1057
1058 (defvar nnmail-split-cache nil)
1059 ;; Alist of split expressions their equivalent regexps.
1060
1061 (defun nnmail-split-it (split)
1062   ;; Return a list of groups matching SPLIT.
1063   (let (cached-pair)
1064     (cond
1065      ;; nil split
1066      ((null split)
1067       nil)
1068
1069      ;; A group name.  Do the \& and \N subs into the string.
1070      ((stringp split)
1071       (when nnmail-split-tracing
1072         (push (format "\"%s\"" split) nnmail-split-trace))
1073       (list (nnmail-expand-newtext split)))
1074
1075      ;; Junk the message.
1076      ((eq split 'junk)
1077       (when nnmail-split-tracing
1078         (push "junk" nnmail-split-trace))
1079       (list 'junk))
1080
1081      ;; Builtin & operation.
1082      ((eq (car split) '&)
1083       (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
1084
1085      ;; Builtin | operation.
1086      ((eq (car split) '|)
1087       (let (done)
1088         (while (and (not done) (cdr split))
1089           (setq split (cdr split)
1090                 done (nnmail-split-it (car split))))
1091         done))
1092
1093      ;; Builtin : operation.
1094      ((eq (car split) ':)
1095       (nnmail-split-it (save-excursion (eval (cdr split)))))
1096
1097      ;; Builtin ! operation.
1098      ((eq (car split) '!)
1099       (funcall (cadr split) (nnmail-split-it (caddr split))))
1100
1101      ;; Check the cache for the regexp for this split.
1102      ((setq cached-pair (assq split nnmail-split-cache))
1103       (goto-char (point-max))
1104       ;; FIX FIX FIX problem with re-search-backward is that if you have
1105       ;; a split: (from "foo-\\(bar\\|baz\\)@gnus.org "mail.foo.\\1")
1106       ;; and someone mails a message with 'To: foo-bar@gnus.org' and
1107       ;; 'CC: foo-baz@gnus.org', we'll pick 'mail.foo.baz' as the group
1108       ;; if the cc line is a later header, even though the other choice
1109       ;; is probably better.  Also, this routine won't do a crosspost
1110       ;; when there are two different matches.
1111       ;; I guess you could just make this more determined, and it could
1112       ;; look for still more matches prior to this one, and recurse
1113       ;; on each of the multiple matches hit.  Of course, then you'd
1114       ;; want to make sure that nnmail-article-group or nnmail-split-fancy
1115       ;; removed duplicates, since there might be more of those.
1116       ;; I guess we could also remove duplicates in the & split case, since
1117       ;; that's the only thing that can introduce them.
1118       (when (re-search-backward (cdr cached-pair) nil t)
1119         (when nnmail-split-tracing
1120           (push (cdr cached-pair) nnmail-split-trace))
1121         ;; Someone might want to do a \N sub on this match, so get the
1122         ;; correct match positions.
1123         (goto-char (match-end 0))
1124         (let ((value (nth 1 split)))
1125           (re-search-backward (if (symbolp value)
1126                                   (cdr (assq value nnmail-split-abbrev-alist))
1127                                 value)
1128                               (match-end 1)))
1129         (nnmail-split-it (nth 2 split))))
1130
1131      ;; Not in cache, compute a regexp for the field/value pair.
1132      (t
1133       (let* ((field (nth 0 split))
1134              (value (nth 1 split))
1135              (regexp (concat "^\\(\\("
1136                              (if (symbolp field)
1137                                  (cdr (assq field nnmail-split-abbrev-alist))
1138                                field)
1139                              "\\):.*\\)\\<\\("
1140                              (if (symbolp value)
1141                                  (cdr (assq value nnmail-split-abbrev-alist))
1142                                value)
1143                              "\\)\\>")))
1144         (push (cons split regexp) nnmail-split-cache)
1145         ;; Now that it's in the cache, just call nnmail-split-it again
1146         ;; on the same split, which will find it immediately in the cache.
1147         (nnmail-split-it split))))))
1148
1149 (defun nnmail-expand-newtext (newtext)
1150   (let ((len (length newtext))
1151         (pos 0)
1152         c expanded beg N did-expand)
1153     (while (< pos len)
1154       (setq beg pos)
1155       (while (and (< pos len)
1156                   (not (= (aref newtext pos) ?\\)))
1157         (setq pos (1+ pos)))
1158       (unless (= beg pos)
1159         (push (substring newtext beg pos) expanded))
1160       (when (< pos len)
1161         ;; We hit a \; expand it.
1162         (setq did-expand t
1163               pos (1+ pos)
1164               c (aref newtext pos))
1165         (if (not (or (= c ?\&)
1166                      (and (>= c ?1)
1167                           (<= c ?9))))
1168             ;; \ followed by some character we don't expand.
1169             (push (char-to-string c) expanded)
1170           ;; \& or \N
1171           (if (= c ?\&)
1172               (setq N 0)
1173             (setq N (- c ?0)))
1174           (when (match-beginning N)
1175             (push (buffer-substring (match-beginning N) (match-end N))
1176                   expanded))))
1177       (setq pos (1+ pos)))
1178     (if did-expand
1179         (apply 'concat (nreverse expanded))
1180       newtext)))
1181
1182 ;; Activate a backend only if it isn't already activated.
1183 ;; If FORCE, re-read the active file even if the backend is
1184 ;; already activated.
1185 (defun nnmail-activate (backend &optional force)
1186   (nnheader-init-server-buffer)
1187   (let (file timestamp file-time)
1188     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
1189             force
1190             (and (setq file (ignore-errors
1191                               (symbol-value (intern (format "%s-active-file"
1192                                                             backend)))))
1193                  (setq file-time (nth 5 (file-attributes file)))
1194                  (or (not
1195                       (setq timestamp
1196                             (condition-case ()
1197                                 (symbol-value (intern
1198                                                (format "%s-active-timestamp"
1199                                                        backend)))
1200                               (error 'none))))
1201                      (not (consp timestamp))
1202                      (equal timestamp '(0 0))
1203                      (> (nth 0 file-time) (nth 0 timestamp))
1204                      (and (= (nth 0 file-time) (nth 0 timestamp))
1205                           (> (nth 1 file-time) (nth 1 timestamp))))))
1206         (save-excursion
1207           (or (eq timestamp 'none)
1208               (set (intern (format "%s-active-timestamp" backend))
1209                    file-time))
1210           (funcall (intern (format "%s-request-list" backend)))))
1211     t))
1212
1213 (defun nnmail-message-id ()
1214   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
1215
1216 ;;;
1217 ;;; nnmail duplicate handling
1218 ;;;
1219
1220 (defvar nnmail-cache-buffer nil)
1221
1222 (defun nnmail-cache-open ()
1223   (if (or (not nnmail-treat-duplicates)
1224           (and nnmail-cache-buffer
1225                (buffer-name nnmail-cache-buffer)))
1226       ()                                ; The buffer is open.
1227     (save-excursion
1228       (set-buffer
1229        (setq nnmail-cache-buffer
1230              (get-buffer-create " *nnmail message-id cache*")))
1231       (when (file-exists-p nnmail-message-id-cache-file)
1232         (nnheader-insert-file-contents nnmail-message-id-cache-file))
1233       (set-buffer-modified-p nil)
1234       (current-buffer))))
1235
1236 (defun nnmail-cache-close ()
1237   (when (and nnmail-cache-buffer
1238              nnmail-treat-duplicates
1239              (buffer-name nnmail-cache-buffer)
1240              (buffer-modified-p nnmail-cache-buffer))
1241     (save-excursion
1242       (set-buffer nnmail-cache-buffer)
1243       ;; Weed out the excess number of Message-IDs.
1244       (goto-char (point-max))
1245       (when (search-backward "\n" nil t nnmail-message-id-cache-length)
1246         (progn
1247           (beginning-of-line)
1248           (delete-region (point-min) (point))))
1249       ;; Save the buffer.
1250       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
1251           (make-directory (file-name-directory nnmail-message-id-cache-file)
1252                           t))
1253       (nnmail-write-region (point-min) (point-max)
1254                            nnmail-message-id-cache-file nil 'silent)
1255       (set-buffer-modified-p nil)
1256       (setq nnmail-cache-buffer nil)
1257       (kill-buffer (current-buffer)))))
1258
1259 (defun nnmail-cache-insert (id)
1260   (when nnmail-treat-duplicates
1261     (unless (gnus-buffer-live-p nnmail-cache-buffer)
1262       (nnmail-cache-open))
1263     (save-excursion
1264       (set-buffer nnmail-cache-buffer)
1265       (goto-char (point-max))
1266       (insert id "\n"))))
1267
1268 (defun nnmail-cache-id-exists-p (id)
1269   (when nnmail-treat-duplicates
1270     (save-excursion
1271       (set-buffer nnmail-cache-buffer)
1272       (goto-char (point-max))
1273       (search-backward id nil t))))
1274
1275 (defun nnmail-fetch-field (header)
1276   (save-excursion
1277     (save-restriction
1278       (message-narrow-to-head)
1279       (message-fetch-field header))))
1280
1281 (defun nnmail-check-duplication (message-id func artnum-func)
1282   (run-hooks 'nnmail-prepare-incoming-message-hook)
1283   ;; If this is a duplicate message, then we do not save it.
1284   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1285          (case-fold-search t)
1286          (action (when duplication
1287                    (cond
1288                     ((memq nnmail-treat-duplicates '(warn delete))
1289                      nnmail-treat-duplicates)
1290                     ((nnheader-functionp nnmail-treat-duplicates)
1291                      (funcall nnmail-treat-duplicates message-id))
1292                     (t
1293                      nnmail-treat-duplicates))))
1294          group-art)
1295     ;; We insert a line that says what the mail source is.
1296     (let ((case-fold-search t))
1297       (goto-char (point-min))
1298       (re-search-forward "^message-id[ \t]*:" nil t)
1299       (beginning-of-line)
1300       (insert (format "X-Gnus-Mail-Source: %s\n" mail-source-string)))
1301
1302     ;; Let the backend save the article (or not).
1303     (cond
1304      ((not duplication)
1305       (funcall func (setq group-art
1306                           (nreverse (nnmail-article-group artnum-func))))
1307       (nnmail-cache-insert message-id))
1308      ((eq action 'delete)
1309       (setq group-art nil))
1310      ((eq action 'warn)
1311       ;; We insert a warning.
1312       (let ((case-fold-search t))
1313         (goto-char (point-min))
1314         (re-search-forward "^message-id[ \t]*:" nil t)
1315         (beginning-of-line)
1316         (insert
1317          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1318         (funcall func (setq group-art
1319                             (nreverse (nnmail-article-group artnum-func))))))
1320      (t
1321       (funcall func (setq group-art
1322                           (nreverse (nnmail-article-group artnum-func))))))
1323     ;; Add the group-art list to the history list.
1324     (if group-art
1325         (push group-art nnmail-split-history)
1326       (delete-region (point-min) (point-max)))))
1327
1328 ;;; Get new mail.
1329
1330 (defvar nnmail-fetched-sources nil)
1331
1332 (defun nnmail-get-value (&rest args)
1333   (let ((sym (intern (apply 'format args))))
1334     (when (boundp sym)
1335       (symbol-value sym))))
1336
1337 (defun nnmail-get-new-mail (method exit-func temp
1338                                    &optional group spool-func)
1339   "Read new incoming mail."
1340   (let* ((sources (if (listp nnmail-spool-file) nnmail-spool-file
1341                     (list nnmail-spool-file)))
1342          (group-in group)
1343          (i 0)
1344          incoming incomings source)
1345     (when (and (nnmail-get-value "%s-get-new-mail" method)
1346                nnmail-spool-file)
1347       ;; We first activate all the groups.
1348       (nnmail-activate method)
1349       ;; Allow the user to hook.
1350       (run-hooks 'nnmail-pre-get-new-mail-hook)
1351       ;; Open the message-id cache.
1352       (nnmail-cache-open)
1353       ;; The we go through all the existing mail source specification
1354       ;; and fetch the mail from each.
1355       (while (setq source (pop sources))
1356         ;; Be compatible with old values.
1357         (cond
1358          ((stringp source)
1359           (setq source
1360                 (cond
1361                  ((string-match "^po:" source)
1362                   (list 'pop :user (substring source (match-end 0))))
1363                  ((file-directory-p source)
1364                   (list 'directory :path source))
1365                  (t
1366                   (list 'file :path source)))))
1367          ((eq source 'procmail)
1368           (message "Invalid value for nnmail-spool-file: `procmail'")
1369           nil))
1370         ;; Hack to only fetch the contents of a single group's spool file.
1371         (when (and (eq (car source) 'directory)
1372                    group)
1373           (mail-source-bind (directory source)
1374             (setq source (append source
1375                                  (list
1376                                   :predicate
1377                                   `(lambda (file)
1378                                      (string-match 
1379                                       ,(concat
1380                                         (regexp-quote (concat group suffix)) 
1381                                         "$")
1382                                       file)))))))
1383         (when nnmail-fetched-sources
1384           (if (member source nnmail-fetched-sources)
1385               (setq source nil)
1386             (push source nnmail-fetched-sources)))
1387         (when source
1388           (nnheader-message 4 "%s: Reading incoming mail from %s..."
1389                             method (car source))
1390           (when (mail-source-fetch
1391                  source
1392                  `(lambda (file orig-file)
1393                     (nnmail-split-incoming
1394                      file ',(intern (format "%s-save-mail" method))
1395                      ',spool-func (nnmail-get-split-group orig-file source)
1396                      ',(intern (format "%s-active-number" method)))))
1397             (incf i))))
1398       ;; If we did indeed read any incoming spools, we save all info.
1399       (unless (zerop i)
1400         (nnmail-save-active
1401          (nnmail-get-value "%s-group-alist" method)
1402          (nnmail-get-value "%s-active-file" method))
1403         (when exit-func
1404           (funcall exit-func))
1405         (run-hooks 'nnmail-read-incoming-hook)
1406         (nnheader-message 4 "%s: Reading incoming mail...done" method))
1407       ;; Close the message-id cache.
1408       (nnmail-cache-close)
1409       ;; Allow the user to hook.
1410       (run-hooks 'nnmail-post-get-new-mail-hook))))
1411
1412 (defun nnmail-expired-article-p (group time force &optional inhibit)
1413   "Say whether an article that is TIME old in GROUP should be expired."
1414   (if force
1415       t
1416     (let ((days (or (and nnmail-expiry-wait-function
1417                          (funcall nnmail-expiry-wait-function group))
1418                     nnmail-expiry-wait)))
1419       (cond ((or (eq days 'never)
1420                  (and (not force)
1421                       inhibit))
1422              ;; This isn't an expirable group.
1423              nil)
1424             ((eq days 'immediate)
1425              ;; We expire all articles on sight.
1426              t)
1427             ((equal time '(0 0))
1428              ;; This is an ange-ftp group, and we don't have any dates.
1429              nil)
1430             ((numberp days)
1431              (setq days (days-to-time days))
1432              ;; Compare the time with the current time.
1433              (ignore-errors (time-less-p days (time-since time))))))))
1434
1435 (defun nnmail-check-syntax ()
1436   "Check (and modify) the syntax of the message in the current buffer."
1437   (save-restriction
1438     (message-narrow-to-head)
1439     (let ((case-fold-search t))
1440       (unless (re-search-forward "^Message-ID[ \t]*:" nil t)
1441         (insert "Message-ID: " (nnmail-message-id) "\n")))))
1442
1443 (defun nnmail-write-region (start end filename &optional append visit lockname)
1444   "Do a `write-region', and then set the file modes."
1445   (let ((coding-system-for-write nnmail-file-coding-system)
1446         (pathname-coding-system 'binary))
1447     (write-region start end filename append visit lockname)
1448     (set-file-modes filename nnmail-default-file-modes)))
1449
1450 ;;;
1451 ;;; Status functions
1452 ;;;
1453
1454 (defun nnmail-replace-status (name value)
1455   "Make status NAME and VALUE part of the current status line."
1456   (save-restriction
1457     (message-narrow-to-head)
1458     (let ((status (nnmail-decode-status)))
1459       (setq status (delq (member name status) status))
1460       (when value
1461         (push (cons name value) status))
1462       (message-remove-header "status")
1463       (goto-char (point-max))
1464       (insert "Status: " (nnmail-encode-status status) "\n"))))
1465
1466 (defun nnmail-decode-status ()
1467   "Return a status-value alist from STATUS."
1468   (goto-char (point-min))
1469   (when (re-search-forward "^Status: " nil t)
1470     (let (name value status)
1471       (save-restriction
1472         ;; Narrow to the status.
1473         (narrow-to-region
1474          (point)
1475          (if (re-search-forward "^[^ \t]" nil t)
1476              (1- (point))
1477            (point-max)))
1478         ;; Go through all elements and add them to the list.
1479         (goto-char (point-min))
1480         (while (re-search-forward "[^ \t=]+" nil t)
1481           (setq name (match-string 0))
1482           (if (not (eq (char-after) ?=))
1483               ;; Implied "yes".
1484               (setq value "yes")
1485             (forward-char 1)
1486             (if (not (eq (char-after) ?\"))
1487                 (if (not (looking-at "[^ \t]"))
1488                     ;; Implied "no".
1489                     (setq value "no")
1490                   ;; Unquoted value.
1491                   (setq value (match-string 0))
1492                   (goto-char (match-end 0)))
1493               ;; Quoted value.
1494               (setq value (read (current-buffer)))))
1495           (push (cons name value) status)))
1496       status)))
1497
1498 (defun nnmail-encode-status (status)
1499   "Return a status string from STATUS."
1500   (mapconcat
1501    (lambda (elem)
1502      (concat
1503       (car elem) "="
1504       (if (string-match "[ \t]" (cdr elem))
1505           (prin1-to-string (cdr elem))
1506         (cdr elem))))
1507    status " "))
1508
1509 (defun nnmail-split-history ()
1510   "Generate an overview of where the last mail split put articles."
1511   (interactive)
1512   (unless nnmail-split-history
1513     (error "No current split history"))
1514   (with-output-to-temp-buffer "*nnmail split history*"
1515     (let ((history nnmail-split-history)
1516           elem)
1517       (while (setq elem (pop history))
1518         (princ (mapconcat (lambda (ga)
1519                             (concat (car ga) ":" (int-to-string (cdr ga))))
1520                           elem
1521                           ", "))
1522         (princ "\n")))))
1523
1524 (defun nnmail-purge-split-history (group)
1525   "Remove all instances of GROUP from `nnmail-split-history'."
1526   (let ((history nnmail-split-history))
1527     (while history
1528       (setcar history (gnus-delete-if (lambda (e) (string= (car e) group))
1529                                       (car history)))
1530       (pop history))
1531     (setq nnmail-split-history (delq nil nnmail-split-history))))
1532
1533 (defun nnmail-new-mail-p (group)
1534   "Say whether GROUP has new mail."
1535   (let ((his nnmail-split-history)
1536         found)
1537     (while his
1538       (when (assoc group (pop his))
1539         (setq found t
1540               his nil)))
1541     found))
1542
1543 (defun nnmail-within-headers-p ()
1544   "Check to see if point is within the headers of a unix mail message.
1545 Doesn't change point."
1546   (let ((pos (point)))
1547     (save-excursion
1548       (and (nnmail-search-unix-mail-delim-backward)
1549            (not (search-forward "\n\n" pos t))))))
1550
1551 (run-hooks 'nnmail-load-hook)
1552
1553 (provide 'nnmail)
1554
1555 ;;; nnmail.el ends here