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