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