*** 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 'timezone)
30 (require 'sendmail)
31 (require 'message)
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 `nnmail-split-fancy-syntax-table' syntax table.
208 You can use .* 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 (defvar nnmail-split-fancy-syntax-table
265   (copy-syntax-table (standard-syntax-table))
266   "Syntax table used by `nnmail-split-fancy'.")
267
268 (defvar nnmail-prepare-save-mail-hook nil
269   "Hook called before saving mail.")
270
271 \f
272
273 (defconst nnmail-version "nnmail 1.0"
274   "nnmail version.")
275
276 \f
277
278 (defun nnmail-request-post (&optional server)
279   (mail-send-and-exit nil))
280
281 (defun nnmail-find-file (file)
282   "Insert FILE in server buffer safely."
283   (set-buffer nntp-server-buffer)
284   (erase-buffer)
285   (condition-case ()
286       (progn (nnheader-insert-raw-file-contents file) t)
287     (file-error nil)))
288
289 (defun nnmail-group-pathname (group dir &optional file)
290   "Make pathname for GROUP."
291   (concat
292    (let ((dir (file-name-as-directory (expand-file-name dir))))
293      ;; If this directory exists, we use it directly.
294      (if (or nnmail-use-long-file-names 
295              (file-directory-p (concat dir group)))
296          (concat dir group "/")
297        ;; If not, we translate dots into slashes.
298        (concat dir (nnheader-replace-chars-in-string group ?. ?/) "/")))
299    (or file "")))
300   
301 (defun nnmail-date-to-time (date)
302   "Convert DATE into time."
303   (let* ((d1 (timezone-parse-date date))
304          (t1 (timezone-parse-time (aref d1 3))))
305     (apply 'encode-time
306            (mapcar (lambda (el)
307                      (and el (string-to-number el)))
308                    (list
309                     (aref t1 2) (aref t1 1) (aref t1 0)
310                     (aref d1 2) (aref d1 1) (aref d1 0)
311                     (aref d1 4))))))
312
313 (defun nnmail-time-less (t1 t2)
314   "Say whether time T1 is less than time T2."
315   (or (< (car t1) (car t2))
316       (and (= (car t1) (car t2))
317            (< (nth 1 t1) (nth 1 t2)))))
318
319 (defun nnmail-days-to-time (days)
320   "Convert DAYS into time."
321   (let* ((seconds (* 1.0 days 60 60 24))
322          (rest (expt 2 16))
323          (ms (condition-case nil (round (/ seconds rest)) 
324                (range-error (expt 2 16)))))
325     (list ms (condition-case nil (round (- seconds (* ms rest)))
326                (range-error (expt 2 16))))))
327
328 (defun nnmail-time-since (time)
329   "Return the time since TIME, which is either an internal time or a date."
330   (when (stringp time)
331     ;; Convert date strings to internal time.
332     (setq time (nnmail-date-to-time time)))
333   (let* ((current (current-time))
334          (rest (if (< (nth 1 current) (nth 1 time)) (expt 2 16))))
335     (list (- (+ (car current) (if rest -1 0)) (car time))
336           (- (+ (or rest 0) (nth 1 current)) (nth 1 time)))))
337
338 ;; Function taken from rmail.el.
339 (defun nnmail-move-inbox (inbox)
340   "Move INBOX to `nnmail-crash-box'."
341   (let ((inbox (file-truename
342                 (expand-file-name (substitute-in-file-name inbox))))
343         (tofile (file-truename (expand-file-name 
344                                 (substitute-in-file-name nnmail-crash-box))))
345         movemail popmail errors)
346     ;; If getting from mail spool directory,
347     ;; use movemail to move rather than just renaming,
348     ;; so as to interlock with the mailer.
349     (unless (setq popmail (string-match "^po:" (file-name-nondirectory inbox)))
350       (setq movemail t))
351     (when popmail 
352       (setq inbox (file-name-nondirectory inbox)))
353     (when (and movemail
354                ;; On some systems, /usr/spool/mail/foo is a directory
355                ;; and the actual inbox is /usr/spool/mail/foo/foo.
356                (file-directory-p inbox))
357       (setq inbox (expand-file-name (user-login-name) inbox)))
358     (if popmail
359         (message "Getting mail from post office ...")
360       (when (or (and (file-exists-p tofile)
361                      (/= 0 (nth 7 (file-attributes tofile))))
362                 (and (file-exists-p inbox)
363                      (/= 0 (nth 7 (file-attributes inbox)))))
364         (message "Getting mail from %s..." inbox)))
365     ;; Set TOFILE if have not already done so, and
366     ;; rename or copy the file INBOX to TOFILE if and as appropriate.
367     (cond ((file-exists-p tofile)
368            ;; The crash box exists already.
369            t)
370           ((and (not popmail)
371                 (not (file-exists-p inbox)))
372            ;; There is no inbox.
373            (setq tofile nil))
374           ((and (not movemail) (not popmail))
375            ;; Try copying.  If that fails (perhaps no space),
376            ;; rename instead.
377            (condition-case nil
378                (copy-file inbox tofile nil)
379              (error
380               ;; Third arg is t so we can replace existing file TOFILE.
381               (rename-file inbox tofile t)))
382            ;; Make the real inbox file empty.
383            ;; Leaving it deleted could cause lossage
384            ;; because mailers often won't create the file.
385            (condition-case ()
386                (write-region (point) (point) inbox)
387              (file-error nil)))
388           (t
389            (unwind-protect
390                (save-excursion
391                  (setq errors (generate-new-buffer " *nnmail loss*"))
392                  (buffer-disable-undo errors)
393                  (let ((default-directory "/"))
394                    (call-process
395                     (expand-file-name nnmail-movemail-program exec-directory)
396                     nil errors nil inbox tofile))
397                  (if (not (buffer-modified-p errors))
398                      ;; No output => movemail won
399                      nil
400                    (set-buffer errors)
401                    (subst-char-in-region (point-min) (point-max) ?\n ?\  )
402                    (goto-char (point-max))
403                    (skip-chars-backward " \t")
404                    (delete-region (point) (point-max))
405                    (goto-char (point-min))
406                    (if (looking-at "movemail: ")
407                        (delete-region (point-min) (match-end 0)))
408                    (beep t)
409                    (message (concat "movemail: "
410                                     (buffer-substring (point-min)
411                                                       (point-max))))
412                    (sit-for 3)
413                    (setq tofile nil))))))
414     (and errors
415          (buffer-name errors)
416          (kill-buffer errors))
417     tofile))
418
419 (defun nnmail-get-active ()
420   "Returns an assoc of group names and active ranges.
421 nn*-request-list should have been called before calling this function."
422   (let (group-assoc)
423     ;; Go through all groups from the active list.
424     (save-excursion
425       (set-buffer nntp-server-buffer)
426       (goto-char (point-min))
427       (while (re-search-forward 
428               "^\\([^ \t]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)" nil t)
429         ;; We create an alist with `(GROUP (LOW . HIGH))' elements.
430         (push (list (match-string 1)
431                     (cons (string-to-int (match-string 3))
432                           (string-to-int (match-string 2))))
433               group-assoc)))
434     group-assoc))
435
436 (defun nnmail-save-active (group-assoc file-name)
437   "Save GROUP-ASSOC in ACTIVE-FILE."
438   (when file-name
439     (let (group)
440       (save-excursion
441         (set-buffer (get-buffer-create " *nnmail active*"))
442         (buffer-disable-undo (current-buffer))
443         (erase-buffer)
444         (while group-assoc
445           (setq group (pop group-assoc))
446           (insert (format "%s %d %d y\n" (car group) (cdadr group) 
447                           (caadr group))))
448         (unless (file-exists-p (file-name-directory file-name))
449           (make-directory (file-name-directory file-name) t))
450         (write-region 1 (point-max) (expand-file-name file-name) nil 'nomesg)
451         (kill-buffer (current-buffer))))))
452
453 (defun nnmail-get-split-group (file group)
454   (if (or (eq nnmail-spool-file 'procmail)
455           nnmail-use-procmail)
456       (cond (group group)
457             ((string-match (concat "^" (expand-file-name
458                                         (file-name-as-directory
459                                          nnmail-procmail-directory))
460                                    "\\([^/]*\\)" nnmail-procmail-suffix "$")
461                            (expand-file-name file))
462              (substring (expand-file-name file)
463                         (match-beginning 1) (match-end 1)))
464             (t
465              group))
466     group))
467
468 (defun nnmail-process-babyl-mail-format (func)
469   (let ((case-fold-search t)
470         start message-id content-length do-search end)
471     (while (not (eobp))
472       (goto-char (point-min))
473       (re-search-forward
474        "\f\n0, *unseen,+\n\\(\\*\\*\\* EOOH \\*\\*\\*\n\\)?" nil t)
475       (goto-char (match-end 0))
476       (delete-region (match-beginning 0) (match-end 0))
477       (setq start (point))
478       ;; Skip all the headers in case there are more "From "s...
479       (or (search-forward "\n\n" nil t)
480           (search-forward-regexp "^[^:]*\\( .*\\|\\)$" nil t)
481           (search-forward "\1f\f"))
482       ;; Find the Message-ID header.
483       (save-excursion
484         (if (re-search-backward "^Message-ID:[ \t]*\\(<[^>]*>\\)" nil t)
485             (setq message-id (buffer-substring (match-beginning 1)
486                                                (match-end 1)))
487           ;; There is no Message-ID here, so we create one.
488           (save-excursion
489             (when (re-search-backward "^Message-ID:" nil t)
490               (beginning-of-line)
491               (insert "Original-")))
492           (forward-line -1)
493           (insert "Message-ID: " (setq message-id (nnmail-message-id))
494                   "\n")))
495       ;; Look for a Content-Length header.
496       (if (not (save-excursion
497                  (and (re-search-backward 
498                        "^Content-Length:[ \t]*\\([0-9]+\\)" start t)
499                       (setq content-length (string-to-int
500                                             (buffer-substring 
501                                              (match-beginning 1)
502                                              (match-end 1))))
503                       ;; We destroy the header, since none of
504                       ;; the backends ever use it, and we do not
505                       ;; want to confuse other mailers by having
506                       ;; a (possibly) faulty header.
507                       (progn (insert "X-") t))))
508           (setq do-search t)
509         (if (or (= (+ (point) content-length) (point-max))
510                 (save-excursion
511                   (goto-char (+ (point) content-length))
512                   (looking-at "\1f")))
513             (progn
514               (goto-char (+ (point) content-length))
515               (setq do-search nil))
516           (setq do-search t)))
517       ;; Go to the beginning of the next article - or to the end
518       ;; of the buffer.  
519       (if do-search
520           (if (re-search-forward "^\1f" nil t)
521               (goto-char (match-beginning 0))
522             (goto-char (1- (point-max)))))
523       (delete-char 1)                   ; delete ^_
524       (save-excursion
525         (save-restriction
526           (narrow-to-region start (point))
527           (goto-char (point-min))
528           (nnmail-check-duplication message-id func)
529           (setq end (point-max))))
530       (goto-char end))))
531
532 (defun nnmail-search-unix-mail-delim ()
533   "Put point at the beginning of the next message."
534   (let ((case-fold-search t)
535         (delim (concat "^" message-unix-mail-delimiter))
536         found)
537     (while (not found)
538       (if (re-search-forward delim nil t)
539           (when (or (looking-at "[^\n :]+ *:")
540                     (looking-at delim)
541                     (looking-at (concat ">" message-unix-mail-delimiter)))
542             (forward-line -1)
543             (setq found 'yes))
544         (setq found 'no)))
545     (eq found 'yes)))
546
547 (defun nnmail-process-unix-mail-format (func)
548   (let ((case-fold-search t)
549         (delim (concat "^" message-unix-mail-delimiter))
550         start message-id content-length end skip head-end)
551     (goto-char (point-min))
552     (if (not (and (re-search-forward delim nil t)
553                   (goto-char (match-beginning 0))))
554         ;; Possibly wrong format?
555         (error "Error, unknown mail format! (Possibly corrupted.)")
556       ;; Carry on until the bitter end.
557       (while (not (eobp))
558         (setq start (point)
559               end nil)
560         ;; Find the end of the head.
561         (narrow-to-region
562          start 
563          (if (search-forward "\n\n" nil t)
564              (1- (point))
565            ;; This will never happen, but just to be on the safe side --
566            ;; if there is no head-body delimiter, we search a bit manually.
567            (while (and (looking-at "From \\|[^ \t]+:")
568                        (not (eobp)))
569              (forward-line 1)
570              (point))))
571         ;; Find the Message-ID header.
572         (goto-char (point-min))
573         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
574             (setq message-id (match-string 1))
575           (save-excursion
576             (when (re-search-forward "^Message-ID:" nil t)
577               (beginning-of-line)
578               (insert "Original-")))
579           ;; There is no Message-ID here, so we create one.
580           (forward-line 1)
581           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
582         ;; Look for a Content-Length header.
583         (goto-char (point-min))
584         (if (not (re-search-forward
585                   "^Content-Length:[ \t]*\\([0-9]+\\)" nil t))
586             (setq content-length nil)
587           (setq content-length (string-to-int (match-string 1)))
588           ;; We destroy the header, since none of the backends ever 
589           ;; use it, and we do not want to confuse other mailers by
590           ;; having a (possibly) faulty header.
591           (beginning-of-line)
592           (insert "X-"))
593         ;; Find the end of this article.
594         (goto-char (point-max))
595         (widen)
596         (setq head-end (point))
597         ;; We try the Content-Length value.  The idea: skip over the header
598         ;; separator, then check what happens content-length bytes into the
599         ;; message body.  This should be either the end ot the buffer, the
600         ;; message separator or a blank line followed by the separator.
601         ;; The blank line should probably be deleted.  If neither of the
602         ;; three is met, the content-length header is probably invalid.
603         (when content-length
604           (forward-line 1)
605           (setq skip (+ (point) content-length))
606           (goto-char skip)
607           (cond ((or (= skip (point-max))
608                      (= (1+ skip) (point-max)))
609                  (setq end (point-max)))
610                 ((looking-at delim)
611                  (setq end skip))
612                 ((looking-at
613                   (concat "[ \t]*\n\\(" delim "\\)"))
614                  (setq end (match-beginning 1)))
615                 (t (setq end nil))))
616         (if end
617             (goto-char end)
618           ;; No Content-Length, so we find the beginning of the next 
619           ;; article or the end of the buffer.
620           (goto-char head-end)
621           (or (nnmail-search-unix-mail-delim)
622               (goto-char (point-max))))
623         ;; Allow the backend to save the article.
624         (save-excursion
625           (save-restriction
626             (narrow-to-region start (point))
627             (goto-char (point-min))
628             (nnmail-check-duplication message-id func)
629             (setq end (point-max))))
630         (goto-char end)))))
631
632 (defun nnmail-process-mmdf-mail-format (func)
633   (let ((delim "^\^A\^A\^A\^A$")
634         (case-fold-search t)
635         start message-id end)
636     (goto-char (point-min))
637     (if (not (and (re-search-forward delim nil t)
638                   (forward-line 1)))
639         ;; Possibly wrong format?
640         (error "Error, unknown mail format! (Possibly corrupted.)")
641       ;; Carry on until the bitter end.
642       (while (not (eobp))
643         (setq start (point))
644         ;; Find the end of the head.
645         (narrow-to-region
646          start 
647          (if (search-forward "\n\n" nil t)
648              (1- (point))
649            ;; This will never happen, but just to be on the safe side --
650            ;; if there is no head-body delimiter, we search a bit manually.
651            (while (and (looking-at "From \\|[^ \t]+:")
652                        (not (eobp)))
653              (forward-line 1)
654              (point))))
655         ;; Find the Message-ID header.
656         (goto-char (point-min))
657         (if (re-search-forward "^Message-ID:[ \t]*\\(<[^>]+>\\)" nil t)
658             (setq message-id (match-string 1))
659           ;; There is no Message-ID here, so we create one.
660           (save-excursion
661             (when (re-search-backward "^Message-ID:" nil t)
662               (beginning-of-line)
663               (insert "Original-")))
664           (forward-line 1)
665           (insert "Message-ID: " (setq message-id (nnmail-message-id)) "\n"))
666         ;; Find the end of this article.
667         (goto-char (point-max))
668         (widen)
669         (if (re-search-forward delim nil t)
670             (beginning-of-line)
671           (goto-char (point-max)))
672         ;; Allow the backend to save the article.
673         (save-excursion
674           (save-restriction
675             (narrow-to-region start (point))
676             (goto-char (point-min))
677             (nnmail-check-duplication message-id func)
678             (setq end (point-max))))
679         (goto-char end)
680         (forward-line 2)))))
681
682 (defun nnmail-split-incoming (incoming func &optional exit-func group)
683   "Go through the entire INCOMING file and pick out each individual mail.
684 FUNC will be called with the buffer narrowed to each mail."
685   (let (;; If this is a group-specific split, we bind the split
686         ;; methods to just this group.
687         (nnmail-split-methods (if (and group
688                                        (or (eq nnmail-spool-file 'procmail)
689                                            nnmail-use-procmail)
690                                        (not nnmail-resplit-incoming))
691                                   (list (list group ""))
692                                 nnmail-split-methods)))
693     (save-excursion
694       ;; Insert the incoming file.
695       (set-buffer (get-buffer-create " *nnmail incoming*"))
696       (buffer-disable-undo (current-buffer))
697       (erase-buffer)
698       (nnheader-insert-raw-file-contents incoming)
699       (unless (zerop (buffer-size))
700         (goto-char (point-min))
701         (save-excursion (run-hooks 'nnmail-prepare-incoming-hook))
702         ;; Handle both babyl, MMDF and unix mail formats, since movemail will
703         ;; use the former when fetching from a mailbox, the latter when
704         ;; fetches from a file.
705         (cond ((or (looking-at "\^L")
706                    (looking-at "BABYL OPTIONS:"))
707                (nnmail-process-babyl-mail-format func))
708               ((looking-at "\^A\^A\^A\^A")
709                (nnmail-process-mmdf-mail-format func))
710               (t
711                (nnmail-process-unix-mail-format func))))
712       (if exit-func (funcall exit-func))
713       (kill-buffer (current-buffer)))))
714
715 ;; Mail crossposts suggested by Brian Edmonds <edmonds@cs.ubc.ca>. 
716 (defun nnmail-article-group (func)
717   "Look at the headers and return an alist of groups that match.
718 FUNC will be called with the group name to determine the article number."
719   (let ((methods nnmail-split-methods)
720         (obuf (current-buffer))
721         (beg (point-min))
722         end group-art method)
723     (if (and (sequencep methods) (= (length methods) 1))
724         ;; If there is only just one group to put everything in, we
725         ;; just return a list with just this one method in.
726         (setq group-art
727               (list (cons (caar methods) (funcall func (caar methods)))))
728       ;; We do actual comparison.
729       (save-excursion
730         ;; Find headers.
731         (goto-char beg)
732         (setq end (if (search-forward "\n\n" nil t) (point) (point-max)))
733         (set-buffer nntp-server-buffer)
734         (erase-buffer)
735         ;; Copy the headers into the work buffer.
736         (insert-buffer-substring obuf beg end)
737         ;; Fold continuation lines.
738         (goto-char (point-min))
739         (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
740           (replace-match " " t t))
741         (if (and (symbolp nnmail-split-methods)
742                  (fboundp nnmail-split-methods))
743             ;; `nnmail-split-methods' is a function, so we just call 
744             ;; this function here and use the result.
745             (setq group-art
746                   (mapcar
747                    (lambda (group) (cons group (funcall func group)))
748                    (condition-case nil
749                        (funcall nnmail-split-methods)
750                      (error
751                       (message 
752                        "Error in `nnmail-split-methods'; using `bogus' mail group")
753                       (sit-for 1)
754                       '("bogus")))))
755           ;; Go through the split methods to find a match.
756           (while (and methods (or nnmail-crosspost (not group-art)))
757             (goto-char (point-max))
758             (setq method (pop methods))
759             (if (or methods
760                     (not (equal "" (nth 1 method))))
761                 (when (and
762                        (condition-case () 
763                            (if (stringp (nth 1 method))
764                                (re-search-backward (cadr method) nil t)
765                              ;; Function to say whether this is a match.
766                              (funcall (nth 1 method) (car method)))
767                          (error nil))
768                        ;; Don't enter the article into the same 
769                        ;; group twice.
770                        (not (assoc (car method) group-art)))
771                   (push (cons (car method) (funcall func (car method))) 
772                         group-art))
773               ;; This is the final group, which is used as a 
774               ;; catch-all.
775               (unless group-art
776                 (setq group-art 
777                       (list (cons (car method) 
778                                   (funcall func (car method)))))))))
779         group-art))))
780
781 (defun nnmail-insert-lines ()
782   "Insert how many lines there are in the body of the mail.
783 Return the number of characters in the body."
784   (let (lines chars)
785     (save-excursion
786       (goto-char (point-min))
787       (when (search-forward "\n\n" nil t) 
788         (setq chars (- (point-max) (point)))
789         (setq lines (count-lines (point) (point-max)))
790         (forward-char -1)
791         (save-excursion
792           (when (re-search-backward "^Lines: " nil t)
793             (delete-region (point) (progn (forward-line 1) (point)))))
794         (insert (format "Lines: %d\n" (max lines 0)))
795         chars))))
796
797 (defun nnmail-insert-xref (group-alist)
798   "Insert an Xref line based on the (group . article) alist."
799   (save-excursion
800     (goto-char (point-min))
801     (when (search-forward "\n\n" nil t) 
802       (forward-char -1)
803       (if (re-search-backward "^Xref: " nil t)
804           (delete-region (match-beginning 0) 
805                          (progn (forward-line 1) (point))))
806       (insert (format "Xref: %s" (system-name)))
807       (while group-alist
808         (insert (format " %s:%d" (caar group-alist) (cdar group-alist)))
809         (setq group-alist (cdr group-alist)))
810       (insert "\n"))))
811
812 ;; Written by byer@mv.us.adobe.com (Scott Byer).
813 (defun nnmail-make-complex-temp-name (prefix)
814   (let ((newname (make-temp-name prefix))
815         (newprefix prefix))
816     (while (file-exists-p newname)
817       (setq newprefix (concat newprefix "x"))
818       (setq newname (make-temp-name newprefix)))
819     newname))
820
821 ;; Written by Per Abrahamsen <amanda@iesd.auc.dk>.
822
823 (defun nnmail-split-fancy ()
824   "Fancy splitting method.
825 See the documentation for the variable `nnmail-split-fancy' for documentation."
826   (let ((syntab (syntax-table)))
827     (unwind-protect
828         (progn
829           (set-syntax-table nnmail-split-fancy-syntax-table)
830           (nnmail-split-it nnmail-split-fancy))
831       (set-syntax-table syntab))))
832
833 (defvar nnmail-split-cache nil)
834 ;; Alist of split expressions their equivalent regexps.
835
836 (defun nnmail-split-it (split)
837   ;; Return a list of groups matching SPLIT.
838   (cond ((stringp split)
839          ;; A group.
840          (list split))
841         ((eq (car split) '&)
842          (apply 'nconc (mapcar 'nnmail-split-it (cdr split))))
843         ((eq (car split) '|)
844          (let (done)
845            (while (and (not done) (cdr split))
846              (setq split (cdr split)
847                    done (nnmail-split-it (car split))))
848            done))
849         ((assq split nnmail-split-cache)
850          ;; A compiled match expression.
851          (goto-char (point-max))
852          (if (re-search-backward (cdr (assq split nnmail-split-cache)) nil t)
853              (nnmail-split-it (nth 2 split))))
854         (t
855          ;; An uncompiled match.
856          (let* ((field (nth 0 split))
857                 (value (nth 1 split))
858                 (regexp (concat "^\\(" 
859                                 (if (symbolp field)
860                                     (cdr (assq field 
861                                                nnmail-split-abbrev-alist))
862                                   field)
863                                 "\\):.*\\<\\("
864                                 (if (symbolp value)
865                                     (cdr (assq value
866                                                nnmail-split-abbrev-alist))
867                                   value)
868                                 "\\>\\)")))
869            (setq nnmail-split-cache 
870                  (cons (cons split regexp) nnmail-split-cache))
871            (goto-char (point-max))
872            (if (re-search-backward regexp nil t)
873                (nnmail-split-it (nth 2 split)))))))
874
875 ;; Get a list of spool files to read.
876 (defun nnmail-get-spool-files (&optional group)
877   (if (null nnmail-spool-file)
878       ;; No spool file whatsoever.
879       nil
880     (let* ((procmails 
881             ;; If procmail is used to get incoming mail, the files
882             ;; are stored in this directory.
883             (and (file-exists-p nnmail-procmail-directory)
884                  (or (eq nnmail-spool-file 'procmail)
885                      nnmail-use-procmail)
886                  (directory-files 
887                   nnmail-procmail-directory 
888                   t (concat (if group (concat "^" group) "")
889                             nnmail-procmail-suffix "$") t)))
890            (p procmails)
891            (crash (when (and (file-exists-p nnmail-crash-box)
892                              (> (nth 7 (file-attributes
893                                         (file-truename nnmail-crash-box))) 0))
894                     (list nnmail-crash-box))))
895       ;; Remove any directories that inadvertantly match the procmail
896       ;; suffix, which might happen if the suffix is "". 
897       (while p
898         (when (file-directory-p (car p))
899           (setq procmails (delete (car p) procmails)))
900         (setq p (cdr p)))
901       ;; Return the list of spools.
902       (append 
903        crash
904        (cond ((and group
905                    (or (eq nnmail-spool-file 'procmail)
906                        nnmail-use-procmail))
907               procmails)
908              ((listp nnmail-spool-file)
909               (append nnmail-spool-file procmails))
910              ((stringp nnmail-spool-file)
911               (cons nnmail-spool-file procmails))
912              ((eq nnmail-spool-file 'pop)
913               (cons (format "po:%s" (user-login-name)) procmails))
914              (t
915               procmails))))))
916
917 ;; Activate a backend only if it isn't already activated. 
918 ;; If FORCE, re-read the active file even if the backend is 
919 ;; already activated.
920 (defun nnmail-activate (backend &optional force)
921   (let (file timestamp file-time)
922     (if (or (not (symbol-value (intern (format "%s-group-alist" backend))))
923             force
924             (and (setq file (condition-case ()
925                                 (symbol-value (intern (format "%s-active-file" 
926                                                               backend)))
927                               (error nil)))
928                  (setq file-time (nth 5 (file-attributes file)))
929                  (or (not
930                       (setq timestamp
931                             (condition-case ()
932                                 (symbol-value (intern
933                                                (format "%s-active-timestamp" 
934                                                        backend)))
935                               (error 'none))))
936                      (not (consp timestamp))
937                      (equal timestamp '(0 0))
938                      (> (nth 0 file-time) (nth 0 timestamp))
939                      (and (= (nth 0 file-time) (nth 0 timestamp))
940                           (> (nth 1 file-time) (nth 1 timestamp))))))
941         (save-excursion
942           (or (eq timestamp 'none)
943               (set (intern (format "%s-active-timestamp" backend)) 
944                    (current-time)))
945           (funcall (intern (format "%s-request-list" backend)))
946           (set (intern (format "%s-group-alist" backend)) 
947                (nnmail-get-active))))
948     t))
949
950 (defun nnmail-message-id ()
951   (concat "<" (message-unique-id) "@totally-fudged-out-message-id>"))
952
953 ;;;
954 ;;; nnmail duplicate handling
955 ;;;
956
957 (defvar nnmail-cache-buffer nil)
958
959 (defun nnmail-cache-open ()
960   (if (or (not nnmail-treat-duplicates)
961           (and nnmail-cache-buffer
962                (buffer-name nnmail-cache-buffer)))
963       ()                                ; The buffer is open.
964     (save-excursion
965       (set-buffer 
966        (setq nnmail-cache-buffer 
967              (get-buffer-create " *nnmail message-id cache*")))
968       (buffer-disable-undo (current-buffer))
969       (and (file-exists-p nnmail-message-id-cache-file)
970            (insert-file-contents nnmail-message-id-cache-file))
971       (set-buffer-modified-p nil)
972       (current-buffer))))
973
974 (defun nnmail-cache-close ()
975   (when (and nnmail-cache-buffer
976              nnmail-treat-duplicates
977              (buffer-name nnmail-cache-buffer)
978              (buffer-modified-p nnmail-cache-buffer))
979     (save-excursion
980       (set-buffer nnmail-cache-buffer)
981       ;; Weed out the excess number of Message-IDs.
982       (goto-char (point-max))
983       (and (search-backward "\n" nil t nnmail-message-id-cache-length)
984            (progn
985              (beginning-of-line)
986              (delete-region (point-min) (point))))
987       ;; Save the buffer.
988       (or (file-exists-p (file-name-directory nnmail-message-id-cache-file))
989           (make-directory (file-name-directory nnmail-message-id-cache-file)
990                           t))
991       (write-region (point-min) (point-max)
992                     nnmail-message-id-cache-file nil 'silent)
993       (set-buffer-modified-p nil)
994       (setq nnmail-cache-buffer nil)
995       ;;(kill-buffer (current-buffer))
996       )))
997
998 (defun nnmail-cache-insert (id)
999   (when nnmail-treat-duplicates
1000     (save-excursion
1001       (set-buffer nnmail-cache-buffer)
1002       (goto-char (point-max))
1003       (insert id "\n"))))
1004
1005 (defun nnmail-cache-id-exists-p (id)
1006   (when nnmail-treat-duplicates
1007     (save-excursion
1008       (set-buffer nnmail-cache-buffer)
1009       (goto-char (point-max))
1010       (search-backward id nil t))))
1011
1012 (defun nnmail-check-duplication (message-id func)
1013   ;; If this is a duplicate message, then we do not save it.
1014   (let* ((duplication (nnmail-cache-id-exists-p message-id))
1015          (action (when duplication
1016                    (cond
1017                     ((memq nnmail-treat-duplicates '(warn delete))
1018                      nnmail-treat-duplicates)
1019                     ((nnheader-functionp nnmail-treat-duplicates)
1020                      (funcall nnmail-treat-duplicates message-id))
1021                     (t
1022                      nnmail-treat-duplicates)))))
1023     (cond
1024      ((not duplication)
1025       (nnmail-cache-insert message-id)
1026       (funcall func))
1027      ((eq action 'delete)
1028       (delete-region (point-min) (point-max)))
1029      ((eq action 'warn)
1030       ;; We insert a warning.
1031       (let ((case-fold-search t)
1032             (newid (nnmail-message-id)))
1033         (goto-char (point-min))
1034         (when (re-search-forward "^message-id:" nil t)
1035           (beginning-of-line)
1036           (insert "Original-"))
1037         (beginning-of-line)
1038         (insert 
1039          "Message-ID: " newid "\n"
1040          "Gnus-Warning: This is a duplicate of message " message-id "\n")
1041         (nnmail-cache-insert newid)
1042         (funcall func)))
1043      (t
1044       (funcall func)))))
1045
1046 ;;; Get new mail.
1047
1048 (defun nnmail-get-value (&rest args)
1049   (let ((sym (intern (apply 'format args))))
1050     (when (boundp sym)
1051       (symbol-value sym))))
1052
1053 (defun nnmail-get-new-mail (method exit-func temp
1054                                    &optional group spool-func)
1055   "Read new incoming mail."
1056   (let* ((spools (nnmail-get-spool-files group))
1057          (group-in group)
1058          incoming incomings spool)
1059     (when (and (nnmail-get-value "%s-get-new-mail" method)
1060                nnmail-spool-file)
1061       ;; We first activate all the groups.
1062       (nnmail-activate method)
1063       ;; Allow the user to hook.
1064       (run-hooks 'nnmail-pre-get-new-mail-hook)
1065       ;; Open the message-id cache.
1066       (nnmail-cache-open)
1067       ;; The we go through all the existing spool files and split the
1068       ;; mail from each.
1069       (while spools
1070         (setq spool (pop spools))
1071         ;; We read each spool file if either the spool is a POP-mail
1072         ;; spool, or the file exists.  We can't check for the
1073         ;; existance of POPped mail.
1074         (when (or (string-match "^po:" spool)
1075                   (and (file-exists-p spool)
1076                        (> (nth 7 (file-attributes (file-truename spool))) 0)))
1077           (nnheader-message 3 "%s: Reading incoming mail..." method)
1078           (when (and (nnmail-move-inbox spool)
1079                      (file-exists-p nnmail-crash-box))
1080             ;; There is new mail.  We first find out if all this mail
1081             ;; is supposed to go to some specific group.
1082             (setq group (nnmail-get-split-group spool group-in))
1083             ;; We split the mail
1084             (nnmail-split-incoming 
1085              nnmail-crash-box (intern (format "%s-save-mail" method)) 
1086              spool-func group)
1087             ;; Check whether the inbox is to be moved to the special tmp dir. 
1088             (setq incoming
1089                   (nnmail-make-complex-temp-name 
1090                    (expand-file-name 
1091                     (if nnmail-tmp-directory
1092                         (concat 
1093                          (file-name-as-directory nnmail-tmp-directory)
1094                          (file-name-nondirectory (concat temp "Incoming")))
1095                       (concat temp "Incoming")))))
1096             (rename-file nnmail-crash-box incoming t)
1097             (push incoming incomings))))
1098       ;; If we did indeed read any incoming spools, we save all info. 
1099       (when incomings
1100         (nnmail-save-active 
1101          (nnmail-get-value "%s-group-alist" method)
1102          (nnmail-get-value "%s-active-file" method))
1103         (when exit-func
1104           (funcall exit-func))
1105         (run-hooks 'nnmail-read-incoming-hook)
1106         (nnheader-message 3 "%s: Reading incoming mail...done" method))
1107       ;; Close the message-id cache.
1108       (nnmail-cache-close)
1109       ;; Allow the user to hook.
1110       (run-hooks 'nnmail-post-get-new-mail-hook)
1111       ;; Delete all the temporary files.
1112       (while incomings
1113         (setq incoming (pop incomings))
1114         (and nnmail-delete-incoming
1115              (file-exists-p incoming)
1116              (file-writable-p incoming)
1117              (delete-file incoming))))))
1118
1119 (defun nnmail-expired-article-p (group time force &optional inhibit)
1120   "Say whether an article that is TIME old in GROUP should be expired."
1121   (if force
1122       t
1123     (let ((days (or (and nnmail-expiry-wait-function
1124                          (funcall nnmail-expiry-wait-function group))
1125                     nnmail-expiry-wait)))
1126       (cond ((or (eq days 'never)
1127                  (and (not force)
1128                       inhibit))
1129              ;; This isn't an expirable group.
1130              nil)
1131             ((eq days 'immediate)
1132              ;; We expire all articles on sight.
1133              t)
1134             ((equal time '(0 0))
1135              ;; This is an ange-ftp group, and we don't have any dates.
1136              nil)
1137             ((numberp days)
1138              (setq days (nnmail-days-to-time days))
1139              ;; Compare the time with the current time.
1140              (nnmail-time-less days (nnmail-time-since time)))))))
1141             
1142 (provide 'nnmail)
1143
1144 ;;; nnmail.el ends here