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