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