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