*** empty log message ***
[gnus] / lisp / nnmail.el
1 ;;; nnmail.el --- mail support functions for the Gnus mail backends
2 ;; Copyright (C) 1995 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
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'nnheader)
28 (require 'rmail)
29 (require 'timezone)
30 (require 'sendmail)
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
69 directory.  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-expiry-wait 7
78   "*Articles that are older than `nnmail-expiry-wait' days will be expired.")
79
80 (defvar nnmail-expiry-wait-function nil
81   "*Variable that holds function to specify how old articles should be before they are expired.
82   The function will be called with the name of the group that the
83 expiry is to be performed in, and it should return an integer that
84 says how many days an article can be stored before it is considered
85 'old'. 
86
87 Eg.:
88
89 (setq nnmail-expiry-wait-function
90       (lambda (newsgroup)
91         (cond ((string-match \"private\" newsgroup) 31)
92               ((string-match \"junk\" newsgroup) 1)
93               (t 7))))")
94
95 (defvar nnmail-spool-file 
96   (or (getenv "MAIL")
97       (concat "/usr/spool/mail/" (user-login-name)))
98   "Where the mail backends will look for incoming mail.
99 This variable is \"/usr/spool/mail/$user\" by default.
100 If this variable is nil, no mail backends will read incoming mail.
101 If this variable is a list, all files mentioned in this list will be
102 used as incoming mailboxes.")
103
104 (defvar nnmail-use-procmail nil
105   "*If non-nil, the mail backends will look in `nnmail-procmail-directory' for spool files.
106 The file(s) in `nnmail-spool-file' will also be read.")
107
108 (defvar nnmail-procmail-directory "~/incoming/"
109   "*When using procmail (and the like), incoming mail is put in this directory.
110 The Gnus mail backends will read the mail from this directory.")
111
112 (defvar nnmail-procmail-suffix ".spool"
113   "*Suffix of files created by procmail (and the like).
114 This variable might be a suffix-regexp to match the suffixes of
115 several files - eg. \".spool[0-9]*\".")
116
117 (defvar nnmail-resplit-incoming nil
118   "*If non-nil, re-split incoming procmail sorted mail.")
119
120 (defvar nnmail-delete-file-function 'delete-file
121   "Function called to delete files in some mail backends.")
122
123 (defvar nnmail-movemail-program "movemail"
124   "*A command to be executed to move mail from the inbox.
125 The default is \"movemail\".")
126
127 (defvar nnmail-read-incoming-hook nil
128   "*Hook that will be run after the incoming mail has been transferred.
129 The incoming mail is moved from `nnmail-spool-file' (which normally is
130 something like \"/usr/spool/mail/$user\") to the user's home
131 directory. This hook is called after the incoming mail box has been
132 emptied, and can be used to call any mail box programs you have
133 running (\"xwatch\", etc.)
134
135 Eg.
136
137 \(add-hook 'nnmail-read-incoming-hook 
138            (lambda () 
139              (start-process \"mailsend\" nil 
140                             \"/local/bin/mailsend\" \"read\" \"mbox\")))
141
142 If you have xwatch running, this will alert it that mail has been
143 read.  
144
145 If you use `display-time', you could use something like this:
146
147 \(add-hook 'nnmail-read-incoming-hook
148           (lambda ()
149             ;; Update the displayed time, since that will clear out
150             ;; the flag that says you have mail.
151             (if (eq (process-status \"display-time\") 'run)
152                 (display-time-filter display-time-process \"\"))))") 
153
154 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
155 (defvar nnmail-prepare-incoming-hook nil
156   "*Hook called before treating incoming mail.
157 The hook is run in a buffer with all the new, incoming mail.")
158
159 ;; Suggested by Mejia Pablo J <pjm9806@usl.edu>.
160 (defvar nnmail-tmp-directory nil
161   "*If non-nil, use this directory for temporary storage when reading incoming mail.")
162
163 (defvar nnmail-large-newsgroup 50
164   "*The number of the articles which indicates a large newsgroup.
165 If the number of the articles is greater than the value, verbose
166 messages will be shown to indicate the current status.")
167
168 (defvar nnmail-split-fancy "mail.misc"
169   "*Incoming mail can be split according to this fancy variable.
170 To enable this, set `nnmail-split-methods' to `nnmail-split-fancy'.
171
172 The format is this variable is SPLIT, where SPLIT can be one of
173 the following:
174
175 GROUP: Mail will be stored in GROUP (a string).
176
177 \(FIELD VALUE SPLIT): If the message field FIELD (a regexp) contains
178   VALUE (a regexp), store the messages as specified by SPLIT.
179
180 \(| SPLIT...): Process each SPLIT expression until one of them matches.
181   A SPLIT expression is said to match if it will cause the mail
182   message to be stored in one or more groups.  
183
184 \(& SPLIT...): Process each SPLIT expression.
185
186 FIELD must match a complete field name.  VALUE must match a complete
187 word according to the fundamental mode syntax table.  You can use .*
188 in the regexps to match partial field names or words.
189
190 FIELD and VALUE can also be lisp symbols, in that case they are expanded
191 as specified in `nnmail-split-abbrev-alist'.
192
193 Example:
194
195 \(setq nnmail-split-methods 'nnmail-split-fancy
196       nnmail-split-fancy
197       ;; Messages from the mailer deamon are not crossposted to any of
198       ;; the ordinary groups.  Warnings are put in a separate group
199       ;; from real errors.
200       '(| (\"from\" mail (| (\"subject\" \"warn.*\" \"mail.warning\")
201                           \"mail.misc\"))
202           ;; Non-error messages are crossposted to all relevant
203           ;; groups, but we don't crosspost between the group for the
204           ;; (ding) list and the group for other (ding) related mail.
205           (& (| (any \"ding@ifi\\\\.uio\\\\.no\" \"ding.list\")
206                 (\"subject\" \"ding\" \"ding.misc\"))
207              ;; Other mailing lists...
208              (any \"procmail@informatik\\\\.rwth-aachen\\\\.de\" \"procmail.list\")
209              (any \"SmartList@informatik\\\\.rwth-aachen\\\\.de\" \"SmartList.list\")
210              ;; People...
211              (any \"larsi@ifi\\\\.uio\\\\.no\" \"people.Lars Magne Ingebrigtsen\"))
212           ;; Unmatched mail goes to the catch all group.
213           \"misc.misc\"))")
214
215 (defvar nnmail-split-abbrev-alist
216   '((any . "from\\|to\\|cc\\|sender\\|apparently-to")
217     (mail . "mailer-daemon\\|postmaster"))
218   "*Alist of abbreviations allowed in `nnmail-split-fancy'.")
219
220 (defvar nnmail-delete-incoming nil
221   "*If non-nil, the mail backends will delete incoming files after splitting.")
222
223 (defvar nnmail-message-id-cache-length 1000
224   "*The approximate number of Message-IDs nnmail will keep in its cache.
225 If this variable is nil, no checking on duplicate messages will be
226 perfomed.")
227
228 (defvar nnmail-message-id-cache-file "~/.nnmail-cache"
229   "*The file name of the nnmail Message-ID cache.")
230
231 (defvar nnmail-delete-duplicates nil
232   "*If non-nil, nnmail will delete any duplicate mails it sees.")
233
234 \f
235
236 (defconst nnmail-version "nnmail 1.0"
237   "nnmail version.")
238
239 \f
240
241 (defun nnmail-request-post (&optional server)
242   (mail-send-and-exit nil))
243
244 (defun nnmail-find-file (file)
245   "Insert FILE in server buffer safely."
246   (set-buffer nntp-server-buffer)
247   (erase-buffer)
248   (condition-case ()
249       (progn (insert-file-contents file) t)
250     (file-error nil)))
251
252 (defun nnmail-group-pathname (group mail-dir)
253   "Make pathname for GROUP."
254   (let ((mail-dir (file-name-as-directory (expand-file-name mail-dir))))
255     ;; If this directory exists, we use it directly.
256     (if (or nnmail-use-long-file-names 
257             (file-directory-p (concat mail-dir group)))
258         (concat mail-dir group "/")
259       ;; If not, we translate dots into slashes.
260       (concat mail-dir (nnmail-replace-chars-in-string group ?. ?/) "/"))))
261
262 (defun nnmail-replace-chars-in-string (string from to)
263   "Replace characters in STRING from FROM to TO."
264   (let ((string (substring string 0))   ;Copy string.
265         (len (length string))
266         (idx 0))
267     ;; Replace all occurrences of FROM with TO.
268     (while (< idx len)
269       (if (= (aref string idx) from)
270           (aset string idx to))
271       (setq idx (1+ idx)))
272     string))
273
274 (defun nnmail-days-between (date1 date2)
275   ;; Return the number of days between date1 and date2.
276   (let ((d1 (mapcar (lambda (s) (and s (string-to-int s)) )
277                     (timezone-parse-date date1)))
278         (d2 (mapcar (lambda (s) (and s (string-to-int s)) )
279                     (timezone-parse-date date2))))
280     (- (timezone-absolute-from-gregorian 
281         (nth 1 d1) (nth 2 d1) (car d1))
282        (timezone-absolute-from-gregorian 
283         (nth 1 d2) (nth 2 d2) (car d2)))))
284
285 ;; Function taken from rmail.el.
286 (defun nnmail-move-inbox (inbox tofile)
287   (let ((inbox (file-truename
288                 (expand-file-name (substitute-in-file-name inbox))))
289         movemail popmail errors)
290     ;; Check whether the inbox is to be moved to the special tmp dir. 
291     (if nnmail-tmp-directory
292         (setq tofile (concat (file-name-as-directory nnmail-tmp-directory)
293                              (file-name-nondirectory tofile))))
294     ;; Make the filename unique.
295     (setq tofile (nnmail-make-complex-temp-name (expand-file-name tofile)))
296     ;; We create the directory the tofile is to reside in if it
297     ;; doesn't exist.
298     (or (file-exists-p (file-name-directory tofile))
299         (make-directory (file-name-directory tofile) 'parents))
300     ;; If getting from mail spool directory,
301     ;; use movemail to move rather than just renaming,
302     ;; so as to interlock with the mailer.
303     (or (setq popmail (string-match "^po:" (file-name-nondirectory inbox)))
304         (setq movemail t))
305     (if popmail (setq inbox (file-name-nondirectory inbox)))
306     (if movemail
307         ;; On some systems, /usr/spool/mail/foo is a directory
308         ;; and the actual inbox is /usr/spool/mail/foo/foo.
309         (if (file-directory-p inbox)
310             (setq inbox (expand-file-name (user-login-name) inbox))))
311     (if popmail
312         (message "Getting mail from post office ...")
313       (if (or (and (file-exists-p tofile)
314                    (/= 0 (nth 7 (file-attributes tofile))))
315               (and (file-exists-p inbox)
316                    (/= 0 (nth 7 (file-attributes inbox)))))
317           (message "Getting mail from %s..." inbox)))
318     ;; Set TOFILE if have not already done so, and
319     ;; rename or copy the file INBOX to TOFILE if and as appropriate.
320     (cond ((or (file-exists-p tofile) (and (not popmail)
321                                            (not (file-exists-p inbox))))
322            nil)
323           ((and (not movemail) (not popmail))
324            ;; Try copying.  If that fails (perhaps no space),
325            ;; rename instead.
326            (condition-case nil
327                (copy-file inbox tofile nil)
328              (error
329               ;; Third arg is t so we can replace existing file TOFILE.
330               (rename-file inbox tofile t)))
331            ;; Make the real inbox file empty.
332            ;; Leaving it deleted could cause lossage
333            ;; because mailers often won't create the file.
334            (condition-case ()
335                (write-region (point) (point) inbox)
336              (file-error nil)))
337           (t
338            (unwind-protect
339                (save-excursion
340                  (setq errors (generate-new-buffer " *nnmail loss*"))
341                  (buffer-disable-undo errors)
342                  (let ((default-directory "/"))
343                    (call-process
344                     (expand-file-name nnmail-movemail-program exec-directory)
345                     nil errors nil inbox tofile))
346                  (if (not (buffer-modified-p errors))
347                      ;; No output => movemail won
348                      nil
349                    (set-buffer errors)
350                    (subst-char-in-region (point-min) (point-max) ?\n ?\  )
351                    (goto-char (point-max))
352                    (skip-chars-backward " \t")
353                    (delete-region (point) (point-max))
354                    (goto-char (point-min))
355                    (if (looking-at "movemail: ")
356                        (delete-region (point-min) (match-end 0)))
357                    (beep t)
358                    (message (concat "movemail: "
359                                     (buffer-substring (point-min)
360                                                       (point-max))))
361                    (sit-for 3)
362                    nil)))))
363     (and errors
364          (buffer-name errors)
365          (kill-buffer errors))
366     tofile))
367
368 (defun nnmail-get-active ()
369   "Returns an assoc of group names and active ranges.
370 nn*-request-list should have been called before calling this function."
371   (let (group-assoc)
372     ;; Go through all groups from the active list.
373     (save-excursion
374       (set-buffer nntp-server-buffer)
375       (goto-char (point-min))
376       (while (re-search-forward 
377               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
378         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
379         (push (list (match-string 1)
380                     (cons (string-to-int (match-string 3))
381                           (string-to-int (match-string 2))))
382               group-assoc)))
383     group-assoc))
384
385 (defun nnmail-save-active (group-assoc file-name)
386   (let (group)
387     (save-excursion
388       (set-buffer (get-buffer-create " *nnmail active*"))
389       (buffer-disable-undo (current-buffer))
390       (erase-buffer)
391       (while group-assoc
392         (setq group (car group-assoc))
393         (insert (format "%s %d %d y\n" (car group) (cdr (car (cdr group)) )
394                         (car (car (cdr group)))))
395         (setq group-assoc (cdr group-assoc)))
396       (write-region 1 (point-max) (expand-file-name file-name) nil 'nomesg)
397       (kill-buffer (current-buffer)))))
398
399 (defun nnmail-get-split-group (file group)
400   (if (or (eq nnmail-spool-file 'procmail)
401           nnmail-use-procmail)
402       (cond (group group)
403             ((string-match (concat "^" (expand-file-name
404                                         (file-name-as-directory
405                                          nnmail-procmail-directory))
406                                    "\\(.*\\)" nnmail-procmail-suffix "$")
407                            (expand-file-name file))
408              (substring (expand-file-name file)
409                         (match-beginning 1) (match-end 1)))
410             (t
411              group))
412     group))
413
414 (defun nnmail-split-incoming (incoming func &optional exit-func group)
415   "Go through the entire INCOMING file and pick out each individual mail.
416 FUNC will be called with the buffer narrowed to each mail."
417   (let ((delim (concat "^" rmail-unix-mail-delimiter))
418         ;; If this is a group-specific split, we bind the split
419         ;; methods to just this group.
420         (nnmail-split-methods (if (and group
421                                        (or (eq nnmail-spool-file 'procmail)
422                                            nnmail-use-procmail)
423                                        (not nnmail-resplit-incoming))
424                                   (list (list group ""))
425                                 nnmail-split-methods))
426         start end content-length do-search message-id)
427     (save-excursion
428       ;; Open the message-id cache.
429       (nnmail-cache-open)
430       ;; Insert the incoming file.
431       (set-buffer (get-buffer-create " *nnmail incoming*"))
432       (buffer-disable-undo (current-buffer))
433       (erase-buffer)
434       (insert-file-contents incoming)
435       (goto-char (point-min))
436       (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
437       ;; Go to the beginning of the first mail...
438       (if (and (re-search-forward delim nil t)
439                (goto-char (match-beginning 0)))
440           ;; and then carry on until the bitter end.
441           (while (not (eobp))
442             (setq start (point))
443             ;; Skip all the headers in case there are more "From "s...
444             (if (not (search-forward "\n\n" nil t))
445                 (forward-line 1))
446             ;; Find the Message-ID header.
447             (save-excursion
448               (if (re-search-backward "^Message-ID:[ \t]*\\(<[^>]*>\\)" nil t)
449                   (setq message-id (match-string 1))
450                 ;; There is no Message-ID here, so we create one.
451                 (forward-line -1)
452                 (insert "Message-ID: " (setq message-id (nnmail-message-id))
453                         "\n")))
454             ;; Look for a Content-Length header.
455             (if (not (save-excursion
456                        (when (re-search-backward 
457                               "^Content-Length: \\([0-9]+\\)" start t)
458                          (setq content-length 
459                                (string-to-int (match-string 1)))
460                          ;; We destroy the header, since none of
461                          ;; the backends ever use it, and we do not
462                          ;; want to confuse other mailers by having
463                          ;; a (possibly) faulty header.
464                          (insert "X-") 
465                          t)))
466                 (setq do-search t)
467               (if (or (= (+ (point) content-length) (point-max))
468                       (save-excursion
469                         (goto-char (+ (point) content-length))
470                         (looking-at delim)))
471                   (progn
472                     (goto-char (+ (point) content-length))
473                     (setq do-search nil))
474                 (setq do-search t)))
475             ;; Go to the beginning of the next article - or to the end
476             ;; of the buffer.  
477             (if do-search
478                 (if (re-search-forward delim nil t)
479                     (goto-char (match-beginning 0))
480                   (goto-char (point-max))))
481             (save-excursion
482               (save-restriction
483                 (narrow-to-region start (point))
484                 (goto-char (point-min))
485                 ;; If this is a duplicate message, then we do not save it.
486                 (if (nnmail-cache-id-exists-p message-id)
487                     (delete-region (point-min) (point-max))
488                   (nnmail-cache-insert message-id)
489                   (funcall func))
490                 (setq end (point-max))))
491             (goto-char end)))
492       ;; Close the message-id cache.
493       (nnmail-cache-close)
494       (if exit-func (funcall exit-func))
495       (kill-buffer (current-buffer)))))
496
497 ;; Mail crossposts syggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
498 (defun nnmail-article-group (func)
499   "Look at the headers and return an alist of groups that match.
500 FUNC will be called with the group name to determine the article number."
501   (let ((methods nnmail-split-methods)
502         (obuf (current-buffer))
503         (beg (point-min))
504         end group-art)
505     (if (and (sequencep methods) (= (length methods) 1))
506         ;; If there is only just one group to put everything in, we
507         ;; just return a list with just this one method in.
508         (setq group-art
509               (list (cons (car (car methods))
510                           (funcall func (car (car methods))))))
511       ;; We do actual comparison.
512       (save-excursion
513         ;; Find headers.
514         (goto-char beg)
515         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
516         (set-buffer (get-buffer-create " *nnmail work*"))
517         (buffer-disable-undo (current-buffer))
518         (erase-buffer)
519         ;; Copy the headers into the work buffer.
520         (insert-buffer-substring obuf beg end)
521         ;; Fold continuation lines.
522         (goto-char (point-min))
523         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
524           (replace-match " " t t))
525         (if (and (symbolp nnmail-split-methods)
526                  (fboundp nnmail-split-methods))
527             (setq group-art
528                   (mapcar
529                    (lambda (group) (cons group (funcall func group)))
530                    (condition-case nil
531                        (funcall nnmail-split-methods)
532                      (error
533                       (message "\
534 Problems with `nnmail-split-methods', using `bogus' mail group")
535                       (sit-for 1)
536                       '("bogus")))))
537           ;; Go throught the split methods to find a match.
538           (while (and methods (or nnmail-crosspost (not group-art)))
539             (goto-char (point-max))
540             (if (or (cdr methods)
541                     (not (equal "" (nth 1 (car methods)))))
542                 (if (and (condition-case () 
543                              (if (stringp (nth 1 (car methods)))
544                                  (re-search-backward
545                                   (car (cdr (car methods))) nil t)
546                                ;; Suggested by Brian Edmonds 
547                                ;; <edmonds@cs.ubc.ca>.
548                                (funcall (nth 1 (car methods)) 
549                                         (car (car methods))))
550                            (error nil))
551                          ;; Don't enter the article into the same group twice.
552                          (not (assoc (car (car methods)) group-art)))
553                     (setq group-art
554                           (cons (cons (car (car methods))
555                                       (funcall func (car (car methods)))) 
556                                 group-art)))
557               (or group-art
558                   (setq group-art 
559                         (list (cons (car (car methods)) 
560                                     (funcall func (car (car methods))))))))
561             (setq methods (cdr methods))))
562         (kill-buffer (current-buffer))
563         group-art))))
564
565 (defun nnmail-insert-lines ()
566   "Insert how many lines and chars there are in the body of the mail."
567   (let (lines chars)
568     (save-excursion
569       (goto-char (point-min))
570       (if (search-forward "\n\n" nil t) 
571           (progn
572             (setq chars (- (point-max) (point)))
573             (setq lines (- (count-lines (point) (point-max)) 1))
574             (forward-char -1)
575             (save-excursion
576               (if (re-search-backward "^Lines: " nil t)
577                   (delete-region (point) (progn (forward-line 1) (point)))))
578             (insert (format "Lines: %d\n" lines))
579             chars)))))
580
581 (defun nnmail-insert-xref (group-alist)
582   "Insert an Xref line based on the (group . article) alist."
583   (save-excursion
584     (goto-char (point-min))
585     (if (search-forward "\n\n" nil t) 
586         (progn
587           (forward-char -1)
588           (if (re-search-backward "^Xref: " nil t)
589               (delete-region (match-beginning 0) 
590                              (progn (forward-line 1) (point))))
591           (insert (format "Xref: %s" (system-name)))
592           (while group-alist
593             (insert (format " %s:%d" (car (car group-alist)) 
594                             (cdr (car group-alist))))
595             (setq group-alist (cdr group-alist)))
596           (insert "\n")))))
597
598 ;; Written by byer@mv.us.adobe.com (Scott Byer).
599 (defun nnmail-make-complex-temp-name (prefix)
600   (let ((newname (make-temp-name prefix))
601         (newprefix prefix))
602     (while (file-exists-p newname)
603       (setq newprefix (concat newprefix "x"))
604       (setq newname (make-temp-name newprefix)))
605     newname))
606
607 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
608
609 (defun nnmail-split-fancy ()
610   "Fancy splitting method.
611 See the documentation for the variable `nnmail-split-fancy' for documentation."
612   (nnmail-split-it nnmail-split-fancy))
613
614 (defvar nnmail-split-cache nil)
615 ;; Alist of split expresions their equivalent regexps.
616
617 (defun nnmail-split-it (split)
618   ;; Return a list of groups matching SPLIT.
619   (cond ((stringp split)
620          ;; A group.
621          (list split))
622         ((eq (car split) '&)
623          (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
624         ((eq (car split) '|)
625          (let (done)
626            (while (and (not done) (cdr split))
627              (setq split (cdr split)
628                    done (nnmail-split-it (car split))))
629            done))       ((assq split nnmail-split-cache)
630                          ;; A compiled match expression.
631          (goto-char (point-max))
632          (if (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
633              (nnmail-split-it (nth 2 split))))
634         (t
635          ;; An uncompiled match.
636          (let* ((field (nth 0 split))
637                 (value (nth 1 split))
638                 (regexp (concat "^\\(" 
639                                 (if (symbolp field)
640                                     (cdr (assq field 
641                                                nnmail-split-abbrev-alist))
642                                   field)
643                                 "\\):.*\\<\\("
644                                 (if (symbolp value)
645                                     (cdr (assq value
646                                                nnmail-split-abbrev-alist))
647                                   value)
648                                 "\\>\\)")))
649            (setq nnmail-split-cache 
650                  (cons (cons split regexp) nnmail-split-cache))
651            (goto-char (point-max))
652            (if (re-search-backward regexp nil t)
653                (nnmail-split-it (nth 2 split)))))))
654
655 ;; Get a list of spool files to read.
656 (defun nnmail-get-spool-files (&optional group)
657   (if (null nnmail-spool-file)
658       ;; No spool file whatsoever.
659       nil)
660   (let* ((procmails 
661           ;; If procmail is used to get incoming mail, the files
662           ;; are stored in this directory.
663           (and (file-exists-p nnmail-procmail-directory)
664                (directory-files 
665                 nnmail-procmail-directory 
666                 t (concat (if group group "")
667                           nnmail-procmail-suffix "$") t)))
668          (p procmails))
669     ;; Remove any directories that inadvertantly match the procmail
670     ;; suffix, which might happen if the suffix is "".
671     (while p
672       (and (or (file-directory-p (car p))
673                (file-symlink-p (car p)))
674            (setq procmails (delete (car p) procmails)))
675       (setq p (cdr p)))
676     (cond ((listp nnmail-spool-file)
677            (append nnmail-spool-file procmails))
678           ((stringp nnmail-spool-file)
679            (cons nnmail-spool-file procmails))
680           (t
681            procmails))))
682
683 ;; Activate a backend only if it isn't already activated. 
684 ;; If FORCE, re-read the active file even if the backend is 
685 ;; already activated.
686 (defun nnmail-activate (backend &optional force)
687   (let (file timestamp file-time)
688     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
689             force
690             (and (setq file (condition-case ()
691                                 (symbol-value (intern (format "%s-active-file" 
692                                                               backend)))
693                               (error nil)))
694                  (setq file-time (nth 5 (file-attributes file)))
695                  (or (not
696                       (setq timestamp
697                             (condition-case ()
698                                 (symbol-value (intern
699                                                (format "%s-active-timestamp" 
700                                                        backend)))
701                               (error 'none))))
702                      (not (consp timestamp))
703                      (equal timestamp '(0 0))
704                      (> (nth 0 file-time) (nth 0 timestamp))
705                      (and (= (nth 0 file-time) (nth 0 timestamp))
706                           (> (nth 1 file-time) (nth 1 timestamp))))))
707         (save-excursion
708           (or (eq timestamp 'none)
709               (set (intern (format "%s-active-timestamp" backend)) 
710                    (current-time)))
711           (funcall (intern (format "%s-request-list" backend)))
712           (set (intern (format "%s-group-alist" backend)) 
713                (nnmail-get-active))))
714     t))
715
716 (defun nnmail-message-id ()
717   (concat "<" (nnmail-unique-id) "@totally-fudged-out-message-id>"))
718
719 (defvar nnmail-unique-id-char nil)
720
721 (defun nnmail-number-base36 (num len)
722   (if (if (< len 0) (<= num 0) (= len 0))
723       ""
724     (concat (nnmail-number-base36 (/ num 36) (1- len))
725             (char-to-string (aref "zyxwvutsrqponmlkjihgfedcba9876543210"
726                                   (% num 36))))))
727
728 (defun nnmail-unique-id ()
729   (setq nnmail-unique-id-char
730         (% (1+ (or nnmail-unique-id-char (logand (random t) (1- (lsh 1 20)))))
731            ;; (current-time) returns 16-bit ints,
732            ;; and 2^16*25 just fits into 4 digits i base 36.
733            (* 25 25)))
734   (let ((tm (if (fboundp 'current-time)
735                 (current-time) '(12191 46742 287898))))
736     (concat
737      (nnmail-number-base36 (+ (car   tm) 
738                               (lsh (% nnmail-unique-id-char 25) 16)) 4)
739      (nnmail-number-base36 (+ (nth 1 tm) 
740                               (lsh (/ nnmail-unique-id-char 25) 16)) 4))))
741
742 ;;;
743 ;;; nnmail duplicate handling
744 ;;;
745
746 (defvar nnmail-cache-buffer nil)
747
748 (defun nnmail-cache-open ()
749   (if (or (not nnmail-delete-duplicates)
750           (and nnmail-cache-buffer
751                (buffer-name nnmail-cache-buffer)))
752       ()                                ; The buffer is open.
753     (save-excursion
754       (set-buffer 
755        (setq nnmail-cache-buffer 
756              (get-buffer-create " *nnmail message-id cache*")))
757       (buffer-disable-undo (current-buffer))
758       (and (file-exists-p nnmail-message-id-cache-file)
759            (insert-file-contents nnmail-message-id-cache-file))
760       (current-buffer))))
761
762 (defun nnmail-cache-close ()
763   (if (or (not nnmail-cache-buffer)
764           (not nnmail-delete-duplicates)
765           (not (buffer-name nnmail-cache-buffer))
766           (not (buffer-modified-p nnmail-cache-buffer)))
767       ()                                ; The buffer is closed.
768     (save-excursion
769       (set-buffer nnmail-cache-buffer)
770       ;; Weed out the excess number of Message-IDs.
771       (goto-char (point-max))
772       (and (search-backward "\n" nil t nnmail-message-id-cache-length)
773            (progn
774              (beginning-of-line)
775              (delete-region (point-min) (point))))
776       ;; Save the buffer.
777       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
778           (make-directory (file-name-directory nnmail-message-id-cache-file)
779                           t))
780       (write-region (point-min) (point-max)
781                     nnmail-message-id-cache-file nil 'silent)
782       (set-buffer-modified-p nil))))
783
784 (defun nnmail-cache-insert (id)
785   (and nnmail-delete-duplicates
786        (save-excursion
787          (set-buffer nnmail-cache-buffer)
788          (goto-char (point-max))
789          (insert id "\n"))))
790
791 (defun nnmail-cache-id-exists-p (id)
792   (and nnmail-delete-duplicates
793        (save-excursion
794          (set-buffer nnmail-cache-buffer)
795          (goto-char (point-max))
796          (search-backward id nil t))))
797
798 (defun nnmail-get-value (&rest args)
799   (let ((sym (intern (apply 'format args))))
800     (and (boundp sym)
801          (symbol-value sym))))
802
803 (defun nnmail-get-new-mail (method exit-func temp
804                                    &optional group spool-func)
805   "Read new incoming mail."
806   (let* ((spools (nnmail-get-spool-files group))
807          (group-in group)
808          incoming incomings)
809     (if (or (not (nnmail-get-value "%s-get-new-mail" method))
810             (not nnmail-spool-file))
811         () ; We don't want to look for new mail.
812       ;; We first activate all the groups.
813       (nnmail-activate method)
814       ;; The we go through all the existing spool files and split the
815       ;; mail from each.
816       (while spools
817         (and
818          (file-exists-p (car spools))
819          (> (nth 7 (file-attributes (car spools))) 0)
820          (progn
821            (and gnus-verbose-backends 
822                 (message "%s: Reading incoming mail..." method))
823            (if (not (setq incoming 
824                           (nnmail-move-inbox 
825                            (car spools) 
826                            (concat temp "Incoming"))))
827                () ; There is no new mail.
828              (setq group (nnmail-get-split-group (car spools) group-in))
829              (nnmail-split-incoming 
830               incoming (intern (format "%s-save-mail" method)) 
831               spool-func group)
832              (setq incomings (cons incoming incomings)))))
833         (setq spools (cdr spools)))
834       ;; If we did indeed read any incoming spools, we save all info. 
835       (when incomings
836         (nnmail-save-active 
837          (nnmail-get-value "%s-group-alist" method)
838          (nnmail-get-value "%s-active-file" method))
839         (and exit-func (funcall exit-func))
840         (run-hooks 'nnmail-read-incoming-hook)
841         (and gnus-verbose-backends
842              (message "%s: Reading incoming mail...done" method)))
843       (while incomings
844         (setq incoming (car incomings))
845         (and nnmail-delete-incoming
846              (file-exists-p incoming)
847              (file-writable-p incoming)
848              (delete-file incoming))
849         (setq incomings (cdr incomings))))))
850
851 (provide 'nnmail)
852
853 ;;; nnmail.el ends here