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