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