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