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