7b766af842a424764601485d2cc991efda311b51
[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
31 (defvar nnmail-split-methods
32   '(("mail.misc" ""))
33   "Incoming mail will be split according to this variable.
34
35 If you'd like, for instance, one mail group for mail from the
36 \"4ad-l\" mailing list, one group for junk mail and one for everything
37 else, you could do something like this:
38
39  (setq nnmail-split-methods
40        '((\"mail.4ad\" \"From:.*4ad\")
41          (\"mail.junk\" \"From:.*Lars\\\\|Subject:.*buy\")
42          (\"mail.misc\" \"\")))
43
44 As you can see, this variable is a list of lists, where the first
45 element in each \"rule\" is the name of the group (which, by the way,
46 does not have to be called anything beginning with \"mail\",
47 \"yonka.zow\" is a fine, fine name), and the second is a regexp that
48 nnmail will try to match on the header to find a fit.
49
50 The second element can also be a function.  In that case, it will be
51 called narrowed to the headers with the first element of the rule as
52 the argument.  It should return a non-nil value if it thinks that the
53 mail belongs in that group.
54
55 The last element should always have \"\" as the regexp.")
56
57 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
58 (defvar nnmail-crosspost t
59   "If non-nil, do crossposting if several split methods match the mail.
60 If nil, the first match found will be used.")
61
62 ;; Added by gord@enci.ucalgary.ca (Gordon Matzigkeit).
63 (defvar nnmail-keep-last-article nil
64   "If non-nil, nnmail will never delete the last expired article in a
65 directory.  You may need to set this variable if other programs are putting
66 new mail into folder numbers that Gnus has marked as expired.")
67
68 (defvar nnmail-expiry-wait 7
69   "Articles that are older than `nnmail-expiry-wait' days will be expired.")
70
71 (defvar nnmail-expiry-wait-function nil
72   "Variable that holds funtion to specify how old articles should be before they are expired.
73   The function will be called with the name of the group that the
74 expiry is to be performed in, and it should return an integer that
75 says how many days an article can be stored before it is considered
76 'old'. 
77
78 Eg.:
79
80 (setq nnmail-expiry-wait-function
81       (lambda (newsgroup)
82         (cond ((string-match \"private\" newsgroup) 31)
83               ((string-match \"junk\" newsgroup) 1)
84               (t 7))))")
85
86 (defvar nnmail-spool-file 
87   (or (getenv "MAIL")
88       (concat "/usr/spool/mail/" (user-login-name)))
89   "Where the mail backends will look for incoming mail.
90 This variable is \"/usr/spool/mail/$user\" by default.
91 If this variable is nil, no mail backends will read incoming mail.")
92
93 (defvar nnmail-read-incoming-hook nil
94   "Hook that will be run after the incoming mail has been transferred.
95 The incoming mail is moved from `nnmail-spool-file' (which normally is
96 something like \"/usr/spool/mail/$user\") to the user's home
97 directory. This hook is called after the incoming mail box has been
98 emptied, and can be used to call any mail box programs you have
99 running (\"xwatch\", etc.)
100
101 Eg.
102
103 (add-hook 'nnmail-read-incoming-hook 
104            (lambda () 
105              (start-process \"mailsend\" nil 
106                             \"/local/bin/mailsend\" \"read\" \"mbox\")))")
107
108 ;; Suggested by Erik Selberg <speed@cs.washington.edu>.
109 (defvar nnmail-prepare-incoming-hook nil
110   "Hook called before treating incoming mail.
111 The hook is run in a buffer with all the new, incoming mail.")
112
113 ;; Suggested by Mejia Pablo J <pjm9806@usl.edu>.
114 (defvar nnmail-tmp-directory nil
115   "If non-nil, use this directory for temporary storage when reading incoming mail.")
116
117 (defvar nnmail-large-newsgroup 50
118   "The number of the articles which indicates a large newsgroup.
119 If the number of the articles is greater than the value, verbose
120 messages will be shown to indicate the current status.")
121
122 \f
123
124 (defconst nnmail-version "nnml 0.0"
125   "nnmail version.")
126
127 \f
128
129 (defun nnmail-request-post-buffer (post group subject header article-buffer
130                                         info follow-to respect-poster)
131   (let ((method-address (cdr (assq 'to-address (nth 5 info))))
132         from date to reply-to message-of
133         references message-id sender cc sendto elt)
134     (setq method-address
135           (if (and (stringp method-address) 
136                    (string= method-address ""))
137               nil method-address))
138     (save-excursion
139       (set-buffer (get-buffer-create "*mail*"))
140       (mail-mode)
141       (local-set-key "\C-c\C-c" 'gnus-mail-send-and-exit)
142       (if (and (buffer-modified-p)
143                (> (buffer-size) 0)
144                (not (y-or-n-p "Unsent mail being composed; erase it? ")))
145           ()
146         (erase-buffer)
147         (if post
148             (mail-setup method-address subject nil nil nil nil)
149           (save-excursion
150             (set-buffer article-buffer)
151             (goto-char (point-min))
152             (narrow-to-region (point-min)
153                               (progn (search-forward "\n\n") (point)))
154             (let ((buffer-read-only nil))
155               (set-text-properties (point-min) (point-max) nil))
156             (setq from (header-from header))
157             (setq date (header-date header))
158             (and from
159                  (let ((stop-pos 
160                         (string-match "  *at \\|  *@ \\| *(\\| *<" from)))
161                    (setq message-of
162                          (concat (if stop-pos (substring from 0 stop-pos) from)
163                                  "'s message of " date))))
164             (setq sender (mail-fetch-field "sender"))
165             (setq cc (mail-fetch-field "cc"))
166             (setq to (mail-fetch-field "to"))
167             (setq subject (header-subject header))
168             (or (string-match "^[Rr][Ee]:" subject)
169                 (setq subject (concat "Re: " subject)))
170             (setq reply-to (mail-fetch-field "reply-to"))
171             (setq references (header-references header))
172             (setq message-id (header-id header))
173             (widen))
174           (setq news-reply-yank-from from)
175           (setq news-reply-yank-message-id message-id)
176           
177           ;; Gather the "to" addresses out of the follow-to list and remove
178           ;; them as we go.
179           (if (and follow-to (listp follow-to))
180               (while (setq elt (assoc "To" follow-to))
181                 (setq sendto (concat sendto (and sendto ", ") (cdr elt)))
182                 (setq follow-to (delq elt follow-to))))
183           (mail-setup (if (and follow-to (listp follow-to)) sendto
184                         (or method-address 
185                             (concat (or sender reply-to from "")
186                                     (if to (concat ", " to) "")
187                                     (if cc (concat ", " cc) ""))))
188                       subject message-of nil article-buffer nil)
189           ;; Note that "To" elements should already be in the message.
190           (if (and follow-to (listp follow-to))
191               (progn
192                 (goto-char (point-min))
193                 (re-search-forward "^To:" nil t)
194                 (beginning-of-line)
195                 (forward-line 1)
196                 (while follow-to
197                   (insert 
198                    (car (car follow-to)) ": " (cdr (car follow-to)) "\n")
199                   (setq follow-to (cdr follow-to)))))
200           ;; Fold long references line to follow RFC1036.
201           (mail-position-on-field "References")
202           (let ((begin (- (point) (length "References: ")))
203                 (fill-column 78)
204                 (fill-prefix "\t"))
205             (if references (insert references))
206             (if (and references message-id) (insert " "))
207             (if message-id (insert message-id))
208             ;; The region must end with a newline to fill the region
209             ;; without inserting extra newline.
210             (fill-region-as-paragraph begin (1+ (point))))))
211       (current-buffer))))
212
213 (defun nnmail-find-file (file)
214   "Insert FILE in server buffer safely."
215   (set-buffer nntp-server-buffer)
216   (erase-buffer)
217   (condition-case ()
218       (progn (insert-file-contents file) t)
219     (file-error nil)))
220
221 (defun nnmail-article-pathname (group mail-dir)
222   "Make pathname for GROUP."
223   (concat (file-name-as-directory (expand-file-name mail-dir))
224           (nnmail-replace-chars-in-string group ?. ?/) "/"))
225
226 (defun nnmail-replace-chars-in-string (string from to)
227   "Replace characters in STRING from FROM to TO."
228   (let ((string (substring string 0))   ;Copy string.
229         (len (length string))
230         (idx 0))
231     ;; Replace all occurrences of FROM with TO.
232     (while (< idx len)
233       (if (= (aref string idx) from)
234           (aset string idx to))
235       (setq idx (1+ idx)))
236     string))
237
238 (defun nnmail-days-between (date1 date2)
239   ;; Return the number of days between date1 and date2.
240   (let ((d1 (mapcar (lambda (s) (and s (string-to-int s)) )
241                     (timezone-parse-date date1)))
242         (d2 (mapcar (lambda (s) (and s (string-to-int s)) )
243                     (timezone-parse-date date2))))
244     (- (timezone-absolute-from-gregorian 
245         (nth 1 d1) (nth 2 d1) (car d1))
246        (timezone-absolute-from-gregorian 
247         (nth 1 d2) (nth 2 d2) (car d2)))))
248
249 ;; Function taken from rmail.el.
250 (defun nnmail-move-inbox (inbox tofile)
251   (let ((inbox (file-truename
252                 (expand-file-name (substitute-in-file-name inbox))))
253         (tofile (nnmail-make-complex-temp-name (expand-file-name tofile)))
254         movemail popmail errors)
255     ;; Check whether the inbox is to be moved to the special tmp dir. 
256     (if nnmail-tmp-directory
257         (setq tofile (concat (file-name-as-directory nnmail-tmp-directory)
258                              (file-name-nondirectory tofile))))
259     ;; If getting from mail spool directory,
260     ;; use movemail to move rather than just renaming,
261     ;; so as to interlock with the mailer.
262     (setq movemail (string= (file-name-directory inbox)
263                             (file-truename rmail-spool-directory))
264           popmail (string-match "^po:" (file-name-nondirectory inbox)))
265     (if popmail (setq inbox (file-name-nondirectory inbox)))
266     (if movemail
267         ;; On some systems, /usr/spool/mail/foo is a directory
268         ;; and the actual inbox is /usr/spool/mail/foo/foo.
269         (if (file-directory-p inbox)
270             (setq inbox (expand-file-name (user-login-name) inbox))))
271     (if popmail
272         (message "Getting mail from post office ...")
273       (if (or (and (file-exists-p tofile)
274                    (/= 0 (nth 7 (file-attributes tofile))))
275               (and (file-exists-p inbox)
276                    (/= 0 (nth 7 (file-attributes inbox)))))
277           (message "Getting mail from %s..." inbox)))
278     ;; Set TOFILE if have not already done so, and
279     ;; rename or copy the file INBOX to TOFILE if and as appropriate.
280     (cond ((or (file-exists-p tofile) (and (not popmail)
281                                            (not (file-exists-p inbox))))
282            nil)
283           ((and (not movemail) (not popmail))
284            ;; Try copying.  If that fails (perhaps no space),
285            ;; rename instead.
286            (condition-case nil
287                (copy-file inbox tofile nil)
288              (error
289               ;; Third arg is t so we can replace existing file TOFILE.
290               (rename-file inbox tofile t)))
291            ;; Make the real inbox file empty.
292            ;; Leaving it deleted could cause lossage
293            ;; because mailers often won't create the file.
294            (condition-case ()
295                (write-region (point) (point) inbox)
296              (file-error nil)))
297           (t
298            (unwind-protect
299                (save-excursion
300                  (setq errors (generate-new-buffer " *nnmail loss*"))
301                  (buffer-disable-undo errors)
302                  (call-process
303                   (expand-file-name "movemail" exec-directory)
304                   nil errors nil inbox tofile)
305                  (if (not (buffer-modified-p errors))
306                      ;; No output => movemail won
307                      nil
308                    (set-buffer errors)
309                    (subst-char-in-region (point-min) (point-max)
310                                          ?\n ?\  )
311                    (goto-char (point-max))
312                    (skip-chars-backward " \t")
313                    (delete-region (point) (point-max))
314                    (goto-char (point-min))
315                    (if (looking-at "movemail: ")
316                        (delete-region (point-min) (match-end 0)))
317                    (beep t)
318                    (message (concat "movemail: "
319                                     (buffer-substring (point-min)
320                                                       (point-max))))
321                    (sit-for 3)
322                    nil)))))
323     (and errors
324          (buffer-name errors)
325          (kill-buffer errors))
326     tofile))
327
328
329 (defun nnmail-get-active ()
330   "Returns an assoc of group names and active ranges.
331 nn*-request-list should have been called before calling this function."
332   (let (group-assoc)
333     ;; Go through all groups from the active list.
334     (save-excursion
335       (set-buffer nntp-server-buffer)
336       (goto-char (point-min))
337       (while (re-search-forward 
338               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
339         (setq group-assoc
340               (cons (list (buffer-substring (match-beginning 1) 
341                                             (match-end 1))
342                           (cons (string-to-int 
343                                  (buffer-substring (match-beginning 3)
344                                                    (match-end 3)))
345                                 (string-to-int 
346                                  (buffer-substring (match-beginning 2)
347                                                    (match-end 2)))))
348                     group-assoc))))
349     ;; In addition, add all groups mentioned in `nnmail-split-methods'.
350     (let ((methods (and (not (symbolp nnmail-split-methods))
351                         nnmail-split-methods)))
352       (while methods
353         (if (not (assoc (car (car methods)) group-assoc))
354             (setq group-assoc
355                   (cons (list (car (car methods)) (cons 1 0)) 
356                         group-assoc)))
357         (setq methods (cdr methods))))
358     group-assoc))
359
360 (defun nnmail-save-active (group-assoc file-name)
361   (let (group)
362     (save-excursion
363       (set-buffer (get-buffer-create " *nnmail active*"))
364       (buffer-disable-undo (current-buffer))
365       (erase-buffer)
366       (while group-assoc
367         (setq group (car group-assoc))
368         (insert (format "%s %d %d y\n" (car group) (cdr (car (cdr group)) )
369                         (car (car (cdr group)))))
370         (setq group-assoc (cdr group-assoc)))
371       (write-region 1 (point-max) (expand-file-name file-name) nil 'nomesg)
372       (kill-buffer (current-buffer)))))
373
374 (defun nnmail-split-incoming (incoming func &optional dont-kill)
375   "Go through the entire INCOMING file and pick out each individual mail.
376 FUNC will be called with the buffer narrowed to each mail."
377   (let ((delim (concat "^" rmail-unix-mail-delimiter))
378         start end)
379     (save-excursion
380       (set-buffer (get-buffer-create " *nnmail incoming*"))
381       (buffer-disable-undo (current-buffer))
382       (erase-buffer)
383       (insert-file-contents incoming)
384       (goto-char (point-min))
385       (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
386       ;; Go to the beginning of the first mail...
387       (if (and (re-search-forward delim nil t)
388                (goto-char (match-beginning 0)))
389           ;; and then carry on until the bitter end.
390           (while (not (eobp))
391             (setq start (point))
392             ;; Skip all the headers in case there are more "From "s...
393             (if (not (search-forward "\n\n" nil t))
394                 (forward-line 1))
395             ;; Go to the beginning of the next article - or to the end
396             ;; of the buffer.  
397             (if (re-search-forward delim nil t)
398                 (goto-char (match-beginning 0))
399               (goto-char (point-max)))
400             (save-excursion
401               (save-restriction
402                 (narrow-to-region start (point))
403                 (goto-char (point-min))
404                 (funcall func)
405                 (setq end (point-max))))
406             (goto-char end)))
407       (if dont-kill
408           (current-buffer)
409         (kill-buffer (current-buffer))))))
410
411 ;; Mail crossposts syggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
412 (defun nnmail-article-group (func)
413   "Look at the headers and return an alist of groups that match.
414 FUNC will be called with the group name to determine the article number."
415   (let ((methods nnmail-split-methods)
416         (obuf (current-buffer))
417         (beg (point-min))
418         end found group-art)
419     (save-excursion
420       ;; Find headers.
421       (goto-char beg)
422       (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
423       (set-buffer (get-buffer-create " *nnmail work*"))
424       (buffer-disable-undo (current-buffer))
425       (erase-buffer)
426       ;; Copy the headers into the work buffer.
427       (insert-buffer-substring obuf beg end)
428       ;; Fold continuation lines.
429       (goto-char (point-min))
430       (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
431         (replace-match " " t t))
432       (if (and (symbolp nnmail-split-methods)
433                (fboundp nnmail-split-methods))
434           (setq group-art
435                 (mapcar
436                  (lambda (group) (cons group (funcall func group)))
437                  (funcall nnmail-split-methods)))
438         ;; Go throught the split methods to find a match.
439         (while (and methods (or nnmail-crosspost (not group-art)))
440           (goto-char (point-max))
441           (if (or (cdr methods)
442                   (not (equal "" (nth 1 (car methods)))))
443               (if (and (condition-case () 
444                            (if (stringp (nth 1 (car methods)))
445                                (re-search-backward
446                                 (car (cdr (car methods))) nil t)
447                              ;; Suggested by Brian Edmonds <edmonds@cs.ubc.ca>.
448                              (funcall (nth 1 (car methods)) 
449                                       (car (car methods))))
450                          (error nil))
451                        ;; Don't enter the article into the same group twice.
452                        (not (assoc (car (car methods)) group-art)))
453                   (setq group-art
454                         (cons (cons (car (car methods))
455                                     (funcall func (car (car methods)))) 
456                               group-art)))
457             (or group-art
458                 (setq group-art 
459                       (list (cons (car (car methods)) 
460                                   (funcall func (car (car methods))))))))
461           (setq methods (cdr methods))))
462       (kill-buffer (current-buffer))
463       group-art)))
464
465 (defun nnmail-insert-lines ()
466   "Insert how many lines and chars there are in the body of the mail."
467   (let (lines chars)
468     (save-excursion
469       (goto-char (point-min))
470       (if (search-forward "\n\n" nil t) 
471           (progn
472             (setq chars (- (point-max) (point)))
473             (setq lines (- (count-lines (point) (point-max)) 1))
474             (forward-char -1)
475             (save-excursion
476               (if (re-search-backward "^Lines: " nil t)
477                   (delete-region (point) (progn (forward-line 1) (point)))))
478             (insert (format "Lines: %d\n" lines))
479             chars)))))
480
481 (defun nnmail-insert-xref (group-alist)
482   "Insert an Xref line based on the (group . article) alist."
483   (save-excursion
484     (goto-char (point-min))
485     (if (search-forward "\n\n" nil t) 
486         (progn
487           (forward-char -1)
488           (if (re-search-backward "^Xref: " nil t)
489               (delete-region (match-beginning 0) 
490                              (progn (forward-line 1) (point))))
491           (insert (format "Xref: %s" (system-name)))
492           (while group-alist
493             (insert (format " %s:%d" (car (car group-alist)) 
494                             (cdr (car group-alist))))
495             (setq group-alist (cdr group-alist)))
496           (insert "\n")))))
497
498 ;; Written by byer@mv.us.adobe.com (Scott Byer).
499 (defun nnmail-make-complex-temp-name (prefix)
500   (let ((newname (make-temp-name prefix))
501         (newprefix prefix))
502     (while (file-exists-p newname)
503       (setq newprefix (concat newprefix "x"))
504       (setq newname (make-temp-name newprefix)))
505     newname))
506
507 (provide 'nnmail)
508
509 ;;; nnml.el ends here