*** 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
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 4 info))))
132         from subject date to reply-to message-of
133         references message-id sender cc)
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           (mail-setup (if (and follow-to (listp follow-to)) ""
177                         (or method-address 
178                             (concat (or sender reply-to from "")
179                                     (if to (concat ", " to) "")
180                                     (if cc (concat ", " cc) ""))))
181                       subject message-of nil article-buffer nil)
182           (if (and follow-to (listp follow-to))
183               (progn
184                 (goto-char (point-min))
185                 (while follow-to
186                   (insert 
187                    (car (car follow-to)) ": " (cdr (car follow-to)) "\n")
188                   (setq follow-to (cdr follow-to)))))
189           ;; Fold long references line to follow RFC1036.
190           (mail-position-on-field "References")
191           (let ((begin (- (point) (length "References: ")))
192                 (fill-column 78)
193                 (fill-prefix "\t"))
194             (if references (insert references))
195             (if (and references message-id) (insert " "))
196             (if message-id (insert message-id))
197             ;; The region must end with a newline to fill the region
198             ;; without inserting extra newline.
199             (fill-region-as-paragraph begin (1+ (point))))))
200       (current-buffer))))
201
202 (defun nnmail-find-file (file)
203   "Insert FILE in server buffer safely."
204   (set-buffer nntp-server-buffer)
205   (erase-buffer)
206   (condition-case ()
207       (progn (insert-file-contents file) t)
208     (file-error nil)))
209
210 (defun nnmail-article-pathname (group mail-dir)
211   "Make pathname for GROUP."
212   (concat (file-name-as-directory (expand-file-name mail-dir))
213           (nnmail-replace-chars-in-string group ?. ?/) "/"))
214
215 (defun nnmail-replace-chars-in-string (string from to)
216   "Replace characters in STRING from FROM to TO."
217   (let ((string (substring string 0))   ;Copy string.
218         (len (length string))
219         (idx 0))
220     ;; Replace all occurrences of FROM with TO.
221     (while (< idx len)
222       (if (= (aref string idx) from)
223           (aset string idx to))
224       (setq idx (1+ idx)))
225     string))
226
227 (defun nnmail-days-between (date1 date2)
228   ;; Return the number of days between date1 and date2.
229   (let ((d1 (mapcar (lambda (s) (and s (string-to-int s)) )
230                     (timezone-parse-date date1)))
231         (d2 (mapcar (lambda (s) (and s (string-to-int s)) )
232                     (timezone-parse-date date2))))
233     (- (timezone-absolute-from-gregorian 
234         (nth 1 d1) (nth 2 d1) (car d1))
235        (timezone-absolute-from-gregorian 
236         (nth 1 d2) (nth 2 d2) (car d2)))))
237
238 ;; Function taken from rmail.el.
239 (defun nnmail-move-inbox (inbox tofile)
240   (let ((inbox (file-truename
241                 (expand-file-name (substitute-in-file-name inbox))))
242         (tofile (make-temp-name (expand-file-name tofile)))
243         movemail popmail errors)
244     ;; Check whether the inbox is to be moved to the special tmp dir. 
245     (if nnmail-tmp-directory
246         (setq tofile (concat (file-name-as-directory nnmail-tmp-directory)
247                              (file-name-nondirectory tofile))))
248     ;; If getting from mail spool directory,
249     ;; use movemail to move rather than just renaming,
250     ;; so as to interlock with the mailer.
251     (setq movemail (string= (file-name-directory inbox)
252                             (file-truename rmail-spool-directory))
253           popmail (string-match "^po:" (file-name-nondirectory inbox)))
254     (if popmail (setq inbox (file-name-nondirectory inbox)))
255     (if movemail
256         ;; On some systems, /usr/spool/mail/foo is a directory
257         ;; and the actual inbox is /usr/spool/mail/foo/foo.
258         (if (file-directory-p inbox)
259             (setq inbox (expand-file-name (user-login-name) inbox))))
260     (if popmail
261         (message "Getting mail from post office ...")
262       (if (or (and (file-exists-p tofile)
263                    (/= 0 (nth 7 (file-attributes tofile))))
264               (and (file-exists-p inbox)
265                    (/= 0 (nth 7 (file-attributes inbox)))))
266           (message "Getting mail from %s..." inbox)))
267     ;; Set TOFILE if have not already done so, and
268     ;; rename or copy the file INBOX to TOFILE if and as appropriate.
269     (cond ((or (file-exists-p tofile) (and (not popmail)
270                                            (not (file-exists-p inbox))))
271            nil)
272           ((and (not movemail) (not popmail))
273            ;; Try copying.  If that fails (perhaps no space),
274            ;; rename instead.
275            (condition-case nil
276                (copy-file inbox tofile nil)
277              (error
278               ;; Third arg is t so we can replace existing file TOFILE.
279               (rename-file inbox tofile t)))
280            ;; Make the real inbox file empty.
281            ;; Leaving it deleted could cause lossage
282            ;; because mailers often won't create the file.
283            (condition-case ()
284                (write-region (point) (point) inbox)
285              (file-error nil)))
286           (t
287            (unwind-protect
288                (save-excursion
289                  (setq errors (generate-new-buffer " *nnmail loss*"))
290                  (buffer-disable-undo errors)
291                  (call-process
292                   (expand-file-name "movemail" exec-directory)
293                   nil errors nil inbox tofile)
294                  (if (not (buffer-modified-p errors))
295                      ;; No output => movemail won
296                      nil
297                    (set-buffer errors)
298                    (subst-char-in-region (point-min) (point-max)
299                                          ?\n ?\  )
300                    (goto-char (point-max))
301                    (skip-chars-backward " \t")
302                    (delete-region (point) (point-max))
303                    (goto-char (point-min))
304                    (if (looking-at "movemail: ")
305                        (delete-region (point-min) (match-end 0)))
306                    (beep t)
307                    (message (concat "movemail: "
308                                     (buffer-substring (point-min)
309                                                       (point-max))))
310                    (sit-for 3)
311                    nil)))))
312     (and errors
313          (buffer-name errors)
314          (kill-buffer errors))
315     tofile))
316
317
318 (defun nnmail-get-active ()
319   "Returns an assoc of group names and active ranges.
320 nn*-request-list should have been called before calling this function."
321   (let (group-assoc)
322     ;; Go through all groups from the active list.
323     (save-excursion
324       (set-buffer nntp-server-buffer)
325       (goto-char 1)
326       (while (re-search-forward 
327               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
328         (setq group-assoc
329               (cons (list (buffer-substring (match-beginning 1) 
330                                             (match-end 1))
331                           (cons (string-to-int 
332                                  (buffer-substring (match-beginning 3)
333                                                    (match-end 3)))
334                                 (string-to-int 
335                                  (buffer-substring (match-beginning 2)
336                                                    (match-end 2)))))
337                     group-assoc))))
338     ;; In addition, add all groups mentioned in `nnmail-split-methods'.
339     (let ((methods (and (not (symbolp nnmail-split-methods))
340                         nnmail-split-methods)))
341       (while methods
342         (if (not (assoc (car (car methods)) group-assoc))
343             (setq group-assoc
344                   (cons (list (car (car methods)) (cons 1 0)) 
345                         group-assoc)))
346         (setq methods (cdr methods))))
347     group-assoc))
348
349 (defun nnmail-save-active (group-assoc file-name)
350   (let (group)
351     (save-excursion
352       (set-buffer (get-buffer-create " *nnmail active*"))
353       (buffer-disable-undo (current-buffer))
354       (erase-buffer)
355       (while group-assoc
356         (setq group (car group-assoc))
357         (insert (format "%s %d %d y\n" (car group) (cdr (car (cdr group)) )
358                         (car (car (cdr group)))))
359         (setq group-assoc (cdr group-assoc)))
360       (write-region 1 (point-max) (expand-file-name file-name) nil 'nomesg)
361       (kill-buffer (current-buffer)))))
362
363 (defun nnmail-split-incoming (incoming func &optional dont-kill)
364   "Go through the entire INCOMING file and pick out each individual mail.
365 FUNC will be called with the buffer narrowed to each mail."
366   (let ((delim (concat "^" rmail-unix-mail-delimiter))
367         start)
368     (save-excursion
369       (set-buffer (get-buffer-create " *nnmail incoming*"))
370       (buffer-disable-undo (current-buffer))
371       (erase-buffer)
372       (insert-file-contents incoming)
373       (goto-char 1)
374       (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
375       ;; Go to the beginning of the first mail...
376       (if (and (re-search-forward delim nil t)
377                (goto-char (match-beginning 0)))
378           ;; and then carry on until the bitter end.
379           (while (not (eobp))
380             (setq start (point))
381             ;; Skip all the headers in case there are more "From "s...
382             (if (not (search-forward "\n\n" nil t))
383                 (forward-line 1))
384             (if (re-search-forward delim nil t)
385                 (goto-char (match-beginning 0))
386               (goto-char (point-max)))
387             (save-excursion
388               (save-restriction
389                 (narrow-to-region start (point))
390                 (goto-char (point-min))
391                 (funcall func)))))
392       (if dont-kill
393           (current-buffer)
394         (kill-buffer (current-buffer))))))
395
396 ;; Mail crossposts syggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
397 (defun nnmail-article-group (func)
398   "Look at the headers and return an alist of groups that match.
399 FUNC will be called with the group name to determine the article number."
400   (let ((methods nnmail-split-methods)
401         (obuf (current-buffer))
402         (beg (point-min))
403         end found group-art)
404     (save-excursion
405       ;; Find headers.
406       (goto-char beg)
407       (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
408       (set-buffer (get-buffer-create " *nnmail work*"))
409       (buffer-disable-undo (current-buffer))
410       (erase-buffer)
411       ;; Copy the headers into the work buffer.
412       (insert-buffer-substring obuf beg end)
413       ;; Fold continuation lines.
414       (goto-char (point-min))
415       (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
416         (replace-match " " t t))
417       (if (and (symbolp nnmail-split-methods)
418                (fboundp nnmail-split-methods))
419           (setq group-art
420                 (mapcar
421                  (lambda (group) (cons group (funcall func group)))
422                  (funcall nnmail-split-methods)))
423         ;; Go throught the split methods to find a match.
424         (while (and methods (or nnmail-crosspost (not group-art)))
425           (goto-char (point-max))
426           (if (or (cdr methods)
427                   (not (equal "" (nth 1 (car methods)))))
428               (if (and (condition-case () 
429                            (if (stringp (nth 1 (car methods)))
430                                (re-search-backward
431                                 (car (cdr (car methods))) nil t)
432                              ;; Suggested by Brian Edmonds <edmonds@cs.ubc.ca>.
433                              (funcall (nth 1 (car methods)) 
434                                       (car (car methods))))
435                          (error nil))
436                        ;; Don't enter the article into the same group twice.
437                        (not (assoc (car (car methods)) group-art)))
438                   (setq group-art
439                         (cons (cons (car (car methods))
440                                     (funcall func (car (car methods)))) 
441                               group-art)))
442             (or group-art
443                 (setq group-art 
444                       (list (cons (car (car methods)) 
445                                   (funcall func (car (car methods))))))))
446           (setq methods (cdr methods))))
447       (kill-buffer (current-buffer))
448       group-art)))
449
450 (defun nnmail-insert-lines ()
451   "Insert how many lines and chars there are in the body of the mail."
452   (let (lines chars)
453     (save-excursion
454       (goto-char (point-min))
455       (if (search-forward "\n\n" nil t) 
456           (progn
457             (setq chars (- (point-max) (point)))
458             (setq lines (- (count-lines (point) (point-max)) 1))
459             (forward-char -1)
460             (save-excursion
461               (if (re-search-backward "^Lines: " nil t)
462                   (delete-region (point) (progn (forward-line 1) (point)))))
463             (insert (format "Lines: %d\n" lines))
464             chars)))))
465
466 (defun nnmail-insert-xref (group-alist)
467   "Insert an Xref line based on the (group . article) alist."
468   (save-excursion
469     (goto-char (point-min))
470     (if (search-forward "\n\n" nil t) 
471         (progn
472           (forward-char -1)
473           (if (re-search-backward "^Xref: " nil t)
474               (delete-region (match-beginning 0) 
475                              (progn (forward-line 1) (point))))
476           (insert (format "Xref: %s" (system-name)))
477           (while group-alist
478             (insert (format " %s:%d" (car (car group-alist)) 
479                             (cdr (car group-alist))))
480             (setq group-alist (cdr group-alist)))
481           (insert "\n")))))
482
483 (provide 'nnmail)
484
485 ;;; nnml.el ends here