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