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