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