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